Files
rosetta/tests/model/vrml.luau
T

411 lines
18 KiB
Luau

-- model/vrml tests: assimp's WRL test models (HelloWorld, Wuson, the MotionCaptureROM animation), scenes and glTF
-- samples written by VTK's VRML exporter, and hand-written feature files (PROTO, DEF / USE, per-face colours and
-- separate indices, primitives, ElevationGrid, Extrusion, Switch, LOD, lights, viewpoints, ROUTE animations,
-- PixelTexture, Inline), against VTK's vtkVRMLImporter (polygons, points, world bounds where VTK's transforms are
-- right) and exact expectations; the writer: round trips of every case and of glTF sample models (world triangles,
-- materials, textures, cameras, lights, animation samples), VTK reading our files like the originals; errors; the
-- fuzz no-throw pass. Fixtures: tools/fixtures/vrml.py.
local T = require("@tests/T")
local F = require("@rosetta")
local Vrml = require("@rosetta/model/vrml")
local Gltf = require("@rosetta/model/gltf")
local Bytes = require("@rosetta/core/Bytes")
local Err = require("@rosetta/core/Err")
local Types = require("@rosetta/Types")
local Mat4 = require("@rosetta/codecs/model/Mat4")
local Deflate = require("@rosetta/codecs/compress/Deflate")
local C = require("@tests/model/_vrml_common")
local Cases = require("@tests/gen/vrml_cases")
local GltfCases = require("@tests/gen/vrml_gltf")
local Xcheck = require("@tests/gen/vrml_xcheck")
local t = T.suite("vrml")
local near = C.near
local function decode(data: any, opts: any?): (any, any)
local b = if type(data) == "string" then buffer.fromstring(data) else data
return Vrml.decode(Bytes.reader(b), opts)
end
t:eq(Vrml.name, "vrml", "name")
t:eq(Vrml.category, "model", "category")
t:check(Vrml.caps.decode and Vrml.caps.encode, "contract")
-- ------------------------------------------------------------------------------------------------ reference files
local scenes, byName = {}, {}
local checked = { vtk = 0, bounds = 0, none = 0 }
for i, c in Cases do
local scene, err = decode(c.data, { files = c.files, triangulate = false })
t:check(scene, c.name .. ": decode: " .. tostring(err))
if not scene then
continue
end
scenes[i], byName[c.name] = scene, scene
local s = C.stats(scene)
local v = c.vtk
if v.failed or v.actors == 0 then
checked.none += 1
continue
end
checked.vtk += 1
if not c.primitives then
t:eq(s.polys, v.polys, c.name .. ": polygons (VTK)")
end
t:eq(s.points, v.verts, c.name .. ": points (VTK)")
t:check((s.lines > 0) == (v.lines > 0), c.name .. ": lines (VTK)")
if c.vtkTransforms and v.min then
t:check(C.boundsNear(s.lo, s.hi, v.min, v.max, if c.primitives then 2e-2 else 1e-5), c.name .. ": world bounds (VTK) " .. C.fmt(s.lo, s.hi) .. " vs " .. C.fmt(v.min, v.max))
checked.bounds += 1
end
end
t:note("%d files: %d against VTK (%d with bounds), %d VTK cannot read", #Cases, checked.vtk, checked.bounds, checked.none)
-- ------------------------------------------------------------------------------------------------ exact expectations
local function prims(scene: any): { any }
local out = {}
for _, pl in Types.Scene.flatten(scene) do
table.insert(out, pl)
end
return out
end
do
local hw = byName["assimp/HelloWorld.wrl"]
if hw then
t:eq(#hw.cameras, 1, "HelloWorld: viewpoint")
t:eq(hw.cameras[1].name, "ViewUpClose", "HelloWorld: viewpoint DEF name")
t:eq(hw.meta.source.title, "Hello World!", "HelloWorld: WorldInfo title")
t:eq(hw.meta.source.skipped.Text, 1, "HelloWorld: Text skipped")
local tex = hw.textures[1]
t:check(tex and tex.uri == "earth-topo.png" and tex.data and tex.mime == "image/png", "HelloWorld: texture from files")
t:eq(hw.materials[1].name, "MaterialOffWhite", "HelloWorld: material DEF name")
t:check(near(hw.materials[1].baseColor[1], 0.980392, 1e-6), "HelloWorld: diffuseColor")
end
local mc = byName["assimp/MotionCaptureROM.WRL"]
if mc then
t:eq(#mc.animations, 1, "MotionCaptureROM: one TimeSensor animation")
local a = mc.animations[1]
t:check(#a.channels >= 20, "MotionCaptureROM: channels " .. #a.channels)
local tmax = 0
for _, ch in a.channels do
tmax = math.max(tmax, buffer.readf32(ch.input.data, (ch.input.count - 1) * 4))
end
t:check(near(tmax, 45.27, 1e-4), "MotionCaptureROM: key times x cycleInterval " .. tmax)
end
-- PROTO expansion, DEF / USE of a Shape (one mesh, two nodes)
local pu = byName["feature/feat_proto_use.wrl"]
if pu then
local s = C.stats(pu)
t:eq(#pu.meshes, 3, "proto: meshes (two instances + a shared shape)")
t:eq(s.prims, 4, "proto: placed primitives")
t:check(C.boundsNear(s.lo, s.hi, { -1, -0.5, -0.5 }, { 3.5, 6, 0.5 }, 1e-4), "proto: bounds " .. C.fmt(s.lo, s.hi))
local cols = {}
for _, m in pu.materials do
table.insert(cols, string.format("%g %g %g", m.baseColor[1], m.baseColor[2], m.baseColor[3]))
end
table.sort(cols)
t:eq(table.concat(cols, ", "), "0 1 0, 1 0 0", "proto: IS fields (instance value, default)")
end
-- separate indices, per-face normals / colours, ccw FALSE, solid FALSE
local ix = byName["feature/feat_indices.wrl"]
if ix then
local p1 = ix.meshes[1].primitives[1]
t:eq(p1.attributes.POSITION.count, 8, "indices: corners split by normal / colour / texture index")
t:eq(p1.faces.count, 2, "indices: two quads")
local N, Col, Tx = p1.attributes.NORMAL, p1.attributes.COLOR_0, p1.attributes.TEXCOORD_0
t:check(buffer.readf32(N.data, 8) == 1 and buffer.readf32(Col.data, 0) == 1 and buffer.readf32(Col.data, 8) == 0, "indices: face 1 normal / colour")
t:check(buffer.readf32(Tx.data, 4) == 1, "indices: t flipped (0 -> 1)")
-- ccw FALSE: the first face is written reversed (0 3 2 1)
t:eq(buffer.readu32(p1.indices.data, 4), 3, "indices: ccw FALSE reverses the winding")
local m = ix.materials[p1.material]
t:check(m.doubleSided and m.alphaMode == "blend" and near(m.baseColor[4], 0.75, 1e-6), "indices: solid FALSE, transparency")
t:check(m.extras.vrml.shininess == 0.5 and m.extras.vrml.specularColor[1] == 1, "indices: Phong terms in extras")
local p2 = ix.meshes[2].primitives[1]
t:eq(p2.attributes.POSITION.count, 5, "indices: per-vertex colour indices")
t:check(p2.material == nil, "indices: no appearance, no material")
end
-- primitives: exact bounds, unit normals
local pr = byName["feature/feat_primitives.wrl"]
if pr then
local s = C.stats(pr)
t:check(C.boundsNear(s.lo, s.hi, { -4.5, -2, -1.5 }, { 9, 2, 1.5 }, 1e-6), "primitives: bounds " .. C.fmt(s.lo, s.hi))
local box = pr.meshes[1].primitives[1]
t:eq(box.attributes.POSITION.count, 24, "Box: 24 vertices")
t:eq(box.indices.count, 36, "Box: 12 triangles")
local sph = pr.meshes[2].primitives[1]
local ok = true
local P, N = sph.attributes.POSITION, sph.attributes.NORMAL
for v = 0, P.count - 1 do
for k = 0, 2 do
ok = ok and near(buffer.readf32(P.data, (v * 3 + k) * 4) / 1.5, buffer.readf32(N.data, (v * 3 + k) * 4), 1e-5)
end
end
t:check(ok, "Sphere: normals = position / radius")
-- outward winding: the Box's first triangle faces +z
local function faceNormal(prim: any, tri: number): { number }
local function p(i: number): { number }
local v = buffer.readu32(prim.indices.data, (tri * 3 + i) * 4)
return { buffer.readf32(prim.attributes.POSITION.data, v * 12), buffer.readf32(prim.attributes.POSITION.data, v * 12 + 4), buffer.readf32(prim.attributes.POSITION.data, v * 12 + 8) }
end
local a, b, c = p(0), p(1), p(2)
local e1, e2 = { b[1] - a[1], b[2] - a[2], b[3] - a[3] }, { c[1] - a[1], c[2] - a[2], c[3] - a[3] }
return { e1[2] * e2[3] - e1[3] * e2[2], e1[3] * e2[1] - e1[1] * e2[3], e1[1] * e2[2] - e1[2] * e2[1] }
end
t:check(faceNormal(box, 0)[3] > 0, "Box: counter-clockwise front faces")
local cyl = pr.meshes[4].primitives[1]
local last = cyl.indices.count // 3 - 1
t:check(faceNormal(cyl, last)[2] < 0, "Cylinder: bottom cap faces down")
t:check(faceNormal(cyl, 0)[3] < 0 or faceNormal(cyl, 0)[1] ~= 0, "Cylinder: side faces outwards")
end
local ge = byName["feature/feat_grid_extrusion.wrl"]
if ge then
local grid, ex = ge.meshes[1].primitives[1], ge.meshes[2].primitives[1]
t:eq(grid.attributes.POSITION.count, 12, "ElevationGrid: vertices")
t:eq(grid.faces.count, 6, "ElevationGrid: quads")
t:eq(ex.attributes.POSITION.count, 16, "Extrusion: closed cross section shares its seam")
t:eq(ex.faces.count, 14, "Extrusion: sides + caps")
local s = C.stats(ge)
t:check(near(s.hi[2], 3, 1e-6) and near(s.hi[3], 4, 1e-6), "ElevationGrid: heights and spacing")
end
local sc = byName["feature/feat_scene.wrl"]
if sc then
t:eq(sc.meta.source.title, "feature scene", "scene: title")
t:eq(#sc.cameras, 1, "scene: viewpoint")
t:check(near(sc.cameras[1].yfov, 0.9, 1e-9) and sc.cameras[1].name == "Cam", "scene: fieldOfView")
local types = {}
for _, l in sc.lights do
types[l.type] = l
end
t:check(types.directional and types.point and types.spot, "scene: three light types")
t:check(types.point.range == 10 and near(types.spot.outerCone, 0.6, 1e-9) and near(types.spot.innerCone, 0.4, 1e-9), "scene: radius, cones")
-- the directional light's node turns -z onto its direction (0, -1, -1)
for _, n in sc.nodes do
if n.light and sc.lights[n.light].type == "directional" then
local m = Mat4.fromQuat(n.rotation)
local x, y, z = Mat4.point(m, 0, 0, -1)
t:check(near(x, 0, 1e-6) and near(y, -math.sqrt(0.5), 1e-6) and near(z, -math.sqrt(0.5), 1e-6), "scene: light direction")
end
end
t:eq(#sc.animations, 1, "scene: animation")
local a = sc.animations[1]
t:eq(a.name, "Clock", "scene: animation named after its TimeSensor")
t:eq(#a.channels, 2, "scene: translation + rotation channels")
local tr = a.channels[1].path == "translation" and a.channels[1] or a.channels[2]
t:check(near(buffer.readf32(tr.input.data, 8), 4, 1e-6), "scene: key 1 x cycleInterval 4")
-- translation keys move the outer node: key + center
t:check(near(buffer.readf32(tr.output.data, 12), 1, 1e-6) and near(buffer.readf32(tr.output.data, 16), 2, 1e-6), "scene: translation key + center")
-- PixelTexture: the first row of the file is the bottom one
local img
for _, tex in sc.textures do
img = img or tex.image
end
t:check(img and img.width == 2 and buffer.readu8(img.pixels, 2) == 255 and buffer.readu8(img.pixels, 8) == 255 and buffer.readu8(img.pixels, 9) == 0, "scene: PixelTexture pixels")
-- Switch whichChoice 1: the sphere only; LOD: the first level; Inline: part.wrl
local s = C.stats(sc)
t:check(near(s.lo[2], -3.1, 1e-6), "scene: Inline file placed")
-- center / scaleOrientation: the line set's first point (0, 0, 0) under T C R SR S -SR -C
local mover = nil
for _, pl in prims(sc) do
if pl.primitive.mode == "lines" then
mover = pl
end
end
if mover then
local sr = Mat4.axisAngle(0, 0, 1, math.deg(0.5))
local m = Mat4.mul(Mat4.translation(1, 0, 0), Mat4.mul(Mat4.fromQuat(sr), Mat4.mul(Mat4.scaling(1, 2, 1), Mat4.mul(Mat4.fromQuat({ -sr[1], -sr[2], -sr[3], sr[4] }), Mat4.translation(-1, 0, 0)))))
local ok = true
for k = 1, 16 do
ok = ok and near(mover.matrix[k], m[k], 1e-6)
end
t:check(ok, "scene: Transform center / scaleOrientation")
end
t:eq(sc.meta.unit, 1, "scene: metres")
end
end
-- ------------------------------------------------------------------------------------------------ writer
local function compare(a: any, b: any, label: string)
local sa, sb = C.stats(a), C.stats(b)
t:eq(sb.prims, sa.prims, label .. ": placed primitives")
t:eq(sb.polys, sa.polys, label .. ": faces")
t:eq(sb.lines, sa.lines, label .. ": line segments")
t:eq(sb.points, sa.points, label .. ": points")
if sa.prims > 0 and sa.lo[1] <= sa.hi[1] then
t:check(C.boundsNear(sa.lo, sa.hi, sb.lo, sb.hi, 1e-5), label .. ": bounds " .. C.fmt(sa.lo, sa.hi) .. " vs " .. C.fmt(sb.lo, sb.hi))
t:check(near(sa.area, sb.area, 1e-4), string.format("%s: area %.6g / %.6g", label, sa.area, sb.area))
end
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")
t:check((m.baseColorTexture == nil) == (m2.baseColorTexture == nil), label .. ": material " .. k .. " texture")
end
end
t:eq(#b.cameras, #a.cameras, label .. ": cameras")
t:eq(#b.lights, #a.lights, label .. ": lights")
end
local rt = 0
for i, c in Cases do
local a = scenes[i]
if a then
local files = {}
local out, err = Vrml.encode(a, { files = files, name = "rt.wrl" })
t:check(out, c.name .. ": encode: " .. tostring(err))
if out then
local b, e2 = decode(out, { files = files, triangulate = false })
t:check(b, c.name .. ": re-decode: " .. tostring(e2))
if b then
compare(a, b, c.name .. " (round trip)")
t:eq(#b.animations, #a.animations, c.name .. " (round trip): animations")
rt += 1
end
end
end
end
-- glTF samples through VRML: world triangles, materials, textures, cameras, lights, animation samples
local gltfScenes = {}
for i, c in GltfCases do
local g = Gltf.decode(Bytes.reader(buffer.fromstring(c.data)), { files = c.files })
if not g then
continue
end
gltfScenes[i] = g
local files = {}
local out, err = Vrml.encode(g, { files = files, name = "model.wrl" })
t:check(out, c.name .. ": encode: " .. tostring(err))
if not out then
continue
end
local b = decode(out, { files = files })
t:check(b, c.name .. ": decode our VRML")
if not b then
continue
end
local ga = C.stats(g)
local sb = C.stats(b)
t:check(C.boundsNear(ga.lo, ga.hi, sb.lo, sb.hi, 1e-5), c.name .. ": bounds through VRML " .. C.fmt(ga.lo, ga.hi) .. " vs " .. C.fmt(sb.lo, sb.hi))
t:check(near(ga.area, sb.area, 1e-4), c.name .. ": area through VRML")
t:eq(sb.points, ga.points, c.name .. ": points through VRML")
t:eq(#b.cameras, #g.cameras, c.name .. ": cameras through VRML")
for k, tex in g.textures do
local t2 = b.textures[k]
if tex.data and t2 then
t:check(t2.data and buffer.tostring(t2.data) == buffer.tostring(tex.data), c.name .. ": texture " .. k .. " bytes")
end
end
-- animations: the translation / rotation / scale channels, sampled at their keys
local want = 0
for _, a in g.animations do
for _, ch in a.channels do
if ch.path ~= "weights" then
want += 1
end
end
end
local got = 0
for _, a in b.animations do
got += #a.channels
end
t:eq(got, want, c.name .. ": animation channels through VRML")
rt += 1
end
t:note("%d round trips", rt)
-- VTK reads our files like the originals
local xc = 0
for _, x in Xcheck do
local v = x.vtk
local src = if x.case then scenes[x.case] else (if x.gltf then gltfScenes[x.gltf] else nil)
local srcCase = if x.case then Cases[x.case] else nil
if src and not v.failed and v.actors > 0 then
local s = C.stats(src)
if not (srcCase and srcCase.primitives) then
-- our IndexedFaceSets keep polygons; VTK counts them
t:eq(v.polys, s.polys, x.name .. ": polygons (VTK reads our file)")
end
t:eq(v.verts, s.points, x.name .. ": points (VTK reads our file)")
if x.vtkTransforms and v.min and s.lo[1] <= s.hi[1] then
t:check(C.boundsNear(s.lo, s.hi, v.min, v.max, 1e-4), x.name .. ": bounds (VTK reads our file) " .. C.fmt(s.lo, s.hi) .. " vs " .. C.fmt(v.min, v.max))
end
xc += 1
end
end
t:note("%d of our files read by VTK", xc)
-- ------------------------------------------------------------------------------------------------ api, options, errors
do
local text = Cases[1].data
t:eq(F.detect(text), "vrml", "F.detect")
local s = F.load(text, { files = Cases[1].files })
t:check(s and s.meta.source.format == "vrml", "F.load")
local gz = Deflate.gzip(text)
local sg = decode(gz :: buffer)
t:check(sg and #sg.meshes == #s.meshes, "gzipped .wrz")
local tri = decode(Cases[1].data)
t:check(tri and tri.meshes[1].primitives[1].mode == "triangles", "triangulated by default")
local seg = decode(Cases[1].data, { segments = 8 })
t:check(seg and seg.meshes[1].primitives[1].attributes.POSITION.count < s.meshes[1].primitives[1].attributes.POSITION.count, "segments option")
local _, e1 = decode("#VRML V1.0 ascii\nSeparator { }")
t:check(e1 and e1.code == Err.UNSUPPORTED, "VRML 1.0: " .. tostring(e1))
local _, e2 = decode("#VRML V2.0 utf8\nShape { geometry Box { size 1 1 1 }")
t:check(e2 and e2.code == Err.CORRUPT, "unclosed node: " .. tostring(e2))
local _, e3 = decode("#VRML V2.0 utf8\nShape { appearance USE Nothing }")
t:check(e3 and e3.code == Err.CORRUPT, "USE of an undefined name: " .. tostring(e3))
local _, e4 = decode('#VRML V2.0 utf8\nWorldInfo { title "open')
t:check(e4 and e4.code == Err.TRUNCATED, "unterminated string: " .. tostring(e4))
local deep = "#VRML V2.0 utf8\n" .. string.rep("Group { children [ ", 300) .. string.rep("] } ", 300)
local _, e5 = decode(deep)
t:check(e5 and e5.code == Err.LIMIT, "nesting limit: " .. tostring(e5))
local _, e6 = decode("#VRML V2.0 utf8\nShape { geometry ElevationGrid { xDimension 5000 zDimension 5000 } }", { maxVertices = 1000 })
t:check(e6 and e6.code == Err.LIMIT, "maxVertices: " .. tostring(e6))
local _, e7 = Vrml.encode({} :: any)
t:check(e7 and e7.code == Err.ARG, "encode junk")
-- a quad written as one polygon and read back as one
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 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 quad = Types.Scene.fromPrimitive({ attributes = { POSITION = p }, indices = ind, faces = faces, mode = "polygons" }, "quad")
local q = decode(Vrml.encode(quad) :: buffer, { triangulate = false })
t:check(q and q.meshes[1].primitives[1].faces.count == 1 and q.nodes[1].name == "quad", "a quad stays one polygon, names kept")
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 = Vrml.decode(Bytes.reader(b), { files = {} })
if s then
Vrml.encode(s)
end
return s
end, samples, { mutations = 16, keepHeader = 16 })
end
t:done()