merge ws/3d3-d (model/b3d, model/ldraw)

This commit is contained in:
4DBug committed 2026-10-31 14:30:17 -05:00
commit de2695b87d
14 files changed
+2843 -1

No files matched your search

+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()
+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()