180 lines
8.4 KiB
Python
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/Rosetta/model/fbx", "tests/fixtures/gltf", "src/Rosetta/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)
|