ws-3d3-b: model/iqm (Inter-Quake Model v2 read + write: meshes, every vertex array format, joints -> skin, poses / frames / anims -> channels, bounds; writer merges skins, samples and quantizes animations); new codecs/model/Sampler (channel evaluation STEP / LINEAR + slerp / CUBICSPLINE, animation poses at a time) with tests

mrfixit.iqm matches assimp and an independent Python IQM reader (its skinning reproduces the bounds the IQM tool stored; ours matches it to 1e-4); round trips and glTF skinned models written by us are skinned identically by the Python reader.
This commit is contained in:
4DBug committed 2026-10-31 14:39:22 -05:00
1 parent 4f05c89f01
commit 51daa00a67
11 files changed
+1953

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)