| 1 | #!/usr/bin/env python3 |
| 2 | """Generic per-node fuzzer: Fusion 21.1 (`sg render`) vs Fission (`render-check`), driven by tool_catalog.json. |
| 3 | |
| 4 | For one tool, builds a multi-frame comp where frame 0 uses every default and frames 1..N-1 each |
| 5 | instantiate the tool with a deterministic stratified variation of its catalog inputs; a Switch picks |
| 6 | instance `f` at frame `f`. Scores `accuracy = max(0, 100 - mae_pct)` per frame into accuracy_ledger.json. |
| 7 | |
| 8 | python3 scripts/fuzz_node.py --tool Blur --frames 12 |
| 9 | python3 scripts/fuzz_node.py --category "Color & Depth" |
| 10 | python3 scripts/fuzz_node.py --all |
| 11 | """ |
| 12 | |
| 13 | from __future__ import annotations |
| 14 | |
| 15 | import argparse |
| 16 | import hashlib |
| 17 | import json |
| 18 | import os |
| 19 | import random |
| 20 | import re |
| 21 | import subprocess |
| 22 | import sys |
| 23 | import time |
| 24 | from datetime import datetime, timezone |
| 25 | from pathlib import Path |
| 26 | from typing import Any, Dict, List, Optional, Sequence, Tuple |
| 27 | |
| 28 | SCRIPTS = Path(__file__).resolve().parent |
| 29 | sys.path.insert(0, str(SCRIPTS)) |
| 30 | |
| 31 | import diff_fuzz.assets as assets # noqa: E402 |
| 32 | from diff_fuzz.assets import CONTAINER_ROOT, generate_assets, linear_spline, make_comp, make_loader, make_saver, step_spline # noqa: E402 |
| 33 | from diff_fuzz.runner import alpha_mae_pct, run_comp_both # noqa: E402 |
| 34 | from gen_compatibility import TOOL_METADATA # noqa: E402 |
| 35 | |
| 36 | CATALOG = SCRIPTS / "tool_catalog.json" |
| 37 | LEDGER = SCRIPTS / "accuracy_ledger.json" |
| 38 | PREBUILT_RENDER_CHECK = Path(os.environ.get("FISSION_RENDER_CHECK", "/Users/clo/dev/compositor/target/release/render-check")) |
| 39 | if PREBUILT_RENDER_CHECK.exists(): |
| 40 | assets.RENDER_CHECK = PREBUILT_RENDER_CHECK |
| 41 | |
| 42 | SIZE = 256 |
| 43 | FRAME_TIMEOUT = 20 |
| 44 | GOLDEN = 0.6180339887498949 |
| 45 | |
| 46 | |
| 47 | class FuID(str): |
| 48 | pass |
| 49 | |
| 50 | |
| 51 | # Tools the generic wiring cannot drive yet, with the reason recorded in the ledger. |
| 52 | UNSUPPORTED_RIG = { |
| 53 | "Loader": "needs a footage clip; every probe already exercises it", |
| 54 | "Saver": "output node; every probe already exercises it", |
| 55 | "Switch": "routing node; used by the fuzzer itself", |
| 56 | "Fuse.Switch": "routing node; used by the fuzzer itself", |
| 57 | "MacroOperator": "container node with no inputs of its own", |
| 58 | "GroupOperator": "container node with no inputs of its own", |
| 59 | "Tracker": "needs tracked footage", |
| 60 | "Fuse.Cryptomatte": "needs cryptomatte object-ID metadata", |
| 61 | "Dimension.OpticalFlow": "needs auxiliary vector channels", |
| 62 | "Dimension.CopyAux": "needs auxiliary channels", |
| 63 | "Paint": "needs painted strokes", |
| 64 | "PolylineStroke": "needs painted strokes", |
| 65 | "Multistroke": "needs painted strokes", |
| 66 | "PaintMask": "needs painted strokes", |
| 67 | "SurfaceFBXMesh": "needs a mesh file", |
| 68 | "GridWarp": "needs mesh-point data", |
| 69 | } |
| 70 | UNRIGGED_DOMAINS = ("DataType3D", "MtlGraph3D", "Particles") |
| 71 | RIGS = { |
| 72 | "scene": { |
| 73 | "Bender3D", "Camera3D", "Cube3D", "Displace3D", "Duplicate3D", "ImagePlane3D", "LightAmbient", "LightDirectional", "LightPoint", |
| 74 | "LightSpot", "Merge3D", "Override3D", "Renderer3D", "ReplaceMaterial3D", "ReplaceNormals3D", "Replicate3D", "Shape3D", "Text3D", "Transform3D", |
| 75 | }, |
| 76 | "material": { |
| 77 | "MtlBlinn", "MtlPhong", "MtlCookTorrance", "MtlWard", "MtlReflect", "MtlChanBool", "SphereMap", |
| 78 | "BumpMap", "Texture2DOperator", "TextureTransformOperator", |
| 79 | }, |
| 80 | "particle": { |
| 81 | "pEmitter", "pRender", "pMerge", "pDirectionalForce", "pDrag", "pTurbulence", "pPointForce", "pBounce", "pKill", |
| 82 | "pVortex", "pFlock", "pSpawn", "pChangeStyle", "pGradientForce", |
| 83 | "pAvoid", "pCustom", "pCustomForce", "pFollow", "pImageEmitter", "pTangentForce", |
| 84 | }, |
| 85 | "time": {"TimeSpeed", "TimeStretcher"}, |
| 86 | } |
| 87 | |
| 88 | SLIDER_CONTROLS = { |
| 89 | "SliderControl", "ScrewControl", "RangeControl", "ColorControl", "LevelsControl", "LevelsOutputControl", |
| 90 | "ColorWheelControl", "ColorSuppressionControl", None, |
| 91 | } |
| 92 | CHOICE_CONTROLS = {"CheckboxControl", "MultiButtonControl", "MultiButtonIDControl", "ComboControl", "ComboIDControl"} |
| 93 | # Inputs whose variation tests plumbing the engine intentionally lacks, that resize the frame, or that need |
| 94 | # data the rigs lack (Renderer3D deep output, Displace3D camera, TimeSpeed/TimeStretcher optical flow: Fusion fails the frame). |
| 95 | DENY_IDS = { |
| 96 | "MotionBlur", "ShutterAngle", "CenterBias", "SampleSpread", "UseGPU", "HideInputs", "HiQOnly", |
| 97 | "Width", "Height", "PixelAspect", "Depth", "UseFrameFormatSettings", "AutoResolution", "ProcessMode", |
| 98 | "UseObject", "UseMaterial", "ObjectID", "MaterialID", "CorrectEdges", "ProxyScale", "MaskWidth", "MaskHeight", |
| 99 | "RendererType", "OutputType", "PointCamera", "InterpolateBetweenFrames", |
| 100 | } |
| 101 | # TimeSpeed fails the frame in Fusion once a reversed Speed reaches ~-24 frames of source time. |
| 102 | INPUT_RANGES = {("TimeSpeed", "Speed"): (-2.0, 3.0)} |
| 103 | DENY_PREFIXES = ("Gamut.", "ProcessLayers", "Comments", "Layer", "Motion", "Reset", "Stereo", "EnableWarp.") |
| 104 | DENY_SUFFIXES = ("_LayerSelect", "Nest", "Notify") |
| 105 | MASK_IDS = ("ApplyMaskInverted", "MultiplyByMask", "FitMask", "MaskChannel", "MaskLow", "MaskHigh", "MaskClipBlack", "MaskClipWhite") |
| 106 | IMAGE_INPUT_IDS = ("Input", "Background", "Foreground", "Image", "Source", "Image1", "Image2", "Image3", "BlurImage") |
| 107 | # Renderer3D pinned to OpenGL: the catalog only lists RendererSoftware.* inputs, whose lighting toggles are remapped in `rig_frame`. |
| 108 | RENDERER3D = { |
| 109 | "Width": SIZE, "Height": SIZE, "RendererType": FuID("RendererOpenGL"), |
| 110 | "RendererOpenGL.LightingEnabled": 1, "RendererOpenGL.ShadowsEnabled": 1, |
| 111 | } |
| 112 | EMITTER = {"RandomSeed": 42, "Style": FuID("ParticleStyleBlob"), "Number": 20, "Velocity": 0.05} |
| 113 | PRENDER = {"OutputMode": FuID("TwoD"), "Width": SIZE, "Height": SIZE} |
| 114 | TOOL_OVERRIDES: Dict[str, Dict[str, Any]] = { |
| 115 | "TextPlus": {"StyledText": "Fission", "Size": 0.12}, |
| 116 | "Text3D": {"StyledText": "FISSION", "Font": "Open Sans", "Size": 0.25}, |
| 117 | "Renderer3D": RENDERER3D, |
| 118 | "Camera3D": {"Transform3DOp.Translate.Z": 3.0}, |
| 119 | "LightPoint": {"Transform3DOp.Translate.X": 1.2, "Transform3DOp.Translate.Y": 2.0, "Transform3DOp.Translate.Z": 2.0}, |
| 120 | "LightSpot": {"Transform3DOp.Translate.Y": 2.0, "Transform3DOp.Translate.Z": 3.0, "Transform3DOp.Rotate.X": -35.0}, |
| 121 | "LightDirectional": {"Transform3DOp.Rotate.X": -40.0, "Transform3DOp.Rotate.Y": 25.0}, |
| 122 | "pEmitter": EMITTER, |
| 123 | "pRender": PRENDER, |
| 124 | } |
| 125 | # Image-slot a texture plugs into on tools that otherwise render untextured. |
| 126 | TEXTURE_SLOT = {"Shape3D": "MaterialInput", "ImagePlane3D": "MaterialInput", "Cube3D": "FrontMaterialInput"} |
| 127 | |
| 128 | |
| 129 | def lua_key(name: str) -> str: |
| 130 | return name if re.fullmatch(r"[A-Za-z_]\w*", name) else f'["{name}"]' |
| 131 | |
| 132 | |
| 133 | def lua_val(v: Any) -> str: |
| 134 | if isinstance(v, FuID): |
| 135 | return f'FuID {{ "{v}" }}' |
| 136 | if isinstance(v, str): |
| 137 | return json.dumps(v) |
| 138 | if isinstance(v, (list, tuple)): |
| 139 | return "{ " + ", ".join(lua_val(x) for x in v) + " }" |
| 140 | if isinstance(v, bool): |
| 141 | return "1" if v else "0" |
| 142 | if isinstance(v, float): |
| 143 | return repr(round(v, 6)) |
| 144 | return str(v) |
| 145 | |
| 146 | |
| 147 | def op_block(name: str, kind: str, inputs: Dict[str, Any], links: Dict[str, Tuple[str, str]]) -> str: |
| 148 | rows = [f"\t\t\t\t{lua_key(k)} = Input {{ Value = {lua_val(v)}, }}," for k, v in inputs.items()] |
| 149 | rows += [f'\t\t\t\t{lua_key(k)} = Input {{ SourceOp = "{op}", Source = "{src}", }},' for k, (op, src) in links.items()] |
| 150 | return f"\t\t{name} = {kind} {{\n\t\t\tInputs = {{\n" + "\n".join(rows) + "\n\t\t\t},\n\t\t}," |
| 151 | |
| 152 | |
| 153 | def unit(tool: str, input_id: str, k: int) -> float: |
| 154 | """Deterministic low-discrepancy sample in [0.04, 0.96] per (tool, input, frame).""" |
| 155 | phase = int.from_bytes(hashlib.sha256(f"{tool}/{input_id}".encode()).digest()[:4], "big") / 2**32 |
| 156 | return 0.04 + 0.92 * ((phase + k * GOLDEN) % 1.0) |
| 157 | |
| 158 | |
| 159 | def switch_tree(leaves: List[str]) -> Tuple[str, List[str], List[str]]: |
| 160 | """Binary tree of 2-input Switches: frame f descends via bit L of f. Fusion's Switch only exposes Input0/Input1 from a .comp.""" |
| 161 | nodes: List[str] = [] |
| 162 | splines: List[str] = [] |
| 163 | level, layer = 0, leaves |
| 164 | while len(layer) > 1: |
| 165 | sel = f"SwSel{level}" |
| 166 | splines.append(step_spline(sel, {f: float((f >> level) & 1) for f in range(len(leaves))})) |
| 167 | nxt: List[str] = [] |
| 168 | for j in range(0, len(layer), 2): |
| 169 | if j + 1 == len(layer): |
| 170 | nxt.append(layer[j]) |
| 171 | continue |
| 172 | name = f"Sw{level}_{j // 2}" |
| 173 | nodes.append(op_block(name, "Switch", {}, { |
| 174 | "Source": (sel, "Value"), "Input0": (layer[j], "Output"), "Input1": (layer[j + 1], "Output"), |
| 175 | })) |
| 176 | nxt.append(name) |
| 177 | layer, level = nxt, level + 1 |
| 178 | return layer[0], nodes, splines |
| 179 | |
| 180 | |
| 181 | class Fuzzer: |
| 182 | def __init__(self, tool: str, catalog: Dict[str, Any], frames: int): |
| 183 | self.tool = tool |
| 184 | self.spec = catalog["tools"][tool] |
| 185 | self.kind = self.spec["reg_id"] |
| 186 | self.frames = frames |
| 187 | self.inputs: Dict[str, Dict[str, Any]] = {i["id"]: i for i in self.spec["inputs"]} |
| 188 | self.in_types = {i["data_type"] for i in self.spec["inputs"] if i.get("data_type") in ("Image", "Mask", "ShapeTree", "DataType3D", "MtlGraph3D", "Particles")} |
| 189 | self.out_type = self.spec["outputs"][0].get("data_type") if self.spec["outputs"] else None |
| 190 | self.out_id = self.spec["outputs"][0]["id"] if self.spec["outputs"] else "Output" |
| 191 | self.wired_images = [i for i in IMAGE_INPUT_IDS if self.inputs.get(i, {}).get("data_type") == "Image"] |
| 192 | self.shape_inputs = [i["id"] for i in self.spec["inputs"] if i.get("data_type") == "ShapeTree"] |
| 193 | self.rig = next((r for r, tools_ in RIGS.items() if tool in tools_), None) |
| 194 | |
| 195 | def skip_reason(self) -> Optional[str]: |
| 196 | if self.tool in UNSUPPORTED_RIG: |
| 197 | return UNSUPPORTED_RIG[self.tool] |
| 198 | if self.rig is None and any(d in {self.out_type, *self.in_types} for d in UNRIGGED_DOMAINS): |
| 199 | return "no 3D/material/particle rig for this tool" |
| 200 | return None |
| 201 | |
| 202 | # ---- variation sampling ------------------------------------------------------------- |
| 203 | |
| 204 | def eligible(self, i: Dict[str, Any]) -> bool: |
| 205 | iid, dt, ic = i["id"], i.get("data_type"), i.get("input_control") |
| 206 | if iid in DENY_IDS or iid in MASK_IDS or iid == "Blend" or iid.startswith(DENY_PREFIXES) or iid.endswith(DENY_SUFFIXES): |
| 207 | return False |
| 208 | if "MotionBlur" in self.inputs and iid == "Quality": |
| 209 | return False |
| 210 | if dt == "Point" and ic == "OffsetControl": |
| 211 | return i.get("default") is not None |
| 212 | if dt == "FuID": |
| 213 | return ic in CHOICE_CONTROLS and bool(i.get("combo_entries")) |
| 214 | if dt != "Number": |
| 215 | return False |
| 216 | if ic in CHOICE_CONTROLS: |
| 217 | return True |
| 218 | return ic in SLIDER_CONTROLS and i.get("max_scale", 0) > i.get("min_scale", 0) |
| 219 | |
| 220 | def sample(self, i: Dict[str, Any], k: int) -> Any: |
| 221 | u = unit(self.tool, i["id"], k) |
| 222 | dt, ic, entries = i.get("data_type"), i.get("input_control"), i.get("combo_entries") |
| 223 | default = i.get("default") |
| 224 | if dt == "Point": |
| 225 | return [round(c + (unit(self.tool, f"{i['id']}/{axis}", k) - 0.5) * 0.6, 4) for axis, c in enumerate(default[:2])] |
| 226 | if dt == "FuID": |
| 227 | return FuID(entries[min(len(entries) - 1, int(u * len(entries)))]) |
| 228 | if ic == "CheckboxControl" or (ic == "MultiButtonControl" and (not entries or len(entries) == 1)): |
| 229 | return 1 - int(bool(default)) |
| 230 | if ic in ("ComboControl", "MultiButtonControl"): |
| 231 | n = len(entries) |
| 232 | alt = [x for x in range(n) if x != default] |
| 233 | return alt[int(u * len(alt)) % len(alt)] if alt else default |
| 234 | lo = max(i["min_scale"], i.get("min_allowed", -1e6)) |
| 235 | hi = min(i["max_scale"], i.get("max_allowed", 1e6)) |
| 236 | lo, hi = INPUT_RANGES.get((self.tool, i["id"]), (lo, hi)) |
| 237 | v = lo + u * (hi - lo) |
| 238 | return int(round(v)) if i.get("integer") else round(v, 5) |
| 239 | |
| 240 | def plan(self) -> List[Tuple[str, Dict[str, Any], bool]]: |
| 241 | """(label, overrides, wire_mask) per frame; frame 0 is pure defaults.""" |
| 242 | pool = [i for i in self.spec["inputs"] if self.eligible(i)] |
| 243 | random.Random(self.tool).shuffle(pool) |
| 244 | has_mask = "EffectMask" in self.inputs |
| 245 | plan: List[Tuple[str, Dict[str, Any], bool]] = [("defaults", {}, False)] |
| 246 | cursor = 0 |
| 247 | for k in range(1, self.frames): |
| 248 | ov: Dict[str, Any] = {} |
| 249 | wire = False |
| 250 | if k == 1 and "Blend" in self.inputs: |
| 251 | ov["Blend"] = round(0.15 + 0.7 * unit(self.tool, "Blend", k), 4) |
| 252 | elif k == 2 and has_mask: |
| 253 | wire = True |
| 254 | for mid in MASK_IDS: |
| 255 | mi = self.inputs.get(mid) |
| 256 | if mi and self.eligible_mask(mi): |
| 257 | ov[mid] = self.sample(mi, k) if mid != "MultiplyByMask" else 1 |
| 258 | if k == self.frames - 1 and k > 3: |
| 259 | chosen = pool[:10] |
| 260 | else: |
| 261 | m = 1 + (k % 3) |
| 262 | chosen = [pool[(cursor + j) % len(pool)] for j in range(m)] if pool else [] |
| 263 | cursor += m |
| 264 | for i in chosen: |
| 265 | ov[i["id"]] = self.sample(i, k) |
| 266 | label = ", ".join(f"{a}={b}" for a, b in ov.items()) or "defaults" |
| 267 | plan.append((("mask: " if wire else "") + label, ov, wire)) |
| 268 | return plan |
| 269 | |
| 270 | def eligible_mask(self, i: Dict[str, Any]) -> bool: |
| 271 | return i.get("data_type") in ("Number", "FuID") and i.get("input_control") in (CHOICE_CONTROLS | SLIDER_CONTROLS) |
| 272 | |
| 273 | # ---- comp construction --------------------------------------------------------------- |
| 274 | |
| 275 | def fixed_inputs(self) -> Dict[str, Any]: |
| 276 | fixed: Dict[str, Any] = dict(TOOL_OVERRIDES.get(self.tool, {})) |
| 277 | if not self.wired_images: |
| 278 | for dim in ("Width", "Height", "MaskWidth", "MaskHeight"): |
| 279 | if dim in self.inputs: |
| 280 | fixed[dim] = SIZE |
| 281 | return fixed |
| 282 | |
| 283 | def rig_shared(self) -> List[str]: |
| 284 | """Nodes every frame's rig reuses: a lit textured sphere scene, and the animated plate for the time rig.""" |
| 285 | a = ("PlateA", "Output") |
| 286 | sphere = {"Shape": FuID("SurfaceSphereInputs")} |
| 287 | t3 = lambda x=0.0, y=0.0, z=0.0: {"Transform3DOp.Translate.X": x, "Transform3DOp.Translate.Y": y, "Transform3DOp.Translate.Z": z} |
| 288 | if self.rig == "time": |
| 289 | return [ |
| 290 | linear_spline("TimeA", {0: 0.0, 48: 1.0}), |
| 291 | linear_spline("TimeB", {0: 1.0, 48: 0.0}), |
| 292 | op_block("TimeBG", "Background", { |
| 293 | "Width": SIZE, "Height": SIZE, "Type": FuID("Horizontal"), "TopLeftBlue": 0.2, "TopRightBlue": 0.2, |
| 294 | "TopLeftAlpha": 1, "TopRightAlpha": 1, |
| 295 | }, { |
| 296 | "TopLeftRed": ("TimeA", "Value"), "TopLeftGreen": ("TimeB", "Value"), |
| 297 | "TopRightRed": ("TimeB", "Value"), "TopRightGreen": ("TimeA", "Value"), |
| 298 | }), |
| 299 | ] |
| 300 | if self.rig not in ("scene", "material"): |
| 301 | return [] |
| 302 | return [ |
| 303 | op_block("Cam", "Camera3D", {"Transform3DOp.Translate.Z": 3.0}, {}), |
| 304 | op_block("Pt", "LightPoint", t3(1.5, 1.5, 3.0), {}), |
| 305 | op_block("Amb", "LightAmbient", {"Intensity": 0.25}, {}), |
| 306 | op_block("BaseDir", "LightDirectional", {"Intensity": 0.4, "Transform3DOp.Rotate.X": -30.0, "Transform3DOp.Rotate.Y": 20.0}, {}), |
| 307 | op_block("Sph", "Shape3D", sphere, {"MaterialInput": a}), |
| 308 | op_block("SphL", "Shape3D", {**sphere, "SurfaceSphereInputs.Radius": 0.5, **t3(-0.7)}, {"MaterialInput": a}), |
| 309 | op_block("BoxR", "Shape3D", {"Shape": FuID("SurfaceCubeInputs"), "SurfaceCubeInputs.Size": 0.8, **t3(0.8)}, {"MaterialInput": ("PlateB", "Output")}), |
| 310 | op_block("WSph", "Shape3D", {**sphere, "SurfaceSphereInputs.Radius": 0.5}, {}), |
| 311 | op_block("Wall", "Shape3D", {"Shape": FuID("SurfacePlaneInputs"), "SurfacePlaneInputs.Width": 6.0, "SurfacePlaneInputs.Height": 6.0, **t3(z=-0.8)}, {}), |
| 312 | op_block("Noise", "FastNoise", {"Width": SIZE, "Height": SIZE}, {}), |
| 313 | op_block("RedMtl", "MtlBlinn", {"Diffuse.Color.Red": 0.9, "Diffuse.Color.Green": 0.15, "Diffuse.Color.Blue": 0.1}, {}), |
| 314 | op_block("BaseTex", "Texture2DOperator", {}, {"Input": a}), |
| 315 | ] |
| 316 | |
| 317 | def rig_frame(self, f: int, name: str, inputs: Dict[str, Any], links: Dict[str, Tuple[str, str]]) -> Tuple[List[str], str]: |
| 318 | """Harness for one variation: tool `name` placed in its rig; returns (nodes, op feeding the Switch tree).""" |
| 319 | t, a = self.tool, ("PlateA", "Output") |
| 320 | if self.rig == "time": |
| 321 | links.update({i: ("TimeBG", "Output") for i in self.wired_images}) |
| 322 | return [op_block(name, self.kind, inputs, links)], name |
| 323 | if self.rig == "particle": |
| 324 | emitter = (f"E{f}", "Output") |
| 325 | nodes = [] if t == "pEmitter" else [op_block(emitter[0], "pEmitter", EMITTER, {})] |
| 326 | if t == "pMerge": |
| 327 | nodes.append(op_block(f"E2_{f}", "pEmitter", {**EMITTER, "RandomSeed": 7, "SphereRgn.Translate.X": 0.3}, {})) |
| 328 | links.update({"Particles1": emitter, "Particles2": (f"E2_{f}", "Output")}) |
| 329 | elif t != "pEmitter": |
| 330 | links["Input"] = emitter |
| 331 | if t == "pGradientForce" and "Bitmap" in self.inputs: |
| 332 | links["Bitmap"] = ("Noise", "Output") |
| 333 | nodes.append(op_block(name, self.kind, inputs, links)) |
| 334 | if t == "pRender": |
| 335 | return nodes, name |
| 336 | return nodes + [op_block(f"R{f}", "pRender", PRENDER, {"Input": (name, self.out_id)})], f"R{f}" |
| 337 | |
| 338 | tool_out = (name, self.out_id) |
| 339 | lit = ["Sph", "Pt", "Amb", "Cam"] |
| 340 | if self.rig == "material": |
| 341 | nodes, mtl = [], (name, "MaterialOutput") |
| 342 | if t in ("MtlBlinn", "MtlPhong", "MtlCookTorrance", "MtlWard"): |
| 343 | links["Diffuse.Color.Material"] = a |
| 344 | elif t == "MtlReflect": |
| 345 | links["BackgroundMaterial"] = ("RedMtl", "MaterialOutput") |
| 346 | links["Reflection.Color.Material"] = a |
| 347 | elif t == "MtlChanBool": |
| 348 | links["Background"] = ("RedMtl", "MaterialOutput") |
| 349 | elif t == "SphereMap": |
| 350 | links["Image"] = a |
| 351 | elif t == "BumpMap": |
| 352 | links["Input"] = ("Noise", "Output") |
| 353 | nodes.append(op_block(f"Bm{f}", "MtlBlinn", {}, {"Diffuse.Color.Material": a, "Bumpmap.Material": mtl})) |
| 354 | mtl = (f"Bm{f}", "MaterialOutput") |
| 355 | elif t == "TextureTransformOperator": |
| 356 | links["MaterialInput"] = ("BaseTex", "MaterialOutput") |
| 357 | nodes += [op_block(name, self.kind, inputs, links), op_block(f"S{f}", "Shape3D", {"Shape": FuID("SurfaceSphereInputs")}, {"MaterialInput": mtl})] |
| 358 | scene = [(f"S{f}", "Output")] + [(n, "Output") for n in lit[1:]] |
| 359 | else: |
| 360 | scene = [(n, "Output") for n in lit] |
| 361 | if t in ("Shape3D", "Cube3D", "ImagePlane3D", "Text3D"): |
| 362 | if t in TEXTURE_SLOT: |
| 363 | links[TEXTURE_SLOT[t]] = a |
| 364 | scene[0] = tool_out |
| 365 | elif t in ("LightAmbient", "LightDirectional", "LightPoint", "LightSpot"): |
| 366 | scene = [(n, "Output") for n in ("WSph", "Wall", "Cam")] + [tool_out] |
| 367 | if t == "LightAmbient": |
| 368 | scene.append(("BaseDir", "Output")) |
| 369 | elif t == "Camera3D": |
| 370 | scene[3] = tool_out |
| 371 | elif t == "Merge3D": |
| 372 | links.update({"SceneInput1": ("SphL", "Output"), "SceneInput2": ("BoxR", "Output")}) |
| 373 | scene[0] = tool_out |
| 374 | elif t == "Replicate3D": |
| 375 | links.update({"Destination": ("BoxR", "Output"), "Input1": ("SphL", "Output")}) |
| 376 | scene[0] = tool_out |
| 377 | elif t == "Renderer3D": |
| 378 | inputs = {k.replace("RendererSoftware.", "RendererOpenGL.") if k.endswith(("LightingEnabled", "ShadowsEnabled")) else k: v for k, v in inputs.items()} |
| 379 | links["SceneInput"] = (f"M{f}", "Output") |
| 380 | else: |
| 381 | links["SceneInput"] = ("Sph", "Output") |
| 382 | if t == "Displace3D": |
| 383 | links["Input"] = ("Noise", "Output") |
| 384 | elif t == "ReplaceMaterial3D": |
| 385 | links["MaterialInput"] = ("RedMtl", "MaterialOutput") |
| 386 | scene[0] = tool_out |
| 387 | nodes = [op_block(name, self.kind, inputs, links)] |
| 388 | nodes.append(op_block(f"M{f}", "Merge3D", {}, {f"SceneInput{k + 1}": src for k, src in enumerate(scene)})) |
| 389 | if t == "Renderer3D": |
| 390 | return nodes, name |
| 391 | return nodes + [op_block(f"Ren{f}", "Renderer3D", RENDERER3D, {"SceneInput": (f"M{f}", "Output")})], f"Ren{f}" |
| 392 | |
| 393 | def build(self, plates: Dict[str, str]) -> Tuple[str, List[Tuple[int, str]]]: |
| 394 | tools: List[str] = [ |
| 395 | make_loader("PlateA", plates["color"]), |
| 396 | make_loader("PlateB", plates["fg"]), |
| 397 | make_loader("PlateC", plates["bump"]), |
| 398 | f'\t\tBlackBG = Background {{ Inputs = {{ Width = Input {{ Value = {SIZE}, }}, Height = Input {{ Value = {SIZE}, }}, TopLeftAlpha = Input {{ Value = 1, }}, }}, }},', |
| 399 | f'\t\tWhiteBG = Background {{ Inputs = {{ Width = Input {{ Value = {SIZE}, }}, Height = Input {{ Value = {SIZE}, }}, TopLeftRed = Input {{ Value = 1, }}, TopLeftGreen = Input {{ Value = 1, }}, TopLeftBlue = Input {{ Value = 1, }}, TopLeftAlpha = Input {{ Value = 1, }}, }}, }},', |
| 400 | op_block("MaskSrc", "Background", { |
| 401 | "Width": SIZE, "Height": SIZE, "Type": FuID("Corner"), |
| 402 | "TopLeftRed": 1, "TopLeftGreen": 1, "TopLeftBlue": 1, "TopLeftAlpha": 0.0, |
| 403 | "TopRightRed": 1, "TopRightGreen": 1, "TopRightBlue": 1, "TopRightAlpha": 1.0, |
| 404 | "BottomLeftRed": 1, "BottomLeftGreen": 1, "BottomLeftBlue": 1, "BottomLeftAlpha": 0.8, |
| 405 | "BottomRightRed": 1, "BottomRightGreen": 1, "BottomRightBlue": 1, "BottomRightAlpha": 0.2, |
| 406 | }, {}), |
| 407 | ] |
| 408 | tools += self.rig_shared() |
| 409 | if self.shape_inputs or self.out_type == "ShapeTree" or self.kind == "sRender": |
| 410 | tools.append(op_block("ShapeA", "sRectangle", {}, {})) |
| 411 | tools.append(op_block("ShapeB", "sEllipse", {}, {})) |
| 412 | plates_by_slot = ["PlateA", "PlateB", "PlateC"] |
| 413 | fixed = self.fixed_inputs() |
| 414 | plan = self.plan() |
| 415 | cases: List[Tuple[int, str]] = [] |
| 416 | outs: List[str] = [] |
| 417 | for f, (label, overrides, wire_mask) in enumerate(plan): |
| 418 | links: Dict[str, Tuple[str, str]] = {} |
| 419 | for slot, iid in enumerate(self.wired_images): |
| 420 | links[iid] = (plates_by_slot[slot % 3], "Output") |
| 421 | for slot, iid in enumerate(self.shape_inputs): |
| 422 | links[iid] = (("ShapeA", "ShapeB")[slot % 2], "Output") |
| 423 | if self.kind == "sRender" and "Input" not in links: |
| 424 | links["Input"] = ("ShapeA", "Output") |
| 425 | if wire_mask: |
| 426 | links["EffectMask"] = ("MaskSrc", "Output") |
| 427 | inputs = {**fixed, **overrides} |
| 428 | name = f"T{f}" |
| 429 | if self.rig: |
| 430 | nodes, out = self.rig_frame(f, name, inputs, links) |
| 431 | tools += nodes |
| 432 | outs.append(out) |
| 433 | cases.append((f, label)) |
| 434 | continue |
| 435 | tools.append(op_block(name, self.kind, inputs, links)) |
| 436 | out = name |
| 437 | if self.out_type == "Mask": |
| 438 | out = f"W{f}" |
| 439 | tools.append(op_block(out, "Merge", {}, { |
| 440 | "Background": ("BlackBG", "Output"), |
| 441 | "Foreground": ("WhiteBG", "Output"), |
| 442 | "EffectMask": (name, self.out_id), |
| 443 | })) |
| 444 | elif self.out_type == "ShapeTree": |
| 445 | out = f"R{f}" |
| 446 | tools.append(op_block(out, "sRender", {"Width": SIZE, "Height": SIZE}, {"Input": (name, self.out_id)})) |
| 447 | outs.append(out) |
| 448 | cases.append((f, label)) |
| 449 | root, tree, splines = switch_tree(outs) |
| 450 | tools += tree |
| 451 | tools.append(make_saver(root, f"fn_{self.tool_slug()}")) |
| 452 | comp = make_comp("\n".join(tools + splines), len(outs) - 1, w=SIZE, h=SIZE) |
| 453 | if self.rig == "time": # Fusion fails any request outside GlobalRange, and retiming reaches far outside the render range |
| 454 | comp = comp.replace(f"GlobalRange = {{ 0, {len(outs) - 1} }}", "GlobalRange = { -100, 200 }") |
| 455 | return comp, cases |
| 456 | |
| 457 | def tool_slug(self) -> str: |
| 458 | return re.sub(r"\W", "_", self.tool) |
| 459 | |
| 460 | |
| 461 | def score(rows: Dict[int, Dict[str, Any]], labels: Dict[int, str]) -> Dict[str, Any]: |
| 462 | per_frame: List[Dict[str, Any]] = [] |
| 463 | gt_errors: List[str] = [] |
| 464 | for f in sorted(rows): |
| 465 | r = rows[f] |
| 466 | err = r.get("error") |
| 467 | if err and (err.startswith("sg render") or err.startswith("missing gt")): |
| 468 | gt_errors.append(err) |
| 469 | continue |
| 470 | if err or r.get("size_mismatch"): |
| 471 | acc = alpha = 0.0 |
| 472 | else: |
| 473 | acc = max(0.0, 100.0 - r["mae_pct"]) |
| 474 | alpha = max(0.0, 100.0 - r.get("alpha_mae_pct", 0.0)) |
| 475 | row = {"frame": f, "label": labels[f], "accuracy": round(acc, 4), "alpha_accuracy": round(alpha, 4)} |
| 476 | if err: |
| 477 | row["error"] = err[:160] |
| 478 | elif r.get("size_mismatch"): |
| 479 | row["error"] = f"size mismatch ours={r['dims_ours']} fusion={r['dims_gt']}" |
| 480 | per_frame.append(row) |
| 481 | if not per_frame: |
| 482 | return {"skipped": gt_errors[0] if gt_errors else "no frames rendered"} |
| 483 | accs = [p["accuracy"] for p in per_frame] |
| 484 | alphas = [p["alpha_accuracy"] for p in per_frame] |
| 485 | return { |
| 486 | "mean_accuracy": round(sum(accs) / len(accs), 4), |
| 487 | "min_accuracy": round(min(accs), 4), |
| 488 | "mean_alpha_accuracy": round(sum(alphas) / len(alphas), 4), |
| 489 | "min_alpha_accuracy": round(min(alphas), 4), |
| 490 | "frames": len(per_frame), |
| 491 | "timestamp": datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ"), |
| 492 | "per_frame": per_frame, |
| 493 | } |
| 494 | |
| 495 | |
| 496 | def fuzz_tool(tool: str, catalog: Dict[str, Any], frames: int, plates: Dict[str, str], timeout: int) -> Dict[str, Any]: |
| 497 | fz = Fuzzer(tool, catalog, frames) |
| 498 | reason = fz.skip_reason() |
| 499 | if reason: |
| 500 | return {"skipped": reason} |
| 501 | comp_text, cases = fz.build(plates) |
| 502 | root = assets.ensure_dirs() |
| 503 | prefix = f"fn_{fz.tool_slug()}" |
| 504 | comp_path = root / "comps" / f"{prefix}.comp" |
| 505 | comp_path.write_text(comp_text) |
| 506 | labels = dict(cases) |
| 507 | rows = run_comp_both(comp_path, prefix, [f for f, _ in cases], labels, render_gt=True, timeout_sec=timeout) |
| 508 | def rescore(f: int, error: Optional[str] = None) -> None: |
| 509 | ours, gt = root / "ours" / prefix / f"{f:04d}.png", root / "gt" / f"{prefix}_{f:04d}.png" |
| 510 | m = assets.compute_diff_metrics(ours, gt) |
| 511 | if "error" not in m: |
| 512 | m["alpha_mae_pct"] = alpha_mae_pct(ours, gt) |
| 513 | elif error and m["error"].startswith("missing ours"): |
| 514 | m["error"] = error |
| 515 | rows[f] = {**m, "frame": f, "label": labels[f]} |
| 516 | |
| 517 | hung = [f for f, r in rows.items() if str(r.get("error", "")).startswith("render-check timed out")] |
| 518 | for f in hung: # one slow frame must not zero the whole tool |
| 519 | out = root / "ours" / prefix / f"{f:04d}.png" |
| 520 | out.unlink(missing_ok=True) |
| 521 | try: |
| 522 | subprocess.run([str(assets.RENDER_CHECK), str(comp_path), str(f), "--out", str(out)], capture_output=True, timeout=FRAME_TIMEOUT) |
| 523 | except (subprocess.TimeoutExpired, subprocess.CalledProcessError): |
| 524 | pass |
| 525 | rescore(f, f"render-check hung or failed (>{FRAME_TIMEOUT}s)") |
| 526 | for _ in range(4): # SMB directory cache can lag behind sg render |
| 527 | late = [f for f, r in rows.items() if str(r.get("error", "")).startswith("missing gt")] |
| 528 | if not late: |
| 529 | break |
| 530 | time.sleep(5) |
| 531 | for f in late: |
| 532 | rescore(f) |
| 533 | for r in rows.values(): |
| 534 | if "license server" in str(r.get("error", "")): |
| 535 | raise SystemExit(f"STOP: {r['error']}") |
| 536 | return score(rows, labels) |
| 537 | |
| 538 | |
| 539 | def paper_clover(suite: Path, archive_report: Optional[Path]) -> Dict[str, Any]: |
| 540 | """Mean `100 - MAE%` over the private suite frames and archive_diff comps rendered by both engines.""" |
| 541 | proc = subprocess.run([str(assets.RENDER_CHECK), "--suite", str(suite)], capture_output=True, text=True, timeout=1800) |
| 542 | out = proc.stdout + proc.stderr |
| 543 | suite_acc = [100.0 - float(m.group(1)) for m in re.finditer(r"^(?:PASS|FAIL)\s+\S+\s+\d+\s+([\d.]+)%", out, re.M)] |
| 544 | archive_acc: List[float] = [] |
| 545 | if archive_report: |
| 546 | report = json.loads(archive_report.read_text()) |
| 547 | archive_acc = [100.0 - c["mae_pct"] for c in report["cases"] if c.get("status") == "ok"] |
| 548 | both = suite_acc + archive_acc |
| 549 | if not both: |
| 550 | raise SystemExit("paper-clover: no suite or archive results found") |
| 551 | return { |
| 552 | "mean_accuracy": round(sum(both) / len(both), 4), |
| 553 | "suite": {"cases": len(suite_acc), "mean_accuracy": round(sum(suite_acc) / max(1, len(suite_acc)), 4)}, |
| 554 | "archive": {"cases": len(archive_acc), "mean_accuracy": round(sum(archive_acc) / max(1, len(archive_acc)), 4)}, |
| 555 | "timestamp": datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ"), |
| 556 | } |
| 557 | |
| 558 | |
| 559 | def load_ledger(path: Path) -> Dict[str, Any]: |
| 560 | if path.exists(): |
| 561 | return json.loads(path.read_text()) |
| 562 | return {"fusion_version": "21.1", "tools": {}, "skipped": {}} |
| 563 | |
| 564 | |
| 565 | def save_ledger(path: Path, ledger: Dict[str, Any]) -> None: |
| 566 | ledger["tools"] = dict(sorted(ledger["tools"].items())) |
| 567 | ledger["skipped"] = dict(sorted(ledger["skipped"].items())) |
| 568 | path.write_text(json.dumps(ledger, indent=1) + "\n") |
| 569 | |
| 570 | |
| 571 | def main() -> int: |
| 572 | parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) |
| 573 | parser.add_argument("--tool", action="append", default=[], help="Tool class to fuzz (repeatable)") |
| 574 | parser.add_argument("--category", action="append", default=[], help="Fuzz every tool in a compatibility.md category") |
| 575 | parser.add_argument("--all", action="store_true", help="Fuzz every cataloged tool") |
| 576 | parser.add_argument("--paper-clover", action="store_true", help="Refresh the Paper Clover comps headline from the private suite + archive report") |
| 577 | parser.add_argument("--suite", type=Path, default=Path("/Users/clo/dev/compositor/private/suite.txt")) |
| 578 | parser.add_argument("--archive-report", type=Path, help="scripts/archive_diff.py --report-json output") |
| 579 | parser.add_argument("--frames", type=int, default=12, help="Frames per tool (default 12)") |
| 580 | parser.add_argument("--timeout", type=int, default=90, help="Per-render timeout in seconds") |
| 581 | parser.add_argument("--ledger", type=Path, default=LEDGER) |
| 582 | parser.add_argument("--catalog", type=Path, default=CATALOG) |
| 583 | parser.add_argument("--dry-run", action="store_true", help="Write comps only; do not render") |
| 584 | args = parser.parse_args() |
| 585 | |
| 586 | if args.paper_clover: |
| 587 | ledger = load_ledger(args.ledger) |
| 588 | ledger["paper_clover"] = paper_clover(args.suite, args.archive_report) |
| 589 | save_ledger(args.ledger, ledger) |
| 590 | print(json.dumps(ledger["paper_clover"])) |
| 591 | return 0 |
| 592 | |
| 593 | catalog = json.loads(args.catalog.read_text()) |
| 594 | meta = {m.name: m for m in TOOL_METADATA} |
| 595 | if args.all: |
| 596 | names = list(catalog["tools"]) |
| 597 | else: |
| 598 | names = list(args.tool) |
| 599 | for cat in args.category: |
| 600 | names += [m.name for m in TOOL_METADATA if m.category == cat and m.name in catalog["tools"]] |
| 601 | if not names: |
| 602 | parser.print_help() |
| 603 | return 2 |
| 604 | unknown = [n for n in names if n not in catalog["tools"]] |
| 605 | if unknown: |
| 606 | print(f"Not in catalog: {unknown}", file=sys.stderr) |
| 607 | return 2 |
| 608 | |
| 609 | plates = generate_assets() |
| 610 | ledger = load_ledger(args.ledger) |
| 611 | for tool in dict.fromkeys(names): |
| 612 | t0 = time.time() |
| 613 | if args.dry_run: |
| 614 | fz = Fuzzer(tool, catalog, args.frames) |
| 615 | print(f"{tool}: skip={fz.skip_reason()}") |
| 616 | if not fz.skip_reason(): |
| 617 | comp, _ = fz.build(plates) |
| 618 | (assets.ensure_dirs() / "comps" / f"fn_{fz.tool_slug()}.comp").write_text(comp) |
| 619 | continue |
| 620 | result = fuzz_tool(tool, catalog, args.frames, plates, args.timeout) |
| 621 | if "skipped" in result: |
| 622 | ledger["tools"].pop(tool, None) |
| 623 | ledger["skipped"][tool] = result["skipped"] |
| 624 | print(f"{tool:<24s} SKIPPED: {result['skipped'][:100]}", flush=True) |
| 625 | else: |
| 626 | ledger["skipped"].pop(tool, None) |
| 627 | result["category"] = meta[tool].category if tool in meta else None |
| 628 | ledger["tools"][tool] = result |
| 629 | worst = min(result["per_frame"], key=lambda p: p["accuracy"]) |
| 630 | print(f"{tool:<24s} mean={result['mean_accuracy']:7.3f}% min={result['min_accuracy']:7.3f}% " |
| 631 | f"alpha_mean={result['mean_alpha_accuracy']:7.3f}% frames={result['frames']} " |
| 632 | f"({time.time() - t0:.0f}s) worst f{worst['frame']}: {worst['label'][:70]}", flush=True) |
| 633 | save_ledger(args.ledger, ledger) |
| 634 | return 0 |
| 635 | |
| 636 | |
| 637 | if __name__ == "__main__": |
| 638 | raise SystemExit(main()) |