205 lines
9.6 KiB
Python
205 lines
9.6 KiB
Python
# B3D fixtures (tools/fixtures.py): assimp's Blitz3D test models (WusonBlitz, dwarf2, turtle1: read from the nixpkgs
|
|
# assimp source, never committed; their textures next to them go into `files`) and B3D files written here (textures
|
|
# with transforms and clamp flags, brushes with alpha / FX, vertex colours, two UV sets, nested rotated / scaled nodes,
|
|
# pivots, master brushes, bones with weights, KEYS + ANIM), with reference values from assimp: `assimp info -r`
|
|
# (meshes, faces, materials, animations, channels, bones) and its PreTransformVertices OBJ export (world bounds,
|
|
# triangle area, signed volume: the handedness conversion and winding), plus the counts the generator wrote.
|
|
# tests/gen/b3d_cases.luau { name, data, files = { name -> bytes }, assimp = {...}, want? = {...} }
|
|
import importlib.util, math, os, re, struct, subprocess
|
|
|
|
INPUTS = ["tools/fixtures/_model_ref.py"]
|
|
|
|
|
|
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_src():
|
|
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]
|
|
|
|
|
|
# ---------------------------------------------------------------------------------------------------- B3D writer
|
|
def chunk(tag, *parts):
|
|
body = b"".join(parts)
|
|
return tag.encode() + struct.pack("<I", len(body)) + body
|
|
|
|
|
|
def cstr(s):
|
|
return s.encode() + b"\0"
|
|
|
|
|
|
def f32(*v):
|
|
return struct.pack("<%df" % len(v), *v)
|
|
|
|
|
|
def i32(*v):
|
|
return struct.pack("<%di" % len(v), *v)
|
|
|
|
|
|
def quat_axis(ax, ay, az, deg):
|
|
# Blitz3D order: w, x, y, z
|
|
l = math.sqrt(ax * ax + ay * ay + az * az)
|
|
h = math.radians(deg) / 2
|
|
s = math.sin(h) / l
|
|
return (math.cos(h), ax * s, ay * s, az * s)
|
|
|
|
|
|
def node(name, pos=(0, 0, 0), scale=(1, 1, 1), rot=(1, 0, 0, 0), *children):
|
|
return chunk("NODE", cstr(name), f32(*pos), f32(*scale), f32(*rot), *children)
|
|
|
|
|
|
def box_mesh(sx, sy, sz, flags=0, sets=1, size=2, brushes=(-1,), master=-1):
|
|
# 8 corners, 12 triangles; split between the brushes round-robin by face
|
|
verts = []
|
|
for i in range(8):
|
|
x, y, z = (sx if i & 1 else -sx), (sy if i & 2 else -sy), (sz if i & 4 else -sz)
|
|
v = f32(x, y, z)
|
|
if flags & 1:
|
|
l = math.sqrt(x * x + y * y + z * z)
|
|
v += f32(x / l, y / l, z / l)
|
|
if flags & 2:
|
|
v += f32((i & 1) * 1.0, ((i >> 1) & 1) * 1.0, ((i >> 2) & 1) * 1.0, 1.0)
|
|
for s in range(sets):
|
|
v += f32(*[(i * 0.1 + s + k * 0.5) for k in range(size)])
|
|
verts.append(v)
|
|
# Blitz3D front faces are clockwise seen from outside (left-handed, Direct3D culling)
|
|
quads = [(0, 2, 3, 1), (4, 5, 7, 6), (0, 1, 5, 4), (2, 6, 7, 3), (0, 4, 6, 2), (1, 3, 7, 5)]
|
|
tris = []
|
|
for a, b, c, d in quads:
|
|
tris += [(a, b, c), (a, c, d)]
|
|
tchunks = []
|
|
for k, br in enumerate(brushes):
|
|
mine = [t for j, t in enumerate(tris) if j % len(brushes) == k]
|
|
tchunks.append(chunk("TRIS", i32(br), b"".join(i32(*t) for t in mine)))
|
|
return chunk("MESH", i32(master), chunk("VRTS", i32(flags, sets, size), b"".join(verts)), *tchunks), 8, 12
|
|
|
|
|
|
def textured():
|
|
texs = chunk("TEXS", cstr("tex/a.png"), i32(1, 2), f32(0.25, 0.5), f32(2, 3), f32(0.5),
|
|
cstr("b.png"), i32(1 | 16 | 32 | 65536, 2), f32(0, 0), f32(1, 1), f32(0))
|
|
brus = chunk("BRUS", i32(2),
|
|
cstr("red"), f32(1, 0, 0, 1), f32(0.5), i32(1, 0), i32(0, 1),
|
|
cstr("glass"), f32(0.2, 0.4, 1, 0.5), f32(0), i32(1, 16 | 1), i32(1, -1))
|
|
m1, _, _ = box_mesh(1, 2, 3, flags=3, sets=2, size=2, brushes=(0, 1))
|
|
m2, _, _ = box_mesh(0.5, 0.5, 0.5, flags=1, sets=1, size=2, brushes=(-1,), master=1)
|
|
child = node("child", (3, 1, -2), (1, 2, 1), quat_axis(0, 1, 1, 50), m2)
|
|
root = node("root", (1, 2, 3), (2, 1, 0.5), quat_axis(1, 1, 0, 30), m1, child)
|
|
data = chunk("BB3D", i32(1), texs, brus, root)
|
|
return data, {"vertices": 16, "triangles": 24, "textures": 2, "materials": 2, "colors": True, "uvSets": 2, "nodes": 2}
|
|
|
|
|
|
def pivots():
|
|
m1, _, _ = box_mesh(1, 1, 1, brushes=(-1,))
|
|
m2, _, _ = box_mesh(2, 0.5, 1, sets=0, brushes=(-1,))
|
|
a = node("a", (5, 0, 0), (1, 1, 1), quat_axis(0, 0, 1, 90), m1)
|
|
b = node("b", (0, 0, 5), (-1, 1, 1), quat_axis(0, 1, 0, -45), m2)
|
|
pivot = node("pivot", (0, 3, 0), (1, 1, 1), quat_axis(1, 0, 0, 20), a, b)
|
|
data = chunk("BB3D", i32(1), node("top", (0, 0, 0), (1, 1, 1), (1, 0, 0, 0), pivot))
|
|
return data, {"vertices": 16, "triangles": 24, "textures": 0, "materials": 0, "colors": False, "uvSets": 1, "nodes": 4, "mirrored": True}
|
|
|
|
|
|
def skinned():
|
|
# a bar along y: 3 rings of 4 vertices; two bones (nested), each weighting rings; keys on both bones
|
|
verts, tris = [], []
|
|
for ring in range(3):
|
|
for k in range(4):
|
|
a = math.radians(90 * k)
|
|
verts.append(f32(math.cos(a), ring * 2.0, math.sin(a)))
|
|
for ring in range(2):
|
|
for k in range(4):
|
|
a, b = ring * 4 + k, ring * 4 + (k + 1) % 4
|
|
tris += [(a, b + 4, b), (a, a + 4, b + 4)]
|
|
mesh = chunk("MESH", i32(-1), chunk("VRTS", i32(0, 0, 0), b"".join(verts)), chunk("TRIS", i32(-1), b"".join(i32(*t) for t in tris)))
|
|
w1 = b"".join(i32(v) + f32(1.0 if v < 4 else 0.5) for v in range(8))
|
|
w2 = b"".join(i32(v) + f32(0.5 if v < 8 else 1.0) for v in range(4, 12))
|
|
keys1 = chunk("KEYS", i32(4), *[i32(f) + f32(*quat_axis(0, 0, 1, f * 10)) for f in (1, 5, 10)])
|
|
keys2 = chunk("KEYS", i32(1 | 2), *[i32(f) + f32(0, 2 + f * 0.1, 0) + f32(1, 1 + f * 0.05, 1) for f in (1, 10)])
|
|
bone2 = node("bone2", (0, 2, 0), (1, 1, 1), (1, 0, 0, 0), chunk("BONE", w2), keys2)
|
|
bone1 = node("bone1", (0, 0, 0), (1, 1, 1), (1, 0, 0, 0), chunk("BONE", w1), keys1, bone2)
|
|
root = node("body", (0, 1, 0), (1, 1, 1), quat_axis(0, 1, 0, 15), mesh, bone1, chunk("ANIM", i32(0, 10), f32(25)))
|
|
data = chunk("BB3D", i32(1), root)
|
|
return data, {"vertices": 12, "triangles": 16, "textures": 0, "materials": 0, "colors": False, "uvSets": 0, "nodes": 3,
|
|
"joints": 2, "channels": 3, "fps": 25.0, "frames": 10}
|
|
|
|
|
|
# ---------------------------------------------------------------------------------------------------- references
|
|
def info(ctx, path):
|
|
try:
|
|
txt = ctx.nix("assimp", ["assimp", "info", path, "-r"]).decode("utf-8", "replace")
|
|
except subprocess.CalledProcessError:
|
|
return {"failed": True}
|
|
out = {}
|
|
for label in ("Meshes", "Materials", "Faces", "Vertices", "Animations", "Bones", "Animation Channels", "Nodes"):
|
|
m = re.search(r"^" + label + r":\s+(\d+)", txt, re.M)
|
|
out[label.lower().replace(" ", "_")] = int(m.group(1)) if m else -1
|
|
return out
|
|
|
|
|
|
def ptv(ctx, path, tmp):
|
|
# world-space triangles from assimp's PreTransformVertices OBJ export: bounds, area, signed volume
|
|
out = os.path.join(tmp, "ptv.obj")
|
|
ctx.nix("assimp", ["assimp", "export", path, out, "-ptv"])
|
|
vs, area, vol = [], 0.0, 0.0
|
|
lo, hi = [1e30] * 3, [-1e30] * 3
|
|
with open(out) as f:
|
|
for line in f:
|
|
p = line.split()
|
|
if not p:
|
|
continue
|
|
if p[0] == "v":
|
|
v = [float(x) for x in p[1:4]]
|
|
vs.append(v)
|
|
lo = [min(a, b) for a, b in zip(lo, v)]
|
|
hi = [max(a, b) for a, b in zip(hi, v)]
|
|
elif p[0] == "f":
|
|
idx = [int(x.split("/")[0]) for x in p[1:]]
|
|
idx = [i - 1 if i > 0 else len(vs) + i for i in idx]
|
|
for k in range(1, len(idx) - 1):
|
|
a, b, c = vs[idx[0]], vs[idx[k]], vs[idx[k + 1]]
|
|
e1 = [b[j] - a[j] for j in range(3)]
|
|
e2 = [c[j] - a[j] for j in range(3)]
|
|
cr = [e1[1] * e2[2] - e1[2] * e2[1], e1[2] * e2[0] - e1[0] * e2[2], e1[0] * e2[1] - e1[1] * e2[0]]
|
|
area += math.sqrt(sum(x * x for x in cr)) / 2
|
|
vol += (a[0] * (b[1] * c[2] - b[2] * c[1]) - a[1] * (b[0] * c[2] - b[2] * c[0]) + a[2] * (b[0] * c[1] - b[1] * c[0])) / 6
|
|
os.remove(out)
|
|
return {"min": lo, "max": hi, "area": area, "volume": vol}
|
|
|
|
|
|
def generate(ctx):
|
|
M = ref_module(ctx)
|
|
tmp = M.tempdir()
|
|
cases = []
|
|
src = assimp_src()
|
|
for rel in ("models/B3D/WusonBlitz.b3d", "models-nonbsd/B3D/dwarf2.b3d", "models-nonbsd/B3D/turtle1.b3d"):
|
|
p = os.path.join(src, "test", rel)
|
|
if not os.path.exists(p):
|
|
continue
|
|
d = os.path.dirname(p)
|
|
files = {f: open(os.path.join(d, f), "rb").read() for f in sorted(os.listdir(d))
|
|
if f.lower().endswith((".png", ".jpg")) and os.path.getsize(os.path.join(d, f)) < 300000}
|
|
cases.append({"name": "assimp/" + rel, "path": p, "files": files})
|
|
for name, fn in (("textured", textured), ("pivots", pivots), ("skinned", skinned)):
|
|
data, want = fn()
|
|
p = os.path.join(tmp, name + ".b3d")
|
|
with open(p, "wb") as f:
|
|
f.write(data)
|
|
files = {"a.png": M_PNG, "b.png": M_PNG} if name == "textured" else {}
|
|
cases.append({"name": "gen/" + name, "path": p, "files": files, "want": want})
|
|
for c in cases:
|
|
a = info(ctx, c["path"])
|
|
if not a.get("failed"):
|
|
a.update(ptv(ctx, c["path"], tmp))
|
|
c["assimp"] = a
|
|
c["data"] = open(c["path"], "rb").read()
|
|
del c["path"]
|
|
ctx.emit("b3d_cases", cases)
|
|
|
|
|
|
# a 1x1 PNG (texture data for the generated files)
|
|
M_PNG = bytes.fromhex("89504e470d0a1a0a0000000d4948445200000001000000010806000000"
|
|
"1f15c4890000000d49444154789c63f8cfc0f01f0005000201a2b3d6bd0000000049454e44ae426082")
|