Files
rosetta/tests/model/gltf.luau
T

352 lines
16 KiB
Luau

-- model/gltf tests: Khronos glTF-Sample-Assets models (JSON with external / embedded buffers, GLB, sparse, interleaved,
-- quantized, morph targets, skins, animations, cameras, lights, texture transforms, material extensions), gltfpack
-- quantized variants and assimp's exporter output, against assimp (meshes, faces, bounds, animations, cameras,
-- lights) and trimesh (area, triangles); full-structure round trips through GLB, embedded .gltf and external files;
-- assimp / trimesh reading our output (gltf_xcheck); textures decoded lazily at the api layer; errors; the fuzz
-- no-throw pass. Fixtures: tools/fixtures/gltf.py.
local T = require("@tests/T")
local F = require("@rosetta")
local Gltf = require("@rosetta/model/gltf")
local MeshOps = require("@rosetta/ops/MeshOps")
local Bytes = require("@rosetta/core/Bytes")
local Err = require("@rosetta/core/Err")
local Types = require("@rosetta/Types")
local Cases = require("@tests/gen/gltf_cases")
local Xcheck = require("@tests/gen/gltf_xcheck")
local t = T.suite("gltf")
local function decode(data: any, opts: any?): (any, any)
local b = if type(data) == "string" then buffer.fromstring(data) else data
return Gltf.decode(Bytes.reader(b), opts)
end
t:eq(Gltf.name, "gltf", "name")
t:eq(Gltf.category, "model", "category")
t:check(Gltf.caps.decode and Gltf.caps.encode and table.find(Gltf.extensions, "glb"), "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 triArea(prim: any): number
local pos = prim.attributes.POSITION
local ind = prim.indices
if not ind then
return 0
end
local area = 0
local function P(i: number, k: number): number
return buffer.readf32(pos.data, (i * 3 + k) * 4)
end
for tri = 0, ind.count // 3 - 1 do
local a, b, c = buffer.readu32(ind.data, tri * 12), buffer.readu32(ind.data, tri * 12 + 4), buffer.readu32(ind.data, tri * 12 + 8)
local e1 = { P(b, 0) - P(a, 0), P(b, 1) - P(a, 1), P(b, 2) - P(a, 2) }
local e2 = { P(c, 0) - P(a, 0), P(c, 1) - P(a, 1), P(c, 2) - P(a, 2) }
local x, y, z = e1[2] * e2[3] - e1[3] * e2[2], e1[3] * e2[1] - e1[1] * e2[3], e1[1] * e2[2] - e1[2] * e2[1]
area += math.sqrt(x * x + y * y + z * z) / 2
end
return area
end
-- assimp's counts: one mesh per primitive, faces after strips / fans / loops are unrolled
local function counts(scene: any): (number, number)
local prims, faces = 0, 0
-- the meshes of the default scene (assimp imports that one only)
local meshes, seen = {}, {}
for _, pl in Types.Scene.flatten(scene) do
if not seen[pl.mesh] then
seen[pl.mesh] = true
table.insert(meshes, scene.meshes[pl.mesh])
end
end
for _, m in meshes do
for _, p in m.primitives do
prims += 1
local n = if p.indices then p.indices.count else p.attributes.POSITION.count
local mode = p.mode
faces += if mode == "triangles" then n // 3
elseif mode == "triangle_strip" or mode == "triangle_fan" then math.max(n - 2, 0)
elseif mode == "lines" then n // 2
elseif mode == "line_strip" then math.max(n - 1, 0)
elseif mode == "line_loop" then n
else n
end
end
return prims, faces
end
-- every value of two scenes equal (buffers by content), meta skipped
local function same(a: any, b: any, path: string, seen: { [any]: boolean }?, skip: { [string]: boolean }?): (boolean, string?)
local s = seen or {}
local sk = skip or { meta = true, extras = true }
if type(a) == "buffer" and type(b) == "buffer" then
return buffer.tostring(a) == buffer.tostring(b), path
end
if type(a) ~= "table" or type(b) ~= "table" then
if type(a) == "number" and type(b) == "number" then
return near(a, b, 1e-6), path
end
return a == b, path
end
if s[a] then
return true, nil
end
s[a] = true
for k, v in a do
if not sk[k] then
local ok, where = same(v, b[k], path .. "." .. tostring(k), s, sk)
if not ok then
return false, where
end
end
end
for k, v in b do
if not sk[k] and a[k] == nil and v ~= nil then
return false, path .. "." .. tostring(k) .. " (extra)"
end
end
return true, nil
end
local byName = {}
local checked = { assimp = 0, trimesh = 0, roundTrips = 0 }
for i, c in Cases do
byName[c.name] = c
local scene, err = decode(c.data, { files = c.files })
t:check(scene, c.name .. ": decode: " .. tostring(err))
local ref = if c.like then nil else c.assimp
local prims, faces = counts(scene)
if ref and not ref.failed then
t:eq(prims, ref.meshes, c.name .. ": meshes (assimp)")
t:eq(faces, ref.faces, c.name .. ": faces (assimp)")
if ref.animations then
t:eq(#scene.animations, ref.animations, c.name .. ": animations (assimp)")
end
if ref.cameras then
t:eq(#scene.cameras, ref.cameras, c.name .. ": cameras (assimp)")
end
if ref.lights then
t:eq(#scene.lights, ref.lights, c.name .. ": lights (assimp)")
end
checked.assimp += 1
end
-- trimesh: the whole scene in world space (quantized variants: against the original model, within quantization)
local tm = if c.like then byName[c.like].trimesh else c.trimesh
local merged = MeshOps.merge(scene)
local onlyTriangles = true -- trimesh reads TRIANGLES primitives only (not strips / fans)
for _, m in scene.meshes do
for _, p in m.primitives do
if p.mode == "triangle_strip" or p.mode == "triangle_fan" then
onlyTriangles = false
end
end
end
-- trimesh ignores sparse accessors
local sparse = string.find(c.data, "\"sparse\"", 1, true) ~= nil
if tm and not tm.failed and tm.faces > 0 and onlyTriangles and not sparse then
local eps = if c.like then 2e-3 else 1e-5
t:eq(merged.indices.count // 3, tm.faces, c.name .. ": triangles (trimesh)")
t:check(near(triArea(merged), tm.area, eps), string.format("%s: area %.6g, trimesh %.6g", c.name, triArea(merged), tm.area))
local lo, hi = MeshOps.bounds(merged)
for k = 1, 3 do
t:check(near(lo[k], tm.bounds[k], eps * 10) and near(hi[k], tm.bounds[k + 3], eps * 10), c.name .. ": bounds (trimesh)")
end
checked.trimesh += 1
end
-- round trips: GLB, embedded .gltf, external files
local glb, gerr = Gltf.encode(scene, { binary = true })
t:check(glb, c.name .. ": encode glb: " .. tostring(gerr))
local back = decode(glb)
t:check(back, c.name .. ": decode our glb")
local SKIP = { meta = true, extras = true, uri = true } -- embedded images lose their file names
local ok, where = same(scene, back, "scene", nil, SKIP)
t:check(ok, c.name .. ": glb round trip differs at " .. tostring(where))
local text = Gltf.encode(scene) :: buffer
local back2 = decode(text)
local ok2, where2 = same(scene, back2, "scene", nil, SKIP)
t:check(ok2, c.name .. ": embedded .gltf round trip differs at " .. tostring(where2))
local files = {}
local ext = Gltf.encode(scene, { external = true, files = files, name = "x.gltf" }) :: buffer
t:check(files["x.bin"] ~= nil or #scene.meshes == 0, c.name .. ": external .bin")
local back3 = decode(ext, { files = files })
local ok3, where3 = same(scene, back3, "scene", nil, SKIP)
t:check(ok3, c.name .. ": external .gltf round trip differs at " .. tostring(where3))
-- writing what we read back gives the same bytes
t:check(buffer.tostring(Gltf.encode(back, { binary = true }) :: buffer) == buffer.tostring(glb :: buffer), c.name .. ": writing is stable")
checked.roundTrips += 1
c.index = i
end
t:note("%d files: %d against assimp, %d against trimesh, %d round trips", #Cases, checked.assimp, checked.trimesh, checked.roundTrips)
-- the reference tools read our files like the originals
local nx = 0
for _, x in Xcheck do
local c = Cases[x.case]
local a, ca = x.assimp, c.assimp
if not ca.failed then
t:check(not a.failed, x.name .. ": assimp reads our file")
t:eq(a.faces, ca.faces, x.name .. ": assimp faces of our file (" .. c.name .. ")")
t:eq(a.meshes, ca.meshes, x.name .. ": assimp meshes of our file")
for k = 1, 3 do
t:check(near(a.min[k], ca.min[k], 1e-4) and near(a.max[k], ca.max[k], 1e-4), x.name .. ": assimp bounds of our file (" .. c.name .. ")")
end
t:eq(a.animations, ca.animations, x.name .. ": assimp animations of our file")
t:eq(a.cameras, ca.cameras, x.name .. ": assimp cameras of our file")
t:eq(a.lights, ca.lights, x.name .. ": assimp lights of our file")
end
if c.trimesh and not c.trimesh.failed and c.trimesh.faces > 0 and c.name ~= "MeshPrimitiveModes/glTF" and not string.find(c.data, "\"sparse\"", 1, true) then
t:check(not x.trimesh.failed and near(x.trimesh.area, c.trimesh.area, 1e-5) and x.trimesh.faces == c.trimesh.faces, x.name .. ": trimesh area of our file (" .. c.name .. ")")
end
nx += 1
end
t:note("%d of our files read back by assimp / trimesh like the originals", nx)
-- details
do
local function load(name: string): any
local c = byName[name]
return decode(c.data, { files = c.files })
end
local box = load("Box/glTF")
t:check(box.nodes[box.roots[1]].matrix ~= nil and box.meta.source.binary == false, "Box: a matrix node, JSON")
t:check(box.materials[1].metallic == 0 and near(box.materials[1].baseColor[1], 0.8, 1e-6), "Box: material")
local bt = load("BoxTextured/glTF")
local tex = bt.textures[1]
t:check(tex.uri == "CesiumLogoFlat.png" and tex.mime == "image/png" and buffer.tostring(tex.data) == byName["BoxTextured/glTF"].files["CesiumLogoFlat.png"], "BoxTextured: the image bytes from opts.files")
t:check(tex.sampler and tex.sampler.wrapS == "repeat" and tex.sampler.minFilter == "nearest_mipmap_linear", "sampler")
-- the api decodes textures lazily (PNG here)
local _, terrs = F.model.loadTextures(bt)
t:check(tex.image and tex.image.width == 256 and next(terrs) == nil, "F.model.loadTextures decodes the PNG")
local files = {}
local ext = Gltf.encode(bt, { external = true, files = files, name = "bt.gltf" }) :: buffer
t:check(files["CesiumLogoFlat.png"] ~= nil and string.find(buffer.tostring(ext), "\"uri\": \"CesiumLogoFlat.png\"", 1, true) ~= nil, "external images keep their file names")
local emb = load("BoxTextured/glTF-Embedded")
t:check(emb.textures[1].data and buffer.tostring(emb.textures[1].data) == buffer.tostring(tex.data), "embedded data: URI image = the external file")
local sparse = load("SimpleSparseAccessor/glTF-Embedded")
local pos = sparse.meshes[1].primitives[1].attributes.POSITION
local maxY = -math.huge
for v = 0, pos.count - 1 do
maxY = math.max(maxY, buffer.readf32(pos.data, v * 12 + 4))
end
t:eq(maxY, 4, "sparse values substituted (the raised vertices, max = the accessor max)")
local cams = load("Cameras/glTF")
t:check(#cams.cameras == 2 and cams.cameras[1].type == "perspective" and cams.cameras[2].type == "orthographic", "cameras")
local skin = load("SimpleSkin/glTF")
t:check(#skin.skins == 1 and #skin.skins[1].joints == 2 and skin.skins[1].inverseBindMatrices.matrix and skin.skins[1].inverseBindMatrices.components == 16, "skin")
t:check(#skin.animations == 1 and skin.animations[1].channels[1].path == "rotation", "skin animation")
local morph = load("SimpleMorph/glTF")
t:check(#morph.meshes[1].primitives[1].targets == 2 and morph.meshes[1].weights[1] == 0.5, "morph targets, weights")
local q = load("AnimatedMorphCube/glTF-Quantized")
local qp = q.meshes[1].primitives[1]
t:check(qp.attributes.NORMAL.type == "snorm8" and qp.targets and qp.targets[1].POSITION.type == "i16", "quantized normals / target deltas")
local unlit = load("UnlitTest/glTF-Binary")
t:check(unlit.materials[1].extensions and unlit.materials[1].extensions.KHR_materials_unlit ~= nil, "KHR_materials_unlit")
local es = load("EmissiveStrengthTest/glTF-Binary")
local strength = 0
for _, m in es.materials do
local e = m.extensions and m.extensions.KHR_materials_emissive_strength
if e then
strength = math.max(strength, e.emissiveStrength)
end
end
t:check(strength > 1, "KHR_materials_emissive_strength")
local cc = load("ClearCoatCarPaint/glTF-Binary")
local clear = cc.materials[1].extensions and cc.materials[1].extensions.KHR_materials_clearcoat
t:check(clear and clear.clearcoatFactor ~= nil, "KHR_materials_clearcoat")
local tt = load("TextureTransformTest/glTF")
local nt = 0
for _, m in tt.materials do
if m.baseColorTexture and m.baseColorTexture.transform then
nt += 1
end
end
t:check(nt >= 5, "KHR_texture_transform on " .. nt .. " materials")
local lights = load("PointLightIntensityTest/glTF-Binary")
t:check(#lights.lights > 0 and lights.lights[1].type == "point", "KHR_lights_punctual")
local ms = load("MultipleScenes/glTF")
t:check(#ms.meta.gltf.scenes == 2, "multiple scenes kept")
local modes = load("MeshPrimitiveModes/glTF")
local seen = {}
for _, m in modes.meshes do
for _, p in m.primitives do
seen[p.mode] = true
end
end
t:check(seen.points and seen.lines and seen.line_loop and seen.line_strip and seen.triangle_strip and seen.triangle_fan, "every primitive mode")
local inter = load("BoxInterleaved/glTF-Binary")
t:check(inter.meshes[1].primitives[1].attributes.NORMAL.count == 24, "interleaved (byteStride) attributes")
-- quantized output declares KHR_mesh_quantization
local qglb = Gltf.encode(q, { binary = true }) :: buffer
t:check(string.find(buffer.tostring(qglb), "KHR_mesh_quantization", 1, true) ~= nil, "KHR_mesh_quantization written")
-- a Scene made by hand (an OBJ-like mesh with u8 colours and polygons) writes and reads back
local s = Types.Scene.new()
local p = Types.Scene.accessor(nil, "f32", 3, 4)
for v, xyz in { { 0, 0, 0 }, { 1, 0, 0 }, { 1, 1, 0 }, { 0, 1, 0 } } do
for k = 1, 3 do
buffer.writef32(p.data, ((v - 1) * 3 + k - 1) * 4, xyz[k])
end
end
local col = Types.Scene.accessor(nil, "unorm8", 3, 4)
local faces = Types.Scene.accessor(nil, "u32", 1, 1)
buffer.writeu32(faces.data, 0, 4)
local ind = Types.Scene.accessor(nil, "u32", 1, 4)
for k = 0, 3 do
buffer.writeu32(ind.data, k * 4, k)
end
local s2 = Types.Scene.fromPrimitive({ attributes = { POSITION = p, COLOR_0 = col }, indices = ind, faces = faces, mode = "polygons" }, "quad")
local out = Gltf.encode(s2, { binary = true }) :: buffer
local back = decode(out)
t:check(back and back.meshes[1].primitives[1].indices.count == 6 and back.meshes[1].primitives[1].attributes.COLOR_0.type == "unorm8", "polygons fan-triangulated, unorm8 VEC3 colours (padded stride)")
-- through the api: the destination's extension picks GLB
local viaApi = F.save(s2, nil, { format = "glb" })
t:check(viaApi and buffer.readstring(viaApi, 0, 4) == "glTF", "F.save format glb")
local viaApi2 = F.save(s2, nil, { format = "gltf" })
t:check(viaApi2 and buffer.readstring(viaApi2, 0, 1) == "{", "F.save format gltf")
local loaded = F.load(viaApi)
t:check(loaded and loaded.kind == "scene" and loaded.meta.source.format == "gltf", "F.load detects GLB")
end
-- errors
do
local _, e = decode("{ not json")
t:check(e and (e.code == Err.CORRUPT or e.code == Err.TRUNCATED), "bad JSON: " .. tostring(e))
local _, e2 = decode('{"asset": {"version": "1.0"}}')
t:check(e2 and e2.code == Err.UNSUPPORTED, "glTF 1: " .. tostring(e2))
local _, e3 = decode('{"asset": {"version": "2.0"}, "extensionsRequired": ["EXT_meshopt_compression"]}')
t:check(e3 and e3.code == Err.UNSUPPORTED, "meshopt: " .. tostring(e3))
local c = byName["Box/glTF"]
local _, e4 = decode(c.data)
t:check(e4 and e4.code == Err.IO, "missing .bin: " .. tostring(e4))
local _, e5 = decode('{"asset": {"version": "2.0"}, "buffers": [{"byteLength": 4, "uri": "data:application/octet-stream;base64,AAAAAA=="}], "bufferViews": [{"buffer": 0, "byteLength": 4}], "accessors": [{"bufferView": 0, "componentType": 5126, "count": 2, "type": "SCALAR"}]}')
t:check(e5 and e5.code == Err.CORRUPT, "accessor past its view: " .. tostring(e5))
local glb = byName["Box/glTF-Binary"].data
local _, e6 = decode(string.sub(glb, 1, 100))
t:check(e6 and e6.code == Err.TRUNCATED, "truncated GLB: " .. tostring(e6))
local _, e7 = Gltf.encode({} :: any)
t:check(e7 and e7.code == Err.ARG, "encode junk")
local bad = Types.Scene.fromPrimitive({ attributes = { POSITION = Types.Scene.accessor(buffer.create(4), "f32", 3, 10) }, mode = "triangles" })
local _, e8 = Gltf.encode(bad)
t:check(e8 and e8.code == Err.ARG, "encode a short accessor: " .. tostring(e8))
end
-- fuzz
do
local samples = {}
for _, c in Cases do
if #c.data < 40000 then
table.insert(samples, c.data)
end
end
t:fuzz("decode", function(b: buffer)
local s = Gltf.decode(Bytes.reader(b))
if s then
Gltf.encode(s, { binary = true })
MeshOps.merge(s)
end
return s
end, samples, { mutations = 20 })
end
t:done()