ws-3d2/fbx: model/fbx (binary 7.x + ASCII read, binary 7.4 / 7.5 + ASCII write): node tree, Objects / Connections -> Scene (full transform model, layer elements, materials, textures, skins, blend shapes, animation stacks, cameras, lights); tests against assimp + Blender, round trips, fuzz; bench lines

This commit is contained in:
4DBug committed 2026-10-31 09:46:25 -05:00
1 parent 646d18f056
commit d4affd565e
14 files changed
+4403

No files matched your search

+15
View File
@@ -451,6 +451,21 @@ do
bench("ply binary decode (" .. buffer.len(ply) // 1000 .. " KB)", 5, buffer.len(ply), function()
Ply.decode(Bytes.reader(ply))
end)
local Fbx = require("@formats/model/fbx")
local fbx = assert(Fbx.encode(scene))
bench("fbx binary decode (" .. buffer.len(fbx) // 1000 .. " KB)", 3, buffer.len(fbx), function()
Fbx.decode(Bytes.reader(fbx))
end)
bench("fbx binary encode (zlib arrays)", 2, buffer.len(fbx), function()
Fbx.encode(scene)
end)
bench("fbx binary encode (raw arrays)", 3, buffer.len(fbx), function()
Fbx.encode(scene, { compress = false })
end)
local fbxa = assert(Fbx.encode(scene, { ascii = true }))
bench("fbx ascii decode (" .. buffer.len(fbxa) // 1000 .. " KB)", 2, buffer.len(fbxa), function()
Fbx.decode(Bytes.reader(fbxa))
end)
local V = 128
local grid = Types.Voxels.new(V, V, V)
for z = 0, V - 1 do
+94
View File
@@ -0,0 +1,94 @@
# tools/fixtures/_fbx_blender: run by tools/fixtures/fbx.py inside Blender (blender -b --python <this> -- <outdir>): builds
# test scenes (textured cube with two materials, vertex colours and a child; a skinned, animated cylinder with a
# shape key; a camera and three lights) and exports each to binary FBX 7.4.
import bpy, sys, os, math
out = sys.argv[sys.argv.index("--") + 1]
def reset():
bpy.ops.wm.read_factory_settings(use_empty=True)
def export(name, **kw):
bpy.ops.export_scene.fbx(filepath=os.path.join(out, name), **kw)
# 1. textured cube: material, uv, vertex colours, packed image
reset()
bpy.ops.mesh.primitive_cube_add(size=2, location=(1, 2, 3), rotation=(0.3, 0.2, 0.1))
cube = bpy.context.object
cube.name = "Cube"
mesh = cube.data
mesh.color_attributes.new("Col", "BYTE_COLOR", "CORNER")
for i, d in enumerate(mesh.color_attributes["Col"].data):
d.color = ((i % 3) / 2, (i % 5) / 4, (i % 7) / 6, 1)
img = bpy.data.images.new("checker", 8, 8)
img.pixels = [((x + y) % 2) * 1.0 if c < 3 else 1.0 for y in range(8) for x in range(8) for c in range(4)]
img.filepath_raw = os.path.join(out, "checker.png")
img.file_format = "PNG"
img.save()
img.pack()
mat = bpy.data.materials.new("Red")
mat.use_nodes = True
bsdf = mat.node_tree.nodes["Principled BSDF"]
bsdf.inputs["Base Color"].default_value = (0.8, 0.1, 0.1, 1)
bsdf.inputs["Roughness"].default_value = 0.4
tex = mat.node_tree.nodes.new("ShaderNodeTexImage")
tex.image = img
mat.node_tree.links.new(tex.outputs["Color"], bsdf.inputs["Base Color"])
mesh.materials.append(mat)
mat2 = bpy.data.materials.new("Blue")
mat2.diffuse_color = (0.1, 0.1, 0.9, 1)
mesh.materials.append(mat2)
for i, p in enumerate(mesh.polygons):
p.material_index = i % 2
bpy.ops.mesh.primitive_uv_sphere_add(segments=12, ring_count=6, location=(-3, 0, 0))
bpy.context.object.name = "Sphere"
bpy.context.object.parent = cube
export("blender_cube.fbx", path_mode="COPY", embed_textures=True)
# 2. skinned, animated mesh with shape keys
reset()
bpy.ops.object.armature_add(location=(0, 0, 0))
arm = bpy.context.object
arm.name = "Rig"
bpy.ops.object.mode_set(mode="EDIT")
b0 = arm.data.edit_bones[0]
b0.name = "root"
b0.head, b0.tail = (0, 0, 0), (0, 0, 1)
b1 = arm.data.edit_bones.new("tip")
b1.head, b1.tail, b1.parent = (0, 0, 1), (0, 0, 2), b0
bpy.ops.object.mode_set(mode="OBJECT")
bpy.ops.mesh.primitive_cylinder_add(vertices=8, depth=2, radius=0.3, location=(0, 0, 1))
cyl = bpy.context.object
cyl.name = "Body"
bpy.ops.object.mode_set(mode="EDIT")
bpy.ops.mesh.subdivide(number_cuts=3)
bpy.ops.object.mode_set(mode="OBJECT")
cyl.shape_key_add(name="Basis")
sk = cyl.shape_key_add(name="Fat")
for v in sk.data:
v.co.x *= 1.5
v.co.y *= 1.5
sk.value = 0.25
cyl.select_set(True)
arm.select_set(True)
bpy.context.view_layer.objects.active = arm
bpy.ops.object.parent_set(type="ARMATURE_AUTO")
bpy.context.scene.frame_start, bpy.context.scene.frame_end = 1, 20
bpy.ops.object.mode_set(mode="POSE")
pb = arm.pose.bones["tip"]
pb.rotation_mode = "XYZ"
for f, a in ((1, 0), (10, 0.8), (20, 0)):
pb.rotation_euler = (a, 0, 0)
pb.keyframe_insert("rotation_euler", frame=f)
bpy.ops.object.mode_set(mode="OBJECT")
for f, v in ((1, 0), (20, 1)):
sk.value = v
sk.keyframe_insert("value", frame=f)
export("blender_skin.fbx", add_leaf_bones=False, bake_anim=True)
# 3. camera and lights
reset()
bpy.ops.object.camera_add(location=(0, -5, 1), rotation=(math.pi / 2, 0, 0))
bpy.context.object.data.lens = 35
for kind, loc in (("POINT", (1, 0, 3)), ("SUN", (0, 0, 5)), ("SPOT", (2, 2, 2))):
bpy.ops.object.light_add(type=kind, location=loc)
bpy.context.object.data.energy = 10
bpy.ops.mesh.primitive_plane_add(size=4)
export("blender_camlight.fbx")
+31
View File
@@ -0,0 +1,31 @@
# tools/fixtures/_fbx_blender_stats: run by tools/fixtures/fbx.py inside Blender (blender -b --python <this> -- <json
# list of paths>): imports each FBX with Blender's importer and prints one JSON line "STATS <list>" with per file
# counts: mesh objects, polygons, vertices, materials, bones, actions, shape keys, cameras, lights, images; or
# {"failed": message}.
import bpy, sys, json
paths = json.loads(sys.argv[sys.argv.index("--") + 1])
res = []
for p in paths:
bpy.ops.wm.read_factory_settings(use_empty=True)
try:
r = bpy.ops.import_scene.fbx(filepath=p)
if "FINISHED" not in r:
raise RuntimeError(str(r))
except Exception as e:
res.append({"failed": str(e)[:200]})
continue
obs = bpy.context.scene.objects
meshes = [o for o in obs if o.type == "MESH"]
res.append({
"meshes": len(meshes),
"polygons": sum(len(o.data.polygons) for o in meshes),
"vertices": sum(len(o.data.vertices) for o in meshes),
"materials": len([m for m in bpy.data.materials if m.users > 0]),
"bones": sum(len(o.data.bones) for o in obs if o.type == "ARMATURE"),
"actions": len(bpy.data.actions),
"shapeKeys": sum(len(o.data.shape_keys.key_blocks) - 1 for o in meshes if o.data.shape_keys),
"cameras": len([o for o in obs if o.type == "CAMERA"]),
"lights": len([o for o in obs if o.type == "LIGHT"]),
"images": len([i for i in bpy.data.images if i.users > 0]),
})
print("STATS " + json.dumps(res))
+38
View File
@@ -0,0 +1,38 @@
-- tools/fixtures/_fbx_encode: run by tools/fixtures/fbx.py (luau CLI, repo root): decodes every FBX case with our
-- reader and writes it back with our writer (binary 7.4, and ASCII for every third case), printing "<file>\t<hex>"
-- lines for assimp and Blender to read back. Files: rt_<case>.fbx (binary), rt_<case>.a.fbx (ASCII).
local Fbx = require("@formats/model/fbx")
local Bytes = require("@formats/core/Bytes")
local Cases = require("@tests/gen/fbx_cases")
local HEX = {}
for i = 0, 255 do
HEX[i] = string.format("%02x", i)
end
local function hex(b: buffer): string
local out = table.create(buffer.len(b))
for i = 0, buffer.len(b) - 1 do
out[i + 1] = HEX[buffer.readu8(b, i)]
end
return table.concat(out)
end
for i, c in Cases do
local scene, err = Fbx.decode(Bytes.reader(buffer.fromstring(c.data)), { files = c.files, triangulate = false })
if scene then
local bin, e2 = Fbx.encode(scene)
if bin then
print(string.format("rt_%d.fbx\t%s", i, hex(bin)))
else
print("encode failed " .. c.name .. ": " .. tostring(e2))
end
if i % 3 == 0 then
local a = Fbx.encode(scene, { ascii = true })
if a then
print(string.format("rt_%d.a.fbx\t%s", i, hex(a)))
end
end
else
print("skipped " .. c.name .. ": " .. tostring(err))
end
end
+179
View File
@@ -0,0 +1,179 @@
# 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/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)