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

+92
View File
@@ -0,0 +1,92 @@
-- codecs/model/Sampler tests: STEP / LINEAR / CUBICSPLINE channels (glTF's Hermite definition), quaternion slerp
-- (shortest path, unit length), clamping outside the keys, weights channels, Sampler.times and Sampler.pose; glTF's
-- InterpolationTest sample model (every interpolation) sampled at its keys gives the key values; bad channels.
local T = require("@tests/T")
local Sampler = require("@formats/codecs/model/Sampler")
local Gltf = require("@formats/model/gltf")
local Bytes = require("@formats/core/Bytes")
local Types = require("@formats/Types")
local Picks = require("@tests/gen/iqm_gltf")
local t = T.suite("codecs/sampler")
local S = Types.Scene
local function acc(list: { number }, comps: number): Types.Accessor
local b = buffer.create(#list * 4)
for i, v in list do
buffer.writef32(b, (i - 1) * 4, v)
end
return S.accessor(b, "f32", comps, #list // comps)
end
local function near(a: number, b: number, eps: number?): boolean
return math.abs(a - b) < (eps or 1e-5)
end
do
local ch: Types.Channel = { node = 1, path = "translation", input = acc({ 0, 1, 3 }, 1), output = acc({ 0, 0, 0, 2, 4, 6, 2, 0, 0 }, 3), interpolation = "LINEAR" }
local s = assert(Sampler.channel(ch))
t:check(near(s(0.5)[1], 1) and near(s(0.5)[2], 2), "linear: halfway")
t:check(near(s(2)[1], 2) and near(s(2)[2], 2), "linear: second span")
t:check(near(s(-1)[2], 0) and near(s(9)[1], 2), "linear: clamped outside the keys")
ch.interpolation = "STEP"
local st = assert(Sampler.channel(ch))
t:check(near(st(0.99)[1], 0) and near(st(1)[1], 2), "step")
end
do
-- rotation: 0 -> 90 degrees about z, and a key stored with the opposite sign (shortest path)
local h = math.sqrt(0.5)
local ch: Types.Channel = { node = 1, path = "rotation", input = acc({ 0, 1, 2 }, 1), output = acc({ 0, 0, 0, 1, 0, 0, h, h, 0, 0, -h, -h }, 4), interpolation = "LINEAR" }
local s = assert(Sampler.channel(ch))
local q = s(0.5)
local a = 2 * math.acos(q[4])
t:check(near(a, math.pi / 4, 1e-4) and near(q[1] ^ 2 + q[2] ^ 2 + q[3] ^ 2 + q[4] ^ 2, 1), "slerp: 45 degrees, unit length")
local q2 = s(1.5)
t:check(near(math.abs(q2[3]), h, 1e-4), "slerp: the same orientation stored negated stays put")
end
do
-- cubic spline: in-tangent, value, out-tangent per key; p(t) for p0 = 0, p1 = 1, m0 = m1 = 0 is smoothstep
local ch: Types.Channel = { node = 1, path = "scale", input = acc({ 0, 2 }, 1), output = acc({ 9, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 9, 9, 9 }, 3), interpolation = "CUBICSPLINE" }
local s = assert(Sampler.channel(ch))
t:check(near(s(1)[1], 0.5) and near(s(0.5)[1], 3 * 0.25 ^ 2 - 2 * 0.25 ^ 3), "cubic: smoothstep")
t:check(near(s(2)[2], 1), "cubic: the last value")
-- tangents scale with the key spacing
local ch2: Types.Channel = { node = 1, path = "translation", input = acc({ 0, 2 }, 1), output = acc({ 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, 3), interpolation = "CUBICSPLINE" }
local s2 = assert(Sampler.channel(ch2))
-- h10(0.5) * dt * m0 = 0.125 * 2 * 1
t:check(near(s2(1)[1], 0.25), "cubic: tangents times the key spacing")
end
do
local ch: Types.Channel = { node = 2, path = "weights", input = acc({ 0, 1 }, 1), output = acc({ 1, 0, 0, 1 }, 1), interpolation = "LINEAR" }
local s = assert(Sampler.channel(ch))
local w = s(0.25)
t:check(#w == 2 and near(w[1], 0.75) and near(w[2], 0.25), "weights")
local anim: Types.Animation = { name = "a", channels = { ch, { node = 1, path = "translation", input = acc({ 0.5, 1 }, 1), output = acc({ 0, 0, 0, 1, 1, 1 }, 3), interpolation = "STEP" } } }
local times = Sampler.times(anim)
t:eq(table.concat(times, " "), "0 0.5 1", "times: sorted, unique")
local pose = Sampler.pose(S.new(), anim, 1)
t:check(pose[2].weights and pose[1].translation and near(pose[1].translation[1], 1), "pose")
t:check(Sampler.channel({ node = 1, path = "translation", input = acc({ 0, 1 }, 1), output = acc({ 1, 2 }, 1), interpolation = "LINEAR" }) == nil, "short output: nil")
t:check(Sampler.channel({ node = 1, path = "translation", input = {} :: any, output = {} :: any, interpolation = "LINEAR" }) == nil, "junk: nil")
end
do
-- a real file: sampling a glTF sample model's skin animation at its own keys returns the key values
local g = assert(Gltf.decode(Bytes.reader(buffer.fromstring(Picks[1].data)), { files = Picks[1].files }))
local ok, total = true, 0
for _, anim in g.animations do
for _, ch in anim.channels do
local s = assert(Sampler.channel(ch))
local IN, OUT = assert(S.reader(ch.input)), assert(S.reader(ch.output))
local comps = if ch.path == "rotation" then 4 else 3
for k = 0, ch.input.count - 1 do
local v = s(IN(k, 0))
for c = 1, comps do
ok = ok and near(v[c], OUT(k, c - 1), 1e-4)
end
total += 1
end
end
end
t:check(ok and total > 0, Picks[1].name .. ": samples at the keys are the keys (" .. total .. ")")
end
t:done()
+319
View File
@@ -0,0 +1,319 @@
-- model/iqm tests: assimp's mrfixit.iqm against assimp (meshes, triangles, vertices, materials, bind pose bounds), an
-- independent Python reader (joints, anims) and the bounds the IQM tool stored per frame (our decoded skeleton and
-- animation, skinned here, must reproduce them); writer round trips (mrfixit, glTF sample models with and without
-- skins) read back by our reader, by assimp and by the Python reader, whose skinning of our files must match ours;
-- errors; the fuzz no-throw pass. Fixtures: tools/fixtures/iqm.py.
local T = require("@tests/T")
local Iqm = require("@formats/model/iqm")
local Gltf = require("@formats/model/gltf")
local MeshOps = require("@formats/ops/MeshOps")
local Sampler = require("@formats/codecs/model/Sampler")
local Mat4 = require("@formats/codecs/model/Mat4")
local Bytes = require("@formats/core/Bytes")
local Err = require("@formats/core/Err")
local Types = require("@formats/Types")
local Cases = require("@tests/gen/iqm_cases")
local Picks = require("@tests/gen/iqm_gltf")
local Xcheck = require("@tests/gen/iqm_xcheck")
local t = T.suite("iqm")
local S = Types.Scene
local function decode(data: any, opts: any?): (any, any)
local b = if type(data) == "string" then buffer.fromstring(data) else data
return Iqm.decode(Bytes.reader(b), opts)
end
t:eq(Iqm.name, "iqm", "name")
t:eq(Iqm.category, "model", "category")
t:check(Iqm.caps.decode and Iqm.caps.encode, "caps")
local function near(a: number, b: number, eps: number): boolean
return math.abs(a - b) <= eps * math.max(1, math.abs(a), math.abs(b))
end
-- the largest coordinate difference between two boxes
local function boxDiff(lo: { number }, hi: { number }, want: any): number
local d = 0
for k = 1, 3 do
d = math.max(d, math.abs(lo[k] - want.min[k]), math.abs(hi[k] - want.max[k]))
end
return d
end
local function boxNear(lo: { number }, hi: { number }, want: any, eps: number): boolean
for k = 1, 3 do
if not near(lo[k], want.min[k], eps) or not near(hi[k], want.max[k], eps) then
return false
end
end
return true
end
-- assimp's IQM root turns z-up into y-up: (x, y, z) -> (x, z, -y)
local function zUpToY(lo: { number }, hi: { number }): ({ number }, { number })
return { lo[1], lo[3], -hi[2] }, { hi[1], hi[3], -lo[2] }
end
local function counts(scene: any): (number, number, number)
local prims, tris, verts = 0, 0, 0
for _, m in scene.meshes do
for _, p in m.primitives do
prims += 1
tris += p.indices.count // 3
verts += p.attributes.POSITION.count
end
end
return prims, tris, verts
end
-- the bounding box of every mesh vertex, skinned with the scene's skins at time t of anim (nil: the rest pose)
local function skinnedBounds(scene: any, anim: any?, time: number): ({ number }, { number })
local pose = if anim then Sampler.pose(scene, anim, time) else nil
local parent = {}
for i, n in scene.nodes do
for _, c in n.children do
parent[c] = i
end
end
local world = {}
local function W(i: number): { number }
if world[i] then
return world[i]
end
local node = scene.nodes[i]
local over = pose and pose[i]
local m
if over then
m = Mat4.compose(over.translation or node.translation, over.rotation or node.rotation, over.scale or node.scale)
else
m = S.nodeMatrix(node)
end
if parent[i] then
m = S.mul(W(parent[i]), m)
end
world[i] = m
return m
end
local lo, hi = { math.huge, math.huge, math.huge }, { -math.huge, -math.huge, -math.huge }
for ni, node in scene.nodes do
local mesh = node.mesh and scene.meshes[node.mesh]
if mesh then
local skin = node.skin and scene.skins[node.skin]
local mats = {}
if skin then
local ibm = assert(S.reader(skin.inverseBindMatrices))
for j, jn in skin.joints do
local inv = {}
for k = 1, 16 do
inv[k] = ibm(j - 1, k - 1)
end
mats[j - 1] = S.mul(W(jn), inv)
end
end
local LINES = { points = true, lines = true, line_strip = true, line_loop = true }
for _, p in mesh.primitives do
if LINES[p.mode] then
continue
end
local P = assert(S.reader(p.attributes.POSITION))
local J = p.attributes.JOINTS_0 and S.reader(p.attributes.JOINTS_0)
local Wt = p.attributes.WEIGHTS_0 and S.reader(p.attributes.WEIGHTS_0)
for v = 0, p.attributes.POSITION.count - 1 do
local x, y, z = P(v, 0), P(v, 1), P(v, 2)
if skin and J and Wt then
local sx, sy, sz = 0, 0, 0
for c = 0, 3 do
local w = Wt(v, c)
if w > 0 then
local qx, qy, qz = Mat4.point(mats[J(v, c)], x, y, z)
sx, sy, sz = sx + w * qx, sy + w * qy, sz + w * qz
end
end
x, y, z = sx, sy, sz
else
x, y, z = Mat4.point(W(ni), x, y, z)
end
lo = { math.min(lo[1], x), math.min(lo[2], y), math.min(lo[3], z) }
hi = { math.max(hi[1], x), math.max(hi[2], y), math.max(hi[3], z) }
end
end
end
end
return lo, hi
end
local function xcheck(name: string): any
for _, x in Xcheck do
if x.name == name then
return x
end
end
return nil
end
-- ------------------------------------------------------------------------------------------------ mrfixit
local fixit = Cases[1]
local scene, err = decode(fixit.data)
t:check(scene, "mrfixit: decode " .. tostring(err))
do
local a, ref = fixit.assimp, fixit.ref
local prims, tris, verts = counts(scene)
t:eq(prims, a.meshes, "mrfixit: meshes (assimp)")
t:eq(tris, a.faces, "mrfixit: triangles (assimp)")
t:eq(verts, a.vertices, "mrfixit: vertices (assimp)")
t:eq(#scene.materials, a.materials, "mrfixit: materials (assimp)")
t:eq(scene.textures[scene.materials[1].baseColorTexture.texture].uri, "Body.jpg", "mrfixit: material string -> texture uri")
local lo, hi = MeshOps.bounds(MeshOps.merge(scene))
local ylo, yhi = zUpToY(lo, hi)
t:check(boxNear(ylo, yhi, a, 1e-4), string.format("mrfixit: bind pose bounds (assimp) %s / %s", table.concat(ylo, " "), table.concat(yhi, " ")))
t:eq(#scene.skins, 1, "mrfixit: one skin")
t:eq(#scene.skins[1].joints, ref.joints, "mrfixit: joints (Python reader)")
for j, n in scene.skins[1].joints do
t:eq(scene.nodes[n].name, ref.jointNames[j], "mrfixit: joint name " .. j)
end
t:eq(#scene.animations, #ref.anims, "mrfixit: animations")
t:eq(scene.animations[1].name, ref.anims[1].name, "mrfixit: animation name")
t:eq(scene.meta.source.animations[1].frames, ref.anims[1].frames, "mrfixit: frames")
local prim = scene.meshes[1].primitives[1]
t:check(prim.attributes.JOINTS_0 and prim.attributes.WEIGHTS_0.type == "unorm8", "mrfixit: blend indexes / weights")
t:check(prim.attributes.TANGENT and prim.attributes.TANGENT.components == 4, "mrfixit: tangents")
-- the bounds the IQM tool stored, from our skeleton + animation (and the Python reader's skinning agrees)
local fps = ref.anims[1].framerate
-- (the tool computed its bounds before quantizing the frames: up to 0.1% off the quantized animation)
local worst, worstPy = 0, 0
for f = 1, ref.frames, 5 do
local l, h = skinnedBounds(scene, scene.animations[1], (f - 1) / fps)
worst = math.max(worst, boxDiff(l, h, ref.stored[f]))
worstPy = math.max(worstPy, boxDiff(l, h, ref.skinned[f]))
t:check(boxDiff(ref.skinned[f].min, ref.skinned[f].max, ref.stored[f]) < 1e-2, "mrfixit: the Python reader reproduces the stored bounds, frame " .. f)
end
t:check(worst < 1e-2, "mrfixit: skinned bounds per frame match the IQM tool's (worst " .. worst .. ")")
t:check(worstPy < 1e-4, "mrfixit: skinned bounds per frame match the Python reader's (worst " .. worstPy .. ")")
t:check(scene.meta.source.bounds and #scene.meta.source.bounds == ref.frames, "mrfixit: bounds block read")
end
-- ------------------------------------------------------------------------------------------------ round trips
do
local out = assert(Iqm.encode(scene))
local back = assert(decode(out))
local p1, t1, v1 = counts(scene)
local p2, t2, v2 = counts(back)
t:check(p1 == p2 and t1 == t2 and v1 == v2, "round trip: counts")
-- positions and indices exact
local same = true
for mi, m in scene.meshes do
local a, b = m.primitives[1], back.meshes[mi].primitives[1]
t:check(buffer.tostring(a.attributes.POSITION.data) == buffer.tostring(b.attributes.POSITION.data), "round trip: positions exact, mesh " .. mi)
t:check(buffer.tostring(a.indices.data) == buffer.tostring(b.indices.data), "round trip: triangles exact, mesh " .. mi)
-- influences: the same (joint, weight) pairs (unused slots and their order may differ)
local ja, wa, jb, wb = S.reader(a.attributes.JOINTS_0), S.reader(a.attributes.WEIGHTS_0), S.reader(b.attributes.JOINTS_0), S.reader(b.attributes.WEIGHTS_0)
for v = 0, a.attributes.POSITION.count - 1 do
local inf = {}
for c = 0, 3 do
if (wa :: any)(v, c) > 0 then
inf[(ja :: any)(v, c)] = (inf[(ja :: any)(v, c)] or 0) + (wa :: any)(v, c)
end
end
for c = 0, 3 do
local w = (wb :: any)(v, c)
if w > 0 then
local j = (jb :: any)(v, c)
same = same and inf[j] ~= nil and math.abs(inf[j] - w) < 1.5 / 255
inf[j] = nil
end
end
same = same and next(inf) == nil
end
end
t:check(same, "round trip: the same influences")
t:eq(#back.skins[1].joints, #scene.skins[1].joints, "round trip: joints")
t:eq(back.meta.source.animations[1].frames, scene.meta.source.animations[1].frames, "round trip: frames")
local worst = 0
for _, time in { 0, 0.5, 1.5, 3 } do
local l1, h1 = skinnedBounds(scene, scene.animations[1], time)
local l2, h2 = skinnedBounds(back, back.animations[1], time)
for k = 1, 3 do
worst = math.max(worst, math.abs(l1[k] - l2[k]), math.abs(h1[k] - h2[k]))
end
end
t:check(worst < 2e-3, "round trip: the animation skins the same (worst " .. worst .. ")")
-- assimp and the Python reader on our file
local x = assert(xcheck("rt_mrfixit.iqm"), "xcheck rt_mrfixit")
t:eq(x.assimp.faces, fixit.assimp.faces, "round trip: assimp triangles")
t:eq(x.assimp.vertices, fixit.assimp.vertices, "round trip: assimp vertices")
t:check(boxNear(x.assimp.min, x.assimp.max, fixit.assimp, 1e-4), "round trip: assimp bounds")
local w2, w3 = 0, 0
for f, box in fixit.ref.skinned do
local mine = x.ref.skinned[f]
w2 = math.max(w2, boxDiff(mine.min, mine.max, box))
w3 = math.max(w3, boxDiff(x.ref.stored[f].min, x.ref.stored[f].max, mine))
end
t:check(w2 < 2e-3, "round trip: the Python reader skins our file like the original (worst " .. w2 .. ")")
t:check(w3 < 1e-4, "round trip: our bounds block matches the Python skinning (worst " .. w3 .. ")")
end
-- glTF sample models through the writer
for _, p in Picks do
local g = assert(Gltf.decode(Bytes.reader(buffer.fromstring(p.data)), { files = p.files }))
local out, e = Iqm.encode(g)
t:check(out, p.name .. ": encode " .. tostring(e))
local back = assert(decode(out))
local x = assert(xcheck("gltf_" .. p.name .. ".iqm"), "xcheck " .. p.name)
local _, tris, verts = counts(back)
t:eq(x.assimp.faces, tris, p.name .. ": assimp reads our triangles")
t:eq(x.assimp.vertices, verts, p.name .. ": assimp reads our vertices")
-- unskinned: the glTF scene's world bounds (skinned: IQM's rest pose is the bind pose, checked by the frames below)
local l2, h2 = skinnedBounds(back, nil, 0)
if #g.skins == 0 then
local lo, hi = skinnedBounds(g, nil, 0)
t:check(boxNear(l2, h2, { min = lo, max = hi }, 1e-4), p.name .. ": world bounds kept")
end
local yl, yh = zUpToY(l2, h2)
t:check(boxNear(yl, yh, x.assimp, 1e-3), p.name .. ": assimp bounds of our file")
if #g.skins > 0 and #g.animations > 0 then
local anim = x.ref.anims[1]
local worst = 0
for f = 1, x.ref.frames do
local l, h = skinnedBounds(g, g.animations[1], (f - 1) / anim.framerate)
local py = x.ref.skinned[f]
for k = 1, 3 do
worst = math.max(worst, math.abs(l[k] - py.min[k]), math.abs(h[k] - py.max[k]))
end
end
t:check(worst < 5e-3, p.name .. ": the Python reader skins our file like the glTF animation (worst " .. worst .. ")")
t:eq(#back.skins[1].joints, #g.skins[1].joints, p.name .. ": joints")
end
end
-- ------------------------------------------------------------------------------------------------ errors
do
local _, e1 = decode("INTERQUAKEMODEL\0")
t:check(e1 and e1.code == Err.TRUNCATED, "short: " .. tostring(e1))
local bad = buffer.fromstring(fixit.data)
buffer.writeu32(bad, 16, 1)
local _, e2 = decode(bad)
t:check(e2 and e2.code == Err.UNSUPPORTED, "version 1: " .. tostring(e2))
local cut = buffer.fromstring(string.sub(fixit.data, 1, 5000))
local _, e3 = decode(cut)
t:check(e3 and e3.code == Err.TRUNCATED, "cut: " .. tostring(e3))
local _, e4 = decode(fixit.data, { maxVertices = 100 })
t:check(e4 and e4.code == Err.LIMIT, "maxVertices: " .. tostring(e4))
local _, e5 = Iqm.encode({} :: any)
t:check(e5 and e5.code == Err.ARG, "encode junk")
local _, e6 = Iqm.encode(S.new())
t:check(e6 and e6.code == Err.ARG, "encode an empty scene: " .. tostring(e6))
t:eq(Iqm.sniff(Bytes.reader(buffer.fromstring(fixit.data))), 1, "sniff")
end
-- ------------------------------------------------------------------------------------------------ fuzz
do
local small = assert(Iqm.encode(assert(Gltf.decode(Bytes.reader(buffer.fromstring(Picks[2].data)), { files = Picks[2].files }))))
local samples = { small, string.sub(fixit.data, 1, 20000) }
t:fuzz("decode", function(b: buffer)
local s = Iqm.decode(Bytes.reader(b))
if s then
Iqm.encode(s)
end
return s
end, samples, { mutations = 24, keepHeader = 16 })
end
t:done()