| author | |
| committer | |
| log | 8424e1111e8ac1d6bd1a49a8a2618309fa504018 |
| tree | f60502e77c2d710da96c8c2bac3bb1d2e95b1e36 |
| parent | f7716eb9e13c156a06b87abbcf3cea3f5200256b |
| signature | Signed by SSH key SHA256:52mNGHRsVFBDED9IAX5pe+LRWUefqTbxEReunq21QvU |
8 files changed, 3080 insertions(+), 2 deletions(-)
crates/engine/src/auto_matte.rs created+30| ... | ... | @@ -0,0 +1,30 @@ |
| 1 | //! `AutoMatte` (`#49`) and diverging Fusion `MagicMask` (`#7`) GPU matting system. | |
| 2 | //! | |
| 3 | //! Architecture: | |
| 4 | //! - **Unified prompt extraction** ([`prompts`]): parses both Fission `AutoMatte` click points / | |
| 5 | //! modes and real Fusion `MagicMask` `MagicMaskStrokes` (`BezierSpline` keyframes or inline) + | |
| 6 | //! matte controls (`MatteBlur`, `MatteContractExpand`, `Invert`, `OutputMode`, `ShowMask`). | |
| 7 | //! - **Stage 1 & 2** ([`cache`]): checks [`AutoMatteCache`] (in-memory + optional disk PNG sequence | |
| 8 | //! from SAM 2 + MatAnyone 2 / VideoMaMa), exposes a zero-hardcoded-dependency native | |
| 9 | //! [`AutoMatteRunner`] worker launcher, and falls back to a real-time WebGPU-safe multi-seed | |
| 10 | //! Oklab color-affinity segmentation + joint-bilateral edge refinement pass when no cached neural | |
| 11 | //! matte is available yet. | |
| 12 | //! - **Stage 3** ([`gpu`]): real-time GPU port of Clover's `polish_alpha` (floor `0.045`, ceiling | |
| 13 | //! `0.985`, toe gamma `1.35` below `0.15`) and `hair_safe_decontaminate` (3-scale normalized- | |
| 14 | //! convolution Gaussian foreground color extrapolation at `sigma = 28, 12, 4` scaled by | |
| 15 | //! `proxy_scale`). | |
| 16 | ||
| 17 | mod cache; | |
| 18 | mod gpu; | |
| 19 | mod prompts; | |
| 20 | #[cfg(test)] | |
| 21 | mod tests; | |
| 22 | ||
| 23 | pub use cache::{AutoMatteCache, CachedMatteFrame}; | |
| 24 | #[cfg(not(target_arch = "wasm32"))] | |
| 25 | pub use cache::{AutoMatteJobRequest, AutoMatteJobState, AutoMatteRunner, AutoMatteWorkerConfig}; | |
| 26 | pub(crate) use gpu::AutoMattePipelines; | |
| 27 | pub use prompts::{ | |
| 28 | AutoMatteParams, OutputMode, PromptMode, PromptPoint, QualityTier, extract_auto_matte_params, | |
| 29 | extract_magic_mask_params, parse_magic_mask_strokes_table, | |
| 30 | }; |
crates/engine/src/auto_matte/cache.rs created+471| ... | ... | @@ -0,0 +1,471 @@ |
| 1 | //! Pluggable per-frame neural matte cache (`AutoMatteCache`) and optional native | |
| 2 | //! external SAM 2 + MatAnyone 2 / VideoMaMa worker launcher (`AutoMatteRunner`). | |
| 3 | ||
| 4 | use std::collections::{HashMap, VecDeque}; | |
| 5 | use std::collections::hash_map::DefaultHasher; | |
| 6 | use std::hash::{Hash, Hasher}; | |
| 7 | use std::sync::atomic::{AtomicU64, Ordering}; | |
| 8 | use std::sync::{Arc, Mutex}; | |
| 9 | ||
| 10 | #[cfg(not(target_arch = "wasm32"))] | |
| 11 | use super::prompts::{PromptMode, PromptPoint, QualityTier}; | |
| 12 | #[cfg(not(target_arch = "wasm32"))] | |
| 13 | use std::path::{Path, PathBuf}; | |
| 14 | ||
| 15 | const DEFAULT_MAX_CACHED_MATTE_FRAMES: usize = 256; | |
| 16 | ||
| 17 | /// Single-channel linear alpha matte frame (`[0.0, 1.0]`, top-down row-major). | |
| 18 | #[derive(Clone, Debug)] | |
| 19 | pub struct CachedMatteFrame { | |
| 20 | pub size: [u32; 2], | |
| 21 | /// Row-major top-down alpha values in `[0.0, 1.0]` (`len == size[0] * size[1]`). | |
| 22 | pub alpha: Vec<f32>, | |
| 23 | /// Deterministic content hash used to key GPU textures and `NodeCache` entries. | |
| 24 | pub content_hash: u64, | |
| 25 | } | |
| 26 | ||
| 27 | impl CachedMatteFrame { | |
| 28 | /// Constructs a cached matte frame from linear `f32` alpha values in `[0.0, 1.0]`. | |
| 29 | pub fn from_alpha_f32(size: [u32; 2], mut alpha: Vec<f32>) -> Self { | |
| 30 | let expected = (size[0] as usize).saturating_mul(size[1] as usize); | |
| 31 | alpha.resize(expected, 0.0); | |
| 32 | for v in &mut alpha { | |
| 33 | *v = if v.is_finite() { v.clamp(0.0, 1.0) } else { 0.0 }; | |
| 34 | } | |
| 35 | let content_hash = hash_alpha(size, &alpha); | |
| 36 | Self { size, alpha, content_hash } | |
| 37 | } | |
| 38 | ||
| 39 | /// Constructs a cached matte frame from 8-bit grayscale alpha bytes (`0..=255`). | |
| 40 | pub fn from_alpha_u8(size: [u32; 2], bytes: &[u8]) -> Self { | |
| 41 | let expected = (size[0] as usize).saturating_mul(size[1] as usize); | |
| 42 | let mut alpha = Vec::with_capacity(expected); | |
| 43 | for &b in bytes.iter().take(expected) { | |
| 44 | alpha.push(f32::from(b) / 255.0); | |
| 45 | } | |
| 46 | Self::from_alpha_f32(size, alpha) | |
| 47 | } | |
| 48 | ||
| 49 | /// Decodes a PNG (grayscale 8/16-bit or RGBA) matte buffer into a [`CachedMatteFrame`]. | |
| 50 | pub fn from_png_bytes(bytes: &[u8]) -> Result<Self, String> { | |
| 51 | let dyn_img = image::load_from_memory(bytes) | |
| 52 | .map_err(|e| format!("failed to decode AutoMatte PNG: {e}"))?; | |
| 53 | let w = dyn_img.width(); | |
| 54 | let h = dyn_img.height(); | |
| 55 | if w == 0 || h == 0 { | |
| 56 | return Err("AutoMatte PNG has zero dimensions".into()); | |
| 57 | } | |
| 58 | let alpha = match dyn_img { | |
| 59 | image::DynamicImage::ImageLuma8(g) => { | |
| 60 | g.as_raw().iter().map(|&v| f32::from(v) / 255.0).collect() | |
| 61 | } | |
| 62 | image::DynamicImage::ImageLuma16(g) => { | |
| 63 | g.as_raw().iter().map(|&v| f32::from(v) / 65535.0).collect() | |
| 64 | } | |
| 65 | image::DynamicImage::ImageRgba8(rgba) => { | |
| 66 | let raw = rgba.as_raw(); | |
| 67 | let all_opaque = raw.chunks_exact(4).all(|px| px[3] == 255); | |
| 68 | if all_opaque { | |
| 69 | raw.chunks_exact(4).map(|px| f32::from(px[0]) / 255.0).collect() | |
| 70 | } else { | |
| 71 | raw.chunks_exact(4).map(|px| f32::from(px[3]) / 255.0).collect() | |
| 72 | } | |
| 73 | } | |
| 74 | other => { | |
| 75 | let g = other.to_luma16(); | |
| 76 | g.as_raw().iter().map(|&v| f32::from(v) / 65535.0).collect() | |
| 77 | } | |
| 78 | }; | |
| 79 | Ok(Self::from_alpha_f32([w, h], alpha)) | |
| 80 | } | |
| 81 | ||
| 82 | #[cfg(not(target_arch = "wasm32"))] | |
| 83 | pub fn from_png_file(path: &Path) -> Result<Self, String> { | |
| 84 | let bytes = std::fs::read(path) | |
| 85 | .map_err(|e| format!("failed to read AutoMatte PNG {}: {e}", path.display()))?; | |
| 86 | Self::from_png_bytes(&bytes) | |
| 87 | } | |
| 88 | } | |
| 89 | ||
| 90 | fn hash_alpha(size: [u32; 2], alpha: &[f32]) -> u64 { | |
| 91 | let mut h = DefaultHasher::new(); | |
| 92 | "automate-matte-v1".hash(&mut h); | |
| 93 | size.hash(&mut h); | |
| 94 | alpha.len().hash(&mut h); | |
| 95 | // Stride-sample large frames + include endpoints so hashing stays sub-millisecond at 4K | |
| 96 | let stride = (alpha.len() / 2048).max(1); | |
| 97 | for (i, &v) in alpha.iter().enumerate().step_by(stride) { | |
| 98 | i.hash(&mut h); | |
| 99 | v.to_bits().hash(&mut h); | |
| 100 | } | |
| 101 | if let Some(&last) = alpha.last() { | |
| 102 | last.to_bits().hash(&mut h); | |
| 103 | } | |
| 104 | h.finish() | |
| 105 | } | |
| 106 | ||
| 107 | #[derive(Default)] | |
| 108 | struct CacheInner { | |
| 109 | frames: HashMap<(String, i64), Arc<CachedMatteFrame>>, | |
| 110 | order: VecDeque<(String, i64)>, | |
| 111 | max_entries: usize, | |
| 112 | } | |
| 113 | ||
| 114 | impl CacheInner { | |
| 115 | fn new(max_entries: usize) -> Self { | |
| 116 | Self { | |
| 117 | frames: HashMap::new(), | |
| 118 | order: VecDeque::new(), | |
| 119 | max_entries: max_entries.max(1), | |
| 120 | } | |
| 121 | } | |
| 122 | ||
| 123 | fn insert(&mut self, key: (String, i64), frame: Arc<CachedMatteFrame>) { | |
| 124 | if self.frames.contains_key(&key) { | |
| 125 | self.order.retain(|k| k != &key); | |
| 126 | } | |
| 127 | self.frames.insert(key.clone(), frame); | |
| 128 | self.order.push_back(key); | |
| 129 | while self.frames.len() > self.max_entries { | |
| 130 | if let Some(oldest) = self.order.pop_front() { | |
| 131 | self.frames.remove(&oldest); | |
| 132 | } else { | |
| 133 | break; | |
| 134 | } | |
| 135 | } | |
| 136 | } | |
| 137 | } | |
| 138 | ||
| 139 | /// Thread-safe per-frame cached neural alpha store shared between `Engine` and optional | |
| 140 | /// background neural workers (SAM 2 + MatAnyone 2 / VideoMaMa). | |
| 141 | #[derive(Clone)] | |
| 142 | pub struct AutoMatteCache { | |
| 143 | inner: Arc<Mutex<CacheInner>>, | |
| 144 | generation: Arc<AtomicU64>, | |
| 145 | } | |
| 146 | ||
| 147 | impl Default for AutoMatteCache { | |
| 148 | fn default() -> Self { | |
| 149 | Self::new() | |
| 150 | } | |
| 151 | } | |
| 152 | ||
| 153 | impl AutoMatteCache { | |
| 154 | pub fn new() -> Self { | |
| 155 | Self::with_capacity(DEFAULT_MAX_CACHED_MATTE_FRAMES) | |
| 156 | } | |
| 157 | ||
| 158 | pub fn with_capacity(max_entries: usize) -> Self { | |
| 159 | Self { | |
| 160 | inner: Arc::new(Mutex::new(CacheInner::new(max_entries))), | |
| 161 | generation: Arc::new(AtomicU64::new(0)), | |
| 162 | } | |
| 163 | } | |
| 164 | ||
| 165 | /// Monotonic counter incremented whenever frames are inserted or evicted explicitly. | |
| 166 | pub fn generation(&self) -> u64 { | |
| 167 | self.generation.load(Ordering::Relaxed) | |
| 168 | } | |
| 169 | ||
| 170 | pub fn insert_frame(&self, node_name: &str, frame: i64, matte: CachedMatteFrame) { | |
| 171 | if let Ok(mut guard) = self.inner.lock() { | |
| 172 | guard.insert((node_name.to_owned(), frame), Arc::new(matte)); | |
| 173 | self.generation.fetch_add(1, Ordering::Relaxed); | |
| 174 | } | |
| 175 | } | |
| 176 | ||
| 177 | pub fn insert_alpha_f32(&self, node_name: &str, frame: i64, size: [u32; 2], alpha: Vec<f32>) { | |
| 178 | self.insert_frame(node_name, frame, CachedMatteFrame::from_alpha_f32(size, alpha)); | |
| 179 | } | |
| 180 | ||
| 181 | pub fn insert_alpha_u8(&self, node_name: &str, frame: i64, size: [u32; 2], alpha: &[u8]) { | |
| 182 | self.insert_frame(node_name, frame, CachedMatteFrame::from_alpha_u8(size, alpha)); | |
| 183 | } | |
| 184 | ||
| 185 | pub fn get_frame(&self, node_name: &str, frame: i64) -> Option<Arc<CachedMatteFrame>> { | |
| 186 | let guard = self.inner.lock().ok()?; | |
| 187 | guard | |
| 188 | .frames | |
| 189 | .get(&(node_name.to_owned(), frame)) | |
| 190 | .or_else(|| guard.frames.get(&("*".to_owned(), frame))) | |
| 191 | .cloned() | |
| 192 | } | |
| 193 | ||
| 194 | /// Looks up `(node_name, frame)` in memory first, then optionally loads a per-frame PNG | |
| 195 | /// sequence file from `cache_dir` on native targets. | |
| 196 | pub fn get_or_load_frame( | |
| 197 | &self, | |
| 198 | node_name: &str, | |
| 199 | frame: i64, | |
| 200 | cache_dir: Option<&str>, | |
| 201 | ) -> Option<Arc<CachedMatteFrame>> { | |
| 202 | if let Some(hit) = self.get_frame(node_name, frame) { | |
| 203 | return Some(hit); | |
| 204 | } | |
| 205 | #[cfg(not(target_arch = "wasm32"))] | |
| 206 | if let Some(dir) = cache_dir { | |
| 207 | if let Some(path) = resolve_cached_png_path(Path::new(dir), node_name, frame) { | |
| 208 | if let Ok(decoded) = CachedMatteFrame::from_png_file(&path) { | |
| 209 | let arc = Arc::new(decoded); | |
| 210 | if let Ok(mut guard) = self.inner.lock() { | |
| 211 | guard.insert((node_name.to_owned(), frame), arc.clone()); | |
| 212 | } | |
| 213 | return Some(arc); | |
| 214 | } | |
| 215 | } | |
| 216 | } | |
| 217 | #[cfg(target_arch = "wasm32")] | |
| 218 | let _ = cache_dir; | |
| 219 | None | |
| 220 | } | |
| 221 | ||
| 222 | pub fn remove_node(&self, node_name: &str) { | |
| 223 | if let Ok(mut guard) = self.inner.lock() { | |
| 224 | guard.frames.retain(|(n, _), _| n != node_name); | |
| 225 | guard.order.retain(|(n, _)| n != node_name); | |
| 226 | self.generation.fetch_add(1, Ordering::Relaxed); | |
| 227 | } | |
| 228 | } | |
| 229 | ||
| 230 | pub fn clear(&self) { | |
| 231 | if let Ok(mut guard) = self.inner.lock() { | |
| 232 | guard.frames.clear(); | |
| 233 | guard.order.clear(); | |
| 234 | self.generation.fetch_add(1, Ordering::Relaxed); | |
| 235 | } | |
| 236 | } | |
| 237 | ||
| 238 | pub fn len(&self) -> usize { | |
| 239 | self.inner.lock().map_or(0, |g| g.frames.len()) | |
| 240 | } | |
| 241 | ||
| 242 | pub fn is_empty(&self) -> bool { | |
| 243 | self.len() == 0 | |
| 244 | } | |
| 245 | } | |
| 246 | ||
| 247 | #[cfg(not(target_arch = "wasm32"))] | |
| 248 | pub(crate) fn resolve_cached_png_path(dir: &Path, node_name: &str, frame: i64) -> Option<PathBuf> { | |
| 249 | if !dir.exists() { | |
| 250 | return None; | |
| 251 | } | |
| 252 | let f = frame.max(0); | |
| 253 | let candidates = [ | |
| 254 | dir.join(format!("{f:04}.png")), | |
| 255 | dir.join(format!("{f:05}.png")), | |
| 256 | dir.join(format!("{f:06}.png")), | |
| 257 | dir.join(format!("{f}.png")), | |
| 258 | dir.join(format!("frame_{f:04}.png")), | |
| 259 | dir.join(format!("alpha_{f:04}.png")), | |
| 260 | dir.join(format!("{node_name}_{f:04}.png")), | |
| 261 | dir.join(node_name).join(format!("{f:04}.png")), | |
| 262 | ]; | |
| 263 | candidates.into_iter().find(|p| p.is_file()) | |
| 264 | } | |
| 265 | ||
| 266 | // ----------------------------------------------------------------------------- | |
| 267 | // Native external neural matte runner (SAM 2 + MatAnyone 2 / VideoMaMa) | |
| 268 | // ----------------------------------------------------------------------------- | |
| 269 | ||
| 270 | /// Configuration for invoking an external Python neural matting worker on native platforms. | |
| 271 | #[cfg(not(target_arch = "wasm32"))] | |
| 272 | #[derive(Clone, Debug)] | |
| 273 | pub struct AutoMatteWorkerConfig { | |
| 274 | /// Python executable (e.g. `~/dev/magic-matte/.venv/bin/python` or `python3`). | |
| 275 | pub python_bin: PathBuf, | |
| 276 | /// Worker script path accepting `--input`, `--output-dir`, `--quality`, `--mode`, | |
| 277 | /// `--start-frame`, `--end-frame`, and `--prompts`. | |
| 278 | pub worker_script: PathBuf, | |
| 279 | /// Directory where per-frame alpha PNGs (`0000.png`, ...) are written. | |
| 280 | pub output_dir: PathBuf, | |
| 281 | } | |
| 282 | ||
| 283 | /// Job request submitted to [`AutoMatteRunner`]. | |
| 284 | #[cfg(not(target_arch = "wasm32"))] | |
| 285 | #[derive(Clone, Debug)] | |
| 286 | pub struct AutoMatteJobRequest { | |
| 287 | pub node_name: String, | |
| 288 | pub input_path: PathBuf, | |
| 289 | pub frame_range: [i64; 2], | |
| 290 | pub quality_tier: QualityTier, | |
| 291 | pub prompt_mode: PromptMode, | |
| 292 | pub prompts: Vec<PromptPoint>, | |
| 293 | } | |
| 294 | ||
| 295 | /// Lifecycle state of an asynchronous neural matting job. | |
| 296 | #[cfg(not(target_arch = "wasm32"))] | |
| 297 | #[derive(Clone, Debug, PartialEq, Eq)] | |
| 298 | pub enum AutoMatteJobState { | |
| 299 | Running, | |
| 300 | Completed { frames_loaded: usize }, | |
| 301 | Failed(String), | |
| 302 | } | |
| 303 | ||
| 304 | /// Optional native helper to launch an external SAM 2 + MatAnyone 2 / VideoMaMa Python worker | |
| 305 | /// asynchronously or synchronously and populate an [`AutoMatteCache`]. | |
| 306 | #[cfg(not(target_arch = "wasm32"))] | |
| 307 | #[derive(Clone)] | |
| 308 | pub struct AutoMatteRunner { | |
| 309 | config: AutoMatteWorkerConfig, | |
| 310 | cache: AutoMatteCache, | |
| 311 | states: Arc<Mutex<HashMap<String, AutoMatteJobState>>>, | |
| 312 | } | |
| 313 | ||
| 314 | #[cfg(not(target_arch = "wasm32"))] | |
| 315 | impl AutoMatteRunner { | |
| 316 | pub fn new(config: AutoMatteWorkerConfig, cache: AutoMatteCache) -> Self { | |
| 317 | Self { | |
| 318 | config, | |
| 319 | cache, | |
| 320 | states: Arc::new(Mutex::new(HashMap::new())), | |
| 321 | } | |
| 322 | } | |
| 323 | ||
| 324 | /// Probes environment variables (`FISSION_AUTOMATTE_PYTHON`, `FISSION_AUTOMATTE_SCRIPT`) | |
| 325 | /// without hardcoding any mandatory external dependency. Returns `None` if not configured. | |
| 326 | pub fn from_env(output_dir: PathBuf, cache: AutoMatteCache) -> Option<Self> { | |
| 327 | let python_bin = std::env::var_os("FISSION_AUTOMATTE_PYTHON").map(PathBuf::from)?; | |
| 328 | let worker_script = std::env::var_os("FISSION_AUTOMATTE_SCRIPT").map(PathBuf::from)?; | |
| 329 | if !python_bin.is_file() || !worker_script.is_file() { | |
| 330 | return None; | |
| 331 | } | |
| 332 | Some(Self::new( | |
| 333 | AutoMatteWorkerConfig { python_bin, worker_script, output_dir }, | |
| 334 | cache, | |
| 335 | )) | |
| 336 | } | |
| 337 | ||
| 338 | pub fn config(&self) -> &AutoMatteWorkerConfig { | |
| 339 | &self.config | |
| 340 | } | |
| 341 | ||
| 342 | pub fn cache(&self) -> &AutoMatteCache { | |
| 343 | &self.cache | |
| 344 | } | |
| 345 | ||
| 346 | pub fn job_state(&self, node_name: &str) -> Option<AutoMatteJobState> { | |
| 347 | self.states.lock().ok()?.get(node_name).cloned() | |
| 348 | } | |
| 349 | ||
| 350 | /// Runs the external worker synchronously and ingests produced PNG mattes into `self.cache`. | |
| 351 | pub fn run_blocking(&self, req: &AutoMatteJobRequest) -> Result<usize, String> { | |
| 352 | run_worker_once(&self.config, &self.cache, req) | |
| 353 | } | |
| 354 | ||
| 355 | /// Spawns a background OS thread running the configured external worker and populating | |
| 356 | /// `self.cache` upon completion. | |
| 357 | pub fn spawn_job(&self, req: AutoMatteJobRequest) -> Result<(), String> { | |
| 358 | if !self.config.python_bin.is_file() { | |
| 359 | return Err(format!( | |
| 360 | "AutoMatte Python binary not found: {}", | |
| 361 | self.config.python_bin.display() | |
| 362 | )); | |
| 363 | } | |
| 364 | if !self.config.worker_script.is_file() { | |
| 365 | return Err(format!( | |
| 366 | "AutoMatte worker script not found: {}", | |
| 367 | self.config.worker_script.display() | |
| 368 | )); | |
| 369 | } | |
| 370 | let node_name = req.node_name.clone(); | |
| 371 | if let Ok(mut guard) = self.states.lock() { | |
| 372 | guard.insert(node_name.clone(), AutoMatteJobState::Running); | |
| 373 | } | |
| 374 | let config = self.config.clone(); | |
| 375 | let cache = self.cache.clone(); | |
| 376 | let states = self.states.clone(); | |
| 377 | std::thread::Builder::new() | |
| 378 | .name(format!("automate-worker-{node_name}")) | |
| 379 | .spawn(move || { | |
| 380 | let outcome = match run_worker_once(&config, &cache, &req) { | |
| 381 | Ok(frames_loaded) => AutoMatteJobState::Completed { frames_loaded }, | |
| 382 | Err(msg) => AutoMatteJobState::Failed(msg), | |
| 383 | }; | |
| 384 | if let Ok(mut guard) = states.lock() { | |
| 385 | guard.insert(node_name, outcome); | |
| 386 | } | |
| 387 | }) | |
| 388 | .map_err(|e| format!("failed to spawn AutoMatte worker thread: {e}"))?; | |
| 389 | Ok(()) | |
| 390 | } | |
| 391 | } | |
| 392 | ||
| 393 | #[cfg(not(target_arch = "wasm32"))] | |
| 394 | fn serialize_prompts_json(prompts: &[PromptPoint]) -> String { | |
| 395 | let mut s = String::from("["); | |
| 396 | for (i, pt) in prompts.iter().enumerate() { | |
| 397 | if i > 0 { | |
| 398 | s.push(','); | |
| 399 | } | |
| 400 | let label = if pt.positive { 1 } else { 0 }; | |
| 401 | s.push_str(&format!( | |
| 402 | "{{\"x\":{:.6},\"y\":{:.6},\"label\":{label}}}", | |
| 403 | pt.x, pt.y | |
| 404 | )); | |
| 405 | } | |
| 406 | s.push(']'); | |
| 407 | s | |
| 408 | } | |
| 409 | ||
| 410 | #[cfg(not(target_arch = "wasm32"))] | |
| 411 | fn run_worker_once( | |
| 412 | config: &AutoMatteWorkerConfig, | |
| 413 | cache: &AutoMatteCache, | |
| 414 | req: &AutoMatteJobRequest, | |
| 415 | ) -> Result<usize, String> { | |
| 416 | std::fs::create_dir_all(&config.output_dir) | |
| 417 | .map_err(|e| format!("failed to create AutoMatte output dir: {e}"))?; | |
| 418 | ||
| 419 | let quality_str = match req.quality_tier { | |
| 420 | QualityTier::FastInteractive => "fast", | |
| 421 | QualityTier::MatAnyone2 => "matanyone2", | |
| 422 | QualityTier::HeroHair => "videomama", | |
| 423 | }; | |
| 424 | let mode_str = match req.prompt_mode { | |
| 425 | PromptMode::ClickPoints => "points", | |
| 426 | PromptMode::AutoPerson => "person", | |
| 427 | PromptMode::Object => "object", | |
| 428 | }; | |
| 429 | let prompts_json = serialize_prompts_json(&req.prompts); | |
| 430 | ||
| 431 | let output = std::process::Command::new(&config.python_bin) | |
| 432 | .arg(&config.worker_script) | |
| 433 | .arg("--input") | |
| 434 | .arg(&req.input_path) | |
| 435 | .arg("--output-dir") | |
| 436 | .arg(&config.output_dir) | |
| 437 | .arg("--quality") | |
| 438 | .arg(quality_str) | |
| 439 | .arg("--mode") | |
| 440 | .arg(mode_str) | |
| 441 | .arg("--start-frame") | |
| 442 | .arg(req.frame_range[0].to_string()) | |
| 443 | .arg("--end-frame") | |
| 444 | .arg(req.frame_range[1].to_string()) | |
| 445 | .arg("--prompts") | |
| 446 | .arg(&prompts_json) | |
| 447 | .output() | |
| 448 | .map_err(|e| format!("failed to execute AutoMatte worker: {e}"))?; | |
| 449 | ||
| 450 | if !output.status.success() { | |
| 451 | let stderr = String::from_utf8_lossy(&output.stderr); | |
| 452 | return Err(format!( | |
| 453 | "AutoMatte worker exited with {}: {}", | |
| 454 | output.status, | |
| 455 | stderr.trim() | |
| 456 | )); | |
| 457 | } | |
| 458 | ||
| 459 | let mut loaded = 0usize; | |
| 460 | let start = req.frame_range[0]; | |
| 461 | let end = req.frame_range[1].max(start); | |
| 462 | for frame in start..=end { | |
| 463 | if let Some(path) = resolve_cached_png_path(&config.output_dir, &req.node_name, frame) { | |
| 464 | if let Ok(decoded) = CachedMatteFrame::from_png_file(&path) { | |
| 465 | cache.insert_frame(&req.node_name, frame, decoded); | |
| 466 | loaded += 1; | |
| 467 | } | |
| 468 | } | |
| 469 | } | |
| 470 | Ok(loaded) | |
| 471 | } |
crates/engine/src/auto_matte/gpu.rs created+687| ... | ... | @@ -0,0 +1,687 @@ |
| 1 | //! WebGPU-safe compute pipeline registry and multi-pass dispatcher for `AutoMatte` & `MagicMask`. | |
| 2 | //! | |
| 3 | //! All input textures use `TextureSampleType::Float { filterable: false }` (read via `textureLoad`), | |
| 4 | //! output storage textures are `WriteOnly`, and uniform buffers use a growable 512-slot chunk ring | |
| 5 | //! reset via `Engine::reset_uniform_cursors()` and trimmed via `Engine::trim_uniform_chunks()`. | |
| 6 | ||
| 7 | use super::cache::CachedMatteFrame; | |
| 8 | use super::prompts::{AutoMatteParams, MAX_GPU_SEEDS, OutputMode, QualityTier}; | |
| 9 | use crate::cache::{CachedTexture, NodeCache}; | |
| 10 | use bytemuck::{Pod, Zeroable}; | |
| 11 | use model::BitDepth; | |
| 12 | use std::collections::{HashMap, VecDeque}; | |
| 13 | use std::num::NonZeroU64; | |
| 14 | ||
| 15 | const AUTO_MATTE_WGSL: &str = include_str!("../shaders/auto_matte.wgsl"); | |
| 16 | const AM_UNIFORM_SLOTS_PER_CHUNK: u32 = 512; | |
| 17 | const MAX_UPLOADED_MATTE_CACHE: usize = 8; | |
| 18 | ||
| 19 | /// Exact 640-byte uniform block matching `AutoMatteUniform` in `auto_matte.wgsl`. | |
| 20 | #[repr(C)] | |
| 21 | #[derive(Clone, Copy, Pod, Zeroable)] | |
| 22 | struct AutoMatteUniform { | |
| 23 | p: [[f32; 4]; 8], | |
| 24 | seeds: [[f32; 4]; MAX_GPU_SEEDS], | |
| 25 | } | |
| 26 | ||
| 27 | impl Default for AutoMatteUniform { | |
| 28 | fn default() -> Self { | |
| 29 | Self { | |
| 30 | p: [[0.0; 4]; 8], | |
| 31 | seeds: [[0.0; 4]; MAX_GPU_SEEDS], | |
| 32 | } | |
| 33 | } | |
| 34 | } | |
| 35 | ||
| 36 | #[derive(Clone, Copy)] | |
| 37 | enum AutoMatteOp { | |
| 38 | SeedSegment, | |
| 39 | BilateralRefine, | |
| 40 | PolishAlpha, | |
| 41 | MorphoH, | |
| 42 | MorphoV, | |
| 43 | GaussBlurH, | |
| 44 | GaussBlurV, | |
| 45 | DecontamInit, | |
| 46 | DecontamMergeScale, | |
| 47 | CompositeOutput, | |
| 48 | } | |
| 49 | ||
| 50 | fn build_auto_matte_wgsl(format: wgpu::TextureFormat, hdr_float: bool) -> String { | |
| 51 | let storage_fmt = match format { | |
| 52 | wgpu::TextureFormat::Rgba16Float => "rgba16float", | |
| 53 | wgpu::TextureFormat::Rgba32Float => "rgba32float", | |
| 54 | _ => "rgba8unorm", | |
| 55 | }; | |
| 56 | let mut src = AUTO_MATTE_WGSL.to_owned(); | |
| 57 | if storage_fmt != "rgba8unorm" { | |
| 58 | src = src.replace( | |
| 59 | "texture_storage_2d<rgba8unorm, write>", | |
| 60 | &format!("texture_storage_2d<{storage_fmt}, write>"), | |
| 61 | ); | |
| 62 | } | |
| 63 | if hdr_float { | |
| 64 | src = src.replace("const HDR_FLOAT: bool = false;", "const HDR_FLOAT: bool = true;"); | |
| 65 | } | |
| 66 | src | |
| 67 | } | |
| 68 | ||
| 69 | fn unfilterable_tex_entry(binding: u32) -> wgpu::BindGroupLayoutEntry { | |
| 70 | wgpu::BindGroupLayoutEntry { | |
| 71 | binding, | |
| 72 | visibility: wgpu::ShaderStages::COMPUTE, | |
| 73 | ty: wgpu::BindingType::Texture { | |
| 74 | sample_type: wgpu::TextureSampleType::Float { filterable: false }, | |
| 75 | view_dimension: wgpu::TextureViewDimension::D2, | |
| 76 | multisampled: false, | |
| 77 | }, | |
| 78 | count: None, | |
| 79 | } | |
| 80 | } | |
| 81 | ||
| 82 | struct AutoMatteFormatPipelines { | |
| 83 | bgl: wgpu::BindGroupLayout, | |
| 84 | seed_segment: wgpu::ComputePipeline, | |
| 85 | bilateral_refine: wgpu::ComputePipeline, | |
| 86 | polish_alpha: wgpu::ComputePipeline, | |
| 87 | morpho_h: wgpu::ComputePipeline, | |
| 88 | morpho_v: wgpu::ComputePipeline, | |
| 89 | gauss_blur_h: wgpu::ComputePipeline, | |
| 90 | gauss_blur_v: wgpu::ComputePipeline, | |
| 91 | decontam_init: wgpu::ComputePipeline, | |
| 92 | decontam_merge_scale: wgpu::ComputePipeline, | |
| 93 | composite_output: wgpu::ComputePipeline, | |
| 94 | } | |
| 95 | ||
| 96 | impl AutoMatteFormatPipelines { | |
| 97 | fn pipeline(&self, op: AutoMatteOp) -> &wgpu::ComputePipeline { | |
| 98 | match op { | |
| 99 | AutoMatteOp::SeedSegment => &self.seed_segment, | |
| 100 | AutoMatteOp::BilateralRefine => &self.bilateral_refine, | |
| 101 | AutoMatteOp::PolishAlpha => &self.polish_alpha, | |
| 102 | AutoMatteOp::MorphoH => &self.morpho_h, | |
| 103 | AutoMatteOp::MorphoV => &self.morpho_v, | |
| 104 | AutoMatteOp::GaussBlurH => &self.gauss_blur_h, | |
| 105 | AutoMatteOp::GaussBlurV => &self.gauss_blur_v, | |
| 106 | AutoMatteOp::DecontamInit => &self.decontam_init, | |
| 107 | AutoMatteOp::DecontamMergeScale => &self.decontam_merge_scale, | |
| 108 | AutoMatteOp::CompositeOutput => &self.composite_output, | |
| 109 | } | |
| 110 | } | |
| 111 | } | |
| 112 | ||
| 113 | struct UploadedMatteTex { | |
| 114 | _texture: wgpu::Texture, | |
| 115 | view: wgpu::TextureView, | |
| 116 | } | |
| 117 | ||
| 118 | /// GPU pipeline registry and growable uniform chunk ring for `AutoMatte` and `MagicMask`. | |
| 119 | pub(crate) struct AutoMattePipelines { | |
| 120 | uniform_stride: u32, | |
| 121 | uniform_chunks: Vec<wgpu::Buffer>, | |
| 122 | uniform_cursor: u32, | |
| 123 | by_format: HashMap<(wgpu::TextureFormat, bool), AutoMatteFormatPipelines>, | |
| 124 | uploaded_mattes: HashMap<u64, UploadedMatteTex>, | |
| 125 | uploaded_order: VecDeque<u64>, | |
| 126 | } | |
| 127 | ||
| 128 | impl AutoMattePipelines { | |
| 129 | pub(crate) fn new(device: &wgpu::Device) -> Self { | |
| 130 | let uniform_size = std::mem::size_of::<AutoMatteUniform>() as u32; | |
| 131 | let min_align = device.limits().min_uniform_buffer_offset_alignment.max(1); | |
| 132 | let uniform_stride = uniform_size.div_ceil(min_align) * min_align; | |
| 133 | Self { | |
| 134 | uniform_stride, | |
| 135 | uniform_chunks: Vec::new(), | |
| 136 | uniform_cursor: 0, | |
| 137 | by_format: HashMap::new(), | |
| 138 | uploaded_mattes: HashMap::new(), | |
| 139 | uploaded_order: VecDeque::new(), | |
| 140 | } | |
| 141 | } | |
| 142 | ||
| 143 | pub(crate) fn reset_uniform_cursor(&mut self) { | |
| 144 | self.uniform_cursor = 0; | |
| 145 | } | |
| 146 | ||
| 147 | pub(crate) fn trim_uniform_chunks(&mut self, max_chunks: usize) { | |
| 148 | self.uniform_cursor = 0; | |
| 149 | if self.uniform_chunks.len() > max_chunks { | |
| 150 | self.uniform_chunks.truncate(max_chunks); | |
| 151 | } | |
| 152 | self.uploaded_mattes.clear(); | |
| 153 | self.uploaded_order.clear(); | |
| 154 | } | |
| 155 | ||
| 156 | fn alloc_uniform_slot( | |
| 157 | &mut self, | |
| 158 | device: &wgpu::Device, | |
| 159 | queue: &wgpu::Queue, | |
| 160 | params: &AutoMatteUniform, | |
| 161 | ) -> (usize, u32) { | |
| 162 | let slot_global = self.uniform_cursor; | |
| 163 | let chunk_idx = (slot_global / AM_UNIFORM_SLOTS_PER_CHUNK) as usize; | |
| 164 | let slot_in_chunk = slot_global % AM_UNIFORM_SLOTS_PER_CHUNK; | |
| 165 | while chunk_idx >= self.uniform_chunks.len() { | |
| 166 | let size = u64::from(AM_UNIFORM_SLOTS_PER_CHUNK) * u64::from(self.uniform_stride); | |
| 167 | let buf = device.create_buffer(&wgpu::BufferDescriptor { | |
| 168 | label: Some("auto-matte-params-ring"), | |
| 169 | size, | |
| 170 | usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST, | |
| 171 | mapped_at_creation: false, | |
| 172 | }); | |
| 173 | self.uniform_chunks.push(buf); | |
| 174 | } | |
| 175 | let offset = slot_in_chunk * self.uniform_stride; | |
| 176 | queue.write_buffer( | |
| 177 | &self.uniform_chunks[chunk_idx], | |
| 178 | u64::from(offset), | |
| 179 | bytemuck::bytes_of(params), | |
| 180 | ); | |
| 181 | self.uniform_cursor = slot_global + 1; | |
| 182 | (chunk_idx, offset) | |
| 183 | } | |
| 184 | ||
| 185 | fn ensure_format(&mut self, device: &wgpu::Device, format: wgpu::TextureFormat, hdr_float: bool) { | |
| 186 | if self.by_format.contains_key(&(format, hdr_float)) { | |
| 187 | return; | |
| 188 | } | |
| 189 | let u_size = std::mem::size_of::<AutoMatteUniform>() as u64; | |
| 190 | let bgl = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { | |
| 191 | label: Some("auto-matte-bgl"), | |
| 192 | entries: &[ | |
| 193 | unfilterable_tex_entry(0), | |
| 194 | unfilterable_tex_entry(1), | |
| 195 | unfilterable_tex_entry(2), | |
| 196 | unfilterable_tex_entry(3), | |
| 197 | wgpu::BindGroupLayoutEntry { | |
| 198 | binding: 4, | |
| 199 | visibility: wgpu::ShaderStages::COMPUTE, | |
| 200 | ty: wgpu::BindingType::StorageTexture { | |
| 201 | access: wgpu::StorageTextureAccess::WriteOnly, | |
| 202 | format, | |
| 203 | view_dimension: wgpu::TextureViewDimension::D2, | |
| 204 | }, | |
| 205 | count: None, | |
| 206 | }, | |
| 207 | wgpu::BindGroupLayoutEntry { | |
| 208 | binding: 5, | |
| 209 | visibility: wgpu::ShaderStages::COMPUTE, | |
| 210 | ty: wgpu::BindingType::Buffer { | |
| 211 | ty: wgpu::BufferBindingType::Uniform, | |
| 212 | has_dynamic_offset: true, | |
| 213 | min_binding_size: NonZeroU64::new(u_size), | |
| 214 | }, | |
| 215 | count: None, | |
| 216 | }, | |
| 217 | ], | |
| 218 | }); | |
| 219 | let pl = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { | |
| 220 | label: Some("auto-matte-pl"), | |
| 221 | bind_group_layouts: &[Some(&bgl)], | |
| 222 | immediate_size: 0, | |
| 223 | }); | |
| 224 | let module = device.create_shader_module(wgpu::ShaderModuleDescriptor { | |
| 225 | label: Some("auto-matte-wgsl"), | |
| 226 | source: wgpu::ShaderSource::Wgsl(build_auto_matte_wgsl(format, hdr_float).into()), | |
| 227 | }); | |
| 228 | let mk = |entry: &str| { | |
| 229 | device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor { | |
| 230 | label: Some(entry), | |
| 231 | layout: Some(&pl), | |
| 232 | module: &module, | |
| 233 | entry_point: Some(entry), | |
| 234 | compilation_options: Default::default(), | |
| 235 | cache: None, | |
| 236 | }) | |
| 237 | }; | |
| 238 | self.by_format.insert( | |
| 239 | (format, hdr_float), | |
| 240 | AutoMatteFormatPipelines { | |
| 241 | bgl, | |
| 242 | seed_segment: mk("seed_segment_op"), | |
| 243 | bilateral_refine: mk("bilateral_refine_op"), | |
| 244 | polish_alpha: mk("polish_alpha_op"), | |
| 245 | morpho_h: mk("morpho_h_op"), | |
| 246 | morpho_v: mk("morpho_v_op"), | |
| 247 | gauss_blur_h: mk("gauss_blur_h_op"), | |
| 248 | gauss_blur_v: mk("gauss_blur_v_op"), | |
| 249 | decontam_init: mk("decontam_init_op"), | |
| 250 | decontam_merge_scale: mk("decontam_merge_scale_op"), | |
| 251 | composite_output: mk("composite_output_op"), | |
| 252 | }, | |
| 253 | ); | |
| 254 | } | |
| 255 | ||
| 256 | #[allow(clippy::too_many_arguments)] | |
| 257 | fn dispatch( | |
| 258 | &mut self, | |
| 259 | device: &wgpu::Device, | |
| 260 | queue: &wgpu::Queue, | |
| 261 | enc: &mut wgpu::CommandEncoder, | |
| 262 | op: AutoMatteOp, | |
| 263 | inputs: [&wgpu::TextureView; 4], | |
| 264 | dst: &CachedTexture, | |
| 265 | params: &AutoMatteUniform, | |
| 266 | ) { | |
| 267 | let hdr_float = dst.depth.is_float(); | |
| 268 | self.ensure_format(device, dst.format, hdr_float); | |
| 269 | let (chunk_idx, offset) = self.alloc_uniform_slot(device, queue, params); | |
| 270 | let fp = &self.by_format[&(dst.format, hdr_float)]; | |
| 271 | let u_size = NonZeroU64::new(std::mem::size_of::<AutoMatteUniform>() as u64); | |
| 272 | let bg = device.create_bind_group(&wgpu::BindGroupDescriptor { | |
| 273 | label: Some("auto-matte-bg"), | |
| 274 | layout: &fp.bgl, | |
| 275 | entries: &[ | |
| 276 | wgpu::BindGroupEntry { binding: 0, resource: wgpu::BindingResource::TextureView(inputs[0]) }, | |
| 277 | wgpu::BindGroupEntry { binding: 1, resource: wgpu::BindingResource::TextureView(inputs[1]) }, | |
| 278 | wgpu::BindGroupEntry { binding: 2, resource: wgpu::BindingResource::TextureView(inputs[2]) }, | |
| 279 | wgpu::BindGroupEntry { binding: 3, resource: wgpu::BindingResource::TextureView(inputs[3]) }, | |
| 280 | wgpu::BindGroupEntry { binding: 4, resource: wgpu::BindingResource::TextureView(&dst.view) }, | |
| 281 | wgpu::BindGroupEntry { | |
| 282 | binding: 5, | |
| 283 | resource: wgpu::BindingResource::Buffer(wgpu::BufferBinding { | |
| 284 | buffer: &self.uniform_chunks[chunk_idx], | |
| 285 | offset: 0, | |
| 286 | size: u_size, | |
| 287 | }), | |
| 288 | }, | |
| 289 | ], | |
| 290 | }); | |
| 291 | let mut pass = enc.begin_compute_pass(&wgpu::ComputePassDescriptor { | |
| 292 | label: Some("auto-matte-pass"), | |
| 293 | timestamp_writes: None, | |
| 294 | }); | |
| 295 | pass.set_pipeline(fp.pipeline(op)); | |
| 296 | pass.set_bind_group(0, &bg, &[offset]); | |
| 297 | pass.dispatch_workgroups(dst.size[0].div_ceil(8), dst.size[1].div_ceil(8), 1); | |
| 298 | } | |
| 299 | ||
| 300 | fn upload_cached_matte( | |
| 301 | &mut self, | |
| 302 | device: &wgpu::Device, | |
| 303 | queue: &wgpu::Queue, | |
| 304 | matte: &CachedMatteFrame, | |
| 305 | ) -> wgpu::TextureView { | |
| 306 | if let Some(existing) = self.uploaded_mattes.get(&matte.content_hash) { | |
| 307 | return existing.view.clone(); | |
| 308 | } | |
| 309 | let w = matte.size[0].max(1); | |
| 310 | let h = matte.size[1].max(1); | |
| 311 | let tex = device.create_texture(&wgpu::TextureDescriptor { | |
| 312 | label: Some("auto-matte-cached-r32f"), | |
| 313 | size: wgpu::Extent3d { | |
| 314 | width: w, | |
| 315 | height: h, | |
| 316 | depth_or_array_layers: 1, | |
| 317 | }, | |
| 318 | mip_level_count: 1, | |
| 319 | sample_count: 1, | |
| 320 | dimension: wgpu::TextureDimension::D2, | |
| 321 | format: wgpu::TextureFormat::R32Float, | |
| 322 | usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST, | |
| 323 | view_formats: &[], | |
| 324 | }); | |
| 325 | queue.write_texture( | |
| 326 | tex.as_image_copy(), | |
| 327 | bytemuck::cast_slice(&matte.alpha), | |
| 328 | wgpu::TexelCopyBufferLayout { | |
| 329 | offset: 0, | |
| 330 | bytes_per_row: Some(w * 4), | |
| 331 | rows_per_image: Some(h), | |
| 332 | }, | |
| 333 | wgpu::Extent3d { | |
| 334 | width: w, | |
| 335 | height: h, | |
| 336 | depth_or_array_layers: 1, | |
| 337 | }, | |
| 338 | ); | |
| 339 | let view = tex.create_view(&wgpu::TextureViewDescriptor::default()); | |
| 340 | let view_clone = view.clone(); | |
| 341 | self.uploaded_mattes.insert( | |
| 342 | matte.content_hash, | |
| 343 | UploadedMatteTex { _texture: tex, view }, | |
| 344 | ); | |
| 345 | self.uploaded_order.push_back(matte.content_hash); | |
| 346 | while self.uploaded_mattes.len() > MAX_UPLOADED_MATTE_CACHE { | |
| 347 | if let Some(old) = self.uploaded_order.pop_front() { | |
| 348 | self.uploaded_mattes.remove(&old); | |
| 349 | } else { | |
| 350 | break; | |
| 351 | } | |
| 352 | } | |
| 353 | view_clone | |
| 354 | } | |
| 355 | ||
| 356 | /// Executes the full AutoMatte / MagicMask GPU pipeline: | |
| 357 | /// 1. Stage 1/2: uses `cached_matte` if present, otherwise runs GPU multi-seed segmentation + | |
| 358 | /// joint-bilateral edge-aware refinement. | |
| 359 | /// 2. Stage 3A: Clover's `polish_alpha` (floor, ceiling, toe gamma, invert) + optional | |
| 360 | /// `MatteContractExpand` and `MatteBlur`. | |
| 361 | /// 3. Stage 3B: Clover's 3-scale `hair_safe_decontaminate` (`sigma = 28, 12, 4` scaled by | |
| 362 | /// `proxy_scale`) + final output mode & `EffectMask` / `Blend` composite. | |
| 363 | #[allow(clippy::too_many_arguments)] | |
| 364 | pub(crate) fn execute( | |
| 365 | &mut self, | |
| 366 | device: &wgpu::Device, | |
| 367 | queue: &wgpu::Queue, | |
| 368 | enc: &mut wgpu::CommandEncoder, | |
| 369 | node_cache: &NodeCache, | |
| 370 | dummy_view: &wgpu::TextureView, | |
| 371 | src: &CachedTexture, | |
| 372 | mask_view: &wgpu::TextureView, | |
| 373 | has_mask: bool, | |
| 374 | mask_inv: bool, | |
| 375 | mbm: bool, | |
| 376 | skip: [f32; 4], | |
| 377 | dst: &CachedTexture, | |
| 378 | params: &AutoMatteParams, | |
| 379 | cached_matte: Option<&CachedMatteFrame>, | |
| 380 | proxy_scale: u32, | |
| 381 | ) { | |
| 382 | let alloc_f16 = || { | |
| 383 | node_cache.acquire_texture_dod_fmt( | |
| 384 | device, | |
| 385 | src.size, | |
| 386 | [0, 0], | |
| 387 | src.size, | |
| 388 | BitDepth::Float16, | |
| 389 | wgpu::TextureFormat::Rgba16Float, | |
| 390 | 0, | |
| 391 | ) | |
| 392 | }; | |
| 393 | ||
| 394 | // --------------------------------------------------------------------- | |
| 395 | // Stage 1 & 2: Acquire raw alpha matte (cached neural OR GPU fallback) | |
| 396 | // --------------------------------------------------------------------- | |
| 397 | let raw_matte_view: wgpu::TextureView; | |
| 398 | let _gpu_fallback_keepalive: Option<CachedTexture>; | |
| 399 | if let Some(cm) = cached_matte { | |
| 400 | raw_matte_view = self.upload_cached_matte(device, queue, cm); | |
| 401 | _gpu_fallback_keepalive = None; | |
| 402 | } else { | |
| 403 | let seeds = params.effective_gpu_seeds(); | |
| 404 | let seg_tex = alloc_f16(); | |
| 405 | let mut u_seg = AutoMatteUniform::default(); | |
| 406 | let mut neg_count = 0u32; | |
| 407 | let count = seeds.len().min(MAX_GPU_SEEDS); | |
| 408 | for (i, pt) in seeds.iter().take(count).enumerate() { | |
| 409 | let [u, v] = pt.to_gpu_uv(); | |
| 410 | let label = if pt.positive { 1.0 } else { neg_count += 1; -1.0 }; | |
| 411 | u_seg.seeds[i] = [u, v, label, pt.weight.max(0.01)]; | |
| 412 | } | |
| 413 | let aspect = (src.size[0] as f32) / (src.size[1].max(1) as f32); | |
| 414 | u_seg.p[0] = [ | |
| 415 | count as f32, | |
| 416 | neg_count as f32, | |
| 417 | 0.12, // perceptual Oklab color sigma | |
| 418 | 0.85, // spatial sigma for positive seeds | |
| 419 | ]; | |
| 420 | u_seg.p[1] = [ | |
| 421 | if neg_count == 0 { 1.25 } else { 0.85 }, | |
| 422 | 1.0, // enable automatic border background seeds when no negative clicks exist | |
| 423 | aspect, | |
| 424 | params.quality_tier as u32 as f32, | |
| 425 | ]; | |
| 426 | self.dispatch( | |
| 427 | device, | |
| 428 | queue, | |
| 429 | enc, | |
| 430 | AutoMatteOp::SeedSegment, | |
| 431 | [&src.view, dummy_view, dummy_view, dummy_view], | |
| 432 | &seg_tex, | |
| 433 | &u_seg, | |
| 434 | ); | |
| 435 | ||
| 436 | // Joint-bilateral edge-aware alpha refinement guided by original RGB | |
| 437 | let refined = match params.quality_tier { | |
| 438 | QualityTier::FastInteractive => { | |
| 439 | let out = alloc_f16(); | |
| 440 | let mut ub = AutoMatteUniform::default(); | |
| 441 | ub.p[0] = [3.0, 3.0, 0.08, 1.0]; | |
| 442 | self.dispatch( | |
| 443 | device, | |
| 444 | queue, | |
| 445 | enc, | |
| 446 | AutoMatteOp::BilateralRefine, | |
| 447 | [&src.view, &seg_tex.view, dummy_view, dummy_view], | |
| 448 | &out, | |
| 449 | &ub, | |
| 450 | ); | |
| 451 | out | |
| 452 | } | |
| 453 | QualityTier::MatAnyone2 => { | |
| 454 | let mid = alloc_f16(); | |
| 455 | let out = alloc_f16(); | |
| 456 | let mut u1 = AutoMatteUniform::default(); | |
| 457 | u1.p[0] = [3.0, 4.5, 0.075, 2.0]; | |
| 458 | self.dispatch( | |
| 459 | device, | |
| 460 | queue, | |
| 461 | enc, | |
| 462 | AutoMatteOp::BilateralRefine, | |
| 463 | [&src.view, &seg_tex.view, dummy_view, dummy_view], | |
| 464 | &mid, | |
| 465 | &u1, | |
| 466 | ); | |
| 467 | let mut u2 = AutoMatteUniform::default(); | |
| 468 | u2.p[0] = [3.0, 2.5, 0.06, 1.0]; | |
| 469 | self.dispatch( | |
| 470 | device, | |
| 471 | queue, | |
| 472 | enc, | |
| 473 | AutoMatteOp::BilateralRefine, | |
| 474 | [&src.view, &mid.view, dummy_view, dummy_view], | |
| 475 | &out, | |
| 476 | &u2, | |
| 477 | ); | |
| 478 | out | |
| 479 | } | |
| 480 | QualityTier::HeroHair => { | |
| 481 | let mid = alloc_f16(); | |
| 482 | let out = alloc_f16(); | |
| 483 | let mut u1 = AutoMatteUniform::default(); | |
| 484 | u1.p[0] = [4.0, 5.0, 0.06, 2.0]; | |
| 485 | self.dispatch( | |
| 486 | device, | |
| 487 | queue, | |
| 488 | enc, | |
| 489 | AutoMatteOp::BilateralRefine, | |
| 490 | [&src.view, &seg_tex.view, dummy_view, dummy_view], | |
| 491 | &mid, | |
| 492 | &u1, | |
| 493 | ); | |
| 494 | let mut u2 = AutoMatteUniform::default(); | |
| 495 | u2.p[0] = [3.0, 2.2, 0.045, 1.0]; | |
| 496 | self.dispatch( | |
| 497 | device, | |
| 498 | queue, | |
| 499 | enc, | |
| 500 | AutoMatteOp::BilateralRefine, | |
| 501 | [&src.view, &mid.view, dummy_view, dummy_view], | |
| 502 | &out, | |
| 503 | &u2, | |
| 504 | ); | |
| 505 | out | |
| 506 | } | |
| 507 | }; | |
| 508 | raw_matte_view = (*refined.view).clone(); | |
| 509 | _gpu_fallback_keepalive = Some(refined); | |
| 510 | } | |
| 511 | ||
| 512 | // --------------------------------------------------------------------- | |
| 513 | // Stage 3A: Clover's exact `polish_alpha` + optional morpho & blur | |
| 514 | // --------------------------------------------------------------------- | |
| 515 | let mut matte_tex = alloc_f16(); | |
| 516 | let mut u_pol = AutoMatteUniform::default(); | |
| 517 | u_pol.p[0] = [ | |
| 518 | params.alpha_floor, | |
| 519 | params.alpha_ceiling, | |
| 520 | params.toe_gamma, | |
| 521 | if params.invert { 1.0 } else { 0.0 }, | |
| 522 | ]; | |
| 523 | self.dispatch( | |
| 524 | device, | |
| 525 | queue, | |
| 526 | enc, | |
| 527 | AutoMatteOp::PolishAlpha, | |
| 528 | [&raw_matte_view, dummy_view, dummy_view, dummy_view], | |
| 529 | &matte_tex, | |
| 530 | &u_pol, | |
| 531 | ); | |
| 532 | ||
| 533 | let scale = proxy_scale.max(1) as f32; | |
| 534 | if params.matte_contract_expand.abs() > 1e-4 { | |
| 535 | let radius_px = (params.matte_contract_expand * (src.size[0] as f32 / 128.0).max(1.0)) | |
| 536 | .clamp(-64.0, 64.0); | |
| 537 | let tmp = alloc_f16(); | |
| 538 | let out = alloc_f16(); | |
| 539 | let mut um = AutoMatteUniform::default(); | |
| 540 | um.p[0][0] = radius_px; | |
| 541 | self.dispatch( | |
| 542 | device, | |
| 543 | queue, | |
| 544 | enc, | |
| 545 | AutoMatteOp::MorphoH, | |
| 546 | [&matte_tex.view, dummy_view, dummy_view, dummy_view], | |
| 547 | &tmp, | |
| 548 | &um, | |
| 549 | ); | |
| 550 | self.dispatch( | |
| 551 | device, | |
| 552 | queue, | |
| 553 | enc, | |
| 554 | AutoMatteOp::MorphoV, | |
| 555 | [&tmp.view, dummy_view, dummy_view, dummy_view], | |
| 556 | &out, | |
| 557 | &um, | |
| 558 | ); | |
| 559 | matte_tex = out; | |
| 560 | } | |
| 561 | ||
| 562 | if params.matte_blur > 1e-3 { | |
| 563 | let sigma = (params.matte_blur / scale).clamp(0.1, 64.0); | |
| 564 | let max_r = (sigma * 2.5).ceil().clamp(1.0, 76.0); | |
| 565 | let tmp = alloc_f16(); | |
| 566 | let out = alloc_f16(); | |
| 567 | let mut ub = AutoMatteUniform::default(); | |
| 568 | ub.p[0] = [sigma, max_r, 0.0, 0.0]; | |
| 569 | self.dispatch( | |
| 570 | device, | |
| 571 | queue, | |
| 572 | enc, | |
| 573 | AutoMatteOp::GaussBlurH, | |
| 574 | [&matte_tex.view, dummy_view, dummy_view, dummy_view], | |
| 575 | &tmp, | |
| 576 | &ub, | |
| 577 | ); | |
| 578 | self.dispatch( | |
| 579 | device, | |
| 580 | queue, | |
| 581 | enc, | |
| 582 | AutoMatteOp::GaussBlurV, | |
| 583 | [&tmp.view, dummy_view, dummy_view, dummy_view], | |
| 584 | &out, | |
| 585 | &ub, | |
| 586 | ); | |
| 587 | matte_tex = out; | |
| 588 | } | |
| 589 | ||
| 590 | // --------------------------------------------------------------------- | |
| 591 | // Stage 3B: Clover's 3-scale `hair_safe_decontaminate` (sigma = 28, 12, 4) | |
| 592 | // --------------------------------------------------------------------- | |
| 593 | let need_decontam = params.decontaminate > 1e-4 | |
| 594 | && params.output_mode == OutputMode::PremultipliedCutout; | |
| 595 | let extrap_keepalive: Option<CachedTexture> = if need_decontam { | |
| 596 | let solid_tex = alloc_f16(); | |
| 597 | let u_zero = AutoMatteUniform::default(); | |
| 598 | self.dispatch( | |
| 599 | device, | |
| 600 | queue, | |
| 601 | enc, | |
| 602 | AutoMatteOp::DecontamInit, | |
| 603 | [&src.view, &matte_tex.view, dummy_view, dummy_view], | |
| 604 | &solid_tex, | |
| 605 | &u_zero, | |
| 606 | ); | |
| 607 | ||
| 608 | let blur_tmp = alloc_f16(); | |
| 609 | let blur_out = alloc_f16(); | |
| 610 | let extrap_a = alloc_f16(); | |
| 611 | let extrap_b = alloc_f16(); | |
| 612 | ||
| 613 | for (idx, &base_sigma) in [28.0_f32, 12.0, 4.0].iter().enumerate() { | |
| 614 | let sigma = (base_sigma / scale).max(0.5); | |
| 615 | let max_r = (sigma * 2.5).ceil().clamp(1.0, 76.0); | |
| 616 | let mut ub = AutoMatteUniform::default(); | |
| 617 | ub.p[0] = [sigma, max_r, 0.0, 0.0]; | |
| 618 | self.dispatch( | |
| 619 | device, | |
| 620 | queue, | |
| 621 | enc, | |
| 622 | AutoMatteOp::GaussBlurH, | |
| 623 | [&solid_tex.view, dummy_view, dummy_view, dummy_view], | |
| 624 | &blur_tmp, | |
| 625 | &ub, | |
| 626 | ); | |
| 627 | self.dispatch( | |
| 628 | device, | |
| 629 | queue, | |
| 630 | enc, | |
| 631 | AutoMatteOp::GaussBlurV, | |
| 632 | [&blur_tmp.view, dummy_view, dummy_view, dummy_view], | |
| 633 | &blur_out, | |
| 634 | &ub, | |
| 635 | ); | |
| 636 | let prev_view = match idx { | |
| 637 | 0 => &src.view, | |
| 638 | 1 => &extrap_a.view, | |
| 639 | _ => &extrap_b.view, | |
| 640 | }; | |
| 641 | let next_tex = if idx % 2 == 0 { &extrap_a } else { &extrap_b }; | |
| 642 | self.dispatch( | |
| 643 | device, | |
| 644 | queue, | |
| 645 | enc, | |
| 646 | AutoMatteOp::DecontamMergeScale, | |
| 647 | [prev_view, &blur_out.view, dummy_view, dummy_view], | |
| 648 | next_tex, | |
| 649 | &u_zero, | |
| 650 | ); | |
| 651 | } | |
| 652 | Some(extrap_a) | |
| 653 | } else { | |
| 654 | None | |
| 655 | }; | |
| 656 | ||
| 657 | // --------------------------------------------------------------------- | |
| 658 | // Stage 3C: Final composite (cutout / matte / overlay + EffectMask/Blend) | |
| 659 | // --------------------------------------------------------------------- | |
| 660 | let extrap_view = extrap_keepalive | |
| 661 | .as_ref() | |
| 662 | .map_or(&src.view, |t| &t.view); | |
| 663 | let mut u_comp = AutoMatteUniform::default(); | |
| 664 | u_comp.p[0] = [ | |
| 665 | params.decontaminate, | |
| 666 | params.output_mode as u32 as f32, | |
| 667 | params.blend, | |
| 668 | if has_mask { 1.0 } else { 0.0 }, | |
| 669 | ]; | |
| 670 | u_comp.p[1] = [ | |
| 671 | if mask_inv { 1.0 } else { 0.0 }, | |
| 672 | if mbm { 1.0 } else { 0.0 }, | |
| 673 | 0.0, | |
| 674 | 0.0, | |
| 675 | ]; | |
| 676 | u_comp.p[2] = skip; | |
| 677 | self.dispatch( | |
| 678 | device, | |
| 679 | queue, | |
| 680 | enc, | |
| 681 | AutoMatteOp::CompositeOutput, | |
| 682 | [&src.view, &matte_tex.view, extrap_view, mask_view], | |
| 683 | dst, | |
| 684 | &u_comp, | |
| 685 | ); | |
| 686 | } | |
| 687 | } |
crates/engine/src/auto_matte/prompts.rs created+677| ... | ... | @@ -0,0 +1,677 @@ |
| 1 | //! Unified prompt & parameter extraction for `AutoMatte` and Fusion `MagicMask`. | |
| 2 | //! | |
| 3 | //! Handles: | |
| 4 | //! - Real Fusion `MagicMask` nodes (`Strokes = Input { SourceOp = "MagicMask1Strokes" }` pointing | |
| 5 | //! at a `BezierSpline` whose `KeyFrames` carry `Value = MagicMaskStrokes { PosStrokes, NegStrokes }`, | |
| 6 | //! or inline `MagicMaskStrokes` tables, plus `Invert`, `MatteBlur`, `MatteContractExpand`, | |
| 7 | //! `ShowMask`, `MatteOnly`, `OutputMode`, `CacheDir`, `Blend`). | |
| 8 | //! - Fission `AutoMatte` nodes (`Points`, `PositivePoints`, `NegativePoints`, `PosPoint1..16`, | |
| 9 | //! `NegPoint1..16`, `PromptMode`, `QualityTier`, `AlphaFloor`, `AlphaCeiling`, `ToeGamma`, | |
| 10 | //! `Decontaminate`, `MatteBlur`, `MatteContractExpand`, `Invert`, `OutputMode`, `CacheDir`, | |
| 11 | //! `Blend`). | |
| 12 | ||
| 13 | use model::{Comp, ExprEngine, LuaKey, LuaTable, LuaValue, Node, ParamValue}; | |
| 14 | use std::hash::{Hash, Hasher}; | |
| 15 | ||
| 16 | /// Maximum seeds packed into the GPU uniform buffer per dispatch. | |
| 17 | pub const MAX_GPU_SEEDS: usize = 32; | |
| 18 | ||
| 19 | /// Default Clover `polish_alpha` floor (kills faint VAE haze <= 0.045). | |
| 20 | pub const DEFAULT_ALPHA_FLOOR: f32 = 0.045; | |
| 21 | /// Default Clover `polish_alpha` ceiling (crisp solid white >= 0.985). | |
| 22 | pub const DEFAULT_ALPHA_CEILING: f32 = 0.985; | |
| 23 | /// Default Clover `polish_alpha` toe gamma below 0.15. | |
| 24 | pub const DEFAULT_TOE_GAMMA: f32 = 1.35; | |
| 25 | ||
| 26 | /// Normalized prompt point in Fusion Y-up `[0..1]` space. | |
| 27 | #[derive(Clone, Copy, Debug, PartialEq)] | |
| 28 | pub struct PromptPoint { | |
| 29 | /// Horizontal normalized coordinate in `[0..1]` (left = 0, right = 1). | |
| 30 | pub x: f32, | |
| 31 | /// Vertical normalized coordinate in Fusion Y-up `[0..1]` (bottom = 0, top = 1). | |
| 32 | pub y: f32, | |
| 33 | /// `true` = foreground / positive click or stroke; `false` = background / negative. | |
| 34 | pub positive: bool, | |
| 35 | /// Relative seed weight (default `1.0`). | |
| 36 | pub weight: f32, | |
| 37 | } | |
| 38 | ||
| 39 | impl PromptPoint { | |
| 40 | pub fn positive(x: f32, y: f32) -> Self { | |
| 41 | Self { x, y, positive: true, weight: 1.0 } | |
| 42 | } | |
| 43 | ||
| 44 | pub fn negative(x: f32, y: f32) -> Self { | |
| 45 | Self { x, y, positive: false, weight: 1.0 } | |
| 46 | } | |
| 47 | ||
| 48 | /// Converts Fusion Y-up `[0..1]` into top-down GPU texture UV `[0..1]`. | |
| 49 | pub fn to_gpu_uv(self) -> [f32; 2] { | |
| 50 | [self.x.clamp(0.0, 1.0), (1.0 - self.y).clamp(0.0, 1.0)] | |
| 51 | } | |
| 52 | } | |
| 53 | ||
| 54 | /// Prompt mode for `AutoMatte`. | |
| 55 | #[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)] | |
| 56 | #[repr(u32)] | |
| 57 | pub enum PromptMode { | |
| 58 | /// Explicit positive/negative click points or strokes. | |
| 59 | #[default] | |
| 60 | ClickPoints = 0, | |
| 61 | /// Automatic person / center-salient foreground heuristic. | |
| 62 | AutoPerson = 1, | |
| 63 | /// Automatic central object heuristic. | |
| 64 | Object = 2, | |
| 65 | } | |
| 66 | ||
| 67 | impl PromptMode { | |
| 68 | pub fn from_i32(v: i32) -> Self { | |
| 69 | match v { | |
| 70 | 1 => Self::AutoPerson, | |
| 71 | 2 => Self::Object, | |
| 72 | _ => Self::ClickPoints, | |
| 73 | } | |
| 74 | } | |
| 75 | } | |
| 76 | ||
| 77 | /// Neural / refinement quality tier for `AutoMatte`. | |
| 78 | #[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)] | |
| 79 | #[repr(u32)] | |
| 80 | pub enum QualityTier { | |
| 81 | /// Fast interactive single-pass refinement. | |
| 82 | FastInteractive = 0, | |
| 83 | /// Balanced MatAnyone 2 tier (default). | |
| 84 | #[default] | |
| 85 | MatAnyone2 = 1, | |
| 86 | /// Hero Hair / VideoMaMa tier (extra edge-preserving bilateral pass). | |
| 87 | HeroHair = 2, | |
| 88 | } | |
| 89 | ||
| 90 | impl QualityTier { | |
| 91 | pub fn from_i32(v: i32) -> Self { | |
| 92 | match v { | |
| 93 | 0 => Self::FastInteractive, | |
| 94 | 2 => Self::HeroHair, | |
| 95 | _ => Self::MatAnyone2, | |
| 96 | } | |
| 97 | } | |
| 98 | } | |
| 99 | ||
| 100 | /// Final compositor output mode for `AutoMatte` & `MagicMask`. | |
| 101 | #[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)] | |
| 102 | #[repr(u32)] | |
| 103 | pub enum OutputMode { | |
| 104 | /// Premultiplied cutout `(fg_clean * alpha, alpha)`. | |
| 105 | #[default] | |
| 106 | PremultipliedCutout = 0, | |
| 107 | /// Grayscale matte `(alpha, alpha, alpha, alpha)`. | |
| 108 | MatteOnly = 1, | |
| 109 | /// Ruby-magenta translucent overlay preview on top of source footage. | |
| 110 | OverlayPreview = 2, | |
| 111 | } | |
| 112 | ||
| 113 | impl OutputMode { | |
| 114 | pub fn from_i32(v: i32) -> Self { | |
| 115 | match v { | |
| 116 | 1 => Self::MatteOnly, | |
| 117 | 2 => Self::OverlayPreview, | |
| 118 | _ => Self::PremultipliedCutout, | |
| 119 | } | |
| 120 | } | |
| 121 | } | |
| 122 | ||
| 123 | /// Unified evaluated parameters for both `AutoMatte` and `MagicMask`. | |
| 124 | #[derive(Clone, Debug)] | |
| 125 | pub struct AutoMatteParams { | |
| 126 | pub is_magic_mask: bool, | |
| 127 | pub prompt_mode: PromptMode, | |
| 128 | pub quality_tier: QualityTier, | |
| 129 | pub points: Vec<PromptPoint>, | |
| 130 | pub alpha_floor: f32, | |
| 131 | pub alpha_ceiling: f32, | |
| 132 | pub toe_gamma: f32, | |
| 133 | pub decontaminate: f32, | |
| 134 | pub matte_blur: f32, | |
| 135 | pub matte_contract_expand: f32, | |
| 136 | pub invert: bool, | |
| 137 | pub output_mode: OutputMode, | |
| 138 | pub cache_dir: Option<String>, | |
| 139 | pub blend: f32, | |
| 140 | } | |
| 141 | ||
| 142 | impl AutoMatteParams { | |
| 143 | /// Deterministic parameter hash for `Engine::NodeCache` keying. | |
| 144 | pub fn hash_into(&self, hasher: &mut impl Hasher) { | |
| 145 | self.is_magic_mask.hash(hasher); | |
| 146 | self.prompt_mode.hash(hasher); | |
| 147 | self.quality_tier.hash(hasher); | |
| 148 | self.points.len().hash(hasher); | |
| 149 | for pt in &self.points { | |
| 150 | pt.x.to_bits().hash(hasher); | |
| 151 | pt.y.to_bits().hash(hasher); | |
| 152 | pt.positive.hash(hasher); | |
| 153 | pt.weight.to_bits().hash(hasher); | |
| 154 | } | |
| 155 | self.alpha_floor.to_bits().hash(hasher); | |
| 156 | self.alpha_ceiling.to_bits().hash(hasher); | |
| 157 | self.toe_gamma.to_bits().hash(hasher); | |
| 158 | self.decontaminate.to_bits().hash(hasher); | |
| 159 | self.matte_blur.to_bits().hash(hasher); | |
| 160 | self.matte_contract_expand.to_bits().hash(hasher); | |
| 161 | self.invert.hash(hasher); | |
| 162 | self.output_mode.hash(hasher); | |
| 163 | self.cache_dir.hash(hasher); | |
| 164 | self.blend.to_bits().hash(hasher); | |
| 165 | } | |
| 166 | ||
| 167 | /// Returns effective seeds for the built-in GPU fallback segmentation, synthesizing | |
| 168 | /// center-salient + border background seeds when `PromptMode` is `AutoPerson` or `Object` | |
| 169 | /// and no explicit points were specified. | |
| 170 | pub fn effective_gpu_seeds(&self) -> Vec<PromptPoint> { | |
| 171 | if !self.points.is_empty() { | |
| 172 | return subsample_seeds(&self.points, MAX_GPU_SEEDS); | |
| 173 | } | |
| 174 | match self.prompt_mode { | |
| 175 | PromptMode::ClickPoints => Vec::new(), | |
| 176 | PromptMode::AutoPerson => vec![ | |
| 177 | PromptPoint::positive(0.50, 0.52), | |
| 178 | PromptPoint::positive(0.50, 0.36), | |
| 179 | PromptPoint::positive(0.50, 0.68), | |
| 180 | PromptPoint::negative(0.04, 0.96), | |
| 181 | PromptPoint::negative(0.96, 0.96), | |
| 182 | PromptPoint::negative(0.04, 0.50), | |
| 183 | PromptPoint::negative(0.96, 0.50), | |
| 184 | PromptPoint::negative(0.04, 0.04), | |
| 185 | PromptPoint::negative(0.96, 0.04), | |
| 186 | ], | |
| 187 | PromptMode::Object => vec![ | |
| 188 | PromptPoint::positive(0.50, 0.50), | |
| 189 | PromptPoint::negative(0.04, 0.04), | |
| 190 | PromptPoint::negative(0.96, 0.04), | |
| 191 | PromptPoint::negative(0.04, 0.96), | |
| 192 | PromptPoint::negative(0.96, 0.96), | |
| 193 | ], | |
| 194 | } | |
| 195 | } | |
| 196 | } | |
| 197 | ||
| 198 | fn subsample_seeds(points: &[PromptPoint], max_total: usize) -> Vec<PromptPoint> { | |
| 199 | if points.len() <= max_total { | |
| 200 | return points.to_vec(); | |
| 201 | } | |
| 202 | let pos: Vec<PromptPoint> = points.iter().copied().filter(|p| p.positive).collect(); | |
| 203 | let neg: Vec<PromptPoint> = points.iter().copied().filter(|p| !p.positive).collect(); | |
| 204 | let (pos_budget, neg_budget) = if neg.is_empty() { | |
| 205 | (max_total, 0) | |
| 206 | } else if pos.is_empty() { | |
| 207 | (0, max_total) | |
| 208 | } else { | |
| 209 | let neg_share = neg.len().min(max_total / 3).max(1); | |
| 210 | let pos_share = max_total.saturating_sub(neg_share).min(pos.len()); | |
| 211 | let rem = max_total.saturating_sub(pos_share + neg_share); | |
| 212 | (pos_share, (neg_share + rem).min(neg.len())) | |
| 213 | }; | |
| 214 | let mut out = Vec::with_capacity(max_total); | |
| 215 | push_uniform_stride(&pos, pos_budget, &mut out); | |
| 216 | push_uniform_stride(&neg, neg_budget, &mut out); | |
| 217 | out | |
| 218 | } | |
| 219 | ||
| 220 | fn push_uniform_stride(src: &[PromptPoint], count: usize, dst: &mut Vec<PromptPoint>) { | |
| 221 | if count == 0 || src.is_empty() { | |
| 222 | return; | |
| 223 | } | |
| 224 | if src.len() <= count { | |
| 225 | dst.extend_from_slice(src); | |
| 226 | return; | |
| 227 | } | |
| 228 | for i in 0..count { | |
| 229 | let idx = (i * (src.len() - 1)) / (count - 1).max(1); | |
| 230 | dst.push(src[idx]); | |
| 231 | } | |
| 232 | } | |
| 233 | ||
| 234 | fn eval_num_alias( | |
| 235 | comp: &Comp, | |
| 236 | node: &Node, | |
| 237 | primary: &str, | |
| 238 | fallback: &str, | |
| 239 | time: f64, | |
| 240 | default: f64, | |
| 241 | expr: &ExprEngine, | |
| 242 | ) -> f64 { | |
| 243 | if node.inputs.contains_key(primary) { | |
| 244 | comp.eval_number(node, primary, time, default, expr) | |
| 245 | } else if node.inputs.contains_key(fallback) { | |
| 246 | comp.eval_number(node, fallback, time, default, expr) | |
| 247 | } else { | |
| 248 | default | |
| 249 | } | |
| 250 | } | |
| 251 | ||
| 252 | fn eval_output_mode(comp: &Comp, node: &Node, time: f64, expr: &ExprEngine) -> OutputMode { | |
| 253 | if node.inputs.contains_key("OutputMode") { | |
| 254 | if let Some(s) = node.static_str("OutputMode") { | |
| 255 | let lower = s.to_ascii_lowercase(); | |
| 256 | if lower.contains("matte") || lower.contains("alpha") { | |
| 257 | return OutputMode::MatteOnly; | |
| 258 | } | |
| 259 | if lower.contains("overlay") || lower.contains("mask") { | |
| 260 | return OutputMode::OverlayPreview; | |
| 261 | } | |
| 262 | if lower.contains("cutout") || lower.contains("premult") || lower.contains("final") { | |
| 263 | return OutputMode::PremultipliedCutout; | |
| 264 | } | |
| 265 | } | |
| 266 | let v = comp.eval_number(node, "OutputMode", time, 0.0, expr).round() as i32; | |
| 267 | return OutputMode::from_i32(v); | |
| 268 | } | |
| 269 | if comp.eval_number(node, "MatteOnly", time, 0.0, expr) > 0.5 { | |
| 270 | return OutputMode::MatteOnly; | |
| 271 | } | |
| 272 | if comp.eval_number(node, "ShowMask", time, 0.0, expr) > 0.5 { | |
| 273 | return OutputMode::OverlayPreview; | |
| 274 | } | |
| 275 | OutputMode::PremultipliedCutout | |
| 276 | } | |
| 277 | ||
| 278 | fn read_cache_dir(node: &Node) -> Option<String> { | |
| 279 | if let Some(dir) = node.static_str("CacheDir") { | |
| 280 | let trimmed = dir.trim(); | |
| 281 | if !trimmed.is_empty() { | |
| 282 | return Some(trimmed.to_owned()); | |
| 283 | } | |
| 284 | } | |
| 285 | if let Some(dir) = node.static_str("MatteDir") { | |
| 286 | let trimmed = dir.trim(); | |
| 287 | if !trimmed.is_empty() { | |
| 288 | return Some(trimmed.to_owned()); | |
| 289 | } | |
| 290 | } | |
| 291 | None | |
| 292 | } | |
| 293 | ||
| 294 | /// Extracts unified parameters for a Fission `AutoMatte` node. | |
| 295 | pub fn extract_auto_matte_params( | |
| 296 | comp: &Comp, | |
| 297 | node: &Node, | |
| 298 | time: f64, | |
| 299 | expr: &ExprEngine, | |
| 300 | ) -> AutoMatteParams { | |
| 301 | let prompt_mode = PromptMode::from_i32( | |
| 302 | comp.eval_number(node, "PromptMode", time, 0.0, expr).round() as i32, | |
| 303 | ); | |
| 304 | let quality_tier = QualityTier::from_i32( | |
| 305 | comp.eval_number(node, "QualityTier", time, 1.0, expr).round() as i32, | |
| 306 | ); | |
| 307 | let alpha_floor = comp | |
| 308 | .eval_number(node, "AlphaFloor", time, DEFAULT_ALPHA_FLOOR as f64, expr) | |
| 309 | .clamp(0.0, 0.95) as f32; | |
| 310 | let alpha_ceiling = comp | |
| 311 | .eval_number(node, "AlphaCeiling", time, DEFAULT_ALPHA_CEILING as f64, expr) | |
| 312 | .clamp((alpha_floor + 0.01) as f64, 1.0) as f32; | |
| 313 | let toe_gamma = comp | |
| 314 | .eval_number(node, "ToeGamma", time, DEFAULT_TOE_GAMMA as f64, expr) | |
| 315 | .clamp(0.1, 4.0) as f32; | |
| 316 | let decontaminate = comp | |
| 317 | .eval_number(node, "Decontaminate", time, 1.0, expr) | |
| 318 | .clamp(0.0, 1.0) as f32; | |
| 319 | let matte_blur = eval_num_alias(comp, node, "MatteBlur", "Blur", time, 0.0, expr).max(0.0) as f32; | |
| 320 | let matte_contract_expand = eval_num_alias( | |
| 321 | comp, | |
| 322 | node, | |
| 323 | "MatteContractExpand", | |
| 324 | "ContractExpand", | |
| 325 | time, | |
| 326 | 0.0, | |
| 327 | expr, | |
| 328 | ) as f32; | |
| 329 | let invert = eval_num_alias(comp, node, "Invert", "InvertMatte", time, 0.0, expr) > 0.5; | |
| 330 | let output_mode = eval_output_mode(comp, node, time, expr); | |
| 331 | let blend = comp.eval_number(node, "Blend", time, 1.0, expr).clamp(0.0, 1.0) as f32; | |
| 332 | let cache_dir = read_cache_dir(node); | |
| 333 | ||
| 334 | let mut points = extract_auto_matte_points(comp, node, time, expr); | |
| 335 | if points.is_empty() { | |
| 336 | points = extract_magic_mask_strokes(comp, node, time); | |
| 337 | } | |
| 338 | ||
| 339 | AutoMatteParams { | |
| 340 | is_magic_mask: false, | |
| 341 | prompt_mode, | |
| 342 | quality_tier, | |
| 343 | points, | |
| 344 | alpha_floor, | |
| 345 | alpha_ceiling, | |
| 346 | toe_gamma, | |
| 347 | decontaminate, | |
| 348 | matte_blur, | |
| 349 | matte_contract_expand, | |
| 350 | invert, | |
| 351 | output_mode, | |
| 352 | cache_dir, | |
| 353 | blend, | |
| 354 | } | |
| 355 | } | |
| 356 | ||
| 357 | /// Extracts unified parameters for a Fusion `MagicMask` node, mapping its real | |
| 358 | /// `MagicMaskStrokes` (`PosStrokes` / `NegStrokes`), `MatteBlur`, `MatteContractExpand`, | |
| 359 | /// `Invert`, `ShowMask` / `OutputMode` / `MatteOnly`, and `Blend` onto the `AutoMatte` pipeline. | |
| 360 | pub fn extract_magic_mask_params( | |
| 361 | comp: &Comp, | |
| 362 | node: &Node, | |
| 363 | time: f64, | |
| 364 | expr: &ExprEngine, | |
| 365 | ) -> AutoMatteParams { | |
| 366 | let points = { | |
| 367 | let mut pts = extract_magic_mask_strokes(comp, node, time); | |
| 368 | if pts.is_empty() { | |
| 369 | pts = extract_auto_matte_points(comp, node, time, expr); | |
| 370 | } | |
| 371 | pts | |
| 372 | }; | |
| 373 | ||
| 374 | let matte_blur = eval_num_alias(comp, node, "MatteBlur", "Blur", time, 0.0, expr).max(0.0) as f32; | |
| 375 | let matte_contract_expand = eval_num_alias( | |
| 376 | comp, | |
| 377 | node, | |
| 378 | "MatteContractExpand", | |
| 379 | "ContractExpand", | |
| 380 | time, | |
| 381 | 0.0, | |
| 382 | expr, | |
| 383 | ) as f32; | |
| 384 | let invert = eval_num_alias(comp, node, "Invert", "InvertMatte", time, 0.0, expr) > 0.5; | |
| 385 | let output_mode = eval_output_mode(comp, node, time, expr); | |
| 386 | let blend = comp.eval_number(node, "Blend", time, 1.0, expr).clamp(0.0, 1.0) as f32; | |
| 387 | let decontaminate = comp | |
| 388 | .eval_number(node, "Decontaminate", time, 1.0, expr) | |
| 389 | .clamp(0.0, 1.0) as f32; | |
| 390 | let alpha_floor = comp | |
| 391 | .eval_number(node, "AlphaFloor", time, DEFAULT_ALPHA_FLOOR as f64, expr) | |
| 392 | .clamp(0.0, 0.95) as f32; | |
| 393 | let alpha_ceiling = comp | |
| 394 | .eval_number(node, "AlphaCeiling", time, DEFAULT_ALPHA_CEILING as f64, expr) | |
| 395 | .clamp((alpha_floor + 0.01) as f64, 1.0) as f32; | |
| 396 | let toe_gamma = comp | |
| 397 | .eval_number(node, "ToeGamma", time, DEFAULT_TOE_GAMMA as f64, expr) | |
| 398 | .clamp(0.1, 4.0) as f32; | |
| 399 | let quality_tier = QualityTier::from_i32( | |
| 400 | comp.eval_number(node, "QualityTier", time, 1.0, expr).round() as i32, | |
| 401 | ); | |
| 402 | let cache_dir = read_cache_dir(node); | |
| 403 | ||
| 404 | AutoMatteParams { | |
| 405 | is_magic_mask: true, | |
| 406 | prompt_mode: PromptMode::ClickPoints, | |
| 407 | quality_tier, | |
| 408 | points, | |
| 409 | alpha_floor, | |
| 410 | alpha_ceiling, | |
| 411 | toe_gamma, | |
| 412 | decontaminate, | |
| 413 | matte_blur, | |
| 414 | matte_contract_expand, | |
| 415 | invert, | |
| 416 | output_mode, | |
| 417 | cache_dir, | |
| 418 | blend, | |
| 419 | } | |
| 420 | } | |
| 421 | ||
| 422 | /// Parses a Fusion `MagicMaskStrokes { PosStrokes = { ... }, NegStrokes = { ... } }` Lua table. | |
| 423 | /// | |
| 424 | /// Supports both flat `{ { x, y }, ... }` point arrays (Fusion 18/19/20 `.comp` format) and | |
| 425 | /// nested stroke polyline arrays `{ { { x, y }, ... }, ... }`. | |
| 426 | pub fn parse_magic_mask_strokes_table(table: &LuaTable) -> Vec<PromptPoint> { | |
| 427 | let mut out = Vec::new(); | |
| 428 | if let Some(pos) = table.get_table("PosStrokes") { | |
| 429 | collect_point_list(pos, true, &mut out); | |
| 430 | } | |
| 431 | if let Some(neg) = table.get_table("NegStrokes") { | |
| 432 | collect_point_list(neg, false, &mut out); | |
| 433 | } | |
| 434 | out | |
| 435 | } | |
| 436 | ||
| 437 | fn collect_point_list(table: &LuaTable, positive: bool, out: &mut Vec<PromptPoint>) { | |
| 438 | // Check if `table` itself is a single `{ x, y }` pair | |
| 439 | if let Some([x, y]) = read_xy_pair(table) { | |
| 440 | out.push(PromptPoint { x, y, positive, weight: 1.0 }); | |
| 441 | return; | |
| 442 | } | |
| 443 | for val in table.positional_values() { | |
| 444 | let Some(entry) = val.as_table() else { continue }; | |
| 445 | if let Some([x, y]) = read_xy_pair(entry) { | |
| 446 | out.push(PromptPoint { x, y, positive, weight: 1.0 }); | |
| 447 | } else { | |
| 448 | // Nested stroke polyline `{ { x1, y1 }, { x2, y2 }, ... }` | |
| 449 | for sub in entry.positional_values() { | |
| 450 | if let Some(pt_tbl) = sub.as_table() { | |
| 451 | if let Some([x, y]) = read_xy_pair(pt_tbl) { | |
| 452 | out.push(PromptPoint { x, y, positive, weight: 1.0 }); | |
| 453 | } | |
| 454 | } | |
| 455 | } | |
| 456 | } | |
| 457 | } | |
| 458 | } | |
| 459 | ||
| 460 | fn read_xy_pair(t: &LuaTable) -> Option<[f32; 2]> { | |
| 461 | let x = t.get_index(1)?.as_f64()?; | |
| 462 | let y = t.get_index(2)?.as_f64()?; | |
| 463 | if x.is_finite() && y.is_finite() { | |
| 464 | Some([x as f32, y as f32]) | |
| 465 | } else { | |
| 466 | None | |
| 467 | } | |
| 468 | } | |
| 469 | ||
| 470 | fn extract_magic_mask_strokes(comp: &Comp, node: &Node, time: f64) -> Vec<PromptPoint> { | |
| 471 | // 1. Follow `Strokes = Input { SourceOp = "MagicMask1Strokes", Source = "Value" }` into | |
| 472 | // `comp.raw_root.Tools[source_op].KeyFrames` | |
| 473 | for stroke_input in ["Strokes", "LegacyStrokes"] { | |
| 474 | if let Some(binding) = node.inputs.get(stroke_input) { | |
| 475 | if let Some(src_op) = &binding.source_op { | |
| 476 | if let Some(pts) = read_strokes_from_spline_tool(comp, src_op, time) { | |
| 477 | if !pts.is_empty() { | |
| 478 | return pts; | |
| 479 | } | |
| 480 | } | |
| 481 | } | |
| 482 | if let Some(ParamValue::Raw(LuaValue::Table(t))) = &binding.value { | |
| 483 | let pts = parse_magic_mask_strokes_table(t); | |
| 484 | if !pts.is_empty() { | |
| 485 | return pts; | |
| 486 | } | |
| 487 | } | |
| 488 | } | |
| 489 | // Also check raw `Inputs.<stroke_input>.Value` directly | |
| 490 | if let Some(val_tbl) = node | |
| 491 | .raw | |
| 492 | .get_table("Inputs") | |
| 493 | .and_then(|i| i.get_table(stroke_input)) | |
| 494 | .and_then(|s| s.get_table("Value")) | |
| 495 | { | |
| 496 | let pts = parse_magic_mask_strokes_table(val_tbl); | |
| 497 | if !pts.is_empty() { | |
| 498 | return pts; | |
| 499 | } | |
| 500 | } | |
| 501 | } | |
| 502 | Vec::new() | |
| 503 | } | |
| 504 | ||
| 505 | fn read_strokes_from_spline_tool(comp: &Comp, spline_name: &str, time: f64) -> Option<Vec<PromptPoint>> { | |
| 506 | let tools = comp.raw_root.as_ref()?.get_table("Tools")?; | |
| 507 | let spline_tbl = find_tool_table_recursive(tools, spline_name)?; | |
| 508 | let kfs = spline_tbl.get_table("KeyFrames")?; | |
| 509 | ||
| 510 | let mut keyframes: Vec<(f64, &LuaTable)> = Vec::new(); | |
| 511 | for (k, v) in &kfs.entries { | |
| 512 | let kf_time = match k { | |
| 513 | LuaKey::Index(i) => *i as f64, | |
| 514 | LuaKey::Number(n) => *n, | |
| 515 | _ => continue, | |
| 516 | }; | |
| 517 | if !kf_time.is_finite() { | |
| 518 | continue; | |
| 519 | } | |
| 520 | let Some(kf_tbl) = v.as_table() else { continue }; | |
| 521 | let Some(val_tbl) = kf_tbl.get_table("Value") else { continue }; | |
| 522 | keyframes.push((kf_time, val_tbl)); | |
| 523 | } | |
| 524 | if keyframes.is_empty() { | |
| 525 | return None; | |
| 526 | } | |
| 527 | keyframes.sort_by(|a, b| a.0.total_cmp(&b.0)); | |
| 528 | ||
| 529 | // Pick closest keyframe <= time, or earliest keyframe if time precedes all keyframes | |
| 530 | let chosen = keyframes | |
| 531 | .iter() | |
| 532 | .rev() | |
| 533 | .find(|(t, _)| *t <= time + 1e-6) | |
| 534 | .unwrap_or(&keyframes[0]); | |
| 535 | Some(parse_magic_mask_strokes_table(chosen.1)) | |
| 536 | } | |
| 537 | ||
| 538 | fn find_tool_table_recursive<'a>(tools: &'a LuaTable, name: &str) -> Option<&'a LuaTable> { | |
| 539 | if let Some(t) = tools.get_table(name) { | |
| 540 | return Some(t); | |
| 541 | } | |
| 542 | for (_, val) in &tools.entries { | |
| 543 | if let Some(t) = val.as_table() { | |
| 544 | if let Some(inner) = t.get_table("Tools") { | |
| 545 | if let Some(found) = find_tool_table_recursive(inner, name) { | |
| 546 | return Some(found); | |
| 547 | } | |
| 548 | } | |
| 549 | } | |
| 550 | } | |
| 551 | None | |
| 552 | } | |
| 553 | ||
| 554 | fn extract_auto_matte_points( | |
| 555 | comp: &Comp, | |
| 556 | node: &Node, | |
| 557 | time: f64, | |
| 558 | expr: &ExprEngine, | |
| 559 | ) -> Vec<PromptPoint> { | |
| 560 | let mut out = Vec::new(); | |
| 561 | ||
| 562 | // 1. `Points` input: table of `{ x, y, label }` OR string `"x,y,+;x,y,-"` | |
| 563 | if let Some(binding) = node.inputs.get("Points") { | |
| 564 | match &binding.value { | |
| 565 | Some(ParamValue::Text(s)) | Some(ParamValue::FuId(s)) => { | |
| 566 | parse_points_string(s, None, &mut out); | |
| 567 | } | |
| 568 | Some(ParamValue::Raw(LuaValue::Table(t))) => { | |
| 569 | parse_mixed_points_table(t, &mut out); | |
| 570 | } | |
| 571 | Some(ParamValue::Point([x, y])) => { | |
| 572 | out.push(PromptPoint::positive(*x as f32, *y as f32)); | |
| 573 | } | |
| 574 | _ => {} | |
| 575 | } | |
| 576 | } | |
| 577 | ||
| 578 | // 2. `PositivePoints` / `NegativePoints`: table of `{ {x, y}, ... }` OR string `"x,y;x,y"` | |
| 579 | for (key, positive) in [("PositivePoints", true), ("NegativePoints", false)] { | |
| 580 | if let Some(binding) = node.inputs.get(key) { | |
| 581 | match &binding.value { | |
| 582 | Some(ParamValue::Text(s)) | Some(ParamValue::FuId(s)) => { | |
| 583 | parse_points_string(s, Some(positive), &mut out); | |
| 584 | } | |
| 585 | Some(ParamValue::Raw(LuaValue::Table(t))) => { | |
| 586 | collect_point_list(t, positive, &mut out); | |
| 587 | } | |
| 588 | Some(ParamValue::Point([x, y])) => { | |
| 589 | out.push(PromptPoint { | |
| 590 | x: *x as f32, | |
| 591 | y: *y as f32, | |
| 592 | positive, | |
| 593 | weight: 1.0, | |
| 594 | }); | |
| 595 | } | |
| 596 | _ => {} | |
| 597 | } | |
| 598 | } | |
| 599 | } | |
| 600 | ||
| 601 | // 3. Numbered point inputs `PosPoint1..16`, `NegPoint1..16`, `Point1..16` (animated-safe!) | |
| 602 | for idx in 1..=16 { | |
| 603 | let pos_name = format!("PosPoint{idx}"); | |
| 604 | if node.inputs.contains_key(&pos_name) { | |
| 605 | let [x, y] = comp.eval_point(node, &pos_name, time, [0.5, 0.5], expr); | |
| 606 | out.push(PromptPoint::positive(x as f32, y as f32)); | |
| 607 | } | |
| 608 | let neg_name = format!("NegPoint{idx}"); | |
| 609 | if node.inputs.contains_key(&neg_name) { | |
| 610 | let [x, y] = comp.eval_point(node, &neg_name, time, [0.5, 0.5], expr); | |
| 611 | out.push(PromptPoint::negative(x as f32, y as f32)); | |
| 612 | } | |
| 613 | let pt_name = format!("Point{idx}"); | |
| 614 | if node.inputs.contains_key(&pt_name) { | |
| 615 | let [x, y] = comp.eval_point(node, &pt_name, time, [0.5, 0.5], expr); | |
| 616 | let lbl_name = format!("Point{idx}Label"); | |
| 617 | let positive = comp.eval_number(node, &lbl_name, time, 1.0, expr) >= 0.5; | |
| 618 | out.push(PromptPoint { | |
| 619 | x: x as f32, | |
| 620 | y: y as f32, | |
| 621 | positive, | |
| 622 | weight: 1.0, | |
| 623 | }); | |
| 624 | } | |
| 625 | } | |
| 626 | ||
| 627 | out | |
| 628 | } | |
| 629 | ||
| 630 | fn parse_mixed_points_table(table: &LuaTable, out: &mut Vec<PromptPoint>) { | |
| 631 | // Support `Points = { PosStrokes = ..., NegStrokes = ... }` as well | |
| 632 | if table.get_table("PosStrokes").is_some() || table.get_table("NegStrokes").is_some() { | |
| 633 | out.extend(parse_magic_mask_strokes_table(table)); | |
| 634 | return; | |
| 635 | } | |
| 636 | for val in table.positional_values() { | |
| 637 | let Some(entry) = val.as_table() else { continue }; | |
| 638 | let Some([x, y]) = read_xy_pair(entry) else { continue }; | |
| 639 | let positive = match entry.get_index(3) { | |
| 640 | Some(LuaValue::Number(n)) => *n > 0.0, | |
| 641 | Some(LuaValue::Bool(b)) => *b, | |
| 642 | Some(LuaValue::String(s)) => !s.starts_with('-') && !s.eq_ignore_ascii_case("neg"), | |
| 643 | _ => entry.get_f64("Label").is_none_or(|n| n > 0.0), | |
| 644 | }; | |
| 645 | out.push(PromptPoint { x, y, positive, weight: 1.0 }); | |
| 646 | } | |
| 647 | } | |
| 648 | ||
| 649 | fn parse_points_string(s: &str, forced_positive: Option<bool>, out: &mut Vec<PromptPoint>) { | |
| 650 | for raw_item in s.split([';', '\n']) { | |
| 651 | let item = raw_item.trim(); | |
| 652 | if item.is_empty() { | |
| 653 | continue; | |
| 654 | } | |
| 655 | let parts: Vec<&str> = item | |
| 656 | .split(|c: char| c == ',' || c.is_whitespace()) | |
| 657 | .filter(|t| !t.is_empty()) | |
| 658 | .collect(); | |
| 659 | if parts.len() < 2 { | |
| 660 | continue; | |
| 661 | } | |
| 662 | let Ok(x) = parts[0].parse::<f32>() else { continue }; | |
| 663 | let Ok(y) = parts[1].parse::<f32>() else { continue }; | |
| 664 | if !x.is_finite() || !y.is_finite() { | |
| 665 | continue; | |
| 666 | } | |
| 667 | let positive = if let Some(p) = forced_positive { | |
| 668 | p | |
| 669 | } else if let Some(tag) = parts.get(2) { | |
| 670 | let t = tag.trim().to_ascii_lowercase(); | |
| 671 | !(t == "-" || t == "0" || t == "-1" || t == "neg" || t == "bg" || t == "false") | |
| 672 | } else { | |
| 673 | true | |
| 674 | }; | |
| 675 | out.push(PromptPoint { x, y, positive, weight: 1.0 }); | |
| 676 | } | |
| 677 | } |
crates/engine/src/auto_matte/tests.rs created+606| ... | ... | @@ -0,0 +1,606 @@ |
| 1 | use super::*; | |
| 2 | use crate::Engine; | |
| 3 | use model::Comp; | |
| 4 | ||
| 5 | fn mk_comp(tools: &str) -> Comp { | |
| 6 | let src = format!( | |
| 7 | "Composition {{ CurrentTime = 0, RenderRange = {{ 0, 10 }}, GlobalRange = {{ 0, 10 }}, Tools = ordered() {{ {tools} }} }}" | |
| 8 | ); | |
| 9 | Comp::from_fusion_str(&src).expect("parse AutoMatte test comp") | |
| 10 | } | |
| 11 | ||
| 12 | fn px_u8(buf: &[u8], w: u32, x: u32, y: u32) -> [u8; 4] { | |
| 13 | let i = ((y * w + x) * 4) as usize; | |
| 14 | buf[i..i + 4].try_into().unwrap() | |
| 15 | } | |
| 16 | ||
| 17 | fn px_f32(buf: &[f32], w: u32, x: u32, y: u32) -> [f32; 4] { | |
| 18 | let i = ((y * w + x) * 4) as usize; | |
| 19 | buf[i..i + 4].try_into().unwrap() | |
| 20 | } | |
| 21 | ||
| 22 | /// 1. Exact GPU verification of Clover's `polish_alpha` (haze floor elimination, ceiling clamping, | |
| 23 | /// toe compression below 0.15 while keeping strands >= 0.15 exact, plus Invert/Blur/Morpho/Modes). | |
| 24 | #[test] | |
| 25 | fn polish_alpha_floor_ceiling_toe_and_modes() { | |
| 26 | let Ok(mut eng) = Engine::new_headless() else { return }; | |
| 27 | let comp = mk_comp( | |
| 28 | r#" | |
| 29 | Plate = Background { | |
| 30 | Inputs = { | |
| 31 | Width = Input { Value = 64, }, Height = Input { Value = 16, }, | |
| 32 | Depth = Input { Value = 3, }, | |
| 33 | TopLeftRed = Input { Value = 0.8, }, TopLeftGreen = Input { Value = 0.6, }, TopLeftBlue = Input { Value = 0.4, }, | |
| 34 | }, | |
| 35 | }, | |
| 36 | AM = AutoMatte { | |
| 37 | Inputs = { | |
| 38 | Input = Input { SourceOp = "Plate", Source = "Output", }, | |
| 39 | OutputMode = Input { Value = 1, }, | |
| 40 | }, | |
| 41 | }, | |
| 42 | AMInv = AutoMatte { | |
| 43 | Inputs = { | |
| 44 | Input = Input { SourceOp = "Plate", Source = "Output", }, | |
| 45 | OutputMode = Input { Value = 1, }, | |
| 46 | Invert = Input { Value = 1, }, | |
| 47 | }, | |
| 48 | }, | |
| 49 | AMOverlay = AutoMatte { | |
| 50 | Inputs = { | |
| 51 | Input = Input { SourceOp = "Plate", Source = "Output", }, | |
| 52 | OutputMode = Input { Value = 2, }, | |
| 53 | }, | |
| 54 | }, | |
| 55 | "#, | |
| 56 | ); | |
| 57 | ||
| 58 | // Build a 64x16 horizontal ramp of raw alpha values covering haze, toe, strands, and ceiling | |
| 59 | let w = 64u32; | |
| 60 | let h = 16u32; | |
| 61 | let mut ramp = vec![0.0_f32; (w * h) as usize]; | |
| 62 | for y in 0..h { | |
| 63 | for x in 0..w { | |
| 64 | ramp[(y * w + x) as usize] = x as f32 / (w - 1) as f32; | |
| 65 | } | |
| 66 | } | |
| 67 | eng.auto_matte_cache.insert_alpha_f32("AM", 0, [w, h], ramp.clone()); | |
| 68 | eng.auto_matte_cache.insert_alpha_f32("AMInv", 0, [w, h], ramp.clone()); | |
| 69 | eng.auto_matte_cache.insert_alpha_f32("AMOverlay", 0, [w, h], ramp); | |
| 70 | ||
| 71 | let (tex, _) = eng.evaluate(&comp, comp.find_node("AM").unwrap(), 0.0); | |
| 72 | let f32_buf = eng.readback_rgba_f32(&tex).unwrap(); | |
| 73 | ||
| 74 | // Check every column against Clover's exact `polish_alpha` formula | |
| 75 | let lo = 0.045_f32; | |
| 76 | let hi = 0.985_f32; | |
| 77 | let toe_gamma = 1.35_f32; | |
| 78 | for x in 0..w { | |
| 79 | let raw = x as f32 / (w - 1) as f32; | |
| 80 | let lin = ((raw - lo) / (hi - lo)).clamp(0.0, 1.0); | |
| 81 | let expected = if lin < 0.15 { | |
| 82 | (lin / 0.15).powf(toe_gamma) * 0.15 | |
| 83 | } else { | |
| 84 | lin | |
| 85 | }; | |
| 86 | let got = px_f32(&f32_buf, w, x, 8); | |
| 87 | assert!( | |
| 88 | (got[3] - expected).abs() < 2e-3, | |
| 89 | "polish_alpha mismatch at x={x} (raw={raw:.4}): got={:.5} expected={:.5}", | |
| 90 | got[3], | |
| 91 | expected | |
| 92 | ); | |
| 93 | // OutputMode = 1 outputs grayscale (a, a, a, a) | |
| 94 | assert!((got[0] - got[3]).abs() < 2e-3); | |
| 95 | } | |
| 96 | ||
| 97 | // Haze <= 0.045 (x=0,1,2 -> raw <= 0.0317) must be exact 0.0 | |
| 98 | assert_eq!(px_f32(&f32_buf, w, 2, 8)[3], 0.0, "VAE haze <= 0.045 must be eliminated"); | |
| 99 | // Ceiling >= 0.985 (x=63 -> raw=1.0) must be exact 1.0 | |
| 100 | assert_eq!(px_f32(&f32_buf, w, 63, 8)[3], 1.0, "Ceiling >= 0.985 must clamp to 1.0"); | |
| 101 | // Toe compression (x=7 -> raw=0.1111 -> lin=0.0703 < 0.15) strictly compressed below linear | |
| 102 | let toe_raw = 7.0_f32 / 63.0; | |
| 103 | let toe_lin = (toe_raw - lo) / (hi - lo); | |
| 104 | let toe_got = px_f32(&f32_buf, w, 7, 8)[3]; | |
| 105 | assert!(toe_got > 0.0 && toe_got < toe_lin - 0.01, "toe must compress misty halo: got={toe_got} lin={toe_lin}"); | |
| 106 | // Strand > 0.15 (x=20 -> raw=0.3175 -> lin=0.2899) untouched by toe | |
| 107 | let strand_raw = 20.0_f32 / 63.0; | |
| 108 | let strand_lin = (strand_raw - lo) / (hi - lo); | |
| 109 | let strand_got = px_f32(&f32_buf, w, 20, 8)[3]; | |
| 110 | assert!((strand_got - strand_lin).abs() < 2e-3, "strand > 0.15 must stay crisp: got={strand_got} lin={strand_lin}"); | |
| 111 | ||
| 112 | // Invert = 1 flips alpha | |
| 113 | let (inv_tex, _) = eng.evaluate(&comp, comp.find_node("AMInv").unwrap(), 0.0); | |
| 114 | let inv_buf = eng.readback_rgba_f32(&inv_tex).unwrap(); | |
| 115 | assert_eq!(px_f32(&inv_buf, w, 2, 8)[3], 1.0); | |
| 116 | assert_eq!(px_f32(&inv_buf, w, 63, 8)[3], 0.0); | |
| 117 | ||
| 118 | // OutputMode = 2 renders opaque ruby overlay where alpha == 1, untouched plate where alpha == 0 | |
| 119 | let (ov_tex, _) = eng.evaluate(&comp, comp.find_node("AMOverlay").unwrap(), 0.0); | |
| 120 | let ov_buf = eng.readback_rgba_f32(&ov_tex).unwrap(); | |
| 121 | let bg_px = px_f32(&ov_buf, w, 1, 8); | |
| 122 | let fg_px = px_f32(&ov_buf, w, 63, 8); | |
| 123 | assert!((bg_px[0] - 0.8).abs() < 1e-2 && (bg_px[3] - 1.0).abs() < 1e-2); | |
| 124 | assert!(fg_px[0] > bg_px[0] + 0.05 && fg_px[1] < bg_px[1] - 0.1, "overlay tints foreground ruby: {fg_px:?}"); | |
| 125 | } | |
| 126 | ||
| 127 | /// 2. GPU `hair_safe_decontaminate`: eliminates neon-cyan background spill inside semi-transparent | |
| 128 | /// hair edge pixels while keeping solid interior (`alpha > 0.94`) RGB bit-exact. | |
| 129 | #[test] | |
| 130 | fn hair_safe_decontaminate_kills_cyan_spill_and_preserves_solid_interior() { | |
| 131 | let Ok(mut eng) = Engine::new_headless() else { return }; | |
| 132 | // Left half [0..26): pure solid brown hair RGB = (0.44, 0.22, 0.10) | |
| 133 | // Middle band [26..36): wispy hair heavily contaminated with neon cyan (0.0, 1.0, 1.0) | |
| 134 | // Right half [36..64): pure neon cyan background (0.0, 1.0, 1.0) | |
| 135 | let comp = mk_comp( | |
| 136 | r#" | |
| 137 | CyanBg = Background { | |
| 138 | Inputs = { | |
| 139 | Width = Input { Value = 64, }, Height = Input { Value = 64, }, | |
| 140 | TopLeftRed = Input { Value = 0.0, }, TopLeftGreen = Input { Value = 1.0, }, TopLeftBlue = Input { Value = 1.0, }, | |
| 141 | }, | |
| 142 | }, | |
| 143 | HairMask = RectangleMask { | |
| 144 | Inputs = { | |
| 145 | MaskWidth = Input { Value = 64, }, MaskHeight = Input { Value = 64, }, | |
| 146 | Center = Input { Value = { 0.20, 0.5 }, }, Width = Input { Value = 0.40, }, Height = Input { Value = 1.0, }, | |
| 147 | }, | |
| 148 | }, | |
| 149 | HairFg = Background { | |
| 150 | Inputs = { | |
| 151 | Width = Input { Value = 64, }, Height = Input { Value = 64, }, | |
| 152 | TopLeftRed = Input { Value = 0.44, }, TopLeftGreen = Input { Value = 0.22, }, TopLeftBlue = Input { Value = 0.10, }, | |
| 153 | EffectMask = Input { SourceOp = "HairMask", Source = "Mask", }, | |
| 154 | }, | |
| 155 | }, | |
| 156 | SpillMask = RectangleMask { | |
| 157 | Inputs = { | |
| 158 | MaskWidth = Input { Value = 64, }, MaskHeight = Input { Value = 64, }, | |
| 159 | Center = Input { Value = { 0.48, 0.5 }, }, Width = Input { Value = 0.16, }, Height = Input { Value = 1.0, }, | |
| 160 | }, | |
| 161 | }, | |
| 162 | SpillBand = Background { | |
| 163 | Inputs = { | |
| 164 | Width = Input { Value = 64, }, Height = Input { Value = 64, }, | |
| 165 | TopLeftRed = Input { Value = 0.15, }, TopLeftGreen = Input { Value = 0.85, }, TopLeftBlue = Input { Value = 0.90, }, | |
| 166 | EffectMask = Input { SourceOp = "SpillMask", Source = "Mask", }, | |
| 167 | }, | |
| 168 | }, | |
| 169 | M1 = Merge { | |
| 170 | Inputs = { | |
| 171 | Background = Input { SourceOp = "CyanBg", Source = "Output", }, | |
| 172 | Foreground = Input { SourceOp = "HairFg", Source = "Output", }, | |
| 173 | }, | |
| 174 | }, | |
| 175 | Plate = Merge { | |
| 176 | Inputs = { | |
| 177 | Background = Input { SourceOp = "M1", Source = "Output", }, | |
| 178 | Foreground = Input { SourceOp = "SpillBand", Source = "Output", }, | |
| 179 | }, | |
| 180 | }, | |
| 181 | AMClean = AutoMatte { | |
| 182 | Inputs = { | |
| 183 | Input = Input { SourceOp = "Plate", Source = "Output", }, | |
| 184 | Decontaminate = Input { Value = 1.0, }, | |
| 185 | AlphaFloor = Input { Value = 0.0, }, | |
| 186 | AlphaCeiling = Input { Value = 1.0, }, | |
| 187 | ToeGamma = Input { Value = 1.0, }, | |
| 188 | }, | |
| 189 | }, | |
| 190 | AMRaw = AutoMatte { | |
| 191 | Inputs = { | |
| 192 | Input = Input { SourceOp = "Plate", Source = "Output", }, | |
| 193 | Decontaminate = Input { Value = 0.0, }, | |
| 194 | AlphaFloor = Input { Value = 0.0, }, | |
| 195 | AlphaCeiling = Input { Value = 1.0, }, | |
| 196 | ToeGamma = Input { Value = 1.0, }, | |
| 197 | }, | |
| 198 | }, | |
| 199 | "#, | |
| 200 | ); | |
| 201 | ||
| 202 | let (w, h) = (64u32, 64u32); | |
| 203 | let mut alpha = vec![0.0_f32; (w * h) as usize]; | |
| 204 | for y in 0..h { | |
| 205 | for x in 0..w { | |
| 206 | let a = if x < 25 { | |
| 207 | 1.0 | |
| 208 | } else if x < 36 { | |
| 209 | // Semi-transparent wispy hair strands (< 0.85) sitting directly over cyan spill | |
| 210 | 0.50 | |
| 211 | } else { | |
| 212 | 0.0 | |
| 213 | }; | |
| 214 | alpha[(y * w + x) as usize] = a; | |
| 215 | } | |
| 216 | } | |
| 217 | eng.auto_matte_cache.insert_alpha_f32("AMClean", 0, [w, h], alpha.clone()); | |
| 218 | eng.auto_matte_cache.insert_alpha_f32("AMRaw", 0, [w, h], alpha); | |
| 219 | ||
| 220 | let (plate_tex, _) = eng.evaluate(&comp, comp.find_node("Plate").unwrap(), 0.0); | |
| 221 | let plate_px = eng.readback_rgba(&plate_tex).unwrap(); | |
| 222 | ||
| 223 | let (clean_tex, _) = eng.evaluate(&comp, comp.find_node("AMClean").unwrap(), 0.0); | |
| 224 | let clean_px = eng.readback_rgba(&clean_tex).unwrap(); | |
| 225 | ||
| 226 | let (raw_tex, _) = eng.evaluate(&comp, comp.find_node("AMRaw").unwrap(), 0.0); | |
| 227 | let raw_px = eng.readback_rgba(&raw_tex).unwrap(); | |
| 228 | ||
| 229 | // 1. Solid interior (x=10, y=32, alpha=1.0) MUST be bit-exact to original Plate | |
| 230 | assert_eq!( | |
| 231 | px_u8(&clean_px, w, 10, 32), | |
| 232 | px_u8(&plate_px, w, 10, 32), | |
| 233 | "solid interior (alpha > 0.94) must remain bit-exact" | |
| 234 | ); | |
| 235 | ||
| 236 | // 2. Wispy edge pixel (x=30, y=32, alpha=0.50): unpremultiplied foreground must match clean | |
| 237 | // brown hair (~112, 56, 26), completely removing the cyan spill (~38, 217, 230) seen in AMRaw! | |
| 238 | let wisp_clean = px_u8(&clean_px, w, 30, 32); | |
| 239 | let wisp_raw = px_u8(&raw_px, w, 30, 32); | |
| 240 | assert!((wisp_clean[3] as i32 - 128).abs() <= 2, "wisp alpha preserved: {wisp_clean:?}"); | |
| 241 | let clean_unpremult_r = wisp_clean[0] as f32 / (wisp_clean[3] as f32 / 255.0); | |
| 242 | let clean_unpremult_g = wisp_clean[1] as f32 / (wisp_clean[3] as f32 / 255.0); | |
| 243 | let clean_unpremult_b = wisp_clean[2] as f32 / (wisp_clean[3] as f32 / 255.0); | |
| 244 | let raw_unpremult_b = wisp_raw[2] as f32 / (wisp_raw[3] as f32 / 255.0); | |
| 245 | ||
| 246 | assert!( | |
| 247 | raw_unpremult_b > 200.0, | |
| 248 | "sanity check: raw non-decontaminated wisp carries heavy cyan blue spill ({raw_unpremult_b:.1})" | |
| 249 | ); | |
| 250 | assert!( | |
| 251 | clean_unpremult_r > 95.0 && clean_unpremult_g < 75.0 && clean_unpremult_b < 45.0, | |
| 252 | "hair_safe_decontaminate must replace cyan spill with clean extrapolated brown hair: clean=({clean_unpremult_r:.1}, {clean_unpremult_g:.1}, {clean_unpremult_b:.1})" | |
| 253 | ); | |
| 254 | ||
| 255 | // 3. Background (x=55, y=32, alpha=0.0) must be transparent black | |
| 256 | assert_eq!(px_u8(&clean_px, w, 55, 32), [0, 0, 0, 0]); | |
| 257 | } | |
| 258 | ||
| 259 | /// 3. Built-in GPU point-seeded segmentation (`+`/`-` click points + bilateral edge refinement, | |
| 260 | /// plus `AutoPerson` center-salient heuristic with zero clicks). | |
| 261 | #[test] | |
| 262 | fn gpu_seeded_segmentation_separates_fg_from_bg() { | |
| 263 | let Ok(mut eng) = Engine::new_headless() else { return }; | |
| 264 | let comp = mk_comp( | |
| 265 | r#" | |
| 266 | BlueBg = Background { | |
| 267 | Inputs = { | |
| 268 | Width = Input { Value = 64, }, Height = Input { Value = 64, }, | |
| 269 | TopLeftRed = Input { Value = 0.08, }, TopLeftGreen = Input { Value = 0.16, }, TopLeftBlue = Input { Value = 0.86, }, | |
| 270 | }, | |
| 271 | }, | |
| 272 | BoxM = RectangleMask { | |
| 273 | Inputs = { | |
| 274 | MaskWidth = Input { Value = 64, }, MaskHeight = Input { Value = 64, }, | |
| 275 | Center = Input { Value = { 0.5, 0.5 }, }, Width = Input { Value = 0.45, }, Height = Input { Value = 0.45, }, | |
| 276 | }, | |
| 277 | }, | |
| 278 | RedObj = Background { | |
| 279 | Inputs = { | |
| 280 | Width = Input { Value = 64, }, Height = Input { Value = 64, }, | |
| 281 | TopLeftRed = Input { Value = 0.88, }, TopLeftGreen = Input { Value = 0.12, }, TopLeftBlue = Input { Value = 0.10, }, | |
| 282 | EffectMask = Input { SourceOp = "BoxM", Source = "Mask", }, | |
| 283 | }, | |
| 284 | }, | |
| 285 | Plate = Merge { | |
| 286 | Inputs = { | |
| 287 | Background = Input { SourceOp = "BlueBg", Source = "Output", }, | |
| 288 | Foreground = Input { SourceOp = "RedObj", Source = "Output", }, | |
| 289 | }, | |
| 290 | }, | |
| 291 | AMPoints = AutoMatte { | |
| 292 | Inputs = { | |
| 293 | Input = Input { SourceOp = "Plate", Source = "Output", }, | |
| 294 | Points = Input { Value = "0.50,0.50,+;0.10,0.10,-;0.90,0.90,-", }, | |
| 295 | QualityTier = Input { Value = 1, }, | |
| 296 | }, | |
| 297 | }, | |
| 298 | AMAutoPerson = AutoMatte { | |
| 299 | Inputs = { | |
| 300 | Input = Input { SourceOp = "Plate", Source = "Output", }, | |
| 301 | PromptMode = Input { Value = 1, }, | |
| 302 | QualityTier = Input { Value = 0, }, | |
| 303 | }, | |
| 304 | }, | |
| 305 | "#, | |
| 306 | ); | |
| 307 | ||
| 308 | // Explicit +/- click points | |
| 309 | let (tex, _) = eng.evaluate(&comp, comp.find_node("AMPoints").unwrap(), 0.0); | |
| 310 | let buf = eng.readback_rgba(&tex).unwrap(); | |
| 311 | let center = px_u8(&buf, 64, 32, 32); | |
| 312 | let corner_tl = px_u8(&buf, 64, 4, 4); | |
| 313 | let corner_br = px_u8(&buf, 64, 60, 60); | |
| 314 | assert!(center[3] >= 245 && center[0] > 200, "foreground center must be opaque red: {center:?}"); | |
| 315 | assert!(corner_tl[3] <= 5 && corner_br[3] <= 5, "background corners must be keyed out: tl={corner_tl:?} br={corner_br:?}"); | |
| 316 | ||
| 317 | // AutoPerson mode with zero manual points | |
| 318 | let (ap_tex, _) = eng.evaluate(&comp, comp.find_node("AMAutoPerson").unwrap(), 0.0); | |
| 319 | let ap_buf = eng.readback_rgba(&ap_tex).unwrap(); | |
| 320 | assert!(px_u8(&ap_buf, 64, 32, 32)[3] >= 240, "AutoPerson center subject must be opaque"); | |
| 321 | assert!(px_u8(&ap_buf, 64, 4, 4)[3] <= 10, "AutoPerson border background must be transparent"); | |
| 322 | } | |
| 323 | ||
| 324 | /// 4. `AutoMatteCache` per-frame injection, disk `CacheDir` PNG loading, real Fusion `MagicMask` | |
| 325 | /// `MagicMaskStrokes` spline parsing, and empty-stroke passthrough (0.00% MAE). | |
| 326 | #[test] | |
| 327 | fn cache_injection_and_fusion_magic_mask_strokes_and_empty_passthrough() { | |
| 328 | let Ok(mut eng) = Engine::new_headless() else { return }; | |
| 329 | ||
| 330 | // Real Fusion MagicMask comp structure matching `/Volumes/Project/trees/fusion/21_ground.comp` | |
| 331 | let comp = mk_comp( | |
| 332 | r#" | |
| 333 | GreenBg = Background { | |
| 334 | Inputs = { | |
| 335 | Width = Input { Value = 64, }, Height = Input { Value = 64, }, | |
| 336 | TopLeftRed = Input { Value = 0.08, }, TopLeftGreen = Input { Value = 0.72, }, TopLeftBlue = Input { Value = 0.14, }, | |
| 337 | }, | |
| 338 | }, | |
| 339 | CircleM = EllipseMask { | |
| 340 | Inputs = { | |
| 341 | MaskWidth = Input { Value = 64, }, MaskHeight = Input { Value = 64, }, | |
| 342 | Center = Input { Value = { 0.35, 0.65 }, }, Width = Input { Value = 0.35, }, Height = Input { Value = 0.35, }, | |
| 343 | }, | |
| 344 | }, | |
| 345 | OrangeSubject = Background { | |
| 346 | Inputs = { | |
| 347 | Width = Input { Value = 64, }, Height = Input { Value = 64, }, | |
| 348 | TopLeftRed = Input { Value = 0.95, }, TopLeftGreen = Input { Value = 0.45, }, TopLeftBlue = Input { Value = 0.05, }, | |
| 349 | EffectMask = Input { SourceOp = "CircleM", Source = "Mask", }, | |
| 350 | }, | |
| 351 | }, | |
| 352 | Plate = Merge { | |
| 353 | Inputs = { | |
| 354 | Background = Input { SourceOp = "GreenBg", Source = "Output", }, | |
| 355 | Foreground = Input { SourceOp = "OrangeSubject", Source = "Output", }, | |
| 356 | }, | |
| 357 | }, | |
| 358 | MagicMask1 = MagicMask { | |
| 359 | Inputs = { | |
| 360 | ReferenceTime = Input { Value = 2466, Disabled = true, }, | |
| 361 | UseLegacyMagicMask = Input { Value = 0, Disabled = true, }, | |
| 362 | Strokes = Input { SourceOp = "MagicMask1Strokes", Source = "Value", }, | |
| 363 | Input = Input { SourceOp = "Plate", Source = "Output", }, | |
| 364 | }, | |
| 365 | }, | |
| 366 | MagicMask1Strokes = BezierSpline { | |
| 367 | KeyFrames = { | |
| 368 | [2466] = { 0, Flags = { Linear = true, LockedY = true }, Value = MagicMaskStrokes { | |
| 369 | PosStrokes = { | |
| 370 | { 0.35, 0.65 }, | |
| 371 | { 0.38, 0.62 }, | |
| 372 | }, | |
| 373 | NegStrokes = { | |
| 374 | { 0.85, 0.20 }, | |
| 375 | } | |
| 376 | } } | |
| 377 | } | |
| 378 | }, | |
| 379 | EmptyMagicMask = MagicMask { | |
| 380 | Inputs = { | |
| 381 | Input = Input { SourceOp = "Plate", Source = "Output", }, | |
| 382 | }, | |
| 383 | }, | |
| 384 | "#, | |
| 385 | ); | |
| 386 | ||
| 387 | // Verify Fusion MagicMaskStrokes extraction (Y-up preserved accurately!) | |
| 388 | let mm1_node = comp.node(comp.find_node("MagicMask1").unwrap()); | |
| 389 | let params = extract_magic_mask_params(&comp, mm1_node, 2466.0, &eng.expr); | |
| 390 | assert!(params.is_magic_mask); | |
| 391 | assert_eq!(params.points.len(), 3); | |
| 392 | assert!(params.points[0].positive && (params.points[0].x - 0.35).abs() < 1e-5 && (params.points[0].y - 0.65).abs() < 1e-5); | |
| 393 | assert!(!params.points[2].positive && (params.points[2].x - 0.85).abs() < 1e-5 && (params.points[2].y - 0.20).abs() < 1e-5); | |
| 394 | ||
| 395 | // Evaluate MagicMask1 on GPU: Fusion Y-up (0.35, 0.65) -> GPU pixel (~22, ~22) is orange subject; | |
| 396 | // Fusion Y-up (0.85, 0.20) -> GPU pixel (~54, ~51) is green background! | |
| 397 | let (mm_tex, _) = eng.evaluate(&comp, comp.find_node("MagicMask1").unwrap(), 2466.0); | |
| 398 | let mm_buf = eng.readback_rgba(&mm_tex).unwrap(); | |
| 399 | let subj_px = px_u8(&mm_buf, 64, 22, 22); | |
| 400 | let bg_px = px_u8(&mm_buf, 64, 54, 51); | |
| 401 | assert!(subj_px[3] >= 240, "MagicMask positive stroke subject must be opaque: {subj_px:?}"); | |
| 402 | assert!(bg_px[3] <= 10, "MagicMask negative stroke background must be transparent: {bg_px:?}"); | |
| 403 | ||
| 404 | // Empty MagicMask (no strokes, no cached matte) MUST pass foreground through bit-for-bit (0.00% MAE) | |
| 405 | let (plate_tex, _) = eng.evaluate(&comp, comp.find_node("Plate").unwrap(), 0.0); | |
| 406 | let (empty_tex, _) = eng.evaluate(&comp, comp.find_node("EmptyMagicMask").unwrap(), 0.0); | |
| 407 | assert_eq!( | |
| 408 | eng.readback_rgba(&empty_tex).unwrap(), | |
| 409 | eng.readback_rgba(&plate_tex).unwrap(), | |
| 410 | "empty MagicMask must pass through input bit-exact with 0.00% MAE" | |
| 411 | ); | |
| 412 | ||
| 413 | // Now inject a cached neural matte into EmptyMagicMask for frame 0 -> must immediately override | |
| 414 | // passthrough and bust OutputCache automatically! | |
| 415 | let mut right_half = vec![0.0_f32; 64 * 64]; | |
| 416 | for y in 0..64 { | |
| 417 | for x in 32..64 { | |
| 418 | right_half[y * 64 + x] = 1.0; | |
| 419 | } | |
| 420 | } | |
| 421 | eng.auto_matte_cache.insert_alpha_f32("EmptyMagicMask", 0, [64, 64], right_half); | |
| 422 | let (injected_tex, _) = eng.evaluate(&comp, comp.find_node("EmptyMagicMask").unwrap(), 0.0); | |
| 423 | let inj_buf = eng.readback_rgba(&injected_tex).unwrap(); | |
| 424 | assert_eq!(px_u8(&inj_buf, 64, 8, 32)[3], 0, "cached matte left half must be transparent"); | |
| 425 | assert_eq!(px_u8(&inj_buf, 64, 56, 32)[3], 255, "cached matte right half must be opaque"); | |
| 426 | ||
| 427 | // Disk CacheDir PNG loading test (native only) | |
| 428 | #[cfg(not(target_arch = "wasm32"))] | |
| 429 | { | |
| 430 | let tmp_dir = std::env::temp_dir().join(format!("fission_automate_test_{}", std::process::id())); | |
| 431 | let _ = std::fs::remove_dir_all(&tmp_dir); | |
| 432 | std::fs::create_dir_all(&tmp_dir).unwrap(); | |
| 433 | let mut png_img = image::GrayImage::new(32, 32); | |
| 434 | for y in 0..32 { | |
| 435 | for x in 0..32 { | |
| 436 | png_img.put_pixel(x, y, image::Luma([if y < 16 { 255 } else { 0 }])); | |
| 437 | } | |
| 438 | } | |
| 439 | png_img.save(tmp_dir.join("0005.png")).unwrap(); | |
| 440 | ||
| 441 | let disk_comp = mk_comp(&format!( | |
| 442 | r#" | |
| 443 | Bg = Background {{ Inputs = {{ Width = Input {{ Value = 32, }}, Height = Input {{ Value = 32, }}, TopLeftRed = Input {{ Value = 1.0, }}, }}, }}, | |
| 444 | DiskAM = AutoMatte {{ | |
| 445 | Inputs = {{ | |
| 446 | Input = Input {{ SourceOp = "Bg", Source = "Output", }}, | |
| 447 | CacheDir = Input {{ Value = "{}", }}, | |
| 448 | OutputMode = Input {{ Value = 1, }}, | |
| 449 | }}, | |
| 450 | }}, | |
| 451 | "#, | |
| 452 | tmp_dir.to_string_lossy().replace('\\', "/") | |
| 453 | )); | |
| 454 | let (disk_tex, _) = eng.evaluate(&disk_comp, disk_comp.find_node("DiskAM").unwrap(), 5.0); | |
| 455 | let disk_buf = eng.readback_rgba(&disk_tex).unwrap(); | |
| 456 | assert_eq!(px_u8(&disk_buf, 32, 16, 4)[3], 255, "top half from 0005.png must be opaque"); | |
| 457 | assert_eq!(px_u8(&disk_buf, 32, 16, 28)[3], 0, "bottom half from 0005.png must be transparent"); | |
| 458 | let _ = std::fs::remove_dir_all(&tmp_dir); | |
| 459 | } | |
| 460 | } | |
| 461 | ||
| 462 | /// 5. MatteContractExpand + MatteBlur + EffectMask + Blend=0 verification. | |
| 463 | #[test] | |
| 464 | fn matte_contract_expand_blur_and_effect_mask() { | |
| 465 | let Ok(mut eng) = Engine::new_headless() else { return }; | |
| 466 | let comp = mk_comp( | |
| 467 | r#" | |
| 468 | Plate = Background { | |
| 469 | Inputs = { | |
| 470 | Width = Input { Value = 64, }, Height = Input { Value = 64, }, | |
| 471 | TopLeftRed = Input { Value = 0.9, }, TopLeftGreen = Input { Value = 0.5, }, TopLeftBlue = Input { Value = 0.2, }, | |
| 472 | }, | |
| 473 | }, | |
| 474 | AMExpand = AutoMatte { | |
| 475 | Inputs = { | |
| 476 | Input = Input { SourceOp = "Plate", Source = "Output", }, | |
| 477 | MatteContractExpand = Input { Value = 3.0, }, | |
| 478 | OutputMode = Input { Value = 1, }, | |
| 479 | }, | |
| 480 | }, | |
| 481 | AMContract = AutoMatte { | |
| 482 | Inputs = { | |
| 483 | Input = Input { SourceOp = "Plate", Source = "Output", }, | |
| 484 | MatteContractExpand = Input { Value = -3.0, }, | |
| 485 | OutputMode = Input { Value = 1, }, | |
| 486 | }, | |
| 487 | }, | |
| 488 | AMBlur = AutoMatte { | |
| 489 | Inputs = { | |
| 490 | Input = Input { SourceOp = "Plate", Source = "Output", }, | |
| 491 | MatteBlur = Input { Value = 2.5, }, | |
| 492 | OutputMode = Input { Value = 1, }, | |
| 493 | }, | |
| 494 | }, | |
| 495 | AMBlendZero = AutoMatte { | |
| 496 | Inputs = { | |
| 497 | Input = Input { SourceOp = "Plate", Source = "Output", }, | |
| 498 | Blend = Input { Value = 0.0, }, | |
| 499 | }, | |
| 500 | }, | |
| 501 | "#, | |
| 502 | ); | |
| 503 | ||
| 504 | let mut box_alpha = vec![0.0_f32; 64 * 64]; | |
| 505 | for y in 20..44 { | |
| 506 | for x in 20..44 { | |
| 507 | box_alpha[y * 64 + x] = 1.0; | |
| 508 | } | |
| 509 | } | |
| 510 | for name in ["AMExpand", "AMContract", "AMBlur", "AMBlendZero"] { | |
| 511 | eng.auto_matte_cache.insert_alpha_f32(name, 0, [64, 64], box_alpha.clone()); | |
| 512 | } | |
| 513 | ||
| 514 | let (exp_tex, _) = eng.evaluate(&comp, comp.find_node("AMExpand").unwrap(), 0.0); | |
| 515 | let exp_buf = eng.readback_rgba(&exp_tex).unwrap(); | |
| 516 | let (con_tex, _) = eng.evaluate(&comp, comp.find_node("AMContract").unwrap(), 0.0); | |
| 517 | let con_buf = eng.readback_rgba(&con_tex).unwrap(); | |
| 518 | ||
| 519 | let exp_count = exp_buf.chunks_exact(4).filter(|p| p[3] > 200).count(); | |
| 520 | let con_count = con_buf.chunks_exact(4).filter(|p| p[3] > 200).count(); | |
| 521 | assert!( | |
| 522 | exp_count > con_count + 400, | |
| 523 | "expanded matte ({exp_count}) must be substantially larger than contracted ({con_count})" | |
| 524 | ); | |
| 525 | ||
| 526 | let (blur_tex, _) = eng.evaluate(&comp, comp.find_node("AMBlur").unwrap(), 0.0); | |
| 527 | let blur_buf = eng.readback_rgba(&blur_tex).unwrap(); | |
| 528 | let edge_a = px_u8(&blur_buf, 64, 20, 32)[3]; | |
| 529 | assert!(edge_a > 40 && edge_a < 220, "MatteBlur must produce smooth edge alpha: {edge_a}"); | |
| 530 | ||
| 531 | let (plate_tex, _) = eng.evaluate(&comp, comp.find_node("Plate").unwrap(), 0.0); | |
| 532 | let (b0_tex, _) = eng.evaluate(&comp, comp.find_node("AMBlendZero").unwrap(), 0.0); | |
| 533 | assert_eq!( | |
| 534 | eng.readback_rgba(&b0_tex).unwrap(), | |
| 535 | eng.readback_rgba(&plate_tex).unwrap(), | |
| 536 | "Blend = 0 must pass input through untouched" | |
| 537 | ); | |
| 538 | } | |
| 539 | ||
| 540 | /// 6. EffectMask gating, proxy_scale=2 decontamination scaling, and native AutoMatteRunner validation. | |
| 541 | #[test] | |
| 542 | fn effect_mask_proxy_scale_and_runner_api() { | |
| 543 | let Ok(mut eng) = Engine::new_headless() else { return }; | |
| 544 | let comp = mk_comp( | |
| 545 | r#" | |
| 546 | Plate = Background { | |
| 547 | Inputs = { | |
| 548 | Width = Input { Value = 64, }, Height = Input { Value = 64, }, | |
| 549 | TopLeftRed = Input { Value = 0.80, }, TopLeftGreen = Input { Value = 0.30, }, TopLeftBlue = Input { Value = 0.20, }, | |
| 550 | }, | |
| 551 | }, | |
| 552 | LeftMask = RectangleMask { | |
| 553 | Inputs = { | |
| 554 | MaskWidth = Input { Value = 64, }, MaskHeight = Input { Value = 64, }, | |
| 555 | Center = Input { Value = { 0.25, 0.5 }, }, Width = Input { Value = 0.5, }, Height = Input { Value = 1.0, }, | |
| 556 | }, | |
| 557 | }, | |
| 558 | AMMasked = AutoMatte { | |
| 559 | Inputs = { | |
| 560 | Input = Input { SourceOp = "Plate", Source = "Output", }, | |
| 561 | EffectMask = Input { SourceOp = "LeftMask", Source = "Mask", }, | |
| 562 | }, | |
| 563 | }, | |
| 564 | "#, | |
| 565 | ); | |
| 566 | // All-zero cached matte: inside LeftMask (left half) becomes transparent, outside LeftMask (right half) | |
| 567 | // stays original Plate because EffectMask gates the AutoMatte effect! | |
| 568 | eng.auto_matte_cache | |
| 569 | .insert_alpha_f32("AMMasked", 0, [64, 64], vec![0.0_f32; 64 * 64]); | |
| 570 | ||
| 571 | let (tex, _) = eng.evaluate(&comp, comp.find_node("AMMasked").unwrap(), 0.0); | |
| 572 | let buf = eng.readback_rgba(&tex).unwrap(); | |
| 573 | assert_eq!(px_u8(&buf, 64, 8, 32)[3], 0, "inside EffectMask must apply zero alpha"); | |
| 574 | assert_eq!(px_u8(&buf, 64, 56, 32)[3], 255, "outside EffectMask must keep original Plate"); | |
| 575 | ||
| 576 | // Proxy scale = 2: full-res 64x64 cached matte resamples cleanly to 32x32 output | |
| 577 | eng.proxy_scale = 2; | |
| 578 | eng.auto_matte_cache | |
| 579 | .insert_alpha_f32("AMMasked", 1, [64, 64], vec![1.0_f32; 64 * 64]); | |
| 580 | let (proxy_tex, _) = eng.evaluate(&comp, comp.find_node("AMMasked").unwrap(), 1.0); | |
| 581 | assert_eq!(proxy_tex.size, [32, 32]); | |
| 582 | let pbuf = eng.readback_rgba(&proxy_tex).unwrap(); | |
| 583 | assert_eq!(px_u8(&pbuf, 32, 4, 16)[3], 255, "proxy_scale=2 resampled cached matte must stay opaque"); | |
| 584 | ||
| 585 | #[cfg(not(target_arch = "wasm32"))] | |
| 586 | { | |
| 587 | let runner = AutoMatteRunner::new( | |
| 588 | AutoMatteWorkerConfig { | |
| 589 | python_bin: std::path::PathBuf::from("/nonexistent/python"), | |
| 590 | worker_script: std::path::PathBuf::from("/nonexistent/worker.py"), | |
| 591 | output_dir: std::env::temp_dir(), | |
| 592 | }, | |
| 593 | eng.auto_matte_cache.clone(), | |
| 594 | ); | |
| 595 | let err = runner.spawn_job(AutoMatteJobRequest { | |
| 596 | node_name: "AMMasked".into(), | |
| 597 | input_path: std::path::PathBuf::from("/nonexistent/clip.mov"), | |
| 598 | frame_range: [0, 0], | |
| 599 | quality_tier: QualityTier::HeroHair, | |
| 600 | prompt_mode: PromptMode::ClickPoints, | |
| 601 | prompts: vec![PromptPoint::positive(0.5, 0.5)], | |
| 602 | }); | |
| 603 | assert!(err.is_err(), "missing worker binary must return clean Err without panicking"); | |
| 604 | } | |
| 605 | } | |
| 606 |
crates/engine/src/eval/mod.rs+114-2| ... | ... | @@ -82,6 +82,8 @@ pub struct Engine { |
| 82 | 82 | warps_masks_pipelines: OnceCell<RefCell<warps_masks::WarpsMasksPipelines>>, |
| 83 | 83 | fx_fuses_pipelines: OnceCell<RefCell<fx_fuses::FxFusesPipelines>>, |
| 84 | 84 | archive_fx2_pipelines: OnceCell<RefCell<archive_fx2::ArchiveFx2Pipelines>>, |
| 85 | auto_matte_pipelines: OnceCell<RefCell<crate::auto_matte::AutoMattePipelines>>, | |
| 86 | pub auto_matte_cache: crate::auto_matte::AutoMatteCache, | |
| 85 | 87 | motion_blur: crate::motion_blur::MotionBlurPipelines, |
| 86 | 88 | pub(crate) supports_f32_filter: bool, |
| 87 | 89 | scene3d: crate::scene3d::Scene3DRenderer, |
| ... | ... | @@ -195,6 +197,8 @@ impl Engine { |
| 195 | 197 | warps_masks_pipelines: OnceCell::new(), |
| 196 | 198 | fx_fuses_pipelines: OnceCell::new(), |
| 197 | 199 | archive_fx2_pipelines: OnceCell::new(), |
| 200 | auto_matte_pipelines: OnceCell::new(), | |
| 201 | auto_matte_cache: crate::auto_matte::AutoMatteCache::new(), | |
| 198 | 202 | motion_blur: crate::motion_blur::MotionBlurPipelines::default(), |
| 199 | 203 | supports_f32_filter, |
| 200 | 204 | scene3d, |
| ... | ... | @@ -356,6 +360,9 @@ impl Engine { |
| 356 | 360 | if let Some(fx2) = self.archive_fx2_pipelines.get() { |
| 357 | 361 | fx2.borrow_mut().reset_uniform_cursor(); |
| 358 | 362 | } |
| 363 | if let Some(am) = self.auto_matte_pipelines.get() { | |
| 364 | am.borrow_mut().reset_uniform_cursor(); | |
| 365 | } | |
| 359 | 366 | if let Some(of) = self.optflow.get() { |
| 360 | 367 | of.reset_uniform_cursor(); |
| 361 | 368 | } |
| ... | ... | @@ -385,6 +392,9 @@ impl Engine { |
| 385 | 392 | if let Some(fx2) = self.archive_fx2_pipelines.get() { |
| 386 | 393 | fx2.borrow_mut().trim_uniform_chunks(2); |
| 387 | 394 | } |
| 395 | if let Some(am) = self.auto_matte_pipelines.get() { | |
| 396 | am.borrow_mut().trim_uniform_chunks(2); | |
| 397 | } | |
| 388 | 398 | self.media.trim_nv12_uniform_chunks(2); |
| 389 | 399 | } |
| 390 | 400 | |
| ... | ... | @@ -490,7 +500,8 @@ impl Engine { |
| 490 | 500 | ) -> (CachedTexture, EvalStats) { |
| 491 | 501 | let t0 = Instant::now(); |
| 492 | 502 | self.sync_bg_cache_with_vram_drops(); |
| 493 | let out_key = self.output_cache_key(comp, target, time); | |
| 503 | let out_key = self.output_cache_key(comp, target, time) | |
| 504 | ^ self.auto_matte_cache.generation().wrapping_mul(0x9e37_79b9_7f4a_7c15); | |
| 494 | 505 | if let Some((tex, unsupported)) = self.output_cache_get(out_key) { |
| 495 | 506 | let stats = EvalStats { |
| 496 | 507 | eval_ms: t0.elapsed().as_secs_f64() * 1000.0, |
| ... | ... | @@ -546,7 +557,8 @@ impl Engine { |
| 546 | 557 | ) -> EvalStats { |
| 547 | 558 | let t0 = Instant::now(); |
| 548 | 559 | self.sync_bg_cache_with_vram_drops(); |
| 549 | let out_key = self.output_cache_key(comp, target, time); | |
| 560 | let out_key = self.output_cache_key(comp, target, time) | |
| 561 | ^ self.auto_matte_cache.generation().wrapping_mul(0x9e37_79b9_7f4a_7c15); | |
| 550 | 562 | let mut stats = EvalStats::default(); |
| 551 | 563 | let mut encoder = self.device.create_command_encoder(&wgpu::CommandEncoderDescriptor { |
| 552 | 564 | label: Some("comp-viewer-eval"), |
| ... | ... | @@ -1030,6 +1042,8 @@ impl Engine { |
| 1030 | 1042 | "Fuse.Outline" => self.eval_outline(comp, node, time, frame_i, enc, visiting, stats), |
| 1031 | 1043 | "Fuse.XfChroma" => self.eval_xf_chroma(comp, node, time, frame_i, enc, visiting, stats), |
| 1032 | 1044 | "Fuse.Cryptomatte" | "Cryptomatte" => self.eval_cryptomatte(comp, node, time, frame_i, enc, visiting, stats), |
| 1045 | "AutoMatte" => self.eval_auto_matte(comp, node, time, frame_i, false, enc, visiting, stats), | |
| 1046 | "MagicMask" => self.eval_auto_matte(comp, node, time, frame_i, true, enc, visiting, stats), | |
| 1033 | 1047 | "pRender" => self.eval_p_render(comp, node, time, frame_i, comp_dims, enc, visiting, stats), |
| 1034 | 1048 | "pEmitter" |
| 1035 | 1049 | | "pPointForce" |
| ... | ... | @@ -1703,6 +1717,104 @@ impl Engine { |
| 1703 | 1717 | dst |
| 1704 | 1718 | } |
| 1705 | 1719 | |
| 1720 | #[allow(clippy::too_many_arguments)] | |
| 1721 | fn eval_auto_matte( | |
| 1722 | &mut self, | |
| 1723 | comp: &Comp, | |
| 1724 | node: &Node, | |
| 1725 | time: f64, | |
| 1726 | frame_i: i64, | |
| 1727 | is_magic_mask: bool, | |
| 1728 | enc: &mut wgpu::CommandEncoder, | |
| 1729 | visiting: &mut HashSet<(NodeId, i64)>, | |
| 1730 | stats: &mut EvalStats, | |
| 1731 | ) -> CachedTexture { | |
| 1732 | let primary_src = node | |
| 1733 | .connected_node("Input") | |
| 1734 | .or_else(|| node.connected_node("Image")) | |
| 1735 | .or_else(|| node.connected_node("Source")) | |
| 1736 | .or_else(|| node.connected_node("Background")) | |
| 1737 | .and_then(|s| comp.find_node(s)); | |
| 1738 | let Some(src_id) = primary_src else { | |
| 1739 | return self.dummy.clone(); | |
| 1740 | }; | |
| 1741 | let src = self.eval_node(comp, src_id, time, enc, visiting, stats); | |
| 1742 | let params = if is_magic_mask { | |
| 1743 | crate::auto_matte::extract_magic_mask_params(comp, node, time, &self.expr) | |
| 1744 | } else { | |
| 1745 | crate::auto_matte::extract_auto_matte_params(comp, node, time, &self.expr) | |
| 1746 | }; | |
| 1747 | let mbm = self.multiplies_by_mask(comp, node, time); | |
| 1748 | if params.blend <= 1e-6 && !mbm { | |
| 1749 | return src; | |
| 1750 | } | |
| 1751 | let cached_matte = self.auto_matte_cache.get_or_load_frame( | |
| 1752 | &node.name, | |
| 1753 | frame_i, | |
| 1754 | params.cache_dir.as_deref(), | |
| 1755 | ); | |
| 1756 | // Empty MagicMask / AutoMatte (no strokes/points & no cached neural matte) passes through | |
| 1757 | // foreground cleanly with 0.00% MAE regression. | |
| 1758 | if cached_matte.is_none() && params.effective_gpu_seeds().is_empty() { | |
| 1759 | return src; | |
| 1760 | } | |
| 1761 | ||
| 1762 | let src = self.crop_to_canvas(enc, src); | |
| 1763 | let (mask, mask_inv) = | |
| 1764 | self.eval_mask_input_sized(comp, node, time, Some(src.size), enc, visiting, stats); | |
| 1765 | let mask_hash = mask.as_ref().map_or(0, |m| m.content_hash); | |
| 1766 | let matte_hash = cached_matte.as_ref().map_or(0, |m| m.content_hash); | |
| 1767 | let skip = self.process_skip(comp, node, time); | |
| 1768 | ||
| 1769 | let mut ph = DefaultHasher::new(); | |
| 1770 | params.hash_into(&mut ph); | |
| 1771 | self.proxy_scale.hash(&mut ph); | |
| 1772 | mask_inv.hash(&mut ph); | |
| 1773 | mbm.hash(&mut ph); | |
| 1774 | for s in skip { | |
| 1775 | s.to_bits().hash(&mut ph); | |
| 1776 | } | |
| 1777 | let param_hash = ph.finish(); | |
| 1778 | let key = self.make_key( | |
| 1779 | node, | |
| 1780 | if is_magic_mask { "MagicMask" } else { "AutoMatte" }, | |
| 1781 | src.size, | |
| 1782 | &[src.content_hash, mask_hash, matte_hash, param_hash], | |
| 1783 | &[], | |
| 1784 | ); | |
| 1785 | if let Some(hit) = self.cache.get(key, node.id, frame_i) { | |
| 1786 | stats.cache_hits += 1; | |
| 1787 | return hit; | |
| 1788 | } | |
| 1789 | stats.cache_misses += 1; | |
| 1790 | stats.nodes_evaluated += 1; | |
| 1791 | ||
| 1792 | let dst = self.alloc_tex(src.size, src.depth, key); | |
| 1793 | let mv = mask.as_ref().map_or(&self.dummy.view, |m| &m.view); | |
| 1794 | let pipelines = self | |
| 1795 | .auto_matte_pipelines | |
| 1796 | .get_or_init(|| RefCell::new(crate::auto_matte::AutoMattePipelines::new(&self.device))); | |
| 1797 | pipelines.borrow_mut().execute( | |
| 1798 | &self.device, | |
| 1799 | &self.queue, | |
| 1800 | enc, | |
| 1801 | &self.cache, | |
| 1802 | &self.dummy.view, | |
| 1803 | &src, | |
| 1804 | mv, | |
| 1805 | mask.is_some(), | |
| 1806 | mask_inv, | |
| 1807 | mbm, | |
| 1808 | skip, | |
| 1809 | &dst, | |
| 1810 | &params, | |
| 1811 | cached_matte.as_deref(), | |
| 1812 | self.proxy_scale, | |
| 1813 | ); | |
| 1814 | self.cache.insert(key, dst.clone(), node.id, frame_i); | |
| 1815 | dst | |
| 1816 | } | |
| 1817 | ||
| 1706 | 1818 | fn make_key(&self, node: &Node, tag: &str, size: [u32; 2], upstream: &[u64], params: &[f32]) -> u64 { |
| 1707 | 1819 | let mut h = DefaultHasher::new(); |
| 1708 | 1820 | self.cache.gpu_salt.hash(&mut h); |
crates/engine/src/lib.rs+1| ... | ... | @@ -1,5 +1,6 @@ |
| 1 | 1 | #[cfg(not(target_arch = "wasm32"))] |
| 2 | 2 | pub mod audio; |
| 3 | pub mod auto_matte; | |
| 3 | 4 | pub mod cache; |
| 4 | 5 | pub mod cryptomatte; |
| 5 | 6 | pub mod custom_shader; |
crates/engine/src/shaders/auto_matte.wgsl created+494| ... | ... | @@ -0,0 +1,494 @@ |
| 1 | // AutoMatte & Diverging MagicMask GPU compute shaders: | |
| 2 | // - Stage 2 GPU fallback: `seed_segment_op` (multi-seed perceptual Oklab color+spatial affinity) | |
| 3 | // + `bilateral_refine_op` (joint-bilateral edge-aware alpha refinement). | |
| 4 | // - Stage 3 Alpha Polish: `polish_alpha_op` (exact port of Clover's floor/ceiling/toe polish), | |
| 5 | // `morpho_h_op` / `morpho_v_op` (MatteContractExpand), `gauss_blur_h_op` / `gauss_blur_v_op`. | |
| 6 | // - Stage 3 Hair-Safe Foreground Decontamination: `decontam_init_op` + 3-scale separable | |
| 7 | // normalized-convolution Gaussian pyramid (`sigma = 28, 12, 4` scaled by proxy_scale) + | |
| 8 | // `decontam_merge_scale_op` + `composite_output_op`. | |
| 9 | // | |
| 10 | // WebGPU-safe (`wasm32` compatible): | |
| 11 | // - All input textures bound with `filterable: false`, read exclusively via `textureLoad`. | |
| 12 | // - Output storage texture is WriteOnly (patched at pipeline compile time for rgba16float/rgba32float). | |
| 13 | // - Growable 512-slot dynamic uniform ring buffer. | |
| 14 | ||
| 15 | @group(0) @binding(0) var src_a: texture_2d<f32>; | |
| 16 | @group(0) @binding(1) var src_b: texture_2d<f32>; | |
| 17 | @group(0) @binding(2) var src_c: texture_2d<f32>; | |
| 18 | @group(0) @binding(3) var mask_tex: texture_2d<f32>; | |
| 19 | @group(0) @binding(4) var dst_tex: texture_storage_2d<rgba8unorm, write>; | |
| 20 | ||
| 21 | const HDR_FLOAT: bool = false; | |
| 22 | const MAX_SEEDS: u32 = 32u; | |
| 23 | ||
| 24 | struct AutoMatteUniform { | |
| 25 | p: array<vec4<f32>, 8>, | |
| 26 | // Each seed: (uv_x, uv_y [top-down 0..1], label [+1.0 pos / -1.0 neg], weight) | |
| 27 | seeds: array<vec4<f32>, 32>, | |
| 28 | }; | |
| 29 | @group(0) @binding(5) var<uniform> u: AutoMatteUniform; | |
| 30 | ||
| 31 | fn store_dst(p: vec2<i32>, col: vec4<f32>) { | |
| 32 | if (HDR_FLOAT) { | |
| 33 | textureStore(dst_tex, p, col); | |
| 34 | } else { | |
| 35 | textureStore(dst_tex, p, clamp(col, vec4<f32>(0.0), vec4<f32>(1.0))); | |
| 36 | } | |
| 37 | } | |
| 38 | ||
| 39 | fn load_clamped(tex: texture_2d<f32>, p: vec2<i32>) -> vec4<f32> { | |
| 40 | let dims = vec2<i32>(textureDimensions(tex)); | |
| 41 | let c = clamp(p, vec2<i32>(0), max(dims - vec2<i32>(1), vec2<i32>(0))); | |
| 42 | return textureLoad(tex, c, 0); | |
| 43 | } | |
| 44 | ||
| 45 | fn sample_bilinear(tex: texture_2d<f32>, uv: vec2<f32>) -> vec4<f32> { | |
| 46 | let dims = vec2<i32>(textureDimensions(tex)); | |
| 47 | let max_c = max(dims - vec2<i32>(1), vec2<i32>(0)); | |
| 48 | let f = clamp(uv, vec2<f32>(0.0), vec2<f32>(1.0)) * vec2<f32>(dims) - vec2<f32>(0.5); | |
| 49 | let fl = floor(f); | |
| 50 | let i0 = clamp(vec2<i32>(fl), vec2<i32>(0), max_c); | |
| 51 | let i1 = clamp(i0 + vec2<i32>(1), vec2<i32>(0), max_c); | |
| 52 | let t = clamp(f - fl, vec2<f32>(0.0), vec2<f32>(1.0)); | |
| 53 | let c00 = textureLoad(tex, i0, 0); | |
| 54 | let c10 = textureLoad(tex, vec2<i32>(i1.x, i0.y), 0); | |
| 55 | let c01 = textureLoad(tex, vec2<i32>(i0.x, i1.y), 0); | |
| 56 | let c11 = textureLoad(tex, i1, 0); | |
| 57 | return mix(mix(c00, c10, t.x), mix(c01, c11, t.x), t.y); | |
| 58 | } | |
| 59 | ||
| 60 | fn cbrt_safe(x: f32) -> f32 { | |
| 61 | return sign(x) * pow(abs(x), 1.0 / 3.0); | |
| 62 | } | |
| 63 | ||
| 64 | // Perceptual Oklab color transform (from linear-ish RGB clamped >= 0). | |
| 65 | fn rgb_to_oklab(rgb_in: vec3<f32>) -> vec3<f32> { | |
| 66 | let rgb = max(rgb_in, vec3<f32>(0.0)); | |
| 67 | let l = 0.4122214708 * rgb.r + 0.5363325363 * rgb.g + 0.0514459929 * rgb.b; | |
| 68 | let m = 0.2119034982 * rgb.r + 0.6806995451 * rgb.g + 0.1073969566 * rgb.b; | |
| 69 | let s = 0.0883024619 * rgb.r + 0.2817188376 * rgb.g + 0.6299787005 * rgb.b; | |
| 70 | let l_ = cbrt_safe(l); | |
| 71 | let m_ = cbrt_safe(m); | |
| 72 | let s_ = cbrt_safe(s); | |
| 73 | return vec3<f32>( | |
| 74 | 0.2104542553 * l_ + 0.7936177850 * m_ - 0.0040720468 * s_, | |
| 75 | 1.9779984951 * l_ - 2.4285922050 * m_ + 0.4505937099 * s_, | |
| 76 | 0.0259040371 * l_ + 0.7827717662 * m_ - 0.8086757660 * s_, | |
| 77 | ); | |
| 78 | } | |
| 79 | ||
| 80 | fn sample_seed_oklab(uv: vec2<f32>, dims: vec2<i32>) -> vec3<f32> { | |
| 81 | let px = vec2<i32>(clamp(uv, vec2<f32>(0.0), vec2<f32>(1.0)) * vec2<f32>(dims)); | |
| 82 | let c0 = load_clamped(src_a, px).rgb; | |
| 83 | let c1 = load_clamped(src_a, px + vec2<i32>(1, 0)).rgb; | |
| 84 | let c2 = load_clamped(src_a, px + vec2<i32>(-1, 0)).rgb; | |
| 85 | let c3 = load_clamped(src_a, px + vec2<i32>(0, 1)).rgb; | |
| 86 | let c4 = load_clamped(src_a, px + vec2<i32>(0, -1)).rgb; | |
| 87 | let avg = (c0 * 2.0 + c1 + c2 + c3 + c4) / 6.0; | |
| 88 | return rgb_to_oklab(avg); | |
| 89 | } | |
| 90 | ||
| 91 | fn read_mask(gid: vec2<u32>, dims: vec2<u32>, has_mask: f32, invert: f32) -> f32 { | |
| 92 | if (has_mask < 0.5) { | |
| 93 | return 1.0; | |
| 94 | } | |
| 95 | let uv = (vec2<f32>(gid) + 0.5) / vec2<f32>(dims); | |
| 96 | let m = sample_bilinear(mask_tex, uv).a; | |
| 97 | return select(m, 1.0 - m, invert > 0.5); | |
| 98 | } | |
| 99 | ||
| 100 | // ----------------------------------------------------------------------------- | |
| 101 | // Stage 2A: Multi-seed perceptual color + spatial affinity segmentation | |
| 102 | // ----------------------------------------------------------------------------- | |
| 103 | @compute @workgroup_size(8, 8) | |
| 104 | fn seed_segment_op(@builtin(global_invocation_id) gid: vec3<u32>) { | |
| 105 | let dims_u = textureDimensions(dst_tex); | |
| 106 | if (gid.x >= dims_u.x || gid.y >= dims_u.y) { | |
| 107 | return; | |
| 108 | } | |
| 109 | let dims = vec2<i32>(dims_u); | |
| 110 | let p = vec2<i32>(gid.xy); | |
| 111 | let uv = (vec2<f32>(gid.xy) + 0.5) / vec2<f32>(dims_u); | |
| 112 | ||
| 113 | let num_seeds = min(u32(u.p[0].x + 0.5), MAX_SEEDS); | |
| 114 | let num_neg = u32(u.p[0].y + 0.5); | |
| 115 | let sigma_c = max(u.p[0].z, 0.02); | |
| 116 | let sigma_s_pos = max(u.p[0].w, 0.05); | |
| 117 | let sigma_s_neg = max(u.p[1].x, 0.05); | |
| 118 | let use_auto_bg = u.p[1].y > 0.5; | |
| 119 | let aspect = max(u.p[1].z, 0.1); | |
| 120 | ||
| 121 | let inv_sc2 = 1.0 / (sigma_c * sigma_c); | |
| 122 | let inv_sp2 = 1.0 / (sigma_s_pos * sigma_s_pos); | |
| 123 | let inv_sn2 = 1.0 / (sigma_s_neg * sigma_s_neg); | |
| 124 | ||
| 125 | let px_lab = rgb_to_oklab(load_clamped(src_a, p).rgb); | |
| 126 | ||
| 127 | // Pass 1: find minimum energy across positive and negative seeds for numerical stability | |
| 128 | var min_e_pos = 1e20; | |
| 129 | var min_e_neg = 1e20; | |
| 130 | var min_dspa_pos = 1e20; | |
| 131 | var pos_count = 0u; | |
| 132 | var neg_count = 0u; | |
| 133 | ||
| 134 | for (var i = 0u; i < num_seeds; i = i + 1u) { | |
| 135 | let s = u.seeds[i]; | |
| 136 | let s_lab = sample_seed_oklab(s.xy, dims); | |
| 137 | let d_col = length(px_lab - s_lab); | |
| 138 | let d_uv = (uv - s.xy) * vec2<f32>(aspect, 1.0); | |
| 139 | let d_spa = length(d_uv); | |
| 140 | if (s.z >= 0.0) { | |
| 141 | let e = d_col * d_col * inv_sc2 + d_spa * d_spa * inv_sp2; | |
| 142 | min_e_pos = min(min_e_pos, e); | |
| 143 | min_dspa_pos = min(min_dspa_pos, d_spa); | |
| 144 | pos_count = pos_count + 1u; | |
| 145 | } else { | |
| 146 | let e = d_col * d_col * inv_sc2 + d_spa * d_spa * inv_sn2; | |
| 147 | min_e_neg = min(min_e_neg, e); | |
| 148 | neg_count = neg_count + 1u; | |
| 149 | } | |
| 150 | } | |
| 151 | ||
| 152 | // Automatic border background seeds when only positive seeds were supplied | |
| 153 | var auto_bg_pts = array<vec2<f32>, 8>( | |
| 154 | vec2<f32>(0.02, 0.02), | |
| 155 | vec2<f32>(0.98, 0.02), | |
| 156 | vec2<f32>(0.02, 0.98), | |
| 157 | vec2<f32>(0.98, 0.98), | |
| 158 | vec2<f32>(0.50, 0.02), | |
| 159 | vec2<f32>(0.50, 0.98), | |
| 160 | vec2<f32>(0.02, 0.50), | |
| 161 | vec2<f32>(0.98, 0.50), | |
| 162 | ); | |
| 163 | var auto_bg_valid = array<f32, 8>(0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0); | |
| 164 | var auto_bg_energy = array<f32, 8>(1e20, 1e20, 1e20, 1e20, 1e20, 1e20, 1e20, 1e20); | |
| 165 | ||
| 166 | if (num_neg == 0u && use_auto_bg && pos_count > 0u) { | |
| 167 | for (var b = 0u; b < 8u; b = b + 1u) { | |
| 168 | let bp = auto_bg_pts[b]; | |
| 169 | let b_lab = sample_seed_oklab(bp, dims); | |
| 170 | // Skip border sample if it is close spatially or in color to any positive seed | |
| 171 | var ok = true; | |
| 172 | for (var i = 0u; i < num_seeds; i = i + 1u) { | |
| 173 | let s = u.seeds[i]; | |
| 174 | if (s.z >= 0.0) { | |
| 175 | let s_dist = length((bp - s.xy) * vec2<f32>(aspect, 1.0)); | |
| 176 | let s_lab = sample_seed_oklab(s.xy, dims); | |
| 177 | let c_dist = length(b_lab - s_lab); | |
| 178 | if (s_dist < 0.10 || c_dist < 0.06) { | |
| 179 | ok = false; | |
| 180 | } | |
| 181 | } | |
| 182 | } | |
| 183 | if (ok) { | |
| 184 | let d_col = length(px_lab - b_lab); | |
| 185 | let d_uv = (uv - bp) * vec2<f32>(aspect, 1.0); | |
| 186 | let d_spa = length(d_uv); | |
| 187 | let e = d_col * d_col * inv_sc2 + d_spa * d_spa * inv_sn2; | |
| 188 | auto_bg_valid[b] = 1.0; | |
| 189 | auto_bg_energy[b] = e; | |
| 190 | min_e_neg = min(min_e_neg, e); | |
| 191 | neg_count = neg_count + 1u; | |
| 192 | } | |
| 193 | } | |
| 194 | } | |
| 195 | ||
| 196 | var prob = 0.0; | |
| 197 | if (pos_count == 0u) { | |
| 198 | prob = 0.0; | |
| 199 | } else if (neg_count == 0u) { | |
| 200 | // Uniform-color fallback: smooth spatial falloff around positive seeds | |
| 201 | prob = exp(-(min_dspa_pos * min_dspa_pos) / (0.35 * 0.35)); | |
| 202 | } else { | |
| 203 | let m = min(min_e_pos, min_e_neg); | |
| 204 | var sum_pos = 0.0; | |
| 205 | var sum_neg = 0.0; | |
| 206 | for (var i = 0u; i < num_seeds; i = i + 1u) { | |
| 207 | let s = u.seeds[i]; | |
| 208 | let w = max(s.w, 0.01); | |
| 209 | let s_lab = sample_seed_oklab(s.xy, dims); | |
| 210 | let d_col = length(px_lab - s_lab); | |
| 211 | let d_uv = (uv - s.xy) * vec2<f32>(aspect, 1.0); | |
| 212 | let d_spa = length(d_uv); | |
| 213 | if (s.z >= 0.0) { | |
| 214 | let e = d_col * d_col * inv_sc2 + d_spa * d_spa * inv_sp2; | |
| 215 | sum_pos = sum_pos + w * exp(-min(e - m, 60.0)); | |
| 216 | } else { | |
| 217 | let e = d_col * d_col * inv_sc2 + d_spa * d_spa * inv_sn2; | |
| 218 | sum_neg = sum_neg + w * exp(-min(e - m, 60.0)); | |
| 219 | } | |
| 220 | } | |
| 221 | if (num_neg == 0u && use_auto_bg) { | |
| 222 | for (var b = 0u; b < 8u; b = b + 1u) { | |
| 223 | if (auto_bg_valid[b] > 0.5) { | |
| 224 | sum_neg = sum_neg + 0.65 * exp(-min(auto_bg_energy[b] - m, 60.0)); | |
| 225 | } | |
| 226 | } | |
| 227 | } | |
| 228 | prob = sum_pos / max(sum_pos + sum_neg, 1e-6); | |
| 229 | } | |
| 230 | ||
| 231 | store_dst(p, vec4<f32>(prob, prob, prob, prob)); | |
| 232 | } | |
| 233 | ||
| 234 | // ----------------------------------------------------------------------------- | |
| 235 | // Stage 2B: Joint-bilateral edge-aware alpha refinement | |
| 236 | // ----------------------------------------------------------------------------- | |
| 237 | @compute @workgroup_size(8, 8) | |
| 238 | fn bilateral_refine_op(@builtin(global_invocation_id) gid: vec3<u32>) { | |
| 239 | let dims_u = textureDimensions(dst_tex); | |
| 240 | if (gid.x >= dims_u.x || gid.y >= dims_u.y) { | |
| 241 | return; | |
| 242 | } | |
| 243 | let p = vec2<i32>(gid.xy); | |
| 244 | let radius = clamp(i32(u.p[0].x + 0.5), 1, 6); | |
| 245 | let sigma_s = max(u.p[0].y, 0.5); | |
| 246 | let sigma_r = max(u.p[0].z, 0.01); | |
| 247 | let stride = clamp(i32(u.p[0].w + 0.5), 1, 4); | |
| 248 | ||
| 249 | let inv_2s2 = 0.5 / (sigma_s * sigma_s); | |
| 250 | let inv_2r2 = 0.5 / (sigma_r * sigma_r); | |
| 251 | ||
| 252 | let center_lab = rgb_to_oklab(load_clamped(src_a, p).rgb); | |
| 253 | var acc_a = 0.0; | |
| 254 | var acc_w = 0.0; | |
| 255 | ||
| 256 | for (var dy = -radius; dy <= radius; dy = dy + 1) { | |
| 257 | for (var dx = -radius; dx <= radius; dx = dx + 1) { | |
| 258 | let off = vec2<i32>(dx * stride, dy * stride); | |
| 259 | let q = p + off; | |
| 260 | let dist2 = f32(off.x * off.x + off.y * off.y); | |
| 261 | let q_lab = rgb_to_oklab(load_clamped(src_a, q).rgb); | |
| 262 | let dc = q_lab - center_lab; | |
| 263 | let dc2 = dot(dc, dc); | |
| 264 | let w = exp(-dist2 * inv_2s2 - dc2 * inv_2r2); | |
| 265 | let qa = load_clamped(src_b, q).r; | |
| 266 | acc_a = acc_a + w * qa; | |
| 267 | acc_w = acc_w + w; | |
| 268 | } | |
| 269 | } | |
| 270 | ||
| 271 | let refined = clamp(acc_a / max(acc_w, 1e-6), 0.0, 1.0); | |
| 272 | store_dst(p, vec4<f32>(refined, refined, refined, refined)); | |
| 273 | } | |
| 274 | ||
| 275 | // ----------------------------------------------------------------------------- | |
| 276 | // Stage 3A: Clover's exact `polish_alpha` (floor, ceiling, toe gamma, invert) | |
| 277 | // ----------------------------------------------------------------------------- | |
| 278 | @compute @workgroup_size(8, 8) | |
| 279 | fn polish_alpha_op(@builtin(global_invocation_id) gid: vec3<u32>) { | |
| 280 | let dims_u = textureDimensions(dst_tex); | |
| 281 | if (gid.x >= dims_u.x || gid.y >= dims_u.y) { | |
| 282 | return; | |
| 283 | } | |
| 284 | let p = vec2<i32>(gid.xy); | |
| 285 | let uv = (vec2<f32>(gid.xy) + 0.5) / vec2<f32>(dims_u); | |
| 286 | ||
| 287 | let lo = u.p[0].x; | |
| 288 | let hi = u.p[0].y; | |
| 289 | let toe_gamma = max(u.p[0].z, 0.01); | |
| 290 | let invert = u.p[0].w > 0.5; | |
| 291 | ||
| 292 | let raw_a = sample_bilinear(src_a, uv).r; | |
| 293 | let denom = max(hi - lo, 1e-4); | |
| 294 | var a = clamp((raw_a - lo) / denom, 0.0, 1.0); | |
| 295 | ||
| 296 | // Toe compression below 0.15 kills faint outer VAE haze while keeping wisps >= 0.15 crisp | |
| 297 | if (a < 0.15 && abs(toe_gamma - 1.0) > 1e-5) { | |
| 298 | a = pow(max(a / 0.15, 0.0), toe_gamma) * 0.15; | |
| 299 | } | |
| 300 | if (invert) { | |
| 301 | a = 1.0 - a; | |
| 302 | } | |
| 303 | ||
| 304 | store_dst(p, vec4<f32>(a, a, a, a)); | |
| 305 | } | |
| 306 | ||
| 307 | // ----------------------------------------------------------------------------- | |
| 308 | // Stage 3B: Separable morphological erode / dilate for `MatteContractExpand` | |
| 309 | // ----------------------------------------------------------------------------- | |
| 310 | fn morpho_1d(p: vec2<i32>, dir: vec2<i32>, signed_radius: f32) -> f32 { | |
| 311 | let abs_r = min(abs(signed_radius), 64.0); | |
| 312 | let r_int = i32(floor(abs_r)); | |
| 313 | let frac = abs_r - f32(r_int); | |
| 314 | let dilate = signed_radius > 0.0; | |
| 315 | ||
| 316 | var acc = load_clamped(src_a, p).r; | |
| 317 | for (var i = 1; i <= r_int; i = i + 1) { | |
| 318 | let a_pos = load_clamped(src_a, p + dir * i).r; | |
| 319 | let a_neg = load_clamped(src_a, p - dir * i).r; | |
| 320 | if (dilate) { | |
| 321 | acc = max(acc, max(a_pos, a_neg)); | |
| 322 | } else { | |
| 323 | acc = min(acc, min(a_pos, a_neg)); | |
| 324 | } | |
| 325 | } | |
| 326 | if (frac > 1e-4) { | |
| 327 | let edge_i = r_int + 1; | |
| 328 | let a_pos = load_clamped(src_a, p + dir * edge_i).r; | |
| 329 | let a_neg = load_clamped(src_a, p - dir * edge_i).r; | |
| 330 | let edge_v = select(min(acc, min(a_pos, a_neg)), max(acc, max(a_pos, a_neg)), dilate); | |
| 331 | acc = mix(acc, edge_v, frac); | |
| 332 | } | |
| 333 | return clamp(acc, 0.0, 1.0); | |
| 334 | } | |
| 335 | ||
| 336 | @compute @workgroup_size(8, 8) | |
| 337 | fn morpho_h_op(@builtin(global_invocation_id) gid: vec3<u32>) { | |
| 338 | let dims_u = textureDimensions(dst_tex); | |
| 339 | if (gid.x >= dims_u.x || gid.y >= dims_u.y) { | |
| 340 | return; | |
| 341 | } | |
| 342 | let p = vec2<i32>(gid.xy); | |
| 343 | let a = morpho_1d(p, vec2<i32>(1, 0), u.p[0].x); | |
| 344 | store_dst(p, vec4<f32>(a, a, a, a)); | |
| 345 | } | |
| 346 | ||
| 347 | @compute @workgroup_size(8, 8) | |
| 348 | fn morpho_v_op(@builtin(global_invocation_id) gid: vec3<u32>) { | |
| 349 | let dims_u = textureDimensions(dst_tex); | |
| 350 | if (gid.x >= dims_u.x || gid.y >= dims_u.y) { | |
| 351 | return; | |
| 352 | } | |
| 353 | let p = vec2<i32>(gid.xy); | |
| 354 | let a = morpho_1d(p, vec2<i32>(0, 1), u.p[0].x); | |
| 355 | store_dst(p, vec4<f32>(a, a, a, a)); | |
| 356 | } | |
| 357 | ||
| 358 | // ----------------------------------------------------------------------------- | |
| 359 | // Stage 3C: Separable Gaussian blur (used by MatteBlur & 3-scale decontamination) | |
| 360 | // ----------------------------------------------------------------------------- | |
| 361 | fn gauss_blur_1d(p: vec2<i32>, dir: vec2<i32>, sigma: f32, max_r: i32) -> vec4<f32> { | |
| 362 | if (sigma < 0.05 || max_r <= 0) { | |
| 363 | return load_clamped(src_a, p); | |
| 364 | } | |
| 365 | let inv_2s2 = 0.5 / (sigma * sigma); | |
| 366 | var sum = load_clamped(src_a, p); | |
| 367 | var sum_w = 1.0; | |
| 368 | ||
| 369 | for (var i = 1; i <= max_r; i = i + 1) { | |
| 370 | let fi = f32(i); | |
| 371 | let w = exp(-fi * fi * inv_2s2); | |
| 372 | let c_pos = load_clamped(src_a, p + dir * i); | |
| 373 | let c_neg = load_clamped(src_a, p - dir * i); | |
| 374 | sum = sum + (c_pos + c_neg) * w; | |
| 375 | sum_w = sum_w + 2.0 * w; | |
| 376 | } | |
| 377 | return sum / sum_w; | |
| 378 | } | |
| 379 | ||
| 380 | @compute @workgroup_size(8, 8) | |
| 381 | fn gauss_blur_h_op(@builtin(global_invocation_id) gid: vec3<u32>) { | |
| 382 | let dims_u = textureDimensions(dst_tex); | |
| 383 | if (gid.x >= dims_u.x || gid.y >= dims_u.y) { | |
| 384 | return; | |
| 385 | } | |
| 386 | let p = vec2<i32>(gid.xy); | |
| 387 | let sigma = max(u.p[0].x, 0.0); | |
| 388 | let max_r = clamp(i32(u.p[0].y + 0.5), 0, 76); | |
| 389 | store_dst(p, gauss_blur_1d(p, vec2<i32>(1, 0), sigma, max_r)); | |
| 390 | } | |
| 391 | ||
| 392 | @compute @workgroup_size(8, 8) | |
| 393 | fn gauss_blur_v_op(@builtin(global_invocation_id) gid: vec3<u32>) { | |
| 394 | let dims_u = textureDimensions(dst_tex); | |
| 395 | if (gid.x >= dims_u.x || gid.y >= dims_u.y) { | |
| 396 | return; | |
| 397 | } | |
| 398 | let p = vec2<i32>(gid.xy); | |
| 399 | let sigma = max(u.p[0].x, 0.0); | |
| 400 | let max_r = clamp(i32(u.p[0].y + 0.5), 0, 76); | |
| 401 | store_dst(p, gauss_blur_1d(p, vec2<i32>(0, 1), sigma, max_r)); | |
| 402 | } | |
| 403 | ||
| 404 | // ----------------------------------------------------------------------------- | |
| 405 | // Stage 3D: Clover's hair-safe normalized-convolution decontamination | |
| 406 | // ----------------------------------------------------------------------------- | |
| 407 | @compute @workgroup_size(8, 8) | |
| 408 | fn decontam_init_op(@builtin(global_invocation_id) gid: vec3<u32>) { | |
| 409 | let dims_u = textureDimensions(dst_tex); | |
| 410 | if (gid.x >= dims_u.x || gid.y >= dims_u.y) { | |
| 411 | return; | |
| 412 | } | |
| 413 | let p = vec2<i32>(gid.xy); | |
| 414 | let orig = load_clamped(src_a, p); | |
| 415 | let a = load_clamped(src_b, p).r; | |
| 416 | // Pure solid interior weight: solid_w = clamp((alpha - 0.82) / 0.14, 0, 1) | |
| 417 | let solid_w = clamp((a - 0.82) / 0.14, 0.0, 1.0); | |
| 418 | store_dst(p, vec4<f32>(orig.rgb * solid_w, solid_w)); | |
| 419 | } | |
| 420 | ||
| 421 | @compute @workgroup_size(8, 8) | |
| 422 | fn decontam_merge_scale_op(@builtin(global_invocation_id) gid: vec3<u32>) { | |
| 423 | let dims_u = textureDimensions(dst_tex); | |
| 424 | if (gid.x >= dims_u.x || gid.y >= dims_u.y) { | |
| 425 | return; | |
| 426 | } | |
| 427 | let p = vec2<i32>(gid.xy); | |
| 428 | let prev = load_clamped(src_a, p); | |
| 429 | let nd = load_clamped(src_b, p); | |
| 430 | let den = nd.a; | |
| 431 | var out_rgb = prev.rgb; | |
| 432 | if (den > 1e-4) { | |
| 433 | let filled = nd.rgb / max(den, 1e-4); | |
| 434 | let blend_scale = clamp(den * 4.0, 0.0, 1.0); | |
| 435 | out_rgb = mix(prev.rgb, filled, blend_scale); | |
| 436 | } | |
| 437 | store_dst(p, vec4<f32>(out_rgb, 1.0)); | |
| 438 | } | |
| 439 | ||
| 440 | // ----------------------------------------------------------------------------- | |
| 441 | // Stage 3E: Final hair-safe foreground blend, output mode & EffectMask composite | |
| 442 | // ----------------------------------------------------------------------------- | |
| 443 | @compute @workgroup_size(8, 8) | |
| 444 | fn composite_output_op(@builtin(global_invocation_id) gid: vec3<u32>) { | |
| 445 | let dims_u = textureDimensions(dst_tex); | |
| 446 | if (gid.x >= dims_u.x || gid.y >= dims_u.y) { | |
| 447 | return; | |
| 448 | } | |
| 449 | let p = vec2<i32>(gid.xy); | |
| 450 | let orig = load_clamped(src_a, p); | |
| 451 | let a = clamp(load_clamped(src_b, p).r, 0.0, 1.0); | |
| 452 | let f_extrap = load_clamped(src_c, p).rgb; | |
| 453 | ||
| 454 | let decontam_strength = clamp(u.p[0].x, 0.0, 1.0); | |
| 455 | let output_mode = i32(u.p[0].y + 0.5); | |
| 456 | let blend = clamp(u.p[0].z, 0.0, 1.0); | |
| 457 | let has_mask = u.p[0].w; | |
| 458 | let mask_inv = u.p[1].x; | |
| 459 | let mbm = u.p[1].y; | |
| 460 | let skip = u.p[2]; | |
| 461 | ||
| 462 | // Blend clean extrapolated hair color into low-alpha strands (alpha < 0.85) | |
| 463 | // while keeping 100% original pixels bit-exact in solid interior (alpha >= 0.94) | |
| 464 | let w_orig = clamp((a - 0.85) / 0.09, 0.0, 1.0); | |
| 465 | let f_decontam = mix(f_extrap, orig.rgb, w_orig); | |
| 466 | let fg_rgb = mix(orig.rgb, f_decontam, decontam_strength); | |
| 467 | ||
| 468 | var effect = vec4<f32>(0.0); | |
| 469 | if (output_mode == 1) { | |
| 470 | // Matte / Alpha Only | |
| 471 | effect = vec4<f32>(a, a, a, a); | |
| 472 | } else if (output_mode == 2) { | |
| 473 | // Overlay Preview (ruby-magenta translucent mask over footage) | |
| 474 | let overlay_col = vec3<f32>(1.0, 0.15, 0.28); | |
| 475 | effect = vec4<f32>(mix(orig.rgb, overlay_col, a * 0.45), 1.0); | |
| 476 | } else { | |
| 477 | // Premultiplied Cutout | |
| 478 | effect = vec4<f32>(fg_rgb * a, a); | |
| 479 | } | |
| 480 | ||
| 481 | let mask_v = read_mask(gid.xy, dims_u, has_mask, mask_inv); | |
| 482 | let eff = clamp(blend * mask_v, 0.0, 1.0); | |
| 483 | var out_c = mix(orig, effect, eff); | |
| 484 | if (mbm > 0.5) { | |
| 485 | out_c = out_c * mask_v; | |
| 486 | } | |
| 487 | let final_c = vec4<f32>( | |
| 488 | select(out_c.r, orig.r, skip.x > 0.5), | |
| 489 | select(out_c.g, orig.g, skip.y > 0.5), | |
| 490 | select(out_c.b, orig.b, skip.z > 0.5), | |
| 491 | select(out_c.a, orig.a, skip.w > 0.5), | |
| 492 | ); | |
| 493 | store_dst(p, final_c); | |
| 494 | } |