merge master into ws/arch2 (ws/video2, ws/3d3, ws/game Archive.slice / collect)

This commit is contained in:
4DBug committed 2026-10-31 15:57:05 -05:00
commit 79fd3c05dd
213 files changed
+47945 -1533

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()
+241
View File
@@ -0,0 +1,241 @@
-- codecs/image/Bcn tests: random BC1..BC7 blocks (every BC7 and BC6H mode, the BC1 3-colour mode, odd sizes) against
-- Pillow's and Godot's (bcdec) decodes; BC6H floats against Godot; the encoders (BC1 / BC3 / BC4 / BC5) within reach
-- of Pillow's encoder PSNR, exact on flat blocks; argument errors; the fuzz no-throw pass. Fixtures: tools/fixtures/bcn.py.
local T = require("@tests/T")
local Bcn = require("@formats/codecs/image/Bcn")
local Half = require("@formats/codecs/image/Half")
local Fx = require("@tests/gen/bcn")
local t = T.suite("bcn")
-- the largest per-byte difference between two rgba8 buffers (channels: which of r, g, b, a count)
local function maxDiff(a: buffer, b: buffer, n: number, channels: { number }): (number, number)
local worst, at = 0, -1
for i = 0, n - 1 do
for _, c in channels do
local d = math.abs(buffer.readu8(a, i * 4 + c) - buffer.readu8(b, i * 4 + c))
if d > worst then
worst, at = d, i
end
end
end
return worst, at
end
local RGBA, RGB, RG, R = { 0, 1, 2, 3 }, { 0, 1, 2 }, { 0, 1 }, { 0 }
-- which channels each reference defines, and the allowed difference to it
local PILLOW: { [string]: { any } } = {
bc1 = { RGBA, 0 },
bc2 = { RGBA, 0 },
bc3 = { RGBA, 0 },
bc4 = { RGB, 0 },
bc5 = { RG, 0 },
bc5s = { RG, 1 }, -- Pillow interpolates the biased unsigned values with truncation
bc7 = { RGBA, 0 },
}
local stats = { pillow = 0, godot = 0 }
for _, c in Fx.cases do
local src = buffer.fromstring(c.data)
local px, err = Bcn.decode(c.kind, src, 0, c.w, c.h)
t:check(px, c.name .. ": " .. tostring(err))
local n = c.w * c.h
if Bcn.FLOAT[c.kind] then
t:eq(buffer.len(px), n * 16, c.name .. ": rgbaf32 size")
-- Godot (bcdec) floats: exact half values
local g = buffer.fromstring(c.godot)
local worst = 0
for i = 0, n - 1 do
for ch = 0, 2 do
local a, b = buffer.readf32(px, i * 16 + ch * 4), buffer.readf32(g, i * 16 + ch * 4)
local d = math.abs(a - b) / math.max(math.abs(b), 1e-3)
worst = math.max(worst, d)
end
end
t:check(worst < 1e-3, string.format("%s: relative error %g against Godot", c.name, worst))
stats.godot += 1
-- Pillow: 8-bit truncation of the clamped float (and no rounding term in its interpolation): within 1. Its
-- signed BC6H differs from bcdec and the spec (negative endpoints), so only BC6H UF16 is compared.
local p = buffer.fromstring(c.pillow)
local w2 = 0
for i = 0, n - 1 do
for ch = 0, 2 do
local v = math.clamp(buffer.readf32(px, i * 16 + ch * 4), 0, 1)
w2 = math.max(w2, math.abs(math.floor(v * 255) - buffer.readu8(p, i * 4 + ch)))
end
end
if c.kind == "bc6h" then
t:check(w2 <= 1, string.format("%s: %d off Pillow", c.name, w2))
stats.pillow += 1
end
else
t:eq(buffer.len(px), n * 4, c.name .. ": rgba8 size")
local ref = PILLOW[c.kind]
local d, at = maxDiff(px, buffer.fromstring(c.pillow), n, ref[1])
t:check(d <= ref[2], string.format("%s: %d off Pillow at pixel %d", c.name, d, at))
stats.pillow += 1
if c.godot then
local chans = if c.kind == "bc4" then R elseif c.kind == "bc5" then RG else RGBA
local dg, atg = maxDiff(px, buffer.fromstring(c.godot), n, chans)
-- bcdec rounds some interpolated values where Pillow truncates: within 1
t:check(dg <= 1, string.format("%s: %d off Godot at pixel %d", c.name, dg, atg))
stats.godot += 1
end
end
-- into a bigger buffer at an offset, from an offset
local big = buffer.create(buffer.len(src) + 5)
buffer.copy(big, 5, src)
local bpp = if Bcn.FLOAT[c.kind] then 16 else 4
local out = buffer.create(n * bpp + 8)
local px2 = Bcn.decode(c.kind, big, 5, c.w, c.h, out, 8)
t:check(px2 == out and buffer.readstring(out, 8, n * bpp) == buffer.readstring(px, 0, n * bpp), c.name .. ": offsets")
end
t:note("%d block images decoded: %d Pillow, %d Godot comparisons", #Fx.cases, stats.pillow, stats.godot)
-- BC4 SNORM = the red channel of BC5 SNORM
do
for _, c in Fx.cases do
if c.kind == "bc5s" then
local src = buffer.fromstring(c.data)
local nb = buffer.len(src) // 16
local b4 = buffer.create(nb * 8)
for i = 0, nb - 1 do
buffer.copy(b4, i * 8, src, i * 16, 8)
end
local p4 = Bcn.decode("bc4s", b4, 0, c.w, c.h) :: buffer
local p5 = Bcn.decode("bc5s", src, 0, c.w, c.h) :: buffer
local ok = true
for i = 0, c.w * c.h - 1 do
ok = ok and buffer.readu8(p4, i * 4) == buffer.readu8(p5, i * 4) and buffer.readu8(p4, i * 4 + 1) == buffer.readu8(p5, i * 4)
end
t:check(ok, c.name .. ": bc4s = bc5s red")
end
end
end
-- encoders
local function psnr(a: buffer, b: buffer, n: number, channels: { number }): number
local se = 0
for i = 0, n - 1 do
for _, c in channels do
local d = buffer.readu8(a, i * 4 + c) - buffer.readu8(b, i * 4 + c)
se += d * d
end
end
return if se == 0 then 99 else 10 * math.log10(255 * 255 * n * #channels / se)
end
for _, e in Fx.enc do
local px = buffer.fromstring(e.rgba)
local n = e.w * e.h
for _, k in { { "bc1", RGB }, { "bc3", RGBA }, { "bc5", RG }, { "bc4", R } } do
local kind, ch = k[1], k[2]
local blocks, err = Bcn.encode(kind, px, e.w, e.h)
t:check(blocks, kind .. " encode: " .. tostring(err))
t:eq(buffer.len(blocks), Bcn.size(kind, e.w, e.h), e.name .. " " .. kind .. ": size")
local back = Bcn.decode(kind, blocks, 0, e.w, e.h) :: buffer
local p = psnr(px, back, n, ch)
local base = e.psnr[kind]
if base then
t:check(p >= base - 0.5, string.format("%s %s: PSNR %.2f dB, Pillow %.2f dB", e.name, kind, p, base))
t:note("%s %s: %.2f dB (Pillow %.2f dB)", e.name, kind, p, base)
else
t:check(p >= 35, string.format("%s %s: PSNR %.2f dB", e.name, kind, p))
end
if kind == "bc1" then
-- the transparent pixels survive (3-colour mode)
local bad = 0
for i = 0, n - 1 do
local a = buffer.readu8(px, i * 4 + 3)
if (a >= 128) ~= (buffer.readu8(back, i * 4 + 3) == 255) then
bad += 1
end
end
t:eq(bad, 0, e.name .. " bc1: alpha mask")
end
end
end
-- flat colours are exact through the single-colour tables (BC1 4-colour and 3-colour, BC4)
do
local rand = T.rng(3)
local worst = 0
for _ = 1, 200 do
local r, g, b = rand(256), rand(256), rand(256)
local px = buffer.create(64)
for i = 0, 15 do
buffer.writeu32(px, i * 4, r + g * 256 + b * 65536 + (if i == 5 then 0 else 255) * 16777216)
end
for _, opaque in { true, false } do
if opaque then
buffer.writeu8(px, 23, 255)
else
buffer.writeu8(px, 23, 0)
end
local back = Bcn.decode("bc1", Bcn.encode("bc1", px, 4, 4) :: buffer, 0, 4, 4) :: buffer
for i = 0, 15 do
if opaque or i ~= 5 then
for c = 0, 2 do
worst = math.max(worst, math.abs(buffer.readu8(back, i * 4 + c) - buffer.readu8(px, i * 4 + c)))
end
end
end
end
end
-- 5 / 6-bit endpoints reach every 8-bit value within 1 (4-colour) / 2 (3-colour midpoints)
t:check(worst <= 2, "flat bc1 colours within " .. worst)
local px = buffer.create(64)
for v = 0, 255, 5 do
for i = 0, 15 do
buffer.writeu32(px, i * 4, v + 0xFF000000)
end
local back = Bcn.decode("bc4", Bcn.encode("bc4", px, 4, 4) :: buffer, 0, 4, 4) :: buffer
t:eq(buffer.readu8(back, 0), v, "flat bc4 " .. v)
end
end
-- Half
do
t:eq(Half.fromFloat(1), 0x3C00, "half 1")
t:eq(Half.fromFloat(-2), 0xC000, "half -2")
t:eq(Half.fromFloat(65504), 0x7BFF, "half max")
t:eq(Half.fromFloat(1e6), 0x7C00, "half overflow")
t:eq(Half.fromFloat(2 ^ -24), 1, "half smallest subnormal")
t:eq(Half.fromFloat(0 / 0), 0x7E00, "half NaN")
local ok = true
for h = 0, 65535 do
local f = Half.TABLE[h]
if f == f and Half.fromFloat(f) ~= h and not (h == 0x8000) then
ok = false
end
end
t:check(ok, "half round trip of every pattern")
end
-- errors
do
local _, e1 = Bcn.decode("bc9", buffer.create(8), 0, 4, 4)
t:check(e1 and string.find(e1, "unsupported") ~= nil, "unknown kind")
local _, e2 = Bcn.decode("bc1", buffer.create(7), 0, 4, 4)
t:check(e2 and string.find(e2, "truncated") ~= nil, "short data")
local _, e3 = Bcn.encode("bc7", buffer.create(64), 4, 4)
t:check(e3 ~= nil, "no bc7 encoder")
local _, e4 = Bcn.encode("bc1", buffer.create(10), 4, 4)
t:check(e4 ~= nil, "short pixels")
end
-- fuzz: random block data of every kind and size
local samples = {}
for _, c in Fx.cases do
table.insert(samples, buffer.fromstring(c.data))
end
for _, kind in { "bc1", "bc2", "bc3", "bc4", "bc4s", "bc5", "bc5s", "bc6h", "bc6hs", "bc7" } do
t:fuzz("decode " .. kind, function(b: buffer)
local n = buffer.len(b) // Bcn.BLOCK[kind]
if n < 1 then
return Bcn.decode(kind, b, 0, 4, 4)
end
return Bcn.decode(kind, b, 0, 4 * n - 1, 3)
end, samples, { mutations = 2 })
end
t:done()
+81
View File
@@ -0,0 +1,81 @@
-- codecs/model/Draco tests: Google's Draco test data (bitstreams 0.9 - 2.2) and files encoded by draco_encoder 1.5.7
-- at every compression level, quantization and as point clouds, decoded and compared byte for byte (points, faces,
-- every attribute's values per point, as CRCs) with libdraco's own decoder (tools/fixtures/_draco_dump.cc), kd-tree
-- point clouds included; argument errors; the fuzz no-throw pass (which also fails on any internal error the
-- decoder's safety net caught). Fixtures: tools/fixtures/draco.py.
local T = require("@tests/T")
local Draco = require("@formats/codecs/model/Draco")
local Err = require("@formats/core/Err")
local Crc32 = require("@formats/core/Crc32")
local Cases = require("@tests/gen/draco_cases")
local t = T.suite("draco")
local counts = { exact = 0, rejected = 0, kd = 0 }
local samples = {}
for _, c in Cases do
local g, err = Draco.decode(c.data)
if c.error then
t:check(g == nil and err ~= nil, c.name .. ": libdraco rejects it, so do we")
counts.rejected += 1
else
t:check(g, c.name .. ": decode: " .. tostring(err))
if g then
t:eq(g.numPoints, c.points, c.name .. ": points")
if c.faces then
t:eq(g.numFaces, c.faces, c.name .. ": faces")
t:eq(Crc32.of(g.indices :: buffer), c.indices, c.name .. ": indices")
end
t:eq(#g.attributes, #c.attrs, c.name .. ": attribute count")
for i, want in c.attrs do
local a = g.attributes[i]
if a then
t:eq(a.typeId, want.type, c.name .. ": attribute " .. i .. " type")
t:eq(a.type, Draco.DATA_TYPES[want.dataType], c.name .. ": attribute " .. i .. " data type")
t:eq(a.components, want.components, c.name .. ": attribute " .. i .. " components")
t:eq(a.normalized, want.normalized, c.name .. ": attribute " .. i .. " normalized")
t:eq(a.uniqueId, want.uniqueId, c.name .. ": attribute " .. i .. " unique id")
t:eq(Crc32.of(a.data), want.crc, c.name .. ": attribute " .. i .. " (" .. a.name .. ") values")
end
end
counts.exact += 1
if g.method == "kdtree" then
counts.kd += 1
end
if #c.data < 4000 then
table.insert(samples, c.data)
end
end
end
end
t:note("%d files decoded exactly like libdraco (%d kd-tree point clouds), %d rejected by both", counts.exact, counts.kd, counts.rejected)
-- the attribute lookup and the header
local first = Cases[1]
local info = Draco.info(first.data)
t:check(info and (info.kind == "mesh" or info.kind == "points"), "info")
t:check(Draco.sniff(buffer.fromstring(first.data)), "sniff")
t:check(not Draco.sniff(buffer.fromstring("DRAC")), "sniff short")
-- errors
local _, e1 = Draco.decode(buffer.fromstring("NOTDRACO......"))
t:check(e1 and e1.code == Err.CORRUPT, "not Draco data: " .. tostring(e1))
local _, e2 = Draco.decode(buffer.fromstring("DRACO\9\0\1\1\0\0"))
t:check(e2 and e2.code == Err.UNSUPPORTED, "future version: " .. tostring(e2))
local _, e3 = Draco.decode(42 :: any)
t:check(e3 and e3.code == Err.ARG, "bad argument")
-- fuzz: never throws, and the internal safety net never fires
local internal = 0
t:fuzz("decode", function(b: buffer)
local g, err = Draco.decode(b)
if not g and err and string.find(err.message, "internal error", 1, true) then
internal += 1
if internal <= 5 then
print(" internal error: " .. err.message)
end
end
return g
end, samples, { mutations = 12, keepHeader = 11 })
t:eq(internal, 0, "fuzz: internal errors")
t:done()
+129
View File
@@ -0,0 +1,129 @@
-- codecs/image/Etc tests: random ETC1 / ETC2 (every mode: individual, differential, T, H, planar; RGB A1 opaque and
-- transparent; RGBA with EAC alpha) and EAC R11 / RG11 (unsigned, signed, multiplier 0) blocks against Godot 4's
-- decode (etcpak); odd sizes; the 16-bit EAC output; errors; the fuzz no-throw pass. Fixtures: tools/fixtures/etc.py.
local T = require("@tests/T")
local Etc = require("@formats/codecs/image/Etc")
local Fx = require("@tests/gen/etc")
local t = T.suite("etc")
local function maxDiff(a: buffer, b: buffer, n: number, channels: { number }): (number, number)
local worst, at = 0, -1
for i = 0, n - 1 do
for _, c in channels do
local d = math.abs(buffer.readu8(a, i * 4 + c) - buffer.readu8(b, i * 4 + c))
if d > worst then
worst, at = d, i
end
end
end
return worst, at
end
local worstEac = 0
for _, c in Fx do
local src = buffer.fromstring(c.data)
local px, err = Etc.decode(c.kind, src, 0, c.w, c.h)
t:check(px, c.name .. ": " .. tostring(err))
local n = c.w * c.h
t:eq(buffer.len(px), n * 4, c.name .. ": size")
local eacKind = string.sub(c.kind, 1, 3) == "eac"
if c.spec then
-- signed EAC against the spec rule (values -1023..1023), biased into 8 bits
local two = c.kind == "eac_rg11s"
local bad = 0
for i = 0, n - 1 do
for ch = 0, if two then 1 else 0 do
local want = math.floor(c.spec[i * 2 + ch + 1] * 127 / 1023 + 0.5) + 128
if buffer.readu8(px, i * 4 + ch) ~= want then
bad += 1
end
end
end
t:eq(bad, 0, c.name .. ": against the spec values")
elseif c.kind == "etc2_rgba1" then
-- Godot decoded the blocks as ETC2 RGB: opaque blocks match it; transparent ones have index 2 transparent
-- black and indexes 1 / 3 unchanged (index 0 drops its modifier in the differential mode); planar is opaque
local g = buffer.fromstring(c.godot)
local bw = (c.w + 3) // 4
local bad = 0
for y = 0, c.h - 1 do
for x = 0, c.w - 1 do
local bo = ((y // 4) * bw + x // 4) * 8
local hi = bit32.byteswap(buffer.readu32(src, bo))
local lo = bit32.byteswap(buffer.readu32(src, bo + 4))
local i = (x % 4) * 4 + y % 4
local idx = bit32.band(bit32.rshift(lo, i + 15), 2) + bit32.band(bit32.rshift(lo, i), 1)
local opaque = bit32.band(hi, 2) ~= 0
local function ch(v: number, at: number): number
v = bit32.band(bit32.rshift(hi, at), 31) + (function(d: number): number
return if d >= 4 then d - 8 else d
end)(bit32.band(bit32.rshift(hi, at - 3), 7))
return v
end
local r2, g2, b2 = ch(0, 27), ch(0, 19), ch(0, 11)
local planar = r2 >= 0 and r2 <= 31 and g2 >= 0 and g2 <= 31 and (b2 < 0 or b2 > 31)
local diff = r2 >= 0 and r2 <= 31 and g2 >= 0 and g2 <= 31 and b2 >= 0 and b2 <= 31
local o = (y * c.w + x) * 4
local mine, ref = buffer.readu32(px, o), buffer.readu32(g, o)
if opaque or planar then
bad += if mine == ref then 0 else 1
elseif idx == 2 then
bad += if mine == 0 then 0 else 1
elseif idx ~= 0 or not diff then
bad += if mine == ref then 0 else 1
end
end
end
t:eq(bad, 0, c.name .. ": punch-through rules over Godot's ETC2 RGB decode")
else
local g = buffer.fromstring(c.godot)
local chans = if c.kind == "eac_r11" then { 0 } elseif eacKind then { 0, 1 } else { 0, 1, 2, 3 }
local d, at = maxDiff(px, g, n, chans)
if eacKind then
-- Godot keeps EAC as 16-bit / half floats and converts to 8 bits with its own rounding
worstEac = math.max(worstEac, d)
t:check(d <= 1, string.format("%s: %d off Godot at pixel %d", c.name, d, at))
else
t:check(d == 0, string.format("%s: %d off Godot at pixel %d", c.name, d, at))
end
end
-- 16-bit EAC agrees with the 8-bit output
if eacKind then
local p16 = Etc.decode(c.kind, src, 0, c.w, c.h, nil, 0, true) :: buffer
t:eq(buffer.len(p16), n * 8, c.name .. ": rgba16 size")
local ok = true
for i = 0, n - 1 do
local v16 = buffer.readu16(p16, i * 8)
ok = ok and math.abs(math.floor(v16 / 257 + 0.5) - buffer.readu8(px, i * 4)) <= 1
end
t:check(ok, c.name .. ": rgba16 ~ rgba8")
end
-- from / into offsets
local big = buffer.create(buffer.len(src) + 3)
buffer.copy(big, 3, src)
local out = buffer.create(n * 4 + 4)
Etc.decode(c.kind, big, 3, c.w, c.h, out, 4)
t:check(buffer.readstring(out, 4, n * 4) == buffer.tostring(px), c.name .. ": offsets")
end
t:note("%d block images match Godot (EAC within %d)", #Fx, worstEac)
do
local _, e1 = Etc.decode("etc3", buffer.create(8), 0, 4, 4)
t:check(e1 and string.find(e1, "unsupported") ~= nil, "unknown kind")
local _, e2 = Etc.decode("etc2_rgba", buffer.create(8), 0, 4, 4)
t:check(e2 and string.find(e2, "truncated") ~= nil, "short data")
t:eq(Etc.size("etc2_rgba", 5, 5), 64, "size")
end
local samples = {}
for _, c in Fx do
table.insert(samples, buffer.fromstring(c.data))
end
for kind in Etc.BLOCK do
t:fuzz("decode " .. kind, function(b: buffer)
local n = buffer.len(b) // Etc.BLOCK[kind]
return Etc.decode(kind, b, 0, math.max(1, 4 * n - 2), 4)
end, samples, { mutations = 2 })
end
t:done()
+113
View File
@@ -0,0 +1,113 @@
-- codecs/video/Legacy tests: Cinepak (24-bit, grey, 8-bit palettised, several strips, a 92x68 size), Microsoft Video 1
-- (16-bit, 8-bit with an AVI palette), QuickTime RLE (depths 1 / 2 / 4 / 8 with colour tables, default Macintosh
-- tables and grey ramps; 16 / 24 / 32-bit and grey from ffmpeg) and QuickTime SMC, in AVI, MOV and MKV: every frame
-- equals ffmpeg's decode (CRC-32 of rgba); seeking; the registry entries; the fuzz pass on each codec's packet decoder.
-- Fixtures: tools/fixtures/legacy.py.
local T = require("@tests/T")
local F = require("@formats")
local Crc32 = require("@formats/core/Crc32")
local Video = require("@formats/codecs/video/Video")
local Legacy = require("@formats/codecs/video/Legacy")
local Fx = require("@tests/gen/legacy_cases")
local t = T.suite("legacy")
-- the registry
t:eq(Video.fromFourcc("cvid"), "cinepak", "cvid")
t:eq(Video.fromFourcc("CRAM"), "msvideo1", "CRAM")
t:eq(Video.fromFourcc("msvc"), "msvideo1", "msvc")
t:eq(Video.fromFourcc("rle "), "qtrle", "rle ")
t:eq(Video.fromFourcc("smc "), "smc", "smc ")
for _, id in Legacy.CODECS do
t:check(Video.canDecode(id), id .. ": decodable")
end
local samples: { [string]: { any } } = {}
for _, c in Fx do
local label = c.name
local v, err = F.video.open(c.data)
t:check(v ~= nil, label .. ": open: " .. tostring(err))
if v then
t:eq(v.codec, c.codec, label .. ": codec")
t:eq(v.width, c.width, label .. ": width")
local n, bad, first = 0, 0, nil
while true do
local f, ferr = v:nextFrame()
if not f then
t:check(ferr == nil, label .. ": decode error " .. tostring(ferr))
break
end
n += 1
local img = f.image
if img.format ~= "rgba8" or img.width ~= c.width or Crc32.of(img.pixels) ~= c.frames[n] then
bad += 1
first = first or n
end
end
t:check(n == #c.frames and bad == 0, string.format("%s: %d of %d frames equal ffmpeg's (%d differ, first %s)", label, n - bad, #c.frames, bad, tostring(first)))
-- seeking: back to the start, the first frame again
v:seek(0)
local f = v:nextFrame()
t:check(f ~= nil and Crc32.of(f.image.pixels) == c.frames[1], label .. ": seek(0)")
-- packets for the fuzz pass
local dmx = v.demuxer
local tr = dmx:track("video")
if not samples[c.codec] then
local list = {}
for k = 1, math.min(3, dmx:count(tr.id)) do
table.insert(list, dmx:get(tr.id, k).data)
end
samples[c.codec] = { track = tr, packets = list }
end
end
end
-- the fuzz pass on the native packet decoders (no pcall in between)
local P = Legacy.Picture
local raw: { [string]: (tr: any) -> (buffer) -> any } = {
cinepak = function(tr)
return function(b)
local pic = P.new(tr.width, tr.height, tr.bitsPerPixel == 8, 4, 4, tr.palette)
return Legacy.Cinepak.decode(pic, b, Legacy.Cinepak.state(), false)
end
end,
msvideo1 = function(tr)
return function(b)
local bits = if tr.bitsPerPixel == 8 then 8 else 16
return Legacy.Msvideo1.decode(P.new(tr.width, tr.height, bits == 8, 4, 4), b, bits)
end
end,
qtrle = function(tr)
return function(b)
local d = tr.bitsPerPixel or 24
for _, depth in { d, 1, 2, 4, 8, 16, 32 } do
Legacy.QtRle.decode(P.new(tr.width, tr.height, Legacy.QtRle.palettised(depth), Legacy.QtRle.pad(depth), 1), b, depth)
end
return true
end
end,
smc = function(tr)
return function(b)
return Legacy.Smc.decode(P.new(tr.width, tr.height, true, 4, 4), b, Legacy.Smc.tables())
end
end,
}
for id, s in samples do
local fn = raw[id]
if fn then
t:fuzz(id .. " packets", fn(s.track), s.packets, { mutations = 24, garbage = 60 })
end
end
t:fuzz("open", function(b: buffer)
local v = F.video.open(b)
if v then
for _ = 1, 3 do
if not v:nextFrame() then
break
end
end
end
return v
end, { Fx[1].data, Fx[#Fx].data }, { mutations = 8, garbage = 20 })
t:done()
+25 -2
View File
@@ -1,4 +1,5 @@
-- codecs/video/Mpeg1 tests, ported from mpeg1-luau tests/decode.luau and tests/robust.luau. Against ffmpeg
-- codecs/video/Mpeg1 tests, ported from mpeg1-luau tests/decode.luau and tests/robust.luau. Every frame bit-exact with
-- `ffmpeg -idct int` (the IDCT codecs/video/Dsp reproduces; frames with concealed macroblocks excepted). Against ffmpeg
-- (tools/fixtures/mpeg1.py): every stream decodes, one access unit at a time, to as many frames as ffmpeg's decode,
-- in display order; each frame's RGBA channel means within 1.5 of ffmpeg's; whole sampled frames within 2 MAE per
-- channel (IDCT and colour rounding) and, as yuv420p (frameImage), within a PSNR floor of ffmpeg -pix_fmt yuv420p;
@@ -11,6 +12,7 @@ local Mpeg1 = require("@formats/codecs/video/Mpeg1")
local Base64 = require("@formats/core/Base64")
local Deflate = require("@formats/codecs/compress/Deflate")
local Types = require("@formats/Types")
local Crc32 = require("@formats/core/Crc32")
local STREAMS = {
require("@tests/gen/mpeg1_qcif_200k"),
@@ -81,6 +83,7 @@ local function psnr(a: buffer, ao: number, b: buffer, bo: number, n: number): nu
end
local MAE_LIMIT = 2
local totalExact, totalConcealed = 0, 0
local MEAN_LIMIT = 1.5
-- 1. every stream against ffmpeg
@@ -101,6 +104,7 @@ for _, fx in STREAMS do
local hasB = string.find(name, "bframes") ~= nil
local dec = Mpeg1.new({ reorder = hasB })
local frames = 0
local exact, concealed = 0, 0
local maxMae, maxMeanErr = 0, 0
local sums = {}
local function onFrame(f: any)
@@ -136,6 +140,21 @@ for _, fx in STREAMS do
end
t:check(buffer.readu8(px, 3) == 255 and buffer.readu8(px, n * 4 - 1) == 255, "alpha 255")
sums[frames] = buffer.tostring(px)
-- bit-exact against ffmpeg -idct int (outside macroblocks the decoder had to conceal)
local ex = fx.exact[frames]
if ex then
local img = Mpeg1.frameImage(f) :: Types.Image
local yc = Crc32.of(img.pixels, 0, n)
local uc = Crc32.of(img.pixels, n, cw * ch)
local vc = Crc32.of(img.pixels, n + cw * ch, cw * ch)
if yc == ex[1] and uc == ex[2] and vc == ex[3] then
exact += 1
elseif next(f.concealed) ~= nil then
concealed += 1
else
t:check(false, string.format("%s frame %d (type %d): differs from ffmpeg -idct int", name, frames, f.pictureType))
end
end
end
local t0 = os.clock()
for _, u in fx.units do
@@ -155,7 +174,10 @@ for _, fx in STREAMS do
t:eq(frames, fx.frames, name .. ": frames (ffmpeg's count)")
t:eq(dec.stats.errors, 0, name .. ": no bitstream errors")
worst = math.max(worst, maxMae)
t:note("%-13s %4dx%-4d %3d frames worst MAE %.3f means err %.3f %6.1f fps (with the checks)", name, w, h, frames, maxMae, maxMeanErr, frames / dt)
t:note("%-13s %4dx%-4d %3d frames %3d bit-exact worst MAE %.3f means err %.3f %6.1f fps (with the checks)", name, w, h, frames, exact, maxMae, maxMeanErr, frames / dt)
t:eq(exact + concealed, frames, name .. ": frames equal to ffmpeg -idct int (or with concealed macroblocks)")
totalExact += exact
totalConcealed += concealed
-- streamed: random pieces through write / decodeFrame, then flush
local d2 = Mpeg1.new({ reorder = hasB })
@@ -187,6 +209,7 @@ for _, fx in STREAMS do
t:eq(got, frames, name .. ": streamed frame count")
end
t:note("worst sampled-frame MAE %.3f (limit %d); worst yuv420p PSNR luma %.1f, chroma %.1f dB", worst, MAE_LIMIT, worstY, worstC)
t:note("%d frames bit-exact with ffmpeg -idct int, %d with concealed macroblocks (ffmpeg error concealment)", totalExact, totalConcealed)
-- 2. a size change mid-stream
do
+304
View File
@@ -0,0 +1,304 @@
-- codecs/video/Mpeg2 tests. Against `ffmpeg -idct int` (tools/fixtures/mpeg2.py): every stream (progressive and
-- interlaced frame pictures with field prediction and field DCT, top / bottom field first, 4:2:2, the alternate scan,
-- Table B-15, the non-linear quantiser scale, DC precision 9..11, custom luma / chroma matrices, f_code > 1, an odd
-- size, B-frames, dual prime, field pictures, concealment vectors) decodes one access unit at a time to exactly ffmpeg's planes, every frame, in display
-- order; the same stream written in random pieces gives the same frames; frame flags (mpeg2, chroma, progressive,
-- topFieldFirst); frameImage (4:2:2 -> yuv420p, rgba8); the registry's VideoCodecDecoder; truncated and corrupted
-- streams never throw; the fuzz no-throw pass.
local T = require("@tests/T")
local Mpeg2 = require("@formats/codecs/video/Mpeg2")
local Video = require("@formats/codecs/video/Video")
local Base64 = require("@formats/core/Base64")
local Crc32 = require("@formats/core/Crc32")
local Deflate = require("@formats/codecs/compress/Deflate")
local STREAMS = {
require("@tests/gen/mpeg2_prog"),
require("@tests/gen/mpeg2_tff"),
require("@tests/gen/mpeg2_bff_alt"),
require("@tests/gen/mpeg2_tools"),
require("@tests/gen/mpeg2_dc9_matrix"),
require("@tests/gen/mpeg2_dc11_q1"),
require("@tests/gen/mpeg2_motion"),
require("@tests/gen/mpeg2_odd_ilace"),
require("@tests/gen/mpeg2_c422"),
require("@tests/gen/mpeg2_c422_ilace"),
require("@tests/gen/mpeg2_dualprime"),
require("@tests/gen/mpeg2_fields"),
require("@tests/gen/mpeg2_fields_conceal"),
}
local t = T.suite("codecs/mpeg2")
local rand = T.rng(11)
local function b64(s: string): buffer
return Base64.decode(s) :: buffer
end
-- CRC-32 of a plane cropped to w x h from a buffer with stride
local function planeCrc(b: buffer, stride: number, w: number, h: number): number
local row = buffer.create(w * h)
for y = 0, h - 1 do
buffer.copy(row, y * w, b, y * stride, w)
end
return Crc32.of(row)
end
-- the cropped planes of a frame, as ffmpeg writes them (w x h luma, ceil(w / 2) x (h or ceil(h / 2)) chroma)
local function crcs(f: any): (number, number, number)
local w, h = f.width, f.height
local cw = (w + 1) // 2
local ch = if f.chroma == 2 then h else (h + 1) // 2
local chw = f.codedWidth // 2
return planeCrc(f.y, f.codedWidth, w, h), planeCrc(f.cb, chw, cw, ch), planeCrc(f.cr, chw, cw, ch)
end
-- differing samples between a frame's luma and a reference yuv frame (debug detail on a mismatch)
local function lumaDiff(f: any, ref: buffer): (number, number)
local n, first = 0, -1
for y = 0, f.height - 1 do
for x = 0, f.width - 1 do
if buffer.readu8(f.y, y * f.codedWidth + x) ~= buffer.readu8(ref, y * f.width + x) then
n += 1
if first < 0 then
first = y * 65536 + x
end
end
end
end
return n, first
end
local function decodeUnits(fx: any, file: buffer): { any }
local dec = Mpeg2.new({ reorder = true, rgba = false })
local out = {}
local function take(f: any)
local y, u, v = crcs(f)
-- the 16-line luma bands now: the planes belong to the decoder
local bands = {}
for b = 0, (f.height + 15) // 16 - 1 do
local rows = math.min(16, f.height - b * 16)
local buf = buffer.create(f.width * rows)
for r = 0, rows - 1 do
buffer.copy(buf, r * f.width, f.y, (b * 16 + r) * f.codedWidth, f.width)
end
bands[b] = Crc32.of(buf)
end
table.insert(out, { y, u, v, f, bands })
end
for i, u in fx.units do
local f = dec:decode(file, u[1], u[2], i)
while f do
take(f)
f = dec:decode(file, 0, 0, i)
end
end
while true do
local f = dec:flush()
if not f then
break
end
take(f)
end
return out
end
-- 1. every stream against ffmpeg, bit-exact. ffmpeg's encoder sometimes ends a B-picture slice before the row's last
-- macroblock (invalid MPEG-2); both decoders conceal the gap, ffmpeg with its error-resilience guesses and deblocking.
-- Frames with concealed macroblocks compare every 16-line luma band but those and their neighbours.
local total, concealedFrames = 0, 0
for _, fx in STREAMS do
local name = fx.name
local file = b64(fx.file)
local t0 = os.clock()
local got = decodeUnits(fx, file)
local dt = os.clock() - t0
t:eq(#got, fx.frames, name .. ": frame count")
local bad, msg = 0, ""
for k, ref in fx.crcs do
local g = got[k]
if g and (g[1] ~= ref[1] or g[2] ~= ref[2] or g[3] ~= ref[3]) then
local f = g[4]
local ok = next(f.concealed) ~= nil
if ok then
concealedFrames += 1
for band, crc in fx.bands[k] do
local b = band - 1
if not (f.concealed[b] or f.concealed[b - 1] or f.concealed[b + 1]) then
ok = ok and g[5][b] == crc
end
end
end
if not ok then
bad += 1
if bad == 1 then
local detail = ""
if k == 1 and #got == 1 then
local n, first = lumaDiff(f, Deflate.zlib(b64(fx.first)) :: buffer)
detail = string.format(" (%d luma samples differ, first at %d,%d)", n, first % 65536, first // 65536)
end
msg = string.format(" (first: frame %d, type %d: y %s u %s v %s%s)", k, f.pictureType,
tostring(g[1] == ref[1]), tostring(g[2] == ref[2]), tostring(g[3] == ref[3]), detail)
end
end
end
end
t:eq(bad, 0, name .. ": frames differing from ffmpeg" .. msg)
local f1 = got[1] and got[1][4]
if f1 then
t:check(f1.mpeg2 == true, name .. ": mpeg2 flag")
t:eq(f1.chroma, fx.chroma, name .. ": chroma format")
end
total += #got
t:note(" %-12s %4dx%-4d %s %3d frames %6.1f fps (with the checks)", name, fx.width, fx.height,
if fx.chroma == 2 then "4:2:2" else "4:2:0", #got, #got / dt)
end
-- 2. interlace flags
do
local got = decodeUnits(STREAMS[2], b64(STREAMS[2].file))
t:check(got[1][4].progressive == false and got[1][4].topFieldFirst == true, "tff: interlaced, top field first")
got = decodeUnits(STREAMS[3], b64(STREAMS[3].file))
t:check(got[1][4].progressive == false and got[1][4].topFieldFirst == false, "bff_alt: bottom field first")
got = decodeUnits(STREAMS[1], b64(STREAMS[1].file))
t:check(got[1][4].progressive == true, "prog: progressive")
end
-- 3. the same stream written in random pieces (decodeFrame) gives the same frames as unit by unit
for _, idx in { 2, 9, 12 } do
local fx = STREAMS[idx]
local file = b64(fx.file)
local want = decodeUnits(fx, file)
local dec = Mpeg2.new({ reorder = true, rgba = false })
local p, k, ok = 0, 0, true
local n = buffer.len(file)
local function check(f: any)
k += 1
local y, u, v = crcs(f)
local ref = want[k]
ok = ok and ref ~= nil and y == ref[1] and u == ref[2] and v == ref[3]
end
while p < n do
local len = math.min(n - p, 1 + rand(5000))
dec:write(file, p, len)
p += len
while true do
local f = dec:decodeFrame()
if not f then
break
end
check(f)
end
end
while true do
local f = dec:flush()
if not f then
break
end
check(f)
end
t:check(ok and k == fx.frames, string.format("%s: random pieces give the same %d frames (%d)", fx.name, fx.frames, k))
end
-- 4. frameImage: yuv420p (4:2:2 converted), rgba8
do
local fx = STREAMS[9]
local dec = Mpeg2.new({ reorder = false, rgba = true })
local file = b64(fx.file)
local f = dec:decode(file, fx.units[1][1], fx.units[1][2])
t:check(f ~= nil and f.pixels ~= nil, "c422: rgba frame")
if f then
local img = Mpeg2.frameImage(f)
t:check(img ~= nil and img.format == "yuv420p" and img.width == fx.width, "c422: frameImage yuv420p")
if img then
local cw, ch = (fx.width + 1) // 2, (fx.height + 1) // 2
t:eq(buffer.len(img.pixels), fx.width * fx.height + 2 * cw * ch, "c422: yuv420p size")
t:eq(img.meta.source.format, "mpeg2", "c422: meta.source.format")
t:eq(img.meta.source.chroma, "422", "c422: meta.source.chroma")
end
local rgba = Mpeg2.frameImage(f, true)
t:check(rgba ~= nil and rgba.format == "rgba8", "c422: frameImage rgba8")
end
t:check(Mpeg2.frameImage({} :: any) == nil, "frameImage of a non-frame is nil")
end
-- 5. the registry's decoder (packets = access units), display order with pts
do
t:check(Video.fromFourcc("mpg2") == "mpeg2" and Video.fromMatroska("V_MPEG2") == "mpeg2", "registry names")
t:check(Video.canDecode("mpeg2") and Video.canDecode("mpeg1"), "registry decoders")
local fx = STREAMS[1]
local file = b64(fx.file)
local want = decodeUnits(fx, file)
local dec = assert(Video.decoder({ id = 1, kind = "video", codec = "mpeg2", timescale = 25 } :: any))
local frames, order = 0, true
local last = -1
for i, u in fx.units do
local d = buffer.create(u[2])
buffer.copy(d, 0, file, u[1], u[2])
dec:decode({ track = 1, pts = i, keyframe = false, data = d } :: any)
while true do
local img, pts = dec:receive()
if not img then
break
end
frames += 1
local ref = want[frames]
local w, h = fx.width, fx.height
order = order and ref ~= nil and Crc32.of(img.pixels, 0, w * h) == ref[1] and img.meta.yuv ~= nil
last = pts or last
end
end
dec:flush()
while dec:receive() do
frames += 1
end
t:eq(frames, fx.frames, "registry decoder: frame count")
t:check(order, "registry decoder: frames in display order, equal to the codec's")
end
-- 6. robustness: truncated units, bit flips, garbage (never throws), and the fuzz pass
do
local samples = {}
for _, idx in { 1, 2, 9, 11 } do
local fx = STREAMS[idx]
local file = b64(fx.file)
local n = math.min(buffer.len(file), 60000)
local b = buffer.create(n)
buffer.copy(b, 0, file, 0, n)
table.insert(samples, b)
end
local threw = 0
for round = 1, 12 do
local src = samples[1 + round % #samples]
local b = buffer.create(buffer.len(src))
buffer.copy(b, 0, src)
for _ = 1, 20 do
local i = rand(buffer.len(b))
buffer.writeu8(b, i, bit32.bxor(buffer.readu8(b, i), bit32.lshift(1, rand(8))))
end
local ok = pcall(function()
local dec = Mpeg2.new({ reorder = true })
dec:write(b)
while dec:decodeFrame() do
end
while dec:flush() do
end
end)
if not ok then
threw += 1
end
end
t:eq(threw, 0, "corrupted streams never throw")
t:fuzz("decode", function(b: buffer)
local dec = Mpeg2.new({ reorder = true })
dec:write(b)
local f = dec:decodeFrame()
while f do
f = dec:decodeFrame()
end
return dec:flush()
end, samples, { mutations = 60, garbage = 10 })
end
t:note(" %d frames bit-exact with ffmpeg -idct int (%d with concealed macroblocks: compared outside them)", total, concealedFrames)
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()
+285
View File
@@ -0,0 +1,285 @@
-- codecs/video/Theora tests. Against ffmpeg (tools/fixtures/theora.py, its vp3 decoder = libtheora's output): every
-- frame of every stream, bit-exact (Adler-32 of the native planes of the picture region, as ffmpeg's framecrc): 4:2:0 /
-- 4:2:2 / 4:4:4, qualities 0..10, a 300 kbit/s high-motion stream (4MV, golden frames, multiple qi), picture regions
-- smaller than the coded frame (even sizes from the encoder, odd sizes at offsets patched into the header), frames
-- the encoder dropped (empty packets: ffmpeg outputs nothing, we repeat the previous picture) and one spliced in;
-- image() as yuv420p (4:2:2 / 4:4:4 chroma averaged); Theora in Matroska through the codecs/video/Video registry.
-- Errors: missing / bad headers, maxPixels, header packets in the data, garbage packets; the fuzz no-throw passes
-- (headers, key and inter frames).
local T = require("@tests/T")
local Theora = require("@formats/codecs/video/Theora")
local Video = require("@formats/codecs/video/Video")
local Ogg = require("@formats/containers/Ogg")
local Mkv = require("@formats/video/mkv")
local Bytes = require("@formats/core/Bytes")
local Base64 = require("@formats/core/Base64")
local Adler32 = require("@formats/core/Adler32")
local Err = require("@formats/core/Err")
local t = T.suite("theora")
local CASES = { "q6", "q0", "q10", "motion", "odd", "static", "yuv422", "yuv444", "odd444", "crop", "crop422" }
local FIXTURES: { [string]: any } = {
q6 = require("@tests/gen/theora_q6"),
q0 = require("@tests/gen/theora_q0"),
q10 = require("@tests/gen/theora_q10"),
motion = require("@tests/gen/theora_motion"),
odd = require("@tests/gen/theora_odd"),
static = require("@tests/gen/theora_static"),
yuv422 = require("@tests/gen/theora_yuv422"),
yuv444 = require("@tests/gen/theora_yuv444"),
odd444 = require("@tests/gen/theora_odd444"),
crop = require("@tests/gen/theora_crop"),
crop422 = require("@tests/gen/theora_crop422"),
}
-- the Theora packets of an Ogg file: headers, data packets
local function packets(file: buffer): ({ buffer }, { buffer })
local d = Ogg.open(file)
local serial = d:find("theora")
local hdrs, data = {}, {}
for p in d:packets(serial) do
if #hdrs < 3 then
table.insert(hdrs, Ogg.copy(p))
else
table.insert(data, Ogg.copy(p))
end
end
return hdrs, data
end
-- ffmpeg's framecrc: Adler-32 started at 0 over the packed planes
local function crc(y: buffer, u: buffer, v: buffer): number
local a = Adler32.of(y, nil, nil, 0)
a = Adler32.of(u, nil, nil, a)
return Adler32.of(v, nil, nil, a)
end
local samples: { buffer } = {}
local headerSets: { { buffer } } = {}
-- 1. every fixture, every frame
for _, name in CASES do
local fx = FIXTURES[name]
local hdrs, data = packets(Base64.decode(fx.file) :: buffer)
table.insert(headerSets, hdrs)
local dec, err = Theora.new(hdrs)
t:check(dec ~= nil, name .. ": headers: " .. tostring(err))
if dec then
t:eq(dec.width, fx.width, name .. ": width")
t:eq(dec.height, fx.height, name .. ": height")
t:eq(dec.pixelFormat, fx.pixfmt, name .. ": pixel format")
local want: { [number]: number } = {}
for _, f in fx.frames do
want[f[1]] = f[2]
end
local bad, dupes, prev = 0, 0, nil :: number?
for k, p in data do
local kind, e = dec:decode(p)
if not kind then
bad += 1
t:check(false, name .. ": frame " .. (k - 1) .. ": " .. tostring(e))
continue
end
local y, u, v = dec:planes()
local c = crc(y, u, v)
local w = want[k - 1]
if kind == "dup" then
dupes += 1
t:check(w == nil, name .. ": ffmpeg shows no frame for empty packet " .. (k - 1))
if c ~= prev then
bad += 1
end
elseif w ~= c then
bad += 1
end
prev = c
end
t:eq(bad, 0, name .. ": frames different from ffmpeg's (of " .. #data .. ", " .. dupes .. " repeated)")
t:eq(#data - dupes, #fx.frames, name .. ": as many shown frames as ffmpeg")
table.insert(samples, data[1])
if data[2] then
table.insert(samples, data[2])
end
end
end
-- 2. an empty packet spliced in after the 5th frame repeats it; the rest follows
do
local fx = require("@tests/gen/theora_dupe") :: any
local hdrs, data = packets(Base64.decode(fx.file) :: buffer)
local dec = Theora.new(hdrs) :: Theora.TheoraDecoder
local bad, prev = 0, nil :: number?
for k, p in data do
local kind = dec:decode(p)
local y, u, v = dec:planes()
local c = crc(y, u, v)
if k == 6 then
t:eq(kind, "dup", "dupe: the empty packet")
t:eq(buffer.len(p), 0, "dupe: it is empty")
t:eq(c, prev, "dupe: repeats the previous picture")
elseif c ~= fx.frames[if k > 6 then k - 1 else k][2] then
bad += 1
end
prev = c
end
t:eq(bad, 0, "dupe: the other frames")
end
-- 3. image(): yuv420p, the planes as they are (4:2:0) or averaged (4:2:2 / 4:4:4)
for _, name in { "q6", "crop", "yuv422", "crop422", "odd444" } do
local fx = FIXTURES[name]
local hdrs, data = packets(Base64.decode(fx.file) :: buffer)
local dec = Theora.new(hdrs) :: Theora.TheoraDecoder
dec:decode(data[1])
dec:decode(data[2])
local img = dec:image()
local y, u, v, cw, ch = dec:planes()
local w, h = dec.width, dec.height
local ow, oh = (w + 1) // 2, (h + 1) // 2
t:eq(img.format, "yuv420p", name .. ": image format")
t:eq(img.width * 1000 + img.height, w * 1000 + h, name .. ": image size")
t:eq(buffer.len(img.pixels), w * h + 2 * ow * oh, name .. ": image bytes")
t:eq(Adler32.of(img.pixels, 0, w * h), Adler32.of(y), name .. ": luma")
local bad = 0
for r = 0, oh - 1 do
for c = 0, ow - 1 do
local want
if fx.pixfmt == "yuv420p" then
want = buffer.readu8(u, math.min(r, ch - 1) * cw + c)
elseif fx.pixfmt == "yuv422p" then
want = (buffer.readu8(u, math.min(2 * r, ch - 1) * cw + c) + buffer.readu8(u, math.min(2 * r + 1, ch - 1) * cw + c) + 1) // 2
else
local r0, r1 = math.min(2 * r, ch - 1), math.min(2 * r + 1, ch - 1)
local c0, c1 = math.min(2 * c, cw - 1), math.min(2 * c + 1, cw - 1)
want = (buffer.readu8(u, r0 * cw + c0) + buffer.readu8(u, r0 * cw + c1) + buffer.readu8(u, r1 * cw + c0) + buffer.readu8(u, r1 * cw + c1) + 2) // 4
end
if buffer.readu8(img.pixels, w * h + r * ow + c) ~= want then
bad += 1
end
end
end
t:eq(bad, 0, name .. ": U downsampled")
local _ = v
t:eq(img.meta.yuv and img.meta.yuv.matrix, "bt601", name .. ": colour matrix")
end
-- 4. Theora in Matroska: the registry entry (V_THEORA, Xiph-laced CodecPrivate) through video/mkv
do
t:eq(Video.fromMatroska("V_THEORA"), "theora", "registry: V_THEORA")
t:check(Video.canDecode("theora"), "registry: theora decodes")
local fx = require("@tests/gen/theora_mkv") :: any
local v, err = Mkv.open(Bytes.reader(Base64.decode(fx.file) :: buffer))
t:check(v ~= nil, "mkv: open: " .. tostring(err))
if v then
t:eq(v.codec, "theora", "mkv: codec")
local n, bad, shown = 0, 0, 0
local want: { [number]: number } = {}
for _, f in fx.frames do
want[f[1]] = f[2]
end
while true do
local f, e = v:nextFrame()
if not f then
t:check(e == nil, "mkv: frames: " .. tostring(e))
break
end
local img = f.image
local w = want[math.floor(f.pts * 25 + 0.5)]
if w then
shown += 1
if Adler32.of(img.pixels, nil, nil, 0) ~= w then
bad += 1
end
end
n += 1
end
t:eq(bad, 0, "mkv: frames as ffmpeg's")
t:eq(shown, #fx.frames, "mkv: every frame ffmpeg shows")
end
end
-- 5. API details and errors
do
local fx = FIXTURES.q6
local hdrs, data = packets(Base64.decode(fx.file) :: buffer)
local dec = Theora.new(hdrs) :: Theora.TheoraDecoder
t:eq(dec.frameRate, 25, "frame rate")
t:check(dec.vendor ~= "" and dec.tags.encoder ~= nil, "comment header: vendor and ENCODER tag")
t:eq(Theora.isHeader(hdrs[1]), 1, "isHeader: identification")
t:eq(Theora.isHeader(hdrs[3]), 3, "isHeader: setup")
t:eq(Theora.isHeader(data[1]), nil, "isHeader: data")
local kind, e = dec:decode(hdrs[2])
t:check(kind == nil and e == nil, "a header packet in the data is skipped")
t:eq(Theora.granuleFrame(dec.info, 0), -1, "granule 0 (3.2.1 numbering)")
t:eq(Theora.granuleFrame(dec.info, 2 ^ dec.info.granuleShift * 12 + 3), 14, "granule: keyframe 12 + 3")
-- the Xiph-laced config Matroska uses
local lens = { buffer.len(hdrs[1]), buffer.len(hdrs[2]) }
local w = Bytes.writer(64)
w:u8(2)
for _, l in lens do
local x = l
while x >= 255 do
w:u8(255)
x -= 255
end
w:u8(x)
end
for _, h in hdrs do
w:bytes(h)
end
local cfg = w:finish()
local parts = Theora.splitConfig(cfg)
t:check(parts ~= nil and #parts == 3 and buffer.len(parts[3]) == buffer.len(hdrs[3]), "splitConfig")
t:check(Theora.new(cfg) ~= nil, "new(config)")
local d2, e2 = Theora.new({ hdrs[1], hdrs[2] })
t:check(d2 == nil and e2 ~= nil and e2.code == Err.CORRUPT, "missing setup header: CORRUPT")
local _, e3 = Theora.new({ hdrs[2], hdrs[1], hdrs[3] })
t:check(e3 ~= nil and e3.code == Err.CORRUPT, "headers out of order: CORRUPT")
local cut = buffer.create(100)
buffer.copy(cut, 0, hdrs[3], 0, 100)
local _, e4 = Theora.new({ hdrs[1], hdrs[2], cut })
t:check(e4 ~= nil, "truncated setup header: " .. tostring(e4))
local _, e5 = Theora.new(hdrs, { maxPixels = 1000 })
t:check(e5 ~= nil and e5.code == Err.LIMIT, "maxPixels: LIMIT")
local _, e6 = dec:decode(data[1], 5, buffer.len(data[1]))
t:check(e6 ~= nil and e6.code == Err.ARG, "decode: range outside the buffer")
-- an inter frame before any keyframe decodes over grey
local fresh = Theora.new(hdrs) :: Theora.TheoraDecoder
t:check(fresh:decode(data[2]) == "inter", "an inter frame first")
local track: any = { id = 1, kind = "video", codec = "theora", timescale = 25, config = cfg }
local vd = Theora.newVideoDecoder(track)
t:check(vd ~= nil, "newVideoDecoder")
if vd then
vd:decode({ track = 1, pts = 0, keyframe = true, data = data[1] })
local img, pts, key = vd:receive()
t:check(img ~= nil and pts == 0 and key == true, "newVideoDecoder: a keyframe picture")
vd:reset()
t:check(vd:receive() == nil, "newVideoDecoder: reset drops pending pictures")
end
local nv, nerr = Theora.newVideoDecoder({ id = 1, kind = "video", codec = "theora", timescale = 25 } :: any)
t:check(nv == nil and nerr ~= nil, "newVideoDecoder without config")
end
-- 6. fuzz: headers, keyframes and inter frames (a decoder primed with a keyframe, fed mutated packets)
do
local hdrs = headerSets[1]
t:fuzz("headers", function(b: buffer)
return Theora.new({ hdrs[1], hdrs[2], b })
end, { hdrs[3] }, { mutations = 24, garbage = 50 })
t:fuzz("identification", function(b: buffer)
return Theora.new({ b, hdrs[2], hdrs[3] })
end, { hdrs[1] }, { mutations = 24, garbage = 20 })
for i, h in headerSets do
local dec = Theora.new(h) :: Theora.TheoraDecoder
local s = { samples[2 * i - 1], samples[2 * i] }
dec:decode(s[1])
t:fuzz("frames " .. CASES[i], function(b: buffer)
local kind = dec:decode(b)
dec:planes()
return kind
end, s, { mutations = 12, garbage = 20, seed = i })
end
end
t:done()
+148
View File
@@ -0,0 +1,148 @@
-- codecs/model/Vrml tests: the classic-encoding lexer and parser (comments, commas, string escapes, hex / exponent
-- numbers, DEF / USE, PROTO with IS fields, nested PROTOs and ROUTEs in bodies, EXTERNPROTO, Script interfaces,
-- IMPORT / EXPORT, the X3D header statements), the XML encoding's adapter (containerField, ProtoDeclare /
-- ProtoInstance, IS / connect), typed field reads of raw XML attributes, detection, errors, the fuzz pass.
local T = require("@tests/T")
local Vrml = require("@formats/codecs/model/Vrml")
local Fields = require("@formats/codecs/model/Vrml/Fields")
local Err = require("@formats/core/Err")
local t = T.suite("vrml codec")
-- ------------------------------------------------------------------------------------------------ lexer / parser
do
local g = assert(Vrml.parse([[#VRML V2.0 utf8
# a comment, then commas as blanks
DEF A Transform { translation 1,2,3 # trailing comment
children [ Shape { geometry IndexedFaceSet { coordIndex [ 0, 1, 2, -1 ] coord Coordinate { point [ 0 0 0, 1e1 0 0, .5 -2.5E-1 +3 ] } } } ] }
WorldInfo { title "say \"hi\" \\ there" info [ "a" "b" ] }
DEF P PixelTexture { image 1 1 4 0xFF8000FF }
USE A
]]))
t:eq(#g.roots, 4, "statements")
t:eq(g.header.version, "2.0", "header")
local a = g.roots[1]
t:eq(a.def, "A", "DEF")
t:eq(table.concat(Fields.vec(a, "translation", { 0, 0, 0 }), " "), "1 2 3", "commas are blanks")
local coord = Fields.node(Fields.node(Fields.nodes(a, "children")[1], "geometry"), "coord")
t:eq(table.concat(Fields.nums(coord, "point") :: { number }, " "), "0 0 0 10 0 0 0.5 -0.25 3", "exponents, leading dot, plus sign")
t:eq(Fields.str(g.roots[2], "title"), 'say "hi" \\ there', "string escapes")
t:eq(#Fields.strs(g.roots[2], "info"), 2, "MFString")
t:eq((Fields.nums(g.roots[3], "image") :: { number })[4], 0xFF8000FF, "hex numbers")
t:check(g.roots[4] == a, "USE is the same node")
end
do
local g = assert(Vrml.parse([[#VRML V2.0 utf8
PROTO Outer [ field SFFloat size 1 exposedField SFColor tint 1 1 1 eventIn SFBool flip ] {
PROTO Inner [ field SFFloat r 1 ] { Sphere { radius IS r } }
DEF G Group { children [ Shape { geometry Inner { r IS size } appearance Appearance { material DEF M Material { diffuseColor IS tint } } } ] }
DEF Clock TimeSensor { }
DEF I PositionInterpolator { key [ 0 1 ] keyValue [ 0 0 0 1 1 1 ] }
ROUTE Clock.fraction_changed TO I.set_fraction
ROUTE I.value_changed TO G.set_translation
}
EXTERNPROTO Far [ field SFFloat x ] [ "far.wrl#Far" "urn:far" ]
DEF O1 Outer { size 3 tint 0 1 0 }
Outer { }
Far { x 2 }
DEF S Script { field SFNode target USE O1 eventIn SFTime touch url "javascript: function touch() {}" }
IMPORT inl.Thing AS Thing
EXPORT S AS Exported
]]))
t:eq(#g.roots, 4, "proto instances, extern instance, script")
local o1, o2 = g.roots[1], g.roots[2]
t:eq(o1.type, "Group", "an instance is its body's first node")
t:eq(o1.def, "O1", "the instance's DEF name")
local function radius(o: any): number
local sh = Fields.nodes(o, "children")[1]
return Fields.num(Fields.node(sh, "geometry"), "radius", -1)
end
t:eq(radius(o1), 3, "IS through a nested PROTO (instance value)")
t:eq(radius(o2), 1, "IS default")
local mat = Fields.node(Fields.node(Fields.nodes(o1, "children")[1], "appearance"), "material")
t:eq(table.concat(Fields.vec(mat, "diffuseColor", { 9, 9, 9 }), " "), "0 1 0", "IS on an SFColor")
local mat2 = Fields.node(Fields.node(Fields.nodes(o2, "children")[1], "appearance"), "material")
t:check(mat ~= mat2, "each instance has its own copy of the body")
t:eq(#g.routes, 4, "the body's ROUTEs, per instance")
t:check(g.routes[2].to == o1 or g.routes[2].to.fields == o1.fields, "routes point at the instance's nodes")
t:eq(g.roots[3].type, "Far", "EXTERNPROTO instance keeps its type")
t:check(g.roots[3].extern == true, "EXTERNPROTO instance flagged")
t:eq(Fields.node(g.roots[4], "target"), o1, "Script interface field with a USE value")
end
do
local g = assert(Vrml.parse("#X3D V3.3 utf8\nPROFILE Immersive\nCOMPONENT CADGeometry:2\nMETA \"author\" \"me\"\nUNIT length foot 0.3048\nGroup { }\n"))
t:check(g.header.x3d and g.header.version == "3.3" and g.header.profile == "Immersive", "X3D header, PROFILE")
t:eq(g.components[1], "CADGeometry:2", "COMPONENT")
t:eq(g.meta.author, "me", "META")
t:eq(g.units.length.factor, 0.3048, "UNIT")
local s = assert(Vrml.build(g))
t:eq(s.meta.unit, 0.3048, "UNIT length -> meta.unit")
end
-- ------------------------------------------------------------------------------------------------ XML adapter
do
local g = assert(Vrml.graph([[<?xml version="1.0"?>
<X3D profile="Interchange" version="4.0"><head><component name="Shaders" level="1"/></head><Scene>
<ProtoDeclare name="Ball"><ProtoInterface><field name="r" type="SFFloat" accessType="initializeOnly" value="2"/></ProtoInterface>
<ProtoBody><Shape><Sphere><IS><connect nodeField="radius" protoField="r"/></IS></Sphere></Shape></ProtoBody></ProtoDeclare>
<Group DEF="G"><ProtoInstance name="Ball"><fieldValue name="r" value="5"/></ProtoInstance>
<ProtoInstance name="Ball" containerField="children"/></Group>
<Shape><Appearance><ImageTexture url='"a.png" "b.png"'/></Appearance><Box containerField="geometry" size="1, 2, 3" solid="FALSE"/></Shape>
<Transform USE="G"/>
</Scene></X3D>]]))
t:check(g.header.xml and g.header.version == "4.0", "XML header")
t:eq(g.components[1], "Shaders:1", "head component")
local grp = g.roots[1]
local kids = Fields.nodes(grp, "children")
t:eq(#kids, 2, "ProtoInstances in children")
t:eq(Fields.num(Fields.node(kids[1], "geometry"), "radius", -1), 5, "fieldValue")
t:eq(Fields.num(Fields.node(kids[2], "geometry"), "radius", -1), 2, "ProtoInterface default")
local shape = g.roots[2]
local box = Fields.node(shape, "geometry")
t:eq(table.concat(Fields.vec(box, "size", { 9, 9, 9 }), " "), "1 2 3", "numbers with commas")
t:eq(Fields.bool(box, "solid", true), false, "XML booleans (any case)")
local tex = Fields.node(Fields.node(shape, "appearance"), "texture")
local urls = Fields.strs(tex, "url")
t:check(#urls == 2 and urls[2] == "b.png", "quoted MFString")
t:eq(g.roots[3], grp, "USE in XML")
local single = { type = "ImageTexture", fields = { url = "plain name.png" } }
t:eq(Fields.strs(single, "url")[1], "plain name.png", "unquoted single MFString")
end
-- ------------------------------------------------------------------------------------------------ errors
do
local function code(text: string): string?
local _, e = Vrml.graph(text)
return e and e.code
end
t:eq(code("#VRML V2.0 utf8\nShape { geometry Box { }"), Err.CORRUPT, "unclosed node")
t:eq(code("#VRML V2.0 utf8\nShape { geometry USE X }"), Err.CORRUPT, "undefined USE")
t:eq(code("#VRML V2.0 utf8\nROUTE A.b TO"), Err.CORRUPT, "bad ROUTE")
t:eq(code("#VRML V2.0 utf8\nWorldInfo { title \"x }"), Err.TRUNCATED, "unterminated string")
t:eq(code("#VRML V1.0 ascii\n"), Err.UNSUPPORTED, "VRML 1.0")
t:eq(code("\224\0\0\1rest"), Err.UNSUPPORTED, "Fast Infoset X3D")
t:eq(code("#VRML V2.0 utf8\n" .. string.rep("Group { children ", 250)), Err.LIMIT, "nesting limit")
t:eq(code("<X3D><Scene><Group></Scene></X3D>"), Err.CORRUPT, "bad XML")
local _, e = Vrml.encode({} :: any)
t:eq(e and e.code, Err.ARG, "encode junk")
end
-- ------------------------------------------------------------------------------------------------ fuzz
do
local samples = {
"#VRML V2.0 utf8\nPROTO P [ field SFFloat a 1 ] { Box { size IS a IS a } }\nDEF X P { a 2 } USE X ROUTE X.a TO X.b\n",
"#X3D V3.3 utf8\nPROFILE Full\nShape { geometry Extrusion { spine [ 0 0 0 0 1 0 1 1 1 ] crossSection [ 0 0 1 0 1 1 0 0 ] } }\n",
"<X3D><Scene><ProtoDeclare name='A'><ProtoBody><Box/></ProtoBody></ProtoDeclare><ProtoInstance name='A'/><Shape><IndexedFaceSet coordIndex='0 1 2 -1 2 3 0'><Coordinate point='0 0 0 1 0 0 1 1 0 0 1 0'/></IndexedFaceSet></Shape></Scene></X3D>",
}
t:fuzz("graph + build", function(b: buffer)
local g = Vrml.graph(b)
if g then
return Vrml.build(g)
end
return nil
end, samples, { mutations = 400 })
end
t:done()
+138
View File
@@ -0,0 +1,138 @@
-- host/Roblox tests: the pure half of the EditableMesh adapter (meshPages: triangle runs within the triangle / vertex
-- limits, corners mapping back to the source indices, double-sided counting, errors; pageData: centring, per-axis
-- scale, inverse-scaled unit normals, uvs + flipV, linear -> sRGB colours). toEditableMesh itself needs Roblox.
local T = require("@tests/T")
local Host = require("@formats/host/Roblox")
local Types = require("@formats/Types")
local Err = require("@formats/core/Err")
local t = T.suite("host_roblox")
local S = Types.Scene
local function f32(list: { number }, comps: number): Types.Accessor
local a = S.accessor(nil, "f32", comps, #list // comps)
for i, v in list do
buffer.writef32(a.data, (i - 1) * 4, v)
end
return a
end
local function near(a: number, b: number, eps: number?): boolean
return math.abs(a - b) <= (eps or 1e-5)
end
-- an n x n grid of quads in the xz plane (two triangles each), u16 indices, normals up, uvs, colours
local function grid(n: number): Types.Primitive
local pos, nrm, uv, col = {}, {}, {}, {}
for z = 0, n do
for x = 0, n do
table.insert(pos, x)
table.insert(pos, 0)
table.insert(pos, z)
for _, v in { 0, 1, 0 } do
table.insert(nrm, v)
end
table.insert(uv, x / n)
table.insert(uv, z / n)
for _, v in { 0.5, 0, 1, 0.25 } do
table.insert(col, v)
end
end
end
local idx = {}
for z = 0, n - 1 do
for x = 0, n - 1 do
local a = z * (n + 1) + x
local b, c, d = a + 1, a + n + 1, a + n + 2
for _, v in { a, c, b, b, c, d } do
table.insert(idx, v)
end
end
end
local ia = S.accessor(nil, "u16", 1, #idx)
for i, v in idx do
buffer.writeu16(ia.data, (i - 1) * 2, v)
end
return {
attributes = { POSITION = f32(pos, 3), NORMAL = f32(nrm, 3), TEXCOORD_0 = f32(uv, 2), COLOR_0 = f32(col, 4) },
indices = ia,
mode = "triangles",
}
end
-- 1. pages within the limits, covering every triangle once, corners = the source indices
local prim = grid(10) -- 121 vertices, 200 triangles
local pages = assert(Host.meshPages(prim, { maxTriangles = 64 }))
t:eq(#pages, 4, "200 triangles / 64 per page")
local covered = 0
for pi, pg in pages do
t:eq(pg.first, covered, "page " .. pi .. " starts after the previous one")
t:check(pg.count <= 64, "page " .. pi .. " within maxTriangles")
t:eq(buffer.len(pg.corners), pg.count * 12, "page " .. pi .. " corners")
for k = 0, pg.count * 3 - 1 do
local src = buffer.readu16((prim.indices :: any).data, (pg.first * 3 + k) * 2)
local l = buffer.readu32(pg.corners, k * 4)
if pg.vertices[l + 1] ~= src then
t:check(false, string.format("page %d corner %d maps back to %d", pi, k, src))
end
end
covered += pg.count
end
t:eq(covered, 200, "every triangle in a page")
t:eq(pages[1].min[1], 0, "page bounds min")
t:check(pages[1].max[3] > 0, "page bounds max")
local one = assert(Host.meshPages(prim))
t:eq(#one, 1, "default limits: one page")
t:eq(#one[1].vertices, 121, "every vertex once")
local two = assert(Host.meshPages(prim, { maxTriangles = 64, doubleSided = true }))
t:eq(#two, 7, "double-sided: 32 front triangles per page")
local tight = assert(Host.meshPages(prim, { maxVertices = 30 }))
for _, pg in tight do
t:check(#pg.vertices <= 30, "maxVertices")
end
t:check(#tight > 1, "maxVertices splits")
-- no indices: vertices in order
local soup = { attributes = { POSITION = f32({ 0, 0, 0, 1, 0, 0, 0, 1, 0, 2, 0, 0, 3, 0, 0, 2, 1, 0 }, 3) }, mode = "triangles" }
local sp = assert(Host.meshPages(soup :: any))
t:eq(sp[1].count, 2, "unindexed triangles")
t:eq(#sp[1].vertices, 6, "unindexed vertices")
-- 2. errors
local _, e1 = Host.meshPages({ attributes = { POSITION = f32({ 0, 0, 0 }, 3) }, mode = "lines" } :: any)
t:check(e1 and e1.code == Err.ARG, "lines are not triangles")
local _, e2 = Host.meshPages({} :: any)
t:check(e2 and e2.code == Err.ARG, "no POSITION")
local bad = grid(1)
buffer.writeu16((bad.indices :: any).data, 2, 999)
local _, e3 = Host.meshPages(bad)
t:check(e3 and e3.code == Err.ARG, "index out of range")
local _, e4 = Host.pageData(prim, {} :: any)
t:check(e4 and e4.code == Err.ARG, "pageData needs a page")
-- 3. pageData: centred, scaled, normals, uvs, colours
local pg = one[1]
local d = assert(Host.pageData(prim, pg, { scale = { 2, 1, 4 } }))
t:eq(d.vertexCount, 121, "vertex count")
t:eq(d.triangleCount, 200, "triangle count")
t:eq(d.centre[1], 10, "centre x (5 * 2)")
t:eq(d.centre[3], 20, "centre z (5 * 4)")
local v0 = pg.vertices[1] -- source vertex of local 1
local sx0 = v0 % 11
t:eq(d.positions[1], (sx0 - 5) * 2, "position x relative to the centre, scaled")
t:check(d.normals and near(d.normals[2], 1), "unit normal")
t:check(d.uvs and near(d.uvs[1], sx0 / 10), "uv")
t:check(d.colors and near(d.colors[1], 0.7353569, 1e-4), "linear 0.5 -> sRGB")
t:check(d.colors and near(d.colors[3], 1) and near(d.colors[4], 0.25), "sRGB 1 and alpha kept")
local slanted = { attributes = { POSITION = f32({ 0, 0, 0, 1, 0, 0, 0, 1, 0 }, 3), NORMAL = f32({ 1, 1, 0, 1, 1, 0, 1, 1, 0 }, 3) }, mode = "triangles" }
local sd = assert(Host.pageData(slanted :: any, assert(Host.meshPages(slanted :: any))[1], { scale = { 2, 1, 1 }, origin = { 0, 0, 0 } }))
t:check(near(sd.normals[1], 0.5 / math.sqrt(1.25)) and near(sd.normals[2], 1 / math.sqrt(1.25)), "normals scale by the inverse")
t:eq(sd.positions[4], 2, "origin option")
local fl = assert(Host.pageData(prim, pg, { flipV = true, normals = false, colors = false }))
t:check(fl.normals == nil and fl.colors == nil, "attributes switched off")
t:check(fl.uvs and near(fl.uvs[2], 1 - (v0 // 11) / 10), "flipV")
t:done()
+78
View File
@@ -0,0 +1,78 @@
-- tests/image/_raster: the shared checks of the simple raster formats' tests (pcx, sgi, sunras, xbm, xpm, ilbm, icns,
-- ani): decode every case against its reference rgba8 pixels, round-trip images through the encoder, fuzz samples.
local Bytes = require("@formats/core/Bytes")
local Types = require("@formats/Types")
local R = {}
local function maxDiff(a: buffer, b: buffer, n: number): (number, number)
local worst, at = 0, -1
for i = 0, n * 4 - 1 do
local d = math.abs(buffer.readu8(a, i) - buffer.readu8(b, i))
if d > worst then
worst, at = d, i // 4
end
end
return worst, at
end
R.maxDiff = maxDiff
-- cases: { { name, data, w, h, rgba, tol? } } (rgba: the reference decode)
function R.decodes(t: any, Fmt: any, cases: { any }, opts: any?): number
local n = 0
for _, c in cases do
local img, err = Fmt.decode(Bytes.reader(buffer.fromstring(c.data)), opts)
t:check(img, c.name .. ": " .. tostring(err))
if img then
t:check(img.width == c.w and img.height == c.h and img.format == "rgba8", string.format("%s: %d x %d %s", c.name, img.width, img.height, img.format))
if img.width == c.w and img.height == c.h then
local d, at = maxDiff(img.pixels, buffer.fromstring(c.rgba), c.w * c.h)
t:check(d <= (c.tol or 0), string.format("%s: %d off the reference at pixel %d", c.name, d, at))
end
n += 1
end
-- from inside a bigger buffer
local big = buffer.create(#c.data + 9)
buffer.writestring(big, 5, c.data)
local img2 = Fmt.decode(Bytes.reader(big, 5, #c.data), opts)
t:check(img2 and img and buffer.tostring(img2.pixels) == buffer.tostring(img.pixels), c.name .. ": from a sub-range")
end
return n
end
-- image(w, h, rgba string) -> Types.Image
function R.image(w: number, h: number, rgba: string): Types.Image
local img = Types.Image.new(w, h)
img.pixels = buffer.fromstring(rgba)
return img
end
-- roundTrip(t, Fmt, img, encodeOpts?, label, tol?) -> the encoded buffer
function R.roundTrip(t: any, Fmt: any, img: Types.Image, eopts: any?, label: string, tol: number?): buffer?
local enc, err = Fmt.encode(img, eopts)
t:check(enc, label .. ": encode " .. tostring(err))
if not enc then
return nil
end
local back, derr = Fmt.decode(Bytes.reader(enc))
t:check(back, label .. ": decode " .. tostring(derr))
if back then
t:check(back.width == img.width and back.height == img.height, label .. ": size")
local d = maxDiff(back.pixels, img.pixels, img.width * img.height)
t:check(d <= (tol or 0), string.format("%s: round trip %d off", label, d))
end
return enc
end
-- samples(cases, every?) -> the fuzz samples (every n-th case's data)
function R.samples(cases: { any }, every: number?): { string }
local samples = {}
for i, c in cases do
if i % (every or 1) == 0 then
table.insert(samples, c.data)
end
end
return samples
end
return R
+72
View File
@@ -0,0 +1,72 @@
-- image/ani tests: animated cursors around Pillow-written ICO / CUR frames (seq + rate, plain, cursor hotspots, INFO
-- title) against Pillow's frame decodes and the written steps / delays; AF_ICON clear and a missing hook are
-- UNSUPPORTED; the encoder through the ICO hook round-trips; the fuzz no-throw pass. Fixtures: tools/fixtures/ani.py.
local T = require("@tests/T")
local Ani = require("@formats/image/ani")
local Ico = require("@formats/image/ico")
local Png = require("@formats/image/png")
local Bytes = require("@formats/core/Bytes")
local Err = require("@formats/core/Err")
local R = require("@tests/image/_raster")
local Fx = require("@tests/gen/ani")
local t = T.suite("ani")
t:eq(Ani.name, "ani", "name")
t:check(Ani.caps.decode and Ani.caps.encode, "caps")
local hooks = {
decodeImage = function(b: buffer): (any, any)
-- Pillow writes the ICO entries as PNG: the ICO decoder gets its own hook
return Ico.decode(Bytes.reader(b), { decodeImage = function(p: buffer): (any, any)
return Png.decode(Bytes.reader(p))
end })
end,
encodeImage = function(img: any, _fmt: string): (any, any)
return Ico.encode(img)
end,
}
for _, c in Fx.cases do
local img, err = Ani.decode(Bytes.reader(buffer.fromstring(c.data)), hooks)
if c.unsupported then
t:check(img == nil and err and err.code == Err.UNSUPPORTED, c.name .. ": UNSUPPORTED")
continue
end
t:check(img, c.name .. ": " .. tostring(err))
t:check(img.width == c.w and img.height == c.h, c.name .. ": size")
t:eq(#img.frames, #c.steps, c.name .. ": steps")
for i, s in c.steps do
local f = img.frames[i]
t:check(math.abs(f.delay - s.delay) < 1e-9, c.name .. ": step " .. i .. " delay")
t:eq(R.maxDiff(f.image.pixels, buffer.fromstring(c.frames[s.frame]), c.w * c.h), 0, c.name .. ": step " .. i .. " pixels")
end
t:eq(img.loops, 0, c.name .. ": loops forever")
if c.title then
t:eq(img.meta.text.title, c.title, c.name .. ": title")
end
if c.hotspot then
t:check(img.meta.hotspot and img.meta.hotspot.x == c.hotspot[1] and img.meta.hotspot.y == c.hotspot[2], c.name .. ": hotspot")
end
-- re-encode through the ICO hook
local enc, eerr = Ani.encode(img, hooks)
t:check(enc, c.name .. ": encode " .. tostring(eerr))
local back = Ani.decode(Bytes.reader(enc :: buffer), hooks) :: any
t:eq(#back.frames, #img.frames, c.name .. ": re-encoded steps")
for i, f in back.frames do
t:eq(buffer.tostring(f.image.pixels), buffer.tostring(img.frames[i].image.pixels), c.name .. ": re-encoded frame " .. i)
t:check(math.abs(f.delay - img.frames[i].delay) < 1 / 120, c.name .. ": re-encoded delay " .. i)
end
end
do
local c = Fx.cases[1]
t:eq(Ani.sniff(Bytes.reader(buffer.fromstring(c.data))), 1, "sniff")
t:eq(Ani.sniff(Bytes.reader(buffer.fromstring("RIFF\0\0\0\0WAVE"))), 0, "sniff WAVE")
local _, e = Ani.decode(Bytes.reader(buffer.fromstring(c.data)))
t:check(e and e.code == Err.UNSUPPORTED, "no hook")
local _, e2 = Ani.encode(Ico.decode(Bytes.reader(buffer.fromstring(c.data))) or ({ pixels = buffer.create(4) } :: any))
t:check(e2 ~= nil, "encode without the hook")
end
t:fuzz("decode", function(b: buffer)
return Ani.decode(Bytes.reader(b), hooks)
end, R.samples(Fx.cases), { mutations = 10 })
t:done()
+212
View File
@@ -0,0 +1,212 @@
-- image/dds tests: files from NVIDIA Texture Tools (BGRA, BC1..BC7 incl. BC6H, mips, DX10, cube / array / volume)
-- and ImageMagick against every surface's reference decode (Pillow per surface, Godot floats for BC6H); hand-written
-- uncompressed DXGI / legacy / FourCC formats against their values (rgba8 and native floats); our encoder's files read
-- by Pillow and nvddsinfo, and round trips; errors; the fuzz no-throw pass. Fixtures: tools/fixtures/dds.py.
local T = require("@tests/T")
local Dds = require("@formats/image/dds")
local Bytes = require("@formats/core/Bytes")
local Err = require("@formats/core/Err")
local Types = require("@formats/Types")
local Fx = require("@tests/gen/dds")
local t = T.suite("dds")
t:eq(Dds.name, "dds", "name")
t:check(Dds.caps.decode and Dds.caps.encode, "caps")
local function dec(data: any, opts: any?): (any, any)
return Dds.decode(Bytes.reader(if type(data) == "string" then buffer.fromstring(data) else data), opts)
end
local function maxDiff(a: buffer, b: buffer, n: number): number
local worst = 0
for i = 0, n * 4 - 1 do
worst = math.max(worst, math.abs(buffer.readu8(a, i) - buffer.readu8(b, i)))
end
return worst
end
-- tool-written files
local surfaces = 0
for _, c in Fx.cases do
local img, err = dec(c.data, { mips = true })
t:check(img, c.name .. ": " .. tostring(err))
t:eq(img.meta.layout, c.layout, c.name .. ": layout")
t:eq(img.meta.source.mips, c.mips, c.name .. ": mips")
local frames = img.frames or { { image = img } }
local native = nil
for _, s in c.surfaces do
local im
if s.level == 0 then
local idx = s.layer * (if c.layout == "volume" then c.depth else 1) + s.slice + 1
im = frames[idx] and frames[idx].image
else
im = img.meta.mipmaps and img.meta.mipmaps[s.level]
end
local label = string.format("%s: level %d layer %d slice %d", c.name, s.level, s.layer, s.slice)
t:check(im and im.width == s.w and im.height == s.h, label .. ": surface size")
if s.floats then
native = native or dec(c.data, { native = true, mips = true })
local nim = if s.level == 0 then native else native.meta.mipmaps[s.level]
t:eq(nim.format, "rgbaf32", label .. ": native rgbaf32")
local g = buffer.fromstring(s.floats)
local worst = 0
for i = 0, s.w * s.h * 4 - 1 do
if i % 4 ~= 3 then
local a, b = buffer.readf32(nim.pixels, i * 4), buffer.readf32(g, i * 4)
worst = math.max(worst, math.abs(a - b) / math.max(math.abs(b), 1e-3))
end
end
t:check(worst < 1e-3, label .. ": floats against Godot " .. worst)
else
local d = maxDiff(im.pixels, buffer.fromstring(s.rgba), s.w * s.h)
t:check(d <= s.tol, string.format("%s: %d off the reference", label, d))
end
surfaces += 1
end
-- surfaces = false keeps only the first
local one = dec(c.data, { surfaces = false })
t:check(one and one.frames == nil, c.name .. ": surfaces = false")
end
t:note("%d tool-written files, %d surfaces match the references", #Fx.cases, surfaces)
-- hand-written formats
for _, c in Fx.hand do
local img, err = dec(c.data)
t:check(img, c.name .. ": " .. tostring(err))
local n = img.width * img.height
local d = maxDiff(img.pixels, buffer.fromstring(c.rgba8), n)
t:check(d <= 1, string.format("%s: rgba8 %d off", c.name, d))
if c.floats then
local nimg = dec(c.data, { native = true })
local f = buffer.fromstring(c.floats)
local worst = 0
local bpp = Types.BPP[nimg.format]
for i = 0, n * 4 - 1 do
local want = buffer.readf32(f, i * 4)
local got
if nimg.format == "rgbaf32" then
got = buffer.readf32(nimg.pixels, i * 4)
elseif nimg.format == "rgba16" then
got = buffer.readu16(nimg.pixels, i * 2) / 65535
else
got = buffer.readu8(nimg.pixels, i) / 255
end
worst = math.max(worst, math.abs(got - want) / math.max(1, math.abs(want)))
end
local tol = if nimg.format == "rgba8" then 1 / 255 elseif nimg.format == "rgba16" then 1 / 65535 else 1e-6
t:check(worst <= tol + 1e-9, string.format("%s: native %s off by %g", c.name, nimg.format, worst))
t:check(bpp ~= nil, c.name .. ": a standard format")
end
end
t:note("%d hand-written formats match", #Fx.hand)
-- our encoder: Pillow / nvddsinfo read the files, and they round-trip
local function source(w: number, h: number): buffer
local px = buffer.create(w * h * 4)
for y = 0, h - 1 do
for x = 0, w - 1 do
local o = (y * w + x) * 4
buffer.writeu8(px, o, math.floor(x / (w - 1) * 255 + 0.5))
buffer.writeu8(px, o + 1, math.floor(y / (h - 1) * 255 + 0.5))
buffer.writeu8(px, o + 2, math.floor(((x * 7 + y * 13) % 64) / 63 * 255 + 0.5))
buffer.writeu8(px, o + 3, math.floor(((x + y) % 5) / 4 * 255 + 0.5))
end
end
return px
end
local src = source(37, 23)
for _, o in Fx.ours do
local img, err = dec(o.data, { mips = true, native = true })
t:check(img, o.name .. ": " .. tostring(err))
t:check(o.width == img.width and o.height == img.height, o.name .. ": nvddsinfo size")
local mips = img.meta.source.mips
t:eq(math.max(1, o.mipcount), mips, o.name .. ": nvddsinfo mip count")
if string.find(o.name, "mips") or string.find(o.name, "rgba16") or string.find(o.name, "rgba32f") or string.find(o.name, "cube") or string.find(o.name, "dx10") then
if not string.find(o.name, "rgba16f") and not string.find(o.name, "array") then
t:check(mips > 1 and #img.meta.mipmaps == mips - 1, o.name .. ": a mip chain")
end
end
if o.pillow then
local p = buffer.fromstring(o.pillow)
local exact = string.find(o.name, "rgba8") or string.find(o.name, "bgra8")
local d = maxDiff(img.pixels, p, img.width * img.height)
t:check(d == 0, string.format("%s: Pillow reads %d off our decode", o.name, d))
if exact then
t:eq(buffer.tostring(p), buffer.tostring(src), o.name .. ": Pillow reads the source exactly")
end
end
if string.find(o.name, "cube") then
t:eq(img.meta.layout, "cube", o.name .. ": cube")
t:eq(#img.frames, 6, o.name .. ": 6 faces")
t:check(string.find(o.caps2, "FE00", 1, true) ~= nil, o.name .. ": nvddsinfo sees all faces")
elseif string.find(o.name, "array") then
t:eq(#img.frames, 6, o.name .. ": 6 layers")
t:eq(o.array, "6", o.name .. ": nvddsinfo array size")
end
if string.find(o.name, "rgba32f") then
t:check(string.find(o.dxgi, "R32G32B32A32_FLOAT", 1, true) ~= nil, o.name .. ": DXGI format " .. o.dxgi)
t:eq(img.format, "rgbaf32", o.name .. ": rgbaf32")
t:check(math.abs(buffer.readf32(img.pixels, 36 * 16) - 4) < 1e-6, o.name .. ": float values kept")
elseif string.find(o.name, "rgba16f") then
t:check(string.find(o.dxgi, "R16G16B16A16_FLOAT", 1, true) ~= nil, o.name .. ": DXGI format " .. o.dxgi)
t:check(math.abs(buffer.readf32(img.pixels, 36 * 16) - 4) < 1e-3, o.name .. ": half values")
elseif string.find(o.name, "rgba16") then
t:check(string.find(o.dxgi, "R16G16B16A16_UNORM", 1, true) ~= nil, o.name .. ": DXGI format " .. o.dxgi)
t:eq(img.format, "rgba16", o.name .. ": rgba16")
end
end
t:note("%d of our files read by Pillow / nvddsinfo", #Fx.ours)
-- round trips
do
local img = Types.Image.new(37, 23)
img.pixels = src
for _, f in { "rgba8", "bgra8" } do
local back = dec(Dds.encode(img, { pixelFormat = f :: any }) :: buffer)
t:eq(buffer.tostring(back.pixels), buffer.tostring(src), f .. " round trip")
end
local f = Types.Image.new(3, 2, "rgbaf32")
for i = 0, 23 do
buffer.writef32(f.pixels, i * 4, i * 0.37 - 2)
end
local back = dec(Dds.encode(f) :: buffer, { native = true })
t:eq(buffer.tostring(back.pixels), buffer.tostring(f.pixels), "rgba32f round trip")
local _, e1 = Dds.encode(f, { pixelFormat = "bc1" })
t:check(e1 and e1.code == Err.ARG, "bc1 needs rgba8")
local _, e2 = Dds.encode(img, { pixelFormat = "bc7" :: any })
t:check(e2 and e2.code == Err.ARG, "no bc7 encoder")
end
-- sniff and errors
do
local c = Fx.cases[1]
t:eq(Dds.sniff(Bytes.reader(buffer.fromstring(c.data))), 1, "sniff")
t:eq(Dds.sniff(Bytes.reader(buffer.fromstring("DDX \124\0\0\0"))), 0, "sniff other")
local _, e = dec(string.sub(c.data, 1, 100))
t:check(e and e.code == Err.TRUNCATED, "short header")
local _, e2 = dec(string.sub(c.data, 1, 140))
t:check(e2 and e2.code == Err.TRUNCATED, "no pixels: " .. tostring(e2))
local bad = buffer.fromstring(c.data)
buffer.writeu32(bad, 4, 100)
local _, e3 = dec(bad)
t:check(e3 and e3.code == Err.CORRUPT, "bad header size")
local _, e4 = dec(c.data, { maxPixels = 10 })
t:check(e4 and e4.code == Err.LIMIT, "limit")
local info = Dds.info(Bytes.reader(buffer.fromstring(c.data)))
t:check(info and info.width > 0, "info")
end
local samples = {}
for i, c in Fx.cases do
if i % 3 == 0 then
table.insert(samples, c.data)
end
end
for _, c in Fx.hand do
table.insert(samples, c.data)
end
t:fuzz("decode", function(b: buffer)
return dec(b, { mips = true })
end, samples, { mutations = 6 })
t:done()
+143
View File
@@ -0,0 +1,143 @@
-- image/exr tests: files from the OpenEXR 3.5 bindings (NONE / RLE / ZIPS / ZIP / PIZ; HALF / FLOAT / UINT; offset
-- data window; decreasing lines; Y-only; a layer), a hand-written subsampled file, exrmaketiled tiles (one level,
-- mip-map, rip-map, round up) and exrmultipart parts against the bindings' reads; PXR24 / B44 / DWAA UNSUPPORTED; our
-- files read back by the bindings and exrheader; round trips; errors; the fuzz no-throw pass. Fixtures:
-- tools/fixtures/exr.py.
local T = require("@tests/T")
local Exr = require("@formats/image/exr")
local Bytes = require("@formats/core/Bytes")
local Err = require("@formats/core/Err")
local Types = require("@formats/Types")
local Fx = require("@tests/gen/exr")
local t = T.suite("exr")
t:eq(Exr.name, "exr", "name")
t:check(Exr.caps.decode and Exr.caps.encode, "caps")
local function dec(data: any, opts: any?): (any, any)
return Exr.decode(Bytes.reader(if type(data) == "string" then buffer.fromstring(data) else data), opts)
end
-- the largest difference between two rgbaf32 buffers (exact for HALF / FLOAT, UINT as their values)
local function worst(a: buffer, b: buffer, n: number): number
local m = 0
for i = 0, n * 4 - 1 do
local x, y = buffer.readf32(a, i * 4), buffer.readf32(b, i * 4)
if x ~= y then
m = math.max(m, math.abs(x - y) / math.max(1, math.abs(y)))
end
end
return m
end
for _, c in Fx.cases do
if c.unsupported then
local img, e = dec(c.data)
t:check(img == nil and e and e.code == Err.UNSUPPORTED, c.name .. ": UNSUPPORTED (" .. tostring(e) .. ")")
continue
end
local opts = { native = true, layer = c.layer, part = c.part, mips = c.mips }
local img, err = dec(c.data, opts)
t:check(img, c.name .. ": " .. tostring(err))
t:check(img.width == c.w and img.height == c.h and img.format == "rgbaf32", c.name .. ": size")
local d = worst(img.pixels, buffer.fromstring(c.floats), c.w * c.h)
t:check(d < 1e-6, string.format("%s: off by %g", c.name, d))
if c.partName then
local byName = dec(c.data, { native = true, part = c.partName })
t:check(byName and buffer.tostring(byName.pixels) == buffer.tostring(img.pixels), c.name .. ": part by name")
t:eq(img.meta.source.parts[c.part].name, c.partName, c.name .. ": part names")
end
if c.mips and string.find(c.name, "mip") then
local mm = img.meta.mipmaps
t:check(mm and #mm >= 5, c.name .. ": mip levels")
local up = string.find(c.name, "up") ~= nil
t:eq(mm[1].width, if up then math.ceil(c.w / 2) else c.w // 2, c.name .. ": level 1 width")
end
-- the rgba8 display conversion
local d8 = dec(c.data, { layer = c.layer, part = c.part })
t:eq(d8.format, "rgba8", c.name .. ": rgba8 by default")
end
t:note("%d files match the OpenEXR bindings", #Fx.cases)
-- the window, the attributes
do
for _, c in Fx.cases do
if c.name == "window_zip.exr" then
local img = dec(c.data)
t:check(img.meta.dataWindow.x == 5 and img.meta.dataWindow.y == -3, "data window origin")
t:check(img.meta.displayWindow.width == 40 and img.meta.displayWindow.height == 20, "display window")
t:eq(img.meta.source.compression, "zip", "compression name")
end
end
end
-- our files: the bindings read our values back, exrheader accepts them
for _, o in Fx.ours do
t:check(o.headerOk, o.name .. ": exrheader")
local img = dec(o.data, { native = true })
local n = img.width * img.height
local d = worst(img.pixels, buffer.fromstring(o.floats), n)
t:check(d == 0, string.format("%s: the bindings read %g off our decode", o.name, d))
end
t:note("%d of our files read back by the OpenEXR bindings", #Fx.ours)
-- round trips: FLOAT exactly, HALF to half precision
do
local f = Types.Image.new(13, 9, "rgbaf32")
local rand = T.rng(5)
for i = 0, 13 * 9 * 4 - 1 do
buffer.writef32(f.pixels, i * 4, (rand(20000) - 5000) / 997)
end
for _, comp in { "none", "zips", "zip" } do
local back = dec(Exr.encode(f, { compression = comp :: any, pixelType = "float" }) :: buffer, { native = true })
t:eq(buffer.tostring(back.pixels), buffer.tostring(f.pixels), comp .. ": float round trip")
local hb = dec(Exr.encode(f, { compression = comp :: any }) :: buffer, { native = true })
t:check(worst(hb.pixels, f.pixels, 13 * 9) < 1e-3, comp .. ": half round trip")
end
local img8 = Types.Image.new(4, 4)
for i = 0, 63 do
buffer.writeu8(img8.pixels, i, (i * 37) % 256)
end
local back8 = dec(Exr.encode(img8, { pixelType = "float" }) :: buffer)
local ok = true
for i = 0, 63 do
ok = ok and math.abs(buffer.readu8(back8.pixels, i) - buffer.readu8(img8.pixels, i)) <= 1
end
t:check(ok, "rgba8 through the display curve and back")
local _, e = Exr.encode(f, { compression = "piz" :: any })
t:check(e and e.code == Err.ARG, "no PIZ encoder")
end
-- sniff, info, errors
do
local c = Fx.cases[1]
t:eq(Exr.sniff(Bytes.reader(buffer.fromstring(c.data))), 1, "sniff")
t:eq(Exr.sniff(Bytes.reader(buffer.fromstring("v/1\0"))), 0, "sniff other")
local info = Exr.info(Bytes.reader(buffer.fromstring(c.data)))
t:check(info and #info.parts == 1 and #info.parts[1].channels == 4, "info")
local _, e = dec(string.sub(c.data, 1, 40))
t:check(e and e.code == Err.TRUNCATED, "short header: " .. tostring(e))
local _, e2 = dec(c.data, { maxPixels = 10 })
t:check(e2 and e2.code == Err.LIMIT, "limit")
local _, e3 = dec(c.data, { part = 3 })
t:check(e3 and e3.code == Err.ARG, "no such part")
-- a zeroed offset table is rebuilt
local b = buffer.fromstring(c.data)
local info2 = Exr.info(Bytes.reader(b)) :: any
local tab = info2.dataStart - 8 * info2.parts[1].chunks
buffer.fill(b, tab, 0, 8 * info2.parts[1].chunks)
local img = dec(b, { native = true })
t:check(img and buffer.tostring(img.pixels) == buffer.tostring(dec(c.data, { native = true }).pixels), "rebuilt offset table")
end
local samples = {}
for i, c in Fx.cases do
if i % 3 == 0 or c.unsupported then
table.insert(samples, c.data)
end
end
t:fuzz("decode", function(b: buffer)
return dec(b, { mips = true })
end, samples, { mutations = 6 })
t:done()
+84
View File
@@ -0,0 +1,84 @@
-- image/icns tests: a libicns file (RLE entries + masks, JPEG 2000 entries skipped), a Pillow file (PNG entries through
-- the decodeImage hook) and a hand-written one (ics#, raw is32, ic04 ARGB) against icns2png's / the written pixels;
-- our RLE file read back by icns2png; PNG entries through encodeImage; errors; the fuzz no-throw pass. Fixtures:
-- tools/fixtures/icns.py.
local T = require("@tests/T")
local Icns = require("@formats/image/icns")
local Png = require("@formats/image/png")
local Bytes = require("@formats/core/Bytes")
local Err = require("@formats/core/Err")
local Types = require("@formats/Types")
local R = require("@tests/image/_raster")
local Fx = require("@tests/gen/icns")
local t = T.suite("icns")
t:eq(Icns.name, "icns", "name")
t:check(Icns.caps.decode and Icns.caps.encode, "caps")
local hooks = {
decodeImage = function(b: buffer): (any, any)
return Png.decode(Bytes.reader(b))
end,
encodeImage = function(img: any, _fmt: string): (any, any)
return Png.encode(img)
end,
}
local function check(c: any)
local img, err = Icns.decode(Bytes.reader(buffer.fromstring(c.data)), hooks)
t:check(img, c.name .. ": " .. tostring(err))
local frames = img.frames or { { image = img } }
t:check(#frames >= #c.entries, c.name .. ": entries") -- icns2png writes one file per size (@2x entries collide)
for _, e in c.entries do
local found = nil
for _, f in frames do
local im = f.image
if im.width == e.w and im.height == e.h and (e.type == "" or im.meta.source.type == e.type) then
found = im
end
end
t:check(found, c.name .. ": entry " .. e.type .. " " .. e.w)
if found then
local d = R.maxDiff(found.pixels, buffer.fromstring(e.rgba), e.w * e.h)
t:eq(d, 0, string.format("%s: %s %dx%d pixels", c.name, e.type, e.w, e.h))
end
end
t:eq(if img.meta.skipped then #img.meta.skipped else 0, c.skipped or 0, c.name .. ": skipped entries")
return img
end
for _, c in Fx.cases do
check(c)
end
for _, o in Fx.ours do
check(o)
end
t:note("%d files and our encoder's file match", #Fx.cases)
do
-- PNG entries through the hooks, legacy entries without them
local img = Types.Image.new(64, 64)
for i = 0, 64 * 64 - 1 do
buffer.writeu32(img.pixels, i * 4, i * 2654435761 % 4294967296)
end
local small = Types.Image.new(16, 16)
buffer.fill(small.pixels, 0, 200)
img.frames = { { image = img, delay = 0, x = 0, y = 0, dispose = "none", blend = "source" }, { image = small, delay = 0, x = 0, y = 0, dispose = "none", blend = "source" } }
local enc = Icns.encode(img, hooks) :: buffer
local back = Icns.decode(Bytes.reader(enc), hooks) :: any
t:check(back and back.width == 64 and buffer.tostring(back.pixels) == buffer.tostring(img.pixels), "PNG entries round trip")
t:eq(#back.frames, 2, "two sizes")
local _, e = Icns.encode(img)
t:check(e and e.code == Err.ARG, "64 x 64 needs the PNG hook")
local leg = Icns.encode(small) :: buffer
local lb = Icns.decode(Bytes.reader(leg)) :: any
t:eq(buffer.tostring(lb.pixels), buffer.tostring(small.pixels), "legacy round trip")
local _, e2 = Icns.decode(Bytes.reader(enc))
t:check(e2 and e2.code == Err.UNSUPPORTED, "PNG entries without the hook: UNSUPPORTED")
t:eq(Icns.sniff(Bytes.reader(enc)), 1, "sniff")
local _, e3 = Icns.encode(Types.Image.new(10, 12))
t:check(e3 and e3.code == Err.ARG, "not square")
end
t:fuzz("decode", function(b: buffer)
return Icns.decode(Bytes.reader(b), hooks)
end, R.samples(Fx.cases), { mutations = 6 })
t:done()
+72
View File
@@ -0,0 +1,72 @@
-- image/ilbm tests: files from netpbm's ppmtoilbm (palette, uncompressed, HAM6, HAM8, 24-bit) and hand-written ones
-- (EHB, chunky PBM, a mask plane, a transparent colour) against ilbmtoppm (colours) and the written masks (alpha); our
-- encoder's files read by ilbmtoppm; round trips (palette, 24 and 32 planes, uncompressed); errors; the fuzz no-throw
-- pass. Fixtures: tools/fixtures/ilbm.py.
local T = require("@tests/T")
local Ilbm = require("@formats/image/ilbm")
local Bytes = require("@formats/core/Bytes")
local Err = require("@formats/core/Err")
local R = require("@tests/image/_raster")
local Fx = require("@tests/gen/ilbm")
local t = T.suite("ilbm")
t:eq(Ilbm.name, "ilbm", "name")
t:check(Ilbm.caps.decode and Ilbm.caps.encode, "caps")
local function check(c: any)
local img, err = Ilbm.decode(Bytes.reader(buffer.fromstring(c.data)))
t:check(img, c.name .. ": " .. tostring(err))
t:check(img.width == c.w and img.height == c.h, c.name .. ": size")
local ref = buffer.fromstring(c.rgba)
local bad, badA = 0, 0
for i = 0, c.w * c.h - 1 do
local transparent = c.transparent and c.transparent[i + 1]
local v = buffer.readu32(img.pixels, i * 4)
if transparent then
badA += if v == 0 then 0 else 1
else
for k = 0, 3 do
if math.abs(buffer.readu8(img.pixels, i * 4 + k) - buffer.readu8(ref, i * 4 + k)) > (c.tol or 0) then
bad += 1
break
end
end
end
end
t:eq(bad, 0, c.name .. ": colours against ilbmtoppm")
t:eq(badA, 0, c.name .. ": transparent pixels")
return img
end
for _, c in Fx.cases do
check(c)
if not c.transparent and not c.tol then
R.roundTrip(t, Ilbm, R.image(c.w, c.h, c.rgba), nil, c.name .. " re-encoded")
R.roundTrip(t, Ilbm, R.image(c.w, c.h, c.rgba), { compress = false }, c.name .. " re-encoded uncompressed")
end
end
for _, o in Fx.ours do
check(o)
end
t:note("%d files and %d of ours match ilbmtoppm", #Fx.cases, #Fx.ours)
do
local img = R.image(3, 2, string.rep("\1\2\3\128", 6))
local enc = R.roundTrip(t, Ilbm, img, nil, "alpha: 32 planes") :: buffer
t:eq(Ilbm.sniff(Bytes.reader(enc)), 1, "sniff")
t:eq(Ilbm.sniff(Bytes.reader(buffer.fromstring("FORM\0\0\0\4AIFF"))), 0, "sniff AIFF")
local back = Ilbm.decode(Bytes.reader(enc)) :: any
t:eq(back.meta.source.planes, 32, "32 planes")
local _, e = Ilbm.decode(Bytes.reader(buffer.fromstring("FORM\0\0\0\4ILBM")))
t:check(e and e.code == Err.CORRUPT, "no BMHD")
local _, e2 = Ilbm.decode(Bytes.reader(enc), { maxPixels = 2 })
t:check(e2 and e2.code == Err.LIMIT, "limit")
for _, c in Fx.cases do
if c.name == "hand_transparent.iff" then
local im = Ilbm.decode(Bytes.reader(buffer.fromstring(c.data))) :: any
t:eq(im.meta.text and im.meta.text.name, "tiny", "NAME chunk")
end
end
end
t:fuzz("decode", function(b: buffer)
return Ilbm.decode(Bytes.reader(b))
end, R.samples(Fx.cases), { mutations = 6 })
t:done()
+167
View File
@@ -0,0 +1,167 @@
-- image/ktx tests: KTX2 files from KTX-Software (`ktx create` from PNGs and raw data in uncompressed / packed / float /
-- BCn / ETC2 / EAC formats, mips, cube maps, arrays, 3D, Zstandard and ZLIB supercompression; Basis Universal is
-- UNSUPPORTED) and KTX1 files from toktx / nvcompress / hand-written ones (big-endian, packed types, row padding,
-- KTXorientation) against their sources or reference decodes; our KTX2 files through `ktx validate` / `ktx extract`;
-- round trips; errors; the fuzz no-throw pass. Fixtures: tools/fixtures/ktx.py.
local T = require("@tests/T")
local Ktx = require("@formats/image/ktx")
local Bytes = require("@formats/core/Bytes")
local Err = require("@formats/core/Err")
local Types = require("@formats/Types")
local Fx = require("@tests/gen/ktx")
local t = T.suite("ktx")
t:eq(Ktx.name, "ktx", "name")
t:check(Ktx.caps.decode and Ktx.caps.encode, "caps")
local function dec(data: any, opts: any?): (any, any)
return Ktx.decode(Bytes.reader(if type(data) == "string" then buffer.fromstring(data) else data), opts)
end
local function maxDiff(a: buffer, b: buffer, n: number): number
local worst = 0
for i = 0, n * 4 - 1 do
worst = math.max(worst, math.abs(buffer.readu8(a, i) - buffer.readu8(b, i)))
end
return worst
end
local nsurf = 0
for _, c in Fx.cases do
if c.unsupported then
local img, e = dec(c.data)
t:check(img == nil and e and e.code == Err.UNSUPPORTED, c.name .. ": UNSUPPORTED (" .. tostring(e) .. ")")
continue
end
local img, err = dec(c.data, { mips = true })
t:check(img, c.name .. ": " .. tostring(err))
if c.layout then
t:eq(img.meta.layout, c.layout, c.name .. ": layout")
end
if c.mips then
t:eq(img.meta.source.mips, c.mips, c.name .. ": mip count")
end
if c.srgb then
t:eq(img.meta.colorSpace, "srgb", c.name .. ": sRGB")
end
local native = nil
local frames = img.frames or { { image = img } }
for _, s in c.surfaces do
local label = string.format("%s: level %d layer %d slice %d", c.name, s.level, s.layer, s.slice)
local im
if s.level == 0 then
local f = frames[s.layer + s.slice + 1]
im = f and f.image
else
im = img.meta.mipmaps and img.meta.mipmaps[s.level]
end
t:check(im and im.width == s.w and im.height == s.h, label .. ": surface size")
if s.rgba then
local d = maxDiff(im.pixels, buffer.fromstring(s.rgba), s.w * s.h)
t:check(d <= s.tol, string.format("%s: %d off the reference", label, d))
end
if s.floats and s.level == 0 and s.layer == 0 then
native = native or dec(c.data, { native = true })
local f = buffer.fromstring(s.floats)
local worst = 0
for i = 0, s.w * s.h * 4 - 1 do
local want = buffer.readf32(f, i * 4)
local got
if native.format == "rgbaf32" then
got = buffer.readf32(native.pixels, i * 4)
elseif native.format == "rgba16" then
got = buffer.readu16(native.pixels, i * 2) / 65535
else
got = buffer.readu8(native.pixels, i) / 255
end
if i % 4 ~= 3 or not string.find(c.name, "bc6h") then
worst = math.max(worst, math.abs(got - want) / math.max(1, math.abs(want)))
end
end
local tol = if native.format == "rgba8" then 1 / 255 elseif native.format == "rgba16" then 1 / 65535 else 1e-3
t:check(worst <= tol + 1e-9, string.format("%s: native %s off by %g", label, native.format, worst))
end
nsurf += 1
end
end
t:note("%d files, %d surfaces match", #Fx.cases, nsurf)
-- our files: ktx validate accepts them, ktx extract reads the first image
local function source(w: number, h: number): buffer
local px = buffer.create(w * h * 4)
for y = 0, h - 1 do
for x = 0, w - 1 do
local o = (y * w + x) * 4
buffer.writeu8(px, o, math.floor(x / (w - 1) * 255 + 0.5))
buffer.writeu8(px, o + 1, math.floor(y / (h - 1) * 255 + 0.5))
buffer.writeu8(px, o + 2, math.floor(((x * 7 + y * 13) % 64) / 63 * 255 + 0.5))
buffer.writeu8(px, o + 3, math.floor(((x + y) % 5) / 4 * 255 + 0.5))
end
end
return px
end
local src = source(37, 23)
for _, o in Fx.ours do
t:check(o.valid, o.name .. ": ktx validate: " .. tostring(o.report))
local img, err = dec(o.data, { mips = true, native = true })
t:check(img, o.name .. ": " .. tostring(err))
if o.png and (string.find(o.name, "rgba8") or string.find(o.name, "srgb")) then
t:eq(o.png, buffer.tostring(src), o.name .. ": ktx extract gives the source")
end
if string.find(o.name, "mips") or string.find(o.name, "zlib") then
t:eq(#img.meta.mipmaps, 5, o.name .. ": mip chain")
end
if string.find(o.name, "cube") then
t:eq(img.meta.layout, "cube", o.name .. ": cube")
t:eq(#img.frames, 6, o.name .. ": faces")
end
end
t:note("%d of our files pass ktx validate", #Fx.ours)
-- round trips
do
local img = Types.Image.new(37, 23)
img.pixels = src
for _, o in { {}, { mips = true }, { zlib = 9 }, { srgb = true } } do
local back = dec(Ktx.encode(img, o :: any) :: buffer)
t:eq(buffer.tostring(back.pixels), buffer.tostring(src), "rgba8 round trip")
end
local f = Types.Image.new(3, 2, "rgbaf32")
for i = 0, 23 do
buffer.writef32(f.pixels, i * 4, i * 0.37 - 2)
end
local back = dec(Ktx.encode(f) :: buffer, { native = true })
t:eq(buffer.tostring(back.pixels), buffer.tostring(f.pixels), "rgba32f round trip")
local _, e = Ktx.encode(f, { pixelFormat = "rgba8" })
t:check(e and e.code == Err.ARG, "format mismatch")
local _, e2 = Ktx.encode(img, { zlib = 12 })
t:check(e2 and e2.code == Err.ARG, "zlib level")
end
-- sniff, info, errors
do
local c = Fx.cases[1]
t:eq(Ktx.sniff(Bytes.reader(buffer.fromstring(c.data))), 1, "sniff KTX2")
t:eq(Ktx.sniff(Bytes.reader(buffer.fromstring("\171KTX 11\187\r\n\26\n"))), 1, "sniff KTX1")
t:eq(Ktx.sniff(Bytes.reader(buffer.fromstring("PNG"))), 0, "sniff other")
local info = Ktx.info(Bytes.reader(buffer.fromstring(c.data)))
t:check(info and info.version == 2 and info.vkFormat == 37, "info")
local _, e = dec(string.sub(c.data, 1, 60))
t:check(e and e.code == Err.TRUNCATED, "short header")
local _, e2 = dec(string.sub(c.data, 1, #c.data - 100))
t:check(e2 and e2.code == Err.TRUNCATED, "cut data: " .. tostring(e2))
local _, e3 = dec(c.data, { maxPixels = 10 })
t:check(e3 and e3.code == Err.LIMIT, "limit")
end
local samples = {}
for i, c in Fx.cases do
if i % 2 == 0 or c.unsupported then
table.insert(samples, c.data)
end
end
t:fuzz("decode", function(b: buffer)
return dec(b, { mips = true })
end, samples, { mutations = 6 })
t:done()
+39
View File
@@ -0,0 +1,39 @@
-- image/pcx tests: files from netpbm (24-bit, 8-bit, packed 2 / 4-bit, 3 / 4 planes, mono), ImageMagick and Pillow
-- against pcxtoppm's decode; our files read by ImageMagick; round trips (palette, 24-bit, 32-bit alpha); errors; the
-- fuzz no-throw pass. Fixtures: tools/fixtures/pcx.py.
local T = require("@tests/T")
local Pcx = require("@formats/image/pcx")
local Bytes = require("@formats/core/Bytes")
local Err = require("@formats/core/Err")
local R = require("@tests/image/_raster")
local Fx = require("@tests/gen/pcx")
local t = T.suite("pcx")
t:eq(Pcx.name, "pcx", "name")
t:check(Pcx.caps.decode and Pcx.caps.encode, "caps")
t:note("%d files match pcxtoppm", R.decodes(t, Pcx, Fx.cases))
-- our files: ImageMagick reads what we decode
for _, o in Fx.ours do
local img = Pcx.decode(Bytes.reader(buffer.fromstring(o.data))) :: any
t:eq(R.maxDiff(img.pixels, buffer.fromstring(o.rgba), o.w * o.h), 0, o.name .. ": ImageMagick reads our file")
end
for _, c in Fx.cases do
R.roundTrip(t, Pcx, R.image(c.w, c.h, c.rgba), nil, c.name .. " re-encoded")
R.roundTrip(t, Pcx, R.image(c.w, c.h, c.rgba), { palette = false }, c.name .. " re-encoded 24-bit")
end
do
local img = R.image(3, 2, string.rep("\1\2\3\128", 6))
local enc = R.roundTrip(t, Pcx, img, nil, "alpha: 4 planes") :: buffer
t:eq(buffer.readu8(enc, 65), 4, "alpha -> 4 planes")
t:eq(Pcx.sniff(Bytes.reader(enc)), 0.8, "sniff")
t:eq(Pcx.sniff(Bytes.reader(buffer.fromstring("GIF89a"))), 0, "sniff other")
local _, e = Pcx.decode(Bytes.reader(buffer.fromstring(string.sub(buffer.tostring(enc), 1, 60))))
t:check(e and e.code == Err.TRUNCATED, "short header")
local _, e2 = Pcx.decode(Bytes.reader(enc), { maxPixels = 2 })
t:check(e2 and e2.code == Err.LIMIT, "limit")
end
t:fuzz("decode", function(b: buffer)
return Pcx.decode(Bytes.reader(b))
end, R.samples(Fx.cases), { mutations = 6 })
t:done()
+34
View File
@@ -0,0 +1,34 @@
-- image/sgi tests: files from netpbm / ImageMagick / Pillow against ImageMagick's decode, our encoder's files read
-- by ImageMagick, round trips through every option, errors, the fuzz no-throw pass. Fixtures: tools/fixtures/sgi.py.
local T = require("@tests/T")
local Sgi = require("@formats/image/sgi")
local Bytes = require("@formats/core/Bytes")
local Err = require("@formats/core/Err")
local R = require("@tests/image/_raster")
local Fx = require("@tests/gen/sgi")
local t = T.suite("sgi")
t:eq(Sgi.name, "sgi", "name")
t:check(Sgi.caps.decode and Sgi.caps.encode, "caps")
t:note("%d files match ImageMagick", R.decodes(t, Sgi, Fx.cases))
t:note("%d of our files read by ImageMagick", R.decodes(t, Sgi, Fx.ours))
for _, c in Fx.cases do
R.roundTrip(t, Sgi, R.image(c.w, c.h, c.rgba), nil, c.name .. " re-encoded")
R.roundTrip(t, Sgi, R.image(c.w, c.h, c.rgba), { rle = false }, c.name .. " re-encoded without RLE")
end
do
local enc = Sgi.encode(R.image(2, 2, string.rep("\1\2\3\4", 4))) :: buffer
t:eq(Sgi.sniff(Bytes.reader(enc)), 1, "sniff")
t:eq(Sgi.sniff(Bytes.reader(buffer.fromstring("GIF89a"))), 0, "sniff other")
local _, e = Sgi.decode(Bytes.reader(buffer.fromstring(string.sub(buffer.tostring(enc), 1, 20))))
t:check(e and e.code == Err.TRUNCATED, "short header")
local _, e2 = Sgi.decode(Bytes.reader(enc), { maxPixels = 2 })
t:check(e2 and e2.code == Err.LIMIT, "limit")
local _, e3 = Sgi.encode({} :: any)
t:check(e3 and e3.code == Err.ARG, "bad image")
end
t:fuzz("decode", function(b: buffer)
return Sgi.decode(Bytes.reader(b))
end, R.samples(Fx.cases), { mutations = 6 })
t:done()
+42
View File
@@ -0,0 +1,42 @@
-- image/sunras tests: files from netpbm / ImageMagick against ImageMagick's decode, our encoder's files read
-- by rasttopnm, round trips through every option, errors, the fuzz no-throw pass. Fixtures: tools/fixtures/sunras.py.
local T = require("@tests/T")
local Sunras = require("@formats/image/sunras")
local Bytes = require("@formats/core/Bytes")
local Err = require("@formats/core/Err")
local R = require("@tests/image/_raster")
local Fx = require("@tests/gen/sunras")
local t = T.suite("sunras")
t:eq(Sunras.name, "sunras", "name")
t:check(Sunras.caps.decode and Sunras.caps.encode, "caps")
t:note("%d files match rasttopnm / ImageMagick", R.decodes(t, Sunras, Fx.cases))
-- our files: rasttopnm reads the colours (it drops alpha)
for _, o in Fx.ours do
local img = Sunras.decode(Bytes.reader(buffer.fromstring(o.data))) :: any
local px = buffer.fromstring(buffer.tostring(img.pixels))
for i = 0, o.w * o.h - 1 do
buffer.writeu8(px, i * 4 + 3, 255)
end
t:eq(R.maxDiff(px, buffer.fromstring(o.rgba), o.w * o.h), 0, o.name .. ": rasttopnm reads our file")
end
for _, c in Fx.cases do
R.roundTrip(t, Sunras, R.image(c.w, c.h, c.rgba), nil, c.name .. " re-encoded")
R.roundTrip(t, Sunras, R.image(c.w, c.h, c.rgba), { rle = false }, c.name .. " re-encoded without RLE")
end
do
local enc = Sunras.encode(R.image(2, 2, string.rep("\1\2\3\4", 4))) :: buffer
t:eq(Sunras.sniff(Bytes.reader(enc)), 1, "sniff")
t:eq(Sunras.sniff(Bytes.reader(buffer.fromstring("GIF89a"))), 0, "sniff other")
local _, e = Sunras.decode(Bytes.reader(buffer.fromstring(string.sub(buffer.tostring(enc), 1, 20))))
t:check(e and e.code == Err.TRUNCATED, "short header")
local _, e2 = Sunras.decode(Bytes.reader(enc), { maxPixels = 2 })
t:check(e2 and e2.code == Err.LIMIT, "limit")
local _, e3 = Sunras.encode({} :: any)
t:check(e3 and e3.code == Err.ARG, "bad image")
end
t:fuzz("decode", function(b: buffer)
return Sunras.decode(Bytes.reader(b))
end, R.samples(Fx.cases), { mutations = 6 })
t:done()
+43
View File
@@ -0,0 +1,43 @@
-- image/xbm tests: files from netpbm / ImageMagick / Pillow and hand-written ones against the reference decode
-- (xbmtopbm), our encoder's files read back by it, round trips, errors, the fuzz no-throw pass.
-- Fixtures: tools/fixtures/xbm.py.
local T = require("@tests/T")
local Xbm = require("@formats/image/xbm")
local Bytes = require("@formats/core/Bytes")
local Err = require("@formats/core/Err")
local R = require("@tests/image/_raster")
local Fx = require("@tests/gen/xbm")
local t = T.suite("xbm")
t:eq(Xbm.name, "xbm", "name")
t:check(Xbm.caps.decode and Xbm.caps.encode, "caps")
t:note("%d files match the reference", R.decodes(t, Xbm, Fx.cases))
t:note("%d of our files read back by it", R.decodes(t, Xbm, Fx.ours))
for _, c in Fx.cases do
R.roundTrip(t, Xbm, R.image(c.w, c.h, c.rgba), nil, c.name .. " re-encoded")
if c.hotspot then
local img = Xbm.decode(Bytes.reader(buffer.fromstring(c.data))) :: any
t:check(img.meta.hotspot and img.meta.hotspot.x == c.hotspot[1] and img.meta.hotspot.y == c.hotspot[2], c.name .. ": hotspot")
end
end
do
-- decimal and octal values, the X10 short arrays
local img = Xbm.decode(Bytes.reader(buffer.fromstring("#define a_width 9\n#define a_height 1\nstatic char a_bits[] = { 1, 0400 };"))) :: any
t:eq(buffer.readu32(img.pixels, 0), 0xFF000000, "decimal: pixel 0 black")
t:eq(buffer.readu32(img.pixels, 4), 0xFFFFFFFF, "decimal: pixel 1 white")
local x10 = Xbm.decode(Bytes.reader(buffer.fromstring("#define b_width 17\n#define b_height 1\nstatic short b_bits[] = { 0x8001, 0x0001 };"))) :: any
t:eq(buffer.readu32(x10.pixels, 15 * 4), 0xFF000000, "x10: bit 15")
t:eq(buffer.readu32(x10.pixels, 16 * 4), 0xFF000000, "x10: second short")
local tr = Xbm.decode(Bytes.reader(buffer.fromstring("#define c_width 2\n#define c_height 1\nstatic char c_bits[] = { 0x01 };")), { transparent = true }) :: any
t:eq(buffer.readu32(tr.pixels, 4), 0x00FFFFFF, "transparent clear bits")
t:eq(Xbm.sniff(Bytes.reader(buffer.fromstring("#define c_width 2\n"))), 0.9, "sniff")
local _, e = Xbm.decode(Bytes.reader(buffer.fromstring("static char x[] = {};")))
t:check(e and e.code == Err.CORRUPT, "no defines")
local named = Xbm.encode(R.image(1, 1, "\0\0\0\255"), { name = "1 bad.xbm" }) :: buffer
t:check(string.find(buffer.tostring(named), "#define _1_bad_width 1", 1, true) ~= nil, "name made an identifier")
end
t:fuzz("decode", function(b: buffer)
return Xbm.decode(Bytes.reader(b))
end, R.samples(Fx.cases), { mutations = 6 })
t:done()
+44
View File
@@ -0,0 +1,44 @@
-- image/xpm tests: files from netpbm / ImageMagick and hand-written ones against the reference decode
-- (ImageMagick), our encoder's files read back by it, round trips, errors, the fuzz no-throw pass.
-- Fixtures: tools/fixtures/xpm.py.
local T = require("@tests/T")
local Xpm = require("@formats/image/xpm")
local Bytes = require("@formats/core/Bytes")
local Err = require("@formats/core/Err")
local R = require("@tests/image/_raster")
local Fx = require("@tests/gen/xpm")
local t = T.suite("xpm")
t:eq(Xpm.name, "xpm", "name")
t:check(Xpm.caps.decode and Xpm.caps.encode, "caps")
t:note("%d files match the reference", R.decodes(t, Xpm, Fx.cases))
t:note("%d of our files read back by it", R.decodes(t, Xpm, Fx.ours))
for _, c in Fx.cases do
R.roundTrip(t, Xpm, R.image(c.w, c.h, c.rgba), nil, c.name .. " re-encoded")
if c.hotspot then
local img = Xpm.decode(Bytes.reader(buffer.fromstring(c.data))) :: any
t:check(img.meta.hotspot and img.meta.hotspot.x == c.hotspot[1] and img.meta.hotspot.y == c.hotspot[2], c.name .. ": hotspot")
end
end
do
local img = Xpm.decode(Bytes.reader(buffer.fromstring('/* XPM */\nstatic char *x[] = {"2 1 2 1 0 0", "a c gray50", "b c Unknownish", "ab"};'))) :: any
t:eq(buffer.readu32(img.pixels, 0), 0xFF7F7F7F, "gray50")
t:check(img.meta.unknownColours and img.meta.unknownColours[1] == "Unknownish", "unknown colour listed")
t:check(img.meta.hotspot and img.meta.hotspot.x == 0, "hotspot")
t:eq(Xpm.sniff(Bytes.reader(buffer.fromstring("/* XPM */\n"))), 1, "sniff")
local _, e = Xpm.decode(Bytes.reader(buffer.fromstring('/* XPM */ static char *x[] = {"2 1 5 1", "a c red"};')))
t:check(e and e.code == Err.TRUNCATED, "short colour table")
-- many colours: two chars per pixel
local big = R.image(300, 1, "")
big.pixels = buffer.create(1200)
for i = 0, 299 do
buffer.writeu32(big.pixels, i * 4, i * 997 + 0xFF000000)
end
local enc = R.roundTrip(t, Xpm, big, nil, "300 colours") :: buffer
t:check(string.find(buffer.tostring(enc), '"300 1 300 2"', 1, true) ~= nil, "two chars per pixel")
end
t:fuzz("decode", function(b: buffer)
return Xpm.decode(Bytes.reader(b))
end, R.samples(Fx.cases), { mutations = 6 })
t:done()
+124
View File
@@ -0,0 +1,124 @@
-- layered/ora tests: OpenRaster files assembled by the spec (offsets, opacity, hidden, composite-ops, nested isolate /
-- auto stacks, no merged image) against the attributes and pixels written there; our encoder's file taken apart by
-- python (stored mimetype first, stack.xml, Pillow's read of every PNG); round trips; hooks; errors; the fuzz no-throw
-- pass. Fixtures: tools/fixtures/ora.py.
local T = require("@tests/T")
local Ora = require("@formats/layered/ora")
local Png = require("@formats/image/png")
local Bytes = require("@formats/core/Bytes")
local Err = require("@formats/core/Err")
local Fx = require("@tests/gen/ora")
local t = T.suite("ora")
t:eq(Ora.name, "ora", "name")
t:eq(Ora.category, "layered", "category")
t:check(Ora.caps.decode and Ora.caps.encode, "caps")
local hooks = {
decodeImage = function(b: buffer): (any, any)
return Png.decode(Bytes.reader(b))
end,
encodeImage = function(img: any, _f: string): (any, any)
return Png.encode(img)
end,
}
-- the tree depth-first, bottom to top, groups before their children
local function walk(layers: { any }, depth: number, out: { any })
for _, l in layers do
table.insert(out, { layer = l, depth = depth })
if l.children then
walk(l.children, depth + 1, out)
end
end
return out
end
local function compare(label: string, doc: any, want: { any })
local got = walk(doc.layers, 0, {})
t:eq(#got, #want, label .. ": layer count")
for i, w in want do
local g = got[i]
if not g then
break
end
local l = g.layer
local ll = label .. ": " .. w.name
t:eq(l.name, w.name, ll .. " name")
t:eq(g.depth, w.depth, ll .. " depth")
t:check(math.abs(l.opacity - w.opacity) < 1e-6, ll .. " opacity")
t:eq(l.visible, w.visible, ll .. " visibility")
t:eq(l.blend, w.blend, ll .. " blend")
if not w.group then
t:check(l.x == w.x and l.y == w.y, ll .. " position")
t:check(l.image.width == w.w and l.image.height == w.h and buffer.tostring(l.image.pixels) == w.rgba, ll .. " pixels")
else
t:check(l.children ~= nil, ll .. " is a group")
end
end
end
for _, c in Fx.cases do
local doc, err = Ora.decode(Bytes.reader(buffer.fromstring(c.data)), hooks)
t:check(doc, c.name .. ": " .. tostring(err))
t:check(doc.kind == "layered" and doc.width == c.w and doc.height == c.h, c.name .. ": size")
compare(c.name, doc, c.layers)
t:eq(doc.meta.composite ~= nil, c.merged, c.name .. ": merged image")
if c.dpi then
t:eq(doc.meta.dpi.x, c.dpi, c.name .. ": dpi")
end
-- round trip
local enc, eerr = Ora.encode(doc, hooks)
t:check(enc, c.name .. ": encode " .. tostring(eerr))
local back = Ora.decode(Bytes.reader(enc :: buffer), hooks)
compare(c.name .. " round trip", back, c.layers)
t:eq(Ora.sniff(Bytes.reader(enc :: buffer)), 1, c.name .. ": sniff our file")
end
-- our encoder's file, as python and Pillow read it
do
local o = Fx.ours
t:check(o.ok, "ours: mimetype first, stored")
t:eq(o.entries[1], "mimetype", "ours: first entry")
t:check(table.find(o.entries, "mergedimage.png") ~= nil and table.find(o.entries, "Thumbnails/thumbnail.png") ~= nil, "ours: merged image and thumbnail")
t:check(o.thumb[1] == 40 and o.thumb[2] == 30, "ours: thumbnail size")
local doc = Ora.decode(Bytes.reader(buffer.fromstring(o.data)), hooks) :: any
t:check(doc and doc.width == o.w and doc.height == o.h, "ours: decodes")
-- python's walk is top first (xml order): compare by name
local byName = {}
for _, g in walk(doc.layers, 0, {}) do
byName[g.layer.name] = g
end
for _, l in o.layers do
local g = byName[l.name]
t:check(g, "ours: layer " .. l.name)
if g then
t:check(math.abs(g.layer.opacity - l.opacity) < 1e-6 and g.layer.visible == l.visible and g.depth == l.depth, "ours: " .. l.name .. " attributes")
if l.tag == "layer" then
t:check(g.layer.x == l.x and g.layer.y == l.y, "ours: " .. l.name .. " position")
t:eq(buffer.tostring(g.layer.image.pixels), l.rgba, "ours: " .. l.name .. " pixels through Pillow")
end
end
end
t:eq(buffer.tostring(doc.meta.composite.pixels), o.merged.rgba, "ours: merged image through Pillow")
end
do
local c = Fx.cases[1]
local _, e = Ora.decode(Bytes.reader(buffer.fromstring(c.data)))
t:check(e and e.code == Err.UNSUPPORTED, "no decodeImage hook")
local doc = Ora.decode(Bytes.reader(buffer.fromstring(c.data)), hooks) :: any
local _, e2 = Ora.encode(doc)
t:check(e2 and e2.code == Err.UNSUPPORTED, "no encodeImage hook")
local _, e3 = Ora.encode({} :: any, hooks)
t:check(e3 and e3.code == Err.ARG, "not a document")
t:eq(Ora.sniff(Bytes.reader(buffer.fromstring("PK\3\4"))), 0, "sniff a plain zip")
end
local samples = {}
for _, c in Fx.cases do
table.insert(samples, c.data)
end
t:fuzz("decode", function(b: buffer)
return Ora.decode(Bytes.reader(b), hooks)
end, samples, { mutations = 12 })
t:done()
+602
View File
@@ -0,0 +1,602 @@
-- model/3ds tests: assimp's 3DS test models (meshes, materials, textures, keyframer hierarchies, pivots, camera /
-- target / rotation animation, cameras, lights) and assimp's 3DS exporter output, against assimp (meshes, faces,
-- corners, materials, animations, cameras, lights, world bounds); the keyframer placing every mesh where its mesh
-- matrix says; round trips through our writer (world triangles, materials, textures, cameras, lights, sampled
-- animation) for the reference files and for glTF sample models; assimp reading our files like the originals
-- (3ds_xcheck); errors; the fuzz no-throw pass. Fixtures: tools/fixtures/3ds.py.
local T = require("@tests/T")
local F = require("@formats")
local ThreeDs = require("@formats/model/3ds")
local Gltf = require("@formats/model/gltf")
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/3ds_cases")
local Picks = require("@tests/gen/3ds_gltf")
local Xcheck = require("@tests/gen/3ds_xcheck")
local t = T.suite("3ds")
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 ThreeDs.decode(Bytes.reader(b), opts)
end
t:eq(ThreeDs.name, "3ds", "name")
t:eq(ThreeDs.category, "model", "category")
t:check(ThreeDs.caps.decode and ThreeDs.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
-- placed primitives, triangles, corners
local function counts(scene: any): (number, number, number)
local prims, faces, corners = 0, 0, 0
local seen = {}
for _, pl in S.flatten(scene) do
if not seen[pl.primitive] then
seen[pl.primitive] = true
prims += 1
faces += pl.primitive.indices.count // 3
corners += pl.primitive.indices.count
end
end
return prims, faces, corners
end
local function noMaterial(scene: any): boolean
for _, m in scene.meshes do
for _, p in m.primitives do
if p.material == nil then
return true
end
end
end
return false
end
-- assimp's default material: an existing grey untextured material named "*default*" is reused
local function defaultReused(scene: any): boolean
for _, m in scene.materials do
local c = m.baseColor
if string.find(string.lower(m.name or ""), "default", 1, true) and c[1] == c[2] and c[1] == c[3] and not m.baseColorTexture then
local x = m.extras["3ds"].maps
if next(x) == nil then
return true
end
end
end
return false
end
-- world bounds: as they are, or under assimp's Z-up -> Y-up root rotation (x, z, -y)
local function boundsMatch(lo: { number }, hi: { number }, want: any, eps: number): boolean
local function eq(a: { number }, b: { number }): boolean
for k = 1, 3 do
if not near(a[k], want.min[k], eps) or not near(b[k], want.max[k], eps) then
return false
end
end
return true
end
return eq(lo, hi) or eq({ lo[1], lo[3], -hi[2] }, { hi[1], hi[3], -lo[2] })
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
-- ------------------------------------------------------------------------------------------------ reference files
-- assimp ignores the camera / light frame of their children (CameraRollAnimWithChildObject: a box linked to the
-- camera); our bounds follow the mesh matrices there (checked below)
local ASSIMP_BOUNDS_DIFFER = { ["assimp/models/CameraRollAnimWithChildObject.3ds"] = true }
local function boundsDiffer(i: number): boolean
return ASSIMP_BOUNDS_DIFFER[Cases[i].name] == true
end
local scenes = {}
local checked = 0
for i, c in Cases do
local scene, err = decode(c.data)
local a = c.assimp
if a.failed then
t:note("%s: assimp rejects it; we read it: %s", c.name, tostring(scene ~= nil))
else
t:check(scene, c.name .. ": decode: " .. tostring(err))
scenes[i] = scene
if scene 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(#scene.cameras, a.cameras, c.name .. ": cameras (assimp)")
t:eq(#scene.lights, a.lights, c.name .. ": lights (assimp)")
t:eq(#scene.animations, a.animations, c.name .. ": animations (assimp)")
local extra = if noMaterial(scene) and not defaultReused(scene) then 1 else 0
t:eq(#scene.materials + extra, a.materials, c.name .. ": materials (assimp, + its default)")
if a.min and not ASSIMP_BOUNDS_DIFFER[c.name] then
local lo, hi = MeshOps.bounds(MeshOps.merge(scene))
t:check(lo and boundsMatch(lo, hi, a, 1e-3), c.name .. ": world bounds (assimp) " .. bstr(lo, hi) .. " want " .. bstr(a.min, a.max))
end
checked += 1
end
end
end
t:note("%d files against assimp", checked)
-- the keyframer places every mesh where its mesh matrix put the stored (world space) vertices
do
local n = 0
for i, c in Cases do
local scene = scenes[i]
if scene and scene.meta.source.keyframer and #scene.animations == 0 and string.sub(c.name, 1, 7) == "assimp/" then
local raw = decode(c.data, { normals = false })
local flat = decode(c.data, { normals = false })
-- the file's vertices: the meshes placed at identity (Read only; via the writer-free path: raw bounds)
local lo, hi = MeshOps.bounds(MeshOps.merge(raw))
local _ = flat
local Read = require("@formats/model/3ds/Read")
local parsed = Read.parse(buffer.fromstring(c.data), 0, #c.data)
local plo, phi = { math.huge, math.huge, math.huge }, { -math.huge, -math.huge, -math.huge }
local placed: { [string]: boolean } = {}
for _, kn in parsed.keyframer.nodes do
if kn.kind == "object" then
placed[kn.name] = true
end
end
for _, o in parsed.objects do
if o.mesh and o.mesh.nf > 0 and placed[o.name] then
for v = 0, o.mesh.nv - 1 do
for k = 1, 3 do
local x = buffer.readf32(o.mesh.positions, (v * 3 + k - 1) * 4)
plo[k], phi[k] = math.min(plo[k], x), math.max(phi[k], x)
end
end
end
end
if lo and plo[1] <= phi[1] then
local ok = true
for k = 1, 3 do
ok = ok and near(lo[k], plo[k], 2e-3) and near(hi[k], phi[k], 2e-3)
end
t:check(ok, c.name .. ": keyframer world bounds = the stored vertices " .. bstr(lo, hi) .. " / " .. bstr(plo, phi))
n += 1
end
end
end
t:note("%d keyframer scenes match their stored vertices", n)
end
-- ------------------------------------------------------------------------------------------------ round trips
local function triArea(prim: any): number
local P = S.reader(prim.attributes.POSITION) :: any
local I = S.reader(prim.indices) :: any
local area = 0
for tri = 0, prim.indices.count // 3 - 1 do
local a, b, c = I(tri * 3, 0), I(tri * 3 + 1, 0), I(tri * 3 + 2, 0)
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
-- the world matrices of the nodes with a camera / light, in tree order
local function worldOf(s: any, field: string): { { number } }
local out = {}
local function visit(i: number, parent: { number })
local n = s.nodes[i]
local w = S.mul(parent, S.nodeMatrix(n))
if n[field] then
table.insert(out, { w = w, item = n[field] })
end
for _, c in n.children do
visit(c, w)
end
end
for _, r in s.roots do
visit(r, S.IDENTITY)
end
return out
end
-- channel value at a time (LINEAR / STEP; quaternions lerped the short way)
local function evalCh(ch: any, time: number, 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
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
if ch.interpolation == "STEP" or t1 <= t0 then
return if time >= t1 then v(k + 1) else v(k)
end
local u = (time - t0) / (t1 - t0)
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
return r
end
end
return v(n - 1)
end
-- the world matrix of every named node at a time (animations[1] applied)
local function posed(s: any, time: number): { [string]: { number } }
local byNode: { [number]: { [string]: any } } = {}
local anim = s.animations[1]
if anim then
for _, ch in anim.channels do
byNode[ch.node] = byNode[ch.node] or {}
byNode[ch.node][ch.path] = ch
end
end
local out = {}
local count: { [string]: number } = {}
local function visit(i: number, parent: { number })
local n = s.nodes[i]
local m
local chs = byNode[i]
if chs then
local tr = if chs.translation then evalCh(chs.translation, time, 3) else (n.translation or { 0, 0, 0 })
local r = if chs.rotation then evalCh(chs.rotation, time, 4) else (n.rotation or { 0, 0, 0, 1 })
local sc = if chs.scale then evalCh(chs.scale, time, 3) else (n.scale or { 1, 1, 1 })
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 }
local Mat4 = require("@formats/codecs/model/Mat4")
m = Mat4.compose(tr, r, sc)
else
m = S.nodeMatrix(n)
end
local w = S.mul(parent, m)
local key = if n.mesh then "mesh" .. n.mesh elseif n.camera then "camera" else if n.light then "light" else nil
if key then
count[key] = (count[key] or 0) + 1
out[key .. "#" .. count[key]] = w
end
for _, c in n.children do
visit(c, w)
end
end
for _, r in s.roots do
visit(r, S.IDENTITY)
end
return out
end
local function compare(a: any, b: any, label: string, eps: number, animTimes: { number }?)
local ma, mb = MeshOps.merge(a), MeshOps.merge(b)
local na = if ma and ma.indices then ma.indices.count // 3 else 0
local nb = if mb and mb.indices then mb.indices.count // 3 else 0
t:eq(nb, na, label .. ": triangles")
if na > 0 and nb > 0 then
t:check(near(triArea(ma), triArea(mb), eps), string.format("%s: area %.7g / %.7g", label, triArea(ma), triArea(mb)))
local la, ha = MeshOps.bounds(ma)
local lb, hb = MeshOps.bounds(mb)
local ok = true
for k = 1, 3 do
ok = ok and near(la[k], lb[k], eps) and near(ha[k], hb[k], eps)
end
t:check(ok, label .. ": bounds " .. bstr(la, ha) .. " / " .. bstr(lb, hb))
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")
t:check(m.doubleSided == m2.doubleSided, label .. ": material " .. k .. " two-sided")
end
end
for _, field in { "camera", "light" } do
local pa, pb = worldOf(a, field), worldOf(b, field)
t:eq(#pb, #pa, label .. ": " .. field .. " nodes")
for k, e in pa do
local w = e.w
local w2 = pb[k] and pb[k].w
local ok = w2 ~= nil
if w2 then
-- position and view axis (3DS cameras and lights carry no scale)
for _, q in { 13, 14, 15 } do
ok = ok and near(w[q], w2[q], 1e-4)
end
if field == "camera" or a.lights[e.item].type ~= "point" then
local function z(m: { number }): (number, number, number)
local l = math.sqrt(m[9] * m[9] + m[10] * m[10] + m[11] * m[11])
return m[9] / l, m[10] / l, m[11] / l
end
local x1, y1, z1 = z(w)
local x2, y2, z2 = z(w2)
ok = ok and x1 * x2 + y1 * y2 + z1 * z2 > 0.9999
end
end
t:check(ok, label .. ": " .. field .. " " .. k .. " placement")
end
end
-- the horizontal field of view (3DS stores a lens, not the aspect)
for k, c in a.cameras do
local c2 = b.cameras[k]
if c2 and c.type == "perspective" then
local function hfov(cam: any): number
return 2 * math.atan(math.tan(cam.yfov / 2) * (cam.aspect or 4 / 3))
end
t:check(near(hfov(c), hfov(c2), 1e-5), label .. ": camera " .. k .. " fov")
end
end
-- one timeline: the first animation's node transforms
local trs = false
for _, ch in (if a.animations[1] then a.animations[1].channels else {}) :: { any } do
trs = trs or ch.path ~= "weights"
end
t:eq(#b.animations, if trs then 1 else 0, label .. ": animations")
if animTimes and #a.animations > 0 then
local bad, n = 0, 0
for _, time in animTimes do
local pa, pb = posed(a, time), posed(b, time)
for nm, w in pa do
local w2 = pb[nm]
if w2 then
for q = 1, 16 do
if not near(w[q], w2[q], 2e-3) then
bad += 1
end
end
n += 1
end
end
end
t:check(bad == 0 and n > 0, string.format("%s: posed world matrices: %d values of %d nodes x times differ", label, bad, n))
end
end
local TIMES = { 0, 0.1, 0.5, 1, 1.5, 2, 3.3, 5, 8 }
local nrt = 0
for i, c in Cases do
local scene = scenes[i]
if scene then
local out, err = ThreeDs.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-4, TIMES)
local p1, f1 = counts(scene)
local p2, f2 = counts(back)
t:check(p1 == p2 and f1 == f2, c.name .. ": primitives and faces kept")
-- the smoothing groups come back, so the normals do
local same = true
for mi, m in scene.meshes do
local m2 = back.meshes[mi]
for pi, p in m.primitives do
local p2 = m2 and m2.primitives[pi]
if not p2 or p2.attributes.POSITION.count ~= p.attributes.POSITION.count then
same = false
end
end
end
t:check(same, c.name .. ": vertex splits (smoothing groups) kept")
end
nrt += 1
end
end
-- glTF sample models through 3DS
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 = ThreeDs.encode(scene, { fps = 1000 })
t:check(out, g.name .. ": encode: " .. tostring(err))
local back, berr = decode(out :: buffer, { fps = 1000 })
t:check(back, g.name .. ": decode ours: " .. tostring(berr))
if back then
-- skins and morph targets are not 3DS; STEP / CUBICSPLINE keys become linear
local linear = true
for _, an in scene.animations do
for _, ch in an.channels do
if ch.interpolation ~= "LINEAR" or ch.path == "weights" then
linear = false
end
end
end
compare(scene, back, "glTF " .. g.name, 2e-4, if linear and #scene.skins == 0 then TIMES else nil)
ng += 1
end
end
end
t:note("%d reference files and %d glTF models through our writer and back", nrt, ng)
-- ------------------------------------------------------------------------------------------------ cross-check
-- assimp reads our files like the originals
local nx = 0
for _, x in Xcheck do
local a = x.assimp
t:check(not a.failed, x.name .. ": assimp reads our file")
if not a.failed then
local scene, want
if x.case then
scene, want = scenes[x.case], Cases[x.case].assimp
else
scene = gltfScenes[x.gltf]
end
if scene then
local _, faces, corners = counts(scene)
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.cameras, #worldOf(scene, "camera"), x.name .. ": assimp cameras of our file")
t:eq(a.lights, #worldOf(scene, "light"), x.name .. ": assimp lights of our file")
if want and not want.failed then
t:eq(a.meshes, want.meshes, x.name .. ": assimp meshes of our file")
t:eq(a.animations, want.animations, x.name .. ": assimp animations of our file")
end
if a.min and not (x.case and boundsDiffer(x.case)) then
local lo, hi = MeshOps.bounds(MeshOps.merge(scene))
t:check(lo and boundsMatch(lo, hi, a, 1e-3), x.name .. ": assimp world bounds of our file " .. bstr(lo, hi) .. " / " .. bstr(a.min, a.max))
end
nx += 1
end
end
end
t:note("%d of our files read back by assimp", nx)
-- ------------------------------------------------------------------------------------------------ details
do
local byName = {}
for i, c in Cases do
byName[c.name] = scenes[i]
end
local tex = byName["assimp/models/cube_with_diffuse_texture.3DS"]
if tex then
local m = tex.materials[1]
t:check(m.baseColorTexture and tex.textures[m.baseColorTexture.texture].uri ~= nil, "diffuse map -> baseColorTexture with a uri")
t:check(tex.textures[1].data == nil, "texture files are not read")
t:check(tex.meshes[1].primitives[1].attributes.TEXCOORD_0 ~= nil and tex.meshes[1].primitives[1].attributes.NORMAL ~= nil, "uvs and normals")
t:eq(tex.meta.up, "z", "3DS is Z up")
end
local spec = byName["assimp/models/cube_with_specular_texture.3DS"]
if spec then
t:check(spec.materials[1].extras["3ds"].maps.specular ~= nil, "specular map kept in extras")
end
local alpha = byName["assimp/models/cubes_with_alpha.3DS"]
if alpha then
local blended = 0
for _, m in alpha.materials do
if m.alphaMode == "blend" and m.baseColor[4] < 1 then
blended += 1
end
end
t:check(blended > 0, "transparency -> alpha " .. blended)
end
local cam = byName["assimp/models/CameraRollAnim.3ds"]
if cam then
local c = cam.cameras[1]
-- 2400 / 53.33 mm = 45 degrees horizontal at 4:3
t:check(near(2 * math.atan(math.tan(c.yfov / 2) * c.aspect), math.rad(45), 1e-4), "camera lens -> fov " .. math.deg(c.yfov))
local paths = {}
for _, ch in cam.animations[1].channels do
paths[ch.path] = true
end
t:check(paths.rotation, "camera roll -> a rotation channel")
end
local child = byName["assimp/models/CameraRollAnimWithChildObject.3ds"]
if child then
local camNode
for _, n in child.nodes do
if n.camera then
camNode = n
end
end
t:check(camNode and #camNode.children == 1 and child.nodes[camNode.children[1]].name == "Box02", "a box linked to the camera")
end
local spin = byName["assimp/models/RotatingCube.3DS"]
if spin then
local ch = spin.animations[1].channels[1]
t:check(ch.path == "rotation" and ch.input.count > 100, "rotation keys accumulated: " .. ch.input.count)
end
local pyr = byName["assimp/models-nonbsd/pyramob.3DS"]
if pyr then
local types = {}
for _, l in pyr.lights do
types[l.type] = true
end
t:check(types.point and types.spot, "omni and spot lights")
end
-- the api
local s = F.load(Cases[1].data)
t:check(s and s.kind == "scene" and s.meta.source.format == "3ds", "F.load detects 3DS")
local viaApi = F.save(s, nil, { format = "3ds" })
t:check(viaApi and buffer.readu16(viaApi, 0) == 0x4D4D, "F.save format 3ds")
-- normals = false keeps the file's vertices
local raw = decode(Cases[1].data, { normals = false })
t:check(raw and raw.meshes[1].primitives[1].attributes.NORMAL == nil, "normals = false")
-- a hand-made scene: two instances of one mesh, a texture without uri goes to opts.files
local p = S.accessor(nil, "f32", 3, 3)
for v, xyz in { { 0, 0, 0 }, { 1, 0, 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 uv = S.accessor(nil, "f32", 2, 3)
local tri = S.fromPrimitive({ attributes = { POSITION = p, TEXCOORD_0 = uv }, mode = "triangles", material = 1 }, "tri")
tri.materials[1] = S.material("red")
tri.materials[1].baseColor = { 1, 0, 0, 1 }
tri.materials[1].baseColorTexture = { texture = 1 }
tri.textures[1] = { data = buffer.fromstring("\137PNG"), mime = "image/png" }
tri.nodes[2] = { name = "copy", children = {}, mesh = 1, translation = { 5, 0, 0 } }
table.insert(tri.roots, 2)
local files = {}
local out = ThreeDs.encode(tri, { name = "tri.3ds", files = files }) :: buffer
t:check(files["tri_1.png"] ~= nil, "embedded texture bytes -> opts.files")
local back = decode(out)
t:check(back and #back.meshes == 1 and #back.nodes == 2 and back.nodes[2].mesh == 1, "instances share one mesh")
t:eq(back.textures[1].uri, "tri_1.png", "the texture's file name")
local lo, hi = MeshOps.bounds(MeshOps.merge(back))
t:check(lo[1] == 0 and hi[1] == 6, "the instance stands at x = 5")
t:eq(back.nodes[2].name, "copy", "instance name")
end
-- ------------------------------------------------------------------------------------------------ errors
do
local empty = decode("MM\6\0\0\0")
t:check(empty and #empty.meshes == 0 and #empty.nodes == 0, "an empty main chunk: an empty scene")
local data = Cases[1].data
local _, e2 = decode(string.sub(data, 1, #data // 2))
t:check(e2 and e2.code == Err.TRUNCATED, "truncated: " .. tostring(e2))
local _, e3 = decode("not a 3ds file at all")
t:check(e3 and e3.code == Err.CORRUPT, "garbage: " .. tostring(e3))
local _, e4 = decode(data, { maxVertices = 3 })
t:check(e4 and e4.code == Err.LIMIT, "maxVertices: " .. tostring(e4))
local _, e5 = ThreeDs.encode({} :: any)
t:check(e5 and e5.code == Err.ARG, "encode junk")
t:check(ThreeDs.sniff(Bytes.reader(buffer.fromstring(data))) > 0.5, "sniff")
t:eq(ThreeDs.sniff(Bytes.reader(buffer.fromstring("MM junk junk junk"))), 0, "sniff junk")
end
-- ------------------------------------------------------------------------------------------------ fuzz
do
local samples = {}
for i, c in Cases do
if #c.data < 40000 then
table.insert(samples, c.data)
end
end
t:fuzz("decode", function(b: buffer)
local s = ThreeDs.decode(Bytes.reader(b))
if s then
ThreeDs.encode(s)
MeshOps.merge(s)
end
return s
end, samples, { mutations = 12, keepHeader = 6 })
end
t:done()
+109
View File
@@ -0,0 +1,109 @@
-- tests/model/_vrml_common: helpers shared by the VRML and X3D tests (tests/model/vrml.luau, x3d.luau): counts over
-- placed primitives (instances count, as the reference readers count them) and world bounds that include lines and
-- points (MeshOps.merge skips them).
local Types = require("@formats/Types")
local C = {}
export type Stats = { prims: number, unique: number, polys: number, lines: number, points: number, lo: { number }, hi: { number }, area: number }
function C.near(a: number, b: number, eps: number): boolean
return math.abs(a - b) <= eps * math.max(1, math.abs(a), math.abs(b))
end
function C.stats(scene: any): Stats
local s: Stats = { prims = 0, unique = 0, polys = 0, lines = 0, points = 0, lo = { math.huge, math.huge, math.huge }, hi = { -math.huge, -math.huge, -math.huge }, area = 0 }
local seen = {}
for _, pl in Types.Scene.flatten(scene) do
local p = pl.primitive
s.prims += 1
if not seen[p] then
seen[p] = true
s.unique += 1
end
local P = p.attributes.POSITION
local nf = 0
if p.mode == "polygons" then
nf = p.faces.count
elseif p.mode == "lines" then
s.lines += (if p.indices then p.indices.count else P.count) // 2
elseif p.mode == "points" then
s.points += P.count
elseif p.mode == "triangle_strip" or p.mode == "triangle_fan" then
nf = math.max(0, (if p.indices then p.indices.count else P.count) - 2)
elseif p.mode == "line_strip" or p.mode == "line_loop" then
local n = if p.indices then p.indices.count else P.count
s.lines += if p.mode == "line_loop" then n else math.max(0, n - 1)
else
nf = (if p.indices then p.indices.count else P.count) // 3
end
s.polys += nf
local m = pl.matrix
local get = assert(Types.Scene.reader(P))
local w = {}
for v = 0, P.count - 1 do
local x, y, z = get(v, 0), get(v, 1), get(v, 2)
local wx, wy, wz = m[1] * x + m[5] * y + m[9] * z + m[13], m[2] * x + m[6] * y + m[10] * z + m[14], m[3] * x + m[7] * y + m[11] * z + m[15]
w[v] = { wx, wy, wz }
s.lo[1], s.lo[2], s.lo[3] = math.min(s.lo[1], wx), math.min(s.lo[2], wy), math.min(s.lo[3], wz)
s.hi[1], s.hi[2], s.hi[3] = math.max(s.hi[1], wx), math.max(s.hi[2], wy), math.max(s.hi[3], wz)
end
-- world area of the faces (fan-triangulated polygons)
local mode = p.mode
if mode == "triangles" or mode == "polygons" or mode == "triangle_strip" or mode == "triangle_fan" then
local ir = if p.indices then Types.Scene.reader(p.indices) else nil
local ind = function(i: number, _c: number): number
return if ir then ir(i, 0) else i
end
local count = if p.indices then p.indices.count else P.count
local function tri(a: number, b: number, c: number)
local A, B, Cc = w[a], w[b], w[c]
if A and B and Cc then
local e1 = { B[1] - A[1], B[2] - A[2], B[3] - A[3] }
local e2 = { Cc[1] - A[1], Cc[2] - A[2], Cc[3] - A[3] }
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]
s.area += math.sqrt(x * x + y * y + z * z) / 2
end
end
if mode == "triangles" then
for t = 0, count // 3 - 1 do
tri(ind(t * 3, 0), ind(t * 3 + 1, 0), ind(t * 3 + 2, 0))
end
elseif mode == "triangle_strip" then
for t = 0, count - 3 do
tri(ind(t, 0), ind(t + 1, 0), ind(t + 2, 0))
end
elseif mode == "triangle_fan" then
for t = 1, count - 2 do
tri(ind(0, 0), ind(t, 0), ind(t + 1, 0))
end
else
local at = 0
local sizes = assert(Types.Scene.reader(p.faces))
for f = 0, p.faces.count - 1 do
local n = sizes(f, 0)
for k = 1, n - 2 do
tri(ind(at, 0), ind(at + k, 0), ind(at + k + 1, 0))
end
at += n
end
end
end
end
return s
end
function C.boundsNear(lo: { number }, hi: { number }, wlo: { number }, whi: { number }, eps: number): boolean
for k = 1, 3 do
if not C.near(lo[k], wlo[k], eps) or not C.near(hi[k], whi[k], eps) then
return false
end
end
return true
end
function C.fmt(lo: { number }, hi: { number }): string
return string.format("%.5g %.5g %.5g / %.5g %.5g %.5g", lo[1], lo[2], lo[3], hi[1], hi[2], hi[3])
end
return C
+230
View File
@@ -0,0 +1,230 @@
-- model/b3d tests: assimp's Blitz3D models (WusonBlitz, dwarf2, turtle1) and generated files (textures, brushes,
-- vertex colours, two UV sets, nested rotated / scaled / mirrored nodes, pivots, master brushes, bones, keys + ANIM)
-- against assimp (meshes, faces, materials, animations, channels, bones; world bounds, triangle area and signed
-- volume from its PreTransformVertices export: the left- to right-handed conversion and the winding) and the counts
-- the generator wrote; the skin's bind pose; error codes; the fuzz no-throw pass. Fixtures: tools/fixtures/b3d.py.
local T = require("@tests/T")
local B3d = require("@formats/model/b3d")
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/b3d_cases")
local t = T.suite("b3d")
local function decode(data: any, opts: any?): (any, any)
local b = if type(data) == "string" then buffer.fromstring(data) else data
return B3d.decode(Bytes.reader(b), opts)
end
t:eq(B3d.name, "b3d", "name")
t:eq(B3d.category, "model", "category")
t:check(B3d.caps.decode and not B3d.caps.encode, "caps")
t:eq(B3d.sniff(Bytes.reader(buffer.fromstring("BB3D\0\0\0\0\1\0\0\0"))), 1, "sniff")
t:eq(B3d.sniff(Bytes.reader(buffer.fromstring("BX3D\0\0\0\0\1\0\0\0"))), 0, "sniff other")
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
-- world triangles of the merged scene: area and signed volume
local function measure(prim: any): (number, number)
local get = assert(Types.Scene.reader(prim.attributes.POSITION))
local idx = prim.indices and Types.Scene.reader(prim.indices)
local n = if idx then prim.indices.count else prim.attributes.POSITION.count
local area, vol = 0, 0
for k = 0, n // 3 - 1 do
local i0, i1, i2 = 3 * k, 3 * k + 1, 3 * k + 2
if idx then
i0, i1, i2 = idx(i0, 0), idx(i1, 0), idx(i2, 0)
end
local ax, ay, az = get(i0, 0), get(i0, 1), get(i0, 2)
local bx, by, bz = get(i1, 0), get(i1, 1), get(i1, 2)
local cx, cy, cz = get(i2, 0), get(i2, 1), get(i2, 2)
local ux, uy, uz, vx, vy, vz = bx - ax, by - ay, bz - az, cx - ax, cy - ay, cz - az
local x, y, z = uy * vz - uz * vy, uz * vx - ux * vz, ux * vy - uy * vx
area += math.sqrt(x * x + y * y + z * z) / 2
vol += (ax * (by * cz - bz * cy) - ay * (bx * cz - bz * cx) + az * (bx * cy - by * cx)) / 6
end
return area, vol
end
-- assimp's bone count: per primitive, the joints that weight one of its vertices (not the mesh node's own joint)
local function boneCount(scene: any): number
local n = 0
for ni, node in scene.nodes do
if node.mesh and node.skin then
local skin = scene.skins[node.skin]
for _, p in scene.meshes[node.mesh].primitives do
local J, W = Types.Scene.reader(p.attributes.JOINTS_0), Types.Scene.reader(p.attributes.WEIGHTS_0)
local idx = assert(Types.Scene.reader(p.indices))
local seen = {}
for i = 0, p.indices.count - 1 do
local v = idx(i, 0)
for k = 0, 3 do
local j = (J :: any)(v, k)
if (W :: any)(v, k) > 0 and skin.joints[j + 1] ~= ni and not seen[j] then
seen[j] = true
n += 1
end
end
end
end
end
end
return n
end
-- ------------------------------------------------------------------------------------------------ cases
local samples = {}
for _, c in Cases do
local scene, err = decode(c.data, { files = c.files })
local a = c.assimp
t:check(scene, c.name .. ": decode: " .. tostring(err))
if scene and not a.failed then
local prims, faces = 0, 0
for _, pl in Types.Scene.flatten(scene) do
prims += 1
faces += pl.primitive.indices.count // 3
end
t:eq(prims, a.meshes, c.name .. ": meshes (assimp)")
t:eq(faces, a.faces, c.name .. ": faces (assimp)")
t:eq(math.max(1, scene.meta.source.brushes), a.materials, c.name .. ": materials (assimp)")
t:eq(#scene.animations, a.animations, c.name .. ": animations (assimp)")
local animated = {}
local nAnimated = 0
for _, anim in scene.animations do
for _, ch in anim.channels do
if not animated[ch.node] then
animated[ch.node] = true
nAnimated += 1
end
end
end
if a.animations > 0 then
t:eq(nAnimated, a.animation_channels, c.name .. ": animated nodes (assimp)")
end
t:eq(boneCount(scene), a.bones, c.name .. ": bones (assimp)")
local merged = assert(MeshOps.merge(scene))
local lo, hi = MeshOps.bounds(merged)
local ok = lo ~= nil
for k = 1, 3 do
ok = ok and near((lo :: any)[k], a.min[k], 1e-4) and near((hi :: any)[k], a.max[k], 1e-4)
end
t:check(ok, string.format("%s: world bounds (assimp) %s / %s", c.name, table.concat(lo or {}, " "), table.concat(hi or {}, " ")))
local area, vol = measure(merged)
t:check(near(area, a.area, 1e-4), string.format("%s: area %.6g (assimp %.6g)", c.name, area, a.area))
-- (a mirrored node: glTF turns its faces back, assimp's PreTransformVertices does not; skip the volume there)
if not (c.want and c.want.mirrored) then
t:check(near(vol, a.volume, 1e-3), string.format("%s: signed volume %.6g (assimp %.6g)", c.name, vol, a.volume))
end
-- textures resolved through files
for _, tex in scene.textures do
local base = string.match(tex.uri, "([^/\\]+)$")
t:check((tex.data ~= nil) == (c.files[base] ~= nil), c.name .. ": texture data " .. tostring(tex.uri))
end
local w = c.want
if w then
local nv, nt = 0, 0
for _, m in scene.meshes do
nv += m.primitives[1].attributes.POSITION.count
for _, p in m.primitives do
nt += p.indices.count // 3
end
end
t:eq(nv, w.vertices, c.name .. ": vertices")
t:eq(nt, w.triangles, c.name .. ": triangles")
t:eq(#scene.textures, w.textures, c.name .. ": textures")
t:eq(#scene.materials, w.materials, c.name .. ": materials")
t:eq(#scene.nodes, w.nodes, c.name .. ": nodes")
local attrs = scene.meshes[1].primitives[1].attributes
t:eq(attrs.COLOR_0 ~= nil, w.colors, c.name .. ": COLOR_0")
local sets = 0
while attrs["TEXCOORD_" .. sets] do
sets += 1
end
t:eq(sets, w.uvSets, c.name .. ": uv sets")
if w.joints then
t:eq(#scene.skins, 1, c.name .. ": one skin")
t:eq(#scene.skins[1].joints, w.joints, c.name .. ": joints")
t:eq(#scene.animations[1].channels, w.channels, c.name .. ": channels")
t:eq(scene.meta.source.fps, w.fps, c.name .. ": fps")
t:eq(scene.meta.source.frames, w.frames, c.name .. ": frames")
end
end
if c.name == "gen/textured" then
local m1, m2 = scene.materials[1], scene.materials[2]
t:check(m1.name == "red" and m1.baseColorTexture and m1.baseColorTexture.texture == 1, "textured: brush texture")
local tr = m1.baseColorTexture and m1.baseColorTexture.transform
t:check(tr and tr.offset[1] == 0.25 and tr.scale[2] == 3 and tr.rotation == 0.5, "textured: texture transform")
t:check(m1.extras.b3d.textures[2] == 2, "textured: second brush texture in extras")
t:check(m2.name == "glass" and m2.alphaMode == "blend" and m2.doubleSided and m2.extensions.KHR_materials_unlit, "textured: alpha, FX")
t:check(m2.baseColorTexture and m2.baseColorTexture.texCoord == 1, "textured: second UV set flag")
t:check(scene.textures[2].sampler and scene.textures[2].sampler.wrapS == "clamp", "textured: clamp")
end
-- the bind pose: skinning the vertices with the inverse bind matrices gives the static placement
for ni, node in scene.nodes do
if node.skin then
local skin = scene.skins[node.skin]
local worlds = {}
for _, pl in Types.Scene.flatten(scene) do
worlds[pl.node] = pl.matrix
end
local ibm = assert(Types.Scene.reader(skin.inverseBindMatrices))
local function world(i: number): { number }
local parent
for pi, n in scene.nodes do
if table.find(n.children, i) then
parent = pi
end
end
local l = Types.Scene.nodeMatrix(scene.nodes[i])
return if parent then Types.Scene.mul(world(parent), l) else l
end
local maxErr = 0
local meshWorld = world(ni)
for j, jn in skin.joints do
local m = {}
for k = 1, 16 do
m[k] = ibm(j - 1, k - 1)
end
local jm = Types.Scene.mul(world(jn), m)
for k = 1, 16 do
maxErr = math.max(maxErr, math.abs(jm[k] - meshWorld[k]))
end
end
t:check(maxErr < 1e-3, c.name .. ": joint * inverse bind = the mesh's world matrix (" .. maxErr .. ")")
end
end
end
if #c.data < 100000 then
table.insert(samples, c.data)
end
end
-- ------------------------------------------------------------------------------------------------ errors
do
local _, e = decode("BB3D\4\0\0\0\1\0\0\0")
t:check(e and e.code == Err.CORRUPT, "no NODE: CORRUPT")
_, e = decode("BB3D\100\0\0\0\1\0\0\0")
t:check(e and e.code == Err.TRUNCATED, "short BB3D: TRUNCATED")
_, e = decode("RIFF\0\0\0\0")
t:check(e and e.code == Err.CORRUPT, "not B3D: CORRUPT")
local s = Cases[#Cases].data
local _, e2 = decode(string.sub(s, 1, #s - 7))
t:check(e2 and e2.code == Err.TRUNCATED, "truncated file: TRUNCATED (" .. tostring(e2) .. ")")
local _, e3 = decode(s, { maxVertices = 4 })
t:check(e3 and e3.code == Err.LIMIT, "maxVertices: LIMIT")
end
-- ------------------------------------------------------------------------------------------------ fuzz
t:fuzz("decode", function(b: buffer)
local s = B3d.decode(Bytes.reader(b))
if s then
MeshOps.merge(s)
end
return s
end, samples, { mutations = 16, keepHeader = 4 })
t:done()
+2 -2
View File
@@ -313,8 +313,8 @@ do
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": ["KHR_draco_mesh_compression"]}')
t:check(e3 and e3.code == Err.UNSUPPORTED, "Draco: " .. tostring(e3))
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))
+164
View File
@@ -0,0 +1,164 @@
-- model/gltf KHR_draco_mesh_compression tests: the Khronos samples compressed by draco_transcoder (two quantizations),
-- Draco's and assimp's Draco glTF files. Every Draco primitive against libdraco's decode of its buffer view (points,
-- faces, index and attribute CRCs); the transcoded files against their uncompressed sources (meshes, primitives,
-- nodes, materials, skins, animations, triangles, world bounds within the quantization step); the scene saved back
-- (uncompressed, without the extension) and reloaded; the fuzz no-throw pass. Fixtures: tools/fixtures/gltf_draco.py.
local T = require("@tests/T")
local Gltf = require("@formats/model/gltf")
local MeshOps = require("@formats/ops/MeshOps")
local Bytes = require("@formats/core/Bytes")
local Crc32 = require("@formats/core/Crc32")
local Cases = require("@tests/gen/gltf_draco")
local t = T.suite("gltf_draco")
local DT = { [1] = "i8", [2] = "u8", [3] = "i16", [4] = "u16", [5] = "i32", [6] = "u32", [9] = "f32" }
local SAME = { i8 = "i8", snorm8 = "i8", u8 = "u8", unorm8 = "u8", i16 = "i16", snorm16 = "i16", u16 = "u16", unorm16 = "u16", i32 = "i32", u32 = "u32", f32 = "f32" }
local function decode(data: string, files: any): (any, any)
return Gltf.decode(Bytes.reader(buffer.fromstring(data)), { files = files })
end
local function triangles(scene: any): number
local n = 0
for _, m in scene.meshes do
for _, p in m.primitives do
if p.mode == "triangles" then
n += if p.indices then p.indices.count // 3 else p.attributes.POSITION.count // 3
end
end
end
return n
end
local checked = { prims = 0, attrs = 0, converted = 0, originals = 0, roundTrips = 0 }
local samples = {}
for _, c in Cases do
local scene, err = decode(c.data, c.files)
t:check(scene, c.name .. ": decode: " .. tostring(err))
if scene then
for _, ref in c.prims do
local label = string.format("%s: mesh %d primitive %d", c.name, ref.mesh, ref.prim)
local prim = scene.meshes[ref.mesh] and scene.meshes[ref.mesh].primitives[ref.prim]
t:check(prim, label .. ": present")
if prim then
t:eq(prim.attributes.POSITION.count, ref.points, label .. ": points")
if ref.faces then
t:eq(prim.indices.count, ref.faces * 3, label .. ": indices")
t:eq(Crc32.of(prim.indices.data), ref.indices, label .. ": index CRC")
end
for name, a in ref.attrs do
local acc = prim.attributes[name]
t:check(acc, label .. ": " .. name)
if acc then
if SAME[acc.type] == DT[a.dataType] then
t:eq(Crc32.of(acc.data), a.crc, label .. ": " .. name .. " values")
checked.attrs += 1
else
checked.converted += 1
end
end
end
checked.prims += 1
end
end
-- against the uncompressed source
local o = c.original
if o then
local orig, oerr = decode(o.data, o.files)
t:check(orig, c.name .. ": original: " .. tostring(oerr))
if orig then
t:eq(#scene.meshes, #orig.meshes, c.name .. ": meshes")
for i, m in orig.meshes do
t:eq(#scene.meshes[i].primitives, #m.primitives, c.name .. ": mesh " .. i .. " primitives")
end
t:eq(#scene.nodes, #orig.nodes, c.name .. ": nodes")
-- draco_transcoder adds a default material to files without one
t:check(#scene.materials == #orig.materials or (#orig.materials == 0 and #scene.materials == 1), c.name .. ": materials")
t:eq(#scene.skins, #orig.skins, c.name .. ": skins")
t:eq(#scene.animations, #orig.animations, c.name .. ": animations")
t:eq(triangles(scene), triangles(orig), c.name .. ": triangles")
local lo, hi = MeshOps.bounds(MeshOps.merge(scene))
local olo, ohi = MeshOps.bounds(MeshOps.merge(orig))
if lo and olo then
-- the quantization step relative to the scene: 11-bit positions by default, 16-bit for "fine"
local rel = if string.find(c.name, "fine", 1, true) then 1e-4 else 5e-3
local ok = true
for k = 1, 3 do
local eps = math.max(ohi[k] - olo[k], 1e-6) * rel
if math.abs(lo[k] - olo[k]) > eps or math.abs(hi[k] - ohi[k]) > eps then
ok = false
end
end
t:check(ok, c.name .. ": world bounds within the quantization step")
end
checked.originals += 1
end
end
-- saved back without the extension
local glb = Gltf.encode(scene, { binary = true })
t:check(glb, c.name .. ": encode")
if glb then
t:check(not string.find(buffer.tostring(glb), "KHR_draco_mesh_compression", 1, true), c.name .. ": no Draco extension written")
local again = Gltf.decode(Bytes.reader(glb))
t:check(again and triangles(again) == triangles(scene), c.name .. ": round trip")
checked.roundTrips += 1
end
if #c.data < 6000 and next(c.files) == nil then
table.insert(samples, c.data)
end
end
end
t:note("%d Draco primitives like libdraco (%d attributes byte for byte, %d converted to their accessor type), %d against the uncompressed sources, %d round trips", checked.prims, checked.attrs, checked.converted, checked.originals, checked.roundTrips)
-- an accessor type other than the Draco attribute's: u8 normalized colours declared as f32
do
local Draco = require("@formats/codecs/model/Draco")
local Base64 = require("@formats/core/Base64")
local DracoCases = require("@tests/gen/draco_cases")
local drc
for _, dc in DracoCases do
if dc.name == "enc/test_generic.ply.cl7" then
drc = dc.data
end
end
local g = drc and Draco.decode(drc)
t:check(g, "colour .drc fixture")
if g then
local pos, col
for _, a in g.attributes do
if a.name == "POSITION" then
pos = a
elseif a.name == "COLOR" then
col = a
end
end
local n = g.numPoints
local doc = string.format(
'{"asset":{"version":"2.0"},"extensionsUsed":["KHR_draco_mesh_compression"],"extensionsRequired":["KHR_draco_mesh_compression"],'
.. '"buffers":[{"byteLength":%d,"uri":"data:application/octet-stream;base64,%s"}],"bufferViews":[{"buffer":0,"byteLength":%d}],'
.. '"accessors":[{"componentType":5126,"count":%d,"type":"VEC3"},{"componentType":5126,"count":%d,"type":"VEC%d"},{"componentType":5125,"count":%d,"type":"SCALAR"}],'
.. '"meshes":[{"primitives":[{"attributes":{"POSITION":0,"COLOR_0":1},"indices":2,"extensions":{"KHR_draco_mesh_compression":{"bufferView":0,"attributes":{"POSITION":%d,"COLOR_0":%d}}}}]}],'
.. '"nodes":[{"mesh":0}],"scenes":[{"nodes":[0]}]}',
#drc, Base64.encode(buffer.fromstring(drc)), #drc, n, n, col.components, g.numFaces * 3, pos.uniqueId, col.uniqueId)
local scene, err = decode(doc, {})
t:check(scene, "converted accessor: " .. tostring(err))
if scene then
local acc = scene.meshes[1].primitives[1].attributes.COLOR_0
t:eq(acc.type, "f32", "colour accessor type")
local ok = true
for i = 0, n * col.components - 1 do
local want = buffer.readu8(col.data, i) / 255
if math.abs(buffer.readf32(acc.data, i * 4) - want) > 1e-6 then
ok = false
end
end
t:check(ok, "u8 normalized colours -> f32 / 255")
end
end
end
t:fuzz("decode", function(b: buffer)
return Gltf.decode(Bytes.reader(b))
end, samples, { mutations = 6, garbage = 50 })
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()
+226
View File
@@ -0,0 +1,226 @@
-- model/ldraw tests: hand-written LDraw files (a brick of primitives found through library paths, an MPD with
-- embedded parts and sub-models, BFC CW / CCW / INVERTNEXT / NOCLIP / uncertified files, mirrored references, colours
-- 16 / 24 / direct / local !COLOUR, optional lines, a missing part, a self-reference, bad lines, CRLF) and real library
-- parts and models (3001, 3062b, 4073, 3626c, car.ldr, pyramid.ldr) against an independent expansion in the generator
-- (world triangles per colour, double-sided faces, lines, area, signed volume of the one-sided faces, bounds, missing
-- files) and LeoCAD's OBJ export (bounds, area); node / flattened / un-flipped scenes agree; mesh sharing; the
-- built-in colour table against LDConfig.ldr; resolve; error codes; the fuzz no-throw pass. Fixtures:
-- tools/fixtures/ldraw.py.
local T = require("@tests/T")
local Ldraw = require("@formats/model/ldraw")
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/ldraw_cases")
local Config = require("@tests/gen/ldraw_config")
local t = T.suite("ldraw")
local function decode(data: any, opts: any?): (any, any)
local b = if type(data) == "string" then buffer.fromstring(data) else data
return Ldraw.decode(Bytes.reader(b), opts)
end
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
t:eq(Ldraw.name, "ldraw", "name")
t:eq(Ldraw.category, "model", "category")
t:check(Ldraw.caps.decode and not Ldraw.caps.encode, "caps")
t:check(Ldraw.sniff(Bytes.reader(buffer.fromstring("0 FILE main.ldr\n1 16 0 0 0 1 0 0 0 1 0 0 0 1 a.dat\n"))) >= 0.9, "sniff MPD")
t:check(Ldraw.sniff(Bytes.reader(buffer.fromstring("0 x\n1 16 0 0 0 1 0 0 0 1 0 0 0 1 3001.dat\n"))) >= 0.8, "sniff LDR")
t:eq(Ldraw.sniff(Bytes.reader(buffer.fromstring("solid cube\n facet normal 0 0 1\n"))), 0, "sniff other")
-- ------------------------------------------------------------------------------------------------ colour table
do
local tbl = Ldraw.colors()
local bad = 0
for _, c in Config.colours do
local e = tbl[c[1]]
if not e or e.rgb ~= c[2] or e.edge ~= c[3] or e.alpha ~= c[4] then
bad += 1
end
end
t:eq(bad, 0, "built-in colours = LDConfig.ldr (" .. #Config.colours .. " colours)")
local over = Ldraw.colors("0 !COLOUR Mine CODE 4 VALUE #010203 EDGE 0\n")
t:check(over[4].rgb == 0x010203 and over[4].edge == 0 and over[4].name == "Mine", "ldconfig overrides")
end
-- ------------------------------------------------------------------------------------------------ measuring
type Stats = { triangles: number, lines: number, optional: number, ds: number, area: number, volume: number, colours: { [number]: number } }
local function det3(m: { number }): number
return m[1] * (m[6] * m[11] - m[10] * m[7]) - m[5] * (m[2] * m[11] - m[10] * m[3]) + m[9] * (m[2] * m[7] - m[6] * m[3])
end
local function measure(scene: any): Stats
local s: Stats = { triangles = 0, lines = 0, optional = 0, ds = 0, area = 0, volume = 0, colours = {} }
for _, pl in Types.Scene.flatten(scene) do
local p = pl.primitive
local n = p.attributes.POSITION.count
if p.mode == "lines" then
if p.extras and p.extras.ldraw and p.extras.ldraw.optional then
s.optional += n // 2
else
s.lines += n // 2
end
else
local mat = scene.materials[p.material]
local code = mat.extras.ldraw.code
s.colours[code] = (s.colours[code] or 0) + n // 3
s.triangles += n // 3
if mat.doubleSided then
s.ds += n // 3
end
local m = pl.matrix
local flip = det3(m) < 0
local get = assert(Types.Scene.reader(p.attributes.POSITION))
for tri = 0, n // 3 - 1 do
local q = {}
for k = 0, 2 do
local x, y, z = get(tri * 3 + k, 0), get(tri * 3 + k, 1), get(tri * 3 + k, 2)
q[k + 1] = { m[1] * x + m[5] * y + m[9] * z + m[13], m[2] * x + m[6] * y + m[10] * z + m[14], m[3] * x + m[7] * y + m[11] * z + m[15] }
end
local a, b, c = q[1], q[2], q[3]
if flip then
a, c = c, a
end
local ux, uy, uz, vx, vy, vz = b[1] - a[1], b[2] - a[2], b[3] - a[3], c[1] - a[1], c[2] - a[2], c[3] - a[3]
local x, y, z = uy * vz - uz * vy, uz * vx - ux * vz, ux * vy - uy * vx
s.area += math.sqrt(x * x + y * y + z * z) / 2
if not mat.doubleSided then
s.volume += (a[1] * (b[2] * c[3] - b[3] * c[2]) - a[2] * (b[1] * c[3] - b[3] * c[1]) + a[3] * (b[1] * c[2] - b[2] * c[1])) / 6
end
end
end
end
return s
end
local function compare(label: string, s: Stats, w: any)
t:eq(s.triangles, w.triangles, label .. ": triangles")
t:eq(s.ds, w.doubleSided, label .. ": double-sided triangles")
t:eq(s.lines, w.lines, label .. ": lines")
local bad = {}
for _, pair in w.colours do
if s.colours[pair[1]] ~= pair[2] then
table.insert(bad, string.format("%d: %s / %d", pair[1], tostring(s.colours[pair[1]]), pair[2]))
end
end
t:check(#bad == 0 and #w.colours == #(function()
local keys = {}
for k in s.colours do
table.insert(keys, k)
end
return keys
end)(), label .. ": triangles per colour " .. table.concat(bad, ", "))
t:check(near(s.area, w.area, 1e-5), string.format("%s: area %.6f / %.6f", label, s.area, w.area))
t:check(near(s.volume, w.volume, 1e-5), string.format("%s: signed volume %.6f / %.6f", label, s.volume, w.volume))
end
-- ------------------------------------------------------------------------------------------------ cases
local samples = {}
local lib: any = nil
for _, c in Cases do
local opts = table.clone(c.opts or {})
opts.files = c.files
local scene, err = decode(c.data, opts)
t:check(scene, c.name .. ": decode: " .. tostring(err))
local w = c.want
compare(c.name, measure(scene), w)
local lo, hi = MeshOps.bounds(assert(MeshOps.merge(scene)))
local ok = lo ~= nil and w.min ~= nil
for k = 1, 3 do
ok = ok and near((lo :: any)[k], w.min[k], 1e-5) and near((hi :: any)[k], w.max[k], 1e-5)
end
t:check(ok, string.format("%s: bounds %s / %s", c.name, table.concat(lo or {}, " "), table.concat(hi or {}, " ")))
t:eq(table.concat(scene.meta.source.missing, ","), table.concat(w.missing, ","), c.name .. ": missing files")
t:check(scene.meta.up == "y" and scene.meta.unit == 0.0004, c.name .. ": meta.up / unit")
-- LeoCAD: its axes are (x, -z, y) of ours, 2 decimals
local lc = c.leocad
if lc then
local lmin = { lo[1], -hi[3], lo[2] }
local lmax = { hi[1], -lo[3], hi[2] }
local good = true
for k = 1, 3 do
good = good and math.abs(lmin[k] - lc.min[k]) < 0.02 and math.abs(lmax[k] - lc.max[k]) < 0.02
end
t:check(good, c.name .. ": bounds (LeoCAD)")
local s = measure(scene)
t:check(near(s.area, lc.area, 2e-4), string.format("%s: area %.3f (LeoCAD %.3f)", c.name, s.area, lc.area))
end
-- the same model flattened into one mesh, and without the root flip
local flat = assert(decode(c.data, { files = c.files, flatten = true }))
t:eq(#flat.meshes <= 1, true, c.name .. ": flatten: one mesh")
compare(c.name .. " (flatten)", measure(flat), w)
local raw = assert(decode(c.data, { files = c.files, upright = false }))
local rlo, rhi = MeshOps.bounds(assert(MeshOps.merge(raw)))
t:check(rlo and near(rlo[2], -hi[2], 1e-6) and near(rhi[3], -lo[3], 1e-6) and raw.meta.source.up == "-y", c.name .. ": upright = false")
if #c.data < 4000 then
table.insert(samples, c.data)
end
if c.name == "two.ldr" then
lib = c.files
-- one mesh per (part, colour): four colours, the missing part has no node
t:eq(#scene.meshes, 4, "two.ldr: meshes per colour")
local root = scene.nodes[scene.roots[1]]
t:eq(#root.children, 4, "two.ldr: one node per placed part")
local steps = {}
for _, ci in root.children do
table.insert(steps, scene.nodes[ci].extras.ldraw.step)
end
t:eq(table.concat(steps, ","), "1,1,1,2", "two.ldr: steps")
-- through resolve instead of files
local viaResolve = assert(decode(c.data, { resolve = function(uri: string): any
return c.files[uri]
end }))
t:eq(measure(viaResolve).triangles, w.triangles, "two.ldr: resolve")
-- optional lines on request
local withOpt = assert(decode(c.data, { files = c.files, optionalLines = true, lines = false }))
local so = measure(withOpt)
t:check(so.optional == w.optional and so.lines == 0, "two.ldr: optional lines only")
elseif c.name == "model.mpd" then
t:check(scene.meta.source.mpd, "model.mpd: mpd")
local meshNodes = 0
for _, n in scene.nodes do
if n.mesh then
meshNodes += 1
end
end
t:check(#scene.meshes < meshNodes, string.format("model.mpd: meshes shared (%d meshes, %d mesh nodes)", #scene.meshes, meshNodes))
local purple
for _, m in scene.materials do
if m.extras.ldraw.code == 1000 then
purple = m
end
end
t:check(purple and purple.name == "Test_Purple" and purple.alphaMode == "blend", "model.mpd: local !COLOUR")
elseif c.name == "badrefs.ldr" then
t:check(scene.meta.source.cycles > 0 and scene.meta.source.badLines == 2, "badrefs.ldr: cycle and bad lines counted")
end
end
-- ------------------------------------------------------------------------------------------------ errors
do
local _, e = decode("")
t:check(e and e.code == Err.CORRUPT, "empty: CORRUPT")
_, e = decode("hello world\nthis is not ldraw\n")
t:check(e and e.code == Err.CORRUPT, "text: CORRUPT")
_, e = decode(Cases[1].data, { files = Cases[1].files, maxTriangles = 10 })
t:check(e and e.code == Err.LIMIT, "maxTriangles: LIMIT")
_, e = decode(Cases[1].data, { files = Cases[1].files, maxDepth = 0 })
t:check(e and e.code == Err.LIMIT, "maxDepth: LIMIT")
end
-- ------------------------------------------------------------------------------------------------ fuzz
t:fuzz("decode", function(b: buffer)
local s = Ldraw.decode(Bytes.reader(b), { files = lib, optionalLines = true })
if s then
MeshOps.merge(s)
end
return s
end, samples, { mutations = 24 })
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()
+430
View File
@@ -0,0 +1,430 @@
-- model/ms3d tests: assimp's MilkShape 3D test models (groups, materials, textures, version 4 with and without the
-- sub-versioned blocks) against assimp (meshes, faces, corners, materials, world bounds); round trips through our
-- writer, of those files and of glTF sample models (world triangles, materials, textures, skins: joints, inverse bind
-- matrices, skinned vertices; animation sampled through the skeleton); assimp reading our files (meshes, faces,
-- bones, animations, bounds: ms3d_xcheck); comments and extras; errors; the fuzz no-throw pass. Fixtures:
-- tools/fixtures/ms3d.py.
local T = require("@tests/T")
local F = require("@formats")
local Ms3d = require("@formats/model/ms3d")
local Gltf = require("@formats/model/gltf")
local MeshOps = require("@formats/ops/MeshOps")
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/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
-- ------------------------------------------------------------------------------------------------ reference files
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)
-- ------------------------------------------------------------------------------------------------ round trips
-- skinned world positions at a time: the skeleton posed by animations[1], vertices blended by their joints
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
-- the same posed triangles (the corners in order) at a few times
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)
-- ------------------------------------------------------------------------------------------------ cross-check
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)
-- ------------------------------------------------------------------------------------------------ details
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
-- a skinned scene by hand: two joints, comments, weights split between them
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
-- ------------------------------------------------------------------------------------------------ errors
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
-- ------------------------------------------------------------------------------------------------ fuzz
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()
+263
View File
@@ -0,0 +1,263 @@
-- model/pmx tests: assimp's MMD model (Alicia_blade.pmx) and synthetic PMX 2.0 / 2.1 models (UTF-16 / UTF-8, index
-- sizes 1 / 2 / 4, additional UVs, BDEF1 / BDEF2 / BDEF4 / SDEF / QDEF, every morph type, IK / inherit / axis bones,
-- display frames, rigid bodies, joints) against assimp (meshes, faces per mesh, materials, bones, world bounds) and the
-- generator's facts (vertices, weights, bones, morphs, textures); the same models as PMD against their PMX decode;
-- errors; the fuzz no-throw pass. Fixtures: tools/fixtures/pmx.py.
local T = require("@tests/T")
local F = require("@formats")
local Pmx = require("@formats/model/pmx")
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/pmx_cases")
local Pmds = require("@tests/gen/pmx_pmd")
local t = T.suite("pmx")
local function decode(data: any, opts: any?): (any, any)
local b = if type(data) == "string" then buffer.fromstring(data) else data
return Pmx.decode(Bytes.reader(b), opts)
end
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
t:eq(Pmx.name, "pmx", "name")
t:eq(Pmx.category, "model", "category")
t:check(Pmx.caps.decode and not Pmx.caps.encode, "contract")
local function faces(scene: any): (number, { number })
local n, per = 0, {}
for i, p in scene.meshes[1].primitives do
per[i] = p.indices.count // 3
n += per[i]
end
return n, per
end
local function bounds(scene: any): ({ number }, { number })
return MeshOps.bounds(MeshOps.merge(scene))
end
-- a file vertex in the decoded primitives: position (z negated) and uv
local function findVertex(scene: any, pos: { number }, uv: { number }): (any, number?)
for _, p in scene.meshes[1].primitives do
local P, U = p.attributes.POSITION, p.attributes.TEXCOORD_0
for v = 0, P.count - 1 do
local x, y, z = buffer.readf32(P.data, v * 12), buffer.readf32(P.data, v * 12 + 4), buffer.readf32(P.data, v * 12 + 8)
if near(x, pos[1], 1e-6) and near(y, pos[2], 1e-6) and near(z, -pos[3], 1e-6) and near(buffer.readf32(U.data, v * 8), uv[1], 1e-6) and near(buffer.readf32(U.data, v * 8 + 4), uv[2], 1e-6) then
return p, v
end
end
end
return nil, nil
end
-- ------------------------------------------------------------------------------------------------ reference files
local scenes = {}
local checked = { assimp = 0, expect = 0 }
for i, c in Cases do
local scene, err = decode(c.data, { files = c.files })
t:check(scene, c.name .. ": decode: " .. tostring(err))
if not scene then
continue
end
scenes[i] = scene
local a = c.assimp
local nf, per = faces(scene)
if not a.skip then
t:eq(#scene.meshes[1].primitives, a.meshes, c.name .. ": meshes (assimp)")
t:eq(nf, a.faces, c.name .. ": faces (assimp)")
t:eq(#scene.materials, a.materials, c.name .. ": materials (assimp)")
local ok = true
for k, pm in a.perMesh do
ok = ok and per[k] == pm.faces
end
t:check(ok, c.name .. ": faces per material (assimp)")
t:eq(#scene.skins[1].joints * #scene.meshes[1].primitives, a.bones, c.name .. ": bones x meshes (assimp)")
if a.min then
local lo, hi = bounds(scene)
local okb = true
for k = 1, 3 do
okb = okb and near(lo[k], a.min[k], 1e-5) and near(hi[k], a.max[k], 1e-5)
end
t:check(okb, string.format("%s: world bounds (assimp) %s / %s", c.name, table.concat(lo, " "), table.concat(hi, " ")))
end
checked.assimp += 1
end
local x = c.expect
if x then
local src = scene.meta.source
t:eq(src.version, x.version, c.name .. ": version")
t:eq(src.name, x.name, c.name .. ": model name")
t:eq(#scene.skins[1].joints, x.bones, c.name .. ": bones")
t:eq(#scene.nodes, 2 + x.bones, c.name .. ": nodes")
t:eq(#scene.textures, x.textures, c.name .. ": textures")
t:eq(#src.rigidBodies, x.rigid, c.name .. ": rigid bodies")
t:eq(#src.joints, x.joints, c.name .. ": joints")
t:eq(#src.displayFrames, x.frames, c.name .. ": display frames")
local mesh = scene.meshes[1]
local vertexMorphs = x.morphTypes["1"] or 0
t:eq(#(mesh.extras.targetNames or {}), vertexMorphs, c.name .. ": vertex morphs -> targets")
t:eq(#mesh.primitives[1].targets, vertexMorphs, c.name .. ": targets per primitive")
t:eq(#((mesh.extras.pmx or {}).morphs or {}), x.morphs - vertexMorphs, c.name .. ": other morphs in extras")
t:check(x.uva == 0 or mesh.primitives[1].attributes["_UVA" .. x.uva] ~= nil, c.name .. ": additional UVs")
-- unique vertices: a material boundary can split a ring, so at least the file's count
local nv = 0
for _, p in mesh.primitives do
nv += p.attributes.POSITION.count
end
t:check(nv >= x.vertices and nv <= x.vertices * 2, c.name .. ": vertices " .. nv .. " / " .. x.vertices)
for _, s in x.samples do
local p, v = findVertex(scene, s.pos, s.uv)
t:check(p ~= nil, c.name .. ": vertex " .. s.index .. " found")
if p and v then
local J, W = p.attributes.JOINTS_0, p.attributes.WEIGHTS_0
local want: { [number]: number } = {}
local sum = 0
local ws = if s.deform == 1 or s.deform == 3 then { s.weights[1], 1 - s.weights[1] } elseif s.deform == 0 then { 1 } else s.weights
for k, b in s.bones do
if b >= 0 and ws[k] and ws[k] > 0 then
want[b] = (want[b] or 0) + ws[k]
sum += ws[k]
end
end
local got: { [number]: number } = {}
for k = 0, 3 do
local w = buffer.readf32(W.data, (v * 4 + k) * 4)
if w > 0 then
local j = buffer.readu16(J.data, (v * 4 + k) * 2)
got[j] = (got[j] or 0) + w
end
end
local ok = true
for b, w in want do
ok = ok and got[b] ~= nil and near(got[b], w / sum, 1e-5)
end
t:check(ok, c.name .. ": vertex " .. s.index .. " weights (deform " .. s.deform .. ")")
if s.deform == 3 then
t:check(p.attributes._SDEF_C ~= nil and buffer.readu8(p.attributes._DEFORM.data, v) == 3, c.name .. ": SDEF attributes")
end
end
end
-- the texture named tex\body.png came from files["tex/body.png"]
t:check(scene.textures[1].uri == "tex/body.png" and scene.textures[1].data ~= nil and scene.textures[1].mime == "image/png", c.name .. ": texture data")
local m1 = scene.materials[1]
t:check(m1.baseColorTexture and m1.baseColorTexture.texture == 1 and m1.doubleSided, c.name .. ": material 1 texture, no-cull")
t:check(m1.extras.pmx.sphereTexture == 2 and m1.extras.pmx.sphereMode == "multiply" and m1.extras.pmx.toonShared == 3, c.name .. ": sphere / toon")
t:check(scene.materials[2].alphaMode == "blend", c.name .. ": translucent material")
local ik = nil
for _, n in scene.nodes do
if n.extras and n.extras.pmx and n.extras.pmx.ik then
ik = n.extras.pmx.ik
end
end
t:check(ik and ik.loops == 40 and #ik.links == 2, c.name .. ": IK bone")
checked.expect += 1
end
end
t:note("%d files: %d against assimp, %d against the generator", #Cases, checked.assimp, checked.expect)
-- skins: every joint's inverse bind matrix undoes its world translation
do
local s = scenes[2]
if s then
local skin = s.skins[1]
local ok = true
local world = {}
-- world matrices by walking from the root
local function walk(n: number, parent: { number })
local w = Types.Scene.mul(parent, Types.Scene.nodeMatrix(s.nodes[n]))
world[n] = w
for _, c in s.nodes[n].children do
walk(c, w)
end
end
walk(1, Types.Scene.IDENTITY)
for k, j in skin.joints do
local w = world[j]
for c = 0, 2 do
ok = ok and near(buffer.readf32(skin.inverseBindMatrices.data, ((k - 1) * 16 + 12 + c) * 4), -w[13 + c], 1e-5)
end
end
t:check(ok, "inverse bind matrices = -world bone positions")
end
end
-- ------------------------------------------------------------------------------------------------ PMD
for _, c in Pmds do
local s, err = decode(c.data)
t:check(s, c.name .. ": decode: " .. tostring(err))
local ref = scenes[c.pmx]
if s and ref then
t:check(s.meta.source.pmd == true and s.meta.source.format == "pmx", c.name .. ": meta.source")
local a, pa = faces(s)
local b, pb = faces(ref)
t:eq(a, b, c.name .. ": faces (= PMX)")
t:eq(#pa, #pb, c.name .. ": primitives (= PMX)")
t:eq(#s.skins[1].joints, #ref.skins[1].joints, c.name .. ": bones (= PMX)")
t:eq(#s.meshes[1].extras.targetNames, #ref.meshes[1].extras.targetNames, c.name .. ": vertex morphs (= PMX)")
local lo, hi = bounds(s)
local lo2, hi2 = bounds(ref)
local ok = true
for k = 1, 3 do
ok = ok and near(lo[k], lo2[k], 1e-6) and near(hi[k], hi2[k], 1e-6)
end
t:check(ok, c.name .. ": bounds (= PMX)")
-- the same morph deltas
local d1 = s.meshes[1].primitives[1].targets[1].POSITION
local d2 = ref.meshes[1].primitives[1].targets[1].POSITION
t:check(d1.count == d2.count and buffer.tostring(d1.data) == buffer.tostring(d2.data), c.name .. ": morph deltas (= PMX)")
t:eq(s.meshes[1].extras.targetNames[1], "up", c.name .. ": English morph names")
t:eq(s.materials[1].extras.pmx.sphereMode, "multiply", c.name .. ": texture*sphere name")
end
end
-- ------------------------------------------------------------------------------------------------ api, errors
do
local c = Cases[2]
t:eq(F.detect(c.data), "pmx", "F.detect pmx")
t:eq(F.detect(Pmds[1].data), "pmx", "F.detect pmd")
local s = F.load(c.data, { files = c.files })
t:check(s and s.kind == "scene" and s.meta.up == "y", "F.load")
local _, e1 = decode(string.sub(c.data, 1, 300))
t:check(e1 and e1.code == Err.TRUNCATED, "truncated: " .. tostring(e1))
local _, e2 = decode("PMX " .. "\0\0\64\64" .. string.sub(c.data, 9))
t:check(e2 and e2.code == Err.UNSUPPORTED, "version 2.0 -> 3.0: " .. tostring(e2))
local _, e3 = decode(string.sub(c.data, 1, 11) .. "\3" .. string.sub(c.data, 13))
t:check(e3 and e3.code == Err.CORRUPT, "index size 3: " .. tostring(e3))
local _, e4 = decode(c.data, { maxVertices = 10 })
t:check(e4 and e4.code == Err.LIMIT, "maxVertices: " .. tostring(e4))
local _, e5 = decode(c.data, { maxBytes = 100 })
t:check(e5 and e5.code == Err.LIMIT, "maxBytes (morph targets): " .. tostring(e5))
local s2 = decode(c.data, { maxBytes = 100, morphs = false })
t:check(s2 and s2.meshes[1].primitives[1].targets == nil, "morphs = false")
local _, e6 = decode("Pmd\0\0\0\64" .. string.rep("\0", 300))
t:check(e6 and e6.code == Err.UNSUPPORTED, "PMD version 2: " .. tostring(e6))
local _, e7 = decode(string.sub(Pmds[1].data, 1, 400))
t:check(e7 and (e7.code == Err.TRUNCATED or e7.code == Err.CORRUPT), "PMD truncated: " .. tostring(e7))
end
-- ------------------------------------------------------------------------------------------------ fuzz
do
local samples = {}
for _, c in Cases do
if #c.data < 120000 then
table.insert(samples, c.data)
end
end
for _, c in Pmds do
table.insert(samples, c.data)
end
t:fuzz("decode", function(b: buffer)
local s = Pmx.decode(Bytes.reader(b))
if s then
MeshOps.merge(s)
end
return s
end, samples, { mutations = 16, keepHeader = 16 })
end
t:done()
+410
View File
@@ -0,0 +1,410 @@
-- 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("@formats")
local Vrml = require("@formats/model/vrml")
local Gltf = require("@formats/model/gltf")
local Bytes = require("@formats/core/Bytes")
local Err = require("@formats/core/Err")
local Types = require("@formats/Types")
local Mat4 = require("@formats/codecs/model/Mat4")
local Deflate = require("@formats/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()
+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()
+308
View File
@@ -0,0 +1,308 @@
-- model/x3d tests: assimp's X3D / X3DV / X3DB test models, scenes and glTF samples written by VTK's X3D exporter and
-- by assimp's X3D exporter, and hand-written feature files (the X3D triangle / quad / line sets, ColorRGBA,
-- ProtoDeclare / ProtoInstance with SFNode defaults, PhysicalMaterial, UnlitMaterial, OrthoViewpoint, ROUTE
-- animation, UNIT, the classic encoding's header statements), against assimp's X3D reader (meshes, faces, materials,
-- world bounds) and exact expectations; .x3dv against the same model as .x3d; the writer (XML and classic): round
-- trips, and assimp reading our X3D like the originals; errors; the fuzz no-throw pass. Fixtures: tools/fixtures/x3d.py.
local T = require("@tests/T")
local F = require("@formats")
local X3d = require("@formats/model/x3d")
local Bytes = require("@formats/core/Bytes")
local Err = require("@formats/core/Err")
local Types = require("@formats/Types")
local C = require("@tests/model/_vrml_common")
local Cases = require("@tests/gen/x3d_cases")
local VrmlCases = require("@tests/gen/vrml_cases")
local GltfCases = require("@tests/gen/vrml_gltf")
local Xcheck = require("@tests/gen/x3d_xcheck")
local Gltf = require("@formats/model/gltf")
local Vrml = require("@formats/model/vrml")
local t = T.suite("x3d")
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 X3d.decode(Bytes.reader(b), opts)
end
t:eq(X3d.name, "x3d", "name")
t:eq(X3d.category, "model", "category")
t:check(X3d.caps.decode and X3d.caps.encode, "contract")
-- assimp's own quirks (its reading is not the specification's): USE'd groups lose their parents' transforms; its X3D
-- exporter writes points and lines as 1- / 2-vertex faces (not valid IndexedFaceSet faces, dropped here)
local QUIRK = { ["assimp/X3D/ComputerKeyboard.x3d"] = "all", ["assimp-export/assimp_MeshPrimitiveModes.x3d"] = "all" }
-- ------------------------------------------------------------------------------------------------ reference files
local scenes, byName = {}, {}
local checked = { assimp = 0, none = 0 }
for i, c in Cases do
local scene, err = decode(c.data, { files = c.files, triangulate = false })
if string.find(c.name, "%.x3db$") then
t:check(scene == nil and err and err.code == Err.UNSUPPORTED, c.name .. ": binary X3D is UNSUPPORTED: " .. tostring(err))
continue
end
t:check(scene, c.name .. ": decode: " .. tostring(err))
if not scene then
continue
end
scenes[i], byName[c.name] = scene, scene
local a = c.assimp
-- (VTK's exporter leaves </X3D> out: assimp then reads nothing)
local unclosed = a.meshes == 0 and not string.find(c.data, "</X3D>", 1, true)
if a.skip or a.failed or unclosed or string.find(c.name, "^feature/") then
checked.none += 1
continue
end
local s = C.stats(scene)
local quirk = QUIRK[c.name]
if quirk ~= "all" then
if quirk ~= "counts" then
t:eq(s.prims, a.meshes, c.name .. ": meshes (assimp: one per placed shape)")
end
if not c.primitives and quirk ~= "counts" then
t:eq(s.polys + s.lines + s.points, a.faces, c.name .. ": faces (assimp)")
end
t:check(#scene.materials <= a.materials, c.name .. ": materials (assimp counts one per use)")
if a.min then
t:check(C.boundsNear(s.lo, s.hi, a.min, a.max, if c.primitives then 5e-3 else 1e-5), c.name .. ": world bounds (assimp) " .. C.fmt(s.lo, s.hi) .. " vs " .. C.fmt(a.min, a.max))
end
end
checked.assimp += 1
end
t:note("%d files: %d against assimp, %d without a reference", #Cases, checked.assimp, checked.none)
-- ------------------------------------------------------------------------------------------------ exact expectations
do
local kb = byName["assimp/X3D/ComputerKeyboard.x3d"]
if kb then
local s = C.stats(kb)
t:eq(#kb.meshes, 3, "keyboard: three extrusions (the keys are USE'd)")
t:check(s.prims > 50, "keyboard: every USE placed: " .. s.prims)
t:eq(#kb.animations, 1, "keyboard: the push animation")
t:check(#kb.animations[1].channels == s.prims - 2, "keyboard: one channel per escape-button instance")
t:check(near(s.hi[3], 0.980018, 1e-5) and near(s.lo[2], -0.0002, 1e-3), "keyboard: the base under its rotation")
end
local hw, hv = byName["assimp/X3D/HelloWorld.x3d"], byName["assimp/X3DV/HelloWorld.x3dv"]
if hw and hv then
local a, b = C.stats(hw), C.stats(hv)
t:check(a.polys == b.polys and C.boundsNear(a.lo, a.hi, b.lo, b.hi, 1e-9), ".x3dv = .x3d: geometry")
t:eq(hv.materials[1].baseColor[2], hw.materials[1].baseColor[2], ".x3dv = .x3d: material")
t:check(hv.textures[1].data and hw.textures[1].data, ".x3dv / .x3d: texture from files")
t:eq(hv.meta.source.profile, "Immersive", ".x3dv: PROFILE")
t:eq(hw.meta.source.profile, "Immersive", ".x3d: profile")
t:eq(hv.meta.source.meta.title, "HelloWorld.x3d", ".x3dv: META")
t:eq(hw.meta.source.meta.creator, "Don Brutzman", ".x3d: head meta")
end
local ls = byName["assimp/X3D/IndexedLineSet.x3d"]
if ls then
local p = ls.meshes[1].primitives[1]
t:check(p.mode == "lines" and p.indices.count == 8, "IndexedLineSet: a closed polyline as 4 segments")
t:check(ls.materials[1].emissive[1] == 1, "IndexedLineSet: emissive colour")
end
local sets = byName["feature/feat_sets.x3d"]
if sets then
local m = sets.meshes
local function tris(k: number): number
local p = m[k].primitives[1]
return if p.mode == "polygons" then p.faces.count else p.indices.count // 3
end
t:eq(tris(1), 2, "IndexedTriangleSet")
local col = m[1].primitives[1].attributes.COLOR_0
t:check(col and col.components == 4 and buffer.readf32(col.data, (2 * 4 + 3) * 4) == 0.5, "ColorRGBA alpha")
t:check(sets.materials[m[1].primitives[1].material].doubleSided, "solid false")
t:eq(tris(2), 3, "TriangleFanSet fanCount")
t:eq(tris(3), 3, "IndexedTriangleStripSet runs")
t:check(m[4].primitives[1].faces.count == 1 and m[4].primitives[1].indices.count == 4, "IndexedQuadSet: one quad")
t:eq(tris(5), 2, "TriangleSet")
t:check(m[6].primitives[1].mode == "lines" and m[6].primitives[1].indices.count == 6, "LineSet vertexCount")
-- strips alternate their winding: every triangle of the strip faces +z
local p = m[3].primitives[1]
local ok = true
local P = p.attributes.POSITION
local function v(i: number): (number, number)
local k = buffer.readu32(p.indices.data, i * 4)
return buffer.readf32(P.data, k * 12), buffer.readf32(P.data, k * 12 + 4)
end
local at = 0
for f = 0, p.faces.count - 1 do
local ax, ay = v(at)
local bx, by = v(at + 1)
local cx, cy = v(at + 2)
ok = ok and (bx - ax) * (cy - ay) - (by - ay) * (cx - ax) > 0
at += buffer.readu32(p.faces.data, f * 4)
end
t:check(ok, "IndexedTriangleStripSet: counter-clockwise triangles")
end
local pr = byName["feature/feat_proto.x3d"]
if pr then
local s = C.stats(pr)
t:check(C.boundsNear(s.lo, s.hi, { -1.1, -2, -0.5 }, { 1.1, 5, 0.5 }, 1e-6), "protos: instances placed and sized " .. C.fmt(s.lo, s.hi))
t:eq(pr.meta.unit, 0.01, "UNIT length")
t:eq(pr.meta.source.meta.title, "protos", "head meta")
local kinds = {}
for _, m in pr.materials do
if m.extensions and m.extensions.KHR_materials_unlit then
kinds.unlit = m
elseif m.metallic == 0.25 then
kinds.physical = m
elseif m.baseColor[3] == 1 and m.baseColor[1] == 0 then
kinds.default = m
end
end
t:check(kinds.physical and kinds.physical.roughness == 0.75, "PhysicalMaterial")
t:check(kinds.unlit and kinds.unlit.baseColor[2] == 1, "UnlitMaterial")
t:check(kinds.default ~= nil, "SFNode field default (the proto's appearance)")
t:eq(#pr.materials, 3, "the default appearance is shared by both instances")
local cam = pr.cameras[1]
t:check(cam and cam.type == "orthographic" and cam.xmag == 2 and cam.ymag == 1, "OrthoViewpoint")
local a = pr.animations[1]
t:check(a and a.name == "Clock" and #a.channels == 1 and a.channels[1].path == "rotation", "ROUTE elements -> animation")
t:check(a and near(buffer.readf32(a.channels[1].input.data, 8), 2, 1e-6), "key times x cycleInterval")
-- quaternion keys stay on one hemisphere (0, pi, 2 pi about y)
local q = a and a.channels[1].output
t:check(q and buffer.readf32(q.data, 2 * 16 + 12) < 0, "rotation keys continuous")
end
local cl = byName["feature/feat_classic.x3dv"]
if cl then
local s = C.stats(cl)
t:check(C.boundsNear(s.lo, s.hi, { 1, 2, 3 }, { 2, 3, 4 }, 1e-6), "classic: DEF Transform")
t:eq(cl.meta.unit, 0.001, "classic: UNIT")
t:eq(cl.meta.source.components[1], "Geometry2D:1", "classic: COMPONENT")
t:eq(cl.meta.source.meta.title, "classic", "classic: META")
t:eq(cl.meshes[1].primitives[1].attributes.COLOR_0.components, 4, "classic: ColorRGBA")
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")
t:check(near(sa.area, sb.area, 1e-4), label .. ": area")
end
t:eq(#b.materials, #a.materials, label .. ": materials")
t:eq(#b.cameras, #a.cameras, label .. ": cameras")
t:eq(#b.lights, #a.lights, label .. ": lights")
t:eq(#b.animations, #a.animations, label .. ": animations")
for k, cam in a.cameras do
t:eq(b.cameras[k].type, cam.type, label .. ": camera type")
end
end
local rt = 0
for i, c in Cases do
local a = scenes[i]
if a then
for _, enc in { "xml", "x3dv" } do
local files = {}
local out, err = X3d.encode(a, { files = files, encoding = enc :: any })
t:check(out, c.name .. ": encode " .. enc .. ": " .. tostring(err))
local b = out and decode(out, { files = files, triangulate = false })
t:check(b, c.name .. ": decode our " .. enc)
if b then
compare(a, b, c.name .. " (" .. enc .. ")")
rt += 1
end
end
end
end
t:note("%d round trips", rt)
-- assimp reads our X3D like the source
local sources: { [string]: { any } } = { xcase = {}, wcase = {}, xgltf = {} }
for i, c in Cases do
sources.xcase[i] = { scenes[i], c }
end
for i, c in VrmlCases do
sources.wcase[i] = { Vrml.decode(Bytes.reader(buffer.fromstring(c.data)), { files = c.files, triangulate = false }), c }
end
for i, c in GltfCases do
sources.xgltf[i] = { Gltf.decode(Bytes.reader(buffer.fromstring(c.data)), { files = c.files }), c }
end
-- assimp loses its place in the tree after an empty <Transform/> (a leaf node: an empty, a locator)
local function hasEmpty(scene: any): boolean
for _, n in scene.nodes do
if #n.children == 0 and not n.mesh and not n.camera and not n.light then
return true
end
end
return false
end
local xc, skipped = 0, 0
for _, x in Xcheck do
local a = x.assimp
local kind = if x.xcase then "xcase" elseif x.wcase then "wcase" else "xgltf"
local src = sources[kind][x[kind]]
if src and src[1] and (a.failed or a.meshes == 0) and hasEmpty(src[1]) then
skipped += 1
elseif src and src[1] and not a.failed then
local s = C.stats(src[1])
t:eq(a.meshes, s.prims, x.name .. ": meshes (assimp reads our file)")
t:eq(a.faces, s.polys + s.lines + s.points, x.name .. ": faces (assimp reads our file)")
-- (shared meshes are written once and USE'd: assimp places USE'd nodes without their parents' transforms)
-- (MotionCaptureROM: assimp misplaces this deep hierarchy; an independent evaluation of our file's transforms
-- agrees with ours)
local deep = src[2].name == "assimp/MotionCaptureROM.WRL"
if a.min and s.lo[1] <= s.hi[1] and s.prims == s.unique and not deep then
t:check(C.boundsNear(s.lo, s.hi, a.min, a.max, 1e-4), x.name .. ": bounds (assimp reads our file) " .. C.fmt(s.lo, s.hi) .. " vs " .. C.fmt(a.min, a.max))
end
xc += 1
elseif src and src[1] then
t:check(false, x.name .. ": assimp cannot read our file (" .. src[2].name .. ")")
end
end
t:note("%d of our files read by assimp (%d skipped: empty nodes)", xc, skipped)
-- ------------------------------------------------------------------------------------------------ api, errors
do
local hw = Cases[2]
t:eq(F.detect(hw.data), "x3d", "F.detect .x3d")
t:eq(F.detect(Cases[5].data), "x3d", "F.detect .x3dv")
local s = F.load(hw.data, { files = hw.files })
t:check(s and s.meta.source.format == "x3d", "F.load")
local x3dv = F.save(s, nil, { format = "x3dv" })
t:check(x3dv and buffer.readstring(x3dv, 0, 5) == "#X3D ", "F.save format x3dv: the classic encoding")
local xml = F.save(s, nil, { format = "x3d" })
t:check(xml and string.find(buffer.tostring(xml), "<X3D", 1, true) ~= nil, "F.save format x3d: XML")
local _, e1 = decode("<X3D><Scene><Shape><Box/></Scene></X3D>")
t:check(e1 and (e1.code == Err.TRUNCATED or e1.code == Err.CORRUPT), "mismatched XML: " .. tostring(e1))
local _, e2 = decode("<?xml version='1.0'?><COLLADA/>")
t:check(e2 and e2.code == Err.CORRUPT, "not X3D: " .. tostring(e2))
-- VTK leaves the root element open: read anyway
local open = decode("<X3D><Scene><Shape><Box/></Shape></Scene>\n")
t:check(open and #open.meshes == 1, "an unclosed <X3D> root (VTK's exporter)")
local _, e3 = X3d.encode({} :: any)
t:check(e3 and e3.code == Err.ARG, "encode junk")
-- containerField and USE in XML
local u = decode([[<X3D><Scene><Shape DEF="S"><IndexedFaceSet coordIndex="0 1 2"><Coordinate point="0 0 0 1 0 0 0 1 0"/></IndexedFaceSet></Shape>
<Transform translation="5 0 0"><Shape USE="S"/></Transform>
<Switch whichChoice="0"><Group><Shape><Sphere containerField="geometry" radius="2"/></Shape></Group></Switch></Scene></X3D>]])
local us = u and C.stats(u)
t:check(us and #u.meshes == 2 and us.prims == 3 and near(us.hi[1], 6, 1e-9) and near(us.hi[2], 2, 1e-6), "USE / containerField / Switch in XML")
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 = X3d.decode(Bytes.reader(b), { files = {} })
if s then
X3d.encode(s)
end
return s
end, samples, { mutations = 16, keepHeader = 16 })
end
t:done()
+105
View File
@@ -0,0 +1,105 @@
-- video/fli tests: FLI (COLOR_64, BRUN, LC, BLACK, COPY, PSTAMP, a ring frame), FLC (prefix chunk, COLOR_256, SS2 with
-- line skips and the last-byte opcode, an empty frame), an odd-size FLC, and 15 / 16 / 24-bit FLCs (BRUN, DTA_BRUN,
-- DELTA, DTA_LC, COPY, DTA_COPY, BLACK), all encoded by the fixture script: every frame equals ffmpeg's decode
-- (CRC-32 of rgba), frame rates, the ring frame option, seeking, errors, the fuzz pass. Fixtures: tools/fixtures/fli.py.
local T = require("@tests/T")
local F = require("@formats")
local Fli = require("@formats/video/fli")
local Bytes = require("@formats/core/Bytes")
local Crc32 = require("@formats/core/Crc32")
local Err = require("@formats/core/Err")
local Fx = require("@tests/gen/fli_cases")
local t = T.suite("fli")
t:eq(Fli.name, "fli", "name")
t:eq(Fli.category, "video", "category")
local function reader(s: string): Bytes.Reader
return Bytes.reader(buffer.fromstring(s))
end
for _, c in Fx do
local label = c.name
t:check(Fli.sniff(reader(c.data)) > 0, label .. ": sniff")
t:eq(F.detect(buffer.fromstring(c.data)), "fli", label .. ": detect")
local v, err = F.video.open(buffer.fromstring(c.data))
t:check(v ~= nil, label .. ": open " .. tostring(err))
if v then
t:eq(v.codec, "flic", label .. ": codec")
t:check(v.width == c.width and v.height == c.height, label .. ": size")
t:check(math.abs(v.frameRate - c.rate) < 1e-9, label .. ": frame rate " .. v.frameRate)
t:eq(v.track.bitsPerPixel, c.depth, label .. ": depth")
local ring = v.demuxer.meta.ringFrame
local want = if ring then #c.frames - 1 else #c.frames
local n, bad = 0, 0
while true do
local f, ferr = v:nextFrame()
if not f then
t:check(ferr == nil, label .. ": " .. tostring(ferr))
break
end
n += 1
if f.image.format ~= "rgba8" or Crc32.of(f.image.pixels) ~= c.frames[n] then
bad += 1
end
end
t:check(n == want and bad == 0, string.format("%s: %d of %d frames equal ffmpeg's (%d differ)", label, n - bad, want, bad))
v:seek(0.25)
local f = v:nextFrame()
local k = math.floor(0.25 * c.rate + 1 - 1e-9) + 1
t:check(f ~= nil and Crc32.of(f.image.pixels) == c.frames[k], label .. ": seek to frame " .. k)
if ring then
local v2 = Fli.open(reader(c.data), { ringFrame = true })
local m = 0
while v2 and v2:nextFrame() do
m += 1
end
t:eq(m, #c.frames, label .. ": with the ring frame")
end
end
end
-- errors
do
local _, e = Fli.open(reader(string.sub(Fx[1].data, 1, 100)))
t:check(e ~= nil and e.code == Err.TRUNCATED, "short header: TRUNCATED")
local bad = Fx[1].data
bad = string.sub(bad, 1, 4) .. "\0\0" .. string.sub(bad, 7)
t:eq(Fli.sniff(reader(bad)), 0, "bad magic: no sniff")
local _, e2 = Fli.open(reader(bad))
t:check(e2 ~= nil and e2.code == Err.CORRUPT, "bad magic: CORRUPT")
local big = string.sub(Fx[1].data, 1, 8) .. "\255\15\255\15" .. string.sub(Fx[1].data, 13)
local _, e3 = Fli.open(reader(big), { maxPixels = 2 ^ 20 })
t:check(e3 ~= nil and e3.code == Err.LIMIT, "maxPixels: LIMIT")
end
local samples = {}
for _, c in Fx do
table.insert(samples, c.data)
end
t:fuzz("open", function(b: buffer)
local v = Fli.open(Bytes.reader(b))
if v then
while v:nextFrame() do
end
end
return v
end, samples, { mutations = 12, garbage = 40, keepHeader = 16 })
-- the frame decoder itself (codecs/video/Legacy/Flic, native: no pcall in between)
local Flic = require("@formats/codecs/video/Legacy").Flic
for _, c in { Fx[1], Fx[2], Fx[4], Fx[6] } do
local d = Fli.demux(reader(c.data))
local packets = {}
for k = 1, math.min(4, d:count(1)) do
table.insert(packets, d:get(1, k).data)
end
t:fuzz(c.name .. " frames", function(b: buffer)
local st = Flic.state(c.width, c.height, c.depth)
if st then
Flic.decode(st, b)
return Flic.image(st)
end
return nil
end, packets, { mutations = 20, garbage = 30 })
end
t:done()
+80
View File
@@ -0,0 +1,80 @@
-- MPEG-2 video in the containers (tools/fixtures/mpeg2.py, "mpeg2_containers"): the same elementary stream copied by
-- ffmpeg into MPEG-TS (stream type 0x02, and the PMT patched to 0x80, private / DigiCipher II video), MPEG-PS (VOB),
-- Matroska (V_MPEG2) and AVI: each opens through F.video.open with codec "mpeg2", its frames equal ffmpeg's
-- `-idct int` decode (luma CRC per frame, display order), seeking lands on a frame; the raw .m2v opens too.
local T = require("@tests/T")
local F = require("@formats")
local Base64 = require("@formats/core/Base64")
local Crc32 = require("@formats/core/Crc32")
local Fx = require("@tests/gen/mpeg2_containers")
local Prog = require("@tests/gen/mpeg2_prog")
local t = T.suite("video/mpeg2")
local function lumaCrc(img: any): number
return Crc32.of(img.pixels, 0, img.width * img.height)
end
local CASES = {
{ "ts", "mpegts" },
{ "ts80", "mpegts" },
{ "mpg", "mpegps" },
{ "mkv", "mkv" },
{ "avi", "avi" },
}
for _, c in CASES do
local key, format = c[1], c[2]
local data = Base64.decode(Fx[key]) :: buffer
local v, err = F.video.open(data)
t:check(v ~= nil, key .. ": opens: " .. tostring(err))
if v then
t:eq(v.format, format, key .. ": format")
t:eq(v.codec, "mpeg2", key .. ": codec")
t:check(v.width == Prog.width and v.height == Prog.height, key .. ": size")
local frames, exact = 0, 0
while true do
local f, ferr = v:nextFrame()
t:check(ferr == nil, key .. ": frame error " .. tostring(ferr))
if not f then
break
end
frames += 1
local ref = Fx.crcs[frames]
if ref and lumaCrc(f.image) == ref[1] then
exact += 1
end
end
t:eq(frames, #Fx.crcs, key .. ": frame count")
-- the frames ffmpeg's encoder left with an uncoded macroblock are concealed differently (tests/codecs/mpeg2)
t:check(exact >= frames - 2, string.format("%s: %d of %d frames equal ffmpeg's", key, exact, frames))
v:seek(0.4)
local f = v:nextFrame()
t:check(f ~= nil and math.abs(f.pts - 0.4) < 0.05, key .. ": seek")
t:note(" %-5s %-7s %d frames, %d bit-exact", key, format, frames, exact)
end
end
-- the elementary stream itself
do
local v, err = F.video.open(Base64.decode(Prog.file) :: buffer)
t:check(v ~= nil and v.codec == "mpeg2", "m2v: opens as mpeg2: " .. tostring(err))
if v then
local n = 0
while v:nextFrame() do
n += 1
end
t:eq(n, Prog.frames, "m2v: frame count")
end
end
t:fuzz("open", function(b: buffer)
local v = F.video.open(b)
if v then
for _ = 1, 3 do
v:nextFrame()
end
end
return v
end, { Base64.decode(Fx.ts) :: buffer, Base64.decode(Fx.mpg) :: buffer }, { mutations = 30, garbage = 5 })
t:done()
+211
View File
@@ -0,0 +1,211 @@
-- video/ogv tests: Ogg Theora files from ffmpeg (libtheora + libvorbis; tools/fixtures/theora.py): sniffing (Theora
-- BOS pages, plain Ogg Vorbis left to the audio formats), tracks, granule times, every frame through F.video.open
-- bit-exact with ffmpeg's (Adler-32 of yuv420p, its framecrc), an empty packet (a repeated frame), the Vorbis track
-- through the api's audio hook against ffmpeg's decode, tags, seeking, remuxing (ogv -> ogv, mkv -> ogv, ogv -> mkv)
-- read back, errors and the fuzz no-throw pass.
local T = require("@tests/T")
local C = require("@tests/video/_common")
local F = require("@formats")
local Ogv = require("@formats/video/ogv")
local Theora = require("@formats/codecs/video/Theora")
local AudioWrap = require("@formats/containers/AudioWrap")
local Bytes = require("@formats/core/Bytes")
local Base64 = require("@formats/core/Base64")
local Adler32 = require("@formats/core/Adler32")
local Err = require("@formats/core/Err")
local t = T.suite("ogv")
local AV = require("@tests/gen/theora_av") :: any
local Q0 = require("@tests/gen/theora_q0") :: any
local DUPE = require("@tests/gen/theora_dupe") :: any
local MKV = require("@tests/gen/theora_mkv") :: any
local OPUS = require("@tests/gen/theora_opus") :: any
local FLAC = require("@tests/gen/theora_flac") :: any
local function file(fx: any): buffer
return Base64.decode(fx.file) :: buffer
end
-- every frame of a VideoDecoder against ffmpeg's framecrc (yuv420p, keyed by frame number); frames ffmpeg does not
-- show (empty packets) must repeat the previous one
local function frames(v: any, fx: any, label: string, fps: number)
local want: { [number]: number } = {}
for _, f in fx.frames do
want[f[1]] = f[2]
end
local n, bad, shown, prev = 0, 0, 0, nil :: number?
while true do
local f, err = v:nextFrame()
if not f then
t:check(err == nil, label .. ": decode error " .. tostring(err))
break
end
n += 1
local c = Adler32.of(f.image.pixels, nil, nil, 0)
local w = want[math.floor(f.pts * fps + 0.5)]
if w then
shown += 1
if c ~= w then
bad += 1
end
elseif c ~= prev then
bad += 1
end
prev = c
end
t:eq(bad, 0, label .. ": frames equal to ffmpeg's (" .. n .. " frames)")
t:eq(shown, #fx.frames, label .. ": every frame ffmpeg shows")
return n
end
-- 1. contract and sniffing
t:eq(Ogv.name, "ogv", "name")
t:eq(Ogv.category, "video", "category")
t:check(table.find(Ogv.extensions, "ogv") ~= nil, "ogv extension")
t:eq(Ogv.sniff(Bytes.reader(file(AV))), 1, "sniff: Theora + Vorbis")
t:eq(Ogv.sniff(Bytes.reader(file(Q0))), 1, "sniff: Theora")
t:eq(Ogv.sniff(Bytes.reader(buffer.fromstring("OggS\0\2" .. string.rep("\0", 40)))), 0, "sniff: an Ogg page without Theora")
t:eq(Ogv.sniff(Bytes.reader(buffer.fromstring("RIFF"))), 0, "sniff: not Ogg")
-- 2. Theora + Vorbis through the api
local v, err = F.video.open(file(AV))
t:check(v ~= nil, "open: " .. tostring(err))
if v then
t:eq(v.format, "ogv", "format")
t:eq(v.codec, "theora", "codec")
t:eq(v.width * 1000 + v.height, 160120, "size")
t:eq(v.frameRate, 25, "frame rate")
local dmx = v.demuxer :: any
t:eq(#dmx.tracks, 2, "two tracks")
local vt, at = dmx:track("video"), dmx:track("audio")
t:check(vt and vt.codec == "theora" and vt.timescale == 25, "video track")
t:check(at and at.codec == "vorbis" and at.sampleRate == 44100 and at.channels == 2, "audio track")
t:check(vt and vt.config and #(Theora.splitConfig(vt.config) or {}) == 3, "video config: three Xiph-laced headers")
t:check(math.abs(v.duration - 1) < 0.05, "duration " .. v.duration)
t:check(v.meta.tags and v.meta.tags.encoder ~= nil, "tags from the comment header")
local first = dmx:get(vt.id, 1)
t:check(first and first.keyframe and first.pts == 0, "first packet: a keyframe at 0")
t:check(not dmx:get(vt.id, 2).keyframe, "second packet: an inter frame")
frames(v, AV, "av", 25)
local pcm = Base64.decode(AV.pcm) :: buffer
C.audio(t, v, { pcm = buffer.tostring(pcm) }, "av", false, 20)
-- seeking
v:seek(0.5)
local f = v:nextFrame()
t:check(f ~= nil and f.pts >= 0.5 - 1e-6 and f.pts < 0.6, "seek 0.5 -> " .. tostring(f and f.pts))
if f then
local want = nil
for _, w in AV.frames do
if w[1] == math.floor(f.pts * 25 + 0.5) then
want = w[2]
end
end
t:eq(Adler32.of(f.image.pixels, nil, nil, 0), want, "the frame after seeking equals ffmpeg's")
end
-- remux ogv -> ogv
v:reset()
local out, rerr = F.save(v, nil, { format = "ogv" })
t:check(out ~= nil, "remux: " .. tostring(rerr))
if out then
t:eq(Ogv.sniff(Bytes.reader(out)), 1, "remux: sniff")
local v2 = F.video.open(out) :: any
t:check(v2 ~= nil and #v2.demuxer.tracks == 2, "remux: two tracks")
if v2 then
frames(v2, AV, "remux", 25)
C.audio(t, v2, { pcm = buffer.tostring(pcm) }, "remux", false, 20)
end
end
-- remux ogv -> mkv (V_THEORA)
v:reset()
local mk, merr = F.save(v, nil, { format = "mkv" })
t:check(mk ~= nil, "to mkv: " .. tostring(merr))
if mk then
local v3 = F.video.open(mk) :: any
t:check(v3 ~= nil and v3.codec == "theora", "to mkv: Theora track")
if v3 then
frames(v3, AV, "to mkv", 25)
end
end
end
-- 3. Opus and FLAC audio tracks (FLAC: exact)
for _, c in { { OPUS, "opus", 48000 }, { FLAC, "flac", 22050 } } do
local fx, codec, rate = c[1], c[2], c[3]
local vd, e = F.video.open(file(fx))
t:check(vd ~= nil, codec .. ": open: " .. tostring(e))
if vd then
local at = (vd.demuxer :: any):track("audio")
t:check(at and at.codec == codec and at.sampleRate == rate and at.channels == 1, codec .. ": audio track")
frames(vd, fx, codec, 25)
C.audio(t, vd, { pcm = buffer.tostring(Base64.decode(fx.pcm) :: buffer) }, codec, codec == "flac", 20)
if codec == "opus" then
vd:reset()
local out = F.save(vd, nil, { format = "ogv" })
local v2 = out and F.video.open(out) :: any
t:check(v2 ~= nil and v2.audio ~= nil, "opus: remux keeps the audio")
if v2 then
C.audio(t, v2, { pcm = buffer.tostring(Base64.decode(fx.pcm) :: buffer) }, "opus remux", false, 20)
end
end
end
end
-- 4. an empty packet: a repeated frame with its own time
do
local vd = Ogv.open(Bytes.reader(file(DUPE))) :: any
local n = 0
local prev, dupAt = nil, nil
while true do
local f = vd:nextFrame()
if not f then
break
end
n += 1
local c = Adler32.of(f.image.pixels, nil, nil, 0)
if n == 6 then
dupAt = f.pts
t:eq(c, prev, "dupe: frame 6 repeats frame 5")
end
prev = c
end
t:eq(n, #DUPE.frames + 1, "dupe: one frame per packet")
t:check(dupAt ~= nil and math.abs((dupAt :: number) - 0.2) < 1e-6, "dupe: its time slot (0.2 s)")
t:check(vd.audio == nil and vd.audioError == nil, "no audio track, no audio error")
end
-- 5. Theora in Matroska -> ogv
do
local mv = F.video.open(file(MKV)) :: any
local out, e = F.save(mv, nil, { format = "ogv" })
t:check(out ~= nil, "mkv -> ogv: " .. tostring(e))
if out then
local v2 = Ogv.open(Bytes.reader(out)) :: any
frames(v2, MKV, "mkv -> ogv", 25)
end
end
-- 6. not Theora: plain Ogg Vorbis goes to the audio format, writing other codecs fails
do
local vd = Ogv.open(Bytes.reader(file(AV))) :: any
local at = vd.demuxer:track("audio")
local ogg = AudioWrap.wrap(vd.demuxer, at) :: buffer
t:eq(Ogv.sniff(Bytes.reader(ogg)), 0, "sniff: Ogg Vorbis is not ogv")
local a = F.load(ogg, { name = "x.ogg" })
t:check(a ~= nil and a.kind == "audio", "F.load of Ogg Vorbis named .ogg: audio")
local v4, e4 = Ogv.open(Bytes.reader(ogg))
t:check(v4 ~= nil and v4.decodeError ~= nil, "an Ogg without video: opens, frames UNSUPPORTED (" .. tostring(e4) .. ")")
local _, ee = Ogv.encode(Ogv.open(Bytes.reader(ogg)) :: any)
t:check(ee ~= nil and ee.code == Err.UNSUPPORTED, "encode without Theora: UNSUPPORTED")
local _, eg = Ogv.open(Bytes.reader(buffer.fromstring("OggS garbage")))
t:check(eg ~= nil, "garbage: an error")
local cut = buffer.create(5000)
buffer.copy(cut, 0, file(Q0), 0, 5000)
local vc = Ogv.open(Bytes.reader(cut))
t:check(vc ~= nil, "a truncated file opens")
end
-- 7. fuzz
t:fuzz("open", C.fuzzOpen(Ogv), { buffer.tostring(file(Q0)) }, { mutations = 16, garbage = 50 })
t:done()
+180
View File
@@ -0,0 +1,180 @@
-- video/smk tests: Smacker files encoded by the fixture script (SMK2 and SMK4, every block type and run, the trees'
-- escape cache, palette updates, a ring frame, ms and 10 us frame times; packed 16-bit stereo / 8-bit mono / 16-bit
-- mono / 8-bit stereo audio and raw s16le / u8 tracks): every video frame and every audio track equal ffmpeg's
-- decode (CRC-32 of rgba / f32le), audio seeking, errors, and the fuzz pass on the container, the video codec and the
-- audio codec. Fixtures: tools/fixtures/smk.py.
local T = require("@tests/T")
local F = require("@formats")
local Smk = require("@formats/video/smk")
local SmkAudio = require("@formats/video/smk/Audio")
local Legacy = require("@formats/codecs/video/Legacy")
local Bytes = require("@formats/core/Bytes")
local Crc32 = require("@formats/core/Crc32")
local Err = require("@formats/core/Err")
local Fx = require("@tests/gen/smk_cases")
local t = T.suite("smk")
t:eq(Smk.name, "smk", "name")
t:eq(Smk.category, "video", "category")
local function reader(s: string): Bytes.Reader
return Bytes.reader(buffer.fromstring(s))
end
-- every frame of an audio Decoder -> f32 buffer, frames
local function drain(dec: any): (buffer, number)
local chunks, total = {}, 0
while true do
local b, n = dec:read(1000)
if n == 0 then
break
end
table.insert(chunks, { b, n })
total += n
end
local out = buffer.create(total * dec.channels * 4)
local at = 0
for _, c in chunks do
buffer.copy(out, at, c[1], 0, c[2] * dec.channels * 4)
at += c[2] * dec.channels * 4
end
return out, total
end
for _, c in Fx do
local label = c.name
t:check(Smk.sniff(reader(c.data)) == 1, label .. ": sniff")
t:eq(F.detect(buffer.fromstring(c.data)), "smk", label .. ": detect")
local v, err = F.video.open(buffer.fromstring(c.data))
t:check(v ~= nil, label .. ": open " .. tostring(err))
if v then
t:eq(v.codec, "smackvid", label .. ": codec")
t:check(v.width == c.width and v.height == c.height, label .. ": size")
t:check(math.abs(v.frameRate - c.rate) < 1e-6, label .. ": frame rate " .. v.frameRate)
local want = if c.ring then #c.frames - 1 else #c.frames
local n, bad = 0, 0
while true do
local f, ferr = v:nextFrame()
if not f then
t:check(ferr == nil, label .. ": " .. tostring(ferr))
break
end
n += 1
if f.image.format ~= "rgba8" or Crc32.of(f.image.pixels) ~= c.frames[n] then
bad += 1
end
end
t:check(n == want and bad == 0, string.format("%s: %d of %d frames equal ffmpeg's (%d differ)", label, n - bad, want, bad))
v:seek(0.2)
local f = v:nextFrame()
local k = math.floor(0.2 * c.rate - 1e-9) + 2
t:check(f ~= nil and Crc32.of(f.image.pixels) == c.frames[k], label .. ": seek to frame " .. k)
-- audio: the first track through the VideoDecoder, every track through Smk.openAudio
if #c.audio > 0 then
t:check(v.audio ~= nil, label .. ": audio " .. tostring(v.audioError))
end
local tracks = {}
for _, tr in v.demuxer.tracks do
if tr.kind == "audio" then
table.insert(tracks, tr)
end
end
t:eq(#tracks, #c.audio, label .. ": audio tracks")
for i, a in c.audio do
local tr = tracks[i]
t:eq(tr.codec, a.codec, label .. ": audio " .. i .. " codec")
local dec, aerr = Smk.openAudio(v.demuxer, tr)
t:check(dec ~= nil, label .. ": audio " .. i .. ": " .. tostring(aerr))
if dec then
t:check(dec.sampleRate == a.rate and dec.channels == a.channels, label .. ": audio " .. i .. " format")
local pcm, frames = drain(dec)
t:eq(frames, a.frames, label .. ": audio " .. i .. " frames")
t:eq(Crc32.of(pcm), a.crc, label .. ": audio " .. i .. " equals ffmpeg's")
dec:seek(0)
local again = drain(dec)
t:eq(Crc32.of(again), a.crc, label .. ": audio " .. i .. " after seek(0)")
dec:seek(0.3)
local tail, rest = drain(dec)
local skip = a.frames - rest
t:check(math.abs(skip - 0.3 * a.rate) <= 1, label .. ": audio " .. i .. " seek(0.3) at frame " .. skip)
local same = buffer.len(tail) > 0
for q = 0, math.min(buffer.len(tail), 4000) - 4, 4 do
if buffer.readu32(tail, q) ~= buffer.readu32(pcm, skip * a.channels * 4 + q) then
same = false
break
end
end
t:check(same, label .. ": audio " .. i .. " seek(0.3) samples")
end
end
if c.ring then
local v2 = Smk.open(reader(c.data), { ringFrame = true })
local m = 0
while v2 and v2:nextFrame() do
m += 1
end
t:eq(m, #c.frames, label .. ": with the ring frame")
end
end
end
-- errors
do
local _, e = Smk.open(reader(string.sub(Fx[1].data, 1, 60)))
t:check(e ~= nil and e.code == Err.TRUNCATED, "short header: TRUNCATED")
local _, e2 = Smk.open(reader("SMK3" .. string.sub(Fx[1].data, 5)))
t:check(e2 ~= nil and e2.code == Err.CORRUPT, "bad magic: CORRUPT")
t:eq(Smk.sniff(reader("SMK3" .. string.sub(Fx[1].data, 5))), 0, "bad magic: no sniff")
local _, e3 = Smk.open(reader(Fx[1].data), { maxPixels = 100 })
t:check(e3 ~= nil and e3.code == Err.LIMIT, "maxPixels: LIMIT")
local _, e4 = Smk.open(reader(string.sub(Fx[1].data, 1, 200)))
t:check(e4 ~= nil and e4.code == Err.TRUNCATED, "trees past the end: TRUNCATED")
end
-- fuzz: the container, the video codec (native, no pcall in between) and the audio codec
local samples = {}
for _, c in Fx do
table.insert(samples, c.data)
end
t:fuzz("open", function(b: buffer)
local v = Smk.open(Bytes.reader(b))
if v then
for _ = 1, 4 do
if not v:nextFrame() then
break
end
end
if v.audio then
v.audio:read(500)
end
end
return v
end, samples, { mutations = 16, garbage = 40, keepHeader = 4 })
local S, P = Legacy.Smacker, Legacy.Picture
for _, c in { Fx[1], Fx[2] } do
local d = Smk.demux(reader(c.data))
local tr = d.tracks[1]
local packets = {}
for k = 1, math.min(3, d:count(1)) do
table.insert(packets, d:get(1, k).data)
end
t:fuzz(c.name .. " trees", function(b: buffer)
return S.trees(b)
end, { tr.config }, { mutations = 30, garbage = 30, keepHeader = 16 })
local trees = assert(S.trees(tr.config))
t:fuzz(c.name .. " frames", function(b: buffer)
return S.decode(P.new(c.width, c.height, true, 4, 4), b, trees, tr.codecTag == "SMK4")
end, packets, { mutations = 30, garbage = 30 })
for _, at in d.tracks do
if at.kind == "audio" then
local ap = {}
for k = 1, math.min(2, d:count(at.id)) do
table.insert(ap, d:get(at.id, k).data)
end
t:fuzz(c.name .. " audio " .. at.codec, function(b: buffer)
return SmkAudio.decode(b, at.channels, at.bitsPerSample, at.codec == "smackaudio")
end, ap, { mutations = 20, garbage = 20 })
end
end
end
t:done()