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

+87
View File
@@ -0,0 +1,87 @@
-- archive/pak tests: Quake ("PACK") and SiN ("SPAK") archives written by tools/fixtures/pak.py list the entries an
-- independent Python reader sees (names, sizes, data CRCs); our writer produces the same bytes as the Python writer
-- for the same files and round-trips; conversion from a tar; errors; the fuzz pass. Fixtures: tools/fixtures/pak.py.
local T = require("@tests/T")
local F = require("@formats")
local Pak = require("@formats/archive/pak")
local Bytes = require("@formats/core/Bytes")
local Crc32 = require("@formats/core/Crc32")
local Err = require("@formats/core/Err")
local Fx = require("@tests/gen/pak")
local t = T.suite("pak")
t:eq(Pak.name, "pak", "name")
t:check(Pak.caps.decode and Pak.caps.encode, "caps")
for _, c in Fx do
local a, err = Pak.decode(Bytes.reader(buffer.fromstring(c.data)))
t:check(a, c.name .. ": " .. tostring(err))
local list = a:list()
t:eq(#list, #c.entries, c.name .. ": entry count")
for i, w in c.entries do
t:eq(list[i].name, w.name, c.name .. ": name " .. i)
t:eq(list[i].size, w.size, c.name .. ": size " .. w.name)
t:eq(Crc32.of((a:read(w.name))), w.crc, c.name .. ": data " .. w.name)
end
t:eq(a.meta.source.variant, c.variant, c.name .. ": variant")
if #c.data > 12 then
t:eq(F.detect(c.data), "pak", c.name .. ": F.detect")
end
-- the writer: same layout as the Python writer
local n = Pak.new(c.variant)
for _, f in c.files do
n:add(f.name, f.data)
end
local out = n:write() :: buffer
if c.layoutDefault then
t:check(buffer.tostring(out) == c.data, c.name .. ": bytes identical to the Python writer")
end
local back = Pak.decode(Bytes.reader(out))
t:eq(#back:list(), #c.files, c.name .. ": round trip count")
-- rewriting a decoded archive keeps its variant
local again = F.save(a) :: buffer
t:eq(buffer.readstring(again, 0, 4), if c.variant == "sin" then "SPAK" else "PACK", c.name .. ": F.save keeps the variant")
end
-- a sub-range reader, conversion from another archive, errors
do
local c = Fx[1]
local big = buffer.create(#c.data + 7)
buffer.writestring(big, 7, c.data)
local a = Pak.decode(Bytes.reader(big, 7, #c.data))
t:check(a and Crc32.of((a:read(c.entries[2].name))) == c.entries[2].crc, "decode from a sub-range")
local tar = F.format("tar").new()
tar:add("dir/", "", { dir = true })
tar:add("dir/x.txt", "x")
local p = F.load(F.save(tar, nil, { format = "pak" }) :: buffer)
t:check(p.format == "pak" and #p:list() == 1 and buffer.tostring(p:read("dir/x.txt")) == "x", "tar -> pak (directories dropped)")
local _, e1 = Pak.decode(Bytes.reader(buffer.fromstring(string.sub(c.data, 1, #c.data - 10))))
t:check(e1 and e1.code == Err.TRUNCATED, "truncated: " .. tostring(e1))
local bad = buffer.fromstring(c.data)
buffer.writeu32(bad, 8, 65)
local _, e2 = Pak.decode(Bytes.reader(bad))
t:check(e2 and e2.code == Err.CORRUPT, "directory size: " .. tostring(e2))
local long = Pak.new()
long:add(string.rep("n", 56), "x")
local _, e3 = long:write()
t:check(e3 and e3.code == Err.ARG, "a 56-byte name does not fit")
local _, e4 = Pak.encode({ kind = "image" })
t:check(e4 and e4.code == Err.ARG, "encode a non-archive")
end
local samples = {}
for _, c in Fx do
table.insert(samples, c.data)
end
t:fuzz("decode", function(b: buffer)
local a = Pak.decode(Bytes.reader(b))
if a then
for _, e in a:list() do
a:read(e.name)
end
a:write()
end
return a
end, samples, { mutations = 40 })
t:done()
+93
View File
@@ -0,0 +1,93 @@
-- codecs/model/Rig tests: morph targets and weights animations from frames, skeletons in local and world space
-- (node TRS, inverse bind matrices against Mat4), influences (top four, normalised), joint TRS animations; and
-- Pixels.palette.
local T = require("@tests/T")
local Rig = require("@formats/codecs/model/Rig")
local Mat4 = require("@formats/codecs/model/Mat4")
local Pixels = require("@formats/codecs/image/Pixels")
local Types = require("@formats/Types")
local t = T.suite("codecs/rig")
local Scene = Types.Scene
local function f32s(list: { number }): buffer
local b = buffer.create(#list * 4)
for i, v in list do
buffer.writef32(b, (i - 1) * 4, v)
end
return b
end
local function near(a: number, b: number): boolean
return math.abs(a - b) < 1e-5
end
-- morph
do
local base = { 0, 0, 0, 1, 0, 0 }
local prim: Types.Primitive = { attributes = { POSITION = Scene.accessor(f32s(base), "f32", 3, 2) }, mode = "points" }
local frames = { f32s(base), f32s({ 0, 1, 0, 1, 2, 0 }), f32s({ 0, 0, 3, 1, 0, 3 }) }
t:check(Rig.morph(prim, frames), "morph")
local tg = prim.targets :: any
t:eq(#tg, 3, "one target per frame")
t:eq(buffer.readf32(tg[2].POSITION.data, 4), 1, "delta y")
t:eq(buffer.readf32(tg[3].POSITION.data, 20), 3, "delta z")
t:check(not Rig.morph(prim, { buffer.create(4) }), "short frame refused")
local s = Scene.new()
s.nodes[1] = { children = {}, mesh = 1 }
Rig.morphAnimation(s, 1, 3, { { name = "a", first = 2, last = 3, fps = 5 }, { name = "none", first = 9, last = 12 } })
t:eq(#s.animations, 1, "out-of-range range skipped")
local ch = s.animations[1].channels[1]
t:eq(ch.path, "weights", "weights channel")
t:eq(ch.input.count, 2, "two keys")
t:check(near(buffer.readf32(ch.input.data, 4), 0.2), "fps")
t:eq(buffer.readf32(ch.output.data, 1 * 4), 1, "key 1 -> target 2")
t:eq(buffer.readf32(ch.output.data, (3 + 2) * 4), 1, "key 2 -> target 3")
end
-- skeleton
do
local q = Mat4.axisAngle(0, 0, 1, 90)
local joints = {
{ name = "root", parent = 0, translation = { 1, 0, 0 }, rotation = q },
{ name = "child", parent = 1, translation = { 0, 2, 0 }, rotation = { 0, 0, 0, 1 } },
}
local s = Scene.new()
local nodes, skin = Rig.skeleton(s, joints, "local")
t:eq(#nodes, 2, "two joint nodes")
t:eq(s.roots[1], nodes[1], "root")
t:eq(s.nodes[nodes[1]].children[1], nodes[2], "parenting")
local ibm = s.skins[skin].inverseBindMatrices :: Types.Accessor
-- child world = T(1,0,0) R90 T(0,2,0): its origin is at (-1, 0, 0); the inverse maps it back to 0
local inv = {}
for k = 1, 16 do
inv[k] = buffer.readf32(ibm.data, (16 + k - 1) * 4)
end
local x, y, z = Mat4.point(inv, -1, 0, 0)
t:check(near(x, 0) and near(y, 0) and near(z, 0), "inverse bind matrix")
-- the same joints given in world space give the same local TRS
local w = Scene.new()
local wn = Rig.skeleton(w, {
joints[1],
{ name = "child", parent = 1, translation = { -1, 0, 0 }, rotation = q },
}, "world")
local c = w.nodes[wn[2]]
t:check(near(c.translation[1], 0) and near(c.translation[2], 2) and near(c.rotation[4], 1), "world -> local")
local j, wt = Rig.influences({ { 0, 1 }, { 1, 0.2, 2, 0.6, 3, 0.1, 4, 0.05, 5, 0.05 } })
t:eq(buffer.readu16(j.data, 8), 2, "largest weight first")
t:check(near(buffer.readf32(wt.data, 16) + buffer.readf32(wt.data, 20) + buffer.readf32(wt.data, 24) + buffer.readf32(wt.data, 28), 1), "normalised")
t:eq(buffer.readf32(wt.data, 0), 1, "single influence")
local ai = Rig.animation(s, "wave", nodes, { 0, 0.5 }, { [2] = { rotation = { 0, 0, 0, 1, 0, 0, 1, 0 }, translation = { 0 } } })
t:eq(#s.animations[ai].channels, 1, "short track skipped, rotation kept")
t:eq(s.animations[ai].channels[1].node, nodes[2], "channel node")
end
-- palette
do
local pal = Pixels.palette(buffer.fromstring("\1\2\3\4\5\6"), 0, 2)
t:eq(buffer.readu32(pal, 4), 0xFF060504, "rgb triples")
t:eq(buffer.readu32(pal, 8), 0xFF000000, "missing entries black")
t:eq(buffer.readu32(Pixels.palette(buffer.fromstring("\1\2\3"), 0, 1, true), 0), 0xFF010203, "bgr")
t:eq(buffer.readu32(Pixels.palette(buffer.create(3), -5, 1), 0), 0xFF000000, "bad base")
end
t:done()
+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()
+315
View File
@@ -0,0 +1,315 @@
-- model/lwo tests: assimp's LightWave test models (LWO2, LWOB, Modo LXOB) against assimp (meshes per layer and
-- surface, polygons, corners, materials, world bounds); layer hierarchy and pivots, UV / colour / normal maps,
-- surfaces and image blocks; a hand-built LWO2 (VMAD splits, MORF / SPOT targets, weight maps, lines, points, skipped
-- curves, PTCH flag, derived surface, XREF clip); errors; the fuzz no-throw pass. Fixtures: tools/fixtures/lwo.py.
local T = require("@tests/T")
local Lwo = require("@formats/model/lwo")
local MeshOps = require("@formats/ops/MeshOps")
local Bytes = require("@formats/core/Bytes")
local Err = require("@formats/core/Err")
local Types = require("@formats/Types")
local Cases = require("@tests/gen/lwo_cases")
local t = T.suite("lwo")
local function decode(data: any, opts: any?): (any, any)
local b = if type(data) == "string" then buffer.fromstring(data) else data
return Lwo.decode(Bytes.reader(b), opts)
end
t:eq(Lwo.name, "lwo", "name")
t:eq(Lwo.category, "model", "category")
t:check(Lwo.caps.decode and not Lwo.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
-- assimp's counts: one mesh per (layer, surface), polygons, corners
local function counts(scene: any): (number, number, number)
local meshes, faces, corners = 0, 0, 0
for _, m in scene.meshes do
local mats = {}
for _, p in m.primitives do
if not mats[p.material] then
mats[p.material] = true
meshes += 1
end
local n = if p.indices then p.indices.count else p.attributes.POSITION.count
corners += n
faces += if p.mode == "polygons" then p.faces.count elseif p.mode == "lines" then n // 2 elseif p.mode == "points" then n else n // 3
end
end
return meshes, faces, corners
end
local function find(name: string): any
for _, c in Cases do
if c.name == name then
return c
end
end
return nil
end
-- ------------------------------------------------------------------------------------------------ assimp
local checked, scenes = 0, {}
for i, c in Cases do
local a = c.assimp
local scene, err = decode(c.data, { triangulate = false })
if a.failed then
t:note("%s: assimp rejects it; we: %s", c.name, if scene then "decoded" else tostring(err))
else
t:check(scene, c.name .. ": decode: " .. tostring(err))
if scene then
scenes[i] = scene
local meshes, faces, corners = counts(scene)
-- LXOB / LWOB files: assimp's material and surface handling differs (MATR tags, flattened detail polygons)
t:eq(meshes, a.meshes, c.name .. ": meshes (assimp)")
t:eq(faces, a.faces, c.name .. ": polygons (assimp)")
t:eq(corners, a.vertices, c.name .. ": corners (assimp)")
t:eq(#scene.materials, a.materials, c.name .. ": materials (assimp)")
if a.min then
local lo, hi = MeshOps.bounds(MeshOps.merge(scene))
local ok = lo ~= nil
for k = 1, 3 do
ok = ok and near(lo[k], a.min[k], 1e-4) and near(hi[k], a.max[k], 1e-4)
end
t:check(ok, string.format("%s: world bounds (assimp) %s / %s", c.name, if lo then table.concat(lo, " ") else "-", if hi then table.concat(hi, " ") else "-"))
end
-- triangulated: the same corners as triangles
local tri = decode(c.data)
t:check(tri and tri.meshes[1] and tri.meshes[1].primitives[1].mode ~= "polygons", c.name .. ": triangulated by default")
checked += 1
end
end
end
t:note("%d files checked against assimp", checked)
-- ------------------------------------------------------------------------------------------------ details
do
local c = find("models/LWO2/hierarchy.lwo")
local s = decode(c.data)
local byName = {}
for i, n in s.nodes do
byName[n.name] = i
end
local root, child0, grand = byName.RootOfHierarchy, byName.ChildOfRoot0, byName.GrandChildOfRoot0
t:check(root and child0 and grand and byName.ChildOfRoot1, "hierarchy: layer names")
t:check(table.find(s.roots, root) ~= nil and #s.roots == 1, "hierarchy: one root layer")
t:check(table.find(s.nodes[root].children, child0) ~= nil, "hierarchy: ChildOfRoot0 under RootOfHierarchy")
t:check(table.find(s.nodes[child0].children, grand) ~= nil, "hierarchy: GrandChildOfRoot0 under ChildOfRoot0")
local p = s.nodes[child0].extras.lwo.pivot
t:check(p and #p == 3, "hierarchy: pivot kept in extras")
-- weight maps -> _WEIGHT_n (no skeleton in LWO)
local prim = s.meshes[s.nodes[root].mesh].primitives[1]
t:check(prim.attributes._WEIGHT_0 and prim.attributes._WEIGHT_1, "hierarchy: weight maps as _WEIGHT_n")
t:check(prim.extras.lwo.maps._WEIGHT_0 ~= nil, "hierarchy: weight map names")
end
do
local c = find("models/LWO2/boxuv.lwo")
local s = decode(c.data)
local mat = s.materials[1]
t:check(mat.baseColorTexture, "boxuv: COLR image block -> baseColorTexture")
local tex = s.textures[mat.baseColorTexture.texture]
t:eq(tex.uri, "boxuv.png", "boxuv: texture uri")
t:eq(tex.mime, "image/png", "boxuv: texture mime")
local prim = s.meshes[1].primitives[1]
local uv = prim.attributes.TEXCOORD_0
t:check(uv and uv.count == prim.attributes.POSITION.count, "boxuv: TEXCOORD_0")
local inRange = true
local get = assert(Types.Scene.reader(uv))
for i = 0, uv.count - 1 do
local u, v = get(i, 0), get(i, 1)
inRange = inRange and u >= -1e-6 and u <= 1 + 1e-6 and v >= -1e-6 and v <= 1 + 1e-6
end
t:check(inRange, "boxuv: uvs in 0..1")
end
do
local c = find("models/LWO2/box_2vc_1unused.lwo")
local s = decode(c.data)
local any = false
for _, p in s.meshes[1].primitives do
any = any or (p.attributes.COLOR_0 ~= nil or p.attributes._COLOR_0 ~= nil)
end
t:check(any, "box_2vc: colour maps")
local mat = s.materials[1]
t:check(mat.extras.lwo.vcol ~= nil, "box_2vc: surface VCOL map name")
end
do
local c = find("models/LWO2/ModoExport_vertNormals.lwo")
local s = decode(c.data)
local prim = s.meshes[1].primitives[1]
t:check(prim.attributes.NORMAL, "Modo NORM map -> NORMAL")
local get = assert(Types.Scene.reader(prim.attributes.NORMAL))
local len = math.sqrt(get(0, 0) ^ 2 + get(0, 1) ^ 2 + get(0, 2) ^ 2)
t:check(near(len, 1, 1e-3), "Modo normals are unit length")
end
do
local c = find("models/LWO2/Subdivision.lwo")
local s = decode(c.data)
t:check(s.meshes[1].primitives[1].extras.lwo.subdivision == true, "PTCH cage flagged")
local lx = find("models/LXOB_Modo/sphereWithVertMap.lxo")
local sx = decode(lx.data)
t:eq(sx.meta.source.version, "LXOB", "LXOB version")
t:check(sx.meshes[1].primitives[1].attributes.NORMAL, "LXOB normals")
local lb = find("models/LWOB/sphere_with_mat_gloss_10pc.lwo")
local sb = decode(lb.data)
t:eq(sb.meta.source.version, "LWOB", "LWOB version")
t:check(sb.materials[1].extras.lwo.glos ~= nil, "LWOB glossiness")
end
-- ------------------------------------------------------------------------------------------------ hand-built LWO2
local function be16(n: number): string
return string.char(bit32.band(bit32.rshift(n, 8), 255), bit32.band(n, 255))
end
local function be32(n: number): string
return be16(bit32.rshift(n, 16)) .. be16(bit32.band(n, 0xFFFF))
end
local function f4(x: number): string
local b = buffer.create(4)
buffer.writef32(b, 0, x)
return be32(buffer.readu32(b, 0))
end
local function s0(s: string): string
s ..= "\0"
return if #s % 2 == 1 then s .. "\0" else s
end
local function chunk(id: string, body: string): string
return id .. be32(#body) .. body .. (if #body % 2 == 1 then "\0" else "")
end
local function sub(id: string, body: string): string
return id .. be16(#body) .. body .. (if #body % 2 == 1 then "\0" else "")
end
local function form(body: string): string
return "FORM" .. be32(#body + 4) .. "LWO2" .. body
end
local function quadFile(): string
local pts = ""
for _, p in { { 0, 0, 0 }, { 1, 0, 0 }, { 1, 1, 0 }, { 0, 1, 0 }, { 2, 0, 0 }, { 3, 0, 0 } } do
pts ..= f4(p[1]) .. f4(p[2]) .. f4(p[3])
end
local pols = "FACE" .. be16(4) .. be16(0) .. be16(1) .. be16(2) .. be16(3) -- 0: quad
.. be16(2) .. be16(4) .. be16(5) -- 1: a line
.. be16(1) .. be16(5) -- 2: a point
local curv = "CURV" .. be16(2) .. be16(0) .. be16(4) -- 3: skipped
local ptch = "PTCH" .. be16(3) .. be16(0) .. be16(1) .. be16(2) -- 4: a patch
local uv = "TXUV" .. be16(2) .. s0("UV")
for i, v in { { 0, 0 }, { 1, 0 }, { 1, 1 }, { 0, 1 } } do
uv ..= be16(i - 1) .. f4(v[1]) .. f4(v[2])
end
local vmad = "TXUV" .. be16(2) .. s0("UV") .. be16(0) .. be16(0) .. f4(0.5) .. f4(0.25) -- point 0 in polygon 0
local morf = "MORF" .. be16(3) .. s0("up") .. be16(2) .. f4(0) .. f4(0) .. f4(1)
local spot = "SPOT" .. be16(3) .. s0("moved") .. be16(1) .. f4(1) .. f4(2) .. f4(0)
local wght = "WGHT" .. be16(1) .. s0("bone") .. be16(3) .. f4(0.75)
local tags = s0("Base") .. s0("Child")
local base = s0("Base") .. s0("") .. sub("COLR", f4(1) .. f4(0) .. f4(0) .. be16(0)) .. sub("TRAN", f4(0.25) .. be16(0)) .. sub("SIDE", be16(3))
local blok = sub("IMAP", s0("\128") .. sub("CHAN", "COLR") .. sub("ENAB", be16(1))) .. sub("PROJ", be16(5)) .. sub("IMAG", be16(2)) .. sub("VMAP", s0("UV"))
local child = s0("Child") .. s0("Base") .. sub("LUMI", f4(0.5) .. be16(0)) .. sub("BLOK", blok)
local ptag = "SURF" .. be16(0) .. be16(0) .. be16(1) .. be16(1) .. be16(2) .. be16(1)
local ptag2 = "SURF" .. be16(0) .. be16(1)
return form(chunk("TAGS", tags) .. chunk("LAYR", be16(0) .. be16(0) .. f4(0.5) .. f4(0) .. f4(0) .. s0("Main")) .. chunk("PNTS", pts)
.. chunk("VMAP", uv) .. chunk("VMAP", morf) .. chunk("VMAP", spot) .. chunk("VMAP", wght)
.. chunk("POLS", pols) .. chunk("PTAG", ptag) .. chunk("VMAD", vmad) .. chunk("POLS", curv) .. chunk("POLS", ptch) .. chunk("PTAG", ptag2)
.. chunk("CLIP", be32(1) .. sub("STIL", s0("C:\\images\\Wood.PNG"))) .. chunk("CLIP", be32(2) .. sub("XREF", be32(1) .. s0("ref")))
.. chunk("SURF", base) .. chunk("SURF", child)
.. chunk("LAYR", be16(1) .. be16(0) .. f4(0.5) .. f4(1) .. f4(2) .. s0("Sub") .. be16(0)))
end
do
local data = quadFile()
local s, err = decode(data, { triangulate = false })
t:check(s, "hand-built: decode " .. tostring(err))
t:eq(#s.nodes, 2, "hand-built: two layers")
local main, subl = s.nodes[1], s.nodes[2]
t:eq(main.name, "Main", "hand-built: layer name")
t:check(table.find(main.children, 2) ~= nil and #s.roots == 1, "hand-built: Sub is a child of Main")
t:check(main.translation and main.translation[1] == 0.5, "hand-built: Main pivot translation")
t:check(subl.translation and subl.translation[2] == 1 and subl.translation[3] == -2, "hand-built: Sub pivot relative to Main, z negated")
t:eq(s.meta.source.skipped.CURV, 1, "hand-built: curve skipped and counted")
local mesh = s.meshes[main.mesh]
local modes = {}
for _, p in mesh.primitives do
modes[#modes + 1] = p.mode .. "/" .. p.material .. (if p.extras.lwo.subdivision then "/patch" else "")
end
t:eq(table.concat(modes, " "), "polygons/1 polygons/2/patch lines/2 points/2", "hand-built: primitives by surface and kind")
local quad = mesh.primitives[1]
t:eq(quad.attributes.POSITION.count, 4, "hand-built: quad vertices")
-- winding reversed, positions relative to the pivot, z negated
local idx = {}
for k = 0, 3 do
idx[k + 1] = buffer.readu32(quad.indices.data, k * 4)
end
local P = assert(Types.Scene.reader(quad.attributes.POSITION))
local UV = assert(Types.Scene.reader(quad.attributes.TEXCOORD_0))
t:eq(P(idx[1], 0), -0.5, "hand-built: x relative to the pivot")
t:eq(P(idx[2], 0), -0.5, "hand-built: winding reversed (second corner is point 3)")
t:eq(P(idx[2], 1), 1, "hand-built: second corner y")
t:eq(UV(idx[1], 0), 0.5, "hand-built: VMAD u")
t:eq(UV(idx[1], 1), 0.75, "hand-built: VMAD v flipped")
t:eq(UV(idx[3], 1), 0, "hand-built: VMAP v flipped (point 2: 1 -> 0)")
t:check(quad.targets and #quad.targets == 2, "hand-built: MORF + SPOT targets")
local T1 = assert(Types.Scene.reader(quad.targets[1].POSITION))
local T2 = assert(Types.Scene.reader(quad.targets[2].POSITION))
t:eq(T1(idx[3], 2), -1, "hand-built: MORF delta (z negated)")
t:eq(T2(idx[4], 1), 2, "hand-built: SPOT -> delta (point 1: y 0 -> 2)")
t:eq(mesh.weights and #mesh.weights, 2, "hand-built: mesh weights")
t:eq(mesh.extras.targetNames[2], "moved", "hand-built: target names")
local W = assert(Types.Scene.reader(quad.attributes._WEIGHT_0))
t:eq(W(idx[2], 0), 0.75, "hand-built: weight map value (point 3)")
local base, child = s.materials[1], s.materials[2]
t:eq(base.baseColor[1], 1, "hand-built: COLR")
t:check(near(base.baseColor[4], 0.75, 1e-6) and base.alphaMode == "blend", "hand-built: TRAN -> alpha")
t:check(base.doubleSided, "hand-built: SIDE 3")
t:check(child.doubleSided and child.baseColor[1] == 1, "hand-built: derived surface copies its source")
t:check(near(child.emissive[1], 0.5, 1e-6), "hand-built: LUMI -> emissive")
t:check(child.baseColorTexture and child.baseColorTexture.texCoord == 0, "hand-built: image block via XREF clip")
t:eq(s.textures[1].uri, "Wood.PNG", "hand-built: texture uri is the file name")
t:eq(s.textures[1].extras.lwo.path, "C:\\images\\Wood.PNG", "hand-built: full path in extras")
local tri = decode(data)
t:eq(tri.meshes[1].primitives[1].indices.count, 6, "hand-built: quad fan-triangulated")
-- triangulated quads keep the right facing: +z after the conversion (LightWave clockwise from -z)
local tp = tri.meshes[1].primitives[1]
local TP = assert(Types.Scene.reader(tp.attributes.POSITION))
local a, b, c = buffer.readu32(tp.indices.data, 0), buffer.readu32(tp.indices.data, 4), buffer.readu32(tp.indices.data, 8)
local ux, uy = TP(b, 0) - TP(a, 0), TP(b, 1) - TP(a, 1)
local vx, vy = TP(c, 0) - TP(a, 0), TP(c, 1) - TP(a, 1)
t:check(ux * vy - uy * vx < 0, "hand-built: facing kept (LightWave +z normal -> glTF -z)")
end
-- ------------------------------------------------------------------------------------------------ errors
do
local _, e1 = decode("FORM\0\0\0\4LWO3")
t:check(e1 and e1.code == Err.UNSUPPORTED, "LWO3: " .. tostring(e1))
local _, e2 = decode("FORM\0\0\0\4ILBM")
t:check(e2 and e2.code == Err.CORRUPT, "not LWO: " .. tostring(e2))
local _, e3 = decode("FORM")
t:check(e3 and e3.code == Err.TRUNCATED, "short: " .. tostring(e3))
local _, e4 = decode(quadFile(), { maxVertices = 3 })
t:check(e4 and e4.code == Err.LIMIT, "maxVertices: " .. tostring(e4))
local bad = form(chunk("PNTS", f4(0) .. f4(0) .. f4(0)) .. chunk("POLS", "FACE" .. be16(3) .. be16(0) .. be16(1) .. be16(2)))
local _, e5 = decode(bad)
t:check(e5 and e5.code == Err.CORRUPT, "point index out of range: " .. tostring(e5))
t:eq(Lwo.sniff(Bytes.reader(buffer.fromstring(quadFile()))), 1, "sniff")
t:eq(Lwo.sniff(Bytes.reader(buffer.fromstring("FORM\0\0\0\4AIFF"))), 0, "sniff AIFF")
end
-- ------------------------------------------------------------------------------------------------ fuzz
do
local samples = { quadFile() }
for _, c in Cases do
if #c.data < 30000 and #samples < 16 then
table.insert(samples, c.data)
end
end
t:fuzz("decode", function(b: buffer)
local s = Lwo.decode(Bytes.reader(b), { triangulate = false })
if s then
MeshOps.merge(s)
end
return s
end, samples, { mutations = 16, keepHeader = 12 })
end
t:done()
+314
View File
@@ -0,0 +1,314 @@
-- model/x tests: assimp's DirectX test models (text, binary 32-bit, MSZIP-compressed binary) and variants made by
-- tools/fixtures/x.py (binary with 64-bit floats, MSZIP-compressed text), against assimp (meshes per material, faces,
-- corners, materials, animations, bones, world bounds); frames, materials and textures, vertex colours, skins
-- (influences, inverse bind matrices against the bind pose), animation keys (the rotation convention against the
-- bind pose); an inline text file; errors; the fuzz no-throw pass. Fixtures: tools/fixtures/x.py.
local T = require("@tests/T")
local X = require("@formats/model/x")
local MeshOps = require("@formats/ops/MeshOps")
local Bytes = require("@formats/core/Bytes")
local Err = require("@formats/core/Err")
local Types = require("@formats/Types")
local Cases = require("@tests/gen/x_cases")
local t = T.suite("x")
local function decode(data: any, opts: any?): (any, any)
local b = if type(data) == "string" then buffer.fromstring(data) else data
return X.decode(Bytes.reader(b), opts)
end
t:eq(X.name, "x", "name")
t:eq(X.category, "model", "category")
t:check(X.caps.decode and not X.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
-- assimp's counts: meshes (one per material), faces, corners, bones (joints with weight in each mesh)
local function counts(scene: any): (number, number, number, number)
local meshes, faces, corners, bones = 0, 0, 0, 0
for _, m in scene.meshes do
for _, p in m.primitives do
meshes += 1
corners += p.indices.count
faces += if p.mode == "polygons" then p.faces.count else p.indices.count // 3
local J, W = p.attributes.JOINTS_0, p.attributes.WEIGHTS_0
if J and W then
local used = {}
local gj, gw = assert(Types.Scene.reader(J)), assert(Types.Scene.reader(W))
for k = 0, p.indices.count - 1 do
local v = buffer.readu32(p.indices.data, k * 4)
for c = 0, 3 do
if gw(v, c) > 0 then
used[gj(v, c)] = true
end
end
end
for _ in used do
bones += 1
end
end
end
end
return meshes, faces, corners, bones
end
local function bounds(scene: any): ({ number }?, { number }?)
local merged = MeshOps.merge(scene)
if not merged then
return nil, nil
end
return MeshOps.bounds(merged)
end
local function boundsMatch(lo: { number }?, hi: { number }?, a: any, eps: number): boolean
if not lo or not hi then
return false
end
for k = 1, 3 do
if not near(lo[k], a.min[k], eps) or not near(hi[k], a.max[k], eps) then
return false
end
end
return true
end
-- ------------------------------------------------------------------------------------------------ assimp
local scenes, byName = {}, {}
local checked = 0
for i, c in Cases do
byName[c.name] = c
local a = c.assimp
local scene, err = decode(c.data, { triangulate = false })
if a.failed then
t:note("%s: assimp rejects it; we: %s", c.name, if scene then "decoded" else tostring(err))
else
t:check(scene, c.name .. ": decode: " .. tostring(err))
scenes[c.name] = scene
local meshes, faces, corners, bones = counts(scene)
t:eq(meshes, a.meshes, c.name .. ": meshes (assimp)")
t:eq(faces + scene.meta.source.skippedFaces, a.faces, c.name .. ": faces (assimp)")
if scene.meta.source.skippedFaces == 0 then
t:eq(corners, a.vertices, c.name .. ": corners (assimp)")
end
t:eq(math.max(#scene.materials, 1), a.materials, c.name .. ": materials (assimp, its default when none)")
t:eq(#scene.animations, a.animations or 0, c.name .. ": animations (assimp)")
t:eq(bones, a.bones or 0, c.name .. ": bones (assimp)")
if a.min then
local lo, hi = bounds(scene)
t:check(boundsMatch(lo, hi, a, 1e-3), string.format("%s: world bounds (assimp) %s / %s", c.name, if lo then table.concat(lo, " ") else "-", if hi then table.concat(hi, " ") else "-"))
end
checked += 1
end
end
t:note("%d files checked against assimp", checked)
-- variants decode like their originals
for _, c in Cases do
if c.of then
local a, b = scenes[c.name], scenes[c.of]
if a and b then
local m1, f1, c1 = counts(a)
local m2, f2, c2 = counts(b)
t:check(m1 == m2 and f1 == f2 and c1 == c2, c.name .. ": same counts as " .. c.of)
local la, ha = bounds(a)
local lb, hb = bounds(b)
t:check(la and lb and boundsMatch(la, ha, { min = lb, max = hb }, 1e-5), c.name .. ": same bounds as " .. c.of)
t:eq(#a.animations, #b.animations, c.name .. ": same animations")
end
end
end
-- ------------------------------------------------------------------------------------------------ details
do
local s = scenes["models/kwxport_test_cubewithvcolors.x"]
local p = s.meshes[1].primitives[1]
t:check(p.attributes.COLOR_0 and p.attributes.COLOR_0.components == 4, "vertex colours -> COLOR_0")
t:eq(s.meta.source.encoding, "text", "text encoding")
local b = scenes["models/test_cube_binary.x"]
t:eq(b.meta.source.encoding, "binary", "binary encoding")
local z = scenes["models/test_cube_compressed.x"]
t:check(z.meta.source.compressed, "bzip")
local v = scenes["variant/test_cube_text.bin64.x"]
t:eq(v.meta.source.floatSize, 64, "64-bit floats")
end
do
-- textures: uri names, TEXCOORD_0
local s = scenes["models/test.x"]
local any = false
for _, m in s.materials do
if m.baseColorTexture then
local tex = s.textures[m.baseColorTexture.texture]
any = any or (type(tex.uri) == "string" and #tex.uri > 0)
end
end
t:check(any, "test.x: a texture file name")
t:check(s.meshes[1].primitives[1].attributes.TEXCOORD_0, "test.x: TEXCOORD_0")
end
do
-- skins: the inverse bind matrix of each joint times the joint's world bind matrix is about the same for all
-- joints (the mesh node's world matrix): checks the matrix layout and the handedness conversion together
local checkedSkins, consistent = 0, 0
for name, s in scenes do
for _, node in s.nodes do
if node.skin then
local skin = s.skins[node.skin]
local world = {}
local function worldOf(i: number): { number }
if world[i] then
return world[i]
end
local m = Types.Scene.nodeMatrix(s.nodes[i])
for pi, pn in s.nodes do
if table.find(pn.children, i) then
m = Types.Scene.mul(worldOf(pi), m)
break
end
end
world[i] = m
return m
end
local get = assert(Types.Scene.reader(skin.inverseBindMatrices))
local ref: { number }? = nil
local ok, total = 0, 0
for j, joint in skin.joints do
local inv = {}
for k = 1, 16 do
inv[k] = get(j - 1, k - 1)
end
local m = Types.Scene.mul(worldOf(joint), inv)
total += 1
if not ref then
ref = m
ok += 1
else
local same = true
for k = 1, 16 do
same = same and math.abs(m[k] - (ref :: any)[k]) < 1e-2 * math.max(1, math.abs(m[k]))
end
ok += if same then 1 else 0
end
end
t:note("%s: skin %d: bind pose consistent for %d / %d joints", name, node.skin, ok, total)
checkedSkins += 1
consistent += if ok >= total * 0.9 then 1 else 0
end
end
end
-- (anim_test.x's frames are not in the bind pose)
t:check(checkedSkins >= 4 and consistent >= checkedSkins * 0.7, string.format("skins consistent with the frames (%d / %d)", consistent, checkedSkins))
end
do
-- the rotation key convention: an animation's first rotation key mostly equals the bone's bind rotation
local same, total = 0, 0
for _, s in scenes do
for _, anim in s.animations do
for _, ch in anim.channels do
if ch.path == "rotation" then
local node = s.nodes[ch.node]
local r = node.rotation
if r then
local get = assert(Types.Scene.reader(ch.output))
local dot = 0
for k = 0, 3 do
dot += get(0, k) * r[k + 1]
end
total += 1
same += if math.abs(dot) > 0.999 then 1 else 0
end
end
end
end
end
t:check(total > 0 and same >= total * 0.5, string.format("first rotation keys match the bind pose (%d / %d)", same, total))
end
-- ------------------------------------------------------------------------------------------------ inline file
local CUBE = [[xof 0303txt 0032
// a quad and a triangle, two materials, one animated frame
Material Red { 1.0; 0.0; 0.0; 1.0;; 10.0; 0.5; 0.5; 0.5;; 0.0; 0.0; 0.0;; TextureFilename { "tex\\red.png"; } }
AnimTicksPerSecond { 100; }
Frame Root {
FrameTransformMatrix { 1,0,0,0, 0,1,0,0, 0,0,1,0, 1,2,3,1;; }
Mesh Shape {
5;
0;0;0;, 1;0;0;, 1;1;0;, 0;1;0;, 2;0;0;;
2;
4;0,1,2,3;,
3;1,4,2;;
MeshMaterialList { 2; 2; 0, 1;; { Red } Material Blue { 0;0;1;0.5;; 1; 0;0;0;; 0;0;0;; } }
MeshNormals { 1; 0;0;-1;; 2; 4;0,0,0,0;, 3;0,0,0;; }
MeshTextureCoords { 5; 0;0;, 1;0;, 1;1;, 0;1;, 0.5;0.5;; }
}
}
AnimationSet Move {
Animation { { Root } AnimationKey { 2; 2; 0; 3; 1;2;3;;, 100; 3; 1;2;5;;; } }
}
]]
do
local s, err = decode(CUBE, { triangulate = false })
t:check(s, "inline: " .. tostring(err))
t:eq(#s.nodes, 1, "inline: one frame")
local root = s.nodes[1]
t:check(root.translation and root.translation[1] == 1 and root.translation[3] == -3, "inline: translation, z negated")
t:eq(#s.materials, 2, "inline: global + inline material")
t:eq(s.materials[1].name, "Red", "inline: material name")
t:eq(s.textures[1].uri, "tex/red.png", "inline: texture uri (backslash -> slash)")
t:eq(s.materials[2].alphaMode, "blend", "inline: alpha < 1 -> blend")
local prims = s.meshes[1].primitives
t:eq(#prims, 2, "inline: one primitive per material")
t:eq(prims[1].material, 1, "inline: first face -> Red (referenced)")
t:eq(prims[2].material, 2, "inline: second face -> Blue")
t:eq(prims[1].faces.count, 1, "inline: the quad kept")
local N = assert(Types.Scene.reader(prims[1].attributes.NORMAL))
t:eq(N(0, 2), 1, "inline: normal z negated")
local anim = s.animations[1]
t:eq(anim.name, "Move", "inline: animation name")
local ch = anim.channels[1]
t:eq(ch.path, "translation", "inline: position key")
local ti, to = assert(Types.Scene.reader(ch.input)), assert(Types.Scene.reader(ch.output))
t:eq(ti(1, 0), 1, "inline: ticks -> seconds")
t:eq(to(1, 2), -5, "inline: key z negated")
local tri = decode(CUBE)
t:eq(tri.meshes[1].primitives[1].indices.count, 6, "inline: quad fan-triangulated")
end
-- ------------------------------------------------------------------------------------------------ errors
do
local _, e1 = decode("xof 0303txt 00")
t:check(e1 and e1.code == Err.TRUNCATED, "short: " .. tostring(e1))
local _, e2 = decode("xof 0303zzz 0032")
t:check(e2 and e2.code == Err.UNSUPPORTED, "encoding: " .. tostring(e2))
local _, e3 = decode("xof 0303txt 0016 Frame {}")
t:check(e3 and e3.code == Err.CORRUPT, "float size: " .. tostring(e3))
local _, e4 = decode("xof 0303txt 0032 Frame A { Mesh { 3; 0;0;0;, 1;0;0;, 0;1;0;; 1; 3; 0,1,7;; } }")
t:check(e4 and e4.code == Err.CORRUPT, "face index out of range: " .. tostring(e4))
local _, e5 = decode("xof 0303txt 0032 Frame A { ")
t:check(e5 and e5.code == Err.CORRUPT, "unterminated: " .. tostring(e5))
local _, e7 = decode("xof 0303txt 0032 Mesh { 33554431; 1; }")
t:check(e7 and e7.code == Err.TRUNCATED, "a vertex count past the data is refused before allocating: " .. tostring(e7))
local _, e6 = decode(CUBE, { maxValues = 10 })
t:check(e6 and e6.code == Err.LIMIT, "maxValues: " .. tostring(e6))
t:eq(X.sniff(Bytes.reader(buffer.fromstring(CUBE))), 1, "sniff")
end
-- ------------------------------------------------------------------------------------------------ fuzz
do
local samples = { CUBE }
for _, c in Cases do
if #c.data < 12000 then
table.insert(samples, c.data)
end
end
t:fuzz("decode", function(b: buffer)
local s = X.decode(Bytes.reader(b), { triangulate = false })
if s then
MeshOps.merge(s)
end
return s
end, samples, { mutations = 16, keepHeader = 16 })
end
t:done()