merge ws/3d3-b (model/lwo, model/x, model/iqm, codecs/model/Sampler; brings ws/game af4488d for codecs/model/Rig)

This commit is contained in:
4DBug committed 2026-10-31 15:02:25 -05:00
commit 44cda7256c
29 files changed
+5664 -4

No files matched your search

+38
View File
@@ -0,0 +1,38 @@
-- tools/fixtures/_iqm_encode: run by tools/fixtures/iqm.py (luau CLI, repo root): writes mrfixit.iqm back through our
-- reader and writer, and every glTF pick through our writer, printing "<file>\t<hex>" lines for assimp and the
-- Python IQM reader. Files: rt_mrfixit.iqm, gltf_<name>.iqm.
local Iqm = require("@formats/model/iqm")
local Gltf = require("@formats/model/gltf")
local Bytes = require("@formats/core/Bytes")
local Cases = require("@tests/gen/iqm_cases")
local Picks = require("@tests/gen/iqm_gltf")
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 _, c in Cases do
local scene = assert(Iqm.decode(Bytes.reader(buffer.fromstring(c.data))))
print("rt_mrfixit.iqm\t" .. hex(assert(Iqm.encode(scene))))
end
for _, p in Picks do
local scene, err = Gltf.decode(Bytes.reader(buffer.fromstring(p.data)), { files = p.files })
if scene then
local out, e2 = Iqm.encode(scene)
if out then
print("gltf_" .. p.name .. ".iqm\t" .. hex(out))
else
print("encode failed " .. p.name .. ": " .. tostring(e2))
end
else
print("skipped " .. p.name .. ": " .. tostring(err))
end
end
+113
View File
@@ -0,0 +1,113 @@
# An independent IQM reader for tools/fixtures/iqm.py (plain Python, from the IQM SDK's format description and its
# demo's skinning: joint matrices = pose world * inverse bind world): header counts and the bounding box of the
# skinned vertices for every animation frame, computed from the joints, poses and frames (not from the file's bounds
# block, which it returns too for comparison).
import math, struct
HEADER = ("version filesize flags num_text ofs_text num_meshes ofs_meshes num_vertexarrays num_vertexes ofs_vertexarrays "
"num_triangles ofs_triangles ofs_adjacency num_joints ofs_joints num_poses ofs_poses num_anims ofs_anims num_frames "
"num_framechannels ofs_frames ofs_bounds num_comment ofs_comment num_extensions ofs_extensions").split()
FMT = {0: ("b", 1), 1: ("B", 1), 2: ("h", 2), 3: ("H", 2), 4: ("i", 4), 5: ("I", 4), 7: ("f", 4), 8: ("d", 8)}
def mat(t, q, s):
x, y, z, w = q
n = math.sqrt(x * x + y * y + z * z + w * w) or 1
x, y, z, w = x / n, y / n, z / n, w / n
r = [[1 - 2 * (y * y + z * z), 2 * (x * y - w * z), 2 * (x * z + w * y)],
[2 * (x * y + w * z), 1 - 2 * (x * x + z * z), 2 * (y * z - w * x)],
[2 * (x * z - w * y), 2 * (y * z + w * x), 1 - 2 * (x * x + y * y)]]
return [[r[i][0] * s[0], r[i][1] * s[1], r[i][2] * s[2], t[i]] for i in range(3)] + [[0, 0, 0, 1]]
def mul(a, b):
return [[sum(a[i][k] * b[k][j] for k in range(4)) for j in range(4)] for i in range(4)]
def inv(m):
# general 4x4 inverse (Gauss-Jordan)
a = [row[:] + [1 if i == j else 0 for j in range(4)] for i, row in enumerate(m)]
for c in range(4):
p = max(range(c, 4), key=lambda r: abs(a[r][c]))
a[c], a[p] = a[p], a[c]
d = a[c][c] or 1e-30
a[c] = [v / d for v in a[c]]
for r in range(4):
if r != c:
f = a[r][c]
a[r] = [v - f * w for v, w in zip(a[r], a[c])]
return [row[4:] for row in a]
def read(data):
h = dict(zip(HEADER, struct.unpack_from("<27I", data, 16)))
text = data[h["ofs_text"]:h["ofs_text"] + h["num_text"]]
def s(o):
return text[o:text.index(b"\0", o)].decode("latin1")
arrays = {}
for i in range(h["num_vertexarrays"]):
typ, flags, fmt, size, ofs = struct.unpack_from("<5I", data, h["ofs_vertexarrays"] + i * 20)
c, n = FMT[fmt]
vals = struct.unpack_from("<%d%s" % (h["num_vertexes"] * size, c), data, ofs)
arrays[typ] = (fmt, size, vals)
joints = []
for j in range(h["num_joints"]):
v = struct.unpack_from("<Ii10f", data, h["ofs_joints"] + j * 48)
joints.append((s(v[0]), v[1], v[2:5], v[5:9], v[9:12]))
bind = []
for name, parent, t, q, sc in joints:
m = mat(t, q, sc)
bind.append(mul(bind[parent], m) if parent >= 0 else m)
invbind = [inv(m) for m in bind]
poses = []
for p in range(h["num_poses"]):
v = struct.unpack_from("<iI20f", data, h["ofs_poses"] + p * 88)
poses.append((v[0], v[1], v[2:12], v[12:22]))
frames = struct.unpack_from("<%dH" % (h["num_frames"] * h["num_framechannels"]), data, h["ofs_frames"]) if h["num_frames"] else ()
anims = []
for a in range(h["num_anims"]):
v = struct.unpack_from("<3IfI", data, h["ofs_anims"] + a * 20)
anims.append({"name": s(v[0]), "first": v[1], "frames": v[2], "framerate": v[3]})
pos = arrays[0][2]
bi = arrays.get(4)
bw = arrays.get(5)
boxes = []
k = 0
for f in range(h["num_frames"]):
world = []
for i, (parent, mask, off, sc) in enumerate(poses):
ch = list(off)
for c in range(10):
if mask & (1 << c):
ch[c] += frames[k] * sc[c]
k += 1
m = mat(ch[0:3], ch[3:7], ch[7:10])
world.append(mul(world[parent], m) if parent >= 0 else m)
skin = [mul(world[j], invbind[j]) for j in range(len(world))]
lo, hi = [1e30] * 3, [-1e30] * 3
for v in range(h["num_vertexes"]):
x, y, z = pos[v * 3:v * 3 + 3]
if bi and bw:
sx = sy = sz = 0.0
tot = 0.0
for c in range(4):
w = bw[2][v * 4 + c] / 255.0 if bw[0] == 1 else bw[2][v * 4 + c]
if w > 0:
m = skin[bi[2][v * 4 + c]]
sx += w * (m[0][0] * x + m[0][1] * y + m[0][2] * z + m[0][3])
sy += w * (m[1][0] * x + m[1][1] * y + m[1][2] * z + m[1][3])
sz += w * (m[2][0] * x + m[2][1] * y + m[2][2] * z + m[2][3])
tot += w
if tot > 0:
x, y, z = sx, sy, sz
lo = [min(a, b) for a, b in zip(lo, (x, y, z))]
hi = [max(a, b) for a, b in zip(hi, (x, y, z))]
boxes.append({"min": lo, "max": hi})
stored = []
if h["ofs_bounds"]:
for f in range(h["num_frames"]):
v = struct.unpack_from("<8f", data, h["ofs_bounds"] + f * 32)
stored.append({"min": list(v[0:3]), "max": list(v[3:6])})
return {"meshes": h["num_meshes"], "vertexes": h["num_vertexes"], "triangles": h["num_triangles"], "joints": h["num_joints"],
"jointNames": [j[0] for j in joints], "anims": anims, "frames": h["num_frames"], "skinned": boxes, "stored": stored}
+57
View File
@@ -0,0 +1,57 @@
# Inter-Quake Model fixtures (tools/fixtures.py): assimp's IQM test model (mrfixit.iqm, from the nixpkgs assimp
# source, never committed) with assimp's view of it (`assimp info -r`, PreTransformVertices bounds) and an independent
# Python reading (tools/fixtures/_iqm_reference.py: counts, and the bounds of the skinned vertices per frame computed
# from joints / poses / frames, next to the bounds block the IQM tool stored); glTF sample models (tests/fixtures/gltf)
# for the writer; then our encoder's output (tools/fixtures/_iqm_encode.luau) read back by assimp and the Python reader.
# tests/gen/iqm_cases.luau { name, data, assimp, ref }
# tests/gen/iqm_gltf.luau { name, data, files }
# tests/gen/iqm_xcheck.luau { name, assimp, ref }
import importlib.util, os
INPUTS = ["src/Formats/model/iqm", "src/Formats/codecs/model", "tools/fixtures/_model_ref.py", "tools/fixtures/fbx.py",
"tools/fixtures/_iqm_reference.py", "tools/fixtures/_iqm_encode.luau", "tests/fixtures/gltf"]
def module(ctx, name):
spec = importlib.util.spec_from_file_location(name, os.path.join(ctx.root, "tools", "fixtures", name + ".py"))
m = importlib.util.module_from_spec(spec)
spec.loader.exec_module(m)
return m
def info(ctx, M, fbx, path, tmp):
a = M.assimp_info(ctx, [path], raw=True)[0]
for k in ("min", "max", "perMesh"):
a.pop(k, None)
if not a.get("failed"):
a.update(fbx.ptv_bounds(ctx, path, tmp))
return a
def generate(ctx):
M = module(ctx, "_model_ref")
fbx = module(ctx, "fbx")
R = module(ctx, "_iqm_reference")
tmp = M.tempdir()
p = os.path.join(fbx.assimp_src(ctx), "test", "models", "IQM", "mrfixit.iqm")
data = open(p, "rb").read()
ctx.emit("iqm_cases", [{"name": "mrfixit.iqm", "data": data, "assimp": info(ctx, M, fbx, p, tmp), "ref": R.read(data)}])
gl = os.path.join(ctx.root, "tests", "fixtures", "gltf")
picks = []
for model in ("RiggedSimple", "SimpleSkin", "Box", "BoxTextured", "BoxVertexColors", "MeshPrimitiveModes", "SimpleMeshes"):
d0 = os.path.join(gl, model)
for variant in sorted(os.listdir(d0)) if os.path.isdir(d0) else []:
d = os.path.join(d0, variant)
mains = [f for f in sorted(os.listdir(d)) if f.endswith((".gltf", ".glb"))] if os.path.isdir(d) else []
if mains:
picks.append({"name": model, "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("iqm_gltf", picks)
ours = M.luau_encode(ctx, "tools/fixtures/_iqm_encode.luau")
out = []
for name in sorted(ours):
q = os.path.join(tmp, name)
open(q, "wb").write(ours[name])
out.append({"name": name, "assimp": info(ctx, M, fbx, q, tmp), "ref": R.read(ours[name])})
ctx.emit("iqm_xcheck", out)
+41
View File
@@ -0,0 +1,41 @@
# LightWave object fixtures (tools/fixtures.py): assimp's LWO test models (LWO2, LWOB, Modo LXOB; models and
# models-nonbsd, read from the nixpkgs assimp source, never committed) with assimp's view of them (`assimp info -r`:
# meshes, polygons, corners, materials, nodes; world bounds from assimp's PreTransformVertices export).
# tests/gen/lwo_cases.luau { name, data, assimp = { meshes, faces, vertices, materials, nodes, min, max } }
import importlib.util, os
def module(ctx, name):
spec = importlib.util.spec_from_file_location(name, os.path.join(ctx.root, "tools", "fixtures", name + ".py"))
m = importlib.util.module_from_spec(spec)
spec.loader.exec_module(m)
return m
INPUTS = ["src/Formats/model/lwo", "tools/fixtures/_model_ref.py", "tools/fixtures/fbx.py"]
def generate(ctx):
M = module(ctx, "_model_ref")
fbx = module(ctx, "fbx") # assimp_src, ptv_bounds
tmp = M.tempdir()
src = fbx.assimp_src(ctx)
cases = []
for sub in ("models/LWO", "models-nonbsd/LWO"):
d0 = os.path.join(src, "test", sub)
for root, _, files in sorted(os.walk(d0)):
for f in sorted(files):
if f.lower().endswith((".lwo", ".lxo")):
p = os.path.join(root, f)
cases.append({"name": sub.split("/")[0] + "/" + os.path.relpath(p, d0), "path": p})
infos = M.assimp_info(ctx, [c["path"] for c in cases], raw=True)
for c, a in zip(cases, infos):
a.pop("min", None)
a.pop("max", None)
a.pop("perMesh", None)
if not a.get("failed"):
a.update(fbx.ptv_bounds(ctx, c["path"], tmp))
c["assimp"] = a
c["data"] = open(c["path"], "rb").read()
del c["path"]
ctx.emit("lwo_cases", cases)
+63
View File
@@ -0,0 +1,63 @@
# Quake PAK fixtures (tools/fixtures.py): PAK files written here from the Quake source's dpackheader_t / dpackfile_t
# layout (header, file data in order, directory at the end: the layout id's qpak and most tools write), in the Quake
# ("PACK", 56-byte names) and SiN ("SPAK", 120-byte names) variants, plus one with the directory first and padding
# between files; with the expected entries read back by an independent Python reader here.
# tests/gen/pak.luau { { name, variant, data, entries = { { name, size, crc } }, files = { { name, data } } } }
import struct, zlib
VARIANTS = {"quake": (b"PACK", 56), "sin": (b"SPAK", 120)}
def write(files, variant="quake", dir_first=False, pad=0):
magic, nl = VARIANTS[variant]
dirlen = len(files) * (nl + 8)
out = bytearray(magic + b"\0" * 8)
if dir_first:
dirofs = 12
out += b"\0" * dirlen
offs = []
for name, data in files:
out += b"\xee" * pad
offs.append(len(out))
out += data
if not dir_first:
dirofs = len(out)
out += b"\0" * dirlen
for i, (name, data) in enumerate(files):
struct.pack_into("<%dsII" % nl, out, dirofs + i * (nl + 8), name.encode(), offs[i], len(data))
struct.pack_into("<II", out, 4, dirofs, dirlen)
return bytes(out)
def read(data):
magic, dirofs, dirlen = struct.unpack_from("<4sII", data)
nl = {b"PACK": 56, b"SPAK": 120}[magic]
out = []
for i in range(dirlen // (nl + 8)):
name, at, n = struct.unpack_from("<%dsII" % nl, data, dirofs + i * (nl + 8))
out.append({"name": name.split(b"\0")[0].decode(), "size": n, "crc": zlib.crc32(data[at:at + n])})
return out
def generate(ctx):
rng = ctx.rng(17)
base = [
("gfx/palette.lmp", bytes(rng.randrange(256) for _ in range(768))),
("maps/start.bsp", rng.randbytes(5000)),
("sound/misc/null.wav", b""),
("progs/player.mdl", rng.randbytes(1234)),
("default.cfg", b"bind w +forward\n"),
("a" * 55, b"longest quake name"),
]
cases = [
("quake", "quake", write(base), base),
("quake-dir-first", "quake", write(base, dir_first=True, pad=3), base),
("empty", "quake", write([]), []),
("sin", "sin", write(base + [("models/" + "b" * 100 + ".def", b"sin")], "sin"), base + [("models/" + "b" * 100 + ".def", b"sin")]),
]
out = []
for name, variant, data, files in cases:
out.append({"name": name, "variant": variant, "data": data, "entries": read(data),
"layoutDefault": not name.endswith("dir-first"),
"files": [{"name": n, "data": d} for n, d in files]})
ctx.emit("pak", out)
+126
View File
@@ -0,0 +1,126 @@
# DirectX .x fixtures (tools/fixtures.py): assimp's X test models (text, binary 32-bit, MSZIP-compressed binary;
# models and models-nonbsd, read from the nixpkgs assimp source, never committed), plus variants made here from the
# text ones: binary with 64-bit floats ("bin 0064") and MSZIP-compressed text ("tzip", per-block raw deflate with
# the previous block as dictionary, as D3DX writes). Reference: assimp (`assimp info -r`: meshes, faces, corners,
# materials, nodes, animations, bones; world bounds from its PreTransformVertices export), on the variants too.
# tests/gen/x_cases.luau { name, data, assimp = { ... } }
import importlib.util, os, re, struct, zlib
INPUTS = ["src/Formats/model/x", "tools/fixtures/_model_ref.py", "tools/fixtures/fbx.py"]
def module(ctx, name):
spec = importlib.util.spec_from_file_location(name, os.path.join(ctx.root, "tools", "fixtures", name + ".py"))
m = importlib.util.module_from_spec(spec)
spec.loader.exec_module(m)
return m
TOKEN = re.compile(rb'\s+|//[^\n]*|#[^\n]*|"[^"]*"|<[^>]*>|[{}]|[;,]|[^\s;,{}"]+')
def to_binary64(text):
"""a text .x file -> binary tokens with 64-bit floats (templates dropped; numbers with . or e are floats)"""
body = text[16:]
out = bytearray(b"xof 0303bin 0064")
toks = [t for t in TOKEN.findall(body) if t.strip() and not t.startswith((b"//", b"#"))]
i, nums = 0, []
def flush():
while nums:
isf = nums[0][0]
run = []
while nums and nums[0][0] == isf:
run.append(nums.pop(0)[1])
if isf:
out.extend(struct.pack("<HI", 7, len(run)) + b"".join(struct.pack("<d", v) for v in run))
else:
out.extend(struct.pack("<HI", 6, len(run)) + b"".join(struct.pack("<I", int(v) & 0xFFFFFFFF) for v in run))
while i < len(toks):
t = toks[i]
if t == b"template":
flush()
depth = 0
while i < len(toks):
if toks[i] == b"{":
depth += 1
elif toks[i] == b"}":
depth -= 1
if depth == 0:
break
i += 1
elif t in (b";", b","):
pass
elif t[:1] in b"0123456789-+.":
try:
v = float(t)
except ValueError:
v = 0.0
nums.append((b"." in t or b"e" in t.lower() or b"#" in t, v))
else:
flush()
if t == b"{":
out.extend(struct.pack("<H", 0x0A))
elif t == b"}":
out.extend(struct.pack("<H", 0x0B))
elif t.startswith(b'"'):
s = t[1:-1]
out.extend(struct.pack("<HI", 2, len(s)) + s + struct.pack("<H", 0x14))
elif t.startswith(b"<"):
pass
else:
out.extend(struct.pack("<HI", 1, len(t)) + t)
i += 1
flush()
return bytes(out)
def to_tzip(text):
"""a text .x file -> "tzip": MSZIP blocks of 32 KiB, each raw deflate with the previous block as dictionary"""
body = text[16:]
out = bytearray(b"xof 0303tzip0032") + struct.pack("<I", 0)
data = body
prev = b""
for p in range(0, len(data), 32768):
blk = data[p:p + 32768]
c = zlib.compressobj(9, zlib.DEFLATED, -15, zdict=prev) if prev else zlib.compressobj(9, zlib.DEFLATED, -15)
z = c.compress(blk) + c.flush(zlib.Z_FINISH)
out.extend(struct.pack("<HH", len(blk), len(z) + 2) + b"CK" + z)
prev = blk
struct.pack_into("<I", out, 16, len(data) + 16) # the size counts the 16-byte header (D3DX)
return bytes(out)
def generate(ctx):
M = module(ctx, "_model_ref")
fbx = module(ctx, "fbx")
tmp = M.tempdir()
src = fbx.assimp_src(ctx)
cases = []
for sub in ("models/X", "models-nonbsd/X"):
d0 = os.path.join(src, "test", sub)
for f in sorted(os.listdir(d0)):
p = os.path.join(d0, f)
if os.path.isfile(p) and open(p, "rb").read(4) == b"xof ":
cases.append({"name": sub.split("/")[0] + "/" + f, "path": p})
# variants of the small text files: binary 64-bit floats and tzip
for name in ("test_cube_text.x", "kwxport_test_cubewithvcolors.x", "test.x", "anim_test.x"):
p = os.path.join(src, "test", "models", "X", name)
text = open(p, "rb").read()
for kind, data in (("bin64", to_binary64(text)), ("tzip", to_tzip(text))):
q = os.path.join(tmp, "%s.%s.x" % (name[:-2], kind))
open(q, "wb").write(data)
cases.append({"name": "variant/%s.%s.x" % (name[:-2], kind), "path": q, "of": "models/" + name})
infos = M.assimp_info(ctx, [c["path"] for c in cases], raw=True)
for c, a in zip(cases, infos):
a.pop("min", None)
a.pop("max", None)
a.pop("perMesh", None)
if not a.get("failed"):
a.update(fbx.assimp_extra(ctx, c["path"]))
a.update(fbx.ptv_bounds(ctx, c["path"], tmp))
c["assimp"] = a
c["data"] = open(c["path"], "rb").read()
del c["path"]
ctx.emit("x_cases", cases)