Files
rosetta/tools/fixtures/fbx.py
T
4DBug 51b08575c4 ws-cleanup: codecs/ grouped by domain; containers/Chunks, codecs/audio/Stream, codecs/image/Pixels, codecs/model/Mat4
C2, the hierarchy (tools/move.py, every reference rewritten mechanically):
- codecs/compress: Deflate Lzma Zstd Brotli Bzip2 Lzw; codecs/entropy: Huffman (from core) RangeCoder;
  codecs/image: Jpeg Dct Vp8 Vp8L Yuv Quantize Raster Blend Pixels; codecs/audio: Mdct Aac Alac Pcm Resample
  VorbisComment Tracker SoundFont Stream; codecs/video: H264 Mpeg1 Video; codecs/text: Json Xml Text Url;
  codecs/font: TrueType Cff; codecs/model: MeshFlatten Mat4. containers/ stays flat; core/ keeps Bytes Bits Err
  Crc32 Adler32 Base64 Md5 Input Sniff.
- LAYERS lint: codecs must sit in a domain folder; gen_registry lists codecs by domain (docs/FORMATS.md).
- Checked: build.py both targets, rojo build of build/roblox, the full suite on both runtimes.

C3, generic code out of format folders:
- containers/Chunks (new): the chunked-file walker (RIFF / RIFX / IFF / PNG / CAF layouts: endianness, size first,
  trailer, padding, lenient missing pad, open-ended ids, size hooks). containers/Riff walks with it (RF64 ds64
  through the resize hook); image/png, audio/aiff and audio/caf list their chunk handlers over it.
- codecs/audio/Stream (new): Stream.packets, the packet-decoder Decoder (read / seek with pre-roll / position,
  priming and end trimming) that aac, caf and m4a each carried (~70 lines each).
