Files
rosetta/tests/model/ms3d.luau
T

418 lines
14 KiB
Luau

-- model/ms3d tests: assimp's MilkShape 3D models against assimp; round trips; assimp reading ours.
-- Fixtures: tools/fixtures/ms3d.py.
local T = require("@tests/T")
local F = require("@rosetta")
local Ms3d = require("@rosetta/model/ms3d")
local Gltf = require("@rosetta/model/gltf")
local MeshOps = require("@rosetta/ops/MeshOps")
local Mat4 = require("@rosetta/codecs/model/Mat4")
local Bytes = require("@rosetta/core/Bytes")
local Err = require("@rosetta/core/Err")
local Types = require("@rosetta/Types")
local Cases = require("@tests/gen/ms3d_cases")
local Picks = require("@tests/gen/ms3d_gltf")
local Xcheck = require("@tests/gen/ms3d_xcheck")
local t = T.suite("ms3d")
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 Ms3d.decode(Bytes.reader(b), opts)
end
t:eq(Ms3d.name, "ms3d", "name")
t:eq(Ms3d.category, "model", "category")
t:check(Ms3d.caps.decode and Ms3d.caps.encode, "contract")
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
local function counts(scene: any): (number, number, number)
local prims, faces, corners = 0, 0, 0
for _, pl in S.flatten(scene) do
prims += 1
faces += pl.primitive.indices.count // 3
corners += pl.primitive.indices.count
end
return prims, faces, corners
end
local function bstr(lo: any, hi: any): string
if not lo then
return "-"
end
return string.format("(%.4g %.4g %.4g) (%.4g %.4g %.4g)", lo[1], lo[2], lo[3], hi[1], hi[2], hi[3])
end
local function boundsEq(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
-- the bones assimp makes: per group, the distinct strongest joints of its vertices
local function bones(scene: any): number
local n = 0
for _, pl in S.flatten(scene) do
local A = pl.primitive.attributes
if A.JOINTS_0 then
local J, W = S.reader(A.JOINTS_0) :: any, S.reader(A.WEIGHTS_0) :: any
local seen = {}
for v = 0, A.JOINTS_0.count - 1 do
local best, bw = -1, 0
for c = 0, 3 do
if W(v, c) > bw then
best, bw = J(v, c), W(v, c)
end
end
if best >= 0 and not seen[best] then
seen[best] = true
n += 1
end
end
end
end
return n
end
local scenes = {}
for i, c in Cases do
local scene, err = decode(c.data)
local a = c.assimp
t:check(scene, c.name .. ": decode: " .. tostring(err))
scenes[i] = scene
if scene and not a.failed then
local prims, faces, corners = counts(scene)
t:eq(prims, a.meshes, c.name .. ": meshes (assimp)")
t:eq(faces, a.faces, c.name .. ": faces (assimp)")
t:eq(corners, a.vertices, c.name .. ": corners (assimp)")
t:eq(math.max(#scene.materials, 1), a.materials, c.name .. ": materials (assimp)")
t:eq(#scene.animations, a.animations, c.name .. ": animations (assimp)")
t:eq(bones(scene), a.bones, c.name .. ": bones (assimp)")
if a.min then
local lo, hi = MeshOps.bounds(MeshOps.merge(scene))
t:check(lo and boundsEq(lo, hi, a, 1e-4), c.name .. ": world bounds (assimp) " .. bstr(lo, hi) .. " / " .. bstr(a.min, a.max))
end
end
end
t:note("%d files against assimp", #Cases)
local function skinnedPositions(s: any, time: number): { number }
local byNode: { [number]: { [string]: any } } = {}
for _, ch in (if s.animations[1] then s.animations[1].channels else {}) :: { any } do
byNode[ch.node] = byNode[ch.node] or {}
byNode[ch.node][ch.path] = ch
end
local function eval(ch: any, comps: number): { number }
local IN, OUT = S.reader(ch.input) :: any, S.reader(ch.output) :: any
local n = ch.input.count
local cubic = ch.interpolation == "CUBICSPLINE"
local function v(k: number): { number }
local e = if cubic then k * 3 + 1 else k
local r = {}
for q = 0, comps - 1 do
r[q + 1] = OUT(e, q)
end
if comps == 4 then
local l = math.sqrt(r[1] * r[1] + r[2] * r[2] + r[3] * r[3] + r[4] * r[4])
r = { r[1] / l, r[2] / l, r[3] / l, r[4] / l }
end
return r
end
if time <= IN(0, 0) then
return v(0)
end
for k = 0, n - 2 do
local t0, t1 = IN(k, 0), IN(k + 1, 0)
if time <= t1 then
local u = if t1 > t0 then (time - t0) / (t1 - t0) else 1
local a0, a1 = v(k), v(k + 1)
if comps == 4 and a0[1] * a1[1] + a0[2] * a1[2] + a0[3] * a1[3] + a0[4] * a1[4] < 0 then
a1 = { -a1[1], -a1[2], -a1[3], -a1[4] }
end
local r = {}
for q = 1, comps do
r[q] = a0[q] + (a1[q] - a0[q]) * u
end
if comps == 4 then
local l = math.sqrt(r[1] * r[1] + r[2] * r[2] + r[3] * r[3] + r[4] * r[4])
r = { r[1] / l, r[2] / l, r[3] / l, r[4] / l }
end
return r
end
end
return v(n - 1)
end
local world: { [number]: { number } } = {}
local function visit(i: number, parent: { number })
local n = s.nodes[i]
local chs = byNode[i]
local m = S.nodeMatrix(n)
if chs then
m = Mat4.compose(if chs.translation then eval(chs.translation, 3) else n.translation,
if chs.rotation then eval(chs.rotation, 4) else n.rotation, n.scale)
end
world[i] = S.mul(parent, m)
for _, c in n.children do
visit(c, world[i])
end
end
for _, r in s.roots do
visit(r, S.IDENTITY)
end
local out = {}
for _, pl in S.flatten(s) do
local prim = pl.primitive
local P = S.reader(prim.attributes.POSITION) :: any
local I = S.reader(prim.indices) :: any
local node = s.nodes[pl.node]
local skin = node.skin and s.skins[node.skin]
local J = prim.attributes.JOINTS_0 and S.reader(prim.attributes.JOINTS_0) :: any
local W = prim.attributes.WEIGHTS_0 and S.reader(prim.attributes.WEIGHTS_0) :: any
local IBM = skin and skin.inverseBindMatrices and S.reader(skin.inverseBindMatrices) :: any
local tri = {}
for k = 0, prim.indices.count - 1 do
local v = I(k, 0)
local x, y, z = P(v, 0), P(v, 1), P(v, 2)
local wx, wy, wz = 0, 0, 0
if skin and J and W then
for c = 0, 3 do
local w = W(v, c)
if w > 0 then
local j = J(v, c)
local ibm = {}
for q = 1, 16 do
ibm[q] = IBM(j, q - 1)
end
local m = S.mul(world[skin.joints[j + 1]], ibm)
local px, py, pz = Mat4.point(m, x, y, z)
wx, wy, wz = wx + px * w, wy + py * w, wz + pz * w
end
end
else
wx, wy, wz = Mat4.point(world[pl.node] or pl.matrix, x, y, z)
end
table.insert(tri, { wx, wy, wz })
if #tri == 3 then
-- each triangle's corners in a fixed order (a mirrored node's winding is flipped on write)
local function r(x: number): number
return math.floor(x * 100 + 0.5)
end
table.sort(tri, function(p: { number }, q: { number }): boolean
if r(p[1]) ~= r(q[1]) then
return r(p[1]) < r(q[1])
elseif r(p[2]) ~= r(q[2]) then
return r(p[2]) < r(q[2])
end
return r(p[3]) < r(q[3])
end)
for _, c in tri do
table.move(c, 1, 3, #out + 1, out)
end
tri = {}
end
end
end
return out
end
local function compare(a: any, b: any, label: string, eps: number)
local _, fa = counts(a)
local _, fb = counts(b)
t:eq(fb, fa, label .. ": triangles")
t:eq(#b.materials, #a.materials, label .. ": materials")
for k, m in a.materials do
local m2 = b.materials[k]
if m2 then
local ok = true
for q = 1, 4 do
ok = ok and near(m.baseColor[q], m2.baseColor[q], 1e-6)
end
t:check(ok, label .. ": material " .. k .. " colour")
local ta = m.baseColorTexture and a.textures[m.baseColorTexture.texture]
local tb = m2.baseColorTexture and b.textures[m2.baseColorTexture.texture]
t:check((ta == nil) == (tb == nil) and (ta == nil or ta.uri == nil or ta.uri == tb.uri), label .. ": material " .. k .. " texture")
end
end
t:eq(#b.skins, if #a.skins > 0 or #a.animations > 0 then 1 else 0, label .. ": skins (animated nodes become joints)")
if a.skins[1] then
t:eq(#b.skins[1].joints, #a.skins[1].joints, label .. ": joints")
end
for _, time in { 0, 0.3, 0.75, 1.2, 2.5, 4 } do
local pa, pb = skinnedPositions(a, time), skinnedPositions(b, time)
local ok = #pa == #pb
local worst = 0
if ok then
for k = 1, #pa do
local d = math.abs(pa[k] - pb[k]) / math.max(1, math.abs(pa[k]))
worst = math.max(worst, d)
end
end
t:check(ok and worst <= eps, string.format("%s: posed vertices at %.2f s (worst %.3g)", label, time, worst))
if #a.animations == 0 then
break
end
end
end
for i, c in Cases do
local scene = scenes[i]
if scene then
local out, err = Ms3d.encode(scene)
t:check(out, c.name .. ": encode: " .. tostring(err))
local back, berr = decode(out :: buffer)
t:check(back, c.name .. ": decode ours: " .. tostring(berr))
if back then
compare(scene, back, c.name, 1e-6)
t:eq(#back.nodes, #scene.nodes, c.name .. ": nodes")
local same = true
for mi, m in scene.meshes do
same = same and back.meshes[mi].primitives[1].attributes.POSITION.count == m.primitives[1].attributes.POSITION.count
end
t:check(same, c.name .. ": vertices kept")
end
end
end
local gltfScenes = {}
local ng = 0
for gi, g in Picks do
local scene, gerr = Gltf.decode(Bytes.reader(buffer.fromstring(g.data)), { files = g.files })
t:check(scene, g.name .. ": glTF decode: " .. tostring(gerr))
if scene then
gltfScenes[gi] = scene
local out, err = Ms3d.encode(scene)
t:check(out, g.name .. ": encode: " .. tostring(err))
local back, berr = decode(out :: buffer)
t:check(back, g.name .. ": decode ours: " .. tostring(berr))
if back then
local lines = false
for _, m in scene.meshes do
for _, p in m.primitives do
lines = lines or p.mode == "points" or p.mode == "lines" or p.mode == "line_strip" or p.mode == "line_loop"
end
end
if not lines then
-- weights are stored in percent
compare(scene, back, "glTF " .. g.name, if #scene.skins > 0 then 1e-2 else 1e-4)
end
ng += 1
end
end
end
t:note("%d reference files and %d glTF models through our writer and back", #Cases, ng)
local nx = 0
for _, x in Xcheck do
local a = x.assimp
t:check(not a.failed, x.name .. ": assimp reads our file")
local scene = if x.case then scenes[x.case] else gltfScenes[x.gltf]
if scene and not a.failed then
local back = decode(Ms3d.encode(scene) :: buffer)
local prims, faces, corners = counts(back)
t:eq(a.meshes, prims, x.name .. ": assimp meshes of our file")
t:eq(a.faces, faces, x.name .. ": assimp faces of our file")
t:eq(a.vertices, corners, x.name .. ": assimp corners of our file")
t:eq(a.bones, bones(back), x.name .. ": assimp bones of our file")
t:eq(a.animations, if #back.nodes > #back.meshes then 1 else 0, x.name .. ": assimp animations of our file (it makes one for any joint)")
t:eq(a.materials, math.max(#back.materials, 1), x.name .. ": assimp materials of our file")
if a.min then
local lo, hi = MeshOps.bounds(MeshOps.merge(back))
t:check(lo and boundsEq(lo, hi, a, 1e-4), x.name .. ": assimp world bounds of our file " .. bstr(lo, hi) .. " / " .. bstr(a.min, a.max))
end
nx += 1
end
end
t:note("%d of our files read back by assimp", nx)
do
local byName = {}
for i, c in Cases do
byName[c.name] = scenes[i]
end
local jeep = byName["assimp/jeep1.ms3d"]
if jeep then
local m = jeep.materials[1]
t:check(m.baseColorTexture and jeep.textures[1].uri ~= nil and jeep.textures[1].data == nil, "texture -> uri, not loaded: " .. tostring(jeep.textures[1].uri))
t:eq(#jeep.meshes, 7, "jeep: 7 groups")
t:eq(jeep.meta.up, "y", "MilkShape is Y up")
t:check(jeep.meta.source.vertexVersion == nil, "jeep: no sub-versioned blocks")
end
local mats = byName["assimp/twospheres_withmats.ms3d"]
if mats then
t:eq(mats.meta.source.commentVersion, 1, "comment block")
t:eq(mats.meta.source.vertexVersion, 3, "vertex extras subversion 3")
t:check(mats.materials[2].extras.ms3d.shininess > 0, "shininess in extras")
end
local gl = gltfScenes[3]
if gl then
local out = Ms3d.encode(gl) :: buffer
local back = decode(out)
t:check(back.skins[1] and #back.skins[1].joints == #gl.skins[1].joints, "joints written")
local W = back.meshes[1].primitives[1].attributes.WEIGHTS_0
local R = S.reader(W) :: any
local split = false
for v = 0, W.count - 1 do
split = split or (R(v, 1) > 0.05)
t:check(math.abs(R(v, 0) + R(v, 1) + R(v, 2) + R(v, 3) - 1) < 1e-6, "weights sum to 1")
end
t:check(split, "vertex extras: second bone weights")
back.nodes[1].extras.ms3d.comment = "the root"
back.materials[1] = F.Types.Scene.material("m")
back.materials[1].extras = { ms3d = { comment = "a material" } }
back.meta.source.comment = "made by a test"
local again = decode(Ms3d.encode(back) :: buffer)
t:eq(again.nodes[1].extras.ms3d.comment, "the root", "joint comment")
t:eq(again.materials[1].extras.ms3d.comment, "a material", "material comment")
t:eq(again.meta.source.comment, "made by a test", "model comment")
end
local s = F.load(Cases[1].data)
t:check(s and s.kind == "scene" and s.meta.source.format == "ms3d", "F.load detects MS3D")
local viaApi = F.save(s, nil, { format = "ms3d" })
t:check(viaApi and buffer.readstring(viaApi, 0, 10) == "MS3D000000", "F.save format ms3d")
end
do
local data = Cases[2].data
local _, e1 = decode(string.sub(data, 1, 100))
t:check(e1 and e1.code == Err.TRUNCATED, "truncated: " .. tostring(e1))
local _, e2 = decode("MS3D000000\9\0\0\0")
t:check(e2 and e2.code == Err.UNSUPPORTED, "version 9: " .. tostring(e2))
local _, e3 = decode("MS3D000001")
t:check(e3 and e3.code == Err.CORRUPT, "bad magic: " .. tostring(e3))
local _, e4 = decode(data, { maxVertices = 10 })
t:check(e4 and e4.code == Err.LIMIT, "maxVertices: " .. tostring(e4))
local _, e5 = Ms3d.encode({} :: any)
t:check(e5 and e5.code == Err.ARG, "encode junk")
t:eq(Ms3d.sniff(Bytes.reader(buffer.fromstring(data))), 1, "sniff")
end
do
local samples = {}
for _, c in Cases do
if #c.data < 40000 then
table.insert(samples, c.data)
end
end
for gi, g in gltfScenes do
if gi <= 4 then
table.insert(samples, buffer.tostring(Ms3d.encode(g) :: buffer))
end
end
t:fuzz("decode", function(b: buffer)
local s = Ms3d.decode(Bytes.reader(b))
if s then
Ms3d.encode(s)
MeshOps.merge(s)
end
return s
end, samples, { mutations = 12, keepHeader = 14 })
end
t:done()