| author | |
| committer | |
| log | 34ea37f66436efdb2c3afa20c7b79f0ff7e3dd9f |
| tree | 6259f5f704578ac4a17e9519a982cdee1d1d614b |
| parent | 316cb0e532d34efbaf71deeeac975c9a70db36dc |
| signature | Signed by SSH key SHA256:52mNGHRsVFBDED9IAX5pe+LRWUefqTbxEReunq21QvU |
11 files changed, 4506 insertions(+), 101 deletions(-)
compatibility.md+32-17| ... | @@ -9,10 +9,10 @@ Auto-generated from live engine sources (`crates/engine/src/eval.rs`, `crates/en | ... | @@ -9,10 +9,10 @@ Auto-generated from live engine sources (`crates/engine/src/eval.rs`, `crates/en |
| 9 | 9 | ||
| 10 | | Metric | Value | | 10 | | Metric | Value | |
| 11 | | --- | --- | | 11 | | --- | --- | |
| 12 | | **Supported Flow Tools** | **66** (57 2D/Fuse/utility in `eval.rs`, 7 3D scene nodes in `scene3d.rs`, 2 Flow annotations) | | 12 | | **Supported Flow Tools** | **79** (70 2D/Fuse/utility in `eval.rs`, 7 3D scene nodes in `scene3d.rs`, 2 Flow annotations) | |
| 13 | | **Modifiers & Animation** | **7** systems (8 Fusion modifier classes + Lua expressions) | | 13 | | **Modifiers & Animation** | **7** systems (8 Fusion modifier classes + Lua expressions) | |
| 14 | | **Active Corpus (`trees/fusion`) Coverage** | **99.1%** (1,975 / 1,993 nodes across 16 `.comp` files) | | 14 | | **Active Corpus (`trees/fusion`) Coverage** | **99.3%** (1,980 / 1,993 nodes across 16 `.comp` files) | |
| 15 | | **Archive Corpus (`private/samples`) Coverage** | **95.8%** (52,653 / 54,955 nodes across 324 `.comp` files) | | 15 | | **Archive Corpus (`private/samples`) Coverage** | **96.1%** (52,825 / 54,955 nodes across 324 `.comp` files) | |
| 16 | | **HiQ vs Fast Mode** | **`HiQ`**: honors `DepthFull` / generator `Depth` / `ChangeDepth` (`Rgba8Unorm`, clamped `Rgba16Float`, unclamped HDR `Rgba16Float`/`Rgba32Float`), full-res blurs & `XGlow`. **`Fast`**: collapses working targets to `Rgba8Unorm`, downsamples blurs, caps `XGlow` octaves for interactive scrubbing. | | 16 | | **HiQ vs Fast Mode** | **`HiQ`**: honors `DepthFull` / generator `Depth` / `ChangeDepth` (`Rgba8Unorm`, clamped `Rgba16Float`, unclamped HDR `Rgba16Float`/`Rgba32Float`), full-res blurs & `XGlow`. **`Fast`**: collapses working targets to `Rgba8Unorm`, downsamples blurs, caps `XGlow` octaves for interactive scrubbing. | |
| 17 | 17 | ||
| 18 | ## Generators | 18 | ## Generators |
| ... | @@ -20,10 +20,10 @@ Auto-generated from live engine sources (`crates/engine/src/eval.rs`, `crates/en | ... | @@ -20,10 +20,10 @@ Auto-generated from live engine sources (`crates/engine/src/eval.rs`, `crates/en |
| 20 | | Tool | Probe Suite | Verified MAE | Usage (Active / Archive) | Notes & Fallbacks | | 20 | | Tool | Probe Suite | Verified MAE | Usage (Active / Archive) | Notes & Fallbacks | |
| 21 | | --- | --- | --- | --- | --- | | 21 | | --- | --- | --- | --- | --- | |
| 22 | | `Background` | `tier1_d` | 0.0% | 103 / 1949 | Solid, Horizontal/Vertical/4-Corner, Linear/Radial gradients; honors generator `Depth` in `HiQ`. | | 22 | | `Background` | `tier1_d` | 0.0% | 103 / 1949 | Solid, Horizontal/Vertical/4-Corner, Linear/Radial gradients; honors generator `Depth` in `HiQ`. | |
| 23 | | `FastNoise` | `noise_text` | Visual* | 18 / 201 | C2 quintic 3D Perlin fBm (`Detail`, `Contrast`, `Brightness`, `Seethe`, `LockXY`, `Angle`, `Discontinuous`, `Gradient`/`TwoColor`). *Proprietary Fusion lattice table differs ([#6](https://shale.paperclover.net/fission/issues/6)). | | 23 | | `FastNoise` | `noise_text` | Visual* | 18 / 201 | C2 quintic 3D Perlin fBm (`Detail`, `Contrast`, `Brightness`, `Seethe`, `LockXY`, `Angle`, `Discontinuous`, `Gradient`/`TwoColor`). *Proprietary Fusion lattice table differs. | |
| 24 | | `Plasma` | `tier1_c` | 0.1%–0.2% | 0 / 39 | 4-circle linear/sine interference pattern with phase/scale animation. | | 24 | | `Plasma` | `tier1_c` | 0.1%–0.2% | 0 / 39 | 4-circle linear/sine interference pattern with phase/scale animation. | |
| 25 | | `TextPlus` | `text`, `noise_text` | 0.1%–0.6% | 53 / 2770 | CoreText rasterizer, alignment, tracking, Euclidean subpixel SDF outline, `StyledTextCLS`. `BorderFill` tracked in [#6](https://shale.paperclover.net/fission/issues/6). | | 25 | | `TextPlus` | `text`, `noise_text` | 0.2%–0.9% | 53 / 2770 | CoreText rasterizer, alignment, tracking, Euclidean subpixel SDF outline, `BorderFill` (`ElementShape = 2`, `Level`, `ExtendHorizontal/Vertical`, `Round`, `Offset`), and `StyledTextCLS`. | |
| 26 | | `Loader` | All suites | 0.0% | 106 / 1274 | PNG/JPG/TIFF/EXR stills & sequences; native macOS `AVFoundation`/`VideoToolbox` + `ffmpeg` video; `.wav`/`.mp3` audio. Direct 16/32-bit float EXR upload tracked in [#5](https://shale.paperclover.net/fission/issues/5). | | 26 | | `Loader` | All suites | 0.0% | 106 / 1274 | PNG/JPG/TIFF/EXR stills & sequences with direct unclamped 16/32-bit float HDR OpenEXR upload in `HiQ`; native macOS `AVFoundation`/`VideoToolbox` + `ffmpeg` video; `.wav`/`.mp3` audio. | |
| 27 | 27 | ||
| 28 | ## Compositing & Blending | 28 | ## Compositing & Blending |
| 29 | 29 | ||
| ... | @@ -54,6 +54,7 @@ Auto-generated from live engine sources (`crates/engine/src/eval.rs`, `crates/en | ... | @@ -54,6 +54,7 @@ Auto-generated from live engine sources (`crates/engine/src/eval.rs`, `crates/en |
| 54 | | --- | --- | --- | --- | --- | | 54 | | --- | --- | --- | --- | --- | |
| 55 | | `LumaKeyer` | Suite comps | 0.1%–0.4% | 4 / 95 | Luminance/channel threshold keying with low/high feathering and matte inversion. | | 55 | | `LumaKeyer` | Suite comps | 0.1%–0.4% | 4 / 95 | Luminance/channel threshold keying with low/high feathering and matte inversion. | |
| 56 | | `UltraKeyer` | `tier1_a` | 0.1%–0.6% | 16 / 66 | Chroma keying with background color pick, matte threshold/gamma, spill suppression, and post-multiply. | | 56 | | `UltraKeyer` | `tier1_a` | 0.1%–0.6% | 16 / 66 | Chroma keying with background color pick, matte threshold/gamma, spill suppression, and post-multiply. | |
| 57 | | `Fuse.Cryptomatte` | Unit tests | 0.0% | 0 / 37 | Cryptomatte 1.2 multi-channel EXR matte extraction (manifest JSON + MurmurHash3-32 ID/coverage rank accumulation, wildcards, `MatteOnly`). | | ||
| 57 | 58 | ||
| 58 | ## Blur, Sharpen & Glow | 59 | ## Blur, Sharpen & Glow |
| 59 | 60 | ||
| ... | @@ -64,8 +65,8 @@ Auto-generated from live engine sources (`crates/engine/src/eval.rs`, `crates/en | ... | @@ -64,8 +65,8 @@ Auto-generated from live engine sources (`crates/engine/src/eval.rs`, `crates/en |
| 64 | | `Filter` | `tier1_a` | 0.1%–0.5% | 0 / 93 | Convolution filter types 0–4 (`Relief`, `Emboss`, `Smooth`, `Sobel`, `Laplacian`) with power & angle. | | 65 | | `Filter` | `tier1_a` | 0.1%–0.5% | 0 / 93 | Convolution filter types 0–4 (`Relief`, `Emboss`, `Smooth`, `Sobel`, `Laplacian`) with power & angle. | |
| 65 | | `VariBlur` | Suite comps | 0.2%–0.8% | 1 / 1 | Per-pixel variable-radius blur driven by `BlurImage` matte. | | 66 | | `VariBlur` | Suite comps | 0.2%–0.8% | 1 / 1 | Per-pixel variable-radius blur driven by `BlurImage` matte. | |
| 66 | | `DirectionalBlur` | `blur` | 0.1%–0.5% | 21 / 816 | `Linear`, `Centered`, `Radial`, and `Zoom` modes plus `Glow` accumulation. | | 67 | | `DirectionalBlur` | `blur` | 0.1%–0.5% | 21 / 816 | `Linear`, `Centered`, `Radial`, and `Zoom` modes plus `Glow` accumulation. | |
| 67 | | `Glow` | `glow` | 0.2%–1.3% | 11 / 549 | Additive bloom (`Glow`, `GlowSize`, `Blend`, color scale). Minor Gaussian tail roll-off tracked in [#6](https://shale.paperclover.net/fission/issues/6). | | 68 | | `Glow` | `glow` | 0.0%–0.2% | 11 / 549 | Additive bloom (`Glow`, `GlowSize`, `Blend`, color scale, border clamping, calibrated Gaussian roll-off). | |
| 68 | | `SoftGlow` | `glow` | 0.0%–0.8% | 3 / 30 | Thresholded soft glow (`Gain`, `XGlowSize`/`YGlowSize`, `Threshold`, `ClippingMode`, `ColorScale`). | | 69 | | `SoftGlow` | `glow` | 0.0%–0.2% | 3 / 30 | Thresholded soft glow (`Gain`, `XGlowSize`/`YGlowSize`, `Threshold`, `ClippingMode`, `ColorScale`, border clamping). | |
| 69 | | `Fuse.XGlow` | Suite comps | 0.2%–0.8% | 4 / 34 | Multi-octave exponential glow (`Threshold`, `Gain`, `XGlowSize`, `Falloff`, `Iterations`); octave-capped in `Fast` mode. | | 70 | | `Fuse.XGlow` | Suite comps | 0.2%–0.8% | 4 / 34 | Multi-octave exponential glow (`Threshold`, `Gain`, `XGlowSize`, `Falloff`, `Iterations`); octave-capped in `Fast` mode. | |
| 70 | | `ErodeDilate` | `blur` | 0.0%–0.3% | 18 / 202 | Positive/negative morphological erode/dilate with `Box` and `Circle` kernels. | | 71 | | `ErodeDilate` | `blur` | 0.0%–0.3% | 18 / 202 | Positive/negative morphological erode/dilate with `Box` and `Circle` kernels. | |
| 71 | | `FilmGrain` | `tier1_c` | Visual* | 0 / 18 | Monochrome log-space correlated film grain (`Size`, `Strength`, `Softness`). *Stochastic per-frame seed. | | 72 | | `FilmGrain` | `tier1_c` | Visual* | 0 / 18 | Monochrome log-space correlated film grain (`Size`, `Strength`, `Softness`). *Stochastic per-frame seed. | |
| ... | @@ -80,7 +81,7 @@ Auto-generated from live engine sources (`crates/engine/src/eval.rs`, `crates/en | ... | @@ -80,7 +81,7 @@ Auto-generated from live engine sources (`crates/engine/src/eval.rs`, `crates/en |
| 80 | | `CameraShake` | `tier1_c` | 0.1%–0.5% | 0 / 12 | Procedural X/Y/Rotation/Zoom camera shake with `OverallStrength`, `Speed`, `Edges`. | | 81 | | `CameraShake` | `tier1_c` | 0.1%–0.5% | 0 / 12 | Procedural X/Y/Rotation/Zoom camera shake with `OverallStrength`, `Speed`, `Edges`. | |
| 81 | | `CornerPositioner` | `tier1_b` | 0.1%–0.4% | 0 / 29 | 4-point projective homography warp (`TopLeft`/`TopRight`/`BottomLeft`/`BottomRight`). | | 82 | | `CornerPositioner` | `tier1_b` | 0.1%–0.4% | 0 / 29 | 4-point projective homography warp (`TopLeft`/`TopRight`/`BottomLeft`/`BottomRight`). | |
| 82 | | `DVE` | `tier1_b` | 0.1%–0.4% | 4 / 22 | 2.5D ZYX Euler rotation + perspective homography (`Center`, `ZMove`, `Pivot`, `AlphaMode`). | | 83 | | `DVE` | `tier1_b` | 0.1%–0.4% | 4 / 22 | 2.5D ZYX Euler rotation + perspective homography (`Center`, `ZMove`, `Pivot`, `AlphaMode`). | |
| 83 | | `Displace` | `displace` | 0.1%–0.7% | 11 / 109 | `XY` refraction (channels, offsets, refraction strength) and `Radial`/`Bump` (`LightPower` angle/color minor parity tracked in [#6](https://shale.paperclover.net/fission/issues/6)). | | 84 | | `Displace` | `displace` | 0.0%–0.1% | 11 / 109 | `XY` refraction (channels, offsets, refraction strength) and `Radial`/`Bump` (`LightPower`, `LightAngle`, `LightChannel` additive directional slope lighting). | |
| 84 | | `Scale` | Suite comps | 0.0%–0.2% | 12 / 98 | Proportional/non-proportional image scaling with resampling filter. | | 85 | | `Scale` | Suite comps | 0.0%–0.2% | 12 / 98 | Proportional/non-proportional image scaling with resampling filter. | |
| 85 | | `BetterResize` | Suite comps | 0.0%–0.2% | 0 / 93 | Target pixel-dimension resize (`Width`, `Height`, `KeepAspect`). | | 86 | | `BetterResize` | Suite comps | 0.0%–0.2% | 0 / 93 | Target pixel-dimension resize (`Width`, `Height`, `KeepAspect`). | |
| 86 | | `Crop` | Suite comps | 0.0%–0.1% | 3 / 168 | Region crop & canvas repositioning (`XOffset`, `YOffset`, `XSize`, `YSize`, `KeepCentered`). | | 87 | | `Crop` | Suite comps | 0.0%–0.1% | 3 / 168 | Region crop & canvas repositioning (`XOffset`, `YOffset`, `XSize`, `YSize`, `KeepCentered`). | |
| ... | @@ -95,6 +96,19 @@ Auto-generated from live engine sources (`crates/engine/src/eval.rs`, `crates/en | ... | @@ -95,6 +96,19 @@ Auto-generated from live engine sources (`crates/engine/src/eval.rs`, `crates/en |
| 95 | | `PolylineMask` | Suite comps | 0.1%–0.5% | 16 / 505 | CPU `zeno` Bezier/linear polygon rasterizer with animated keyframed `Polyline` splines, `SoftEdge`, `Invert`, `PaintMode`. | | 96 | | `PolylineMask` | Suite comps | 0.1%–0.5% | 16 / 505 | CPU `zeno` Bezier/linear polygon rasterizer with animated keyframed `Polyline` splines, `SoftEdge`, `Invert`, `PaintMode`. | |
| 96 | | `BitmapMask` | Suite comps | 0.0%–0.2% | 3 / 121 | Image-to-mask extraction (`Alpha`/`Luminance`/`Red`/`Green`/`Blue`), `Low`/`High` clip, `SoftEdge`, `Invert`. | | 97 | | `BitmapMask` | Suite comps | 0.0%–0.2% | 3 / 121 | Image-to-mask extraction (`Alpha`/`Luminance`/`Red`/`Green`/`Blue`), `Low`/`High` clip, `SoftEdge`, `Invert`. | |
| 97 | 98 | ||
| 99 | ## Particles | ||
| 100 | |||
| 101 | | Tool | Probe Suite | Verified MAE | Usage (Active / Archive) | Notes & Fallbacks | | ||
| 102 | | --- | --- | --- | --- | --- | | ||
| 103 | | `pRender` | Unit tests | Visual* | 1 / 54 | 2D deterministic particle rasterizer (`ParticleStyleBitmap` rotated bilinear sprites, `ParticleStylePoint`/`Blob`, cached frame stepping). *Stochastic seed. | | ||
| 104 | | `pEmitter` | Unit tests | Visual* | 1 / 54 | Seeded particle emitter (`RectRgn`/`SphereRgn`/`CubeRgn`/`LineRgn`/`Point`, `Number`, `Lifespan`, `Velocity`, `RotationZ`, `SpinZ`, `ColorVariance`, `SizeOverLife`, `FadeIn`/`FadeOut`). | | ||
| 105 | | `pPointForce` | Unit tests | Visual* | 1 / 3 | Radial point attractor/repulsor (`Strength`, `Power`, `Translate.X/Y/Z`). | | ||
| 106 | | `pDirectionalForce` | Unit tests | Visual* | 0 / 11 | Directional acceleration / gravity field (`Strength`, `Direction`). | | ||
| 107 | | `pTurbulence` | Unit tests | Visual* | 0 / 0 | Seeded 3D turbulent noise force field (`XStrength`, `YStrength`, `Density`). | | ||
| 108 | | `pDrag` | Unit tests | Visual* | 0 / 2 | Velocity damping / aerodynamic drag force. | | ||
| 109 | | `pKill` | Unit tests | Visual* | 0 / 1 | Region-based particle termination (`Inside`/`Outside`/`Entering`/`Leaving`). | | ||
| 110 | | `pMerge` | Unit tests | Visual* | 0 / 0 | Combines multiple upstream particle emitter streams. | | ||
| 111 | |||
| 98 | ## 3D Pipeline | 112 | ## 3D Pipeline |
| 99 | 113 | ||
| 100 | | Tool | Probe Suite | Verified MAE | Usage (Active / Archive) | Notes & Fallbacks | | 114 | | Tool | Probe Suite | Verified MAE | Usage (Active / Archive) | Notes & Fallbacks | |
| ... | @@ -112,8 +126,9 @@ Auto-generated from live engine sources (`crates/engine/src/eval.rs`, `crates/en | ... | @@ -112,8 +126,9 @@ Auto-generated from live engine sources (`crates/engine/src/eval.rs`, `crates/en |
| 112 | 126 | ||
| 113 | | Tool | Probe Suite | Verified MAE | Usage (Active / Archive) | Notes & Fallbacks | | 127 | | Tool | Probe Suite | Verified MAE | Usage (Active / Archive) | Notes & Fallbacks | |
| 114 | | --- | --- | --- | --- | --- | | 128 | | --- | --- | --- | --- | --- | |
| 115 | | `Saver` | All suites | 0.0% | 15 / 278 | Output sink / passthrough in interactive Flow; target selector for `render-check` CLI. | | 129 | | `Saver` | All suites | 0.0% | 15 / 278 | Output sink / passthrough in interactive Flow; Saver-driven pipelined PNG sequence export (`render-check --export` and `Cmd+Shift+R`). | |
| 116 | | `TimeStretcher` | Suite comps | 0.0% | 13 / 82 | Keyframed/expression `SourceTime` remapping upstream of evaluation (nearest/frame evaluation; Optical Flow tracked in [#4](https://shale.paperclover.net/fission/issues/4)). | | 130 | | `Dimension.OpticalFlow` | Unit tests | 0.1% | 2 / 10 | GPU 4-level pyramid coarse-to-fine bidirectional dense optical flow feeding downstream `TimeStretcher` flow interpolation. | |
| 131 | | `TimeStretcher` | Suite comps | 0.0%–0.2% | 13 / 82 | Keyframed/expression `SourceTime` remapping with `Nearest` (`0`), `Blend` (`1`), and GPU `OpticalFlow` (`2`) bidirectional warped interpolation. | | ||
| 117 | | `TimeSpeed` | Suite comps | 0.0% | 0 / 166 | Constant/animated `Speed` and `Delay` time remapping. | | 132 | | `TimeSpeed` | Suite comps | 0.0% | 0 / 166 | Constant/animated `Speed` and `Delay` time remapping. | |
| 118 | | `Switch` | Suite comps | 0.0% | 2 / 23 | Dynamic input routing by `Which` index (`Input1`..`InputN`). | | 133 | | `Switch` | Suite comps | 0.0% | 2 / 23 | Dynamic input routing by `Which` index (`Input1`..`InputN`). | |
| 119 | | `Fuse.Switch` | Suite comps | 0.0% | 1 / 184 | Fuse variant of `Switch` routing `Input1`..`InputN` by `Which`. | | 134 | | `Fuse.Switch` | Suite comps | 0.0% | 1 / 184 | Fuse variant of `Switch` routing `Input1`..`InputN` by `Which`. | |
| ... | @@ -147,12 +162,7 @@ Unlike Blackmagic Fusion — which unlinks missing OFX or Resolve-only plugins w | ... | @@ -147,12 +162,7 @@ Unlike Blackmagic Fusion — which unlinks missing OFX or Resolve-only plugins w |
| 147 | | `SurfaceTracker` | 2 / 1 | [#7](https://shale.paperclover.net/fission/issues/7) | Preserved lossless on save; passes through main image input in Flow. | | 162 | | `SurfaceTracker` | 2 / 1 | [#7](https://shale.paperclover.net/fission/issues/7) | Preserved lossless on save; passes through main image input in Flow. | |
| 148 | | `MagicMask` | 3 / 1 | [#7](https://shale.paperclover.net/fission/issues/7) | Preserved lossless on save; passes through main image input in Flow. | | 163 | | `MagicMask` | 3 / 1 | [#7](https://shale.paperclover.net/fission/issues/7) | Preserved lossless on save; passes through main image input in Flow. | |
| 149 | | `PlanarTracker` | 0 / 0 | [#7](https://shale.paperclover.net/fission/issues/7) | Preserved lossless on save; passes through main image input in Flow. | | 164 | | `PlanarTracker` | 0 / 0 | [#7](https://shale.paperclover.net/fission/issues/7) | Preserved lossless on save; passes through main image input in Flow. | |
| 150 | | `Fuse.Cryptomatte` | 0 / 37 | [#2](https://shale.paperclover.net/fission/issues/2) | Preserved lossless on save; passes through main image input (multi-channel EXR matte extraction tracked). | | 165 | | `Dimension.CopyAux` | 4 / 0 | — | Preserved lossless on save; passes through main image input. | |
| 151 | | `Dimension.OpticalFlow` | 2 / 10 | [#4](https://shale.paperclover.net/fission/issues/4) | Preserved lossless on save; passes through main image input (GPU dense optical flow tracked). | | ||
| 152 | | `Dimension.CopyAux` | 4 / 0 | [#4](https://shale.paperclover.net/fission/issues/4) | Preserved lossless on save; passes through main image input. | | ||
| 153 | | `pEmitter` | 1 / 54 | [#3](https://shale.paperclover.net/fission/issues/3) | Preserved lossless on save; skipped in 3D scene until particle simulator lands. | | ||
| 154 | | `pRender` | 1 / 54 | [#3](https://shale.paperclover.net/fission/issues/3) | Preserved lossless on save; skipped / passthrough until particle simulator lands. | | ||
| 155 | | `pPointForce` | 1 / 3 | [#3](https://shale.paperclover.net/fission/issues/3) | Preserved lossless on save; skipped in 3D scene until particle simulator lands. | | ||
| 156 | | `SurfaceFBXMesh` | 0 / 216 | — | Preserved lossless on save; FBX mesh geometry not yet imported in `Renderer3D`. | | 166 | | `SurfaceFBXMesh` | 0 / 216 | — | Preserved lossless on save; FBX mesh geometry not yet imported in `Renderer3D`. | |
| 157 | | `Text3D` | 0 / 410 | — | Preserved lossless on save; extruded 3D text mesh not yet implemented in `Renderer3D`. | | 167 | | `Text3D` | 0 / 410 | — | Preserved lossless on save; extruded 3D text mesh not yet implemented in `Renderer3D`. | |
| 158 | | `MtlBlinn` | 0 / 181 | — | Preserved lossless on save; basic diffuse color & texture resolved in `Renderer3D` (full Blinn specular/bump pending). | | 168 | | `MtlBlinn` | 0 / 181 | — | Preserved lossless on save; basic diffuse color & texture resolved in `Renderer3D` (full Blinn specular/bump pending). | |
| ... | @@ -168,6 +178,11 @@ Unlike Blackmagic Fusion — which unlinks missing OFX or Resolve-only plugins w | ... | @@ -168,6 +178,11 @@ Unlike Blackmagic Fusion — which unlinks missing OFX or Resolve-only plugins w |
| 168 | | `Texture2DOperator` | 0 / 44 | — | Preserved lossless on save; passes through main input in Flow. | | 178 | | `Texture2DOperator` | 0 / 44 | — | Preserved lossless on save; passes through main input in Flow. | |
| 169 | | `Multistroke` | 0 / 33 | — | Preserved lossless on save; passes through main input in Flow. | | 179 | | `Multistroke` | 0 / 33 | — | Preserved lossless on save; passes through main input in Flow. | |
| 170 | | `Drip` | 0 / 29 | — | Preserved lossless on save; passes through main input in Flow. | | 180 | | `Drip` | 0 / 29 | — | Preserved lossless on save; passes through main input in Flow. | |
| 181 | | `PolylineStroke` | 0 / 27 | — | Preserved lossless on save; passes through main input in Flow. | | ||
| 182 | | `Fuse.KScope` | 0 / 27 | — | Preserved lossless on save; passes through main input in Flow. | | ||
| 183 | | `ReplaceNormals3D` | 0 / 27 | — | Preserved lossless on save; passes through main input in Flow. | | ||
| 184 | | `Paint` | 0 / 25 | — | Preserved lossless on save; passes through main input in Flow. | | ||
| 185 | | `Fuse.HexagonTiles` | 0 / 25 | — | Preserved lossless on save; passes through main input in Flow. | | ||
| 171 | 186 | ||
| 172 | --- | 187 | --- |
| 173 | 188 |
crates/engine/src/cryptomatte.rs created+856| ... | @@ -0,0 +1,856 @@ | ||
| 1 | //! OpenEXR Cryptomatte (`Fuse.Cryptomatte`) matte extraction following the | ||
| 2 | //! Psyop Cryptomatte 1.2 specification. | ||
| 3 | |||
| 4 | use std::collections::{BTreeMap, HashMap, HashSet}; | ||
| 5 | use std::path::Path; | ||
| 6 | |||
| 7 | /// Extracted single-channel Cryptomatte coverage mask (`[0.0, 1.0]`, top-down). | ||
| 8 | #[derive(Clone, Debug)] | ||
| 9 | pub struct CryptomatteResult { | ||
| 10 | pub size: [u32; 2], | ||
| 11 | pub matte: Vec<f32>, | ||
| 12 | } | ||
| 13 | |||
| 14 | /// Exact MurmurHash3 32-bit x86 (`c1 = 0xcc9e2d51`, `c2 = 0x1b873593`, `fmix32`). | ||
| 15 | pub fn murmur3_32(bytes: &[u8], seed: u32) -> u32 { | ||
| 16 | const C1: u32 = 0xcc9e_2d51; | ||
| 17 | const C2: u32 = 0x1b87_3593; | ||
| 18 | |||
| 19 | let mut hash = seed; | ||
| 20 | let chunks = bytes.chunks_exact(4); | ||
| 21 | let remainder = chunks.remainder(); | ||
| 22 | |||
| 23 | for chunk in chunks { | ||
| 24 | let mut k = u32::from_le_bytes([chunk[0], chunk[1], chunk[2], chunk[3]]); | ||
| 25 | k = k.wrapping_mul(C1); | ||
| 26 | k = k.rotate_left(15); | ||
| 27 | k = k.wrapping_mul(C2); | ||
| 28 | |||
| 29 | hash ^= k; | ||
| 30 | hash = hash.rotate_left(13); | ||
| 31 | hash = hash.wrapping_mul(5).wrapping_add(0xe654_6b64); | ||
| 32 | } | ||
| 33 | |||
| 34 | if !remainder.is_empty() { | ||
| 35 | let mut k1 = 0u32; | ||
| 36 | for (i, &b) in remainder.iter().enumerate() { | ||
| 37 | k1 |= u32::from(b) << (i * 8); | ||
| 38 | } | ||
| 39 | k1 = k1.wrapping_mul(C1); | ||
| 40 | k1 = k1.rotate_left(15); | ||
| 41 | k1 = k1.wrapping_mul(C2); | ||
| 42 | hash ^= k1; | ||
| 43 | } | ||
| 44 | |||
| 45 | hash ^= bytes.len() as u32; | ||
| 46 | hash ^= hash >> 16; | ||
| 47 | hash = hash.wrapping_mul(0x85eb_ca6b); | ||
| 48 | hash ^= hash >> 13; | ||
| 49 | hash = hash.wrapping_mul(0xc2b2_ae35); | ||
| 50 | hash ^= hash >> 16; | ||
| 51 | hash | ||
| 52 | } | ||
| 53 | |||
| 54 | /// Converts a 32-bit Cryptomatte hash into its IEEE-754 `f32` ID representation, | ||
| 55 | /// flipping bit 23 when exponent is 0 (subnormal/zero) or 255 (inf/NaN). | ||
| 56 | pub fn crypto_hash_to_float(hash: u32) -> f32 { | ||
| 57 | let exp = (hash >> 23) & 0xFF; | ||
| 58 | let adjusted = if exp == 0 || exp == 255 { | ||
| 59 | hash ^ (1 << 23) | ||
| 60 | } else { | ||
| 61 | hash | ||
| 62 | }; | ||
| 63 | f32::from_bits(adjusted) | ||
| 64 | } | ||
| 65 | |||
| 66 | /// Parses a Fusion `Fuse.Cryptomatte` `MatteList` string such as | ||
| 67 | /// `"\"floor\", \"Armature\", \"floor.001\""` or `"Hero, Tree"`. | ||
| 68 | /// | ||
| 69 | /// Handles double-quoted tokens (including escaped quotes/backslashes and embedded commas), | ||
| 70 | /// unquoted comma- or newline-separated tokens, trims whitespace, and ignores empty entries. | ||
| 71 | pub fn parse_matte_list(matte_list: &str) -> Vec<String> { | ||
| 72 | let mut out = Vec::new(); | ||
| 73 | let mut chars = matte_list.chars().peekable(); | ||
| 74 | |||
| 75 | while let Some(&ch) = chars.peek() { | ||
| 76 | if ch.is_whitespace() || ch == ',' { | ||
| 77 | chars.next(); | ||
| 78 | continue; | ||
| 79 | } | ||
| 80 | |||
| 81 | if ch == '"' { | ||
| 82 | chars.next(); // consume opening quote | ||
| 83 | let mut token = String::new(); | ||
| 84 | while let Some(c) = chars.next() { | ||
| 85 | if c == '\\' { | ||
| 86 | if let Some(escaped) = chars.next() { | ||
| 87 | match escaped { | ||
| 88 | 'n' => token.push('\n'), | ||
| 89 | 'r' => token.push('\r'), | ||
| 90 | 't' => token.push('\t'), | ||
| 91 | other => token.push(other), | ||
| 92 | } | ||
| 93 | } | ||
| 94 | } else if c == '"' { | ||
| 95 | break; | ||
| 96 | } else { | ||
| 97 | token.push(c); | ||
| 98 | } | ||
| 99 | } | ||
| 100 | if !token.is_empty() { | ||
| 101 | out.push(token); | ||
| 102 | } | ||
| 103 | // Skip trailing whitespace / separator after closing quote | ||
| 104 | while let Some(&next_ch) = chars.peek() { | ||
| 105 | if next_ch == ',' || next_ch == '\n' || next_ch == '\r' { | ||
| 106 | chars.next(); | ||
| 107 | break; | ||
| 108 | } else if next_ch.is_whitespace() { | ||
| 109 | chars.next(); | ||
| 110 | } else { | ||
| 111 | break; | ||
| 112 | } | ||
| 113 | } | ||
| 114 | } else { | ||
| 115 | let mut token = String::new(); | ||
| 116 | while let Some(&c) = chars.peek() { | ||
| 117 | if c == ',' || c == '\n' || c == '\r' { | ||
| 118 | chars.next(); | ||
| 119 | break; | ||
| 120 | } | ||
| 121 | token.push(c); | ||
| 122 | chars.next(); | ||
| 123 | } | ||
| 124 | let trimmed = token.trim(); | ||
| 125 | if !trimmed.is_empty() { | ||
| 126 | out.push(trimmed.to_string()); | ||
| 127 | } | ||
| 128 | } | ||
| 129 | } | ||
| 130 | |||
| 131 | out | ||
| 132 | } | ||
| 133 | |||
| 134 | /// Lightweight zero-dependency parser for flat Cryptomatte JSON manifest objects | ||
| 135 | /// (`{"object_name": "a1b2c3d4", ...}`), handling JSON string escapes (`\"`, `\\`, `\uXXXX`) | ||
| 136 | /// and parsing the 8-hex-digit hash string into `u32`. | ||
| 137 | pub fn parse_manifest_json(json: &str) -> HashMap<String, u32> { | ||
| 138 | let mut map = HashMap::new(); | ||
| 139 | let bytes = json.as_bytes(); | ||
| 140 | let len = bytes.len(); | ||
| 141 | let mut pos = 0usize; | ||
| 142 | |||
| 143 | let skip_ws = |p: &mut usize| { | ||
| 144 | while *p < len && matches!(bytes[*p], b' ' | b'\t' | b'\r' | b'\n') { | ||
| 145 | *p += 1; | ||
| 146 | } | ||
| 147 | }; | ||
| 148 | |||
| 149 | skip_ws(&mut pos); | ||
| 150 | if pos >= len || bytes[pos] != b'{' { | ||
| 151 | return map; | ||
| 152 | } | ||
| 153 | pos += 1; // consume '{' | ||
| 154 | |||
| 155 | loop { | ||
| 156 | skip_ws(&mut pos); | ||
| 157 | if pos >= len || bytes[pos] == b'}' { | ||
| 158 | break; | ||
| 159 | } | ||
| 160 | if bytes[pos] == b',' { | ||
| 161 | pos += 1; | ||
| 162 | continue; | ||
| 163 | } | ||
| 164 | let Some(key) = parse_json_string(json, &mut pos) else { | ||
| 165 | break; | ||
| 166 | }; | ||
| 167 | skip_ws(&mut pos); | ||
| 168 | if pos >= len || bytes[pos] != b':' { | ||
| 169 | break; | ||
| 170 | } | ||
| 171 | pos += 1; // consume ':' | ||
| 172 | skip_ws(&mut pos); | ||
| 173 | let Some(val_str) = parse_json_string(json, &mut pos) else { | ||
| 174 | break; | ||
| 175 | }; | ||
| 176 | let hex = val_str | ||
| 177 | .trim() | ||
| 178 | .trim_start_matches("0x") | ||
| 179 | .trim_start_matches("0X"); | ||
| 180 | if let Ok(hash) = u32::from_str_radix(hex, 16) { | ||
| 181 | map.insert(key, hash); | ||
| 182 | } | ||
| 183 | skip_ws(&mut pos); | ||
| 184 | if pos < len && bytes[pos] == b',' { | ||
| 185 | pos += 1; | ||
| 186 | } | ||
| 187 | } | ||
| 188 | |||
| 189 | map | ||
| 190 | } | ||
| 191 | |||
| 192 | fn parse_json_string(src: &str, pos: &mut usize) -> Option<String> { | ||
| 193 | let bytes = src.as_bytes(); | ||
| 194 | if *pos >= bytes.len() || bytes[*pos] != b'"' { | ||
| 195 | return None; | ||
| 196 | } | ||
| 197 | *pos += 1; // consume opening '"' | ||
| 198 | let mut out = String::new(); | ||
| 199 | while *pos < bytes.len() { | ||
| 200 | let ch = src[*pos..].chars().next()?; | ||
| 201 | *pos += ch.len_utf8(); | ||
| 202 | match ch { | ||
| 203 | '"' => return Some(out), | ||
| 204 | '\\' => { | ||
| 205 | if *pos >= bytes.len() { | ||
| 206 | return None; | ||
| 207 | } | ||
| 208 | let esc = src[*pos..].chars().next()?; | ||
| 209 | *pos += esc.len_utf8(); | ||
| 210 | match esc { | ||
| 211 | '"' => out.push('"'), | ||
| 212 | '\\' => out.push('\\'), | ||
| 213 | '/' => out.push('/'), | ||
| 214 | 'b' => out.push('\u{0008}'), | ||
| 215 | 'f' => out.push('\u{000C}'), | ||
| 216 | 'n' => out.push('\n'), | ||
| 217 | 'r' => out.push('\r'), | ||
| 218 | 't' => out.push('\t'), | ||
| 219 | 'u' => { | ||
| 220 | let code_unit = parse_hex4(src, pos)?; | ||
| 221 | if (0xD800..=0xDBFF).contains(&code_unit) { | ||
| 222 | // UTF-16 surrogate pair | ||
| 223 | if src[*pos..].starts_with("\\u") { | ||
| 224 | *pos += 2; | ||
| 225 | let low = parse_hex4(src, pos)?; | ||
| 226 | if (0xDC00..=0xDFFF).contains(&low) { | ||
| 227 | let combined = 0x10000 | ||
| 228 | + ((u32::from(code_unit - 0xD800)) << 10) | ||
| 229 | + u32::from(low - 0xDC00); | ||
| 230 | if let Some(c) = char::from_u32(combined) { | ||
| 231 | out.push(c); | ||
| 232 | } | ||
| 233 | } | ||
| 234 | } | ||
| 235 | } else if let Some(c) = char::from_u32(u32::from(code_unit)) { | ||
| 236 | out.push(c); | ||
| 237 | } | ||
| 238 | } | ||
| 239 | other => out.push(other), | ||
| 240 | } | ||
| 241 | } | ||
| 242 | other => out.push(other), | ||
| 243 | } | ||
| 244 | } | ||
| 245 | None | ||
| 246 | } | ||
| 247 | |||
| 248 | fn parse_hex4(src: &str, pos: &mut usize) -> Option<u16> { | ||
| 249 | if *pos + 4 > src.len() { | ||
| 250 | return None; | ||
| 251 | } | ||
| 252 | let slice = &src[*pos..*pos + 4]; | ||
| 253 | let val = u16::from_str_radix(slice, 16).ok()?; | ||
| 254 | *pos += 4; | ||
| 255 | Some(val) | ||
| 256 | } | ||
| 257 | |||
| 258 | #[derive(Default)] | ||
| 259 | struct CryptoLayerMeta { | ||
| 260 | name: Option<String>, | ||
| 261 | manifest: Option<String>, | ||
| 262 | manif_file: Option<String>, | ||
| 263 | } | ||
| 264 | |||
| 265 | fn attr_value_to_string(val: &exr::meta::attribute::AttributeValue) -> Option<String> { | ||
| 266 | use exr::meta::attribute::AttributeValue; | ||
| 267 | match val { | ||
| 268 | AttributeValue::Text(t) => Some(t.to_string()), | ||
| 269 | AttributeValue::Bytes { bytes, .. } => { | ||
| 270 | Some(String::from_utf8_lossy(bytes.as_slice()).into_owned()) | ||
| 271 | } | ||
| 272 | AttributeValue::Custom { bytes, .. } => { | ||
| 273 | Some(String::from_utf8_lossy(bytes.as_slice()).into_owned()) | ||
| 274 | } | ||
| 275 | _ => None, | ||
| 276 | } | ||
| 277 | } | ||
| 278 | |||
| 279 | fn collect_crypto_metadata_from_map( | ||
| 280 | other: &HashMap<exr::meta::attribute::Text, exr::meta::attribute::AttributeValue>, | ||
| 281 | out: &mut BTreeMap<String, CryptoLayerMeta>, | ||
| 282 | ) { | ||
| 283 | for (k, v) in other { | ||
| 284 | let key = k.to_string(); | ||
| 285 | let Some(rest) = key.strip_prefix("cryptomatte/") else { | ||
| 286 | continue; | ||
| 287 | }; | ||
| 288 | let Some((id, field)) = rest.split_once('/') else { | ||
| 289 | continue; | ||
| 290 | }; | ||
| 291 | if id.is_empty() { | ||
| 292 | continue; | ||
| 293 | } | ||
| 294 | let Some(val_str) = attr_value_to_string(v) else { | ||
| 295 | continue; | ||
| 296 | }; | ||
| 297 | let entry = out.entry(id.to_string()).or_default(); | ||
| 298 | match field { | ||
| 299 | "name" => entry.name = Some(val_str), | ||
| 300 | "manifest" => entry.manifest = Some(val_str), | ||
| 301 | "manif_file" => entry.manif_file = Some(val_str), | ||
| 302 | _ => {} | ||
| 303 | } | ||
| 304 | } | ||
| 305 | } | ||
| 306 | |||
| 307 | fn parse_channel_component(comp: &str) -> Option<usize> { | ||
| 308 | match comp.to_ascii_lowercase().as_str() { | ||
| 309 | "r" | "red" => Some(0), | ||
| 310 | "g" | "green" => Some(1), | ||
| 311 | "b" | "blue" => Some(2), | ||
| 312 | "a" | "alpha" => Some(3), | ||
| 313 | _ => None, | ||
| 314 | } | ||
| 315 | } | ||
| 316 | |||
| 317 | /// Splits a full EXR channel name such as `"ViewLayer.CryptoObject00.R"` into | ||
| 318 | /// `("ViewLayer.CryptoObject", 0, 0)` (prefix, rank, rgba component index). | ||
| 319 | fn split_crypto_rank_channel(full_name: &str) -> Option<(&str, u8, usize)> { | ||
| 320 | let (chan_layer, comp_name) = full_name.rsplit_once('.')?; | ||
| 321 | let comp_idx = parse_channel_component(comp_name)?; | ||
| 322 | if chan_layer.len() < 3 { | ||
| 323 | return None; | ||
| 324 | } | ||
| 325 | let split_at = chan_layer.len() - 2; | ||
| 326 | let digits = chan_layer.get(split_at..)?; | ||
| 327 | if !digits.bytes().all(|b| b.is_ascii_digit()) { | ||
| 328 | return None; | ||
| 329 | } | ||
| 330 | let rank: u8 = digits.parse().ok()?; | ||
| 331 | let prefix = &chan_layer[..split_at]; | ||
| 332 | if prefix.is_empty() { | ||
| 333 | return None; | ||
| 334 | } | ||
| 335 | Some((prefix, rank, comp_idx)) | ||
| 336 | } | ||
| 337 | |||
| 338 | fn full_channel_name(layer_name: Option<&str>, ch_name: &str) -> String { | ||
| 339 | if let Some(ln) = layer_name.filter(|s| !s.is_empty()) { | ||
| 340 | if ch_name == ln || ch_name.starts_with(&format!("{ln}.")) { | ||
| 341 | ch_name.to_string() | ||
| 342 | } else { | ||
| 343 | format!("{ln}.{ch_name}") | ||
| 344 | } | ||
| 345 | } else { | ||
| 346 | ch_name.to_string() | ||
| 347 | } | ||
| 348 | } | ||
| 349 | |||
| 350 | fn prefix_matches(candidate_prefix: &str, requested: &str) -> bool { | ||
| 351 | candidate_prefix == requested | ||
| 352 | || candidate_prefix.ends_with(&format!(".{requested}")) | ||
| 353 | || candidate_prefix.eq_ignore_ascii_case(requested) | ||
| 354 | || candidate_prefix | ||
| 355 | .to_ascii_lowercase() | ||
| 356 | .ends_with(&format!(".{}", requested.to_ascii_lowercase())) | ||
| 357 | } | ||
| 358 | |||
| 359 | fn glob_match(pattern: &str, text: &str) -> bool { | ||
| 360 | let p: Vec<char> = pattern.chars().collect(); | ||
| 361 | let t: Vec<char> = text.chars().collect(); | ||
| 362 | let (mut pi, mut ti) = (0usize, 0usize); | ||
| 363 | let mut star_pi: Option<usize> = None; | ||
| 364 | let mut star_ti = 0usize; | ||
| 365 | |||
| 366 | while ti < t.len() { | ||
| 367 | if pi < p.len() && (p[pi] == '?' || p[pi] == t[ti]) { | ||
| 368 | pi += 1; | ||
| 369 | ti += 1; | ||
| 370 | } else if pi < p.len() && p[pi] == '*' { | ||
| 371 | star_pi = Some(pi); | ||
| 372 | star_ti = ti; | ||
| 373 | pi += 1; | ||
| 374 | } else if let Some(sp) = star_pi { | ||
| 375 | pi = sp + 1; | ||
| 376 | star_ti += 1; | ||
| 377 | ti = star_ti; | ||
| 378 | } else { | ||
| 379 | return false; | ||
| 380 | } | ||
| 381 | } | ||
| 382 | |||
| 383 | while pi < p.len() && p[pi] == '*' { | ||
| 384 | pi += 1; | ||
| 385 | } | ||
| 386 | pi == p.len() | ||
| 387 | } | ||
| 388 | |||
| 389 | fn parse_hex_literal_token(token: &str) -> Option<u32> { | ||
| 390 | let inner = token.strip_prefix('<')?.strip_suffix('>')?.trim(); | ||
| 391 | let hex = inner | ||
| 392 | .strip_prefix("0x") | ||
| 393 | .or_else(|| inner.strip_prefix("0X"))?; | ||
| 394 | u32::from_str_radix(hex, 16).ok() | ||
| 395 | } | ||
| 396 | |||
| 397 | /// Lists Cryptomatte layer names discovered in an OpenEXR file's header metadata | ||
| 398 | /// (falling back to rank-00 channel prefix discovery when metadata is absent). | ||
| 399 | pub fn list_cryptomatte_layers(exr_path: &Path) -> Vec<String> { | ||
| 400 | let Ok(meta) = exr::meta::MetaData::read_from_file(exr_path, false) else { | ||
| 401 | return Vec::new(); | ||
| 402 | }; | ||
| 403 | let mut crypto_meta: BTreeMap<String, CryptoLayerMeta> = BTreeMap::new(); | ||
| 404 | for header in &meta.headers { | ||
| 405 | collect_crypto_metadata_from_map(&header.shared_attributes.other, &mut crypto_meta); | ||
| 406 | collect_crypto_metadata_from_map(&header.own_attributes.other, &mut crypto_meta); | ||
| 407 | } | ||
| 408 | |||
| 409 | let mut layers = Vec::new(); | ||
| 410 | for entry in crypto_meta.values() { | ||
| 411 | if let Some(name) = entry.name.as_ref().filter(|s| !s.is_empty()) { | ||
| 412 | if !layers.contains(name) { | ||
| 413 | layers.push(name.clone()); | ||
| 414 | } | ||
| 415 | } | ||
| 416 | } | ||
| 417 | |||
| 418 | if !layers.is_empty() { | ||
| 419 | return layers; | ||
| 420 | } | ||
| 421 | |||
| 422 | // Fallback: infer Cryptomatte layer prefixes from `00.R` channels. | ||
| 423 | for header in &meta.headers { | ||
| 424 | let lname = header.own_attributes.layer_name.as_ref().map(|t| t.to_string()); | ||
| 425 | for ch in &header.channels.list { | ||
| 426 | let full = full_channel_name(lname.as_deref(), &ch.name.to_string()); | ||
| 427 | if let Some((prefix, 0, 0)) = split_crypto_rank_channel(&full) { | ||
| 428 | let p = prefix.to_string(); | ||
| 429 | if !layers.contains(&p) { | ||
| 430 | layers.push(p); | ||
| 431 | } | ||
| 432 | } | ||
| 433 | } | ||
| 434 | } | ||
| 435 | |||
| 436 | layers | ||
| 437 | } | ||
| 438 | |||
| 439 | /// Extracts a Cryptomatte coverage matte from a multi-channel OpenEXR file. | ||
| 440 | /// | ||
| 441 | /// - Reads all flat layers and custom header `other` attributes via | ||
| 442 | /// `exr::prelude::read_all_flat_layers_from_file`. | ||
| 443 | /// - Resolves `cryptomatte/<id>/name`, `cryptomatte/<id>/manifest`, and sidecar | ||
| 444 | /// `cryptomatte/<id>/manif_file` relative to `exr_path.parent()`. | ||
| 445 | /// - Matches `layer_name` by exact name, suffix (e.g. `"CryptoObject"` -> `"ViewLayer.CryptoObject"`), | ||
| 446 | /// or falls back to the first Cryptomatte layer when `layer_name` is `None`/empty. | ||
| 447 | /// - Accumulates coverage across all rank channel groups (`<prefix>00`..`<prefix>09`) | ||
| 448 | /// for `(R, G)` and `(B, A)` pairs and clamps the final matte to `[0.0, 1.0]`. | ||
| 449 | pub fn extract_cryptomatte( | ||
| 450 | exr_path: &Path, | ||
| 451 | layer_name: Option<&str>, | ||
| 452 | matte_list: &str, | ||
| 453 | ) -> Option<CryptomatteResult> { | ||
| 454 | use exr::prelude::*; | ||
| 455 | |||
| 456 | let img = read_all_flat_layers_from_file(exr_path).ok()?; | ||
| 457 | |||
| 458 | // 1. Collect Cryptomatte header metadata from image-level and layer-level `other` attributes. | ||
| 459 | let mut crypto_meta: BTreeMap<String, CryptoLayerMeta> = BTreeMap::new(); | ||
| 460 | collect_crypto_metadata_from_map(&img.attributes.other, &mut crypto_meta); | ||
| 461 | for layer in &img.layer_data { | ||
| 462 | collect_crypto_metadata_from_map(&layer.attributes.other, &mut crypto_meta); | ||
| 463 | } | ||
| 464 | |||
| 465 | // 2. Select target Cryptomatte layer and manifest. | ||
| 466 | let req_layer = layer_name.map(str::trim).filter(|s| !s.is_empty()); | ||
| 467 | let selected_meta: Option<&CryptoLayerMeta> = if let Some(req) = req_layer { | ||
| 468 | crypto_meta | ||
| 469 | .values() | ||
| 470 | .find(|m| m.name.as_deref() == Some(req)) | ||
| 471 | .or_else(|| { | ||
| 472 | crypto_meta | ||
| 473 | .values() | ||
| 474 | .find(|m| m.name.as_deref().is_some_and(|n| prefix_matches(n, req))) | ||
| 475 | }) | ||
| 476 | } else { | ||
| 477 | crypto_meta | ||
| 478 | .values() | ||
| 479 | .find(|m| m.name.as_deref().is_some_and(|n| !n.is_empty())) | ||
| 480 | }; | ||
| 481 | |||
| 482 | let selected_prefix: String = if let Some(name) = selected_meta.and_then(|m| m.name.clone()) { | ||
| 483 | name | ||
| 484 | } else if let Some(req) = req_layer { | ||
| 485 | req.to_string() | ||
| 486 | } else { | ||
| 487 | // Fallback: infer first rank-00 prefix from channels. | ||
| 488 | let mut inferred = None; | ||
| 489 | 'outer: for layer in &img.layer_data { | ||
| 490 | let lname = layer.attributes.layer_name.as_ref().map(|t| t.to_string()); | ||
| 491 | for ch in &layer.channel_data.list { | ||
| 492 | let full = full_channel_name(lname.as_deref(), &ch.name.to_string()); | ||
| 493 | if let Some((prefix, 0, 0)) = split_crypto_rank_channel(&full) { | ||
| 494 | inferred = Some(prefix.to_string()); | ||
| 495 | break 'outer; | ||
| 496 | } | ||
| 497 | } | ||
| 498 | } | ||
| 499 | inferred? | ||
| 500 | }; | ||
| 501 | |||
| 502 | let mut manifest: HashMap<String, u32> = HashMap::new(); | ||
| 503 | if let Some(meta) = selected_meta { | ||
| 504 | if let Some(inline_json) = &meta.manifest { | ||
| 505 | manifest.extend(parse_manifest_json(inline_json)); | ||
| 506 | } | ||
| 507 | if let Some(sidecar) = meta.manif_file.as_deref().filter(|s| !s.is_empty()) { | ||
| 508 | let sidecar_path = exr_path | ||
| 509 | .parent() | ||
| 510 | .map(|p| p.join(sidecar)) | ||
| 511 | .unwrap_or_else(|| Path::new(sidecar).to_path_buf()); | ||
| 512 | if let Ok(sidecar_json) = std::fs::read_to_string(&sidecar_path) { | ||
| 513 | for (k, v) in parse_manifest_json(&sidecar_json) { | ||
| 514 | manifest.entry(k).or_insert(v); | ||
| 515 | } | ||
| 516 | } | ||
| 517 | } | ||
| 518 | } | ||
| 519 | |||
| 520 | // 3. Build target f32 bit-pattern ID set from matte_list. | ||
| 521 | let mut target_ids: HashSet<u32> = HashSet::new(); | ||
| 522 | for token in parse_matte_list(matte_list) { | ||
| 523 | if let Some(hex_val) = parse_hex_literal_token(&token) { | ||
| 524 | target_ids.insert(hex_val); | ||
| 525 | target_ids.insert(crypto_hash_to_float(hex_val).to_bits()); | ||
| 526 | continue; | ||
| 527 | } | ||
| 528 | if token.contains('*') || token.contains('?') { | ||
| 529 | for (name, &h) in &manifest { | ||
| 530 | if glob_match(&token, name) { | ||
| 531 | target_ids.insert(crypto_hash_to_float(h).to_bits()); | ||
| 532 | } | ||
| 533 | } | ||
| 534 | continue; | ||
| 535 | } | ||
| 536 | if let Some(&h) = manifest.get(&token) { | ||
| 537 | target_ids.insert(crypto_hash_to_float(h).to_bits()); | ||
| 538 | } | ||
| 539 | let direct_hash = murmur3_32(token.as_bytes(), 0); | ||
| 540 | target_ids.insert(crypto_hash_to_float(direct_hash).to_bits()); | ||
| 541 | } | ||
| 542 | |||
| 543 | // 4. Gather rank channel groups (<prefix>00 .. <prefix>09) across all flat layers. | ||
| 544 | let mut dims: Option<(usize, usize)> = None; | ||
| 545 | let mut ranks: BTreeMap<u8, [Option<Vec<f32>>; 4]> = BTreeMap::new(); | ||
| 546 | |||
| 547 | for layer in &img.layer_data { | ||
| 548 | let lw = layer.size.width(); | ||
| 549 | let lh = layer.size.height(); | ||
| 550 | if lw == 0 || lh == 0 { | ||
| 551 | continue; | ||
| 552 | } | ||
| 553 | let lname = layer.attributes.layer_name.as_ref().map(|t| t.to_string()); | ||
| 554 | for ch in &layer.channel_data.list { | ||
| 555 | let full = full_channel_name(lname.as_deref(), &ch.name.to_string()); | ||
| 556 | let Some((prefix, rank, comp_idx)) = split_crypto_rank_channel(&full) else { | ||
| 557 | continue; | ||
| 558 | }; | ||
| 559 | if rank > 9 || !prefix_matches(prefix, &selected_prefix) { | ||
| 560 | continue; | ||
| 561 | } | ||
| 562 | if let Some((w, h)) = dims { | ||
| 563 | if lw != w || lh != h { | ||
| 564 | continue; | ||
| 565 | } | ||
| 566 | } else { | ||
| 567 | dims = Some((lw, lh)); | ||
| 568 | } | ||
| 569 | let vals: Vec<f32> = ch.sample_data.values_as_f32().collect(); | ||
| 570 | if vals.len() == lw * lh { | ||
| 571 | let slots = ranks.entry(rank).or_insert_with(|| [None, None, None, None]); | ||
| 572 | if slots[comp_idx].is_none() { | ||
| 573 | slots[comp_idx] = Some(vals); | ||
| 574 | } | ||
| 575 | } | ||
| 576 | } | ||
| 577 | } | ||
| 578 | |||
| 579 | let (w, h) = dims?; | ||
| 580 | let pixel_count = w * h; | ||
| 581 | let mut matte = vec![0.0_f32; pixel_count]; | ||
| 582 | |||
| 583 | if target_ids.is_empty() { | ||
| 584 | return Some(CryptomatteResult { | ||
| 585 | size: [w as u32, h as u32], | ||
| 586 | matte, | ||
| 587 | }); | ||
| 588 | } | ||
| 589 | |||
| 590 | // 5. Accumulate coverage across all rank (ID, coverage) pairs. | ||
| 591 | for slots in ranks.values() { | ||
| 592 | if let (Some(ids), Some(covs)) = (&slots[0], &slots[1]) { | ||
| 593 | for i in 0..pixel_count { | ||
| 594 | if target_ids.contains(&ids[i].to_bits()) { | ||
| 595 | matte[i] += covs[i]; | ||
| 596 | } | ||
| 597 | } | ||
| 598 | } | ||
| 599 | if let (Some(ids), Some(covs)) = (&slots[2], &slots[3]) { | ||
| 600 | for i in 0..pixel_count { | ||
| 601 | if target_ids.contains(&ids[i].to_bits()) { | ||
| 602 | matte[i] += covs[i]; | ||
| 603 | } | ||
| 604 | } | ||
| 605 | } | ||
| 606 | } | ||
| 607 | |||
| 608 | for v in &mut matte { | ||
| 609 | *v = if v.is_nan() { 0.0 } else { v.clamp(0.0, 1.0) }; | ||
| 610 | } | ||
| 611 | |||
| 612 | Some(CryptomatteResult { | ||
| 613 | size: [w as u32, h as u32], | ||
| 614 | matte, | ||
| 615 | }) | ||
| 616 | } | ||
| 617 | |||
| 618 | #[cfg(test)] | ||
| 619 | mod tests { | ||
| 620 | use super::*; | ||
| 621 | use crate::media::MediaCache; | ||
| 622 | use model::ClipSpec; | ||
| 623 | |||
| 624 | #[test] | ||
| 625 | fn test_murmur3_and_crypto_hash_to_float() { | ||
| 626 | // Known MurmurHash3-32 (seed = 0) test vectors from the Cryptomatte / SMHasher specs. | ||
| 627 | assert_eq!(murmur3_32(b"", 0), 0x0000_0000); | ||
| 628 | assert_eq!(murmur3_32(b"hello", 0), 0x248b_fa47); | ||
| 629 | assert_eq!(murmur3_32(b"bunny", 0), 0x1385_1a76); | ||
| 630 | assert_eq!( | ||
| 631 | murmur3_32(b"The quick brown fox jumps over the lazy dog", 0), | ||
| 632 | 0x2e4f_f723 | ||
| 633 | ); | ||
| 634 | |||
| 635 | // Normal exponent (not 0 and not 255) is preserved bit-for-bit. | ||
| 636 | let hello_hash = murmur3_32(b"hello", 0); | ||
| 637 | assert_eq!(crypto_hash_to_float(hello_hash).to_bits(), hello_hash); | ||
| 638 | |||
| 639 | let bunny_hash = murmur3_32(b"bunny", 0); | ||
| 640 | assert_eq!(crypto_hash_to_float(bunny_hash).to_bits(), bunny_hash); | ||
| 641 | |||
| 642 | // Exponent == 0 (subnormal / zero) must flip bit 23 so exponent becomes 1. | ||
| 643 | let zero_exp_pos: u32 = 0x0012_3456; | ||
| 644 | let f_pos = crypto_hash_to_float(zero_exp_pos); | ||
| 645 | assert_eq!(f_pos.to_bits(), zero_exp_pos ^ (1 << 23)); | ||
| 646 | assert_eq!((f_pos.to_bits() >> 23) & 0xFF, 1); | ||
| 647 | assert!(f_pos.is_normal()); | ||
| 648 | |||
| 649 | let zero_exp_neg: u32 = 0x8000_0000; | ||
| 650 | let f_neg = crypto_hash_to_float(zero_exp_neg); | ||
| 651 | assert_eq!(f_neg.to_bits(), zero_exp_neg ^ (1 << 23)); | ||
| 652 | assert_eq!((f_neg.to_bits() >> 23) & 0xFF, 1); | ||
| 653 | |||
| 654 | // Exponent == 255 (inf / NaN) must flip bit 23 so exponent becomes 254. | ||
| 655 | let nan_exp: u32 = 0x7f80_1234; | ||
| 656 | let f_nan = crypto_hash_to_float(nan_exp); | ||
| 657 | assert_eq!(f_nan.to_bits(), nan_exp ^ (1 << 23)); | ||
| 658 | assert_eq!((f_nan.to_bits() >> 23) & 0xFF, 254); | ||
| 659 | assert!(f_nan.is_finite()); | ||
| 660 | } | ||
| 661 | |||
| 662 | #[test] | ||
| 663 | fn test_parse_matte_list_and_manifest() { | ||
| 664 | let parsed = parse_matte_list("\"floor\", \"Armature\", \"floor.001\""); | ||
| 665 | assert_eq!(parsed, vec!["floor", "Armature", "floor.001"]); | ||
| 666 | |||
| 667 | let unquoted = parse_matte_list("Hero, Tree\n Rock , "); | ||
| 668 | assert_eq!(unquoted, vec!["Hero", "Tree", "Rock"]); | ||
| 669 | |||
| 670 | let escaped = parse_matte_list("\"obj, with, commas\", \"quote \\\"inside\\\"\""); | ||
| 671 | assert_eq!(escaped, vec!["obj, with, commas", "quote \"inside\""]); | ||
| 672 | |||
| 673 | let manifest_json = r#"{ | ||
| 674 | "Hero": "a1b2c3d4", | ||
| 675 | "Tree \"Oak\"": "00112233", | ||
| 676 | "Path\\Node": "deadbeef", | ||
| 677 | "Unicode\u0041": "01020304" | ||
| 678 | }"#; | ||
| 679 | let manifest = parse_manifest_json(manifest_json); | ||
| 680 | assert_eq!(manifest.len(), 4); | ||
| 681 | assert_eq!(manifest.get("Hero"), Some(&0xa1b2_c3d4)); | ||
| 682 | assert_eq!(manifest.get("Tree \"Oak\""), Some(&0x0011_2233)); | ||
| 683 | assert_eq!(manifest.get("Path\\Node"), Some(&0xdead_beef)); | ||
| 684 | assert_eq!(manifest.get("UnicodeA"), Some(&0x0102_0304)); | ||
| 685 | } | ||
| 686 | |||
| 687 | #[test] | ||
| 688 | fn test_synthetic_hdr_exr_and_cryptomatte() { | ||
| 689 | use exr::prelude::*; | ||
| 690 | |||
| 691 | let w = 4usize; | ||
| 692 | let h = 2usize; | ||
| 693 | let n = w * h; | ||
| 694 | |||
| 695 | let hero_hash = murmur3_32(b"Hero", 0); | ||
| 696 | let tree_hash = murmur3_32(b"Tree", 0); | ||
| 697 | let hero_id = crypto_hash_to_float(hero_hash); | ||
| 698 | let tree_id = crypto_hash_to_float(tree_hash); | ||
| 699 | |||
| 700 | // HDR combined channels: pixel 0 has HDR highlight 3.75, negative value -0.25, and NaN in pixel 1. | ||
| 701 | let mut comb_r = vec![0.5_f32; n]; | ||
| 702 | let mut comb_g = vec![0.25_f32; n]; | ||
| 703 | let mut comb_b = vec![0.125_f32; n]; | ||
| 704 | let comb_a = vec![1.0_f32; n]; | ||
| 705 | comb_r[0] = 3.75; | ||
| 706 | comb_g[0] = -0.25; | ||
| 707 | comb_b[1] = f32::NAN; | ||
| 708 | |||
| 709 | // Cryptomatte rank 00 (R/G = rank 0, B/A = rank 1) and rank 01 (R/G = rank 2, B/A = rank 3). | ||
| 710 | // Pixel 0: anti-aliased edge with Hero (0.7 in rank 0) + Tree (0.3 in rank 1). | ||
| 711 | // Pixel 1: Hero (1.0 in rank 0). | ||
| 712 | // Pixel 2: Tree (0.4 in rank 0) + Hero (0.6 in rank 2 inside CryptoObject01.R/G). | ||
| 713 | let mut c00_r = vec![0.0_f32; n]; | ||
| 714 | let mut c00_g = vec![0.0_f32; n]; | ||
| 715 | let mut c00_b = vec![0.0_f32; n]; | ||
| 716 | let mut c00_a = vec![0.0_f32; n]; | ||
| 717 | |||
| 718 | let mut c01_r = vec![0.0_f32; n]; | ||
| 719 | let mut c01_g = vec![0.0_f32; n]; | ||
| 720 | let c01_b = vec![0.0_f32; n]; | ||
| 721 | let c01_a = vec![0.0_f32; n]; | ||
| 722 | |||
| 723 | // Pixel 0: Hero 0.7 (rank 0), Tree 0.3 (rank 1) | ||
| 724 | c00_r[0] = hero_id; | ||
| 725 | c00_g[0] = 0.7; | ||
| 726 | c00_b[0] = tree_id; | ||
| 727 | c00_a[0] = 0.3; | ||
| 728 | |||
| 729 | // Pixel 1: Hero 1.0 (rank 0) | ||
| 730 | c00_r[1] = hero_id; | ||
| 731 | c00_g[1] = 1.0; | ||
| 732 | |||
| 733 | // Pixel 2: Tree 0.4 (rank 0), Hero 0.6 (rank 2 in CryptoObject01) | ||
| 734 | c00_r[2] = tree_id; | ||
| 735 | c00_g[2] = 0.4; | ||
| 736 | c01_r[2] = hero_id; | ||
| 737 | c01_g[2] = 0.6; | ||
| 738 | |||
| 739 | let channels = AnyChannels::sort(SmallVec::from_vec(vec![ | ||
| 740 | AnyChannel::new("ViewLayer.Combined.R", FlatSamples::F32(comb_r)), | ||
| 741 | AnyChannel::new("ViewLayer.Combined.G", FlatSamples::F32(comb_g)), | ||
| 742 | AnyChannel::new("ViewLayer.Combined.B", FlatSamples::F32(comb_b)), | ||
| 743 | AnyChannel::new("ViewLayer.Combined.A", FlatSamples::F32(comb_a)), | ||
| 744 | AnyChannel::new("ViewLayer.CryptoObject00.R", FlatSamples::F32(c00_r)), | ||
| 745 | AnyChannel::new("ViewLayer.CryptoObject00.G", FlatSamples::F32(c00_g)), | ||
| 746 | AnyChannel::new("ViewLayer.CryptoObject00.B", FlatSamples::F32(c00_b)), | ||
| 747 | AnyChannel::new("ViewLayer.CryptoObject00.A", FlatSamples::F32(c00_a)), | ||
| 748 | AnyChannel::new("ViewLayer.CryptoObject01.R", FlatSamples::F32(c01_r)), | ||
| 749 | AnyChannel::new("ViewLayer.CryptoObject01.G", FlatSamples::F32(c01_g)), | ||
| 750 | AnyChannel::new("ViewLayer.CryptoObject01.B", FlatSamples::F32(c01_b)), | ||
| 751 | AnyChannel::new("ViewLayer.CryptoObject01.A", FlatSamples::F32(c01_a)), | ||
| 752 | ])); | ||
| 753 | |||
| 754 | let manifest_json = format!( | ||
| 755 | r#"{{"Hero":"{:08x}","Tree":"{:08x}"}}"#, | ||
| 756 | hero_hash, tree_hash | ||
| 757 | ); | ||
| 758 | |||
| 759 | let mut layer_attrs = LayerAttributes::default(); | ||
| 760 | layer_attrs.other.insert( | ||
| 761 | Text::new_or_panic("cryptomatte/abcdef0/name"), | ||
| 762 | AttributeValue::Text(Text::new_or_panic("ViewLayer.CryptoObject")), | ||
| 763 | ); | ||
| 764 | layer_attrs.other.insert( | ||
| 765 | Text::new_or_panic("cryptomatte/abcdef0/manifest"), | ||
| 766 | AttributeValue::Text(Text::new_or_panic(&manifest_json)), | ||
| 767 | ); | ||
| 768 | |||
| 769 | let layer = Layer::new( | ||
| 770 | (w, h), | ||
| 771 | layer_attrs, | ||
| 772 | Encoding::FAST_LOSSLESS, | ||
| 773 | channels, | ||
| 774 | ); | ||
| 775 | let image = Image::from_layer(layer); | ||
| 776 | |||
| 777 | let tmp_path = std::env::temp_dir().join(format!( | ||
| 778 | "engine_test_hdr_crypto_{}.exr", | ||
| 779 | std::process::id() | ||
| 780 | )); | ||
| 781 | image | ||
| 782 | .write() | ||
| 783 | .to_file(&tmp_path) | ||
| 784 | .expect("failed to write synthetic EXR"); | ||
| 785 | |||
| 786 | // 1. Verify MediaCache::load_clip preserves unclamped HDR f32 values & sanitizes NaN. | ||
| 787 | let mut cache = MediaCache::new(64); | ||
| 788 | let clip = ClipSpec { | ||
| 789 | filename: tmp_path.to_string_lossy().into_owned(), | ||
| 790 | alternate_filename: None, | ||
| 791 | start_frame: 0, | ||
| 792 | length: Some(1), | ||
| 793 | trim_in: 0, | ||
| 794 | trim_out: 0, | ||
| 795 | global_start: 0, | ||
| 796 | global_end: 0, | ||
| 797 | extend_first: 0, | ||
| 798 | extend_last: 0, | ||
| 799 | loop_clip: false, | ||
| 800 | reverse: false, | ||
| 801 | }; | ||
| 802 | let (_, _, decoded, loaded_from_disk) = cache | ||
| 803 | .load_clip(&clip, 0, false, [None, None, None, None]) | ||
| 804 | .expect("MediaCache::load_clip failed on synthetic EXR"); | ||
| 805 | assert!(loaded_from_disk); | ||
| 806 | assert_eq!(decoded.size, [w as u32, h as u32]); | ||
| 807 | |||
| 808 | let f32_px = decoded | ||
| 809 | .rgba_f32 | ||
| 810 | .as_ref() | ||
| 811 | .expect("EXR must populate rgba_f32"); | ||
| 812 | assert_eq!(f32_px.len(), n * 4); | ||
| 813 | assert!((f32_px[0] - 3.75).abs() < 1e-6, "expected HDR 3.75, got {}", f32_px[0]); | ||
| 814 | assert!((f32_px[1] - (-0.25)).abs() < 1e-6, "expected -0.25, got {}", f32_px[1]); | ||
| 815 | assert!((f32_px[2] - 0.125).abs() < 1e-6); | ||
| 816 | assert!((f32_px[3] - 1.0).abs() < 1e-6); | ||
| 817 | // Pixel 1 blue was NaN -> must be sanitized to 0.0. | ||
| 818 | assert_eq!(f32_px[4 + 2], 0.0); | ||
| 819 | // 8-bit preview should clamp 3.75 -> 255 and -0.25 -> 0. | ||
| 820 | assert_eq!(decoded.rgba[0], 255); | ||
| 821 | assert_eq!(decoded.rgba[1], 0); | ||
| 822 | |||
| 823 | // 2. Verify list_cryptomatte_layers. | ||
| 824 | let layers = list_cryptomatte_layers(&tmp_path); | ||
| 825 | assert_eq!(layers, vec!["ViewLayer.CryptoObject"]); | ||
| 826 | |||
| 827 | // 3. Verify extract_cryptomatte for Hero, Tree, and both (also testing suffix layer match). | ||
| 828 | let res_hero = extract_cryptomatte(&tmp_path, Some("CryptoObject"), "\"Hero\"") | ||
| 829 | .expect("extract_cryptomatte Hero failed"); | ||
| 830 | assert_eq!(res_hero.size, [w as u32, h as u32]); | ||
| 831 | assert!((res_hero.matte[0] - 0.7).abs() < 1e-6); | ||
| 832 | assert!((res_hero.matte[1] - 1.0).abs() < 1e-6); | ||
| 833 | assert!((res_hero.matte[2] - 0.6).abs() < 1e-6); | ||
| 834 | assert!((res_hero.matte[3] - 0.0).abs() < 1e-6); | ||
| 835 | |||
| 836 | let res_tree = extract_cryptomatte(&tmp_path, Some("ViewLayer.CryptoObject"), "\"Tree\"") | ||
| 837 | .expect("extract_cryptomatte Tree failed"); | ||
| 838 | assert!((res_tree.matte[0] - 0.3).abs() < 1e-6); | ||
| 839 | assert!((res_tree.matte[1] - 0.0).abs() < 1e-6); | ||
| 840 | assert!((res_tree.matte[2] - 0.4).abs() < 1e-6); | ||
| 841 | |||
| 842 | let res_both = extract_cryptomatte(&tmp_path, None, "\"Hero\", \"Tree\"") | ||
| 843 | .expect("extract_cryptomatte both failed"); | ||
| 844 | assert!((res_both.matte[0] - 1.0).abs() < 1e-6); | ||
| 845 | assert!((res_both.matte[1] - 1.0).abs() < 1e-6); | ||
| 846 | assert!((res_both.matte[2] - 1.0).abs() < 1e-6); | ||
| 847 | assert!((res_both.matte[3] - 0.0).abs() < 1e-6); | ||
| 848 | |||
| 849 | // Wildcard matching against manifest keys. | ||
| 850 | let res_wild = extract_cryptomatte(&tmp_path, None, "Her*") | ||
| 851 | .expect("extract_cryptomatte wildcard failed"); | ||
| 852 | assert!((res_wild.matte[0] - 0.7).abs() < 1e-6); | ||
| 853 | |||
| 854 | let _ = std::fs::remove_file(&tmp_path); | ||
| 855 | } | ||
| 856 | } | ||
crates/engine/src/eval.rs+647-34| ... | @@ -332,6 +332,9 @@ pub struct Engine { | ... | @@ -332,6 +332,9 @@ pub struct Engine { |
| 332 | pipelines_f32: std::sync::OnceLock<Pipelines>, | 332 | pipelines_f32: std::sync::OnceLock<Pipelines>, |
| 333 | supports_f32_filter: bool, | 333 | supports_f32_filter: bool, |
| 334 | scene3d: crate::scene3d::Scene3DRenderer, | 334 | scene3d: crate::scene3d::Scene3DRenderer, |
| 335 | optflow: std::sync::OnceLock<crate::optflow::OpticalFlowPipelines>, | ||
| 336 | particles: crate::particles::ParticleCache, | ||
| 337 | sprite_cache: HashMap<(NodeId, u64, i64), crate::particles::SpriteImage>, | ||
| 335 | dummy: CachedTexture, | 338 | dummy: CachedTexture, |
| 336 | pub cache: NodeCache, | 339 | pub cache: NodeCache, |
| 337 | pub media: MediaCache, | 340 | pub media: MediaCache, |
| ... | @@ -373,6 +376,9 @@ impl Engine { | ... | @@ -373,6 +376,9 @@ impl Engine { |
| 373 | pipelines_f32: std::sync::OnceLock::new(), | 376 | pipelines_f32: std::sync::OnceLock::new(), |
| 374 | supports_f32_filter, | 377 | supports_f32_filter, |
| 375 | scene3d, | 378 | scene3d, |
| 379 | optflow: std::sync::OnceLock::new(), | ||
| 380 | particles: crate::particles::ParticleCache::default(), | ||
| 381 | sprite_cache: HashMap::new(), | ||
| 376 | dummy, | 382 | dummy, |
| 377 | cache: NodeCache::new(2048), // 2 GB GPU texture cache cap (prevents thrashing on 100+ node diamond DAGs) | 383 | cache: NodeCache::new(2048), // 2 GB GPU texture cache cap (prevents thrashing on 100+ node diamond DAGs) |
| 378 | media: MediaCache::new(1024), | 384 | media: MediaCache::new(1024), |
| ... | @@ -486,6 +492,8 @@ impl Engine { | ... | @@ -486,6 +492,8 @@ impl Engine { |
| 486 | pub fn bust_all_caches(&mut self) { | 492 | pub fn bust_all_caches(&mut self) { |
| 487 | self.cache.bust_all(); | 493 | self.cache.bust_all(); |
| 488 | self.media.clear(); | 494 | self.media.clear(); |
| 495 | self.particles.clear(); | ||
| 496 | self.sprite_cache.clear(); | ||
| 489 | } | 497 | } |
| 490 | 498 | ||
| 491 | pub fn bust_gpu_cache(&mut self) { | 499 | pub fn bust_gpu_cache(&mut self) { |
| ... | @@ -717,7 +725,12 @@ impl Engine { | ... | @@ -717,7 +725,12 @@ impl Engine { |
| 717 | let comp_dims = self.scaled_dims(comp.width, comp.height); | 725 | let comp_dims = self.scaled_dims(comp.width, comp.height); |
| 718 | 726 | ||
| 719 | // Bypass (`PassThrough`) or passthrough utility nodes | 727 | // Bypass (`PassThrough`) or passthrough utility nodes |
| 720 | if node.bypassed || matches!(node.kind.as_str(), "Saver" | "PipeRouter" | "Fuse.Wireless" | "Tracker") { | 728 | if node.bypassed |
| 729 | || matches!( | ||
| 730 | node.kind.as_str(), | ||
| 731 | "Saver" | "PipeRouter" | "Fuse.Wireless" | "Tracker" | "Dimension.OpticalFlow" | "OpticalFlow" | ||
| 732 | ) | ||
| 733 | { | ||
| 721 | let port = default_main_input_port(&node.kind); | 734 | let port = default_main_input_port(&node.kind); |
| 722 | if let Some(src_id) = node.connected_node(port).and_then(|s| comp.find_node(s)) { | 735 | if let Some(src_id) = node.connected_node(port).and_then(|s| comp.find_node(s)) { |
| 723 | return self.eval_node(comp, src_id, time, enc, visiting, stats); | 736 | return self.eval_node(comp, src_id, time, enc, visiting, stats); |
| ... | @@ -744,6 +757,54 @@ impl Engine { | ... | @@ -744,6 +757,54 @@ impl Engine { |
| 744 | if node.kind == "TimeStretcher" { | 757 | if node.kind == "TimeStretcher" { |
| 745 | let remapped = comp.eval_number(node, "SourceTime", time, time, &self.expr); | 758 | let remapped = comp.eval_number(node, "SourceTime", time, time, &self.expr); |
| 746 | if let Some(src_id) = node.connected_node("Input").and_then(|s| comp.find_node(s)) { | 759 | if let Some(src_id) = node.connected_node("Input").and_then(|s| comp.find_node(s)) { |
| 760 | let interp = comp | ||
| 761 | .eval_number(node, "InterpolateBetweenFrames", time, 1.0, &self.expr) | ||
| 762 | .round() as i32; | ||
| 763 | let f0 = remapped.floor(); | ||
| 764 | let frac = (remapped - f0) as f32; | ||
| 765 | if interp >= 1 && frac > 1e-3 && frac < 1.0 - 1e-3 { | ||
| 766 | let src_node = comp.node(src_id); | ||
| 767 | let has_optflow = matches!(src_node.kind.as_str(), "Dimension.OpticalFlow" | "OpticalFlow"); | ||
| 768 | let eval_src_id = if has_optflow { | ||
| 769 | src_node | ||
| 770 | .connected_node("Input") | ||
| 771 | .and_then(|s| comp.find_node(s)) | ||
| 772 | .unwrap_or(src_id) | ||
| 773 | } else { | ||
| 774 | src_id | ||
| 775 | }; | ||
| 776 | let tex_a = self.eval_node(comp, eval_src_id, f0, enc, visiting, stats); | ||
| 777 | let tex_b = self.eval_node(comp, eval_src_id, f0 + 1.0, enc, visiting, stats); | ||
| 778 | let use_flow = interp == 2 && (has_optflow || self.hiq); | ||
| 779 | let dst_depth = self.node_depth(comp, node, time, Some(tex_a.depth.max(tex_b.depth))); | ||
| 780 | let mut h = DefaultHasher::new(); | ||
| 781 | self.cache.gpu_salt.hash(&mut h); | ||
| 782 | self.cache.node_salt(node.id).hash(&mut h); | ||
| 783 | "TimeStretcherInterp".hash(&mut h); | ||
| 784 | use_flow.hash(&mut h); | ||
| 785 | tex_a.content_hash.hash(&mut h); | ||
| 786 | tex_b.content_hash.hash(&mut h); | ||
| 787 | ((frac * 1000.0).round() as i32).hash(&mut h); | ||
| 788 | dst_depth.hash(&mut h); | ||
| 789 | let key = h.finish(); | ||
| 790 | if let Some(hit) = self.cache.get(key, node.id, frame_i) { | ||
| 791 | stats.cache_hits += 1; | ||
| 792 | return hit; | ||
| 793 | } | ||
| 794 | stats.cache_misses += 1; | ||
| 795 | stats.nodes_evaluated += 1; | ||
| 796 | let fmt = self.texture_format_for(self.effective_depth(dst_depth)); | ||
| 797 | let optflow = self.optflow.get_or_init(|| crate::optflow::OpticalFlowPipelines::new(&self.device)); | ||
| 798 | let mut out = if use_flow { | ||
| 799 | optflow.interpolate_flow(&self.device, &self.queue, enc, &tex_a, &tex_b, frac, fmt) | ||
| 800 | } else { | ||
| 801 | optflow.blend_frames(&self.device, &self.queue, enc, &tex_a, &tex_b, frac, fmt) | ||
| 802 | }; | ||
| 803 | out.depth = self.effective_depth(dst_depth); | ||
| 804 | out.content_hash = key; | ||
| 805 | self.cache.insert(key, out.clone(), node.id, frame_i); | ||
| 806 | return out; | ||
| 807 | } | ||
| 747 | return self.eval_node(comp, src_id, remapped, enc, visiting, stats); | 808 | return self.eval_node(comp, src_id, remapped, enc, visiting, stats); |
| 748 | } | 809 | } |
| 749 | return self.dummy.clone(); | 810 | return self.dummy.clone(); |
| ... | @@ -811,6 +872,16 @@ impl Engine { | ... | @@ -811,6 +872,16 @@ impl Engine { |
| 811 | "Fuse.Colorize" => self.eval_colorize(comp, node, time, frame_i, enc, visiting, stats), | 872 | "Fuse.Colorize" => self.eval_colorize(comp, node, time, frame_i, enc, visiting, stats), |
| 812 | "Fuse.Outline" => self.eval_outline(comp, node, time, frame_i, enc, visiting, stats), | 873 | "Fuse.Outline" => self.eval_outline(comp, node, time, frame_i, enc, visiting, stats), |
| 813 | "Fuse.XfChroma" => self.eval_xf_chroma(comp, node, time, frame_i, enc, visiting, stats), | 874 | "Fuse.XfChroma" => self.eval_xf_chroma(comp, node, time, frame_i, enc, visiting, stats), |
| 875 | "Fuse.Cryptomatte" | "Cryptomatte" => self.eval_cryptomatte(comp, node, time, frame_i, enc, visiting, stats), | ||
| 876 | "pRender" => self.eval_p_render(comp, node, time, frame_i, comp_dims, enc, visiting, stats), | ||
| 877 | "pEmitter" | ||
| 878 | | "pPointForce" | ||
| 879 | | "pDirectionalForce" | ||
| 880 | | "pTurbulence" | ||
| 881 | | "pDrag" | ||
| 882 | | "pFriction" | ||
| 883 | | "pKill" | ||
| 884 | | "pMerge" => self.dummy.clone(), | ||
| 814 | "Custom" => self.eval_custom(comp, node, time, frame_i, comp_dims, enc, visiting, stats), | 885 | "Custom" => self.eval_custom(comp, node, time, frame_i, comp_dims, enc, visiting, stats), |
| 815 | "Renderer3D" => self.eval_renderer3d(comp, node, time, frame_i, comp_dims, enc, visiting, stats), | 886 | "Renderer3D" => self.eval_renderer3d(comp, node, time, frame_i, comp_dims, enc, visiting, stats), |
| 816 | other => { | 887 | other => { |
| ... | @@ -908,7 +979,23 @@ impl Engine { | ... | @@ -908,7 +979,23 @@ impl Engine { |
| 908 | } | 979 | } |
| 909 | let (mask, mask_inv) = self.eval_mask_input_sized(comp, node, time, Some(self.scaled_dims(img.size[0], img.size[1])), enc, visiting, stats); | 980 | let (mask, mask_inv) = self.eval_mask_input_sized(comp, node, time, Some(self.scaled_dims(img.size[0], img.size[1])), enc, visiting, stats); |
| 910 | let mask_hash = mask.as_ref().map_or(0, |m| m.content_hash); | 981 | let mask_hash = mask.as_ref().map_or(0, |m| m.content_hash); |
| 911 | let dst_depth = self.node_depth(comp, node, time, None); | 982 | // OpenEXR clips natively produce float HDR in HiQ unless Loader explicitly forces int8/int16. |
| 983 | let explicit_depth = comp | ||
| 984 | .eval_number(node, "Depth", time, 0.0, &self.expr) | ||
| 985 | .round() as i32; | ||
| 986 | let native_depth = if self.hiq && img.rgba_f32.is_some() { | ||
| 987 | BitDepth::from_fusion_depth(explicit_depth).unwrap_or_else(|| { | ||
| 988 | if comp.depth_full == BitDepth::Float32 { | ||
| 989 | BitDepth::Float32 | ||
| 990 | } else { | ||
| 991 | BitDepth::Float16 | ||
| 992 | } | ||
| 993 | }) | ||
| 994 | } else { | ||
| 995 | self.node_depth(comp, node, time, None) | ||
| 996 | }; | ||
| 997 | let dst_depth = self.effective_depth(native_depth); | ||
| 998 | let use_float_upload = self.hiq && dst_depth.is_float() && img.rgba_f32.is_some(); | ||
| 912 | let target_size = self.scaled_dims(img.size[0], img.size[1]); | 999 | let target_size = self.scaled_dims(img.size[0], img.size[1]); |
| 913 | let mut h = DefaultHasher::new(); | 1000 | let mut h = DefaultHasher::new(); |
| 914 | self.cache.gpu_salt.hash(&mut h); | 1001 | self.cache.gpu_salt.hash(&mut h); |
| ... | @@ -921,6 +1008,7 @@ impl Engine { | ... | @@ -921,6 +1008,7 @@ impl Engine { |
| 921 | mask_hash.hash(&mut h); | 1008 | mask_hash.hash(&mut h); |
| 922 | mask_inv.hash(&mut h); | 1009 | mask_inv.hash(&mut h); |
| 923 | dst_depth.hash(&mut h); | 1010 | dst_depth.hash(&mut h); |
| 1011 | use_float_upload.hash(&mut h); | ||
| 924 | let key = h.finish(); | 1012 | let key = h.finish(); |
| 925 | 1013 | ||
| 926 | if let Some(hit) = self.cache.get(key, node.id, frame_i) { | 1014 | if let Some(hit) = self.cache.get(key, node.id, frame_i) { |
| ... | @@ -930,25 +1018,65 @@ impl Engine { | ... | @@ -930,25 +1018,65 @@ impl Engine { |
| 930 | stats.cache_misses += 1; | 1018 | stats.cache_misses += 1; |
| 931 | stats.nodes_evaluated += 1; | 1019 | stats.nodes_evaluated += 1; |
| 932 | 1020 | ||
| 933 | let need_depth_conv = dst_depth != BitDepth::Int8; | 1021 | let need_depth_conv = !use_float_upload && dst_depth != BitDepth::Int8; |
| 934 | let need_post = target_size != img.size || mask.is_some() || need_depth_conv; | 1022 | let need_post = target_size != img.size || mask.is_some() || need_depth_conv; |
| 935 | let full_tex = create_texture(&self.device, img.size, if need_post { 0 } else { key }); | 1023 | let full_tex = if use_float_upload { |
| 936 | self.queue.write_texture( | 1024 | let f32_px = img.rgba_f32.as_ref().expect("checked is_some"); |
| 937 | full_tex.texture.as_image_copy(), | 1025 | let tex = self.alloc_tex(img.size, dst_depth, if need_post { 0 } else { key }); |
| 938 | &img.rgba, | 1026 | if tex.format == wgpu::TextureFormat::Rgba32Float { |
| 939 | wgpu::TexelCopyBufferLayout { | 1027 | self.queue.write_texture( |
| 940 | offset: 0, | 1028 | tex.texture.as_image_copy(), |
| 941 | bytes_per_row: Some(img.size[0] * 4), | 1029 | bytemuck::cast_slice(f32_px), |
| 942 | rows_per_image: Some(img.size[1]), | 1030 | wgpu::TexelCopyBufferLayout { |
| 943 | }, | 1031 | offset: 0, |
| 944 | wgpu::Extent3d { | 1032 | bytes_per_row: Some(img.size[0] * 16), |
| 945 | width: img.size[0], | 1033 | rows_per_image: Some(img.size[1]), |
| 946 | height: img.size[1], | 1034 | }, |
| 947 | depth_or_array_layers: 1, | 1035 | wgpu::Extent3d { |
| 948 | }, | 1036 | width: img.size[0], |
| 949 | ); | 1037 | height: img.size[1], |
| 1038 | depth_or_array_layers: 1, | ||
| 1039 | }, | ||
| 1040 | ); | ||
| 1041 | } else { | ||
| 1042 | let f16_bits = img.rgba_f16.as_ref().expect("EXR populates rgba_f16"); | ||
| 1043 | self.queue.write_texture( | ||
| 1044 | tex.texture.as_image_copy(), | ||
| 1045 | bytemuck::cast_slice(f16_bits), | ||
| 1046 | wgpu::TexelCopyBufferLayout { | ||
| 1047 | offset: 0, | ||
| 1048 | bytes_per_row: Some(img.size[0] * 8), | ||
| 1049 | rows_per_image: Some(img.size[1]), | ||
| 1050 | }, | ||
| 1051 | wgpu::Extent3d { | ||
| 1052 | width: img.size[0], | ||
| 1053 | height: img.size[1], | ||
| 1054 | depth_or_array_layers: 1, | ||
| 1055 | }, | ||
| 1056 | ); | ||
| 1057 | } | ||
| 1058 | tex | ||
| 1059 | } else { | ||
| 1060 | let tex = create_texture(&self.device, img.size, if need_post { 0 } else { key }); | ||
| 1061 | self.queue.write_texture( | ||
| 1062 | tex.texture.as_image_copy(), | ||
| 1063 | &img.rgba, | ||
| 1064 | wgpu::TexelCopyBufferLayout { | ||
| 1065 | offset: 0, | ||
| 1066 | bytes_per_row: Some(img.size[0] * 4), | ||
| 1067 | rows_per_image: Some(img.size[1]), | ||
| 1068 | }, | ||
| 1069 | wgpu::Extent3d { | ||
| 1070 | width: img.size[0], | ||
| 1071 | height: img.size[1], | ||
| 1072 | depth_or_array_layers: 1, | ||
| 1073 | }, | ||
| 1074 | ); | ||
| 1075 | tex | ||
| 1076 | }; | ||
| 1077 | let work_depth = if use_float_upload { dst_depth } else { BitDepth::Int8 }; | ||
| 950 | let base_tex = if target_size != img.size { | 1078 | let base_tex = if target_size != img.size { |
| 951 | let scaled = create_texture(&self.device, target_size, if mask.is_some() || need_depth_conv { 0 } else { key }); | 1079 | let scaled = self.alloc_tex(target_size, work_depth, if mask.is_some() || need_depth_conv { 0 } else { key }); |
| 952 | let mut u = UniformParams::default(); | 1080 | let mut u = UniformParams::default(); |
| 953 | u.p[0] = [1.0, 1.0, 0.0, 0.0]; | 1081 | u.p[0] = [1.0, 1.0, 0.0, 0.0]; |
| 954 | self.dispatch_op(enc, ShaderOp::DisplayBlit, &full_tex.view, &self.dummy.view, &self.dummy.view, &scaled, &u); | 1082 | self.dispatch_op(enc, ShaderOp::DisplayBlit, &full_tex.view, &self.dummy.view, &self.dummy.view, &scaled, &u); |
| ... | @@ -957,7 +1085,7 @@ impl Engine { | ... | @@ -957,7 +1085,7 @@ impl Engine { |
| 957 | full_tex | 1085 | full_tex |
| 958 | }; | 1086 | }; |
| 959 | let masked_tex = if let Some(m) = mask { | 1087 | let masked_tex = if let Some(m) = mask { |
| 960 | let masked = create_texture(&self.device, target_size, if need_depth_conv { 0 } else { key }); | 1088 | let masked = self.alloc_tex(target_size, work_depth, if need_depth_conv { 0 } else { key }); |
| 961 | let mut u = UniformParams::default(); | 1089 | let mut u = UniformParams::default(); |
| 962 | u.p[0] = [if mask_inv { 1.0 } else { 0.0 }, 0.0, 0.0, 0.0]; | 1090 | u.p[0] = [if mask_inv { 1.0 } else { 0.0 }, 0.0, 0.0, 0.0]; |
| 963 | self.dispatch_op(enc, ShaderOp::MaskApply, &base_tex.view, &self.dummy.view, &m.view, &masked, &u); | 1091 | self.dispatch_op(enc, ShaderOp::MaskApply, &base_tex.view, &self.dummy.view, &m.view, &masked, &u); |
| ... | @@ -977,6 +1105,250 @@ impl Engine { | ... | @@ -977,6 +1105,250 @@ impl Engine { |
| 977 | tex | 1105 | tex |
| 978 | } | 1106 | } |
| 979 | 1107 | ||
| 1108 | fn resolve_upstream_exr_path(&self, comp: &Comp, start_id: NodeId, time: f64) -> Option<std::path::PathBuf> { | ||
| 1109 | let mut cur_id = start_id; | ||
| 1110 | let mut cur_time = time; | ||
| 1111 | for _ in 0..16 { | ||
| 1112 | let n = comp.node(cur_id); | ||
| 1113 | match n.kind.as_str() { | ||
| 1114 | "Loader" => { | ||
| 1115 | let clip = n.clips.first()?; | ||
| 1116 | let resolved = crate::media::resolve_clip_path(clip, cur_time.round() as i64)?; | ||
| 1117 | if resolved | ||
| 1118 | .extension() | ||
| 1119 | .and_then(|e| e.to_str()) | ||
| 1120 | .is_some_and(|e| e.eq_ignore_ascii_case("exr")) | ||
| 1121 | { | ||
| 1122 | return Some(resolved); | ||
| 1123 | } | ||
| 1124 | return None; | ||
| 1125 | } | ||
| 1126 | "TimeStretcher" => { | ||
| 1127 | cur_time = comp.eval_number(n, "SourceTime", cur_time, cur_time, &self.expr); | ||
| 1128 | cur_id = n.connected_node("Input").and_then(|s| comp.find_node(s))?; | ||
| 1129 | } | ||
| 1130 | "TimeSpeed" => { | ||
| 1131 | let speed = comp.eval_number(n, "Speed", cur_time, 1.0, &self.expr); | ||
| 1132 | let delay = comp.eval_number(n, "Delay", cur_time, 0.0, &self.expr); | ||
| 1133 | cur_time = (cur_time - delay) * speed; | ||
| 1134 | cur_id = n.connected_node("Input").and_then(|s| comp.find_node(s))?; | ||
| 1135 | } | ||
| 1136 | "PipeRouter" | "Fuse.Wireless" | "Dimension.OpticalFlow" | "OpticalFlow" | "GamutConvert" | ||
| 1137 | | "ChangeDepth" | "BrightnessContrast" | "ColorCorrector" | "ColorGain" => { | ||
| 1138 | cur_id = n.connected_node("Input").and_then(|s| comp.find_node(s))?; | ||
| 1139 | } | ||
| 1140 | _ => return None, | ||
| 1141 | } | ||
| 1142 | } | ||
| 1143 | None | ||
| 1144 | } | ||
| 1145 | |||
| 1146 | #[allow(clippy::too_many_arguments)] | ||
| 1147 | fn eval_cryptomatte( | ||
| 1148 | &mut self, | ||
| 1149 | comp: &Comp, | ||
| 1150 | node: &Node, | ||
| 1151 | time: f64, | ||
| 1152 | frame_i: i64, | ||
| 1153 | enc: &mut wgpu::CommandEncoder, | ||
| 1154 | visiting: &mut HashSet<(NodeId, i64)>, | ||
| 1155 | stats: &mut EvalStats, | ||
| 1156 | ) -> CachedTexture { | ||
| 1157 | let Some(src_id) = node.connected_node("Input").and_then(|s| comp.find_node(s)) else { | ||
| 1158 | return self.dummy.clone(); | ||
| 1159 | }; | ||
| 1160 | let src = self.eval_node(comp, src_id, time, enc, visiting, stats); | ||
| 1161 | let matte_list = comp.eval_text(node, "MatteList", time, "", &self.expr); | ||
| 1162 | let layer_name = comp.eval_text(node, "LayerName", time, "", &self.expr); | ||
| 1163 | let matte_only = comp.eval_number(node, "MatteOnly", time, 0.0, &self.expr) > 0.5; | ||
| 1164 | let Some(exr_path) = self.resolve_upstream_exr_path(comp, src_id, time) else { | ||
| 1165 | return src; | ||
| 1166 | }; | ||
| 1167 | |||
| 1168 | let dst_depth = self.node_depth(comp, node, time, Some(src.depth)); | ||
| 1169 | let mut h = DefaultHasher::new(); | ||
| 1170 | self.cache.gpu_salt.hash(&mut h); | ||
| 1171 | self.cache.node_salt(node.id).hash(&mut h); | ||
| 1172 | "Fuse.Cryptomatte".hash(&mut h); | ||
| 1173 | src.content_hash.hash(&mut h); | ||
| 1174 | exr_path.hash(&mut h); | ||
| 1175 | matte_list.hash(&mut h); | ||
| 1176 | layer_name.hash(&mut h); | ||
| 1177 | matte_only.hash(&mut h); | ||
| 1178 | dst_depth.hash(&mut h); | ||
| 1179 | let key = h.finish(); | ||
| 1180 | |||
| 1181 | if let Some(hit) = self.cache.get(key, node.id, frame_i) { | ||
| 1182 | stats.cache_hits += 1; | ||
| 1183 | return hit; | ||
| 1184 | } | ||
| 1185 | stats.cache_misses += 1; | ||
| 1186 | stats.nodes_evaluated += 1; | ||
| 1187 | |||
| 1188 | let layer_opt = if layer_name.trim().is_empty() { | ||
| 1189 | None | ||
| 1190 | } else { | ||
| 1191 | Some(layer_name.as_str()) | ||
| 1192 | }; | ||
| 1193 | let Some(cm) = crate::cryptomatte::extract_cryptomatte(&exr_path, layer_opt, &matte_list) else { | ||
| 1194 | return src; | ||
| 1195 | }; | ||
| 1196 | |||
| 1197 | let mut matte_rgba = vec![0u8; (cm.size[0] as usize) * (cm.size[1] as usize) * 4]; | ||
| 1198 | for (i, &m) in cm.matte.iter().enumerate() { | ||
| 1199 | let b = (m.clamp(0.0, 1.0) * 255.0 + 0.5) as u8; | ||
| 1200 | matte_rgba[i * 4] = b; | ||
| 1201 | matte_rgba[i * 4 + 1] = b; | ||
| 1202 | matte_rgba[i * 4 + 2] = b; | ||
| 1203 | matte_rgba[i * 4 + 3] = b; | ||
| 1204 | } | ||
| 1205 | |||
| 1206 | let matte_full = create_texture(&self.device, cm.size, 0); | ||
| 1207 | self.queue.write_texture( | ||
| 1208 | matte_full.texture.as_image_copy(), | ||
| 1209 | &matte_rgba, | ||
| 1210 | wgpu::TexelCopyBufferLayout { | ||
| 1211 | offset: 0, | ||
| 1212 | bytes_per_row: Some(cm.size[0] * 4), | ||
| 1213 | rows_per_image: Some(cm.size[1]), | ||
| 1214 | }, | ||
| 1215 | wgpu::Extent3d { | ||
| 1216 | width: cm.size[0], | ||
| 1217 | height: cm.size[1], | ||
| 1218 | depth_or_array_layers: 1, | ||
| 1219 | }, | ||
| 1220 | ); | ||
| 1221 | |||
| 1222 | let matte_tex = if cm.size != src.size { | ||
| 1223 | let scaled = create_texture(&self.device, src.size, 0); | ||
| 1224 | let mut u = UniformParams::default(); | ||
| 1225 | u.p[0] = [1.0, 1.0, 0.0, 0.0]; | ||
| 1226 | self.dispatch_op(enc, ShaderOp::DisplayBlit, &matte_full.view, &self.dummy.view, &self.dummy.view, &scaled, &u); | ||
| 1227 | scaled | ||
| 1228 | } else { | ||
| 1229 | matte_full | ||
| 1230 | }; | ||
| 1231 | |||
| 1232 | let out = if matte_only { | ||
| 1233 | let dst = self.alloc_tex(src.size, dst_depth, key); | ||
| 1234 | let mut u = UniformParams::default(); | ||
| 1235 | u.p[0] = [1.0, 1.0, 0.0, 0.0]; | ||
| 1236 | self.dispatch_op(enc, ShaderOp::DisplayBlit, &matte_tex.view, &self.dummy.view, &self.dummy.view, &dst, &u); | ||
| 1237 | dst | ||
| 1238 | } else { | ||
| 1239 | let dst = self.alloc_tex(src.size, dst_depth, key); | ||
| 1240 | let mut u = UniformParams::default(); | ||
| 1241 | u.p[0] = [0.0, 0.0, 0.0, 0.0]; | ||
| 1242 | self.dispatch_op(enc, ShaderOp::MaskApply, &src.view, &self.dummy.view, &matte_tex.view, &dst, &u); | ||
| 1243 | dst | ||
| 1244 | }; | ||
| 1245 | self.cache.insert(key, out.clone(), node.id, frame_i); | ||
| 1246 | out | ||
| 1247 | } | ||
| 1248 | |||
| 1249 | #[allow(clippy::too_many_arguments)] | ||
| 1250 | fn eval_p_render( | ||
| 1251 | &mut self, | ||
| 1252 | comp: &Comp, | ||
| 1253 | node: &Node, | ||
| 1254 | time: f64, | ||
| 1255 | frame_i: i64, | ||
| 1256 | comp_dims: [u32; 2], | ||
| 1257 | enc: &mut wgpu::CommandEncoder, | ||
| 1258 | visiting: &mut HashSet<(NodeId, i64)>, | ||
| 1259 | stats: &mut EvalStats, | ||
| 1260 | ) -> CachedTexture { | ||
| 1261 | let w = comp.eval_number(node, "Width", time, comp.width as f64, &self.expr).round().max(1.0) as u32; | ||
| 1262 | let h = comp.eval_number(node, "Height", time, comp.height as f64, &self.expr).round().max(1.0) as u32; | ||
| 1263 | let dims = if w > 1 && h > 1 { self.scaled_dims(w, h) } else { comp_dims }; | ||
| 1264 | let dst_depth = self.node_depth(comp, node, time, None); | ||
| 1265 | |||
| 1266 | let bitmap_sources = crate::particles::collect_bitmap_sources(comp, node.id); | ||
| 1267 | let mut sprites: HashMap<NodeId, crate::particles::SpriteImage> = HashMap::new(); | ||
| 1268 | let mut sprite_hashes: Vec<(NodeId, u64)> = Vec::with_capacity(bitmap_sources.len()); | ||
| 1269 | |||
| 1270 | for (emitter_id, sprite_node_id) in bitmap_sources { | ||
| 1271 | let spr_key = (sprite_node_id, comp.revision, frame_i); | ||
| 1272 | if let Some(cached) = self.sprite_cache.get(&spr_key).cloned() { | ||
| 1273 | sprite_hashes.push((emitter_id, (cached.size[0] as u64) << 32 | cached.size[1] as u64)); | ||
| 1274 | sprites.insert(emitter_id, cached); | ||
| 1275 | continue; | ||
| 1276 | } | ||
| 1277 | let mut sprite_enc = self.device.create_command_encoder(&wgpu::CommandEncoderDescriptor { | ||
| 1278 | label: Some("particle-sprite-eval"), | ||
| 1279 | }); | ||
| 1280 | let mut sprite_vis = visiting.clone(); | ||
| 1281 | let sprite_tex = self.eval_node(comp, sprite_node_id, time, &mut sprite_enc, &mut sprite_vis, stats); | ||
| 1282 | self.queue.submit(Some(sprite_enc.finish())); | ||
| 1283 | sprite_hashes.push((emitter_id, sprite_tex.content_hash)); | ||
| 1284 | if let Ok(rgba) = self.readback_rgba(&sprite_tex) { | ||
| 1285 | let spr = crate::particles::SpriteImage { | ||
| 1286 | size: sprite_tex.size, | ||
| 1287 | rgba, | ||
| 1288 | }; | ||
| 1289 | if self.sprite_cache.len() > 64 { | ||
| 1290 | self.sprite_cache.clear(); | ||
| 1291 | } | ||
| 1292 | self.sprite_cache.insert(spr_key, spr.clone()); | ||
| 1293 | sprites.insert(emitter_id, spr); | ||
| 1294 | } | ||
| 1295 | } | ||
| 1296 | |||
| 1297 | let mut h_key = DefaultHasher::new(); | ||
| 1298 | self.cache.gpu_salt.hash(&mut h_key); | ||
| 1299 | self.cache.node_salt(node.id).hash(&mut h_key); | ||
| 1300 | "pRender".hash(&mut h_key); | ||
| 1301 | comp.revision.hash(&mut h_key); | ||
| 1302 | frame_i.hash(&mut h_key); | ||
| 1303 | dims.hash(&mut h_key); | ||
| 1304 | dst_depth.hash(&mut h_key); | ||
| 1305 | sprite_hashes.hash(&mut h_key); | ||
| 1306 | let key = h_key.finish(); | ||
| 1307 | |||
| 1308 | if let Some(hit) = self.cache.get(key, node.id, frame_i) { | ||
| 1309 | stats.cache_hits += 1; | ||
| 1310 | return hit; | ||
| 1311 | } | ||
| 1312 | stats.cache_misses += 1; | ||
| 1313 | stats.nodes_evaluated += 1; | ||
| 1314 | |||
| 1315 | let rgba = crate::particles::render_particles_2d( | ||
| 1316 | &mut self.particles, | ||
| 1317 | comp, | ||
| 1318 | node.id, | ||
| 1319 | time, | ||
| 1320 | dims, | ||
| 1321 | &self.expr, | ||
| 1322 | &sprites, | ||
| 1323 | ); | ||
| 1324 | let base_tex = create_texture(&self.device, dims, if dst_depth == BitDepth::Int8 { key } else { 0 }); | ||
| 1325 | self.queue.write_texture( | ||
| 1326 | base_tex.texture.as_image_copy(), | ||
| 1327 | &rgba, | ||
| 1328 | wgpu::TexelCopyBufferLayout { | ||
| 1329 | offset: 0, | ||
| 1330 | bytes_per_row: Some(dims[0] * 4), | ||
| 1331 | rows_per_image: Some(dims[1]), | ||
| 1332 | }, | ||
| 1333 | wgpu::Extent3d { | ||
| 1334 | width: dims[0], | ||
| 1335 | height: dims[1], | ||
| 1336 | depth_or_array_layers: 1, | ||
| 1337 | }, | ||
| 1338 | ); | ||
| 1339 | |||
| 1340 | let out = if dst_depth != BitDepth::Int8 { | ||
| 1341 | let promoted = self.alloc_tex(dims, dst_depth, key); | ||
| 1342 | let u = UniformParams::default(); | ||
| 1343 | self.dispatch_op(enc, ShaderOp::ChangeDepth, &base_tex.view, &self.dummy.view, &self.dummy.view, &promoted, &u); | ||
| 1344 | promoted | ||
| 1345 | } else { | ||
| 1346 | base_tex | ||
| 1347 | }; | ||
| 1348 | self.cache.insert(key, out.clone(), node.id, frame_i); | ||
| 1349 | out | ||
| 1350 | } | ||
| 1351 | |||
| 980 | fn eval_background( | 1352 | fn eval_background( |
| 981 | &mut self, | 1353 | &mut self, |
| 982 | comp: &Comp, | 1354 | comp: &Comp, |
| ... | @@ -1682,8 +2054,13 @@ impl Engine { | ... | @@ -1682,8 +2054,13 @@ impl Engine { |
| 1682 | return src; | 2054 | return src; |
| 1683 | } | 2055 | } |
| 1684 | let is_soft_glow = node.kind == "SoftGlow"; | 2056 | let is_soft_glow = node.kind == "SoftGlow"; |
| 1685 | // Fusion SoftGlow/Glow sizes are in 720px-reference pixels (same as Blur). | 2057 | // Fusion SoftGlow/Glow sizes are in 720px-reference pixels; Glow's Gaussian kernel is |
| 1686 | let scale_ref = src.size[0] as f32 / 720.0 * 1.14; | 2058 | // slightly tighter (~0.86x) than SoftGlow's (~1.00x). |
| 2059 | let scale_ref = if is_soft_glow { | ||
| 2060 | src.size[0] as f32 / 720.0 | ||
| 2061 | } else { | ||
| 2062 | src.size[0] as f32 / 720.0 * 0.86 | ||
| 2063 | }; | ||
| 1687 | let (raw_size, gain, thresh, combine_mode) = if is_soft_glow { | 2064 | let (raw_size, gain, thresh, combine_mode) = if is_soft_glow { |
| 1688 | let sz = comp.eval_number(node, "XGlowSize", time, 10.0, &self.expr) as f32; | 2065 | let sz = comp.eval_number(node, "XGlowSize", time, 10.0, &self.expr) as f32; |
| 1689 | let g = comp.eval_number(node, "Gain", time, 2.0, &self.expr) as f32; | 2066 | let g = comp.eval_number(node, "Gain", time, 2.0, &self.expr) as f32; |
| ... | @@ -1751,12 +2128,12 @@ impl Engine { | ... | @@ -1751,12 +2128,12 @@ impl Engine { |
| 1751 | 2128 | ||
| 1752 | let mut uh = UniformParams::default(); | 2129 | let mut uh = UniformParams::default(); |
| 1753 | uh.p[0] = [1.0, 0.0, size / down as f32, 0.0]; | 2130 | uh.p[0] = [1.0, 0.0, size / down as f32, 0.0]; |
| 1754 | uh.p[1] = [1.0, 0.0, 0.0, 0.0]; | 2131 | uh.p[1] = [1.0, 0.0, 0.0, 1.0]; |
| 1755 | self.dispatch_op(enc, ShaderOp::Blur, &small.view, &self.dummy.view, &self.dummy.view, &tmp1, &uh); | 2132 | self.dispatch_op(enc, ShaderOp::Blur, &small.view, &self.dummy.view, &self.dummy.view, &tmp1, &uh); |
| 1756 | 2133 | ||
| 1757 | let mut uv = UniformParams::default(); | 2134 | let mut uv = UniformParams::default(); |
| 1758 | uv.p[0] = [0.0, 1.0, size / down as f32, 0.0]; | 2135 | uv.p[0] = [0.0, 1.0, size / down as f32, 0.0]; |
| 1759 | uv.p[1] = [1.0, 0.0, 0.0, 0.0]; | 2136 | uv.p[1] = [1.0, 0.0, 0.0, 1.0]; |
| 1760 | self.dispatch_op(enc, ShaderOp::Blur, &tmp1.view, &self.dummy.view, &self.dummy.view, &tmp2, &uv); | 2137 | self.dispatch_op(enc, ShaderOp::Blur, &tmp1.view, &self.dummy.view, &self.dummy.view, &tmp2, &uv); |
| 1761 | self.dispatch_op(enc, ShaderOp::DisplayBlit, &tmp2.view, &self.dummy.view, &self.dummy.view, &upscaled, &u_blit); | 2138 | self.dispatch_op(enc, ShaderOp::DisplayBlit, &tmp2.view, &self.dummy.view, &self.dummy.view, &upscaled, &u_blit); |
| 1762 | upscaled | 2139 | upscaled |
| ... | @@ -1765,12 +2142,12 @@ impl Engine { | ... | @@ -1765,12 +2142,12 @@ impl Engine { |
| 1765 | let tmp2 = self.alloc_tex(src.size, src.depth, 0); | 2142 | let tmp2 = self.alloc_tex(src.size, src.depth, 0); |
| 1766 | let mut uh = UniformParams::default(); | 2143 | let mut uh = UniformParams::default(); |
| 1767 | uh.p[0] = [1.0, 0.0, size, 0.0]; | 2144 | uh.p[0] = [1.0, 0.0, size, 0.0]; |
| 1768 | uh.p[1] = [1.0, 0.0, 0.0, 0.0]; | 2145 | uh.p[1] = [1.0, 0.0, 0.0, 1.0]; |
| 1769 | self.dispatch_op(enc, ShaderOp::Blur, &glow_src.view, &self.dummy.view, &self.dummy.view, &tmp1, &uh); | 2146 | self.dispatch_op(enc, ShaderOp::Blur, &glow_src.view, &self.dummy.view, &self.dummy.view, &tmp1, &uh); |
| 1770 | 2147 | ||
| 1771 | let mut uv = UniformParams::default(); | 2148 | let mut uv = UniformParams::default(); |
| 1772 | uv.p[0] = [0.0, 1.0, size, 0.0]; | 2149 | uv.p[0] = [0.0, 1.0, size, 0.0]; |
| 1773 | uv.p[1] = [1.0, 0.0, 0.0, 0.0]; | 2150 | uv.p[1] = [1.0, 0.0, 0.0, 1.0]; |
| 1774 | self.dispatch_op(enc, ShaderOp::Blur, &tmp1.view, &self.dummy.view, &self.dummy.view, &tmp2, &uv); | 2151 | self.dispatch_op(enc, ShaderOp::Blur, &tmp1.view, &self.dummy.view, &self.dummy.view, &tmp2, &uv); |
| 1775 | tmp2 | 2152 | tmp2 |
| 1776 | }; | 2153 | }; |
| ... | @@ -2125,6 +2502,8 @@ impl Engine { | ... | @@ -2125,6 +2502,8 @@ impl Engine { |
| 2125 | let strength = comp.eval_number(node, "RefractionStrength", time, 0.05, &self.expr) as f32; | 2502 | let strength = comp.eval_number(node, "RefractionStrength", time, 0.05, &self.expr) as f32; |
| 2126 | let spread = comp.eval_number(node, "Spread", time, 0.0, &self.expr) as f32; | 2503 | let spread = comp.eval_number(node, "Spread", time, 0.0, &self.expr) as f32; |
| 2127 | let light_power = comp.eval_number(node, "LightPower", time, 0.0, &self.expr) as f32; | 2504 | let light_power = comp.eval_number(node, "LightPower", time, 0.0, &self.expr) as f32; |
| 2505 | let light_angle_rad = (comp.eval_number(node, "LightAngle", time, 0.0, &self.expr) as f32 - 45.0).to_radians(); | ||
| 2506 | let light_channel = comp.eval_number(node, "LightChannel", time, 5.0, &self.expr) as f32; | ||
| 2128 | let offset = comp.eval_number(node, "Offset", time, 0.0, &self.expr) as f32; | 2507 | let offset = comp.eval_number(node, "Offset", time, 0.0, &self.expr) as f32; |
| 2129 | let center = comp.eval_point(node, "Center", time, [0.5, 0.5], &self.expr); | 2508 | let center = comp.eval_point(node, "Center", time, [0.5, 0.5], &self.expr); |
| 2130 | let blend = comp.eval_number(node, "Blend", time, 1.0, &self.expr) as f32; | 2509 | let blend = comp.eval_number(node, "Blend", time, 1.0, &self.expr) as f32; |
| ... | @@ -2134,8 +2513,9 @@ impl Engine { | ... | @@ -2134,8 +2513,9 @@ impl Engine { |
| 2134 | u.p[1] = [yo, strength, blend, if mask.is_some() { 1.0 } else { 0.0 }]; | 2513 | u.p[1] = [yo, strength, blend, if mask.is_some() { 1.0 } else { 0.0 }]; |
| 2135 | u.p[2] = [if mask_inv { 1.0 } else { 0.0 }, spread, light_power, offset]; | 2514 | u.p[2] = [if mask_inv { 1.0 } else { 0.0 }, spread, light_power, offset]; |
| 2136 | u.p[3] = [center[0] as f32, center[1] as f32, xch, ych]; | 2515 | u.p[3] = [center[0] as f32, center[1] as f32, xch, ych]; |
| 2516 | u.p[4] = [light_angle_rad, light_channel, 0.0, 0.0]; | ||
| 2137 | 2517 | ||
| 2138 | let key = self.make_key(node, "Displace", src.size, &[src.content_hash, fg.content_hash, mask_hash], bytemuck::cast_slice(&u.p[..4])); | 2518 | let key = self.make_key(node, "Displace", src.size, &[src.content_hash, fg.content_hash, mask_hash], bytemuck::cast_slice(&u.p[..5])); |
| 2139 | if let Some(hit) = self.cache.get(key, node.id, frame_i) { | 2519 | if let Some(hit) = self.cache.get(key, node.id, frame_i) { |
| 2140 | stats.cache_hits += 1; | 2520 | stats.cache_hits += 1; |
| 2141 | return hit; | 2521 | return hit; |
| ... | @@ -2450,13 +2830,23 @@ impl Engine { | ... | @@ -2450,13 +2830,23 @@ impl Engine { |
| 2450 | comp.eval_number(node, "Alpha1", time, 1.0, &self.expr) as f32, | 2830 | comp.eval_number(node, "Alpha1", time, 1.0, &self.expr) as f32, |
| 2451 | ]; | 2831 | ]; |
| 2452 | let outline_enabled = comp.eval_number(node, "Enabled2", time, 0.0, &self.expr) > 0.5; | 2832 | let outline_enabled = comp.eval_number(node, "Enabled2", time, 0.0, &self.expr) > 0.5; |
| 2833 | let elem2_shape = comp.eval_number(node, "ElementShape2", time, 1.0, &self.expr).round() as i32; | ||
| 2453 | let outline_rgba = [ | 2834 | let outline_rgba = [ |
| 2454 | comp.eval_number(node, "Red2", time, 1.0, &self.expr) as f32, | 2835 | comp.eval_number(node, "Red2", time, 1.0, &self.expr) as f32, |
| 2455 | comp.eval_number(node, "Green2", time, 0.0, &self.expr) as f32, | 2836 | comp.eval_number(node, "Green2", time, 0.0, &self.expr) as f32, |
| 2456 | comp.eval_number(node, "Blue2", time, 0.0, &self.expr) as f32, | 2837 | comp.eval_number(node, "Blue2", time, 0.0, &self.expr) as f32, |
| 2457 | comp.eval_number(node, "Alpha2", time, 1.0, &self.expr) as f32, | 2838 | comp.eval_number(node, "Alpha2", time, 1.0, &self.expr) as f32, |
| 2458 | ]; | 2839 | ]; |
| 2840 | let elem2_opacity = comp.eval_number(node, "Opacity2", time, 1.0, &self.expr).clamp(0.0, 1.0) as f32; | ||
| 2459 | let outline_thickness = comp.eval_number(node, "Thickness2", time, 0.02, &self.expr) as f32; | 2841 | let outline_thickness = comp.eval_number(node, "Thickness2", time, 0.02, &self.expr) as f32; |
| 2842 | let border_level = comp.eval_number(node, "Level2", time, 3.0, &self.expr).round() as i32; | ||
| 2843 | let border_ext_h = comp.eval_number(node, "ExtendHorizontal2", time, 0.0, &self.expr) as f32; | ||
| 2844 | let border_ext_v = comp.eval_number(node, "ExtendVertical2", time, 0.0, &self.expr) as f32; | ||
| 2845 | let border_round = comp.eval_number(node, "Round2", time, 0.0, &self.expr).clamp(0.0, 1.0) as f32; | ||
| 2846 | let border_offset = comp.eval_point(node, "Offset2", time, [0.0, 0.0], &self.expr); | ||
| 2847 | let is_border_fill = outline_enabled && elem2_shape == 2; | ||
| 2848 | let is_text_outline = outline_enabled && elem2_shape != 2; | ||
| 2849 | |||
| 2460 | let write_start = comp.eval_number(node, "Start", time, 0.0, &self.expr) as f32; | 2850 | let write_start = comp.eval_number(node, "Start", time, 0.0, &self.expr) as f32; |
| 2461 | let write_end = comp.eval_number(node, "End", time, 1.0, &self.expr) as f32; | 2851 | let write_end = comp.eval_number(node, "End", time, 1.0, &self.expr) as f32; |
| 2462 | let shear_x = comp.eval_number(node, "CharacterShearX", time, 0.0, &self.expr) as f32; | 2852 | let shear_x = comp.eval_number(node, "CharacterShearX", time, 0.0, &self.expr) as f32; |
| ... | @@ -2471,12 +2861,16 @@ impl Engine { | ... | @@ -2471,12 +2861,16 @@ impl Engine { |
| 2471 | font_family.hash(&mut kh); | 2861 | font_family.hash(&mut kh); |
| 2472 | font_style.hash(&mut kh); | 2862 | font_style.hash(&mut kh); |
| 2473 | outline_enabled.hash(&mut kh); | 2863 | outline_enabled.hash(&mut kh); |
| 2864 | elem2_shape.hash(&mut kh); | ||
| 2865 | border_level.hash(&mut kh); | ||
| 2474 | cls_entries.len().hash(&mut kh); | 2866 | cls_entries.len().hash(&mut kh); |
| 2475 | for v in [ | 2867 | for v in [ |
| 2476 | size_norm, tracking, center[0] as f32, center[1] as f32, h_lcr, v_tcb, | 2868 | size_norm, tracking, center[0] as f32, center[1] as f32, h_lcr, v_tcb, |
| 2477 | fill_rgba[0], fill_rgba[1], fill_rgba[2], fill_rgba[3], | 2869 | fill_rgba[0], fill_rgba[1], fill_rgba[2], fill_rgba[3], |
| 2478 | outline_rgba[0], outline_rgba[1], outline_rgba[2], outline_rgba[3], | 2870 | outline_rgba[0], outline_rgba[1], outline_rgba[2], outline_rgba[3], elem2_opacity, |
| 2479 | outline_thickness, write_start, write_end, shear_x, | 2871 | outline_thickness, border_ext_h, border_ext_v, border_round, |
| 2872 | border_offset[0] as f32, border_offset[1] as f32, | ||
| 2873 | write_start, write_end, shear_x, | ||
| 2480 | ] { | 2874 | ] { |
| 2481 | v.to_bits().hash(&mut kh); | 2875 | v.to_bits().hash(&mut kh); |
| 2482 | } | 2876 | } |
| ... | @@ -2489,12 +2883,22 @@ impl Engine { | ... | @@ -2489,12 +2883,22 @@ impl Engine { |
| 2489 | stats.cache_misses += 1; | 2883 | stats.cache_misses += 1; |
| 2490 | stats.nodes_evaluated += 1; | 2884 | stats.nodes_evaluated += 1; |
| 2491 | 2885 | ||
| 2492 | let outline_radius = if outline_enabled && outline_thickness > 1e-4 { | 2886 | let size_px = size_norm * size[0] as f32; |
| 2493 | (outline_thickness * size_norm * size[0] as f32 * 0.50).clamp(1.0, 28.0) | 2887 | let outline_radius = if is_text_outline && outline_thickness > 1e-4 { |
| 2888 | (outline_thickness * size_px * 0.50).clamp(1.0, 28.0) | ||
| 2494 | } else { | 2889 | } else { |
| 2495 | 0.0 | 2890 | 0.0 |
| 2496 | }; | 2891 | }; |
| 2497 | let (tex_size, origin, pixels) = rasterize_text_plus( | 2892 | let border_pad_px = if is_border_fill { |
| 2893 | let ext_max = border_ext_h.abs().max(border_ext_v.abs()) * size_px; | ||
| 2894 | let off_max = (border_offset[0].abs() as f32 * size[0] as f32) | ||
| 2895 | .max(border_offset[1].abs() as f32 * size[1] as f32); | ||
| 2896 | (0.45 * size_px + ext_max + off_max).ceil() as i32 + 4 | ||
| 2897 | } else { | ||
| 2898 | 0 | ||
| 2899 | }; | ||
| 2900 | let dod_pad = (outline_radius.ceil() as i32 + 2).max(border_pad_px); | ||
| 2901 | let (tex_size, origin, mut pixels) = rasterize_text_plus( | ||
| 2498 | size, | 2902 | size, |
| 2499 | &TextPlusParams { | 2903 | &TextPlusParams { |
| 2500 | text: &text_str, | 2904 | text: &text_str, |
| ... | @@ -2511,14 +2915,223 @@ impl Engine { | ... | @@ -2511,14 +2915,223 @@ impl Engine { |
| 2511 | shear_x, | 2915 | shear_x, |
| 2512 | cls: cls_entries, | 2916 | cls: cls_entries, |
| 2513 | }, | 2917 | }, |
| 2514 | outline_radius.ceil() as i32 + 2, | 2918 | dod_pad, |
| 2515 | ); | 2919 | ); |
| 2920 | |||
| 2921 | // Fusion TextPlus ElementShape = 2 (BorderFill): draw filled (optionally rounded) box(es) | ||
| 2922 | // behind text according to Level (0=Text, 1=Line, 2=Word, 3=Character), ExtendH/V, Round, Offset. | ||
| 2923 | if is_border_fill && elem2_opacity > 1e-4 { | ||
| 2924 | let tw = tex_size[0] as usize; | ||
| 2925 | let th = tex_size[1] as usize; | ||
| 2926 | // Find non-empty rows to identify vertical line bands. | ||
| 2927 | let mut row_has = vec![false; th]; | ||
| 2928 | for y in 0..th { | ||
| 2929 | let base = y * tw * 4; | ||
| 2930 | for x in 0..tw { | ||
| 2931 | if pixels[base + x * 4 + 3] > 8 { | ||
| 2932 | row_has[y] = true; | ||
| 2933 | break; | ||
| 2934 | } | ||
| 2935 | } | ||
| 2936 | } | ||
| 2937 | // Merge vertical gaps smaller than 0.28 * size_px (e.g. dot on 'i'/'j'). | ||
| 2938 | let v_merge = (0.28 * size_px).ceil() as usize; | ||
| 2939 | let mut lines: Vec<(usize, usize)> = Vec::new(); | ||
| 2940 | let mut y = 0; | ||
| 2941 | while y < th { | ||
| 2942 | if row_has[y] { | ||
| 2943 | let y0 = y; | ||
| 2944 | let mut y1 = y; | ||
| 2945 | y += 1; | ||
| 2946 | while y < th { | ||
| 2947 | if row_has[y] { | ||
| 2948 | y1 = y; | ||
| 2949 | y += 1; | ||
| 2950 | } else { | ||
| 2951 | let mut gap = 0; | ||
| 2952 | while y + gap < th && !row_has[y + gap] && gap <= v_merge { | ||
| 2953 | gap += 1; | ||
| 2954 | } | ||
| 2955 | if gap <= v_merge && y + gap < th { | ||
| 2956 | y += gap; | ||
| 2957 | y1 = y; | ||
| 2958 | y += 1; | ||
| 2959 | } else { | ||
| 2960 | break; | ||
| 2961 | } | ||
| 2962 | } | ||
| 2963 | } | ||
| 2964 | lines.push((y0, y1)); | ||
| 2965 | } else { | ||
| 2966 | y += 1; | ||
| 2967 | } | ||
| 2968 | } | ||
| 2969 | |||
| 2970 | if !lines.is_empty() { | ||
| 2971 | let mut boxes: Vec<[f32; 4]> = Vec::new(); // [x0, y0, x1, y1] | ||
| 2972 | let base_hx = if border_level == 3 { | ||
| 2973 | 0.03 * size_px | ||
| 2974 | } else { | ||
| 2975 | 0.18 * size_px | ||
| 2976 | }; | ||
| 2977 | let ext_scale = if border_level == 3 { 0.20 } else { 1.0 }; | ||
| 2978 | let ext_x = border_ext_h * size_px * ext_scale; | ||
| 2979 | let ext_y = border_ext_v * size_px * ext_scale; | ||
| 2980 | let off_x = border_offset[0] as f32 * size[0] as f32; | ||
| 2981 | let off_y = -(border_offset[1] as f32) * size[1] as f32; | ||
| 2982 | |||
| 2983 | if border_level == 0 { | ||
| 2984 | // Whole-text bounding box | ||
| 2985 | let mut x0 = tw; | ||
| 2986 | let mut x1 = 0usize; | ||
| 2987 | let gy0 = lines.first().unwrap().0; | ||
| 2988 | let gy1 = lines.last().unwrap().1; | ||
| 2989 | for yy in gy0..=gy1 { | ||
| 2990 | let base = yy * tw * 4; | ||
| 2991 | for xx in 0..tw { | ||
| 2992 | if pixels[base + xx * 4 + 3] > 8 { | ||
| 2993 | x0 = x0.min(xx); | ||
| 2994 | x1 = x1.max(xx); | ||
| 2995 | } | ||
| 2996 | } | ||
| 2997 | } | ||
| 2998 | if x0 <= x1 { | ||
| 2999 | let top_pad = 0.14 * size_px + ext_y; | ||
| 3000 | let bot_pad = 0.16 * size_px + ext_y; | ||
| 3001 | boxes.push([ | ||
| 3002 | x0 as f32 - base_hx - ext_x + off_x, | ||
| 3003 | gy0 as f32 - top_pad + off_y, | ||
| 3004 | x1 as f32 + 1.0 + base_hx + ext_x + off_x, | ||
| 3005 | gy1 as f32 + 1.0 + bot_pad + off_y, | ||
| 3006 | ]); | ||
| 3007 | } | ||
| 3008 | } else { | ||
| 3009 | // Per-line (1), per-word (2), or per-character (3) | ||
| 3010 | let h_merge = match border_level { | ||
| 3011 | 1 => tw, // single box per line | ||
| 3012 | 2 => (0.18 * size_px).ceil().max(2.0) as usize, // merge chars within a word | ||
| 3013 | _ => if border_round > 0.01 { 0 } else { (0.08 * size_px).ceil() as usize }, | ||
| 3014 | }; | ||
| 3015 | for &(ly0, ly1) in &lines { | ||
| 3016 | let mut col_has = vec![false; tw]; | ||
| 3017 | for yy in ly0..=ly1 { | ||
| 3018 | let base = yy * tw * 4; | ||
| 3019 | for xx in 0..tw { | ||
| 3020 | if pixels[base + xx * 4 + 3] > 8 { | ||
| 3021 | col_has[xx] = true; | ||
| 3022 | } | ||
| 3023 | } | ||
| 3024 | } | ||
| 3025 | let mut runs: Vec<(usize, usize)> = Vec::new(); | ||
| 3026 | let mut x = 0; | ||
| 3027 | while x < tw { | ||
| 3028 | if col_has[x] { | ||
| 3029 | let x0 = x; | ||
| 3030 | let mut x1 = x; | ||
| 3031 | x += 1; | ||
| 3032 | while x < tw { | ||
| 3033 | if col_has[x] { | ||
| 3034 | x1 = x; | ||
| 3035 | x += 1; | ||
| 3036 | } else { | ||
| 3037 | let mut gap = 0; | ||
| 3038 | while x + gap < tw && !col_has[x + gap] && gap <= h_merge { | ||
| 3039 | gap += 1; | ||
| 3040 | } | ||
| 3041 | if gap <= h_merge && x + gap < tw { | ||
| 3042 | x += gap; | ||
| 3043 | x1 = x; | ||
| 3044 | x += 1; | ||
| 3045 | } else { | ||
| 3046 | break; | ||
| 3047 | } | ||
| 3048 | } | ||
| 3049 | } | ||
| 3050 | runs.push((x0, x1)); | ||
| 3051 | } else { | ||
| 3052 | x += 1; | ||
| 3053 | } | ||
| 3054 | } | ||
| 3055 | let cy = 0.5 * (ly0 as f32 + ly1 as f32 + 1.0) + 0.015 * size_px; | ||
| 3056 | let half_h = (0.40 * size_px).max(0.5 * (ly1 as f32 - ly0 as f32 + 1.0) + 0.06 * size_px) + ext_y; | ||
| 3057 | for (rx0, rx1) in runs { | ||
| 3058 | let cx = 0.5 * (rx0 as f32 + rx1 as f32 + 1.0) + off_x; | ||
| 3059 | let half_w = 0.5 * (rx1 as f32 - rx0 as f32 + 1.0) + base_hx + ext_x; | ||
| 3060 | boxes.push([ | ||
| 3061 | cx - half_w, | ||
| 3062 | cy - half_h + off_y, | ||
| 3063 | cx + half_w, | ||
| 3064 | cy + half_h + off_y, | ||
| 3065 | ]); | ||
| 3066 | } | ||
| 3067 | } | ||
| 3068 | } | ||
| 3069 | |||
| 3070 | // Rasterize antialiased rounded boxes and composite text OVER box! | ||
| 3071 | let mut box_cov = vec![0.0_f32; tw * th]; | ||
| 3072 | for b in &boxes { | ||
| 3073 | let cx = 0.5 * (b[0] + b[2]); | ||
| 3074 | let cy = 0.5 * (b[1] + b[3]); | ||
| 3075 | let hw = (0.5 * (b[2] - b[0])).max(0.5); | ||
| 3076 | let hh = (0.5 * (b[3] - b[1])).max(0.5); | ||
| 3077 | let rad = (border_round * hh).min(hw.min(hh)); | ||
| 3078 | let ix0 = (b[0].floor() as i32 - 1).clamp(0, tw as i32 - 1) as usize; | ||
| 3079 | let ix1 = (b[2].ceil() as i32 + 1).clamp(0, tw as i32 - 1) as usize; | ||
| 3080 | let iy0 = (b[1].floor() as i32 - 1).clamp(0, th as i32 - 1) as usize; | ||
| 3081 | let iy1 = (b[3].ceil() as i32 + 1).clamp(0, th as i32 - 1) as usize; | ||
| 3082 | for yy in iy0..=iy1 { | ||
| 3083 | let py = yy as f32 + 0.5 - cy; | ||
| 3084 | let qy = py.abs() - (hh - rad); | ||
| 3085 | let row_off = yy * tw; | ||
| 3086 | for xx in ix0..=ix1 { | ||
| 3087 | let px = xx as f32 + 0.5 - cx; | ||
| 3088 | let qx = px.abs() - (hw - rad); | ||
| 3089 | let sdf = (qx.max(0.0).hypot(qy.max(0.0))) + qx.max(qy).min(0.0) - rad; | ||
| 3090 | let cov = (0.5 - sdf).clamp(0.0, 1.0); | ||
| 3091 | if cov > box_cov[row_off + xx] { | ||
| 3092 | box_cov[row_off + xx] = cov; | ||
| 3093 | } | ||
| 3094 | } | ||
| 3095 | } | ||
| 3096 | } | ||
| 3097 | |||
| 3098 | let br = outline_rgba[0] * elem2_opacity; | ||
| 3099 | let bg = outline_rgba[1] * elem2_opacity; | ||
| 3100 | let bb = outline_rgba[2] * elem2_opacity; | ||
| 3101 | let ba = outline_rgba[3] * elem2_opacity; | ||
| 3102 | for i in 0..(tw * th) { | ||
| 3103 | let cov = box_cov[i]; | ||
| 3104 | if cov <= 1e-4 { | ||
| 3105 | continue; | ||
| 3106 | } | ||
| 3107 | let idx = i * 4; | ||
| 3108 | let fg_r = pixels[idx] as f32 / 255.0; | ||
| 3109 | let fg_g = pixels[idx + 1] as f32 / 255.0; | ||
| 3110 | let fg_b = pixels[idx + 2] as f32 / 255.0; | ||
| 3111 | let fg_a = pixels[idx + 3] as f32 / 255.0; | ||
| 3112 | let bg_a = cov * ba; | ||
| 3113 | let bg_r = cov * br; | ||
| 3114 | let bg_g = cov * bg; | ||
| 3115 | let bg_b = cov * bb; | ||
| 3116 | let inv_fg = 1.0 - fg_a; | ||
| 3117 | let out_r = (fg_r + bg_r * inv_fg).clamp(0.0, 1.0); | ||
| 3118 | let out_g = (fg_g + bg_g * inv_fg).clamp(0.0, 1.0); | ||
| 3119 | let out_b = (fg_b + bg_b * inv_fg).clamp(0.0, 1.0); | ||
| 3120 | let out_a = (fg_a + bg_a * inv_fg).clamp(0.0, 1.0); | ||
| 3121 | pixels[idx] = (out_r * 255.0 + 0.5) as u8; | ||
| 3122 | pixels[idx + 1] = (out_g * 255.0 + 0.5) as u8; | ||
| 3123 | pixels[idx + 2] = (out_b * 255.0 + 0.5) as u8; | ||
| 3124 | pixels[idx + 3] = (out_a * 255.0 + 0.5) as u8; | ||
| 3125 | } | ||
| 3126 | } | ||
| 3127 | } | ||
| 3128 | |||
| 2516 | let fill_tex = create_texture_dod( | 3129 | let fill_tex = create_texture_dod( |
| 2517 | &self.device, | 3130 | &self.device, |
| 2518 | tex_size, | 3131 | tex_size, |
| 2519 | origin, | 3132 | origin, |
| 2520 | size, | 3133 | size, |
| 2521 | if outline_enabled { 0 } else { key }, | 3134 | if outline_radius > 0.0 { 0 } else { key }, |
| 2522 | ); | 3135 | ); |
| 2523 | self.queue.write_texture( | 3136 | self.queue.write_texture( |
| 2524 | fill_tex.texture.as_image_copy(), | 3137 | fill_tex.texture.as_image_copy(), |
crates/engine/src/lib.rs+3| ... | @@ -1,8 +1,11 @@ | ... | @@ -1,8 +1,11 @@ |
| 1 | pub mod audio; | 1 | pub mod audio; |
| 2 | pub mod cache; | 2 | pub mod cache; |
| 3 | pub mod cryptomatte; | ||
| 3 | pub mod eval; | 4 | pub mod eval; |
| 4 | pub mod export; | 5 | pub mod export; |
| 5 | pub mod media; | 6 | pub mod media; |
| 7 | pub mod optflow; | ||
| 8 | pub mod particles; | ||
| 6 | pub mod scene3d; | 9 | pub mod scene3d; |
| 7 | 10 | ||
| 8 | pub use audio::{AudioPlayer, AudioTrack}; | 11 | pub use audio::{AudioPlayer, AudioTrack}; |
crates/engine/src/media.rs+104-19| ... | @@ -12,6 +12,57 @@ pub struct DecodedImage { | ... | @@ -12,6 +12,57 @@ pub struct DecodedImage { |
| 12 | pub size: [u32; 2], | 12 | pub size: [u32; 2], |
| 13 | /// Premultiplied RGBA8 pixels, top-down. | 13 | /// Premultiplied RGBA8 pixels, top-down. |
| 14 | pub rgba: Arc<Vec<u8>>, | 14 | pub rgba: Arc<Vec<u8>>, |
| 15 | /// Optional unclamped linear HDR RGBA16F bit-packed pixels (`[r, g, b, a, ...]`), | ||
| 16 | /// pre-converted once at EXR decode for zero-copy `Rgba16Float` GPU upload. | ||
| 17 | pub rgba_f16: Option<Arc<Vec<u16>>>, | ||
| 18 | /// Optional unclamped linear HDR RGBA32F pixels (`[r, g, b, a, ...]`, top-down), | ||
| 19 | /// populated for OpenEXR images to preserve HDR highlights `> 1.0` and negative values. | ||
| 20 | pub rgba_f32: Option<Arc<Vec<f32>>>, | ||
| 21 | } | ||
| 22 | |||
| 23 | impl DecodedImage { | ||
| 24 | pub fn byte_size(&self) -> u64 { | ||
| 25 | let u8_bytes = self.rgba.len() as u64; | ||
| 26 | let f16_bytes = self | ||
| 27 | .rgba_f16 | ||
| 28 | .as_ref() | ||
| 29 | .map_or(0, |v| (v.len() * std::mem::size_of::<u16>()) as u64); | ||
| 30 | let f32_bytes = self | ||
| 31 | .rgba_f32 | ||
| 32 | .as_ref() | ||
| 33 | .map_or(0, |v| (v.len() * std::mem::size_of::<f32>()) as u64); | ||
| 34 | u8_bytes + f16_bytes + f32_bytes | ||
| 35 | } | ||
| 36 | } | ||
| 37 | |||
| 38 | /// Converts IEEE-754 `f32` to IEEE-754 binary16 (`f16`) bits for direct `Rgba16Float` GPU upload. | ||
| 39 | #[inline] | ||
| 40 | pub fn f32_to_f16_bits(val: f32) -> u16 { | ||
| 41 | let bits = val.to_bits(); | ||
| 42 | let sign = ((bits >> 16) & 0x8000) as u16; | ||
| 43 | let exp = ((bits >> 23) & 0xFF) as i32; | ||
| 44 | let frac = bits & 0x007F_FFFF; | ||
| 45 | |||
| 46 | if exp == 0xFF { | ||
| 47 | return if frac != 0 { 0 } else { sign | 0x7C00 }; | ||
| 48 | } | ||
| 49 | let new_exp = exp - 127 + 15; | ||
| 50 | if new_exp >= 31 { | ||
| 51 | return sign | 0x7BFF; | ||
| 52 | } | ||
| 53 | if new_exp <= 0 { | ||
| 54 | if new_exp < -10 { | ||
| 55 | return sign; | ||
| 56 | } | ||
| 57 | let m = (frac | 0x0080_0000) >> (1 - new_exp + 13); | ||
| 58 | return sign | (m as u16); | ||
| 59 | } | ||
| 60 | let rounded = frac + 0x1000; | ||
| 61 | if rounded >= 0x0080_0000 { | ||
| 62 | let e = new_exp + 1; | ||
| 63 | return if e >= 31 { sign | 0x7BFF } else { sign | ((e as u16) << 10) }; | ||
| 64 | } | ||
| 65 | sign | ((new_exp as u16) << 10) | ((rounded >> 13) as u16) | ||
| 15 | } | 66 | } |
| 16 | 67 | ||
| 17 | #[derive(Clone, Copy, Debug)] | 68 | #[derive(Clone, Copy, Debug)] |
| ... | @@ -288,7 +339,8 @@ fn is_exr_path(path: &Path) -> bool { | ... | @@ -288,7 +339,8 @@ fn is_exr_path(path: &Path) -> bool { |
| 288 | } | 339 | } |
| 289 | 340 | ||
| 290 | /// Decodes a single-layer or multi-layer (Blender `ViewLayer.Combined.R/G/B/A`) OpenEXR | 341 | /// Decodes a single-layer or multi-layer (Blender `ViewLayer.Combined.R/G/B/A`) OpenEXR |
| 291 | /// into RGBA8 (`u8`, linear [0..1] clamped so downstream `GamutConvert` applies exact sRGB!). | 342 | /// into both clamped RGBA8 (`u8`, linear [0..1] preview for Fast mode / 8-bit pipelines) |
| 343 | /// and unclamped linear HDR RGBA32F (`f32`, preserving highlights `> 1.0` and negative values). | ||
| 292 | fn decode_exr_rgba( | 344 | fn decode_exr_rgba( |
| 293 | path: &Path, | 345 | path: &Path, |
| 294 | red_name: Option<&str>, | 346 | red_name: Option<&str>, |
| ... | @@ -313,12 +365,17 @@ fn decode_exr_rgba( | ... | @@ -313,12 +365,17 @@ fn decode_exr_rgba( |
| 313 | } | 365 | } |
| 314 | names.extend_from_slice(fallbacks); | 366 | names.extend_from_slice(fallbacks); |
| 315 | for target in names { | 367 | for target in names { |
| 316 | for ch in &layer.channel_data.list { | 368 | for candidate_layer in &img.layer_data { |
| 317 | let cname = ch.name.to_string(); | 369 | if candidate_layer.size.width() != w || candidate_layer.size.height() != h { |
| 318 | if cname == target || cname.ends_with(&format!(".{target}")) { | 370 | continue; |
| 319 | let vals: Vec<f32> = ch.sample_data.values_as_f32().collect(); | 371 | } |
| 320 | if vals.len() == w * h { | 372 | for ch in &candidate_layer.channel_data.list { |
| 321 | return Some(vals); | 373 | let cname = ch.name.to_string(); |
| 374 | if cname == target || cname.ends_with(&format!(".{target}")) { | ||
| 375 | let vals: Vec<f32> = ch.sample_data.values_as_f32().collect(); | ||
| 376 | if vals.len() == w * h { | ||
| 377 | return Some(vals); | ||
| 378 | } | ||
| 322 | } | 379 | } |
| 323 | } | 380 | } |
| 324 | } | 381 | } |
| ... | @@ -333,17 +390,36 @@ fn decode_exr_rgba( | ... | @@ -333,17 +390,36 @@ fn decode_exr_rgba( |
| 333 | .unwrap_or_else(|| ch_r.clone()); | 390 | .unwrap_or_else(|| ch_r.clone()); |
| 334 | let ch_a = find_channel(alpha_name, &["ViewLayer.Combined.A", "Combined.A", "A", "a"]); | 391 | let ch_a = find_channel(alpha_name, &["ViewLayer.Combined.A", "Combined.A", "A", "a"]); |
| 335 | 392 | ||
| 393 | let sanitize = |v: f32| if v.is_nan() { 0.0 } else { v }; | ||
| 394 | |||
| 336 | let mut raw = vec![0u8; w * h * 4]; | 395 | let mut raw = vec![0u8; w * h * 4]; |
| 396 | let mut raw_f16 = vec![0u16; w * h * 4]; | ||
| 397 | let mut raw_f32 = vec![0.0_f32; w * h * 4]; | ||
| 337 | for i in 0..(w * h) { | 398 | for i in 0..(w * h) { |
| 338 | let a = ch_a.as_ref().map_or(1.0, |v| v[i]).clamp(0.0, 1.0); | 399 | let a_raw = sanitize(ch_a.as_ref().map_or(1.0, |v| v[i])); |
| 339 | let mut r = ch_r[i].clamp(0.0, 1.0); | 400 | let mut r_raw = sanitize(ch_r[i]); |
| 340 | let mut g = ch_g[i].clamp(0.0, 1.0); | 401 | let mut g_raw = sanitize(ch_g[i]); |
| 341 | let mut b = ch_b[i].clamp(0.0, 1.0); | 402 | let mut b_raw = sanitize(ch_b[i]); |
| 342 | if post_multiply && a < 1.0 { | 403 | if post_multiply && a_raw < 1.0 { |
| 343 | r *= a; | 404 | let a_mul = a_raw.clamp(0.0, 1.0); |
| 344 | g *= a; | 405 | r_raw *= a_mul; |
| 345 | b *= a; | 406 | g_raw *= a_mul; |
| 407 | b_raw *= a_mul; | ||
| 346 | } | 408 | } |
| 409 | raw_f32[i * 4] = r_raw; | ||
| 410 | raw_f32[i * 4 + 1] = g_raw; | ||
| 411 | raw_f32[i * 4 + 2] = b_raw; | ||
| 412 | raw_f32[i * 4 + 3] = a_raw; | ||
| 413 | |||
| 414 | raw_f16[i * 4] = f32_to_f16_bits(r_raw); | ||
| 415 | raw_f16[i * 4 + 1] = f32_to_f16_bits(g_raw); | ||
| 416 | raw_f16[i * 4 + 2] = f32_to_f16_bits(b_raw); | ||
| 417 | raw_f16[i * 4 + 3] = f32_to_f16_bits(a_raw); | ||
| 418 | |||
| 419 | let a = a_raw.clamp(0.0, 1.0); | ||
| 420 | let r = r_raw.clamp(0.0, 1.0); | ||
| 421 | let g = g_raw.clamp(0.0, 1.0); | ||
| 422 | let b = b_raw.clamp(0.0, 1.0); | ||
| 347 | raw[i * 4] = (r * 255.0 + 0.5) as u8; | 423 | raw[i * 4] = (r * 255.0 + 0.5) as u8; |
| 348 | raw[i * 4 + 1] = (g * 255.0 + 0.5) as u8; | 424 | raw[i * 4 + 1] = (g * 255.0 + 0.5) as u8; |
| 349 | raw[i * 4 + 2] = (b * 255.0 + 0.5) as u8; | 425 | raw[i * 4 + 2] = (b * 255.0 + 0.5) as u8; |
| ... | @@ -352,6 +428,8 @@ fn decode_exr_rgba( | ... | @@ -352,6 +428,8 @@ fn decode_exr_rgba( |
| 352 | Some(DecodedImage { | 428 | Some(DecodedImage { |
| 353 | size: [w as u32, h as u32], | 429 | size: [w as u32, h as u32], |
| 354 | rgba: Arc::new(raw), | 430 | rgba: Arc::new(raw), |
| 431 | rgba_f16: Some(Arc::new(raw_f16)), | ||
| 432 | rgba_f32: Some(Arc::new(raw_f32)), | ||
| 355 | }) | 433 | }) |
| 356 | } | 434 | } |
| 357 | 435 | ||
| ... | @@ -391,10 +469,10 @@ impl MediaCache { | ... | @@ -391,10 +469,10 @@ impl MediaCache { |
| 391 | } | 469 | } |
| 392 | 470 | ||
| 393 | fn insert_cached(&mut self, cache_key: (PathBuf, i64), decoded: DecodedImage) { | 471 | fn insert_cached(&mut self, cache_key: (PathBuf, i64), decoded: DecodedImage) { |
| 394 | let bytes = decoded.rgba.len() as u64; | 472 | let bytes = decoded.byte_size(); |
| 395 | self.tick += 1; | 473 | self.tick += 1; |
| 396 | if let Some(prev) = self.images.insert(cache_key.clone(), decoded) { | 474 | if let Some(prev) = self.images.insert(cache_key.clone(), decoded) { |
| 397 | self.total_bytes = self.total_bytes.saturating_sub(prev.rgba.len() as u64); | 475 | self.total_bytes = self.total_bytes.saturating_sub(prev.byte_size()); |
| 398 | } | 476 | } |
| 399 | self.lru.insert(cache_key, self.tick); | 477 | self.lru.insert(cache_key, self.tick); |
| 400 | self.total_bytes += bytes; | 478 | self.total_bytes += bytes; |
| ... | @@ -405,7 +483,7 @@ impl MediaCache { | ... | @@ -405,7 +483,7 @@ impl MediaCache { |
| 405 | }; | 483 | }; |
| 406 | self.lru.remove(&oldest); | 484 | self.lru.remove(&oldest); |
| 407 | if let Some(rem) = self.images.remove(&oldest) { | 485 | if let Some(rem) = self.images.remove(&oldest) { |
| 408 | self.total_bytes = self.total_bytes.saturating_sub(rem.rgba.len() as u64); | 486 | self.total_bytes = self.total_bytes.saturating_sub(rem.byte_size()); |
| 409 | } | 487 | } |
| 410 | } | 488 | } |
| 411 | } | 489 | } |
| ... | @@ -472,6 +550,8 @@ impl MediaCache { | ... | @@ -472,6 +550,8 @@ impl MediaCache { |
| 472 | let decoded = DecodedImage { | 550 | let decoded = DecodedImage { |
| 473 | size: [info.width, info.height], | 551 | size: [info.width, info.height], |
| 474 | rgba: Arc::new(raw), | 552 | rgba: Arc::new(raw), |
| 553 | rgba_f16: None, | ||
| 554 | rgba_f32: None, | ||
| 475 | }; | 555 | }; |
| 476 | self.insert_cached(cache_key, decoded.clone()); | 556 | self.insert_cached(cache_key, decoded.clone()); |
| 477 | return Some((base_buf, idx, decoded, true)); | 557 | return Some((base_buf, idx, decoded, true)); |
| ... | @@ -510,7 +590,12 @@ impl MediaCache { | ... | @@ -510,7 +590,12 @@ impl MediaCache { |
| 510 | } | 590 | } |
| 511 | } | 591 | } |
| 512 | } | 592 | } |
| 513 | DecodedImage { size, rgba: Arc::new(raw) } | 593 | DecodedImage { |
| 594 | size, | ||
| 595 | rgba: Arc::new(raw), | ||
| 596 | rgba_f16: None, | ||
| 597 | rgba_f32: None, | ||
| 598 | } | ||
| 514 | }; | 599 | }; |
| 515 | self.insert_cached(cache_key, decoded.clone()); | 600 | self.insert_cached(cache_key, decoded.clone()); |
| 516 | Some((resolved, -1, decoded, true)) | 601 | Some((resolved, -1, decoded, true)) |
crates/engine/src/optflow.rs created+1261| ... | @@ -0,0 +1,1261 @@ | ||
| 1 | //! GPU dense optical flow (`Dimension.OpticalFlow`) and flow-warped frame interpolation | ||
| 2 | //! (`TimeStretcher` `InterpolateBetweenFrames = 1` Blend and `= 2` Flow). | ||
| 3 | |||
| 4 | use crate::cache::CachedTexture; | ||
| 5 | use bytemuck::{Pod, Zeroable}; | ||
| 6 | use model::BitDepth; | ||
| 7 | use std::collections::HashMap; | ||
| 8 | use std::collections::hash_map::DefaultHasher; | ||
| 9 | use std::hash::{Hash, Hasher}; | ||
| 10 | use std::sync::RwLock; | ||
| 11 | |||
| 12 | #[repr(C)] | ||
| 13 | #[derive(Clone, Copy, Pod, Zeroable)] | ||
| 14 | struct OptFlowUniform { | ||
| 15 | /// `[dst_w, dst_h, inv_dst_w, inv_dst_h]` | ||
| 16 | dst_size: [f32; 4], | ||
| 17 | /// `[scale_x, scale_y, alpha, extra]` | ||
| 18 | params: [f32; 4], | ||
| 19 | } | ||
| 20 | |||
| 21 | const OPTFLOW_WGSL: &str = r#" | ||
| 22 | struct OptFlowUniform { | ||
| 23 | dst_size: vec4<f32>, | ||
| 24 | params: vec4<f32>, | ||
| 25 | }; | ||
| 26 | |||
| 27 | @group(0) @binding(0) var tex_a: texture_2d<f32>; | ||
| 28 | @group(0) @binding(1) var tex_b: texture_2d<f32>; | ||
| 29 | @group(0) @binding(2) var tex_c: texture_2d<f32>; | ||
| 30 | @group(0) @binding(3) var lin_samp: sampler; | ||
| 31 | @group(0) @binding(4) var<uniform> u: OptFlowUniform; | ||
| 32 | |||
| 33 | struct VsOut { | ||
| 34 | @builtin(position) pos: vec4<f32>, | ||
| 35 | @location(0) uv: vec2<f32>, | ||
| 36 | }; | ||
| 37 | |||
| 38 | @vertex | ||
| 39 | fn vs_fullscreen(@builtin(vertex_index) vid: u32) -> VsOut { | ||
| 40 | var positions = array<vec2<f32>, 3>( | ||
| 41 | vec2<f32>(-1.0, -1.0), | ||
| 42 | vec2<f32>(3.0, -1.0), | ||
| 43 | vec2<f32>(-1.0, 3.0), | ||
| 44 | ); | ||
| 45 | let p = positions[vid]; | ||
| 46 | var out: VsOut; | ||
| 47 | out.pos = vec4<f32>(p, 0.0, 1.0); | ||
| 48 | out.uv = vec2<f32>(p.x * 0.5 + 0.5, 0.5 - p.y * 0.5); | ||
| 49 | return out; | ||
| 50 | } | ||
| 51 | |||
| 52 | // --- 0. Linear cross-dissolve (TimeStretcher InterpolateBetweenFrames = 1 Blend) --- | ||
| 53 | |||
| 54 | @fragment | ||
| 55 | fn fs_blend(in: VsOut) -> @location(0) vec4<f32> { | ||
| 56 | let a = textureSampleLevel(tex_a, lin_samp, in.uv, 0.0); | ||
| 57 | let b = textureSampleLevel(tex_b, lin_samp, in.uv, 0.0); | ||
| 58 | let alpha = clamp(u.params.z, 0.0, 1.0); | ||
| 59 | return mix(a, b, alpha); | ||
| 60 | } | ||
| 61 | |||
| 62 | // --- 1. Feature extraction & anti-aliased pyramid downsample --- | ||
| 63 | // Stores (luma, R-G chroma, B-Y chroma, alpha) in Rgba16Float so isoluminant colored edges track. | ||
| 64 | |||
| 65 | @fragment | ||
| 66 | fn fs_extract_features(in: VsOut) -> @location(0) vec4<f32> { | ||
| 67 | let c = textureSampleLevel(tex_a, lin_samp, in.uv, 0.0); | ||
| 68 | let luma = dot(c.rgb, vec3<f32>(0.299, 0.587, 0.114)); | ||
| 69 | let rg = (c.r - c.g) * 0.5; | ||
| 70 | let by = (c.b - 0.5 * (c.r + c.g)) * 0.5; | ||
| 71 | return vec4<f32>(luma, rg, by, c.a); | ||
| 72 | } | ||
| 73 | |||
| 74 | @fragment | ||
| 75 | fn fs_downsample(in: VsOut) -> @location(0) vec4<f32> { | ||
| 76 | // 4-tap bilinear box/tent filter at +-0.25 dst texels (~ +-0.5 src texels) | ||
| 77 | let d = u.dst_size.zw * 0.25; | ||
| 78 | let c0 = textureSampleLevel(tex_a, lin_samp, in.uv + vec2<f32>(-d.x, -d.y), 0.0); | ||
| 79 | let c1 = textureSampleLevel(tex_a, lin_samp, in.uv + vec2<f32>( d.x, -d.y), 0.0); | ||
| 80 | let c2 = textureSampleLevel(tex_a, lin_samp, in.uv + vec2<f32>(-d.x, d.y), 0.0); | ||
| 81 | let c3 = textureSampleLevel(tex_a, lin_samp, in.uv + vec2<f32>( d.x, d.y), 0.0); | ||
| 82 | return 0.25 * (c0 + c1 + c2 + c3); | ||
| 83 | } | ||
| 84 | |||
| 85 | // --- Helper: weighted 3x3 patch SAD between src_tex(uv) and dst_tex(uv + flow_px * inv_size) --- | ||
| 86 | |||
| 87 | fn feat_diff(a: vec4<f32>, b: vec4<f32>) -> f32 { | ||
| 88 | let d = abs(a - b); | ||
| 89 | return d.x + 0.85 * (d.y + d.z) + 0.5 * d.w; | ||
| 90 | } | ||
| 91 | |||
| 92 | fn patch_sad_ab(uv: vec2<f32>, flow_px: vec2<f32>, inv_sz: vec2<f32>) -> f32 { | ||
| 93 | let uv_t = uv + flow_px * inv_sz; | ||
| 94 | var cost: f32 = 0.0; | ||
| 95 | for (var dy: i32 = -1; dy <= 1; dy = dy + 1) { | ||
| 96 | for (var dx: i32 = -1; dx <= 1; dx = dx + 1) { | ||
| 97 | let off = vec2<f32>(f32(dx), f32(dy)) * inv_sz; | ||
| 98 | let w = select(1.0, 2.0, dx == 0 && dy == 0); | ||
| 99 | let fa = textureSampleLevel(tex_a, lin_samp, uv + off, 0.0); | ||
| 100 | let fb = textureSampleLevel(tex_b, lin_samp, uv_t + off, 0.0); | ||
| 101 | cost = cost + w * feat_diff(fa, fb); | ||
| 102 | } | ||
| 103 | } | ||
| 104 | return cost; | ||
| 105 | } | ||
| 106 | |||
| 107 | fn patch_sad_ba(uv: vec2<f32>, flow_px: vec2<f32>, inv_sz: vec2<f32>) -> f32 { | ||
| 108 | let uv_t = uv + flow_px * inv_sz; | ||
| 109 | var cost: f32 = 0.0; | ||
| 110 | for (var dy: i32 = -1; dy <= 1; dy = dy + 1) { | ||
| 111 | for (var dx: i32 = -1; dx <= 1; dx = dx + 1) { | ||
| 112 | let off = vec2<f32>(f32(dx), f32(dy)) * inv_sz; | ||
| 113 | let w = select(1.0, 2.0, dx == 0 && dy == 0); | ||
| 114 | let fb = textureSampleLevel(tex_b, lin_samp, uv + off, 0.0); | ||
| 115 | let fa = textureSampleLevel(tex_a, lin_samp, uv_t + off, 0.0); | ||
| 116 | cost = cost + w * feat_diff(fb, fa); | ||
| 117 | } | ||
| 118 | } | ||
| 119 | return cost; | ||
| 120 | } | ||
| 121 | |||
| 122 | fn parabolic_offset(c_neg: f32, c_0: f32, c_pos: f32) -> f32 { | ||
| 123 | let denom = c_neg - 2.0 * c_0 + c_pos; | ||
| 124 | if (denom <= 1e-5) { | ||
| 125 | return 0.0; | ||
| 126 | } | ||
| 127 | return clamp(0.5 * (c_neg - c_pos) / denom, -0.5, 0.5); | ||
| 128 | } | ||
| 129 | |||
| 130 | // --- 2a. Coarsest level (1/8 res): [-4..4] x [-4..4] bidirectional search + parabolic subpixel --- | ||
| 131 | |||
| 132 | @fragment | ||
| 133 | fn fs_flow_coarse(in: VsOut) -> @location(0) vec4<f32> { | ||
| 134 | let inv_sz = u.dst_size.zw; | ||
| 135 | let reg = 0.0004; | ||
| 136 | |||
| 137 | // Forward A -> B | ||
| 138 | var best_fwd = vec2<f32>(0.0, 0.0); | ||
| 139 | var best_fwd_cost: f32 = 1e20; | ||
| 140 | for (var dy: i32 = -4; dy <= 4; dy = dy + 1) { | ||
| 141 | for (var dx: i32 = -4; dx <= 4; dx = dx + 1) { | ||
| 142 | let v = vec2<f32>(f32(dx), f32(dy)); | ||
| 143 | let c = patch_sad_ab(in.uv, v, inv_sz) + reg * dot(v, v); | ||
| 144 | if (c < best_fwd_cost) { | ||
| 145 | best_fwd_cost = c; | ||
| 146 | best_fwd = v; | ||
| 147 | } | ||
| 148 | } | ||
| 149 | } | ||
| 150 | let fc_l = patch_sad_ab(in.uv, best_fwd + vec2<f32>(-1.0, 0.0), inv_sz); | ||
| 151 | let fc_r = patch_sad_ab(in.uv, best_fwd + vec2<f32>( 1.0, 0.0), inv_sz); | ||
| 152 | let fc_u = patch_sad_ab(in.uv, best_fwd + vec2<f32>(0.0, -1.0), inv_sz); | ||
| 153 | let fc_d = patch_sad_ab(in.uv, best_fwd + vec2<f32>(0.0, 1.0), inv_sz); | ||
| 154 | let fc_0 = patch_sad_ab(in.uv, best_fwd, inv_sz); | ||
| 155 | let fwd = best_fwd + vec2<f32>( | ||
| 156 | parabolic_offset(fc_l, fc_0, fc_r), | ||
| 157 | parabolic_offset(fc_u, fc_0, fc_d), | ||
| 158 | ); | ||
| 159 | |||
| 160 | // Backward B -> A | ||
| 161 | var best_bwd = vec2<f32>(0.0, 0.0); | ||
| 162 | var best_bwd_cost: f32 = 1e20; | ||
| 163 | for (var dy: i32 = -4; dy <= 4; dy = dy + 1) { | ||
| 164 | for (var dx: i32 = -4; dx <= 4; dx = dx + 1) { | ||
| 165 | let v = vec2<f32>(f32(dx), f32(dy)); | ||
| 166 | let c = patch_sad_ba(in.uv, v, inv_sz) + reg * dot(v, v); | ||
| 167 | if (c < best_bwd_cost) { | ||
| 168 | best_bwd_cost = c; | ||
| 169 | best_bwd = v; | ||
| 170 | } | ||
| 171 | } | ||
| 172 | } | ||
| 173 | let bc_l = patch_sad_ba(in.uv, best_bwd + vec2<f32>(-1.0, 0.0), inv_sz); | ||
| 174 | let bc_r = patch_sad_ba(in.uv, best_bwd + vec2<f32>( 1.0, 0.0), inv_sz); | ||
| 175 | let bc_u = patch_sad_ba(in.uv, best_bwd + vec2<f32>(0.0, -1.0), inv_sz); | ||
| 176 | let bc_d = patch_sad_ba(in.uv, best_bwd + vec2<f32>(0.0, 1.0), inv_sz); | ||
| 177 | let bc_0 = patch_sad_ba(in.uv, best_bwd, inv_sz); | ||
| 178 | let bwd = best_bwd + vec2<f32>( | ||
| 179 | parabolic_offset(bc_l, bc_0, bc_r), | ||
| 180 | parabolic_offset(bc_u, bc_0, bc_d), | ||
| 181 | ); | ||
| 182 | |||
| 183 | return vec4<f32>(fwd, bwd); | ||
| 184 | } | ||
| 185 | |||
| 186 | // --- 2b. Finer levels (1/4, 1/2): upsample x2 + [-2..2] search + 1 iter Lucas-Kanade --- | ||
| 187 | |||
| 188 | fn lk_refine_ab(uv: vec2<f32>, flow_px: vec2<f32>, inv_sz: vec2<f32>) -> vec2<f32> { | ||
| 189 | let uv_t = uv + flow_px * inv_sz; | ||
| 190 | var a00: f32 = 0.015; | ||
| 191 | var a01: f32 = 0.0; | ||
| 192 | var a11: f32 = 0.015; | ||
| 193 | var b0: f32 = 0.0; | ||
| 194 | var b1: f32 = 0.0; | ||
| 195 | let dx_uv = vec2<f32>(inv_sz.x, 0.0); | ||
| 196 | let dy_uv = vec2<f32>(0.0, inv_sz.y); | ||
| 197 | |||
| 198 | for (var j: i32 = -1; j <= 1; j = j + 1) { | ||
| 199 | for (var i: i32 = -1; i <= 1; i = i + 1) { | ||
| 200 | let off = vec2<f32>(f32(i), f32(j)) * inv_sz; | ||
| 201 | let p_a = textureSampleLevel(tex_a, lin_samp, uv + off, 0.0); | ||
| 202 | let p_b = textureSampleLevel(tex_b, lin_samp, uv_t + off, 0.0); | ||
| 203 | let gx = 0.5 * ( | ||
| 204 | textureSampleLevel(tex_b, lin_samp, uv_t + off + dx_uv, 0.0) - | ||
| 205 | textureSampleLevel(tex_b, lin_samp, uv_t + off - dx_uv, 0.0) | ||
| 206 | ); | ||
| 207 | let gy = 0.5 * ( | ||
| 208 | textureSampleLevel(tex_b, lin_samp, uv_t + off + dy_uv, 0.0) - | ||
| 209 | textureSampleLevel(tex_b, lin_samp, uv_t + off - dy_uv, 0.0) | ||
| 210 | ); | ||
| 211 | let it = p_b - p_a; | ||
| 212 | let w = vec4<f32>(1.0, 0.85, 0.85, 0.5); | ||
| 213 | a00 = a00 + dot(gx * gx, w); | ||
| 214 | a01 = a01 + dot(gx * gy, w); | ||
| 215 | a11 = a11 + dot(gy * gy, w); | ||
| 216 | b0 = b0 - dot(gx * it, w); | ||
| 217 | b1 = b1 - dot(gy * it, w); | ||
| 218 | } | ||
| 219 | } | ||
| 220 | let det = a00 * a11 - a01 * a01; | ||
| 221 | if (abs(det) < 1e-6) { | ||
| 222 | return flow_px; | ||
| 223 | } | ||
| 224 | let delta = vec2<f32>( | ||
| 225 | (a11 * b0 - a01 * b1) / det, | ||
| 226 | (-a01 * b0 + a00 * b1) / det, | ||
| 227 | ); | ||
| 228 | return flow_px + clamp(delta, vec2<f32>(-1.0), vec2<f32>(1.0)); | ||
| 229 | } | ||
| 230 | |||
| 231 | fn lk_refine_ba(uv: vec2<f32>, flow_px: vec2<f32>, inv_sz: vec2<f32>) -> vec2<f32> { | ||
| 232 | let uv_t = uv + flow_px * inv_sz; | ||
| 233 | var a00: f32 = 0.015; | ||
| 234 | var a01: f32 = 0.0; | ||
| 235 | var a11: f32 = 0.015; | ||
| 236 | var b0: f32 = 0.0; | ||
| 237 | var b1: f32 = 0.0; | ||
| 238 | let dx_uv = vec2<f32>(inv_sz.x, 0.0); | ||
| 239 | let dy_uv = vec2<f32>(0.0, inv_sz.y); | ||
| 240 | |||
| 241 | for (var j: i32 = -1; j <= 1; j = j + 1) { | ||
| 242 | for (var i: i32 = -1; i <= 1; i = i + 1) { | ||
| 243 | let off = vec2<f32>(f32(i), f32(j)) * inv_sz; | ||
| 244 | let p_b = textureSampleLevel(tex_b, lin_samp, uv + off, 0.0); | ||
| 245 | let p_a = textureSampleLevel(tex_a, lin_samp, uv_t + off, 0.0); | ||
| 246 | let gx = 0.5 * ( | ||
| 247 | textureSampleLevel(tex_a, lin_samp, uv_t + off + dx_uv, 0.0) - | ||
| 248 | textureSampleLevel(tex_a, lin_samp, uv_t + off - dx_uv, 0.0) | ||
| 249 | ); | ||
| 250 | let gy = 0.5 * ( | ||
| 251 | textureSampleLevel(tex_a, lin_samp, uv_t + off + dy_uv, 0.0) - | ||
| 252 | textureSampleLevel(tex_a, lin_samp, uv_t + off - dy_uv, 0.0) | ||
| 253 | ); | ||
| 254 | let it = p_a - p_b; | ||
| 255 | let w = vec4<f32>(1.0, 0.85, 0.85, 0.5); | ||
| 256 | a00 = a00 + dot(gx * gx, w); | ||
| 257 | a01 = a01 + dot(gx * gy, w); | ||
| 258 | a11 = a11 + dot(gy * gy, w); | ||
| 259 | b0 = b0 - dot(gx * it, w); | ||
| 260 | b1 = b1 - dot(gy * it, w); | ||
| 261 | } | ||
| 262 | } | ||
| 263 | let det = a00 * a11 - a01 * a01; | ||
| 264 | if (abs(det) < 1e-6) { | ||
| 265 | return flow_px; | ||
| 266 | } | ||
| 267 | let delta = vec2<f32>( | ||
| 268 | (a11 * b0 - a01 * b1) / det, | ||
| 269 | (-a01 * b0 + a00 * b1) / det, | ||
| 270 | ); | ||
| 271 | return flow_px + clamp(delta, vec2<f32>(-1.0), vec2<f32>(1.0)); | ||
| 272 | } | ||
| 273 | |||
| 274 | @fragment | ||
| 275 | fn fs_flow_refine(in: VsOut) -> @location(0) vec4<f32> { | ||
| 276 | let inv_sz = u.dst_size.zw; | ||
| 277 | let scale = u.params.xy; | ||
| 278 | let prev = textureSampleLevel(tex_c, lin_samp, in.uv, 0.0); | ||
| 279 | let base_fwd = prev.xy * scale; | ||
| 280 | let base_bwd = prev.zw * scale; | ||
| 281 | let reg = 0.00015; | ||
| 282 | |||
| 283 | // Forward A -> B: local [-2..2] around base_fwd, plus zero-flow candidate for sharp static boundaries | ||
| 284 | var best_fwd = base_fwd; | ||
| 285 | var best_fwd_cost = patch_sad_ab(in.uv, base_fwd, inv_sz) + reg * dot(base_fwd, base_fwd); | ||
| 286 | let zero_fwd_cost = patch_sad_ab(in.uv, vec2<f32>(0.0), inv_sz); | ||
| 287 | if (zero_fwd_cost < best_fwd_cost) { | ||
| 288 | best_fwd_cost = zero_fwd_cost; | ||
| 289 | best_fwd = vec2<f32>(0.0); | ||
| 290 | } | ||
| 291 | for (var dy: i32 = -2; dy <= 2; dy = dy + 1) { | ||
| 292 | for (var dx: i32 = -2; dx <= 2; dx = dx + 1) { | ||
| 293 | if (dx == 0 && dy == 0) { continue; } | ||
| 294 | let v = base_fwd + vec2<f32>(f32(dx), f32(dy)); | ||
| 295 | let c = patch_sad_ab(in.uv, v, inv_sz) + reg * dot(v, v); | ||
| 296 | if (c < best_fwd_cost) { | ||
| 297 | best_fwd_cost = c; | ||
| 298 | best_fwd = v; | ||
| 299 | } | ||
| 300 | } | ||
| 301 | } | ||
| 302 | let fwd = lk_refine_ab(in.uv, best_fwd, inv_sz); | ||
| 303 | |||
| 304 | // Backward B -> A: local [-2..2] around base_bwd, plus zero-flow candidate | ||
| 305 | var best_bwd = base_bwd; | ||
| 306 | var best_bwd_cost = patch_sad_ba(in.uv, base_bwd, inv_sz) + reg * dot(base_bwd, base_bwd); | ||
| 307 | let zero_bwd_cost = patch_sad_ba(in.uv, vec2<f32>(0.0), inv_sz); | ||
| 308 | if (zero_bwd_cost < best_bwd_cost) { | ||
| 309 | best_bwd_cost = zero_bwd_cost; | ||
| 310 | best_bwd = vec2<f32>(0.0); | ||
| 311 | } | ||
| 312 | for (var dy: i32 = -2; dy <= 2; dy = dy + 1) { | ||
| 313 | for (var dx: i32 = -2; dx <= 2; dx = dx + 1) { | ||
| 314 | if (dx == 0 && dy == 0) { continue; } | ||
| 315 | let v = base_bwd + vec2<f32>(f32(dx), f32(dy)); | ||
| 316 | let c = patch_sad_ba(in.uv, v, inv_sz) + reg * dot(v, v); | ||
| 317 | if (c < best_bwd_cost) { | ||
| 318 | best_bwd_cost = c; | ||
| 319 | best_bwd = v; | ||
| 320 | } | ||
| 321 | } | ||
| 322 | } | ||
| 323 | let bwd = lk_refine_ba(in.uv, best_bwd, inv_sz); | ||
| 324 | |||
| 325 | return vec4<f32>(fwd, bwd); | ||
| 326 | } | ||
| 327 | |||
| 328 | // --- 2c. Edge-preserving 3x3 bilateral flow smoothing --- | ||
| 329 | // Uses feat_a edges to guide fwd smoothing and feat_b edges to guide bwd smoothing. | ||
| 330 | |||
| 331 | @fragment | ||
| 332 | fn fs_flow_smooth(in: VsOut) -> @location(0) vec4<f32> { | ||
| 333 | let inv_sz = u.dst_size.zw; | ||
| 334 | let center_flow = textureSampleLevel(tex_c, lin_samp, in.uv, 0.0); | ||
| 335 | let center_fa = textureSampleLevel(tex_a, lin_samp, in.uv, 0.0); | ||
| 336 | let center_fb = textureSampleLevel(tex_b, lin_samp, in.uv, 0.0); | ||
| 337 | |||
| 338 | var sum_fwd = vec2<f32>(0.0); | ||
| 339 | var w_fwd: f32 = 0.0; | ||
| 340 | var sum_bwd = vec2<f32>(0.0); | ||
| 341 | var w_bwd: f32 = 0.0; | ||
| 342 | |||
| 343 | let inv_2sig_f2 = 1.0 / (2.0 * 0.08 * 0.08); | ||
| 344 | let inv_2sig_v2 = 1.0 / (2.0 * 1.5 * 1.5); | ||
| 345 | |||
| 346 | for (var dy: i32 = -1; dy <= 1; dy = dy + 1) { | ||
| 347 | for (var dx: i32 = -1; dx <= 1; dx = dx + 1) { | ||
| 348 | let off = vec2<f32>(f32(dx), f32(dy)) * inv_sz; | ||
| 349 | let q_uv = in.uv + off; | ||
| 350 | let q_flow = textureSampleLevel(tex_c, lin_samp, q_uv, 0.0); | ||
| 351 | let q_fa = textureSampleLevel(tex_a, lin_samp, q_uv, 0.0); | ||
| 352 | let q_fb = textureSampleLevel(tex_b, lin_samp, q_uv, 0.0); | ||
| 353 | |||
| 354 | let spatial = select(0.5, 1.0, dx == 0 && dy == 0); | ||
| 355 | |||
| 356 | let dfa = q_fa - center_fa; | ||
| 357 | let dfv = q_flow.xy - center_flow.xy; | ||
| 358 | let wf = spatial * exp(-dot(dfa, dfa) * inv_2sig_f2 - dot(dfv, dfv) * inv_2sig_v2); | ||
| 359 | sum_fwd = sum_fwd + wf * q_flow.xy; | ||
| 360 | w_fwd = w_fwd + wf; | ||
| 361 | |||
| 362 | let dfb = q_fb - center_fb; | ||
| 363 | let dbv = q_flow.zw - center_flow.zw; | ||
| 364 | let wb = spatial * exp(-dot(dfb, dfb) * inv_2sig_f2 - dot(dbv, dbv) * inv_2sig_v2); | ||
| 365 | sum_bwd = sum_bwd + wb * q_flow.zw; | ||
| 366 | w_bwd = w_bwd + wb; | ||
| 367 | } | ||
| 368 | } | ||
| 369 | |||
| 370 | let out_fwd = select(center_flow.xy, sum_fwd / w_fwd, w_fwd > 1e-5); | ||
| 371 | let out_bwd = select(center_flow.zw, sum_bwd / w_bwd, w_bwd > 1e-5); | ||
| 372 | return vec4<f32>(out_fwd, out_bwd); | ||
| 373 | } | ||
| 374 | |||
| 375 | // --- 3. Bidirectional occlusion-aware warp & blend into target_format --- | ||
| 376 | |||
| 377 | struct WarpCandidate { | ||
| 378 | col_a: vec4<f32>, | ||
| 379 | col_b: vec4<f32>, | ||
| 380 | err_va: f32, | ||
| 381 | err_vb: f32, | ||
| 382 | score: f32, | ||
| 383 | }; | ||
| 384 | |||
| 385 | fn eval_candidate(uv: vec2<f32>, v_px: vec2<f32>, alpha: f32, inv_sz: vec2<f32>, flow_scale: vec2<f32>) -> WarpCandidate { | ||
| 386 | let v_uv = v_px * inv_sz; | ||
| 387 | let uv_a = uv - alpha * v_uv; | ||
| 388 | let uv_b = uv + (1.0 - alpha) * v_uv; | ||
| 389 | |||
| 390 | let col_a = textureSampleLevel(tex_a, lin_samp, uv_a, 0.0); | ||
| 391 | let col_b = textureSampleLevel(tex_b, lin_samp, uv_b, 0.0); | ||
| 392 | |||
| 393 | let f_at_a = textureSampleLevel(tex_c, lin_samp, uv_a, 0.0).xy * flow_scale; | ||
| 394 | let f_at_b = -textureSampleLevel(tex_c, lin_samp, uv_b, 0.0).zw * flow_scale; | ||
| 395 | |||
| 396 | let err_va = length(f_at_a - v_px); | ||
| 397 | let err_vb = length(f_at_b - v_px); | ||
| 398 | let photo_err = length(col_a - col_b); | ||
| 399 | |||
| 400 | let cost_both = err_va + err_vb + 6.0 * photo_err; | ||
| 401 | let cost_one = min(err_va, err_vb) + 1.5; | ||
| 402 | |||
| 403 | var out: WarpCandidate; | ||
| 404 | out.col_a = col_a; | ||
| 405 | out.col_b = col_b; | ||
| 406 | out.err_va = err_va; | ||
| 407 | out.err_vb = err_vb; | ||
| 408 | out.score = min(cost_both, cost_one); | ||
| 409 | return out; | ||
| 410 | } | ||
| 411 | |||
| 412 | @fragment | ||
| 413 | fn fs_warp_flow(in: VsOut) -> @location(0) vec4<f32> { | ||
| 414 | let inv_sz = u.dst_size.zw; | ||
| 415 | let flow_scale = u.params.xy; | ||
| 416 | let alpha = clamp(u.params.z, 0.0, 1.0); | ||
| 417 | |||
| 418 | if (alpha <= 1e-4) { | ||
| 419 | return textureSampleLevel(tex_a, lin_samp, in.uv, 0.0); | ||
| 420 | } | ||
| 421 | if (alpha >= 1.0 - 1e-4) { | ||
| 422 | return textureSampleLevel(tex_b, lin_samp, in.uv, 0.0); | ||
| 423 | } | ||
| 424 | |||
| 425 | let raw_flow = textureSampleLevel(tex_c, lin_samp, in.uv, 0.0); | ||
| 426 | let v_a = raw_flow.xy * flow_scale; | ||
| 427 | let v_b = -raw_flow.zw * flow_scale; | ||
| 428 | |||
| 429 | let ca = eval_candidate(in.uv, v_a, alpha, inv_sz, flow_scale); | ||
| 430 | let cb = eval_candidate(in.uv, v_b, alpha, inv_sz, flow_scale); | ||
| 431 | |||
| 432 | // Pick the physically consistent candidate (forward-origin vs backward-origin) | ||
| 433 | let use_a = ca.score <= cb.score; | ||
| 434 | let col_a = select(cb.col_a, ca.col_a, use_a); | ||
| 435 | let col_b = select(cb.col_b, ca.col_b, use_a); | ||
| 436 | let err_va = select(cb.err_va, ca.err_va, use_a); | ||
| 437 | let err_vb = select(cb.err_vb, ca.err_vb, use_a); | ||
| 438 | |||
| 439 | // Occlusion-aware blending weights based on forward-backward self-consistency | ||
| 440 | let inv_2sig2 = 1.0 / (2.0 * 1.5 * 1.5); | ||
| 441 | let wa = (1.0 - alpha) * exp(-err_va * err_va * inv_2sig2); | ||
| 442 | let wb = alpha * exp(-err_vb * err_vb * inv_2sig2); | ||
| 443 | let wsum = wa + wb; | ||
| 444 | |||
| 445 | if (wsum > 1e-4) { | ||
| 446 | return (wa * col_a + wb * col_b) / wsum; | ||
| 447 | } | ||
| 448 | return mix(col_a, col_b, alpha); | ||
| 449 | } | ||
| 450 | "#; | ||
| 451 | |||
| 452 | /// Self-contained `wgpu` pipelines for GPU optical flow and motion-compensated frame interpolation. | ||
| 453 | pub struct OpticalFlowPipelines { | ||
| 454 | shader: wgpu::ShaderModule, | ||
| 455 | bgl: wgpu::BindGroupLayout, | ||
| 456 | pipeline_layout: wgpu::PipelineLayout, | ||
| 457 | sampler: wgpu::Sampler, | ||
| 458 | extract_features: wgpu::RenderPipeline, | ||
| 459 | downsample: wgpu::RenderPipeline, | ||
| 460 | flow_coarse: wgpu::RenderPipeline, | ||
| 461 | flow_refine: wgpu::RenderPipeline, | ||
| 462 | flow_smooth: wgpu::RenderPipeline, | ||
| 463 | blend_pipelines: RwLock<HashMap<wgpu::TextureFormat, wgpu::RenderPipeline>>, | ||
| 464 | warp_pipelines: RwLock<HashMap<wgpu::TextureFormat, wgpu::RenderPipeline>>, | ||
| 465 | } | ||
| 466 | |||
| 467 | impl OpticalFlowPipelines { | ||
| 468 | pub fn new(device: &wgpu::Device) -> Self { | ||
| 469 | let shader = device.create_shader_module(wgpu::ShaderModuleDescriptor { | ||
| 470 | label: Some("optflow-shader"), | ||
| 471 | source: wgpu::ShaderSource::Wgsl(OPTFLOW_WGSL.into()), | ||
| 472 | }); | ||
| 473 | |||
| 474 | let tex_entry = |binding| wgpu::BindGroupLayoutEntry { | ||
| 475 | binding, | ||
| 476 | visibility: wgpu::ShaderStages::FRAGMENT, | ||
| 477 | ty: wgpu::BindingType::Texture { | ||
| 478 | sample_type: wgpu::TextureSampleType::Float { filterable: true }, | ||
| 479 | view_dimension: wgpu::TextureViewDimension::D2, | ||
| 480 | multisampled: false, | ||
| 481 | }, | ||
| 482 | count: None, | ||
| 483 | }; | ||
| 484 | |||
| 485 | let bgl = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { | ||
| 486 | label: Some("optflow-bgl"), | ||
| 487 | entries: &[ | ||
| 488 | tex_entry(0), | ||
| 489 | tex_entry(1), | ||
| 490 | tex_entry(2), | ||
| 491 | wgpu::BindGroupLayoutEntry { | ||
| 492 | binding: 3, | ||
| 493 | visibility: wgpu::ShaderStages::FRAGMENT, | ||
| 494 | ty: wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Filtering), | ||
| 495 | count: None, | ||
| 496 | }, | ||
| 497 | wgpu::BindGroupLayoutEntry { | ||
| 498 | binding: 4, | ||
| 499 | visibility: wgpu::ShaderStages::FRAGMENT, | ||
| 500 | ty: wgpu::BindingType::Buffer { | ||
| 501 | ty: wgpu::BufferBindingType::Uniform, | ||
| 502 | has_dynamic_offset: false, | ||
| 503 | min_binding_size: None, | ||
| 504 | }, | ||
| 505 | count: None, | ||
| 506 | }, | ||
| 507 | ], | ||
| 508 | }); | ||
| 509 | |||
| 510 | let pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { | ||
| 511 | label: Some("optflow-pl"), | ||
| 512 | bind_group_layouts: &[Some(&bgl)], | ||
| 513 | immediate_size: 0, | ||
| 514 | }); | ||
| 515 | |||
| 516 | let sampler = device.create_sampler(&wgpu::SamplerDescriptor { | ||
| 517 | label: Some("optflow-linear"), | ||
| 518 | address_mode_u: wgpu::AddressMode::ClampToEdge, | ||
| 519 | address_mode_v: wgpu::AddressMode::ClampToEdge, | ||
| 520 | mag_filter: wgpu::FilterMode::Linear, | ||
| 521 | min_filter: wgpu::FilterMode::Linear, | ||
| 522 | mipmap_filter: wgpu::MipmapFilterMode::Nearest, | ||
| 523 | ..Default::default() | ||
| 524 | }); | ||
| 525 | |||
| 526 | let f16 = wgpu::TextureFormat::Rgba16Float; | ||
| 527 | let extract_features = | ||
| 528 | create_fullscreen_pipeline(device, &shader, &pipeline_layout, "fs_extract_features", f16); | ||
| 529 | let downsample = | ||
| 530 | create_fullscreen_pipeline(device, &shader, &pipeline_layout, "fs_downsample", f16); | ||
| 531 | let flow_coarse = | ||
| 532 | create_fullscreen_pipeline(device, &shader, &pipeline_layout, "fs_flow_coarse", f16); | ||
| 533 | let flow_refine = | ||
| 534 | create_fullscreen_pipeline(device, &shader, &pipeline_layout, "fs_flow_refine", f16); | ||
| 535 | let flow_smooth = | ||
| 536 | create_fullscreen_pipeline(device, &shader, &pipeline_layout, "fs_flow_smooth", f16); | ||
| 537 | |||
| 538 | Self { | ||
| 539 | shader, | ||
| 540 | bgl, | ||
| 541 | pipeline_layout, | ||
| 542 | sampler, | ||
| 543 | extract_features, | ||
| 544 | downsample, | ||
| 545 | flow_coarse, | ||
| 546 | flow_refine, | ||
| 547 | flow_smooth, | ||
| 548 | blend_pipelines: RwLock::new(HashMap::new()), | ||
| 549 | warp_pipelines: RwLock::new(HashMap::new()), | ||
| 550 | } | ||
| 551 | } | ||
| 552 | |||
| 553 | fn ensure_target_pipeline( | ||
| 554 | &self, | ||
| 555 | device: &wgpu::Device, | ||
| 556 | cache: &RwLock<HashMap<wgpu::TextureFormat, wgpu::RenderPipeline>>, | ||
| 557 | entry: &str, | ||
| 558 | format: wgpu::TextureFormat, | ||
| 559 | ) { | ||
| 560 | if cache.read().unwrap().contains_key(&format) { | ||
| 561 | return; | ||
| 562 | } | ||
| 563 | let pipe = create_fullscreen_pipeline(device, &self.shader, &self.pipeline_layout, entry, format); | ||
| 564 | cache.write().unwrap().insert(format, pipe); | ||
| 565 | } | ||
| 566 | |||
| 567 | #[allow(clippy::too_many_arguments)] | ||
| 568 | fn run_pass( | ||
| 569 | &self, | ||
| 570 | device: &wgpu::Device, | ||
| 571 | queue: &wgpu::Queue, | ||
| 572 | enc: &mut wgpu::CommandEncoder, | ||
| 573 | pipeline: &wgpu::RenderPipeline, | ||
| 574 | label: &str, | ||
| 575 | view_a: &wgpu::TextureView, | ||
| 576 | view_b: &wgpu::TextureView, | ||
| 577 | view_c: &wgpu::TextureView, | ||
| 578 | dst_view: &wgpu::TextureView, | ||
| 579 | dst_size: [u32; 2], | ||
| 580 | params: [f32; 4], | ||
| 581 | ) { | ||
| 582 | let w = dst_size[0].max(1) as f32; | ||
| 583 | let h = dst_size[1].max(1) as f32; | ||
| 584 | let uniform = OptFlowUniform { | ||
| 585 | dst_size: [w, h, 1.0 / w, 1.0 / h], | ||
| 586 | params, | ||
| 587 | }; | ||
| 588 | let ubuf = device.create_buffer(&wgpu::BufferDescriptor { | ||
| 589 | label: Some("optflow-uniform"), | ||
| 590 | size: std::mem::size_of::<OptFlowUniform>() as u64, | ||
| 591 | usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST, | ||
| 592 | mapped_at_creation: false, | ||
| 593 | }); | ||
| 594 | queue.write_buffer(&ubuf, 0, bytemuck::bytes_of(&uniform)); | ||
| 595 | |||
| 596 | let bg = device.create_bind_group(&wgpu::BindGroupDescriptor { | ||
| 597 | label: Some(label), | ||
| 598 | layout: &self.bgl, | ||
| 599 | entries: &[ | ||
| 600 | wgpu::BindGroupEntry { | ||
| 601 | binding: 0, | ||
| 602 | resource: wgpu::BindingResource::TextureView(view_a), | ||
| 603 | }, | ||
| 604 | wgpu::BindGroupEntry { | ||
| 605 | binding: 1, | ||
| 606 | resource: wgpu::BindingResource::TextureView(view_b), | ||
| 607 | }, | ||
| 608 | wgpu::BindGroupEntry { | ||
| 609 | binding: 2, | ||
| 610 | resource: wgpu::BindingResource::TextureView(view_c), | ||
| 611 | }, | ||
| 612 | wgpu::BindGroupEntry { | ||
| 613 | binding: 3, | ||
| 614 | resource: wgpu::BindingResource::Sampler(&self.sampler), | ||
| 615 | }, | ||
| 616 | wgpu::BindGroupEntry { | ||
| 617 | binding: 4, | ||
| 618 | resource: ubuf.as_entire_binding(), | ||
| 619 | }, | ||
| 620 | ], | ||
| 621 | }); | ||
| 622 | |||
| 623 | let mut rp = enc.begin_render_pass(&wgpu::RenderPassDescriptor { | ||
| 624 | label: Some(label), | ||
| 625 | color_attachments: &[Some(wgpu::RenderPassColorAttachment { | ||
| 626 | view: dst_view, | ||
| 627 | depth_slice: None, | ||
| 628 | resolve_target: None, | ||
| 629 | ops: wgpu::Operations { | ||
| 630 | load: wgpu::LoadOp::Clear(wgpu::Color::TRANSPARENT), | ||
| 631 | store: wgpu::StoreOp::Store, | ||
| 632 | }, | ||
| 633 | })], | ||
| 634 | depth_stencil_attachment: None, | ||
| 635 | timestamp_writes: None, | ||
| 636 | occlusion_query_set: None, | ||
| 637 | multiview_mask: None, | ||
| 638 | }); | ||
| 639 | rp.set_pipeline(pipeline); | ||
| 640 | rp.set_bind_group(0, &bg, &[]); | ||
| 641 | rp.draw(0..3, 0..1); | ||
| 642 | } | ||
| 643 | |||
| 644 | /// Linear cross-dissolve `(1 - alpha) * A + alpha * B` for `TimeStretcher` | ||
| 645 | /// `InterpolateBetweenFrames = 1` (`Blend`). | ||
| 646 | #[allow(clippy::too_many_arguments)] | ||
| 647 | pub fn blend_frames( | ||
| 648 | &self, | ||
| 649 | device: &wgpu::Device, | ||
| 650 | queue: &wgpu::Queue, | ||
| 651 | enc: &mut wgpu::CommandEncoder, | ||
| 652 | frame_a: &CachedTexture, | ||
| 653 | frame_b: &CachedTexture, | ||
| 654 | alpha: f32, | ||
| 655 | target_format: wgpu::TextureFormat, | ||
| 656 | ) -> CachedTexture { | ||
| 657 | self.ensure_target_pipeline(device, &self.blend_pipelines, "fs_blend", target_format); | ||
| 658 | let key = hash_interp(frame_a.content_hash, frame_b.content_hash, alpha, 1, target_format); | ||
| 659 | let dst = alloc_output_texture(device, frame_a, target_format, key); | ||
| 660 | |||
| 661 | let guard = self.blend_pipelines.read().unwrap(); | ||
| 662 | let pipe = guard.get(&target_format).unwrap(); | ||
| 663 | self.run_pass( | ||
| 664 | device, | ||
| 665 | queue, | ||
| 666 | enc, | ||
| 667 | pipe, | ||
| 668 | "optflow-blend", | ||
| 669 | &frame_a.view, | ||
| 670 | &frame_b.view, | ||
| 671 | &frame_a.view, | ||
| 672 | &dst.view, | ||
| 673 | dst.size, | ||
| 674 | [1.0, 1.0, alpha.clamp(0.0, 1.0), 0.0], | ||
| 675 | ); | ||
| 676 | dst | ||
| 677 | } | ||
| 678 | |||
| 679 | /// Multi-scale coarse-to-fine GPU optical flow + bidirectional occlusion-aware warp | ||
| 680 | /// interpolation for `Dimension.OpticalFlow` and `TimeStretcher` | ||
| 681 | /// `InterpolateBetweenFrames = 2` (`Flow`). | ||
| 682 | #[allow(clippy::too_many_arguments)] | ||
| 683 | pub fn interpolate_flow( | ||
| 684 | &self, | ||
| 685 | device: &wgpu::Device, | ||
| 686 | queue: &wgpu::Queue, | ||
| 687 | enc: &mut wgpu::CommandEncoder, | ||
| 688 | frame_a: &CachedTexture, | ||
| 689 | frame_b: &CachedTexture, | ||
| 690 | alpha: f32, | ||
| 691 | target_format: wgpu::TextureFormat, | ||
| 692 | ) -> CachedTexture { | ||
| 693 | self.ensure_target_pipeline(device, &self.warp_pipelines, "fs_warp_flow", target_format); | ||
| 694 | let key = hash_interp(frame_a.content_hash, frame_b.content_hash, alpha, 2, target_format); | ||
| 695 | let dst = alloc_output_texture(device, frame_a, target_format, key); | ||
| 696 | |||
| 697 | // Compute 4-level pyramid dimensions: full, 1/2, 1/4, 1/8 | ||
| 698 | let s0 = [frame_a.size[0].max(1), frame_a.size[1].max(1)]; | ||
| 699 | let s1 = [s0[0].div_ceil(2).max(1), s0[1].div_ceil(2).max(1)]; | ||
| 700 | let s2 = [s1[0].div_ceil(2).max(1), s1[1].div_ceil(2).max(1)]; | ||
| 701 | let s3 = [s2[0].div_ceil(2).max(1), s2[1].div_ceil(2).max(1)]; | ||
| 702 | |||
| 703 | // 1. Build (luma, R-G, B-Y, alpha) feature pyramids for A and B | ||
| 704 | let (fa0_tex, fa0_view) = alloc_f16_tex(device, s0, "optflow-fa0"); | ||
| 705 | let (fb0_tex, fb0_view) = alloc_f16_tex(device, s0, "optflow-fb0"); | ||
| 706 | self.run_pass( | ||
| 707 | device, queue, enc, &self.extract_features, "optflow-extract-a", | ||
| 708 | &frame_a.view, &frame_a.view, &frame_a.view, &fa0_view, s0, [0.0; 4], | ||
| 709 | ); | ||
| 710 | self.run_pass( | ||
| 711 | device, queue, enc, &self.extract_features, "optflow-extract-b", | ||
| 712 | &frame_b.view, &frame_b.view, &frame_b.view, &fb0_view, s0, [0.0; 4], | ||
| 713 | ); | ||
| 714 | |||
| 715 | let (fa1_tex, fa1_view) = alloc_f16_tex(device, s1, "optflow-fa1"); | ||
| 716 | let (fb1_tex, fb1_view) = alloc_f16_tex(device, s1, "optflow-fb1"); | ||
| 717 | self.run_pass( | ||
| 718 | device, queue, enc, &self.downsample, "optflow-down-a1", | ||
| 719 | &fa0_view, &fa0_view, &fa0_view, &fa1_view, s1, [0.0; 4], | ||
| 720 | ); | ||
| 721 | self.run_pass( | ||
| 722 | device, queue, enc, &self.downsample, "optflow-down-b1", | ||
| 723 | &fb0_view, &fb0_view, &fb0_view, &fb1_view, s1, [0.0; 4], | ||
| 724 | ); | ||
| 725 | |||
| 726 | let (fa2_tex, fa2_view) = alloc_f16_tex(device, s2, "optflow-fa2"); | ||
| 727 | let (fb2_tex, fb2_view) = alloc_f16_tex(device, s2, "optflow-fb2"); | ||
| 728 | self.run_pass( | ||
| 729 | device, queue, enc, &self.downsample, "optflow-down-a2", | ||
| 730 | &fa1_view, &fa1_view, &fa1_view, &fa2_view, s2, [0.0; 4], | ||
| 731 | ); | ||
| 732 | self.run_pass( | ||
| 733 | device, queue, enc, &self.downsample, "optflow-down-b2", | ||
| 734 | &fb1_view, &fb1_view, &fb1_view, &fb2_view, s2, [0.0; 4], | ||
| 735 | ); | ||
| 736 | |||
| 737 | let (fa3_tex, fa3_view) = alloc_f16_tex(device, s3, "optflow-fa3"); | ||
| 738 | let (fb3_tex, fb3_view) = alloc_f16_tex(device, s3, "optflow-fb3"); | ||
| 739 | self.run_pass( | ||
| 740 | device, queue, enc, &self.downsample, "optflow-down-a3", | ||
| 741 | &fa2_view, &fa2_view, &fa2_view, &fa3_view, s3, [0.0; 4], | ||
| 742 | ); | ||
| 743 | self.run_pass( | ||
| 744 | device, queue, enc, &self.downsample, "optflow-down-b3", | ||
| 745 | &fb2_view, &fb2_view, &fb2_view, &fb3_view, s3, [0.0; 4], | ||
| 746 | ); | ||
| 747 | |||
| 748 | // 2. Coarse-to-fine bidirectional flow estimation | ||
| 749 | // Level 3 (1/8 res): exhaustive [-4..4] search + parabolic subpixel + bilateral smooth | ||
| 750 | let (flow3_raw_tex, flow3_raw_view) = alloc_f16_tex(device, s3, "optflow-f3-raw"); | ||
| 751 | let (flow3_tex, flow3_view) = alloc_f16_tex(device, s3, "optflow-f3"); | ||
| 752 | self.run_pass( | ||
| 753 | device, queue, enc, &self.flow_coarse, "optflow-coarse-l3", | ||
| 754 | &fa3_view, &fb3_view, &fa3_view, &flow3_raw_view, s3, [0.0; 4], | ||
| 755 | ); | ||
| 756 | self.run_pass( | ||
| 757 | device, queue, enc, &self.flow_smooth, "optflow-smooth-l3", | ||
| 758 | &fa3_view, &fb3_view, &flow3_raw_view, &flow3_view, s3, [0.0; 4], | ||
| 759 | ); | ||
| 760 | |||
| 761 | // Level 2 (1/4 res): upsample + [-2..2] refine + LK + bilateral smooth | ||
| 762 | let scale_3_to_2 = [s2[0] as f32 / s3[0] as f32, s2[1] as f32 / s3[1] as f32, 0.0, 0.0]; | ||
| 763 | let (flow2_raw_tex, flow2_raw_view) = alloc_f16_tex(device, s2, "optflow-f2-raw"); | ||
| 764 | let (flow2_tex, flow2_view) = alloc_f16_tex(device, s2, "optflow-f2"); | ||
| 765 | self.run_pass( | ||
| 766 | device, queue, enc, &self.flow_refine, "optflow-refine-l2", | ||
| 767 | &fa2_view, &fb2_view, &flow3_view, &flow2_raw_view, s2, scale_3_to_2, | ||
| 768 | ); | ||
| 769 | self.run_pass( | ||
| 770 | device, queue, enc, &self.flow_smooth, "optflow-smooth-l2", | ||
| 771 | &fa2_view, &fb2_view, &flow2_raw_view, &flow2_view, s2, [0.0; 4], | ||
| 772 | ); | ||
| 773 | |||
| 774 | // Level 1 (1/2 res): upsample + [-2..2] refine + LK + bilateral smooth | ||
| 775 | let scale_2_to_1 = [s1[0] as f32 / s2[0] as f32, s1[1] as f32 / s2[1] as f32, 0.0, 0.0]; | ||
| 776 | let (flow1_raw_tex, flow1_raw_view) = alloc_f16_tex(device, s1, "optflow-f1-raw"); | ||
| 777 | let (flow1_tex, flow1_view) = alloc_f16_tex(device, s1, "optflow-f1"); | ||
| 778 | self.run_pass( | ||
| 779 | device, queue, enc, &self.flow_refine, "optflow-refine-l1", | ||
| 780 | &fa1_view, &fb1_view, &flow2_view, &flow1_raw_view, s1, scale_2_to_1, | ||
| 781 | ); | ||
| 782 | self.run_pass( | ||
| 783 | device, queue, enc, &self.flow_smooth, "optflow-smooth-l1", | ||
| 784 | &fa1_view, &fb1_view, &flow1_raw_view, &flow1_view, s1, [0.0; 4], | ||
| 785 | ); | ||
| 786 | |||
| 787 | // 3. Full-resolution bidirectional occlusion-aware warp & blend | ||
| 788 | let scale_1_to_0 = [ | ||
| 789 | s0[0] as f32 / s1[0] as f32, | ||
| 790 | s0[1] as f32 / s1[1] as f32, | ||
| 791 | alpha.clamp(0.0, 1.0), | ||
| 792 | 0.0, | ||
| 793 | ]; | ||
| 794 | { | ||
| 795 | let guard = self.warp_pipelines.read().unwrap(); | ||
| 796 | let pipe = guard.get(&target_format).unwrap(); | ||
| 797 | self.run_pass( | ||
| 798 | device, | ||
| 799 | queue, | ||
| 800 | enc, | ||
| 801 | pipe, | ||
| 802 | "optflow-warp", | ||
| 803 | &frame_a.view, | ||
| 804 | &frame_b.view, | ||
| 805 | &flow1_view, | ||
| 806 | &dst.view, | ||
| 807 | s0, | ||
| 808 | scale_1_to_0, | ||
| 809 | ); | ||
| 810 | } | ||
| 811 | |||
| 812 | // Keep temporary textures alive until all passes are encoded into `enc`. | ||
| 813 | drop(( | ||
| 814 | fa0_tex, fb0_tex, fa1_tex, fb1_tex, fa2_tex, fb2_tex, fa3_tex, fb3_tex, | ||
| 815 | flow3_raw_tex, flow3_tex, flow2_raw_tex, flow2_tex, flow1_raw_tex, flow1_tex, | ||
| 816 | )); | ||
| 817 | |||
| 818 | dst | ||
| 819 | } | ||
| 820 | } | ||
| 821 | |||
| 822 | fn create_fullscreen_pipeline( | ||
| 823 | device: &wgpu::Device, | ||
| 824 | shader: &wgpu::ShaderModule, | ||
| 825 | layout: &wgpu::PipelineLayout, | ||
| 826 | frag_entry: &str, | ||
| 827 | format: wgpu::TextureFormat, | ||
| 828 | ) -> wgpu::RenderPipeline { | ||
| 829 | device.create_render_pipeline(&wgpu::RenderPipelineDescriptor { | ||
| 830 | label: Some(frag_entry), | ||
| 831 | layout: Some(layout), | ||
| 832 | vertex: wgpu::VertexState { | ||
| 833 | module: shader, | ||
| 834 | entry_point: Some("vs_fullscreen"), | ||
| 835 | compilation_options: Default::default(), | ||
| 836 | buffers: &[], | ||
| 837 | }, | ||
| 838 | fragment: Some(wgpu::FragmentState { | ||
| 839 | module: shader, | ||
| 840 | entry_point: Some(frag_entry), | ||
| 841 | compilation_options: Default::default(), | ||
| 842 | targets: &[Some(wgpu::ColorTargetState { | ||
| 843 | format, | ||
| 844 | blend: None, | ||
| 845 | write_mask: wgpu::ColorWrites::ALL, | ||
| 846 | })], | ||
| 847 | }), | ||
| 848 | primitive: wgpu::PrimitiveState { | ||
| 849 | topology: wgpu::PrimitiveTopology::TriangleList, | ||
| 850 | ..Default::default() | ||
| 851 | }, | ||
| 852 | depth_stencil: None, | ||
| 853 | multisample: wgpu::MultisampleState::default(), | ||
| 854 | multiview_mask: None, | ||
| 855 | cache: None, | ||
| 856 | }) | ||
| 857 | } | ||
| 858 | |||
| 859 | fn alloc_f16_tex( | ||
| 860 | device: &wgpu::Device, | ||
| 861 | size: [u32; 2], | ||
| 862 | label: &str, | ||
| 863 | ) -> (wgpu::Texture, wgpu::TextureView) { | ||
| 864 | let tex = device.create_texture(&wgpu::TextureDescriptor { | ||
| 865 | label: Some(label), | ||
| 866 | size: wgpu::Extent3d { | ||
| 867 | width: size[0].max(1), | ||
| 868 | height: size[1].max(1), | ||
| 869 | depth_or_array_layers: 1, | ||
| 870 | }, | ||
| 871 | mip_level_count: 1, | ||
| 872 | sample_count: 1, | ||
| 873 | dimension: wgpu::TextureDimension::D2, | ||
| 874 | format: wgpu::TextureFormat::Rgba16Float, | ||
| 875 | usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::RENDER_ATTACHMENT, | ||
| 876 | view_formats: &[], | ||
| 877 | }); | ||
| 878 | let view = tex.create_view(&wgpu::TextureViewDescriptor::default()); | ||
| 879 | (tex, view) | ||
| 880 | } | ||
| 881 | |||
| 882 | fn alloc_output_texture( | ||
| 883 | device: &wgpu::Device, | ||
| 884 | reference: &CachedTexture, | ||
| 885 | format: wgpu::TextureFormat, | ||
| 886 | content_hash: u64, | ||
| 887 | ) -> CachedTexture { | ||
| 888 | let size = [reference.size[0].max(1), reference.size[1].max(1)]; | ||
| 889 | let depth = match format { | ||
| 890 | wgpu::TextureFormat::Rgba16Float => BitDepth::Float16, | ||
| 891 | wgpu::TextureFormat::Rgba32Float => BitDepth::Float32, | ||
| 892 | _ => BitDepth::Int8, | ||
| 893 | }; | ||
| 894 | let tex = device.create_texture(&wgpu::TextureDescriptor { | ||
| 895 | label: Some("optflow-out"), | ||
| 896 | size: wgpu::Extent3d { | ||
| 897 | width: size[0], | ||
| 898 | height: size[1], | ||
| 899 | depth_or_array_layers: 1, | ||
| 900 | }, | ||
| 901 | mip_level_count: 1, | ||
| 902 | sample_count: 1, | ||
| 903 | dimension: wgpu::TextureDimension::D2, | ||
| 904 | format, | ||
| 905 | usage: wgpu::TextureUsages::TEXTURE_BINDING | ||
| 906 | | wgpu::TextureUsages::STORAGE_BINDING | ||
| 907 | | wgpu::TextureUsages::COPY_SRC | ||
| 908 | | wgpu::TextureUsages::COPY_DST | ||
| 909 | | wgpu::TextureUsages::RENDER_ATTACHMENT, | ||
| 910 | view_formats: &[], | ||
| 911 | }); | ||
| 912 | CachedTexture::from_texture_dod_depth( | ||
| 913 | tex, | ||
| 914 | size, | ||
| 915 | reference.origin, | ||
| 916 | [reference.canvas_size[0].max(1), reference.canvas_size[1].max(1)], | ||
| 917 | depth, | ||
| 918 | content_hash, | ||
| 919 | ) | ||
| 920 | } | ||
| 921 | |||
| 922 | fn hash_interp( | ||
| 923 | hash_a: u64, | ||
| 924 | hash_b: u64, | ||
| 925 | alpha: f32, | ||
| 926 | mode: u8, | ||
| 927 | format: wgpu::TextureFormat, | ||
| 928 | ) -> u64 { | ||
| 929 | let mut h = DefaultHasher::new(); | ||
| 930 | "optflow".hash(&mut h); | ||
| 931 | hash_a.hash(&mut h); | ||
| 932 | hash_b.hash(&mut h); | ||
| 933 | alpha.to_bits().hash(&mut h); | ||
| 934 | mode.hash(&mut h); | ||
| 935 | format.hash(&mut h); | ||
| 936 | h.finish() | ||
| 937 | } | ||
| 938 | |||
| 939 | #[cfg(test)] | ||
| 940 | mod tests { | ||
| 941 | use super::*; | ||
| 942 | |||
| 943 | fn create_headless_device() -> (wgpu::Device, wgpu::Queue) { | ||
| 944 | let instance = wgpu::Instance::new(wgpu::InstanceDescriptor::new_without_display_handle()); | ||
| 945 | let adapter = pollster::block_on(instance.request_adapter(&Default::default())) | ||
| 946 | .expect("no GPU adapter found"); | ||
| 947 | let mut req_features = wgpu::Features::empty(); | ||
| 948 | if adapter.features().contains(wgpu::Features::FLOAT32_FILTERABLE) { | ||
| 949 | req_features |= wgpu::Features::FLOAT32_FILTERABLE; | ||
| 950 | } | ||
| 951 | pollster::block_on(adapter.request_device(&wgpu::DeviceDescriptor { | ||
| 952 | required_features: req_features, | ||
| 953 | ..Default::default() | ||
| 954 | })) | ||
| 955 | .expect("failed to request GPU device") | ||
| 956 | } | ||
| 957 | |||
| 958 | /// Renders a 256x144 RGBA8 scene with a subtle static background and a textured/gradient | ||
| 959 | /// 48x48 box whose top-left corner is at `(box_x, box_y)`. | ||
| 960 | fn render_box_scene(w: u32, h: u32, box_x: i32, box_y: i32) -> Vec<u8> { | ||
| 961 | let mut pixels = vec![0u8; (w * h * 4) as usize]; | ||
| 962 | let box_size = 48i32; | ||
| 963 | for y in 0..h as i32 { | ||
| 964 | for x in 0..w as i32 { | ||
| 965 | // Static dark-slate subtle background | ||
| 966 | let mut r = 24.0 + (x as f32 / w as f32) * 10.0; | ||
| 967 | let mut g = 28.0 + (y as f32 / h as f32) * 10.0; | ||
| 968 | let mut b = 36.0; | ||
| 969 | |||
| 970 | let lx = x - box_x; | ||
| 971 | let ly = y - box_y; | ||
| 972 | if lx >= 0 && lx < box_size && ly >= 0 && ly < box_size { | ||
| 973 | let u = lx as f32 / (box_size - 1) as f32; | ||
| 974 | let v = ly as f32 / (box_size - 1) as f32; | ||
| 975 | // Rich multi-channel gradient + soft checker inside the box | ||
| 976 | let stripe = if ((lx / 8) + (ly / 8)) % 2 == 0 { 35.0 } else { 0.0 }; | ||
| 977 | r = (60.0 + 160.0 * u + stripe).min(255.0); | ||
| 978 | g = (50.0 + 160.0 * v + stripe * 0.5).min(255.0); | ||
| 979 | b = (210.0 - 140.0 * u + 40.0 * v).clamp(0.0, 255.0); | ||
| 980 | } | ||
| 981 | |||
| 982 | let idx = ((y as u32 * w + x as u32) * 4) as usize; | ||
| 983 | pixels[idx] = r.round() as u8; | ||
| 984 | pixels[idx + 1] = g.round() as u8; | ||
| 985 | pixels[idx + 2] = b.round() as u8; | ||
| 986 | pixels[idx + 3] = 255; | ||
| 987 | } | ||
| 988 | } | ||
| 989 | pixels | ||
| 990 | } | ||
| 991 | |||
| 992 | fn upload_rgba8( | ||
| 993 | device: &wgpu::Device, | ||
| 994 | queue: &wgpu::Queue, | ||
| 995 | w: u32, | ||
| 996 | h: u32, | ||
| 997 | rgba: &[u8], | ||
| 998 | hash: u64, | ||
| 999 | ) -> CachedTexture { | ||
| 1000 | let tex = device.create_texture(&wgpu::TextureDescriptor { | ||
| 1001 | label: Some("test-rgba8"), | ||
| 1002 | size: wgpu::Extent3d { | ||
| 1003 | width: w, | ||
| 1004 | height: h, | ||
| 1005 | depth_or_array_layers: 1, | ||
| 1006 | }, | ||
| 1007 | mip_level_count: 1, | ||
| 1008 | sample_count: 1, | ||
| 1009 | dimension: wgpu::TextureDimension::D2, | ||
| 1010 | format: wgpu::TextureFormat::Rgba8Unorm, | ||
| 1011 | usage: wgpu::TextureUsages::TEXTURE_BINDING | ||
| 1012 | | wgpu::TextureUsages::COPY_DST | ||
| 1013 | | wgpu::TextureUsages::COPY_SRC | ||
| 1014 | | wgpu::TextureUsages::RENDER_ATTACHMENT, | ||
| 1015 | view_formats: &[], | ||
| 1016 | }); | ||
| 1017 | queue.write_texture( | ||
| 1018 | tex.as_image_copy(), | ||
| 1019 | rgba, | ||
| 1020 | wgpu::TexelCopyBufferLayout { | ||
| 1021 | offset: 0, | ||
| 1022 | bytes_per_row: Some(w * 4), | ||
| 1023 | rows_per_image: Some(h), | ||
| 1024 | }, | ||
| 1025 | wgpu::Extent3d { | ||
| 1026 | width: w, | ||
| 1027 | height: h, | ||
| 1028 | depth_or_array_layers: 1, | ||
| 1029 | }, | ||
| 1030 | ); | ||
| 1031 | CachedTexture::from_texture(tex, [w, h], hash) | ||
| 1032 | } | ||
| 1033 | |||
| 1034 | fn readback_bytes( | ||
| 1035 | device: &wgpu::Device, | ||
| 1036 | queue: &wgpu::Queue, | ||
| 1037 | tex: &CachedTexture, | ||
| 1038 | bpp: u32, | ||
| 1039 | ) -> Vec<u8> { | ||
| 1040 | let [w, h] = tex.size; | ||
| 1041 | let unpadded_bpr = w * bpp; | ||
| 1042 | let align = wgpu::COPY_BYTES_PER_ROW_ALIGNMENT; | ||
| 1043 | let padded_bpr = unpadded_bpr.div_ceil(align) * align; | ||
| 1044 | let buf = device.create_buffer(&wgpu::BufferDescriptor { | ||
| 1045 | label: Some("test-readback"), | ||
| 1046 | size: u64::from(padded_bpr) * u64::from(h), | ||
| 1047 | usage: wgpu::BufferUsages::COPY_DST | wgpu::BufferUsages::MAP_READ, | ||
| 1048 | mapped_at_creation: false, | ||
| 1049 | }); | ||
| 1050 | let mut enc = device.create_command_encoder(&wgpu::CommandEncoderDescriptor { | ||
| 1051 | label: Some("test-readback-enc"), | ||
| 1052 | }); | ||
| 1053 | enc.copy_texture_to_buffer( | ||
| 1054 | tex.texture.as_image_copy(), | ||
| 1055 | wgpu::TexelCopyBufferInfo { | ||
| 1056 | buffer: &buf, | ||
| 1057 | layout: wgpu::TexelCopyBufferLayout { | ||
| 1058 | offset: 0, | ||
| 1059 | bytes_per_row: Some(padded_bpr), | ||
| 1060 | rows_per_image: Some(h), | ||
| 1061 | }, | ||
| 1062 | }, | ||
| 1063 | wgpu::Extent3d { | ||
| 1064 | width: w, | ||
| 1065 | height: h, | ||
| 1066 | depth_or_array_layers: 1, | ||
| 1067 | }, | ||
| 1068 | ); | ||
| 1069 | queue.submit(Some(enc.finish())); | ||
| 1070 | |||
| 1071 | let slice = buf.slice(..); | ||
| 1072 | let (tx, rx) = std::sync::mpsc::channel(); | ||
| 1073 | slice.map_async(wgpu::MapMode::Read, move |res| { | ||
| 1074 | let _ = tx.send(res); | ||
| 1075 | }); | ||
| 1076 | device | ||
| 1077 | .poll(wgpu::PollType::Wait { | ||
| 1078 | submission_index: None, | ||
| 1079 | timeout: Some(std::time::Duration::from_secs(10)), | ||
| 1080 | }) | ||
| 1081 | .expect("device poll failed"); | ||
| 1082 | rx.recv().expect("channel closed").expect("map_async failed"); | ||
| 1083 | let data = slice.get_mapped_range().expect("get_mapped_range failed"); | ||
| 1084 | let mut out = Vec::with_capacity((unpadded_bpr * h) as usize); | ||
| 1085 | for row in 0..h as usize { | ||
| 1086 | let start = row * padded_bpr as usize; | ||
| 1087 | out.extend_from_slice(&data[start..start + unpadded_bpr as usize]); | ||
| 1088 | } | ||
| 1089 | drop(data); | ||
| 1090 | buf.unmap(); | ||
| 1091 | out | ||
| 1092 | } | ||
| 1093 | |||
| 1094 | fn f16_to_f32(bits: u16) -> f32 { | ||
| 1095 | let sign = ((bits >> 15) as u32) << 31; | ||
| 1096 | let exp = ((bits >> 10) & 0x1f) as u32; | ||
| 1097 | let frac = (bits & 0x03ff) as u32; | ||
| 1098 | if exp == 0 { | ||
| 1099 | if frac == 0 { | ||
| 1100 | f32::from_bits(sign) | ||
| 1101 | } else { | ||
| 1102 | // Subnormal | ||
| 1103 | let val = (frac as f32) * (2.0f32).powi(-24); | ||
| 1104 | if sign != 0 { -val } else { val } | ||
| 1105 | } | ||
| 1106 | } else if exp == 31 { | ||
| 1107 | f32::from_bits(sign | 0x7f80_0000 | (frac << 13)) | ||
| 1108 | } else { | ||
| 1109 | f32::from_bits(sign | ((exp + 112) << 23) | (frac << 13)) | ||
| 1110 | } | ||
| 1111 | } | ||
| 1112 | |||
| 1113 | fn mae_rgba8(a: &[u8], b: &[u8]) -> f64 { | ||
| 1114 | assert_eq!(a.len(), b.len()); | ||
| 1115 | let sum: u64 = a | ||
| 1116 | .iter() | ||
| 1117 | .zip(b.iter()) | ||
| 1118 | .map(|(&x, &y)| x.abs_diff(y) as u64) | ||
| 1119 | .sum(); | ||
| 1120 | sum as f64 / a.len() as f64 | ||
| 1121 | } | ||
| 1122 | |||
| 1123 | #[test] | ||
| 1124 | fn test_optflow_shifts_moving_box_accurately() { | ||
| 1125 | let (device, queue) = create_headless_device(); | ||
| 1126 | let pipelines = OpticalFlowPipelines::new(&device); | ||
| 1127 | |||
| 1128 | let (w, h) = (256u32, 144u32); | ||
| 1129 | let img_a = render_box_scene(w, h, 80, 56); | ||
| 1130 | let img_b = render_box_scene(w, h, 80 + 16, 56 - 8); | ||
| 1131 | let img_gt = render_box_scene(w, h, 80 + 8, 56 - 4); | ||
| 1132 | |||
| 1133 | let tex_a = upload_rgba8(&device, &queue, w, h, &img_a, 1); | ||
| 1134 | let tex_b = upload_rgba8(&device, &queue, w, h, &img_b, 2); | ||
| 1135 | |||
| 1136 | // 1. Rgba8Unorm blend vs optical flow | ||
| 1137 | let mut enc = device.create_command_encoder(&wgpu::CommandEncoderDescriptor { | ||
| 1138 | label: Some("optflow-test-rgba8"), | ||
| 1139 | }); | ||
| 1140 | let blended = pipelines.blend_frames( | ||
| 1141 | &device, | ||
| 1142 | &queue, | ||
| 1143 | &mut enc, | ||
| 1144 | &tex_a, | ||
| 1145 | &tex_b, | ||
| 1146 | 0.5, | ||
| 1147 | wgpu::TextureFormat::Rgba8Unorm, | ||
| 1148 | ); | ||
| 1149 | let flowed = pipelines.interpolate_flow( | ||
| 1150 | &device, | ||
| 1151 | &queue, | ||
| 1152 | &mut enc, | ||
| 1153 | &tex_a, | ||
| 1154 | &tex_b, | ||
| 1155 | 0.5, | ||
| 1156 | wgpu::TextureFormat::Rgba8Unorm, | ||
| 1157 | ); | ||
| 1158 | queue.submit(Some(enc.finish())); | ||
| 1159 | |||
| 1160 | let blend_bytes = readback_bytes(&device, &queue, &blended, 4); | ||
| 1161 | let flow_bytes = readback_bytes(&device, &queue, &flowed, 4); | ||
| 1162 | |||
| 1163 | let blend_mae = mae_rgba8(&blend_bytes, &img_gt); | ||
| 1164 | let optflow_mae = mae_rgba8(&flow_bytes, &img_gt); | ||
| 1165 | println!("Rgba8Unorm: blend_mae = {blend_mae:.3}, optflow_mae = {optflow_mae:.3}"); | ||
| 1166 | |||
| 1167 | assert!( | ||
| 1168 | optflow_mae < blend_mae * 0.35, | ||
| 1169 | "expected optflow_mae ({optflow_mae:.3}) < 0.35 * blend_mae ({:.3})", | ||
| 1170 | blend_mae * 0.35 | ||
| 1171 | ); | ||
| 1172 | assert!( | ||
| 1173 | optflow_mae < 4.0, | ||
| 1174 | "expected optflow_mae ({optflow_mae:.3}) < 4.0" | ||
| 1175 | ); | ||
| 1176 | |||
| 1177 | // 2. Rgba16Float output format verification | ||
| 1178 | let mut enc_f16 = device.create_command_encoder(&wgpu::CommandEncoderDescriptor { | ||
| 1179 | label: Some("optflow-test-f16"), | ||
| 1180 | }); | ||
| 1181 | let flowed_f16 = pipelines.interpolate_flow( | ||
| 1182 | &device, | ||
| 1183 | &queue, | ||
| 1184 | &mut enc_f16, | ||
| 1185 | &tex_a, | ||
| 1186 | &tex_b, | ||
| 1187 | 0.5, | ||
| 1188 | wgpu::TextureFormat::Rgba16Float, | ||
| 1189 | ); | ||
| 1190 | queue.submit(Some(enc_f16.finish())); | ||
| 1191 | |||
| 1192 | assert_eq!(flowed_f16.format, wgpu::TextureFormat::Rgba16Float); | ||
| 1193 | assert_eq!(flowed_f16.depth, BitDepth::Float16); | ||
| 1194 | |||
| 1195 | let f16_raw = readback_bytes(&device, &queue, &flowed_f16, 8); | ||
| 1196 | let f16_as_u8: Vec<u8> = f16_raw | ||
| 1197 | .chunks_exact(2) | ||
| 1198 | .map(|c| { | ||
| 1199 | let v = f16_to_f32(u16::from_le_bytes([c[0], c[1]])); | ||
| 1200 | (v.clamp(0.0, 1.0) * 255.0).round() as u8 | ||
| 1201 | }) | ||
| 1202 | .collect(); | ||
| 1203 | let f16_mae = mae_rgba8(&f16_as_u8, &img_gt); | ||
| 1204 | println!("Rgba16Float: optflow_mae = {f16_mae:.3}"); | ||
| 1205 | assert!( | ||
| 1206 | f16_mae < blend_mae * 0.35 && f16_mae < 4.0, | ||
| 1207 | "expected Rgba16Float optflow_mae ({f16_mae:.3}) < min(4.0, {:.3})", | ||
| 1208 | blend_mae * 0.35 | ||
| 1209 | ); | ||
| 1210 | } | ||
| 1211 | |||
| 1212 | #[test] | ||
| 1213 | fn test_optflow_mismatched_sizes_and_rgba32float() { | ||
| 1214 | let (device, queue) = create_headless_device(); | ||
| 1215 | let pipelines = OpticalFlowPipelines::new(&device); | ||
| 1216 | |||
| 1217 | let img_a = render_box_scene(128, 72, 40, 20); | ||
| 1218 | let img_b = render_box_scene(96, 54, 30, 15); | ||
| 1219 | let tex_a = upload_rgba8(&device, &queue, 128, 72, &img_a, 10); | ||
| 1220 | let tex_b = upload_rgba8(&device, &queue, 96, 54, &img_b, 11); | ||
| 1221 | |||
| 1222 | let mut enc = device.create_command_encoder(&wgpu::CommandEncoderDescriptor { | ||
| 1223 | label: Some("optflow-test-f32"), | ||
| 1224 | }); | ||
| 1225 | let flowed_f32 = pipelines.interpolate_flow( | ||
| 1226 | &device, | ||
| 1227 | &queue, | ||
| 1228 | &mut enc, | ||
| 1229 | &tex_a, | ||
| 1230 | &tex_b, | ||
| 1231 | 0.5, | ||
| 1232 | wgpu::TextureFormat::Rgba32Float, | ||
| 1233 | ); | ||
| 1234 | let blend_f32 = pipelines.blend_frames( | ||
| 1235 | &device, | ||
| 1236 | &queue, | ||
| 1237 | &mut enc, | ||
| 1238 | &tex_a, | ||
| 1239 | &tex_b, | ||
| 1240 | 0.0, | ||
| 1241 | wgpu::TextureFormat::Rgba32Float, | ||
| 1242 | ); | ||
| 1243 | queue.submit(Some(enc.finish())); | ||
| 1244 | |||
| 1245 | assert_eq!(flowed_f32.size, [128, 72]); | ||
| 1246 | assert_eq!(flowed_f32.format, wgpu::TextureFormat::Rgba32Float); | ||
| 1247 | assert_eq!(flowed_f32.depth, BitDepth::Float32); | ||
| 1248 | |||
| 1249 | // Verify blend at alpha=0.0 reproduces frame_a accurately in Rgba32Float | ||
| 1250 | let raw_f32 = readback_bytes(&device, &queue, &blend_f32, 16); | ||
| 1251 | let f32_as_u8: Vec<u8> = raw_f32 | ||
| 1252 | .chunks_exact(4) | ||
| 1253 | .map(|c| { | ||
| 1254 | let v = f32::from_le_bytes([c[0], c[1], c[2], c[3]]); | ||
| 1255 | (v.clamp(0.0, 1.0) * 255.0).round() as u8 | ||
| 1256 | }) | ||
| 1257 | .collect(); | ||
| 1258 | let err = mae_rgba8(&f32_as_u8, &img_a); | ||
| 1259 | assert!(err < 0.5, "expected alpha=0 blend MAE ({err:.3}) < 0.5"); | ||
| 1260 | } | ||
| 1261 | } | ||
crates/engine/src/particles.rs created+1541| ... | @@ -0,0 +1,1541 @@ | ||
| 1 | //! Fusion deterministic particle simulation & 2D rendering system. | ||
| 2 | //! | ||
| 3 | //! Supports `pEmitter`, `pPointForce`, `pDirectionalForce`, `pTurbulence`, | ||
| 4 | //! `pDrag` / `pFriction`, `pKill`, `pMerge`, and `pRender` (2D mode). | ||
| 5 | |||
| 6 | use std::collections::{HashMap, HashSet}; | ||
| 7 | |||
| 8 | use model::{Comp, ExprEngine, Gradient, Node, NodeId}; | ||
| 9 | |||
| 10 | /// Maximum simultaneous live particles kept in a single simulation to prevent | ||
| 11 | /// pathological comps from hanging or exhausting memory. | ||
| 12 | const MAX_PARTICLES: usize = 20_000; | ||
| 13 | |||
| 14 | /// Maximum lookback frames from `target_frame` when `sim_start` is far earlier. | ||
| 15 | const MAX_SIM_WINDOW: i64 = 600; | ||
| 16 | |||
| 17 | /// Fusion internal acceleration scale for `pPointForce`. | ||
| 18 | /// Matches Fusion Studio's particle-space scaling where `Strength = -2..-4` | ||
| 19 | /// gently disperses particles over ~85-100 frames in `[-0.5, +0.5]` space. | ||
| 20 | const POINT_FORCE_SCALE: f64 = 2.0e-5; | ||
| 21 | |||
| 22 | /// Fusion internal acceleration scale for `pDirectionalForce`. | ||
| 23 | const DIRECTIONAL_FORCE_SCALE: f64 = 2.0e-3; | ||
| 24 | |||
| 25 | /// Fusion internal acceleration scale for `pTurbulence`. | ||
| 26 | const TURBULENCE_SCALE: f64 = 2.0e-3; | ||
| 27 | |||
| 28 | /// Premultiplied RGBA8 bitmap sprite image used by `ParticleStyleBitmap`. | ||
| 29 | #[derive(Clone, Debug)] | ||
| 30 | pub struct SpriteImage { | ||
| 31 | pub size: [u32; 2], | ||
| 32 | pub rgba: Vec<u8>, | ||
| 33 | } | ||
| 34 | |||
| 35 | /// Persistent frame-to-frame cache for deterministic particle simulations. | ||
| 36 | /// | ||
| 37 | /// Keyed by `(render_node, comp.revision)`. Advancing sequentially `f -> f+1` | ||
| 38 | /// only steps 1 frame instead of re-simulating from `sim_start`. | ||
| 39 | #[derive(Default)] | ||
| 40 | pub struct ParticleCache { | ||
| 41 | entries: HashMap<(NodeId, u64), CachedSim>, | ||
| 42 | } | ||
| 43 | |||
| 44 | impl ParticleCache { | ||
| 45 | pub fn clear(&mut self) { | ||
| 46 | self.entries.clear(); | ||
| 47 | } | ||
| 48 | } | ||
| 49 | |||
| 50 | #[derive(Clone)] | ||
| 51 | struct CachedSim { | ||
| 52 | sim_start: i64, | ||
| 53 | current_frame: i64, | ||
| 54 | state: SimState, | ||
| 55 | } | ||
| 56 | |||
| 57 | #[derive(Clone, Default)] | ||
| 58 | struct SimState { | ||
| 59 | particles: Vec<Particle>, | ||
| 60 | /// Fractional emission accumulator per `pEmitter` node. | ||
| 61 | emit_accum: HashMap<NodeId, f64>, | ||
| 62 | } | ||
| 63 | |||
| 64 | #[derive(Clone, Copy, Debug)] | ||
| 65 | struct Particle { | ||
| 66 | emitter_id: NodeId, | ||
| 67 | pos: [f64; 3], | ||
| 68 | vel: [f64; 3], | ||
| 69 | rot_z: f64, | ||
| 70 | spin_z: f64, | ||
| 71 | age: f64, | ||
| 72 | lifespan: f64, | ||
| 73 | size: f64, | ||
| 74 | color: [f32; 4], | ||
| 75 | alive: bool, | ||
| 76 | } | ||
| 77 | |||
| 78 | #[derive(Clone, Copy, Debug, PartialEq, Eq)] | ||
| 79 | enum ParticleStyleKind { | ||
| 80 | Point, | ||
| 81 | Blob, | ||
| 82 | Bitmap, | ||
| 83 | } | ||
| 84 | |||
| 85 | /// Deterministic SplitMix64 PRNG. | ||
| 86 | #[derive(Clone, Copy)] | ||
| 87 | struct SplitMix64(u64); | ||
| 88 | |||
| 89 | impl SplitMix64 { | ||
| 90 | fn from_parts(seed: i64, frame: i64, node_id: usize) -> Self { | ||
| 91 | let mut s = (seed as u64).wrapping_mul(0x9E37_79B9_7F4A_7C15); | ||
| 92 | s ^= (frame as u64).wrapping_mul(0xBF58_476D_1CE4_E5B9); | ||
| 93 | s ^= (node_id as u64).wrapping_mul(0x94D0_49BB_1331_11EB); | ||
| 94 | let mut rng = Self(s ^ 0xD1B5_4A32_D192_ED03); | ||
| 95 | let _ = rng.next_u64(); | ||
| 96 | rng | ||
| 97 | } | ||
| 98 | |||
| 99 | #[inline] | ||
| 100 | fn next_u64(&mut self) -> u64 { | ||
| 101 | self.0 = self.0.wrapping_add(0x9E37_79B9_7F4A_7C15); | ||
| 102 | let mut z = self.0; | ||
| 103 | z = (z ^ (z >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9); | ||
| 104 | z = (z ^ (z >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB); | ||
| 105 | z ^ (z >> 31) | ||
| 106 | } | ||
| 107 | |||
| 108 | /// Uniform float in `[0.0, 1.0)`. | ||
| 109 | #[inline] | ||
| 110 | fn next_f64(&mut self) -> f64 { | ||
| 111 | (self.next_u64() >> 11) as f64 * (1.0 / ((1u64 << 53) as f64)) | ||
| 112 | } | ||
| 113 | |||
| 114 | /// Uniform float in `[-1.0, 1.0)`. | ||
| 115 | #[inline] | ||
| 116 | fn signed(&mut self) -> f64 { | ||
| 117 | self.next_f64() * 2.0 - 1.0 | ||
| 118 | } | ||
| 119 | |||
| 120 | /// Uniform float in `[lo, hi]`. | ||
| 121 | #[inline] | ||
| 122 | fn range(&mut self, lo: f64, hi: f64) -> f64 { | ||
| 123 | let (a, b) = if lo <= hi { (lo, hi) } else { (hi, lo) }; | ||
| 124 | a + (b - a) * self.next_f64() | ||
| 125 | } | ||
| 126 | } | ||
| 127 | |||
| 128 | /// Returns true if `kind` is a Fusion particle stream operator. | ||
| 129 | fn is_particle_node_kind(kind: &str) -> bool { | ||
| 130 | matches!( | ||
| 131 | kind, | ||
| 132 | "pRender" | ||
| 133 | | "pEmitter" | ||
| 134 | | "pPointForce" | ||
| 135 | | "pDirectionalForce" | ||
| 136 | | "pTurbulence" | ||
| 137 | | "pDrag" | ||
| 138 | | "pFriction" | ||
| 139 | | "pKill" | ||
| 140 | | "pMerge" | ||
| 141 | | "pBounce" | ||
| 142 | | "pVortex" | ||
| 143 | | "pFlock" | ||
| 144 | | "pAvoid" | ||
| 145 | | "pSpawn" | ||
| 146 | | "pChangeStyle" | ||
| 147 | | "pCustom" | ||
| 148 | | "pCustomForce" | ||
| 149 | | "pGradientForce" | ||
| 150 | | "pImageEmitter" | ||
| 151 | ) || (kind.starts_with('p') | ||
| 152 | && kind | ||
| 153 | .as_bytes() | ||
| 154 | .get(1) | ||
| 155 | .is_some_and(|b| b.is_ascii_uppercase())) | ||
| 156 | } | ||
| 157 | |||
| 158 | /// Returns the particle stream input node IDs of `node` in deterministic order. | ||
| 159 | fn particle_stream_inputs(comp: &Comp, node: &Node) -> Vec<NodeId> { | ||
| 160 | let mut ports: Vec<&str> = Vec::new(); | ||
| 161 | for key in node.inputs.keys() { | ||
| 162 | if key == "Input" | ||
| 163 | || key | ||
| 164 | .strip_prefix("Input") | ||
| 165 | .is_some_and(|rest| !rest.is_empty() && rest.bytes().all(|b| b.is_ascii_digit())) | ||
| 166 | { | ||
| 167 | ports.push(key.as_str()); | ||
| 168 | } | ||
| 169 | } | ||
| 170 | ports.sort_unstable(); | ||
| 171 | |||
| 172 | let mut out = Vec::with_capacity(ports.len()); | ||
| 173 | for port in ports { | ||
| 174 | if let Some(src_name) = node.connected_node(port) { | ||
| 175 | if let Some(&src_id) = comp.node_by_name.get(src_name) { | ||
| 176 | out.push(src_id); | ||
| 177 | } | ||
| 178 | } | ||
| 179 | } | ||
| 180 | out | ||
| 181 | } | ||
| 182 | |||
| 183 | /// Walks upstream from `render_node` through particle operators and returns every | ||
| 184 | /// `(emitter_node_id, sprite_source_node_id)` pair for `pEmitter` nodes whose | ||
| 185 | /// `ParticleStyleBitmap.DropToolsHere` input is connected. | ||
| 186 | pub fn collect_bitmap_sources(comp: &Comp, render_node: NodeId) -> Vec<(NodeId, NodeId)> { | ||
| 187 | let mut visited = HashSet::new(); | ||
| 188 | let mut out = Vec::new(); | ||
| 189 | collect_bitmap_sources_dfs(comp, render_node, &mut visited, &mut out); | ||
| 190 | out | ||
| 191 | } | ||
| 192 | |||
| 193 | fn collect_bitmap_sources_dfs( | ||
| 194 | comp: &Comp, | ||
| 195 | node_id: NodeId, | ||
| 196 | visited: &mut HashSet<NodeId>, | ||
| 197 | out: &mut Vec<(NodeId, NodeId)>, | ||
| 198 | ) { | ||
| 199 | if !visited.insert(node_id) { | ||
| 200 | return; | ||
| 201 | } | ||
| 202 | let Some(node) = comp.nodes.get(node_id.0) else { | ||
| 203 | return; | ||
| 204 | }; | ||
| 205 | if !is_particle_node_kind(&node.kind) { | ||
| 206 | return; | ||
| 207 | } | ||
| 208 | |||
| 209 | if node.kind == "pEmitter" { | ||
| 210 | if let Some(src_name) = node.connected_node("ParticleStyleBitmap.DropToolsHere") { | ||
| 211 | if let Some(&src_id) = comp.node_by_name.get(src_name) { | ||
| 212 | out.push((node_id, src_id)); | ||
| 213 | } | ||
| 214 | } | ||
| 215 | } | ||
| 216 | |||
| 217 | for up_id in particle_stream_inputs(comp, node) { | ||
| 218 | collect_bitmap_sources_dfs(comp, up_id, visited, out); | ||
| 219 | } | ||
| 220 | } | ||
| 221 | |||
| 222 | /// Flattened, topologically-ordered particle graph upstream of a `pRender` node. | ||
| 223 | struct ParticlePlan { | ||
| 224 | emitters: Vec<NodeId>, | ||
| 225 | /// Forces/modifiers in topological order along with the set of upstream | ||
| 226 | /// emitters whose particles flow through each modifier. | ||
| 227 | modifiers: Vec<(NodeId, HashSet<NodeId>)>, | ||
| 228 | } | ||
| 229 | |||
| 230 | fn build_particle_plan(comp: &Comp, render_node: NodeId) -> ParticlePlan { | ||
| 231 | let mut visited = HashSet::new(); | ||
| 232 | let mut emitters = Vec::new(); | ||
| 233 | let mut modifiers = Vec::new(); | ||
| 234 | let mut upstream_emitters: HashMap<NodeId, HashSet<NodeId>> = HashMap::new(); | ||
| 235 | |||
| 236 | build_plan_dfs( | ||
| 237 | comp, | ||
| 238 | render_node, | ||
| 239 | &mut visited, | ||
| 240 | &mut emitters, | ||
| 241 | &mut modifiers, | ||
| 242 | &mut upstream_emitters, | ||
| 243 | ); | ||
| 244 | |||
| 245 | ParticlePlan { | ||
| 246 | emitters, | ||
| 247 | modifiers, | ||
| 248 | } | ||
| 249 | } | ||
| 250 | |||
| 251 | fn build_plan_dfs( | ||
| 252 | comp: &Comp, | ||
| 253 | node_id: NodeId, | ||
| 254 | visited: &mut HashSet<NodeId>, | ||
| 255 | emitters: &mut Vec<NodeId>, | ||
| 256 | modifiers: &mut Vec<(NodeId, HashSet<NodeId>)>, | ||
| 257 | upstream_emitters: &mut HashMap<NodeId, HashSet<NodeId>>, | ||
| 258 | ) -> HashSet<NodeId> { | ||
| 259 | if let Some(cached) = upstream_emitters.get(&node_id) { | ||
| 260 | return cached.clone(); | ||
| 261 | } | ||
| 262 | if !visited.insert(node_id) { | ||
| 263 | return HashSet::new(); | ||
| 264 | } | ||
| 265 | |||
| 266 | let Some(node) = comp.nodes.get(node_id.0) else { | ||
| 267 | return HashSet::new(); | ||
| 268 | }; | ||
| 269 | if !is_particle_node_kind(&node.kind) { | ||
| 270 | return HashSet::new(); | ||
| 271 | } | ||
| 272 | |||
| 273 | let mut scope = HashSet::new(); | ||
| 274 | for up_id in particle_stream_inputs(comp, node) { | ||
| 275 | let up_set = build_plan_dfs( | ||
| 276 | comp, | ||
| 277 | up_id, | ||
| 278 | visited, | ||
| 279 | emitters, | ||
| 280 | modifiers, | ||
| 281 | upstream_emitters, | ||
| 282 | ); | ||
| 283 | scope.extend(up_set); | ||
| 284 | } | ||
| 285 | |||
| 286 | if node.kind == "pEmitter" { | ||
| 287 | if !node.bypassed { | ||
| 288 | emitters.push(node_id); | ||
| 289 | scope.insert(node_id); | ||
| 290 | } | ||
| 291 | } else if !node.bypassed | ||
| 292 | && matches!( | ||
| 293 | node.kind.as_str(), | ||
| 294 | "pPointForce" | ||
| 295 | | "pDirectionalForce" | ||
| 296 | | "pTurbulence" | ||
| 297 | | "pDrag" | ||
| 298 | | "pFriction" | ||
| 299 | | "pKill" | ||
| 300 | ) | ||
| 301 | { | ||
| 302 | modifiers.push((node_id, scope.clone())); | ||
| 303 | } | ||
| 304 | |||
| 305 | upstream_emitters.insert(node_id, scope.clone()); | ||
| 306 | scope | ||
| 307 | } | ||
| 308 | |||
| 309 | /// Runs deterministic frame-stepped particle simulation up to `time.floor()` and | ||
| 310 | /// rasterizes all live particles into a premultiplied RGBA8 buffer of size | ||
| 311 | /// `dims[0] * dims[1] * 4`. | ||
| 312 | pub fn render_particles_2d( | ||
| 313 | cache: &mut ParticleCache, | ||
| 314 | comp: &Comp, | ||
| 315 | render_node: NodeId, | ||
| 316 | time: f64, | ||
| 317 | dims: [u32; 2], | ||
| 318 | expr: &ExprEngine, | ||
| 319 | sprites: &HashMap<NodeId, SpriteImage>, | ||
| 320 | ) -> Vec<u8> { | ||
| 321 | let pixel_count = (dims[0] as usize).saturating_mul(dims[1] as usize); | ||
| 322 | let mut out = vec![0u8; pixel_count.saturating_mul(4)]; | ||
| 323 | if pixel_count == 0 { | ||
| 324 | return out; | ||
| 325 | } | ||
| 326 | |||
| 327 | let Some(rnode) = comp.nodes.get(render_node.0) else { | ||
| 328 | return out; | ||
| 329 | }; | ||
| 330 | if rnode.bypassed { | ||
| 331 | return out; | ||
| 332 | } | ||
| 333 | |||
| 334 | let plan = build_particle_plan(comp, render_node); | ||
| 335 | if plan.emitters.is_empty() { | ||
| 336 | return out; | ||
| 337 | } | ||
| 338 | |||
| 339 | let target_frame = time.floor() as i64; | ||
| 340 | let base_start = if comp.global_range[0] <= 0 { | ||
| 341 | 0 | ||
| 342 | } else { | ||
| 343 | comp.global_range[0] | ||
| 344 | }; | ||
| 345 | let sim_start = base_start.max(target_frame - MAX_SIM_WINDOW); | ||
| 346 | if target_frame < sim_start { | ||
| 347 | return out; | ||
| 348 | } | ||
| 349 | |||
| 350 | // Evict stale revisions for this render node. | ||
| 351 | let key = (render_node, comp.revision); | ||
| 352 | cache | ||
| 353 | .entries | ||
| 354 | .retain(|&(nid, rev), _| nid != render_node || rev == comp.revision); | ||
| 355 | |||
| 356 | let need_reset = match cache.entries.get(&key) { | ||
| 357 | Some(cached) => { | ||
| 358 | target_frame < cached.current_frame | ||
| 359 | || target_frame == sim_start | ||
| 360 | || cached.sim_start != sim_start | ||
| 361 | } | ||
| 362 | None => true, | ||
| 363 | }; | ||
| 364 | |||
| 365 | if need_reset { | ||
| 366 | let mut state = SimState::default(); | ||
| 367 | for f in sim_start..=target_frame { | ||
| 368 | step_simulation(&mut state, comp, &plan, f, expr); | ||
| 369 | } | ||
| 370 | cache.entries.insert( | ||
| 371 | key, | ||
| 372 | CachedSim { | ||
| 373 | sim_start, | ||
| 374 | current_frame: target_frame, | ||
| 375 | state, | ||
| 376 | }, | ||
| 377 | ); | ||
| 378 | } else if let Some(cached) = cache.entries.get_mut(&key) { | ||
| 379 | if target_frame > cached.current_frame { | ||
| 380 | for f in (cached.current_frame + 1)..=target_frame { | ||
| 381 | step_simulation(&mut cached.state, comp, &plan, f, expr); | ||
| 382 | } | ||
| 383 | cached.current_frame = target_frame; | ||
| 384 | } | ||
| 385 | } | ||
| 386 | |||
| 387 | let Some(cached) = cache.entries.get(&key) else { | ||
| 388 | return out; | ||
| 389 | }; | ||
| 390 | |||
| 391 | rasterize_particles( | ||
| 392 | &mut out, | ||
| 393 | dims, | ||
| 394 | comp, | ||
| 395 | &cached.state.particles, | ||
| 396 | time, | ||
| 397 | expr, | ||
| 398 | sprites, | ||
| 399 | ); | ||
| 400 | out | ||
| 401 | } | ||
| 402 | |||
| 403 | /// Advances the particle simulation by a single integer frame `frame`. | ||
| 404 | fn step_simulation( | ||
| 405 | state: &mut SimState, | ||
| 406 | comp: &Comp, | ||
| 407 | plan: &ParticlePlan, | ||
| 408 | frame: i64, | ||
| 409 | expr: &ExprEngine, | ||
| 410 | ) { | ||
| 411 | let t = frame as f64; | ||
| 412 | |||
| 413 | // 1. Apply forces & kills to existing live particles, then integrate motion and age. | ||
| 414 | if !state.particles.is_empty() { | ||
| 415 | for (mod_id, scope) in &plan.modifiers { | ||
| 416 | let Some(node) = comp.nodes.get(mod_id.0) else { | ||
| 417 | continue; | ||
| 418 | }; | ||
| 419 | apply_modifier(&mut state.particles, comp, node, scope, t, expr); | ||
| 420 | } | ||
| 421 | |||
| 422 | for p in &mut state.particles { | ||
| 423 | if !p.alive { | ||
| 424 | continue; | ||
| 425 | } | ||
| 426 | p.pos[0] += p.vel[0]; | ||
| 427 | p.pos[1] += p.vel[1]; | ||
| 428 | p.pos[2] += p.vel[2]; | ||
| 429 | p.rot_z += p.spin_z; | ||
| 430 | p.age += 1.0; | ||
| 431 | if p.age >= p.lifespan { | ||
| 432 | p.alive = false; | ||
| 433 | } | ||
| 434 | } | ||
| 435 | state.particles.retain(|p| p.alive); | ||
| 436 | } | ||
| 437 | |||
| 438 | // 2. Emit new particles for `frame` (born with `age = 0.0` at their spawn region). | ||
| 439 | for &emitter_id in &plan.emitters { | ||
| 440 | if state.particles.len() >= MAX_PARTICLES { | ||
| 441 | break; | ||
| 442 | } | ||
| 443 | let Some(node) = comp.nodes.get(emitter_id.0) else { | ||
| 444 | continue; | ||
| 445 | }; | ||
| 446 | emit_particles(state, comp, node, emitter_id, frame, t, expr); | ||
| 447 | } | ||
| 448 | } | ||
| 449 | |||
| 450 | fn emit_particles( | ||
| 451 | state: &mut SimState, | ||
| 452 | comp: &Comp, | ||
| 453 | node: &Node, | ||
| 454 | emitter_id: NodeId, | ||
| 455 | frame: i64, | ||
| 456 | t: f64, | ||
| 457 | expr: &ExprEngine, | ||
| 458 | ) { | ||
| 459 | let seed = comp.eval_number(node, "RandomSeed", t, 0.0, expr).round() as i64; | ||
| 460 | let mut rng = SplitMix64::from_parts(seed, frame, emitter_id.0); | ||
| 461 | |||
| 462 | let number = comp.eval_number(node, "Number", t, 10.0, expr).max(0.0); | ||
| 463 | let number_var = comp | ||
| 464 | .eval_number(node, "NumberVariance", t, 0.0, expr) | ||
| 465 | .max(0.0); | ||
| 466 | |||
| 467 | let rate = (number + rng.signed() * number_var).max(0.0); | ||
| 468 | let accum = state.emit_accum.entry(emitter_id).or_insert(0.0); | ||
| 469 | *accum += rate; | ||
| 470 | let mut emit_count = accum.floor() as usize; | ||
| 471 | *accum -= emit_count as f64; | ||
| 472 | |||
| 473 | if emit_count == 0 { | ||
| 474 | return; | ||
| 475 | } | ||
| 476 | let remaining_cap = MAX_PARTICLES.saturating_sub(state.particles.len()); | ||
| 477 | if emit_count > remaining_cap { | ||
| 478 | emit_count = remaining_cap; | ||
| 479 | } | ||
| 480 | |||
| 481 | let lifespan_base = comp.eval_number(node, "Lifespan", t, 100.0, expr).max(1.0); | ||
| 482 | let lifespan_var = comp | ||
| 483 | .eval_number(node, "LifespanVariance", t, 0.0, expr) | ||
| 484 | .max(0.0); | ||
| 485 | let pos_var = comp | ||
| 486 | .eval_number(node, "PositionVariance", t, 0.0, expr) | ||
| 487 | .max(0.0); | ||
| 488 | |||
| 489 | let vel_base = comp.eval_number(node, "Velocity", t, 0.0, expr); | ||
| 490 | let vel_var = comp | ||
| 491 | .eval_number(node, "VelocityVariance", t, 0.0, expr) | ||
| 492 | .max(0.0); | ||
| 493 | let angle_base = comp.eval_number(node, "Angle", t, 0.0, expr); | ||
| 494 | let angle_var = comp | ||
| 495 | .eval_number(node, "AngleVariance", t, 0.0, expr) | ||
| 496 | .max(0.0); | ||
| 497 | let angle_z_base = comp.eval_number(node, "AngleZ", t, 0.0, expr); | ||
| 498 | let angle_z_var = comp | ||
| 499 | .eval_number(node, "AngleZVariance", t, 0.0, expr) | ||
| 500 | .max(0.0); | ||
| 501 | |||
| 502 | let rot_z_base = comp.eval_number(node, "RotationZ", t, 0.0, expr); | ||
| 503 | let rot_z_var = comp | ||
| 504 | .eval_number(node, "RotationZVariance", t, 0.0, expr) | ||
| 505 | .max(0.0); | ||
| 506 | let spin_z_base = comp.eval_number(node, "SpinZ", t, 0.0, expr); | ||
| 507 | let spin_z_var = comp | ||
| 508 | .eval_number(node, "SpinZVariance", t, 0.0, expr) | ||
| 509 | .max(0.0); | ||
| 510 | |||
| 511 | let base_r = comp.eval_number(node, "ParticleStyle.Red", t, 1.0, expr); | ||
| 512 | let base_g = comp.eval_number(node, "ParticleStyle.Green", t, 1.0, expr); | ||
| 513 | let base_b = comp.eval_number(node, "ParticleStyle.Blue", t, 1.0, expr); | ||
| 514 | let base_a = comp.eval_number(node, "ParticleStyle.Alpha", t, 1.0, expr); | ||
| 515 | |||
| 516 | let color_var = comp.eval_number(node, "ParticleStyle.ColorVariance", t, 0.0, expr) > 0.5; | ||
| 517 | let r_lo = (base_r + comp.eval_number(node, "ParticleStyle.RedLow", t, 0.0, expr)).clamp(0.0, 1.0); | ||
| 518 | let r_hi = (base_r + comp.eval_number(node, "ParticleStyle.RedHigh", t, 0.0, expr)).clamp(0.0, 1.0); | ||
| 519 | let g_lo = (base_g + comp.eval_number(node, "ParticleStyle.GreenLow", t, 0.0, expr)).clamp(0.0, 1.0); | ||
| 520 | let g_hi = (base_g + comp.eval_number(node, "ParticleStyle.GreenHigh", t, 0.0, expr)).clamp(0.0, 1.0); | ||
| 521 | let b_lo = (base_b + comp.eval_number(node, "ParticleStyle.BlueLow", t, 0.0, expr)).clamp(0.0, 1.0); | ||
| 522 | let b_hi = (base_b + comp.eval_number(node, "ParticleStyle.BlueHigh", t, 0.0, expr)).clamp(0.0, 1.0); | ||
| 523 | let a_lo = (base_a + comp.eval_number(node, "ParticleStyle.AlphaLow", t, 0.0, expr)).clamp(0.0, 1.0); | ||
| 524 | let a_hi = (base_a + comp.eval_number(node, "ParticleStyle.AlphaHigh", t, 0.0, expr)).clamp(0.0, 1.0); | ||
| 525 | |||
| 526 | let size_base = comp | ||
| 527 | .eval_number(node, "ParticleStyle.Size", t, 0.1, expr) | ||
| 528 | .max(0.0); | ||
| 529 | let size_var = comp | ||
| 530 | .eval_number(node, "ParticleStyle.SizeVariance", t, 0.0, expr) | ||
| 531 | .max(0.0); | ||
| 532 | |||
| 533 | let region = RegionSpec::from_node(comp, node, t, expr); | ||
| 534 | |||
| 535 | for _ in 0..emit_count { | ||
| 536 | let mut pos = region.sample(&mut rng); | ||
| 537 | if pos_var > 0.0 { | ||
| 538 | pos[0] += rng.signed() * pos_var; | ||
| 539 | pos[1] += rng.signed() * pos_var; | ||
| 540 | pos[2] += rng.signed() * pos_var; | ||
| 541 | } | ||
| 542 | |||
| 543 | let speed = vel_base + rng.signed() * vel_var; | ||
| 544 | let ang = (angle_base + rng.signed() * angle_var).to_radians(); | ||
| 545 | let ang_z = (angle_z_base + rng.signed() * angle_z_var).to_radians(); | ||
| 546 | let cos_z = ang_z.cos(); | ||
| 547 | let vel = [ | ||
| 548 | speed * ang.cos() * cos_z, | ||
| 549 | speed * ang.sin() * cos_z, | ||
| 550 | speed * ang_z.sin(), | ||
| 551 | ]; | ||
| 552 | |||
| 553 | let rot_z = rot_z_base + rng.signed() * rot_z_var; | ||
| 554 | let spin_z = spin_z_base + rng.signed() * spin_z_var; | ||
| 555 | let lifespan = (lifespan_base + rng.signed() * lifespan_var).max(1.0); | ||
| 556 | let size = (size_base + rng.signed() * size_var).max(0.0); | ||
| 557 | |||
| 558 | let color = if color_var { | ||
| 559 | [ | ||
| 560 | rng.range(r_lo, r_hi) as f32, | ||
| 561 | rng.range(g_lo, g_hi) as f32, | ||
| 562 | rng.range(b_lo, b_hi) as f32, | ||
| 563 | rng.range(a_lo, a_hi) as f32, | ||
| 564 | ] | ||
| 565 | } else { | ||
| 566 | [ | ||
| 567 | base_r.clamp(0.0, 1.0) as f32, | ||
| 568 | base_g.clamp(0.0, 1.0) as f32, | ||
| 569 | base_b.clamp(0.0, 1.0) as f32, | ||
| 570 | base_a.clamp(0.0, 1.0) as f32, | ||
| 571 | ] | ||
| 572 | }; | ||
| 573 | |||
| 574 | state.particles.push(Particle { | ||
| 575 | emitter_id, | ||
| 576 | pos, | ||
| 577 | vel, | ||
| 578 | rot_z, | ||
| 579 | spin_z, | ||
| 580 | age: 0.0, | ||
| 581 | lifespan, | ||
| 582 | size, | ||
| 583 | color, | ||
| 584 | alive: true, | ||
| 585 | }); | ||
| 586 | } | ||
| 587 | } | ||
| 588 | |||
| 589 | #[derive(Clone, Copy)] | ||
| 590 | enum RegionSpec { | ||
| 591 | Point { | ||
| 592 | center: [f64; 3], | ||
| 593 | }, | ||
| 594 | Rect { | ||
| 595 | center: [f64; 3], | ||
| 596 | width: f64, | ||
| 597 | height: f64, | ||
| 598 | }, | ||
| 599 | Sphere { | ||
| 600 | center: [f64; 3], | ||
| 601 | radius: f64, | ||
| 602 | }, | ||
| 603 | Cube { | ||
| 604 | center: [f64; 3], | ||
| 605 | width: f64, | ||
| 606 | height: f64, | ||
| 607 | depth: f64, | ||
| 608 | }, | ||
| 609 | Line { | ||
| 610 | start: [f64; 3], | ||
| 611 | end: [f64; 3], | ||
| 612 | }, | ||
| 613 | All, | ||
| 614 | } | ||
| 615 | |||
| 616 | impl RegionSpec { | ||
| 617 | fn from_node(comp: &Comp, node: &Node, t: f64, expr: &ExprEngine) -> Self { | ||
| 618 | let region_name = node.static_str("Region").unwrap_or("Point"); | ||
| 619 | match region_name { | ||
| 620 | "RectRgn" => Self::Rect { | ||
| 621 | center: [ | ||
| 622 | comp.eval_number(node, "RectRgn.Translate.X", t, 0.0, expr), | ||
| 623 | comp.eval_number(node, "RectRgn.Translate.Y", t, 0.0, expr), | ||
| 624 | comp.eval_number(node, "RectRgn.Translate.Z", t, 0.0, expr), | ||
| 625 | ], | ||
| 626 | width: comp.eval_number(node, "RectRgn.Width", t, 0.5, expr).abs(), | ||
| 627 | height: comp.eval_number(node, "RectRgn.Height", t, 0.5, expr).abs(), | ||
| 628 | }, | ||
| 629 | "SphereRgn" => Self::Sphere { | ||
| 630 | center: [ | ||
| 631 | comp.eval_number(node, "SphereRgn.Translate.X", t, 0.0, expr), | ||
| 632 | comp.eval_number(node, "SphereRgn.Translate.Y", t, 0.0, expr), | ||
| 633 | comp.eval_number(node, "SphereRgn.Translate.Z", t, 0.0, expr), | ||
| 634 | ], | ||
| 635 | radius: comp.eval_number(node, "SphereRgn.Size", t, 0.5, expr).abs() * 0.5, | ||
| 636 | }, | ||
| 637 | "CubeRgn" => Self::Cube { | ||
| 638 | center: [ | ||
| 639 | comp.eval_number(node, "CubeRgn.Translate.X", t, 0.0, expr), | ||
| 640 | comp.eval_number(node, "CubeRgn.Translate.Y", t, 0.0, expr), | ||
| 641 | comp.eval_number(node, "CubeRgn.Translate.Z", t, 0.0, expr), | ||
| 642 | ], | ||
| 643 | width: comp.eval_number(node, "CubeRgn.Width", t, 0.5, expr).abs(), | ||
| 644 | height: comp.eval_number(node, "CubeRgn.Height", t, 0.5, expr).abs(), | ||
| 645 | depth: comp.eval_number(node, "CubeRgn.Depth", t, 0.5, expr).abs(), | ||
| 646 | }, | ||
| 647 | "LineRgn" => { | ||
| 648 | let tx = comp.eval_number(node, "LineRgn.Translate.X", t, 0.0, expr); | ||
| 649 | let ty = comp.eval_number(node, "LineRgn.Translate.Y", t, 0.0, expr); | ||
| 650 | let tz = comp.eval_number(node, "LineRgn.Translate.Z", t, 0.0, expr); | ||
| 651 | Self::Line { | ||
| 652 | start: [ | ||
| 653 | tx + comp.eval_number(node, "LineRgn.Start.X", t, -0.5, expr), | ||
| 654 | ty + comp.eval_number(node, "LineRgn.Start.Y", t, 0.0, expr), | ||
| 655 | tz + comp.eval_number(node, "LineRgn.Start.Z", t, 0.0, expr), | ||
| 656 | ], | ||
| 657 | end: [ | ||
| 658 | tx + comp.eval_number(node, "LineRgn.End.X", t, 0.5, expr), | ||
| 659 | ty + comp.eval_number(node, "LineRgn.End.Y", t, 0.0, expr), | ||
| 660 | tz + comp.eval_number(node, "LineRgn.End.Z", t, 0.0, expr), | ||
| 661 | ], | ||
| 662 | } | ||
| 663 | } | ||
| 664 | "AllRgn" | "All" => Self::All, | ||
| 665 | _ => Self::Point { | ||
| 666 | center: [ | ||
| 667 | comp.eval_number(node, "Point.Translate.X", t, 0.0, expr), | ||
| 668 | comp.eval_number(node, "Point.Translate.Y", t, 0.0, expr), | ||
| 669 | comp.eval_number(node, "Point.Translate.Z", t, 0.0, expr), | ||
| 670 | ], | ||
| 671 | }, | ||
| 672 | } | ||
| 673 | } | ||
| 674 | |||
| 675 | fn sample(&self, rng: &mut SplitMix64) -> [f64; 3] { | ||
| 676 | match *self { | ||
| 677 | Self::Point { center } => center, | ||
| 678 | Self::Rect { | ||
| 679 | center, | ||
| 680 | width, | ||
| 681 | height, | ||
| 682 | } => [ | ||
| 683 | center[0] + (rng.next_f64() - 0.5) * width, | ||
| 684 | center[1] + (rng.next_f64() - 0.5) * height, | ||
| 685 | center[2], | ||
| 686 | ], | ||
| 687 | Self::Sphere { center, radius } => { | ||
| 688 | let u = rng.next_f64(); | ||
| 689 | let v = rng.next_f64(); | ||
| 690 | let w = rng.next_f64(); | ||
| 691 | let theta = u * std::f64::consts::TAU; | ||
| 692 | let cos_phi = 2.0 * v - 1.0; | ||
| 693 | let sin_phi = (1.0 - cos_phi * cos_phi).max(0.0).sqrt(); | ||
| 694 | let r = radius * w.cbrt(); | ||
| 695 | [ | ||
| 696 | center[0] + r * sin_phi * theta.cos(), | ||
| 697 | center[1] + r * sin_phi * theta.sin(), | ||
| 698 | center[2] + r * cos_phi, | ||
| 699 | ] | ||
| 700 | } | ||
| 701 | Self::Cube { | ||
| 702 | center, | ||
| 703 | width, | ||
| 704 | height, | ||
| 705 | depth, | ||
| 706 | } => [ | ||
| 707 | center[0] + (rng.next_f64() - 0.5) * width, | ||
| 708 | center[1] + (rng.next_f64() - 0.5) * height, | ||
| 709 | center[2] + (rng.next_f64() - 0.5) * depth, | ||
| 710 | ], | ||
| 711 | Self::Line { start, end } => { | ||
| 712 | let u = rng.next_f64(); | ||
| 713 | [ | ||
| 714 | start[0] + (end[0] - start[0]) * u, | ||
| 715 | start[1] + (end[1] - start[1]) * u, | ||
| 716 | start[2] + (end[2] - start[2]) * u, | ||
| 717 | ] | ||
| 718 | } | ||
| 719 | Self::All => [0.0, 0.0, 0.0], | ||
| 720 | } | ||
| 721 | } | ||
| 722 | |||
| 723 | fn contains(&self, p: [f64; 3]) -> bool { | ||
| 724 | match *self { | ||
| 725 | Self::All => true, | ||
| 726 | Self::Point { center } => { | ||
| 727 | let dx = p[0] - center[0]; | ||
| 728 | let dy = p[1] - center[1]; | ||
| 729 | let dz = p[2] - center[2]; | ||
| 730 | dx * dx + dy * dy + dz * dz <= 1e-4 | ||
| 731 | } | ||
| 732 | Self::Rect { | ||
| 733 | center, | ||
| 734 | width, | ||
| 735 | height, | ||
| 736 | } => { | ||
| 737 | (p[0] - center[0]).abs() <= width * 0.5 | ||
| 738 | && (p[1] - center[1]).abs() <= height * 0.5 | ||
| 739 | } | ||
| 740 | Self::Sphere { center, radius } => { | ||
| 741 | let dx = p[0] - center[0]; | ||
| 742 | let dy = p[1] - center[1]; | ||
| 743 | let dz = p[2] - center[2]; | ||
| 744 | dx * dx + dy * dy + dz * dz <= radius * radius | ||
| 745 | } | ||
| 746 | Self::Cube { | ||
| 747 | center, | ||
| 748 | width, | ||
| 749 | height, | ||
| 750 | depth, | ||
| 751 | } => { | ||
| 752 | (p[0] - center[0]).abs() <= width * 0.5 | ||
| 753 | && (p[1] - center[1]).abs() <= height * 0.5 | ||
| 754 | && (p[2] - center[2]).abs() <= depth * 0.5 | ||
| 755 | } | ||
| 756 | Self::Line { start, end } => { | ||
| 757 | let vx = end[0] - start[0]; | ||
| 758 | let vy = end[1] - start[1]; | ||
| 759 | let vz = end[2] - start[2]; | ||
| 760 | let len_sq = vx * vx + vy * vy + vz * vz; | ||
| 761 | let u = if len_sq > 1e-9 { | ||
| 762 | (((p[0] - start[0]) * vx + (p[1] - start[1]) * vy + (p[2] - start[2]) * vz) | ||
| 763 | / len_sq) | ||
| 764 | .clamp(0.0, 1.0) | ||
| 765 | } else { | ||
| 766 | 0.0 | ||
| 767 | }; | ||
| 768 | let cx = start[0] + vx * u; | ||
| 769 | let cy = start[1] + vy * u; | ||
| 770 | let cz = start[2] + vz * u; | ||
| 771 | let dx = p[0] - cx; | ||
| 772 | let dy = p[1] - cy; | ||
| 773 | let dz = p[2] - cz; | ||
| 774 | dx * dx + dy * dy + dz * dz <= 1e-3 | ||
| 775 | } | ||
| 776 | } | ||
| 777 | } | ||
| 778 | } | ||
| 779 | |||
| 780 | fn apply_modifier( | ||
| 781 | particles: &mut [Particle], | ||
| 782 | comp: &Comp, | ||
| 783 | node: &Node, | ||
| 784 | scope: &HashSet<NodeId>, | ||
| 785 | t: f64, | ||
| 786 | expr: &ExprEngine, | ||
| 787 | ) { | ||
| 788 | match node.kind.as_str() { | ||
| 789 | "pPointForce" => { | ||
| 790 | let strength = comp.eval_number(node, "Strength", t, 0.0, expr); | ||
| 791 | if strength.abs() < 1e-12 { | ||
| 792 | return; | ||
| 793 | } | ||
| 794 | let power = comp.eval_number(node, "Power", t, 2.0, expr); | ||
| 795 | let tx = comp.eval_number(node, "Translate.X", t, 0.0, expr); | ||
| 796 | let ty = comp.eval_number(node, "Translate.Y", t, 0.0, expr); | ||
| 797 | let tz = comp.eval_number(node, "Translate.Z", t, 0.0, expr); | ||
| 798 | |||
| 799 | for p in particles.iter_mut() { | ||
| 800 | if !p.alive || !scope.contains(&p.emitter_id) { | ||
| 801 | continue; | ||
| 802 | } | ||
| 803 | let dx = tx - p.pos[0]; | ||
| 804 | let dy = ty - p.pos[1]; | ||
| 805 | let dz = tz - p.pos[2]; | ||
| 806 | let dist = (dx * dx + dy * dy + dz * dz).sqrt(); | ||
| 807 | if dist < 1e-7 { | ||
| 808 | continue; | ||
| 809 | } | ||
| 810 | let falloff = dist.max(0.05).powf(power); | ||
| 811 | let mag = (strength * POINT_FORCE_SCALE / falloff).clamp(-0.25, 0.25); | ||
| 812 | let inv_d = 1.0 / dist; | ||
| 813 | p.vel[0] += dx * inv_d * mag; | ||
| 814 | p.vel[1] += dy * inv_d * mag; | ||
| 815 | p.vel[2] += dz * inv_d * mag; | ||
| 816 | } | ||
| 817 | } | ||
| 818 | "pDirectionalForce" => { | ||
| 819 | let strength = comp.eval_number(node, "Strength", t, 0.1, expr); | ||
| 820 | if strength.abs() < 1e-12 { | ||
| 821 | return; | ||
| 822 | } | ||
| 823 | let dir = comp | ||
| 824 | .eval_number(node, "Direction", t, -90.0, expr) | ||
| 825 | .to_radians(); | ||
| 826 | let dir_z = comp | ||
| 827 | .eval_number(node, "DirectionZ", t, 0.0, expr) | ||
| 828 | .to_radians(); | ||
| 829 | let mag = strength * DIRECTIONAL_FORCE_SCALE; | ||
| 830 | let ax = mag * dir.cos() * dir_z.cos(); | ||
| 831 | let ay = mag * dir.sin() * dir_z.cos(); | ||
| 832 | let az = mag * dir_z.sin(); | ||
| 833 | |||
| 834 | for p in particles.iter_mut() { | ||
| 835 | if !p.alive || !scope.contains(&p.emitter_id) { | ||
| 836 | continue; | ||
| 837 | } | ||
| 838 | p.vel[0] += ax; | ||
| 839 | p.vel[1] += ay; | ||
| 840 | p.vel[2] += az; | ||
| 841 | } | ||
| 842 | } | ||
| 843 | "pDrag" | "pFriction" => { | ||
| 844 | let drag = if node.kind == "pFriction" { | ||
| 845 | comp.eval_number(node, "VelocityFriction", t, 0.1, expr) | ||
| 846 | } else { | ||
| 847 | comp.eval_number(node, "Drag", t, 0.1, expr) | ||
| 848 | } | ||
| 849 | .max(0.0); | ||
| 850 | let damp = (-drag).exp(); | ||
| 851 | for p in particles.iter_mut() { | ||
| 852 | if !p.alive || !scope.contains(&p.emitter_id) { | ||
| 853 | continue; | ||
| 854 | } | ||
| 855 | p.vel[0] *= damp; | ||
| 856 | p.vel[1] *= damp; | ||
| 857 | p.vel[2] *= damp; | ||
| 858 | } | ||
| 859 | } | ||
| 860 | "pTurbulence" => { | ||
| 861 | let sx = comp.eval_number(node, "XStrength", t, 0.1, expr); | ||
| 862 | let sy = comp.eval_number(node, "YStrength", t, 0.1, expr); | ||
| 863 | let sz = comp.eval_number(node, "ZStrength", t, 0.0, expr); | ||
| 864 | if sx.abs() < 1e-12 && sy.abs() < 1e-12 && sz.abs() < 1e-12 { | ||
| 865 | return; | ||
| 866 | } | ||
| 867 | let density = comp.eval_number(node, "Density", t, 1.0, expr).max(0.01); | ||
| 868 | let seed = comp.eval_number(node, "RandomSeed", t, 0.0, expr).round() as u64; | ||
| 869 | let time_shift = t * 0.03; | ||
| 870 | |||
| 871 | for p in particles.iter_mut() { | ||
| 872 | if !p.alive || !scope.contains(&p.emitter_id) { | ||
| 873 | continue; | ||
| 874 | } | ||
| 875 | let qx = p.pos[0] * density + time_shift; | ||
| 876 | let qy = p.pos[1] * density - time_shift * 0.7; | ||
| 877 | let qz = p.pos[2] * density; | ||
| 878 | let nx = value_noise_3d(qx, qy, qz, seed); | ||
| 879 | let ny = value_noise_3d(qx + 31.7, qy + 17.3, qz + 47.1, seed ^ 0x517C_C1B7_2722_0A95); | ||
| 880 | let nz = value_noise_3d(qx - 19.4, qy + 53.9, qz - 11.2, seed ^ 0x9E37_79B9_7F4A_7C15); | ||
| 881 | p.vel[0] += nx * sx * TURBULENCE_SCALE; | ||
| 882 | p.vel[1] += ny * sy * TURBULENCE_SCALE; | ||
| 883 | p.vel[2] += nz * sz * TURBULENCE_SCALE; | ||
| 884 | } | ||
| 885 | } | ||
| 886 | "pKill" => { | ||
| 887 | let region = if node.static_str("Region").is_some() { | ||
| 888 | RegionSpec::from_node(comp, node, t, expr) | ||
| 889 | } else { | ||
| 890 | RegionSpec::All | ||
| 891 | }; | ||
| 892 | let kill_outside = matches!( | ||
| 893 | node.static_str("RegionMode"), | ||
| 894 | Some("Outside") | Some("Leaving") | ||
| 895 | ); | ||
| 896 | for p in particles.iter_mut() { | ||
| 897 | if !p.alive || !scope.contains(&p.emitter_id) { | ||
| 898 | continue; | ||
| 899 | } | ||
| 900 | let inside = region.contains(p.pos); | ||
| 901 | if (!kill_outside && inside) || (kill_outside && !inside) { | ||
| 902 | p.alive = false; | ||
| 903 | } | ||
| 904 | } | ||
| 905 | } | ||
| 906 | _ => {} | ||
| 907 | } | ||
| 908 | } | ||
| 909 | |||
| 910 | /// Smooth deterministic 3D value noise in `[-1.0, 1.0]`. | ||
| 911 | fn value_noise_3d(x: f64, y: f64, z: f64, seed: u64) -> f64 { | ||
| 912 | let xi = x.floor() as i64; | ||
| 913 | let yi = y.floor() as i64; | ||
| 914 | let zi = z.floor() as i64; | ||
| 915 | let xf = x - xi as f64; | ||
| 916 | let yf = y - yi as f64; | ||
| 917 | let zf = z - zi as f64; | ||
| 918 | |||
| 919 | let u = xf * xf * (3.0 - 2.0 * xf); | ||
| 920 | let v = yf * yf * (3.0 - 2.0 * yf); | ||
| 921 | let w = zf * zf * (3.0 - 2.0 * zf); | ||
| 922 | |||
| 923 | let n000 = lattice_hash(xi, yi, zi, seed); | ||
| 924 | let n100 = lattice_hash(xi + 1, yi, zi, seed); | ||
| 925 | let n010 = lattice_hash(xi, yi + 1, zi, seed); | ||
| 926 | let n110 = lattice_hash(xi + 1, yi + 1, zi, seed); | ||
| 927 | let n001 = lattice_hash(xi, yi, zi + 1, seed); | ||
| 928 | let n101 = lattice_hash(xi + 1, yi, zi + 1, seed); | ||
| 929 | let n011 = lattice_hash(xi, yi + 1, zi + 1, seed); | ||
| 930 | let n111 = lattice_hash(xi + 1, yi + 1, zi + 1, seed); | ||
| 931 | |||
| 932 | let nx00 = n000 + (n100 - n000) * u; | ||
| 933 | let nx10 = n010 + (n110 - n010) * u; | ||
| 934 | let nx01 = n001 + (n101 - n001) * u; | ||
| 935 | let nx11 = n011 + (n111 - n011) * u; | ||
| 936 | |||
| 937 | let nxy0 = nx00 + (nx10 - nx00) * v; | ||
| 938 | let nxy1 = nx01 + (nx11 - nx01) * v; | ||
| 939 | |||
| 940 | nxy0 + (nxy1 - nxy0) * w | ||
| 941 | } | ||
| 942 | |||
| 943 | #[inline] | ||
| 944 | fn lattice_hash(x: i64, y: i64, z: i64, seed: u64) -> f64 { | ||
| 945 | let mut h = seed | ||
| 946 | ^ (x as u64).wrapping_mul(0x9E37_79B9_7F4A_7C15) | ||
| 947 | ^ (y as u64).wrapping_mul(0xBF58_476D_1CE4_E5B9) | ||
| 948 | ^ (z as u64).wrapping_mul(0x94D0_49BB_1331_11EB); | ||
| 949 | h = (h ^ (h >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9); | ||
| 950 | h = (h ^ (h >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB); | ||
| 951 | h ^= h >> 31; | ||
| 952 | let unit = (h >> 11) as f64 * (1.0 / ((1u64 << 53) as f64)); | ||
| 953 | unit * 2.0 - 1.0 | ||
| 954 | } | ||
| 955 | |||
| 956 | struct EmitterRenderProps<'a> { | ||
| 957 | style: ParticleStyleKind, | ||
| 958 | size_over_life: Option<&'a model::BezierSpline>, | ||
| 959 | fade_in: f64, | ||
| 960 | fade_out: f64, | ||
| 961 | color_over_life: Option<Gradient>, | ||
| 962 | } | ||
| 963 | |||
| 964 | fn collect_emitter_render_props<'a>( | ||
| 965 | comp: &'a Comp, | ||
| 966 | particles: &[Particle], | ||
| 967 | time: f64, | ||
| 968 | expr: &ExprEngine, | ||
| 969 | ) -> HashMap<NodeId, EmitterRenderProps<'a>> { | ||
| 970 | let mut map = HashMap::new(); | ||
| 971 | for p in particles { | ||
| 972 | if map.contains_key(&p.emitter_id) { | ||
| 973 | continue; | ||
| 974 | } | ||
| 975 | let Some(node) = comp.nodes.get(p.emitter_id.0) else { | ||
| 976 | continue; | ||
| 977 | }; | ||
| 978 | let style = match node.static_str("Style") { | ||
| 979 | Some("ParticleStyleBitmap") => ParticleStyleKind::Bitmap, | ||
| 980 | Some("ParticleStyleBlob") => ParticleStyleKind::Blob, | ||
| 981 | _ => ParticleStyleKind::Point, | ||
| 982 | }; | ||
| 983 | let size_over_life = node | ||
| 984 | .inputs | ||
| 985 | .get("ParticleStyle.SizeOverLife") | ||
| 986 | .and_then(|b| b.source_op.as_deref()) | ||
| 987 | .and_then(|src| comp.splines.get(src)); | ||
| 988 | let fade_in = comp | ||
| 989 | .eval_number(node, "ParticleStyle.FadeIn", time, 0.0, expr) | ||
| 990 | .clamp(0.0, 1.0); | ||
| 991 | let fade_out = comp | ||
| 992 | .eval_number(node, "ParticleStyle.FadeOut", time, 0.0, expr) | ||
| 993 | .clamp(0.0, 1.0); | ||
| 994 | let color_over_life_on = | ||
| 995 | comp.eval_number(node, "ParticleStyle.ColorOverLifeControls", time, 0.0, expr) > 0.5; | ||
| 996 | let color_over_life = if color_over_life_on { | ||
| 997 | comp.eval_gradient(node, "ParticleStyle.ColorOverLife", time) | ||
| 998 | } else { | ||
| 999 | None | ||
| 1000 | }; | ||
| 1001 | map.insert( | ||
| 1002 | p.emitter_id, | ||
| 1003 | EmitterRenderProps { | ||
| 1004 | style, | ||
| 1005 | size_over_life, | ||
| 1006 | fade_in, | ||
| 1007 | fade_out, | ||
| 1008 | color_over_life, | ||
| 1009 | }, | ||
| 1010 | ); | ||
| 1011 | } | ||
| 1012 | map | ||
| 1013 | } | ||
| 1014 | |||
| 1015 | fn rasterize_particles( | ||
| 1016 | out: &mut [u8], | ||
| 1017 | dims: [u32; 2], | ||
| 1018 | comp: &Comp, | ||
| 1019 | particles: &[Particle], | ||
| 1020 | time: f64, | ||
| 1021 | expr: &ExprEngine, | ||
| 1022 | sprites: &HashMap<NodeId, SpriteImage>, | ||
| 1023 | ) { | ||
| 1024 | if particles.is_empty() { | ||
| 1025 | return; | ||
| 1026 | } | ||
| 1027 | |||
| 1028 | let props_map = collect_emitter_render_props(comp, particles, time, expr); | ||
| 1029 | let w = dims[0] as usize; | ||
| 1030 | let h = dims[1] as usize; | ||
| 1031 | let w_f = w as f64; | ||
| 1032 | let h_f = h as f64; | ||
| 1033 | |||
| 1034 | // Accumulate in linear-ish float premultiplied RGBA for clean blending, then pack to u8. | ||
| 1035 | let mut accum = vec![0.0f32; w * h * 4]; | ||
| 1036 | |||
| 1037 | for p in particles { | ||
| 1038 | if !p.alive { | ||
| 1039 | continue; | ||
| 1040 | } | ||
| 1041 | let Some(props) = props_map.get(&p.emitter_id) else { | ||
| 1042 | continue; | ||
| 1043 | }; | ||
| 1044 | |||
| 1045 | let life_frac = (p.age / p.lifespan.max(1.0)).clamp(0.0, 1.0); | ||
| 1046 | // Fusion's SizeOverLife LUT maps 0.5 -> 1.0x (0.0 -> 0x, 1.0 -> 2x). | ||
| 1047 | let size_mult = props | ||
| 1048 | .size_over_life | ||
| 1049 | .map(|sp| (2.0 * sp.eval(life_frac)).max(0.0)) | ||
| 1050 | .unwrap_or(1.0); | ||
| 1051 | let size_world = p.size * size_mult; | ||
| 1052 | if size_world <= 1e-6 { | ||
| 1053 | continue; | ||
| 1054 | } | ||
| 1055 | |||
| 1056 | let mut fade = 1.0f64; | ||
| 1057 | if props.fade_in > 1e-6 && life_frac < props.fade_in { | ||
| 1058 | fade *= life_frac / props.fade_in; | ||
| 1059 | } | ||
| 1060 | if props.fade_out > 1e-6 && life_frac > (1.0 - props.fade_out) { | ||
| 1061 | fade *= ((1.0 - life_frac) / props.fade_out).max(0.0); | ||
| 1062 | } | ||
| 1063 | |||
| 1064 | let mut cr = p.color[0]; | ||
| 1065 | let mut cg = p.color[1]; | ||
| 1066 | let mut cb = p.color[2]; | ||
| 1067 | let mut ca = p.color[3] * fade as f32; | ||
| 1068 | if let Some(grad) = &props.color_over_life { | ||
| 1069 | let g = grad.sample(life_frac); | ||
| 1070 | cr *= g[0]; | ||
| 1071 | cg *= g[1]; | ||
| 1072 | cb *= g[2]; | ||
| 1073 | ca *= g[3]; | ||
| 1074 | } | ||
| 1075 | ca = ca.clamp(0.0, 1.0); | ||
| 1076 | if ca <= 1e-4 { | ||
| 1077 | continue; | ||
| 1078 | } | ||
| 1079 | |||
| 1080 | // Fusion 2D particle coordinates: X in [-0.5, +0.5], Y-up with same unit scale as X. | ||
| 1081 | let cx = (p.pos[0] + 0.5) * w_f; | ||
| 1082 | let cy = h_f * 0.5 - p.pos[1] * w_f; | ||
| 1083 | |||
| 1084 | if props.style == ParticleStyleKind::Bitmap { | ||
| 1085 | if let Some(sprite) = sprites.get(&p.emitter_id) { | ||
| 1086 | if sprite.size[0] > 0 | ||
| 1087 | && sprite.size[1] > 0 | ||
| 1088 | && sprite.rgba.len() | ||
| 1089 | >= (sprite.size[0] as usize) | ||
| 1090 | .saturating_mul(sprite.size[1] as usize) | ||
| 1091 | .saturating_mul(4) | ||
| 1092 | { | ||
| 1093 | draw_bitmap_particle( | ||
| 1094 | &mut accum, | ||
| 1095 | w, | ||
| 1096 | h, | ||
| 1097 | cx, | ||
| 1098 | cy, | ||
| 1099 | size_world * w_f, | ||
| 1100 | p.rot_z, | ||
| 1101 | [cr, cg, cb, ca], | ||
| 1102 | sprite, | ||
| 1103 | ); | ||
| 1104 | continue; | ||
| 1105 | } | ||
| 1106 | } | ||
| 1107 | } | ||
| 1108 | |||
| 1109 | let is_blob = props.style == ParticleStyleKind::Blob; | ||
| 1110 | draw_radial_particle( | ||
| 1111 | &mut accum, | ||
| 1112 | w, | ||
| 1113 | h, | ||
| 1114 | cx, | ||
| 1115 | cy, | ||
| 1116 | (size_world * w_f * 0.5).max(0.75), | ||
| 1117 | [cr, cg, cb, ca], | ||
| 1118 | is_blob, | ||
| 1119 | ); | ||
| 1120 | } | ||
| 1121 | |||
| 1122 | for (dst, &src) in out.iter_mut().zip(accum.iter()) { | ||
| 1123 | *dst = (src.clamp(0.0, 1.0) * 255.0 + 0.5) as u8; | ||
| 1124 | } | ||
| 1125 | } | ||
| 1126 | |||
| 1127 | #[allow(clippy::too_many_arguments)] | ||
| 1128 | fn draw_bitmap_particle( | ||
| 1129 | accum: &mut [f32], | ||
| 1130 | w: usize, | ||
| 1131 | h: usize, | ||
| 1132 | cx: f64, | ||
| 1133 | cy: f64, | ||
| 1134 | draw_w: f64, | ||
| 1135 | rot_z_deg: f64, | ||
| 1136 | tint: [f32; 4], | ||
| 1137 | sprite: &SpriteImage, | ||
| 1138 | ) { | ||
| 1139 | let sw = sprite.size[0] as f64; | ||
| 1140 | let sh = sprite.size[1] as f64; | ||
| 1141 | let draw_h = draw_w * (sh / sw); | ||
| 1142 | if draw_w < 0.5 || draw_h < 0.5 { | ||
| 1143 | return; | ||
| 1144 | } | ||
| 1145 | |||
| 1146 | let hw = draw_w * 0.5; | ||
| 1147 | let hh = draw_h * 0.5; | ||
| 1148 | let theta = rot_z_deg.to_radians(); | ||
| 1149 | let cos_t = theta.cos(); | ||
| 1150 | let sin_t = theta.sin(); | ||
| 1151 | |||
| 1152 | let rx = hw * cos_t.abs() + hh * sin_t.abs() + 1.0; | ||
| 1153 | let ry = hw * sin_t.abs() + hh * cos_t.abs() + 1.0; | ||
| 1154 | |||
| 1155 | let min_x = ((cx - rx).floor() as isize).max(0) as usize; | ||
| 1156 | let max_x = ((cx + rx).ceil() as isize).min(w as isize - 1); | ||
| 1157 | let min_y = ((cy - ry).floor() as isize).max(0) as usize; | ||
| 1158 | let max_y = ((cy + ry).ceil() as isize).min(h as isize - 1); | ||
| 1159 | if max_x < min_x as isize || max_y < min_y as isize { | ||
| 1160 | return; | ||
| 1161 | } | ||
| 1162 | |||
| 1163 | let inv_dw = 1.0 / draw_w; | ||
| 1164 | let inv_dh = 1.0 / draw_h; | ||
| 1165 | let edge_u = inv_dw * 0.5; | ||
| 1166 | let edge_v = inv_dh * 0.5; | ||
| 1167 | let sw_i = sprite.size[0] as usize; | ||
| 1168 | let sh_i = sprite.size[1] as usize; | ||
| 1169 | |||
| 1170 | for py in min_y..=(max_y as usize) { | ||
| 1171 | let dy = (py as f64 + 0.5) - cy; | ||
| 1172 | let row_off = py * w * 4; | ||
| 1173 | for px in min_x..=(max_x as usize) { | ||
| 1174 | let dx = (px as f64 + 0.5) - cx; | ||
| 1175 | // Inverse rotate into sprite local space (CCW in Y-up). | ||
| 1176 | let lx = dx * cos_t - dy * sin_t; | ||
| 1177 | let ly = dx * sin_t + dy * cos_t; | ||
| 1178 | |||
| 1179 | let u = lx * inv_dw + 0.5; | ||
| 1180 | let v = ly * inv_dh + 0.5; | ||
| 1181 | if u <= -edge_u || u >= 1.0 + edge_u || v <= -edge_v || v >= 1.0 + edge_v { | ||
| 1182 | continue; | ||
| 1183 | } | ||
| 1184 | |||
| 1185 | // Anti-aliased border coverage (0.5px feather at edges). | ||
| 1186 | let cov_u = ((u + edge_u) / (2.0 * edge_u)) | ||
| 1187 | .min((1.0 + edge_u - u) / (2.0 * edge_u)) | ||
| 1188 | .clamp(0.0, 1.0); | ||
| 1189 | let cov_v = ((v + edge_v) / (2.0 * edge_v)) | ||
| 1190 | .min((1.0 + edge_v - v) / (2.0 * edge_v)) | ||
| 1191 | .clamp(0.0, 1.0); | ||
| 1192 | let cov = (cov_u * cov_v) as f32; | ||
| 1193 | if cov <= 1e-4 { | ||
| 1194 | continue; | ||
| 1195 | } | ||
| 1196 | |||
| 1197 | let sample = sample_sprite_bilinear( | ||
| 1198 | &sprite.rgba, | ||
| 1199 | sw_i, | ||
| 1200 | sh_i, | ||
| 1201 | u.clamp(0.0, 1.0), | ||
| 1202 | v.clamp(0.0, 1.0), | ||
| 1203 | ); | ||
| 1204 | let alpha_scale = tint[3] * cov; | ||
| 1205 | let pa = sample[3] * alpha_scale; | ||
| 1206 | if pa <= 1e-5 { | ||
| 1207 | continue; | ||
| 1208 | } | ||
| 1209 | let pr = sample[0] * tint[0] * alpha_scale; | ||
| 1210 | let pg = sample[1] * tint[1] * alpha_scale; | ||
| 1211 | let pb = sample[2] * tint[2] * alpha_scale; | ||
| 1212 | |||
| 1213 | let idx = row_off + px * 4; | ||
| 1214 | let inv_a = 1.0 - pa; | ||
| 1215 | accum[idx] = pr + accum[idx] * inv_a; | ||
| 1216 | accum[idx + 1] = pg + accum[idx + 1] * inv_a; | ||
| 1217 | accum[idx + 2] = pb + accum[idx + 2] * inv_a; | ||
| 1218 | accum[idx + 3] = pa + accum[idx + 3] * inv_a; | ||
| 1219 | } | ||
| 1220 | } | ||
| 1221 | } | ||
| 1222 | |||
| 1223 | #[inline] | ||
| 1224 | fn sample_sprite_bilinear(rgba: &[u8], w: usize, h: usize, u: f64, v: f64) -> [f32; 4] { | ||
| 1225 | let fx = (u * w as f64 - 0.5).clamp(0.0, (w - 1) as f64); | ||
| 1226 | let fy = (v * h as f64 - 0.5).clamp(0.0, (h - 1) as f64); | ||
| 1227 | let x0 = fx.floor() as usize; | ||
| 1228 | let y0 = fy.floor() as usize; | ||
| 1229 | let x1 = (x0 + 1).min(w - 1); | ||
| 1230 | let y1 = (y0 + 1).min(h - 1); | ||
| 1231 | let tx = (fx - x0 as f64) as f32; | ||
| 1232 | let ty = (fy - y0 as f64) as f32; | ||
| 1233 | |||
| 1234 | let i00 = (y0 * w + x0) * 4; | ||
| 1235 | let i10 = (y0 * w + x1) * 4; | ||
| 1236 | let i01 = (y1 * w + x0) * 4; | ||
| 1237 | let i11 = (y1 * w + x1) * 4; | ||
| 1238 | |||
| 1239 | let w00 = (1.0 - tx) * (1.0 - ty) * (1.0 / 255.0); | ||
| 1240 | let w10 = tx * (1.0 - ty) * (1.0 / 255.0); | ||
| 1241 | let w01 = (1.0 - tx) * ty * (1.0 / 255.0); | ||
| 1242 | let w11 = tx * ty * (1.0 / 255.0); | ||
| 1243 | |||
| 1244 | [ | ||
| 1245 | rgba[i00] as f32 * w00 | ||
| 1246 | + rgba[i10] as f32 * w10 | ||
| 1247 | + rgba[i01] as f32 * w01 | ||
| 1248 | + rgba[i11] as f32 * w11, | ||
| 1249 | rgba[i00 + 1] as f32 * w00 | ||
| 1250 | + rgba[i10 + 1] as f32 * w10 | ||
| 1251 | + rgba[i01 + 1] as f32 * w01 | ||
| 1252 | + rgba[i11 + 1] as f32 * w11, | ||
| 1253 | rgba[i00 + 2] as f32 * w00 | ||
| 1254 | + rgba[i10 + 2] as f32 * w10 | ||
| 1255 | + rgba[i01 + 2] as f32 * w01 | ||
| 1256 | + rgba[i11 + 2] as f32 * w11, | ||
| 1257 | rgba[i00 + 3] as f32 * w00 | ||
| 1258 | + rgba[i10 + 3] as f32 * w10 | ||
| 1259 | + rgba[i01 + 3] as f32 * w01 | ||
| 1260 | + rgba[i11 + 3] as f32 * w11, | ||
| 1261 | ] | ||
| 1262 | } | ||
| 1263 | |||
| 1264 | #[allow(clippy::too_many_arguments)] | ||
| 1265 | fn draw_radial_particle( | ||
| 1266 | accum: &mut [f32], | ||
| 1267 | w: usize, | ||
| 1268 | h: usize, | ||
| 1269 | cx: f64, | ||
| 1270 | cy: f64, | ||
| 1271 | radius: f64, | ||
| 1272 | color: [f32; 4], | ||
| 1273 | is_blob: bool, | ||
| 1274 | ) { | ||
| 1275 | let bound = radius + 1.0; | ||
| 1276 | let min_x = ((cx - bound).floor() as isize).max(0) as usize; | ||
| 1277 | let max_x = ((cx + bound).ceil() as isize).min(w as isize - 1); | ||
| 1278 | let min_y = ((cy - bound).floor() as isize).max(0) as usize; | ||
| 1279 | let max_y = ((cy + bound).ceil() as isize).min(h as isize - 1); | ||
| 1280 | if max_x < min_x as isize || max_y < min_y as isize { | ||
| 1281 | return; | ||
| 1282 | } | ||
| 1283 | |||
| 1284 | let r_sq_max = (radius + 0.5) * (radius + 0.5); | ||
| 1285 | let inv_r = 1.0 / radius.max(1e-6); | ||
| 1286 | |||
| 1287 | for py in min_y..=(max_y as usize) { | ||
| 1288 | let dy = (py as f64 + 0.5) - cy; | ||
| 1289 | let dy2 = dy * dy; | ||
| 1290 | let row_off = py * w * 4; | ||
| 1291 | for px in min_x..=(max_x as usize) { | ||
| 1292 | let dx = (px as f64 + 0.5) - cx; | ||
| 1293 | let d2 = dx * dx + dy2; | ||
| 1294 | if d2 >= r_sq_max { | ||
| 1295 | continue; | ||
| 1296 | } | ||
| 1297 | let dist = d2.sqrt(); | ||
| 1298 | let cov = if is_blob { | ||
| 1299 | let t = (dist * inv_r).clamp(0.0, 1.0); | ||
| 1300 | let s = 1.0 - t * t; | ||
| 1301 | (s * s) as f32 | ||
| 1302 | } else { | ||
| 1303 | (radius + 0.5 - dist).clamp(0.0, 1.0) as f32 | ||
| 1304 | }; | ||
| 1305 | let pa = (color[3] * cov).clamp(0.0, 1.0); | ||
| 1306 | if pa <= 1e-5 { | ||
| 1307 | continue; | ||
| 1308 | } | ||
| 1309 | let pr = color[0] * pa; | ||
| 1310 | let pg = color[1] * pa; | ||
| 1311 | let pb = color[2] * pa; | ||
| 1312 | |||
| 1313 | let idx = row_off + px * 4; | ||
| 1314 | let inv_a = 1.0 - pa; | ||
| 1315 | accum[idx] = pr + accum[idx] * inv_a; | ||
| 1316 | accum[idx + 1] = pg + accum[idx + 1] * inv_a; | ||
| 1317 | accum[idx + 2] = pb + accum[idx + 2] * inv_a; | ||
| 1318 | accum[idx + 3] = pa + accum[idx + 3] * inv_a; | ||
| 1319 | } | ||
| 1320 | } | ||
| 1321 | } | ||
| 1322 | |||
| 1323 | #[cfg(test)] | ||
| 1324 | mod tests { | ||
| 1325 | use super::*; | ||
| 1326 | use std::path::Path; | ||
| 1327 | use std::time::Instant; | ||
| 1328 | |||
| 1329 | fn make_white_sprite(size: u32) -> SpriteImage { | ||
| 1330 | SpriteImage { | ||
| 1331 | size: [size, size], | ||
| 1332 | rgba: vec![255u8; (size as usize) * (size as usize) * 4], | ||
| 1333 | } | ||
| 1334 | } | ||
| 1335 | |||
| 1336 | fn count_nonzero_alpha(buf: &[u8]) -> usize { | ||
| 1337 | buf.chunks_exact(4).filter(|px| px[3] > 0).count() | ||
| 1338 | } | ||
| 1339 | |||
| 1340 | #[test] | ||
| 1341 | fn test_particle_emitter_and_point_force_deterministic() { | ||
| 1342 | let comp_src = r#" | ||
| 1343 | Composition { | ||
| 1344 | GlobalRange = { 0, 100 }, | ||
| 1345 | RenderRange = { 0, 100 }, | ||
| 1346 | Tools = { | ||
| 1347 | SpriteSrc = Background { | ||
| 1348 | Inputs = { | ||
| 1349 | Width = Input { Value = 32, }, | ||
| 1350 | Height = Input { Value = 32, }, | ||
| 1351 | }, | ||
| 1352 | }, | ||
| 1353 | pEmitter1SizeOverLife = LUTBezier { | ||
| 1354 | KeyColorSplines = { | ||
| 1355 | [0] = { | ||
| 1356 | [0] = { 0.5, RH = { 0.333, 0.5 }, Flags = { Linear = true } }, | ||
| 1357 | [1] = { 0.25, LH = { 0.667, 0.25 }, Flags = { Linear = true } } | ||
| 1358 | } | ||
| 1359 | }, | ||
| 1360 | }, | ||
| 1361 | pEmitter1 = pEmitter { | ||
| 1362 | Inputs = { | ||
| 1363 | RandomSeed = Input { Value = 42, }, | ||
| 1364 | Number = Input { Value = 15, }, | ||
| 1365 | Lifespan = Input { Value = 60, }, | ||
| 1366 | Region = Input { Value = FuID { "RectRgn" }, }, | ||
| 1367 | ["RectRgn.Width"] = Input { Value = 0.6, }, | ||
| 1368 | ["RectRgn.Height"] = Input { Value = 0.4, }, | ||
| 1369 | Style = Input { Value = FuID { "ParticleStyleBitmap" }, }, | ||
| 1370 | ["ParticleStyleBitmap.DropToolsHere"] = Input { | ||
| 1371 | SourceOp = "SpriteSrc", | ||
| 1372 | Source = "Output", | ||
| 1373 | }, | ||
| 1374 | ["ParticleStyle.Red"] = Input { Value = 1, }, | ||
| 1375 | ["ParticleStyle.Green"] = Input { Value = 0, }, | ||
| 1376 | ["ParticleStyle.Blue"] = Input { Value = 0, }, | ||
| 1377 | ["ParticleStyle.ColorVariance"] = Input { Value = 1, }, | ||
| 1378 | ["ParticleStyle.GreenHigh"] = Input { Value = 1, }, | ||
| 1379 | ["ParticleStyle.Size"] = Input { Value = 0.12, }, | ||
| 1380 | ["ParticleStyle.SizeOverLife"] = Input { | ||
| 1381 | SourceOp = "pEmitter1SizeOverLife", | ||
| 1382 | Source = "Value", | ||
| 1383 | }, | ||
| 1384 | ["ParticleStyle.FadeIn"] = Input { Value = 0.1, }, | ||
| 1385 | ["ParticleStyle.FadeOut"] = Input { Value = 0.1, }, | ||
| 1386 | }, | ||
| 1387 | }, | ||
| 1388 | pPointForce1 = pPointForce { | ||
| 1389 | Inputs = { | ||
| 1390 | Strength = Input { Value = -3.0, }, | ||
| 1391 | Power = Input { Value = 0.5, }, | ||
| 1392 | ["Translate.X"] = Input { Value = 0.0, }, | ||
| 1393 | ["Translate.Y"] = Input { Value = 0.0, }, | ||
| 1394 | Input = Input { | ||
| 1395 | SourceOp = "pEmitter1", | ||
| 1396 | Source = "Output", | ||
| 1397 | }, | ||
| 1398 | }, | ||
| 1399 | }, | ||
| 1400 | pRender1 = pRender { | ||
| 1401 | Inputs = { | ||
| 1402 | Input = Input { | ||
| 1403 | SourceOp = "pPointForce1", | ||
| 1404 | Source = "Output", | ||
| 1405 | }, | ||
| 1406 | }, | ||
| 1407 | }, | ||
| 1408 | }, | ||
| 1409 | } | ||
| 1410 | "#; | ||
| 1411 | |||
| 1412 | let comp = Comp::from_fusion_str(comp_src).expect("parse synthetic particle comp"); | ||
| 1413 | let render_id = comp.node_by_name["pRender1"]; | ||
| 1414 | let emitter_id = comp.node_by_name["pEmitter1"]; | ||
| 1415 | let sprite_id = comp.node_by_name["SpriteSrc"]; | ||
| 1416 | let force_id = comp.node_by_name["pPointForce1"]; | ||
| 1417 | |||
| 1418 | // Verify bitmap source discovery. | ||
| 1419 | let sources = collect_bitmap_sources(&comp, render_id); | ||
| 1420 | assert_eq!(sources, vec![(emitter_id, sprite_id)]); | ||
| 1421 | |||
| 1422 | let expr = ExprEngine::new(); | ||
| 1423 | let mut sprites = HashMap::new(); | ||
| 1424 | sprites.insert(emitter_id, make_white_sprite(16)); | ||
| 1425 | |||
| 1426 | let dims = [160, 90]; | ||
| 1427 | |||
| 1428 | // 1. Determinism: two fresh caches produce bit-identical buffers. | ||
| 1429 | let mut cache_a = ParticleCache::default(); | ||
| 1430 | let mut cache_b = ParticleCache::default(); | ||
| 1431 | let img_a = render_particles_2d(&mut cache_a, &comp, render_id, 25.0, dims, &expr, &sprites); | ||
| 1432 | let img_b = render_particles_2d(&mut cache_b, &comp, render_id, 25.0, dims, &expr, &sprites); | ||
| 1433 | assert_eq!(img_a, img_b, "particle render must be bit-identical across runs"); | ||
| 1434 | assert!( | ||
| 1435 | count_nonzero_alpha(&img_a) > 50, | ||
| 1436 | "expected non-empty rendered particles" | ||
| 1437 | ); | ||
| 1438 | |||
| 1439 | // 2. Force affects particle trajectories: bypassing pPointForce1 changes output. | ||
| 1440 | let mut comp_no_force = comp.clone(); | ||
| 1441 | comp_no_force.nodes[force_id.0].bypassed = true; | ||
| 1442 | comp_no_force.revision += 1; | ||
| 1443 | let mut cache_no_force = ParticleCache::default(); | ||
| 1444 | let img_no_force = render_particles_2d( | ||
| 1445 | &mut cache_no_force, | ||
| 1446 | &comp_no_force, | ||
| 1447 | render_id, | ||
| 1448 | 25.0, | ||
| 1449 | dims, | ||
| 1450 | &expr, | ||
| 1451 | &sprites, | ||
| 1452 | ); | ||
| 1453 | assert_ne!( | ||
| 1454 | img_a, img_no_force, | ||
| 1455 | "pPointForce must visibly change particle trajectories" | ||
| 1456 | ); | ||
| 1457 | |||
| 1458 | // 3. Cache consistency & sequential speedup: stepping 25 -> 26 matches fresh 0 -> 26. | ||
| 1459 | let t_seq_start = Instant::now(); | ||
| 1460 | let img_26_cached = | ||
| 1461 | render_particles_2d(&mut cache_a, &comp, render_id, 26.0, dims, &expr, &sprites); | ||
| 1462 | let seq_elapsed = t_seq_start.elapsed(); | ||
| 1463 | |||
| 1464 | let mut fresh_cache = ParticleCache::default(); | ||
| 1465 | let t_fresh_start = Instant::now(); | ||
| 1466 | let img_26_fresh = render_particles_2d( | ||
| 1467 | &mut fresh_cache, | ||
| 1468 | &comp, | ||
| 1469 | render_id, | ||
| 1470 | 26.0, | ||
| 1471 | dims, | ||
| 1472 | &expr, | ||
| 1473 | &sprites, | ||
| 1474 | ); | ||
| 1475 | let fresh_elapsed = t_fresh_start.elapsed(); | ||
| 1476 | assert_eq!( | ||
| 1477 | img_26_cached, img_26_fresh, | ||
| 1478 | "cached sequential step must match fresh simulation" | ||
| 1479 | ); | ||
| 1480 | assert!( | ||
| 1481 | seq_elapsed <= fresh_elapsed * 2 + std::time::Duration::from_millis(5), | ||
| 1482 | "cached sequential step should be fast (seq={seq_elapsed:?}, fresh={fresh_elapsed:?})" | ||
| 1483 | ); | ||
| 1484 | |||
| 1485 | cache_a.clear(); | ||
| 1486 | assert!(cache_a.entries.is_empty()); | ||
| 1487 | } | ||
| 1488 | |||
| 1489 | #[test] | ||
| 1490 | fn test_01_intro_particles_if_present() { | ||
| 1491 | let path = Path::new("/Volumes/Project/trees/fusion/01_intro.comp"); | ||
| 1492 | if !path.exists() { | ||
| 1493 | return; | ||
| 1494 | } | ||
| 1495 | |||
| 1496 | let comp = Comp::from_fusion_file(path).expect("parse 01_intro.comp"); | ||
| 1497 | let render_id = comp.node_by_name["pRender1"]; | ||
| 1498 | let emitter_id = comp.node_by_name["pEmitter1"]; | ||
| 1499 | let bc4_id = comp.node_by_name["BrightnessContrast4"]; | ||
| 1500 | |||
| 1501 | let sources = collect_bitmap_sources(&comp, render_id); | ||
| 1502 | assert_eq!( | ||
| 1503 | sources, | ||
| 1504 | vec![(emitter_id, bc4_id)], | ||
| 1505 | "01_intro.comp pEmitter1 bitmap source should be BrightnessContrast4" | ||
| 1506 | ); | ||
| 1507 | |||
| 1508 | let expr = ExprEngine::new(); | ||
| 1509 | let mut sprites = HashMap::new(); | ||
| 1510 | sprites.insert(emitter_id, make_white_sprite(32)); | ||
| 1511 | |||
| 1512 | // In 01_intro.comp, TimeStretcher1 evaluates pRender1 at SourceTime = time / 25 | ||
| 1513 | // (so comp f600 -> t=24, comp f1600 -> t=64). | ||
| 1514 | let ts_node = &comp.nodes[comp.node_by_name["TimeStretcher1"].0]; | ||
| 1515 | let t_f600 = comp.eval_number(ts_node, "SourceTime", 600.0, 24.0, &expr); | ||
| 1516 | let t_f1600 = comp.eval_number(ts_node, "SourceTime", 1600.0, 64.0, &expr); | ||
| 1517 | |||
| 1518 | let dims = [320, 180]; | ||
| 1519 | let mut cache = ParticleCache::default(); | ||
| 1520 | let start = Instant::now(); | ||
| 1521 | let buf_600 = render_particles_2d(&mut cache, &comp, render_id, t_f600, dims, &expr, &sprites); | ||
| 1522 | let buf_1600 = | ||
| 1523 | render_particles_2d(&mut cache, &comp, render_id, t_f1600, dims, &expr, &sprites); | ||
| 1524 | let elapsed = start.elapsed(); | ||
| 1525 | |||
| 1526 | let nz_600 = count_nonzero_alpha(&buf_600); | ||
| 1527 | let nz_1600 = count_nonzero_alpha(&buf_1600); | ||
| 1528 | assert!( | ||
| 1529 | nz_600 > 0, | ||
| 1530 | "expected non-zero alpha pixels at f600 (SourceTime={t_f600})" | ||
| 1531 | ); | ||
| 1532 | assert!( | ||
| 1533 | nz_1600 > 0, | ||
| 1534 | "expected non-zero alpha pixels at f1600 (SourceTime={t_f1600})" | ||
| 1535 | ); | ||
| 1536 | assert!( | ||
| 1537 | elapsed.as_secs_f64() < 2.0, | ||
| 1538 | "01_intro particle render should be fast, took {elapsed:?}" | ||
| 1539 | ); | ||
| 1540 | } | ||
| 1541 | } | ||
crates/engine/src/shaders.wgsl+16-10| ... | @@ -842,16 +842,22 @@ fn displace_op(@builtin(global_invocation_id) gid: vec3<u32>) { | ... | @@ -842,16 +842,22 @@ fn displace_op(@builtin(global_invocation_id) gid: vec3<u32>) { |
| 842 | warped = sample_edges(src_a, fu + base_disp, 2); | 842 | warped = sample_edges(src_a, fu + base_disp, 2); |
| 843 | } | 843 | } |
| 844 | 844 | ||
| 845 | if (light_power > 1e-4) { | 845 | if (abs(light_power) > 1e-4) { |
| 846 | let dx = 1.0 / fdims.x; | 846 | let light_angle = u.p[4].x; |
| 847 | let dy = 1.0 / fdims.y; | 847 | let light_ch = i32(u.p[4].y + 0.5); |
| 848 | let lx0 = dot(textureSampleLevel(src_b, samp_lin, clamp(uv - vec2<f32>(dx, 0.0), vec2<f32>(0.0), vec2<f32>(1.0)), 0.0).rgb, vec3<f32>(0.299, 0.587, 0.114)); | 848 | // Fusion Displace radial LightPower adds directional slope lighting from Foreground |
| 849 | let lx1 = dot(textureSampleLevel(src_b, samp_lin, clamp(uv + vec2<f32>(dx, 0.0), vec2<f32>(0.0), vec2<f32>(1.0)), 0.0).rgb, vec3<f32>(0.299, 0.587, 0.114)); | 849 | // along LightAngle (default 0 deg -> diagonal (+1, +1) in UV y-down, per-channel RGB by default). |
| 850 | let ly0 = dot(textureSampleLevel(src_b, samp_lin, clamp(uv - vec2<f32>(0.0, dy), vec2<f32>(0.0), vec2<f32>(1.0)), 0.0).rgb, vec3<f32>(0.299, 0.587, 0.114)); | 850 | let dir_uv = vec2<f32>(cos(light_angle), -sin(light_angle)) * 1.41421356 / fdims; |
| 851 | let ly1 = dot(textureSampleLevel(src_b, samp_lin, clamp(uv + vec2<f32>(0.0, dy), vec2<f32>(0.0), vec2<f32>(1.0)), 0.0).rgb, vec3<f32>(0.299, 0.587, 0.114)); | 851 | let s_pos = textureSampleLevel(src_b, samp_lin, clamp(uv + dir_uv, vec2<f32>(0.0), vec2<f32>(1.0)), 0.0); |
| 852 | let grad = vec2<f32>(lx1 - lx0, ly0 - ly1); | 852 | let s_neg = textureSampleLevel(src_b, samp_lin, clamp(uv - dir_uv, vec2<f32>(0.0), vec2<f32>(1.0)), 0.0); |
| 853 | let shade = clamp(1.0 + dot(grad, vec2<f32>(0.707, 0.707)) * light_power * 1.2, 0.0, 2.0); | 853 | var delta_rgb: vec3<f32>; |
| 854 | warped = vec4<f32>(warped.rgb * shade, warped.a); | 854 | if (light_ch >= 0 && light_ch <= 4) { |
| 855 | let d = pick_channel(s_pos, light_ch) - pick_channel(s_neg, light_ch); | ||
| 856 | delta_rgb = vec3<f32>(d, d, d); | ||
| 857 | } else { | ||
| 858 | delta_rgb = s_pos.rgb - s_neg.rgb; | ||
| 859 | } | ||
| 860 | warped = vec4<f32>(max(warped.rgb + delta_rgb * light_power, vec3<f32>(0.0)), warped.a); | ||
| 855 | } | 861 | } |
| 856 | } | 862 | } |
| 857 | 863 |
crates/model/src/comp.rs+14| ... | @@ -127,7 +127,21 @@ pub fn is_supported_tool(kind: &str) -> bool { | ... | @@ -127,7 +127,21 @@ pub fn is_supported_tool(kind: &str) -> bool { |
| 127 | | "Fuse.Colorize" | 127 | | "Fuse.Colorize" |
| 128 | | "Fuse.Outline" | 128 | | "Fuse.Outline" |
| 129 | | "Fuse.XfChroma" | 129 | | "Fuse.XfChroma" |
| 130 | | "Fuse.Cryptomatte" | ||
| 131 | | "Cryptomatte" | ||
| 132 | | "Dimension.OpticalFlow" | ||
| 133 | | "OpticalFlow" | ||
| 130 | | "Custom" | 134 | | "Custom" |
| 135 | // Particle system | ||
| 136 | | "pRender" | ||
| 137 | | "pEmitter" | ||
| 138 | | "pPointForce" | ||
| 139 | | "pDirectionalForce" | ||
| 140 | | "pTurbulence" | ||
| 141 | | "pDrag" | ||
| 142 | | "pFriction" | ||
| 143 | | "pKill" | ||
| 144 | | "pMerge" | ||
| 131 | // 3D tools | 145 | // 3D tools |
| 132 | | "Renderer3D" | 146 | | "Renderer3D" |
| 133 | | "Merge3D" | 147 | | "Merge3D" |
scripts/fusion_probes.py+3-1| ... | @@ -905,7 +905,9 @@ def build_probe_text(): | ... | @@ -905,7 +905,9 @@ def build_probe_text(): |
| 905 | (1, "txt_left_top", 'StyledText = Input { Value = "TopLeft", }, Size = Input { Value = 0.10, }, Center = Input { Value = { 0.2, 0.7 }, }, HorizontalLeftCenterRight = Input { Value = -1, }, VerticalTopCenterBottom = Input { Value = -1, },'), | 905 | (1, "txt_left_top", 'StyledText = Input { Value = "TopLeft", }, Size = Input { Value = 0.10, }, Center = Input { Value = { 0.2, 0.7 }, }, HorizontalLeftCenterRight = Input { Value = -1, }, VerticalTopCenterBottom = Input { Value = -1, },'), |
| 906 | (2, "txt_right_bottom", 'StyledText = Input { Value = "BotRight", }, Size = Input { Value = 0.10, }, Center = Input { Value = { 0.8, 0.3 }, }, HorizontalLeftCenterRight = Input { Value = 1, }, VerticalTopCenterBottom = Input { Value = 1, },'), | 906 | (2, "txt_right_bottom", 'StyledText = Input { Value = "BotRight", }, Size = Input { Value = 0.10, }, Center = Input { Value = { 0.8, 0.3 }, }, HorizontalLeftCenterRight = Input { Value = 1, }, VerticalTopCenterBottom = Input { Value = 1, },'), |
| 907 | (3, "txt_tracking_1.3", 'StyledText = Input { Value = "WIDE", }, Size = Input { Value = 0.12, }, CharacterSpacing = Input { Value = 1.3, },'), | 907 | (3, "txt_tracking_1.3", 'StyledText = Input { Value = "WIDE", }, Size = Input { Value = 0.12, }, CharacterSpacing = Input { Value = 1.3, },'), |
| 908 | (4, "txt_outline_round", 'StyledText = Input { Value = "the", }, Size = Input { Value = 0.18, }, Enabled2 = Input { Value = 1, }, ElementShape2 = Input { Value = 2, }, Thickness2 = Input { Value = 0.04, }, Red2 = Input { Value = 0.9, }, Green2 = Input { Value = 0.2, }, Blue2 = Input { Value = 0.2, },'), | 908 | (4, "txt_border_default", 'StyledText = Input { Value = "the", }, Size = Input { Value = 0.18, }, Enabled2 = Input { Value = 1, }, ElementShape2 = Input { Value = 2, }, Thickness2 = Input { Value = 0.04, }, Red2 = Input { Value = 0.9, }, Green2 = Input { Value = 0.2, }, Blue2 = Input { Value = 0.2, },'), |
| 909 | (5, "txt_border_ext_rnd", 'StyledText = Input { Value = "Hi Box", }, Size = Input { Value = 0.14, }, Enabled2 = Input { Value = 1, }, ElementShape2 = Input { Value = 2, }, Level2 = Input { Value = 3, }, ExtendHorizontal2 = Input { Value = 0.2, }, ExtendVertical2 = Input { Value = 0.15, }, Round2 = Input { Value = 0.4, }, Red2 = Input { Value = 0.15, }, Green2 = Input { Value = 0.45, }, Blue2 = Input { Value = 0.85, },'), | ||
| 910 | (6, "txt_border_offset", 'StyledText = Input { Value = "BOX", }, Size = Input { Value = 0.16, }, Enabled2 = Input { Value = 1, }, ElementShape2 = Input { Value = 2, }, Level2 = Input { Value = 2, }, ExtendHorizontal2 = Input { Value = 0.1, }, ExtendVertical2 = Input { Value = 0.1, }, Offset2 = Input { Value = { 0.03, -0.02 }, }, Red2 = Input { Value = 0.2, }, Green2 = Input { Value = 0.7, }, Blue2 = Input { Value = 0.3, }, Alpha2 = Input { Value = 0.8, },'), | ||
| 909 | ] | 911 | ] |
| 910 | nodes = ["""\t\tBlackBG = Background { | 912 | nodes = ["""\t\tBlackBG = Background { |
| 911 | \t\t\tInputs = { Width = Input { Value = 512, }, Height = Input { Value = 512, }, TopLeftAlpha = Input { Value = 1, }, }, | 913 | \t\t\tInputs = { Width = Input { Value = 512, }, Height = Input { Value = 512, }, TopLeftAlpha = Input { Value = 1, }, }, |
scripts/gen_compatibility.py+29-20| ... | @@ -45,6 +45,7 @@ CATEGORIES: Sequence[str] = ( | ... | @@ -45,6 +45,7 @@ CATEGORIES: Sequence[str] = ( |
| 45 | "Blur, Sharpen & Glow", | 45 | "Blur, Sharpen & Glow", |
| 46 | "Transform, Warp & Framing", | 46 | "Transform, Warp & Framing", |
| 47 | "Masks", | 47 | "Masks", |
| 48 | "Particles", | ||
| 48 | "3D Pipeline", | 49 | "3D Pipeline", |
| 49 | "Time, Routing & Utility", | 50 | "Time, Routing & Utility", |
| 50 | ) | 51 | ) |
| ... | @@ -55,10 +56,10 @@ CATEGORIES: Sequence[str] = ( | ... | @@ -55,10 +56,10 @@ CATEGORIES: Sequence[str] = ( |
| 55 | TOOL_METADATA: Sequence[ToolMeta] = ( | 56 | TOOL_METADATA: Sequence[ToolMeta] = ( |
| 56 | # Generators | 57 | # Generators |
| 57 | ToolMeta("Background", "Generators", "`tier1_d`", "0.0%", "Solid, Horizontal/Vertical/4-Corner, Linear/Radial gradients; honors generator `Depth` in `HiQ`."), | 58 | ToolMeta("Background", "Generators", "`tier1_d`", "0.0%", "Solid, Horizontal/Vertical/4-Corner, Linear/Radial gradients; honors generator `Depth` in `HiQ`."), |
| 58 | ToolMeta("FastNoise", "Generators", "`noise_text`", "Visual*", "C2 quintic 3D Perlin fBm (`Detail`, `Contrast`, `Brightness`, `Seethe`, `LockXY`, `Angle`, `Discontinuous`, `Gradient`/`TwoColor`). *Proprietary Fusion lattice table differs ([#6](" + SHALE_ISSUES_URL + "/6))."), | 59 | ToolMeta("FastNoise", "Generators", "`noise_text`", "Visual*", "C2 quintic 3D Perlin fBm (`Detail`, `Contrast`, `Brightness`, `Seethe`, `LockXY`, `Angle`, `Discontinuous`, `Gradient`/`TwoColor`). *Proprietary Fusion lattice table differs."), |
| 59 | ToolMeta("Plasma", "Generators", "`tier1_c`", "0.1%–0.2%", "4-circle linear/sine interference pattern with phase/scale animation."), | 60 | ToolMeta("Plasma", "Generators", "`tier1_c`", "0.1%–0.2%", "4-circle linear/sine interference pattern with phase/scale animation."), |
| 60 | ToolMeta("TextPlus", "Generators", "`text`, `noise_text`", "0.1%–0.6%", "CoreText rasterizer, alignment, tracking, Euclidean subpixel SDF outline, `StyledTextCLS`. `BorderFill` tracked in [#6](" + SHALE_ISSUES_URL + "/6)."), | 61 | ToolMeta("TextPlus", "Generators", "`text`, `noise_text`", "0.2%–0.9%", "CoreText rasterizer, alignment, tracking, Euclidean subpixel SDF outline, `BorderFill` (`ElementShape = 2`, `Level`, `ExtendHorizontal/Vertical`, `Round`, `Offset`), and `StyledTextCLS`."), |
| 61 | ToolMeta("Loader", "Generators", "All suites", "0.0%", "PNG/JPG/TIFF/EXR stills & sequences; native macOS `AVFoundation`/`VideoToolbox` + `ffmpeg` video; `.wav`/`.mp3` audio. Direct 16/32-bit float EXR upload tracked in [#5](" + SHALE_ISSUES_URL + "/5)."), | 62 | ToolMeta("Loader", "Generators", "All suites", "0.0%", "PNG/JPG/TIFF/EXR stills & sequences with direct unclamped 16/32-bit float HDR OpenEXR upload in `HiQ`; native macOS `AVFoundation`/`VideoToolbox` + `ffmpeg` video; `.wav`/`.mp3` audio."), |
| 62 | 63 | ||
| 63 | # Compositing & Blending | 64 | # Compositing & Blending |
| 64 | ToolMeta("Merge", "Compositing & Blending", "`merge`", "0.0%–0.3%", "All ApplyModes (`Normal`, `Screen`, `Multiply`, `Difference`, `DarkerColor`, `Overlay`, `Hard/Soft/Linear/VividLight`, `LinearDodge`, etc.), `Operator=Over/Under`, `Gain`, `BurnIn`, `SubtractiveAdditive`, `Blend`, effect mask."), | 65 | ToolMeta("Merge", "Compositing & Blending", "`merge`", "0.0%–0.3%", "All ApplyModes (`Normal`, `Screen`, `Multiply`, `Difference`, `DarkerColor`, `Overlay`, `Hard/Soft/Linear/VividLight`, `LinearDodge`, etc.), `Operator=Over/Under`, `Gain`, `BurnIn`, `SubtractiveAdditive`, `Blend`, effect mask."), |
| ... | @@ -80,6 +81,7 @@ TOOL_METADATA: Sequence[ToolMeta] = ( | ... | @@ -80,6 +81,7 @@ TOOL_METADATA: Sequence[ToolMeta] = ( |
| 80 | # Keying | 81 | # Keying |
| 81 | ToolMeta("LumaKeyer", "Keying", "Suite comps", "0.1%–0.4%", "Luminance/channel threshold keying with low/high feathering and matte inversion."), | 82 | ToolMeta("LumaKeyer", "Keying", "Suite comps", "0.1%–0.4%", "Luminance/channel threshold keying with low/high feathering and matte inversion."), |
| 82 | ToolMeta("UltraKeyer", "Keying", "`tier1_a`", "0.1%–0.6%", "Chroma keying with background color pick, matte threshold/gamma, spill suppression, and post-multiply."), | 83 | ToolMeta("UltraKeyer", "Keying", "`tier1_a`", "0.1%–0.6%", "Chroma keying with background color pick, matte threshold/gamma, spill suppression, and post-multiply."), |
| 84 | ToolMeta("Fuse.Cryptomatte", "Keying", "Unit tests", "0.0%", "Cryptomatte 1.2 multi-channel EXR matte extraction (manifest JSON + MurmurHash3-32 ID/coverage rank accumulation, wildcards, `MatteOnly`).", aliases=("Cryptomatte",)), | ||
| 83 | 85 | ||
| 84 | # Blur, Sharpen & Glow | 86 | # Blur, Sharpen & Glow |
| 85 | ToolMeta("Blur", "Blur, Sharpen & Glow", "`blur`, `tier1_d`", "0.0%–0.4%", "`Fast Gaussian`, `Gaussian`, and `Box` filters; X/Y lock; `ClippingMode`; HDR float16 survival in `HiQ`; downsampled in `Fast`."), | 87 | ToolMeta("Blur", "Blur, Sharpen & Glow", "`blur`, `tier1_d`", "0.0%–0.4%", "`Fast Gaussian`, `Gaussian`, and `Box` filters; X/Y lock; `ClippingMode`; HDR float16 survival in `HiQ`; downsampled in `Fast`."), |
| ... | @@ -87,8 +89,8 @@ TOOL_METADATA: Sequence[ToolMeta] = ( | ... | @@ -87,8 +89,8 @@ TOOL_METADATA: Sequence[ToolMeta] = ( |
| 87 | ToolMeta("Filter", "Blur, Sharpen & Glow", "`tier1_a`", "0.1%–0.5%", "Convolution filter types 0–4 (`Relief`, `Emboss`, `Smooth`, `Sobel`, `Laplacian`) with power & angle."), | 89 | ToolMeta("Filter", "Blur, Sharpen & Glow", "`tier1_a`", "0.1%–0.5%", "Convolution filter types 0–4 (`Relief`, `Emboss`, `Smooth`, `Sobel`, `Laplacian`) with power & angle."), |
| 88 | ToolMeta("VariBlur", "Blur, Sharpen & Glow", "Suite comps", "0.2%–0.8%", "Per-pixel variable-radius blur driven by `BlurImage` matte."), | 90 | ToolMeta("VariBlur", "Blur, Sharpen & Glow", "Suite comps", "0.2%–0.8%", "Per-pixel variable-radius blur driven by `BlurImage` matte."), |
| 89 | ToolMeta("DirectionalBlur", "Blur, Sharpen & Glow", "`blur`", "0.1%–0.5%", "`Linear`, `Centered`, `Radial`, and `Zoom` modes plus `Glow` accumulation."), | 91 | ToolMeta("DirectionalBlur", "Blur, Sharpen & Glow", "`blur`", "0.1%–0.5%", "`Linear`, `Centered`, `Radial`, and `Zoom` modes plus `Glow` accumulation."), |
| 90 | ToolMeta("Glow", "Blur, Sharpen & Glow", "`glow`", "0.2%–1.3%", "Additive bloom (`Glow`, `GlowSize`, `Blend`, color scale). Minor Gaussian tail roll-off tracked in [#6](" + SHALE_ISSUES_URL + "/6)."), | 92 | ToolMeta("Glow", "Blur, Sharpen & Glow", "`glow`", "0.0%–0.2%", "Additive bloom (`Glow`, `GlowSize`, `Blend`, color scale, border clamping, calibrated Gaussian roll-off)."), |
| 91 | ToolMeta("SoftGlow", "Blur, Sharpen & Glow", "`glow`", "0.0%–0.8%", "Thresholded soft glow (`Gain`, `XGlowSize`/`YGlowSize`, `Threshold`, `ClippingMode`, `ColorScale`)."), | 93 | ToolMeta("SoftGlow", "Blur, Sharpen & Glow", "`glow`", "0.0%–0.2%", "Thresholded soft glow (`Gain`, `XGlowSize`/`YGlowSize`, `Threshold`, `ClippingMode`, `ColorScale`, border clamping)."), |
| 92 | ToolMeta("Fuse.XGlow", "Blur, Sharpen & Glow", "Suite comps", "0.2%–0.8%", "Multi-octave exponential glow (`Threshold`, `Gain`, `XGlowSize`, `Falloff`, `Iterations`); octave-capped in `Fast` mode."), | 94 | ToolMeta("Fuse.XGlow", "Blur, Sharpen & Glow", "Suite comps", "0.2%–0.8%", "Multi-octave exponential glow (`Threshold`, `Gain`, `XGlowSize`, `Falloff`, `Iterations`); octave-capped in `Fast` mode."), |
| 93 | ToolMeta("ErodeDilate", "Blur, Sharpen & Glow", "`blur`", "0.0%–0.3%", "Positive/negative morphological erode/dilate with `Box` and `Circle` kernels."), | 95 | ToolMeta("ErodeDilate", "Blur, Sharpen & Glow", "`blur`", "0.0%–0.3%", "Positive/negative morphological erode/dilate with `Box` and `Circle` kernels."), |
| 94 | ToolMeta("FilmGrain", "Blur, Sharpen & Glow", "`tier1_c`", "Visual*", "Monochrome log-space correlated film grain (`Size`, `Strength`, `Softness`). *Stochastic per-frame seed."), | 96 | ToolMeta("FilmGrain", "Blur, Sharpen & Glow", "`tier1_c`", "Visual*", "Monochrome log-space correlated film grain (`Size`, `Strength`, `Softness`). *Stochastic per-frame seed."), |
| ... | @@ -100,7 +102,7 @@ TOOL_METADATA: Sequence[ToolMeta] = ( | ... | @@ -100,7 +102,7 @@ TOOL_METADATA: Sequence[ToolMeta] = ( |
| 100 | ToolMeta("CameraShake", "Transform, Warp & Framing", "`tier1_c`", "0.1%–0.5%", "Procedural X/Y/Rotation/Zoom camera shake with `OverallStrength`, `Speed`, `Edges`."), | 102 | ToolMeta("CameraShake", "Transform, Warp & Framing", "`tier1_c`", "0.1%–0.5%", "Procedural X/Y/Rotation/Zoom camera shake with `OverallStrength`, `Speed`, `Edges`."), |
| 101 | ToolMeta("CornerPositioner", "Transform, Warp & Framing", "`tier1_b`", "0.1%–0.4%", "4-point projective homography warp (`TopLeft`/`TopRight`/`BottomLeft`/`BottomRight`)."), | 103 | ToolMeta("CornerPositioner", "Transform, Warp & Framing", "`tier1_b`", "0.1%–0.4%", "4-point projective homography warp (`TopLeft`/`TopRight`/`BottomLeft`/`BottomRight`)."), |
| 102 | ToolMeta("DVE", "Transform, Warp & Framing", "`tier1_b`", "0.1%–0.4%", "2.5D ZYX Euler rotation + perspective homography (`Center`, `ZMove`, `Pivot`, `AlphaMode`)."), | 104 | ToolMeta("DVE", "Transform, Warp & Framing", "`tier1_b`", "0.1%–0.4%", "2.5D ZYX Euler rotation + perspective homography (`Center`, `ZMove`, `Pivot`, `AlphaMode`)."), |
| 103 | ToolMeta("Displace", "Transform, Warp & Framing", "`displace`", "0.1%–0.7%", "`XY` refraction (channels, offsets, refraction strength) and `Radial`/`Bump` (`LightPower` angle/color minor parity tracked in [#6](" + SHALE_ISSUES_URL + "/6))."), | 105 | ToolMeta("Displace", "Transform, Warp & Framing", "`displace`", "0.0%–0.1%", "`XY` refraction (channels, offsets, refraction strength) and `Radial`/`Bump` (`LightPower`, `LightAngle`, `LightChannel` additive directional slope lighting)."), |
| 104 | ToolMeta("Scale", "Transform, Warp & Framing", "Suite comps", "0.0%–0.2%", "Proportional/non-proportional image scaling with resampling filter."), | 106 | ToolMeta("Scale", "Transform, Warp & Framing", "Suite comps", "0.0%–0.2%", "Proportional/non-proportional image scaling with resampling filter."), |
| 105 | ToolMeta("BetterResize", "Transform, Warp & Framing", "Suite comps", "0.0%–0.2%", "Target pixel-dimension resize (`Width`, `Height`, `KeepAspect`)."), | 107 | ToolMeta("BetterResize", "Transform, Warp & Framing", "Suite comps", "0.0%–0.2%", "Target pixel-dimension resize (`Width`, `Height`, `KeepAspect`)."), |
| 106 | ToolMeta("Crop", "Transform, Warp & Framing", "Suite comps", "0.0%–0.1%", "Region crop & canvas repositioning (`XOffset`, `YOffset`, `XSize`, `YSize`, `KeepCentered`)."), | 108 | ToolMeta("Crop", "Transform, Warp & Framing", "Suite comps", "0.0%–0.1%", "Region crop & canvas repositioning (`XOffset`, `YOffset`, `XSize`, `YSize`, `KeepCentered`)."), |
| ... | @@ -112,6 +114,16 @@ TOOL_METADATA: Sequence[ToolMeta] = ( | ... | @@ -112,6 +114,16 @@ TOOL_METADATA: Sequence[ToolMeta] = ( |
| 112 | ToolMeta("PolylineMask", "Masks", "Suite comps", "0.1%–0.5%", "CPU `zeno` Bezier/linear polygon rasterizer with animated keyframed `Polyline` splines, `SoftEdge`, `Invert`, `PaintMode`."), | 114 | ToolMeta("PolylineMask", "Masks", "Suite comps", "0.1%–0.5%", "CPU `zeno` Bezier/linear polygon rasterizer with animated keyframed `Polyline` splines, `SoftEdge`, `Invert`, `PaintMode`."), |
| 113 | ToolMeta("BitmapMask", "Masks", "Suite comps", "0.0%–0.2%", "Image-to-mask extraction (`Alpha`/`Luminance`/`Red`/`Green`/`Blue`), `Low`/`High` clip, `SoftEdge`, `Invert`."), | 115 | ToolMeta("BitmapMask", "Masks", "Suite comps", "0.0%–0.2%", "Image-to-mask extraction (`Alpha`/`Luminance`/`Red`/`Green`/`Blue`), `Low`/`High` clip, `SoftEdge`, `Invert`."), |
| 114 | 116 | ||
| 117 | # Particles | ||
| 118 | ToolMeta("pRender", "Particles", "Unit tests", "Visual*", "2D deterministic particle rasterizer (`ParticleStyleBitmap` rotated bilinear sprites, `ParticleStylePoint`/`Blob`, cached frame stepping). *Stochastic seed."), | ||
| 119 | ToolMeta("pEmitter", "Particles", "Unit tests", "Visual*", "Seeded particle emitter (`RectRgn`/`SphereRgn`/`CubeRgn`/`LineRgn`/`Point`, `Number`, `Lifespan`, `Velocity`, `RotationZ`, `SpinZ`, `ColorVariance`, `SizeOverLife`, `FadeIn`/`FadeOut`)."), | ||
| 120 | ToolMeta("pPointForce", "Particles", "Unit tests", "Visual*", "Radial point attractor/repulsor (`Strength`, `Power`, `Translate.X/Y/Z`)."), | ||
| 121 | ToolMeta("pDirectionalForce", "Particles", "Unit tests", "Visual*", "Directional acceleration / gravity field (`Strength`, `Direction`)."), | ||
| 122 | ToolMeta("pTurbulence", "Particles", "Unit tests", "Visual*", "Seeded 3D turbulent noise force field (`XStrength`, `YStrength`, `Density`)."), | ||
| 123 | ToolMeta("pDrag", "Particles", "Unit tests", "Visual*", "Velocity damping / aerodynamic drag force.", aliases=("pFriction",)), | ||
| 124 | ToolMeta("pKill", "Particles", "Unit tests", "Visual*", "Region-based particle termination (`Inside`/`Outside`/`Entering`/`Leaving`)."), | ||
| 125 | ToolMeta("pMerge", "Particles", "Unit tests", "Visual*", "Combines multiple upstream particle emitter streams."), | ||
| 126 | |||
| 115 | # 3D Pipeline | 127 | # 3D Pipeline |
| 116 | ToolMeta("Renderer3D", "3D Pipeline", "`cam3d`, `cam3d_fov`", "0.1%–0.4%", "GPU wgpu 3D rasterizer with depth buffer, perspective camera selection, lighting, and 2D texture sampling."), | 128 | ToolMeta("Renderer3D", "3D Pipeline", "`cam3d`, `cam3d_fov`", "0.1%–0.4%", "GPU wgpu 3D rasterizer with depth buffer, perspective camera selection, lighting, and 2D texture sampling."), |
| 117 | ToolMeta("Camera3D", "3D Pipeline", "`cam3d`, `cam3d_fov`", "0.1%–0.4%", "All 6 `RotOrder` permutations (`XYZ`..`ZYX`), `AoV`/`FLength`, `ApertureW`/`ApertureH`, `ResolutionGateFit` (`Inside`/`Outside`/`Width`/`Height`/`Stretch`)."), | 129 | ToolMeta("Camera3D", "3D Pipeline", "`cam3d`, `cam3d_fov`", "0.1%–0.4%", "All 6 `RotOrder` permutations (`XYZ`..`ZYX`), `AoV`/`FLength`, `ApertureW`/`ApertureH`, `ResolutionGateFit` (`Inside`/`Outside`/`Width`/`Height`/`Stretch`)."), |
| ... | @@ -123,8 +135,9 @@ TOOL_METADATA: Sequence[ToolMeta] = ( | ... | @@ -123,8 +135,9 @@ TOOL_METADATA: Sequence[ToolMeta] = ( |
| 123 | ToolMeta("LightDirectional", "3D Pipeline", "Suite comps", "0.1%–0.4%", "World-oriented directional light (`-Z` emission axis) with RGB intensity in `Renderer3D`."), | 135 | ToolMeta("LightDirectional", "3D Pipeline", "Suite comps", "0.1%–0.4%", "World-oriented directional light (`-Z` emission axis) with RGB intensity in `Renderer3D`."), |
| 124 | 136 | ||
| 125 | # Time, Routing & Utility | 137 | # Time, Routing & Utility |
| 126 | ToolMeta("Saver", "Time, Routing & Utility", "All suites", "0.0%", "Output sink / passthrough in interactive Flow; target selector for `render-check` CLI."), | 138 | ToolMeta("Saver", "Time, Routing & Utility", "All suites", "0.0%", "Output sink / passthrough in interactive Flow; Saver-driven pipelined PNG sequence export (`render-check --export` and `Cmd+Shift+R`)."), |
| 127 | ToolMeta("TimeStretcher", "Time, Routing & Utility", "Suite comps", "0.0%", "Keyframed/expression `SourceTime` remapping upstream of evaluation (nearest/frame evaluation; Optical Flow tracked in [#4](" + SHALE_ISSUES_URL + "/4))."), | 139 | ToolMeta("Dimension.OpticalFlow", "Time, Routing & Utility", "Unit tests", "0.1%", "GPU 4-level pyramid coarse-to-fine bidirectional dense optical flow feeding downstream `TimeStretcher` flow interpolation.", aliases=("OpticalFlow",)), |
| 140 | ToolMeta("TimeStretcher", "Time, Routing & Utility", "Suite comps", "0.0%–0.2%", "Keyframed/expression `SourceTime` remapping with `Nearest` (`0`), `Blend` (`1`), and GPU `OpticalFlow` (`2`) bidirectional warped interpolation."), | ||
| 128 | ToolMeta("TimeSpeed", "Time, Routing & Utility", "Suite comps", "0.0%", "Constant/animated `Speed` and `Delay` time remapping."), | 141 | ToolMeta("TimeSpeed", "Time, Routing & Utility", "Suite comps", "0.0%", "Constant/animated `Speed` and `Delay` time remapping."), |
| 129 | ToolMeta("Switch", "Time, Routing & Utility", "Suite comps", "0.0%", "Dynamic input routing by `Which` index (`Input1`..`InputN`)."), | 142 | ToolMeta("Switch", "Time, Routing & Utility", "Suite comps", "0.0%", "Dynamic input routing by `Which` index (`Input1`..`InputN`)."), |
| 130 | ToolMeta("Fuse.Switch", "Time, Routing & Utility", "Suite comps", "0.0%", "Fuse variant of `Switch` routing `Input1`..`InputN` by `Which`."), | 143 | ToolMeta("Fuse.Switch", "Time, Routing & Utility", "Suite comps", "0.0%", "Fuse variant of `Switch` routing `Input1`..`InputN` by `Which`."), |
| ... | @@ -170,12 +183,7 @@ UNSUPPORTED_NOTES: Sequence[UnsupportedMeta] = ( | ... | @@ -170,12 +183,7 @@ UNSUPPORTED_NOTES: Sequence[UnsupportedMeta] = ( |
| 170 | UnsupportedMeta("SurfaceTracker", "Preserved lossless on save; passes through main image input in Flow.", 7), | 183 | UnsupportedMeta("SurfaceTracker", "Preserved lossless on save; passes through main image input in Flow.", 7), |
| 171 | UnsupportedMeta("MagicMask", "Preserved lossless on save; passes through main image input in Flow.", 7), | 184 | UnsupportedMeta("MagicMask", "Preserved lossless on save; passes through main image input in Flow.", 7), |
| 172 | UnsupportedMeta("PlanarTracker", "Preserved lossless on save; passes through main image input in Flow.", 7), | 185 | UnsupportedMeta("PlanarTracker", "Preserved lossless on save; passes through main image input in Flow.", 7), |
| 173 | UnsupportedMeta("Fuse.Cryptomatte", "Preserved lossless on save; passes through main image input (multi-channel EXR matte extraction tracked).", 2), | 186 | UnsupportedMeta("Dimension.CopyAux", "Preserved lossless on save; passes through main image input.", None), |
| 174 | UnsupportedMeta("Dimension.OpticalFlow", "Preserved lossless on save; passes through main image input (GPU dense optical flow tracked).", 4), | ||
| 175 | UnsupportedMeta("Dimension.CopyAux", "Preserved lossless on save; passes through main image input.", 4), | ||
| 176 | UnsupportedMeta("pEmitter", "Preserved lossless on save; skipped in 3D scene until particle simulator lands.", 3), | ||
| 177 | UnsupportedMeta("pRender", "Preserved lossless on save; skipped / passthrough until particle simulator lands.", 3), | ||
| 178 | UnsupportedMeta("pPointForce", "Preserved lossless on save; skipped in 3D scene until particle simulator lands.", 3), | ||
| 179 | UnsupportedMeta("SurfaceFBXMesh", "Preserved lossless on save; FBX mesh geometry not yet imported in `Renderer3D`.", None), | 187 | UnsupportedMeta("SurfaceFBXMesh", "Preserved lossless on save; FBX mesh geometry not yet imported in `Renderer3D`.", None), |
| 180 | UnsupportedMeta("Text3D", "Preserved lossless on save; extruded 3D text mesh not yet implemented in `Renderer3D`.", None), | 188 | UnsupportedMeta("Text3D", "Preserved lossless on save; extruded 3D text mesh not yet implemented in `Renderer3D`.", None), |
| 181 | UnsupportedMeta("MtlBlinn", "Preserved lossless on save; basic diffuse color & texture resolved in `Renderer3D` (full Blinn specular/bump pending).", None), | 189 | UnsupportedMeta("MtlBlinn", "Preserved lossless on save; basic diffuse color & texture resolved in `Renderer3D` (full Blinn specular/bump pending).", None), |
| ... | @@ -195,17 +203,15 @@ def parse_eval_rs(path: Path) -> Set[str]: | ... | @@ -195,17 +203,15 @@ def parse_eval_rs(path: Path) -> Set[str]: |
| 195 | raise RuntimeError(f"Could not locate eval_node_inner in {path}") | 203 | raise RuntimeError(f"Could not locate eval_node_inner in {path}") |
| 196 | body = m.group(0) | 204 | body = m.group(0) |
| 197 | tools: Set[str] = set() | 205 | tools: Set[str] = set() |
| 198 | for mm in re.finditer(r"matches!\(node\.kind\.as_str\(\),\s*([^)]+)\)", body): | 206 | for mm in re.finditer(r"matches!\(\s*node\.kind\.as_str\(\),\s*([^)]+)\)", body, re.S): |
| 199 | tools.update(re.findall(r'"([^"]+)"', mm.group(1))) | 207 | tools.update(re.findall(r'"([^"]+)"', mm.group(1))) |
| 200 | for mm in re.finditer(r'node\.kind\s*==\s*"([^"]+)"', body): | 208 | for mm in re.finditer(r'node\.kind\s*==\s*"([^"]+)"', body): |
| 201 | tools.add(mm.group(1)) | 209 | tools.add(mm.group(1)) |
| 202 | mm = re.search(r"match node\.kind\.as_str\(\)\s*\{(.*?)\n\s*other =>", body, re.S) | 210 | mm = re.search(r"match node\.kind\.as_str\(\)\s*\{(.*?)\n\s*other =>", body, re.S) |
| 203 | if not mm: | 211 | if not mm: |
| 204 | raise RuntimeError(f"Could not locate main match in eval_node_inner in {path}") | 212 | raise RuntimeError(f"Could not locate main match in eval_node_inner in {path}") |
| 205 | for line in mm.group(1).splitlines(): | 213 | for arm in re.finditer(r'((?:"[^"]+"\s*(?:\|\s*)?)+)=>', mm.group(1), re.S): |
| 206 | if "=>" in line and not line.strip().startswith("//"): | 214 | tools.update(re.findall(r'"([^"]+)"', arm.group(1))) |
| 207 | lhs = line.split("=>", 1)[0] | ||
| 208 | tools.update(re.findall(r'"([^"]+)"', lhs)) | ||
| 209 | return tools | 215 | return tools |
| 210 | 216 | ||
| 211 | 217 | ||
| ... | @@ -332,10 +338,13 @@ def build_markdown( | ... | @@ -332,10 +338,13 @@ def build_markdown( |
| 332 | 338 | ||
| 333 | live_engine_tools = eval_tools | scene3d_tools | 339 | live_engine_tools = eval_tools | scene3d_tools |
| 334 | meta_by_name: Dict[str, ToolMeta] = {m.name: m for m in TOOL_METADATA} | 340 | meta_by_name: Dict[str, ToolMeta] = {m.name: m for m in TOOL_METADATA} |
| 341 | meta_all_names: Set[str] = set(meta_by_name.keys()) | ||
| 342 | for m in TOOL_METADATA: | ||
| 343 | meta_all_names.update(m.aliases) | ||
| 335 | non_render_tools = {"Note", "Underlay"} | 344 | non_render_tools = {"Note", "Underlay"} |
| 336 | 345 | ||
| 337 | # Detect drift: tools in eval.rs / scene3d.rs not in TOOL_METADATA | 346 | # Detect drift: tools in eval.rs / scene3d.rs not in TOOL_METADATA |
| 338 | uncategorized = sorted(live_engine_tools - set(meta_by_name.keys())) | 347 | uncategorized = sorted(live_engine_tools - meta_all_names) |
| 339 | for name in uncategorized: | 348 | for name in uncategorized: |
| 340 | warnings.append(f"Uncategorized tool found in engine source: {name}") | 349 | warnings.append(f"Uncategorized tool found in engine source: {name}") |
| 341 | 350 |