- codecs/image/Pixels: image/bmp/Pixels promoted (+ rgb555); image/ico's DIB decoder uses its row loops instead of
  its own (the AND mask / alpha rule stay ICO's).
- codecs/model/Mat4 (new): matrices / quaternions / TRS shared by FBX (Xform keeps only the FBX transform model),
  Collada (Math keeps only <lookat> / <skew>) and USD (its matrix helpers and general 4x4 inverse); Mat4.mul is
  Types.Scene.mul. The Collada normal matrix is now the inverse transpose (it was the inverse; same result for the
  fixtures' bind shapes).
- README rewritten (install for Rojo and LÖVE / LuaJIT, quick start per category, F.* and F.ops, host notes:
  FORMATS_NO_JIT_TUNE, paths, layout); docs/STYLE.md: the codec domains, "what belongs in a format folder" with the
  shared building blocks and the DUP rule, conventions (WAVE order, lower-case tags, loops, the api hooks
  decodeImage / encodeImage / openAudio / plugins / resolve, the codecs/video/Video registry), Err.from, the type
  baseline. New tests: tests/containers/chunks, tests/codecs/mat4. Type baseline 93.
2026-10-31 12:25:03 -05:00

180 lines
8.4 KiB
Python

# FBX fixtures (tools/fixtures.py): assimp's FBX test models (binary 7.4 / 7.5, ASCII 7.4 / 7.5 / 7.7, embedded
# textures, skeletons, animation; read from the nixpkgs assimp source, never committed), scenes exported by Blender
# (tools/fixtures/_fbx_blender.py: materials, textures, vertex colours, skin, shape keys, animation, camera, lights)
# and by assimp's FBX exporters (binary and ASCII), with reference values from assimp (`assimp info -r`: meshes,
# faces, vertices, bounds, materials, animations, cameras, lights, bones) and Blender's importer
# (tools/fixtures/_fbx_blender_stats.py). Then our encoder's output (tools/fixtures/_fbx_encode.luau) read back by
# assimp and Blender.
# tests/gen/fbx_cases.luau { name, data, files = { name -> bytes }, assimp, blender? }
# tests/gen/fbx_xcheck.luau { name, case, assimp, blender? }
# tests/gen/fbx_gltf.luau glTF sample models (tests/fixtures/gltf) for the writer round trips: { name, data, files }
import importlib.util, json, os, shutil, subprocess
INPUTS = ["src/Formats/model/fbx", "tests/fixtures/gltf", "src/Formats/codecs/compress/Deflate", "tools/fixtures/_model_ref.py",
"tools/fixtures/_fbx_blender.py", "tools/fixtures/_fbx_blender_stats.py", "tools/fixtures/_fbx_encode.luau"]
def ref_module(ctx):
spec = importlib.util.spec_from_file_location("_model_ref", os.path.join(ctx.root, "tools", "fixtures", "_model_ref.py"))
m = importlib.util.module_from_spec(spec)
spec.loader.exec_module(m)
return m
def assimp_extra(ctx, path):
import re
try:
txt = ctx.nix("assimp", ["assimp", "info", path, "-r"]).decode("utf-8", "replace")
except subprocess.CalledProcessError:
return {}
out = {}
for label in ("Animations", "Cameras", "Lights", "Bones", "Animation Channels"):
m = re.search(r"^" + label + r":\s+(\d+)", txt, re.M)
if m:
out[label.lower().replace(" ", "_")] = int(m.group(1))
return out
def ptv_bounds(ctx, path, tmp):
# world-space bounds: assimp's PreTransformVertices output (`assimp info` multiplies node matrices in the wrong
# order for nested nodes, so its own bounds are not used)
out = os.path.join(tmp, "ptv.obj")
try:
ctx.nix("assimp", ["assimp", "export", path, out, "-ptv"])
lo, hi = [1e30] * 3, [-1e30] * 3
with open(out) as f:
for line in f:
if line.startswith("v "):
v = [float(x) for x in line.split()[1:4]]
lo = [min(a, b) for a, b in zip(lo, v)]
hi = [max(a, b) for a, b in zip(hi, v)]
os.remove(out)
return {"min": lo, "max": hi} if lo[0] <= hi[0] else {}
except (subprocess.CalledProcessError, OSError, ValueError):
return {}
def blender():
return shutil.which("blender")
def blender_stats(ctx, paths):
exe = blender()
if not exe or not paths:
return [None] * len(paths)
script = os.path.join(ctx.root, "tools", "fixtures", "_fbx_blender_stats.py")
try:
res = subprocess.run([exe, "-b", "--factory-startup", "--python", script, "--", json.dumps(paths)],
capture_output=True, timeout=900)
except (subprocess.TimeoutExpired, OSError):
return [None] * len(paths)
for line in res.stdout.decode("utf-8", "replace").split("\n"):
if line.startswith("STATS "):
return json.loads(line[6:])
return [None] * len(paths)
def assimp_src(ctx):
out = subprocess.run(["nix", "build", "nixpkgs#assimp.src", "--no-link", "--print-out-paths"], capture_output=True, check=True)
return out.stdout.decode().strip().split("\n")[-1]
def generate(ctx):
M = ref_module(ctx)
tmp = M.tempdir()
cases = []
# assimp's test models (read only)
src = os.path.join(assimp_src(ctx), "test", "models", "FBX")
for root, _, files in sorted(os.walk(src)):
for f in sorted(files):
if f.lower().endswith(".fbx"):
p = os.path.join(root, f)
cases.append({"name": "assimp/" + os.path.relpath(p, src), "path": p, "files": {}})
# Blender's exporter
exe = blender()
if exe:
bdir = os.path.join(tmp, "blender")
os.makedirs(bdir)
subprocess.run([exe, "-b", "--factory-startup", "--python", os.path.join(ctx.root, "tools", "fixtures", "_fbx_blender.py"), "--", bdir],
capture_output=True, check=True, timeout=600)
for f in sorted(os.listdir(bdir)):
if f.endswith(".fbx"):
cases.append({"name": "blender/" + f, "path": os.path.join(bdir, f), "files": {}})
# assimp's exporters: binary and ASCII, from a few glTF sample models (skin, morph, textures) and a PLY torus
gl = os.path.join(ctx.root, "tests", "fixtures", "gltf")
for model, variant, main in (("SimpleSkin", "glTF", "SimpleSkin.gltf"), ("BoxTextured", "glTF", "BoxTextured.gltf"),
("RiggedSimple", "glTF-Binary", "RiggedSimple.glb"), ("Cameras", "glTF", "Cameras.gltf"),
("BoxVertexColors", "glTF-Binary", "BoxVertexColors.glb")):
inp = os.path.join(gl, model, variant, main)
if not os.path.exists(inp):
continue
for fmt in ("fbx", "fbxa"):
out = os.path.join(tmp, "%s_%s.fbx" % (model, fmt))
try:
ctx.nix("assimp", ["assimp", "export", inp, out, "-f" + fmt])
except subprocess.CalledProcessError:
continue
cases.append({"name": "assimp-export/%s.%s" % (model, fmt), "path": out, "files": {}})
paths = [c["path"] for c in cases]
infos = M.assimp_info(ctx, paths, raw=True)
bl = blender_stats(ctx, paths)
for c, a, b in zip(cases, infos, bl):
a.update(assimp_extra(ctx, c["path"]))
a.pop("min", None)
a.pop("max", None)
a.update(ptv_bounds(ctx, c["path"], tmp))
c["assimp"] = a
if b:
c["blender"] = b
c["data"] = open(c["path"], "rb").read()
# sibling files a model refers to (textures next to it)
d = os.path.dirname(c["path"])
for f in sorted(os.listdir(d)):
if f.lower().endswith((".png", ".jpg", ".jpeg", ".tga")) and os.path.getsize(os.path.join(d, f)) < 300000:
c["files"][f] = open(os.path.join(d, f), "rb").read()
del c["path"]
ctx.emit("fbx_cases", cases)
# glTF sample models for the writer round trips (glTF -> FBX -> Scene, compared with the glTF scene)
picks = []
for model in ("Box", "BoxTextured", "BoxVertexColors", "SimpleSkin", "RiggedSimple", "SimpleMorph", "AnimatedMorphCube",
"Cameras", "MultiUVTest", "InterpolationTest", "NegativeScaleTest", "PointLightIntensityTest",
"AnimatedTriangle", "TextureCoordinateTest", "MeshPrimitiveModes", "SimpleMeshes"):
d0 = os.path.join(gl, model)
if not os.path.isdir(d0):
continue
for variant in sorted(os.listdir(d0)):
d = os.path.join(d0, variant)
if not os.path.isdir(d):
continue
mains = [f for f in sorted(os.listdir(d)) if f.endswith(".gltf") or f.endswith(".glb")]
if mains:
picks.append({"name": model + "/" + variant, "data": open(os.path.join(d, mains[0]), "rb").read(),
"files": {f: open(os.path.join(d, f), "rb").read() for f in sorted(os.listdir(d)) if f != mains[0]}})
break
ctx.emit("fbx_gltf", picks)
# the reference tools read our output
ours = M.luau_encode(ctx, "tools/fixtures/_fbx_encode.luau")
xtmp = M.tempdir()
names = sorted(n for n in ours if n.endswith(".fbx"))
for name, data in ours.items():
with open(os.path.join(xtmp, name), "wb") as f:
f.write(data)
xpaths = [os.path.join(xtmp, n) for n in names]
xi = M.assimp_info(ctx, xpaths, raw=True)
bin_paths = [p for p in xpaths if not p.endswith(".a.fbx")] # Blender reads binary FBX only
xb_bin = dict(zip(bin_paths, blender_stats(ctx, bin_paths)))
xb = [xb_bin.get(p) for p in xpaths]
out = []
for n, p, a, b in zip(names, xpaths, xi, xb):
a.update(assimp_extra(ctx, p))
a.pop("min", None)
a.pop("max", None)
a.update(ptv_bounds(ctx, p, xtmp))
e = {"name": n, "case": int(n.split("_")[1].split(".")[0]), "assimp": a}
if b:
e["blender"] = b
out.append(e)
ctx.emit("fbx_xcheck", out)