ws-3d: model/stl (ASCII + binary, VisCAM / Magics colours), model/ply (ASCII + binary LE/BE, arbitrary properties, point clouds, raw extra elements), model/off (OFF/COFF/NOFF/STOFF, face colours), read + write; codecs/MeshFlatten (Scene -> one world-space mesh for the mesh-only writers, shared instead of a copy per format); tests vs assimp / trimesh / plyfile, reference tools reading our output

This commit is contained in:
4DBug committed 2026-10-31 09:02:59 -05:00
1 parent fb909438a5
commit 35891a06d1
18 files changed
+5408

No files matched your search

+214
View File
@@ -0,0 +1,214 @@
-- model/off tests: OFF files written by trimesh and by the generator (COFF integer / float colours, RGB / RGBA, NOFF,
-- STOFF, STCNOFF, face colours, colormap indices, comments, counts on the header line, CRLF, tabs, n-gons, a point
-- cloud) against the values they were written from (positions cross-checked with trimesh); our encoder's output read
-- back by trimesh, assimp and the generator's reader (verdicts from the fixture step); round trips (polygons,
-- triangles, face colours, scenes); the contract, error codes and the fuzz no-throw pass. Fixtures:
-- tools/fixtures/off.py.
local T = require("@tests/T")
local Off = require("@formats/model/off")
local Bytes = require("@formats/core/Bytes")
local Crc32 = require("@formats/core/Crc32")
local Err = require("@formats/core/Err")
local Types = require("@formats/Types")
local Fx = require("@tests/gen/off")
local Scenes = require("@tests/gen/off_scenes")
local t = T.suite("off")
local function decode(data: any, opts: any?): (any, any)
local b = if type(data) == "string" then buffer.fromstring(data) else data
return Off.decode(Bytes.reader(b), opts)
end
local function same(a: any, b: any): boolean
if a == nil or b == nil then
return a == b
end
return a.type == b.type and a.components == b.components and a.count == b.count and buffer.tostring(a.data) == buffer.tostring(b.data)
end
-- 1. the contract
t:eq(Off.name, "off", "name")
t:eq(Off.category, "model", "category")
t:check(table.find(Off.extensions, "off") ~= nil, "extensions")
t:check(Off.caps.decode and Off.caps.encode, "caps")
-- 2. every fixture against the values it was written from; 3. round trips
for _, c in Fx.cases do
local label = c.name
local scene, err = decode(c.data)
t:check(scene, label .. ": " .. tostring(err))
local src = scene.meta.source
t:check(src.format == "off" and src.keyword == c.keyword and src.vertices == c.vertices and src.faces == c.faces, label .. ": meta.source")
t:eq(src.colormap, c.colormap, label .. ": colormap flag")
local p = scene.meshes[1].primitives[1]
local A = p.attributes
t:eq(Crc32.of(A.POSITION.data), c.pos_crc, label .. ": POSITION crc")
t:check((A.NORMAL and Crc32.of(A.NORMAL.data)) == c.nrm_crc, label .. ": NORMAL")
t:check((A.TEXCOORD_0 and Crc32.of(A.TEXCOORD_0.data)) == c.tex_crc, label .. ": TEXCOORD_0")
if c.color then
t:check(A.COLOR_0 and A.COLOR_0.type == c.color.type and A.COLOR_0.components == 4, label .. ": COLOR_0 type")
t:eq(Crc32.of(A.COLOR_0.data), c.color.crc, label .. ": COLOR_0 crc")
else
t:check(A.COLOR_0 == nil, label .. ": no COLOR_0")
end
local ex = p.extras or {}
if c.faceColors then
t:check(ex.faceColors and ex.faceColors.type == c.faceColors.type and ex.faceColors.count == c.faces, label .. ": faceColors type")
t:eq(Crc32.of(ex.faceColors.data), c.faceColors.crc, label .. ": faceColors crc")
else
t:check(ex.faceColors == nil, label .. ": no faceColors")
end
if c.faces == 0 then
t:check(p.mode == "points" and p.indices == nil, label .. ": a point cloud")
else
t:eq(p.mode, "triangles", label .. ": mode")
t:eq(p.indices.count, c.tris * 3, label .. ": index count")
t:eq(Crc32.of(p.indices.data), if c.allTri then c.corners_crc else c.tri_crc, label .. ": indices crc")
if c.faceColors and not c.allTri then
t:eq(Crc32.of(ex.faceOfTriangle.data), c.fot_crc, label .. ": faceOfTriangle")
end
end
t:eq(Off.sniff(Bytes.reader(buffer.fromstring(c.data))), 0.9, label .. ": sniff")
-- polygons kept
local poly = decode(c.data, { triangulate = false })
local pp = poly.meshes[1].primitives[1]
if c.faces > 0 and not c.allTri then
t:eq(pp.mode, "polygons", label .. ": polygons")
t:eq(Crc32.of(pp.indices.data), c.corners_crc, label .. ": corners")
t:eq(Crc32.of(pp.faces.data), c.sizes_crc, label .. ": sizes")
end
-- round trips: polygons in, polygons out; triangles in, triangles out (face colours through faceOfTriangle)
for _, s in { poly, scene } do
local out, eerr = Off.encode(s)
t:check(out, label .. ": encode: " .. tostring(eerr))
local back, berr = decode(out, { triangulate = false })
t:check(back, label .. ": decode our output: " .. tostring(berr))
local bp, sp = back.meshes[1].primitives[1], s.meshes[1].primitives[1]
for name, a in sp.attributes do
t:check(same(bp.attributes[name], a), label .. ": " .. name .. " round trip")
end
t:eq(bp.mode, sp.mode, label .. ": mode round trip")
t:check(same(bp.indices, sp.indices) and same(bp.faces, sp.faces), label .. ": faces round trip")
local sfc = sp.extras and sp.extras.faceColors
local bfc = bp.extras and bp.extras.faceColors
if sfc and sp.extras.faceOfTriangle then
t:eq(bfc.count, sp.extras.faceOfTriangle.count, label .. ": a colour per triangle")
else
t:check(same(bfc, sfc), label .. ": faceColors round trip")
end
end
end
t:note("%d files match their source values and round-trip", #Fx.cases)
for _, v in Fx.ours do
t:check(v.ok, "trimesh / assimp read our " .. v.name .. ": " .. v.detail)
end
t:note("%d encodings read back by trimesh, assimp and the generator", #Fx.ours)
-- the encoder scenes: decode(encode()) gives the scene back (identity transforms)
local function build(spec: any): Types.Scene
local scene = Types.Scene.new()
for i, m in spec.meshes do
local prims = {}
for _, p in m.prims do
local attrs = {}
for name, a in p.attrs do
attrs[name] = Types.Scene.accessor(buffer.fromstring(a[3]), a[1], a[2], p.count)
end
local prim: any = { attributes = attrs, mode = p.mode }
if p.indices then
prim.indices = Types.Scene.accessor(buffer.fromstring(p.indices), "u32", 1, #p.indices // 4)
end
if p.faces then
prim.faces = Types.Scene.accessor(buffer.fromstring(p.faces), "u32", 1, #p.faces // 4)
end
if p.faceColors then
prim.extras = { faceColors = Types.Scene.accessor(buffer.fromstring(p.faceColors), "unorm8", 4, #p.faceColors // 4) }
end
table.insert(prims, prim)
end
scene.meshes[i] = { primitives = prims }
end
for i, n in spec.nodes do
scene.nodes[i] = { mesh = n.mesh, children = n.children or {}, translation = n.translation, rotation = n.rotation, scale = n.scale, matrix = n.matrix }
end
scene.roots = spec.roots
return scene
end
for _, spec in Scenes do
local scene = build(spec)
local sp = scene.meshes[1].primitives[1]
local out = Off.encode(scene) :: buffer
local back = decode(out, { triangulate = false })
local bp = back.meshes[1].primitives[1]
if spec.name ~= "polys" then
for name, a in sp.attributes do
t:check(same(bp.attributes[name], a), spec.name .. ": " .. name .. " round trip")
end
end
t:eq(bp.mode, sp.mode, spec.name .. ": mode")
t:check(same(bp.indices, sp.indices) and same(bp.faces, sp.faces), spec.name .. ": faces")
t:check(same(bp.extras and bp.extras.faceColors, sp.extras and sp.extras.faceColors), spec.name .. ": face colours")
end
do
local scene = build(Scenes[1])
local plain = buffer.tostring(Off.encode(scene, { colors = false, normals = false, texcoords = false }) :: buffer)
t:eq(string.sub(plain, 1, 4), "OFF\n", "plain OFF")
t:eq(string.sub(buffer.tostring(Off.encode(scene, { colors = false }) :: buffer), 1, 6), "STNOFF", "no colours")
local cm = buffer.tostring(Off.encode(scene, { comment = "made\nhere" }) :: buffer)
t:check(string.find(cm, "STCNOFF\n# made here\n", 1, true) ~= nil, "comment option")
end
-- 4. error codes
do
local function code(s: string, opts: any?): string?
local _, e = decode(s, opts)
return e and e.code
end
t:check(decode("OFF\n3 1 0\n0 0 0\n1 0 0\n0 1 0\n3 0 1 2\n"), "a minimal file")
t:eq(code("PFF\n3 1 0\n"), Err.CORRUPT, "bad keyword")
t:eq(code("4OFF\n1 0 0\n0 0 0 1\n"), Err.UNSUPPORTED, "4OFF")
t:eq(code("nOFF\n4\n1 0 0\n0 0 0 0\n"), Err.UNSUPPORTED, "nOFF")
t:eq(code("OFF BINARY\n"), Err.UNSUPPORTED, "binary OFF")
t:eq(code("OFF\n"), Err.TRUNCATED, "no counts")
t:eq(code("# nothing\n\n"), Err.TRUNCATED, "empty")
t:eq(code("OFF\nx 1 0\n"), Err.CORRUPT, "bad counts")
t:eq(code("OFF\n3 1 0\n0 0 0\n1 0 0\n0 1 0\n"), Err.TRUNCATED, "face missing")
t:eq(code("OFF\n3 1 0\n0 0 0\n1 0 0\n0 1 0\n3 0 1 3\n"), Err.CORRUPT, "index out of range")
t:eq(code("OFF\n3 1 0\n0 0 0\n1 0 0\n0 1 0\n4 0 1 2\n"), Err.CORRUPT, "short face")
t:eq(code("OFF\n3 1 0\n0 0 0\n1 q 0\n0 1 0\n3 0 1 2\n"), Err.CORRUPT, "bad number")
t:eq(code("OFF\n3 1 0\n0 0 0\n1 0\n0 1 0\n3 0 1 2\n"), Err.CORRUPT, "short vertex")
t:eq(code("COFF\n3 1 0\n0 0 0 1 2\n1 0 0 1 2\n0 1 0 1 2\n3 0 1 2\n"), Err.CORRUPT, "two colour values")
t:eq(code("COFF\n3 1 0\n0 0 0 300 2 3\n1 0 0 1 2 3\n0 1 0 1 2 3\n3 0 1 2\n"), Err.CORRUPT, "colour over 255")
t:eq(code("OFF\n3 1 0\n0 0 0\n1 0 0\n0 1 0\n3 0 1 2\n", { maxVertices = 2 }), Err.LIMIT, "maxVertices")
t:eq(code("OFF\n3 1 0\n0 0 0\n1 0 0\n0 1 0\n3 0 1 2\n", { maxFaces = 0 }), Err.LIMIT, "maxFaces")
t:eq(code("OFF\n10000000 0 0\n1 2 3\n"), Err.TRUNCATED, "counts over the data")
local _, a1 = Off.encode({} :: any)
t:check(a1 and a1.code == Err.ARG, "encode a non-scene: " .. tostring(a1))
local nan = Types.Scene.fromPrimitive({ attributes = { POSITION = Types.Scene.accessor(nil, "f32", 3, 1) }, mode = "points" })
buffer.writef32(nan.meshes[1].primitives[1].attributes.POSITION.data, 0, math.huge)
local _, a2 = Off.encode(nan)
t:check(a2 and a2.code == Err.ARG, "infinite coordinate: " .. tostring(a2))
t:eq(Off.sniff(Bytes.reader(buffer.fromstring("solid x\n"))), 0, "sniff an STL")
end
-- 5. fuzz
do
local samples = {}
for _, c in Fx.cases do
table.insert(samples, c.data)
end
t:fuzz("decode", function(b: buffer)
return Off.decode(Bytes.reader(b))
end, samples, { mutations = 20 })
t:fuzz("decode polygons + re-encode", function(b: buffer)
local s = Off.decode(Bytes.reader(b), { triangulate = false })
if s then
return Off.encode(s)
end
return nil
end, samples, { mutations = 6, garbage = 20 })
end
t:done()
+379
View File
@@ -0,0 +1,379 @@
-- model/ply tests: files written by plyfile (ascii / binary LE / BE, every property type and spelling, odd orders,
-- n-gons up to 300 vertices, face properties and lists, extra elements, comments, point clouds) and by assimp, against
-- plyfile's reading mapped to the Scene conventions (CRC-32 of every attribute, the indices triangulated or as
-- polygons, face data, raw elements); our encoder's output read back by plyfile and assimp (verdicts from the fixture
-- step); round trips in every encoding (fixtures and generated scenes, polygons and points); the contract, error
-- codes, the fuzz no-throw pass and a binary decode throughput note. Fixtures: tools/fixtures/ply.py.
local T = require("@tests/T")
local Ply = require("@formats/model/ply")
local Bytes = require("@formats/core/Bytes")
local Crc32 = require("@formats/core/Crc32")
local Err = require("@formats/core/Err")
local Types = require("@formats/Types")
local Fx = require("@tests/gen/ply")
local Scenes = require("@tests/gen/ply_scenes")
local t = T.suite("ply")
local function decode(data: any, opts: any?): (any, any)
local b = if type(data) == "string" then buffer.fromstring(data) else data
return Ply.decode(Bytes.reader(b), opts)
end
local ENCODINGS = { "ascii", "binary_little_endian", "binary_big_endian" }
-- 1. the contract
t:eq(Ply.name, "ply", "name")
t:eq(Ply.category, "model", "category")
t:check(table.find(Ply.extensions, "ply") ~= nil, "extensions")
t:check(Ply.caps.decode and Ply.caps.encode, "caps")
-- a decoded scene against a reference case (triangulated)
local function verify(scene: any, c: any, label: string)
t:check(scene.kind == "scene" and #scene.meshes == 1 and #scene.meshes[1].primitives == 1, label .. ": one primitive")
local p = scene.meshes[1].primitives[1]
local n = 0
for name, want in c.attrs do
local a = p.attributes[name]
t:check(a ~= nil, label .. ": attribute " .. name)
t:eq(a.type, want.type, label .. ": " .. name .. " type")
t:eq(a.components, want.components, label .. ": " .. name .. " components")
t:eq(a.count, c.vertices, label .. ": " .. name .. " count")
t:eq(Crc32.of(a.data), want.crc, label .. ": " .. name .. " crc")
n += 1
end
local m = 0
for _ in p.attributes do
m += 1
end
t:eq(m, n, label .. ": no other attributes")
if c.faces > 0 then
t:eq(p.mode, "triangles", label .. ": mode")
t:eq(Crc32.of(p.indices.data), if c.allTri then c.corners_crc else c.tri_crc, label .. ": indices crc")
t:eq(p.indices.count, c.tris * 3, label .. ": index count")
local fa = c.faceAttributes
local ex = p.extras or {}
if next(fa) ~= nil and not c.allTri then
t:eq(Crc32.of(ex.faceOfTriangle.data), c.fot_crc, label .. ": faceOfTriangle")
else
t:check(ex.faceOfTriangle == nil, label .. ": no faceOfTriangle")
end
for name, want in fa do
if want.list then
local fl = ex.faceLists[name]
t:eq(Crc32.of(fl.sizes.data), want.sizes_crc, label .. ": face list " .. name .. " sizes")
t:eq(Crc32.of(fl.items.data), want.items_crc, label .. ": face list " .. name .. " items")
else
local a = ex.faceAttributes[name]
t:eq(a.type, want.type, label .. ": face attribute " .. name .. " type")
t:eq(Crc32.of(a.data), want.crc, label .. ": face attribute " .. name)
end
end
else
t:eq(p.mode, "points", label .. ": a point cloud")
t:check(p.indices == nil, label .. ": no indices")
end
local meta = scene.meta.ply
t:eq(#meta.comments, #c.comments, label .. ": comment count")
for i, s in c.comments do
t:eq(meta.comments[i], s, label .. ": comment")
end
t:eq(#meta.objInfo, #c.objInfo, label .. ": obj_info count")
for i, s in c.objInfo do
t:eq(meta.objInfo[i], s, label .. ": obj_info")
end
t:eq(table.concat(meta.order, ","), table.concat(c.order, ","), label .. ": element order")
t:eq(#meta.elements, #c.elements, label .. ": raw elements")
for i, want in c.elements do
local el = meta.elements[i]
t:eq(el.name, want.name, label .. ": element name")
t:eq(el.count, want.count, label .. ": element count")
for k, wp in want.props do
local pr = el.properties[k]
t:eq(pr.name, wp.name, label .. ": element property")
if wp.list then
t:eq(Crc32.of(pr.sizes), wp.sizes_crc, label .. ": " .. el.name .. "." .. pr.name .. " sizes")
t:eq(Crc32.of(pr.values), wp.values_crc, label .. ": " .. el.name .. "." .. pr.name .. " items")
else
t:eq(Crc32.of(pr.values), wp.crc, label .. ": " .. el.name .. "." .. pr.name)
end
end
end
end
-- 2. every fixture against plyfile; 3. round trips of every fixture in every encoding
for _, c in Fx.cases do
local label = c.name
local scene, err = decode(c.data)
t:check(scene, label .. ": " .. tostring(err))
t:eq(scene.meta.source.format, "ply", label .. ": meta.source.format")
t:eq(scene.meta.source.encoding, c.encoding, label .. ": encoding")
t:eq(scene.meta.source.vertices, c.vertices, label .. ": vertices")
t:eq(scene.meta.source.faces, c.faces, label .. ": faces")
verify(scene, c, label)
t:eq(Ply.sniff(Bytes.reader(buffer.fromstring(c.data))), 1, label .. ": sniff")
local big = buffer.create(#c.data + 9)
buffer.writestring(big, 4, c.data)
local s2 = Ply.decode(Bytes.reader(big, 4, #c.data))
t:check(s2 and Crc32.of(s2.meshes[1].primitives[1].attributes.POSITION.data) == c.attrs.POSITION.crc, label .. ": decode from a sub-range")
-- polygons kept
local poly = decode(c.data, { triangulate = false })
local pp = poly.meshes[1].primitives[1]
if c.faces > 0 and not c.allTri then
t:eq(pp.mode, "polygons", label .. ": polygons mode")
t:eq(Crc32.of(pp.indices.data), c.corners_crc, label .. ": polygon corners")
t:eq(Crc32.of(pp.faces.data), c.sizes_crc, label .. ": polygon sizes")
end
for _, enc in ENCODINGS do
local out, eerr = Ply.encode(scene, { format = enc })
t:check(out, label .. " -> " .. enc .. ": " .. tostring(eerr))
local back, berr = decode(out)
t:check(back, label .. " -> " .. enc .. ": decode: " .. tostring(berr))
t:eq(back.meta.source.encoding, enc, label .. " -> " .. enc .. ": encoding")
local cc = table.clone(c)
if c.faces > 0 and not c.allTri then
-- written as triangles: the face data goes through faceOfTriangle, one row per triangle
cc.faces, cc.allTri, cc.corners_crc = c.tris, true, c.tri_crc
cc.faceAttributes = {}
local bp = back.meshes[1].primitives[1]
local fa = bp.extras and bp.extras.faceAttributes
for name in c.faceAttributes do
if not c.faceAttributes[name].list then
t:check(fa and fa[name] and fa[name].count == c.tris, label .. ": face attribute per triangle")
end
end
end
verify(back, cc, label .. " -> " .. enc)
-- polygons in, polygons out
local pout = Ply.encode(poly, { format = enc }) :: buffer
local pback = decode(pout, { triangulate = false })
verify(decode(pout), c, label .. " -> " .. enc .. " (polygons)")
local bp = pback.meshes[1].primitives[1]
t:eq(bp.mode, pp.mode, label .. ": polygons round trip mode")
if pp.indices then
t:check(buffer.tostring(bp.indices.data) == buffer.tostring(pp.indices.data), label .. ": polygons round trip indices")
end
if pp.faces then
t:check(buffer.tostring(bp.faces.data) == buffer.tostring(pp.faces.data), label .. ": polygons round trip sizes")
end
-- binary output of a binary input with the same byte order is the same file, header included
if enc == c.encoding and enc ~= "ascii" and string.sub(label, 1, 6) ~= "assimp" then
t:check(buffer.tostring(pout) == c.data, label .. ": byte-exact re-encode")
end
end
end
t:note("%d files match plyfile and round-trip in 3 encodings", #Fx.cases)
for _, v in Fx.ours do
t:check(v.ok, "plyfile / assimp read our " .. v.name .. ": " .. v.detail)
end
t:note("%d encodings read back by plyfile and assimp", #Fx.ours)
-- the encoder scenes: decode(encode()) against the properties computed by the generator
local function build(spec: any): Types.Scene
local scene = Types.Scene.new()
for i, m in spec.meshes do
local prims = {}
for _, p in m.prims do
local attrs = {}
for name, a in p.attrs do
attrs[name] = Types.Scene.accessor(buffer.fromstring(a[3]), a[1], a[2], p.count)
end
local prim: any = { attributes = attrs, mode = p.mode }
if p.indices then
prim.indices = Types.Scene.accessor(buffer.fromstring(p.indices), "u32", 1, #p.indices // 4)
end
if p.faces then
prim.faces = Types.Scene.accessor(buffer.fromstring(p.faces), "u32", 1, #p.faces // 4)
end
table.insert(prims, prim)
end
scene.meshes[i] = { primitives = prims }
end
for i, n in spec.nodes do
scene.nodes[i] = { mesh = n.mesh, children = n.children or {}, translation = n.translation, rotation = n.rotation, scale = n.scale, matrix = n.matrix }
end
scene.roots = spec.roots
return scene
end
local ATTR_OF: { [string]: { string | number } } = {
x = { "POSITION", 0 },
y = { "POSITION", 1 },
z = { "POSITION", 2 },
nx = { "NORMAL", 0 },
ny = { "NORMAL", 1 },
nz = { "NORMAL", 2 },
red = { "COLOR_0", 0 },
green = { "COLOR_0", 1 },
blue = { "COLOR_0", 2 },
alpha = { "COLOR_0", 3 },
s = { "TEXCOORD_0", 0 },
t = { "TEXCOORD_0", 1 },
}
local READ: { [string]: (buffer, number) -> number } = { ["<f4"] = buffer.readf32, u1 = buffer.readu8, ["<u2"] = buffer.readu16 }
local SIZE: { [string]: number } = { ["<f4"] = 4, u1 = 1, ["<u2"] = 2 }
for _, spec in Scenes do
local scene = build(spec)
for _, enc in ENCODINGS do
local label = spec.name .. "/" .. enc
local out, err = Ply.encode(scene, { format = enc })
t:check(out, label .. ": " .. tostring(err))
local back = decode(out, { triangulate = false })
local p = back.meshes[1].primitives[1]
for _, prop in spec.props do
local where = ATTR_OF[prop.name]
local a = if where then p.attributes[where[1]] else p.attributes["_" .. prop.name]
t:check(a ~= nil, label .. ": property " .. prop.name)
local comp = if where then where[2] :: number else 0
local rd, sz = READ[prop.dtype], SIZE[prop.dtype]
local vals = buffer.fromstring(prop.values)
local n = buffer.len(vals) // sz
t:eq(a.count, n, label .. ": " .. prop.name .. " count")
local csz = Types.COMPONENT_SIZE[a.type]
for i = 0, n - 1 do
local got = rd(a.data, (i * a.components + comp) * csz)
local want = rd(vals, i * sz)
if prop.tol then
t:check(math.abs(got - want) <= prop.tol, label .. ": " .. prop.name .. " value")
else
t:eq(got, want, label .. ": " .. prop.name .. " value")
end
end
end
if spec.faces then
local sizes = buffer.fromstring(spec.faceSizes)
local corners = buffer.fromstring(spec.faceCorners)
t:check(buffer.tostring(p.indices.data) == buffer.tostring(corners), label .. ": corners")
if p.mode == "polygons" then
t:check(buffer.tostring(p.faces.data) == buffer.tostring(sizes), label .. ": face sizes")
else
t:eq(p.mode, "triangles", label .. ": mode")
t:eq(p.indices.count, buffer.len(sizes) // 4 * 3, label .. ": all triangles")
end
else
t:eq(p.mode, "points", label .. ": points")
end
-- identity scenes: every attribute comes back as it was (COLOR_0 of the merged scene filled with white)
if not spec.transformed and #spec.meshes == 1 then
for name, a in scene.meshes[1].primitives[1].attributes do
t:check(buffer.tostring(p.attributes[name].data) == buffer.tostring(a.data), label .. ": " .. name .. " round trip")
t:eq(p.attributes[name].type, a.type, label .. ": " .. name .. " type")
end
end
end
end
-- options and meta: comments, extra elements written back, faceAttributes of a triangulated mesh
do
local scene = build(Scenes[1])
scene.meta.ply = { comments = { "first" }, objInfo = { "info line" } }
local out = Ply.encode(scene, { format = "ascii", comments = { "second" } }) :: buffer
local s = buffer.tostring(out)
t:check(string.find(s, "comment first\ncomment second\nobj_info info line\n", 1, true) ~= nil, "comments and obj_info")
local back = decode(out)
t:eq(back.meta.ply.comments[2], "second", "comment option")
local _, e = Ply.encode(scene, { format = "binary" } :: any)
t:check(e and e.code == Err.ARG, "bad format option: " .. tostring(e))
-- the default is binary little endian
t:check(string.find(buffer.tostring(Ply.encode(scene) :: buffer), "format binary_little_endian 1.0", 1, true) ~= nil, "default encoding")
-- a scene without nodes uses its meshes
local bare = Types.Scene.new()
bare.meshes[1] = scene.meshes[1]
t:eq(decode(Ply.encode(bare) :: buffer).meta.source.vertices, 20, "a scene without nodes")
end
-- 4. error codes
do
local function code(s: string, opts: any?): string?
local _, e = decode(s, opts)
return e and e.code
end
local H = "ply\nformat ascii 1.0\nelement vertex 3\nproperty float x\nproperty float y\nproperty float z\nelement face 1\nproperty list uchar int vertex_indices\nend_header\n"
t:check(decode(H .. "0 0 0\n1 0 0\n0 1 0\n3 0 1 2\n"), "a minimal ascii file")
t:eq(code("plx\n"), Err.CORRUPT, "bad signature")
t:eq(code("ply\nformat ascii 2.0\nend_header\n"), Err.UNSUPPORTED, "version 2")
t:eq(code("ply\nformat text 1.0\nend_header\n"), Err.UNSUPPORTED, "unknown format")
t:eq(code("ply\nformat ascii 1.0\nelement vertex 1\n"), Err.TRUNCATED, "no end_header")
t:eq(code("ply\nformat ascii 1.0\nproperty float x\nend_header\n"), Err.CORRUPT, "property before element")
t:eq(code("ply\nformat ascii 1.0\nelement vertex 1\nproperty float x\nproperty float x\nend_header\n0 0\n"), Err.CORRUPT, "duplicate property")
t:eq(code("ply\nformat ascii 1.0\nelement vertex 1\nproperty quad x\nend_header\n"), Err.CORRUPT, "unknown type")
t:eq(code("ply\nformat ascii 1.0\nelement vertex 1\nproperty list uchar float x\nend_header\n1 0\n"), Err.UNSUPPORTED, "list in the vertex element")
t:eq(code("ply\nformat ascii 1.0\nbanana\nend_header\n"), Err.CORRUPT, "unknown header line")
t:eq(code("ply\nformat ascii 1.0\nelement face 0\nend_header\n"), Err.CORRUPT, "no vertex element")
t:eq(code(H .. "0 0 0\n1 0 0\n0 1 0\n3 0 1 3\n"), Err.CORRUPT, "ascii index out of range")
t:eq(code(H .. "0 0 0\n1 0 0\n0 1 0\n3 0 1 -1\n"), Err.CORRUPT, "negative index")
t:eq(code(H .. "0 0 0\n1 0 0\n0 1 0\n3 0 1\n"), Err.TRUNCATED, "ascii cut")
t:eq(code(H .. "0 0 0\n1 zz 0\n0 1 0\n3 0 1 2\n"), Err.CORRUPT, "bad number")
t:eq(code(H .. "0 0 0\n1 0 0\n0 1 0\n300 0 1 2\n"), Err.CORRUPT, "uchar count over 255")
t:eq(code(H .. "0 0 0\n1 0 0\n0 1 0\n3 0 1 2.5\n"), Err.CORRUPT, "fractional index")
t:eq(code(H .. "0 0 0\n1 0 0\n0 1 0\n3 0 1 2\n", { maxVertices = 2 }), Err.LIMIT, "maxVertices")
t:eq(code(H .. "0 0 0\n1 0 0\n0 1 0\n3 0 1 2\n", { maxFaces = 0 }), Err.LIMIT, "maxFaces")
t:eq(code("ply\nformat ascii 1.0\nelement vertex 1000000\nproperty float x\nend_header\n1\n"), Err.TRUNCATED, "ascii count over the data")
local B = "ply\nformat binary_little_endian 1.0\nelement vertex 3\nproperty float x\nproperty float y\nproperty float z\nelement face 1\nproperty list uchar int vertex_indices\nend_header\n"
local verts = string.rep("\0", 36)
t:check(decode(B .. verts .. "\3\0\0\0\0\1\0\0\0\2\0\0\0"), "a minimal binary file")
t:eq(code(B .. verts .. "\3\0\0\0\0\1\0\0\0\3\0\0\0"), Err.CORRUPT, "binary index out of range")
t:eq(code(B .. verts .. "\3\0\0\0\0\1\0\0\0\2\0\0"), Err.TRUNCATED, "binary list cut")
t:eq(code(B .. string.sub(verts, 1, 30)), Err.TRUNCATED, "binary rows cut")
t:eq(code("ply\nformat binary_big_endian 1.0\nelement vertex 4000000000\nproperty float x\nend_header\n", { maxVertices = 2 ^ 40, maxFaces = 2 ^ 40 }), Err.TRUNCATED, "huge count")
local _, a1 = Ply.encode({} :: any)
t:check(a1 and a1.code == Err.ARG, "encode a non-scene: " .. tostring(a1))
local noPos = Types.Scene.fromPrimitive({ attributes = {}, mode = "points" })
local _, a2 = Ply.encode(noPos)
t:check(a2 and a2.code == Err.ARG, "no POSITION: " .. tostring(a2))
end
-- 5. fuzz
do
local samples = {}
for _, c in Fx.cases do
if #c.data < 30000 then
table.insert(samples, c.data)
end
end
t:fuzz("decode", function(b: buffer)
return Ply.decode(Bytes.reader(b))
end, samples, { mutations = 30 })
t:fuzz("decode polygons + re-encode", function(b: buffer)
local s = Ply.decode(Bytes.reader(b), { triangulate = false })
if s then
return Ply.encode(s, { format = "ascii" })
end
return nil
end, samples, { mutations = 6, garbage = 20 })
end
-- throughput: a 500 x 500 grid (250k vertices, 498k triangles), binary little endian
do
local W = 500
local pos = buffer.create(W * W * 12)
for i = 0, W * W - 1 do
buffer.writef32(pos, i * 12, i % W)
buffer.writef32(pos, i * 12 + 4, i // W)
buffer.writef32(pos, i * 12 + 8, (i * 7) % 13)
end
local nt = (W - 1) * (W - 1) * 2
local idx = buffer.create(nt * 12)
local k = 0
for y = 0, W - 2 do
for x = 0, W - 2 do
local a = y * W + x
for _, v in { a, a + 1, a + W + 1, a, a + W + 1, a + W } do
buffer.writeu32(idx, k * 4, v)
k += 1
end
end
end
local scene = Types.Scene.fromPrimitive({ attributes = { POSITION = Types.Scene.accessor(pos, "f32", 3, W * W) }, indices = Types.Scene.accessor(idx, "u32", 1, nt * 3), mode = "triangles" })
local t0 = os.clock()
local data = Ply.encode(scene) :: buffer
local te = os.clock() - t0
t0 = os.clock()
local back = Ply.decode(Bytes.reader(data))
local dt = os.clock() - t0
t:check(back and back.meshes[1].primitives[1].indices.count == nt * 3, "bench decode")
t:check(buffer.tostring(back.meshes[1].primitives[1].indices.data) == buffer.tostring(idx), "bench round trip")
t:note("binary LE decode: %d vertices + %d triangles (%.1f MB) in %.3f s, %.0f MB/s (encode %.2f s)", W * W, nt, buffer.len(data) / 1e6, dt, buffer.len(data) / 1e6 / math.max(dt, 1e-6), te)
end
t:done()
+342
View File
@@ -0,0 +1,342 @@
-- model/stl tests: files made by trimesh, assimp and by hand (binary starting with "solid", VisCAM / Magics colours,
-- raw attribute words, odd ASCII, several solids, quads, no endsolid, trailing bytes) against trimesh's raw reader
-- (CRC-32 of the f32 vertices / normals, area, bounds), our encoder's output read back by trimesh and assimp (verdicts
-- from the fixture step), round trips of every encoding and option, the contract, error codes, the fuzz no-throw pass
-- and a binary decode throughput note. Fixtures: tools/fixtures/stl.py.
local T = require("@tests/T")
local Stl = require("@formats/model/stl")
local Bytes = require("@formats/core/Bytes")
local Crc32 = require("@formats/core/Crc32")
local Err = require("@formats/core/Err")
local Types = require("@formats/Types")
local Fx = require("@tests/gen/stl")
local Scenes = require("@tests/gen/stl_scenes")
local t = T.suite("stl")
local function decode(data: any, opts: any?): (any, any)
local b = if type(data) == "string" then buffer.fromstring(data) else data
return Stl.decode(Bytes.reader(b), opts)
end
-- every primitive's accessor `name` concatenated (nil when a primitive lacks it)
local function concat(scene: any, name: string): buffer?
local parts = {}
for _, p in scene.meshes[1].primitives do
local a = p.attributes[name]
if not a then
return nil
end
table.insert(parts, buffer.tostring(a.data))
end
return buffer.fromstring(table.concat(parts))
end
-- 1. the contract
t:eq(Stl.name, "stl", "name")
t:eq(Stl.category, "model", "category")
t:check(table.find(Stl.extensions, "stl") ~= nil, "extensions")
t:check(Stl.caps.decode and Stl.caps.encode, "caps")
-- 2. every fixture against the reference
for _, c in Fx.cases do
local label = c.name
local scene, err = decode(c.data)
t:check(scene, label .. ": " .. tostring(err))
t:check(scene.kind == "scene" and #scene.meshes == 1 and #scene.nodes == 1 and scene.roots[1] == 1, label .. ": a one-node scene")
t:eq(scene.meta.up, "z", label .. ": up")
t:eq(scene.meta.source.format, "stl", label .. ": meta.source.format")
t:eq(scene.meta.source.binary, c.binary, label .. ": binary")
t:eq(scene.meta.source.facets, c.facets, label .. ": facet count")
local pos = concat(scene, "POSITION") :: buffer
t:eq(buffer.len(pos), c.facets * 36, label .. ": POSITION size")
t:eq(Crc32.of(pos), c.pos_crc, label .. ": POSITION crc")
for _, p in scene.meshes[1].primitives do
t:check(p.mode == "triangles" and p.indices == nil and p.attributes.POSITION.type == "f32" and p.attributes.POSITION.components == 3, label .. ": a triangle soup")
end
if c.nrm_crc then
t:eq(Crc32.of(concat(scene, "NORMAL") :: buffer), c.nrm_crc, label .. ": NORMAL crc")
end
if c.area then
local area = 0
local lo, hi = { math.huge, math.huge, math.huge }, { -math.huge, -math.huge, -math.huge }
for f = 0, c.facets - 1 do
local v = {}
for k = 0, 8 do
v[k + 1] = buffer.readf32(pos, f * 36 + k * 4)
end
for k = 0, 2 do
for a = 1, 3 do
lo[a] = math.min(lo[a], v[k * 3 + a])
hi[a] = math.max(hi[a], v[k * 3 + a])
end
end
local ux, uy, uz = v[4] - v[1], v[5] - v[2], v[6] - v[3]
local wx, wy, wz = v[7] - v[1], v[8] - v[2], v[9] - v[3]
local cx, cy, cz = uy * wz - uz * wy, uz * wx - ux * wz, ux * wy - uy * wx
area += math.sqrt(cx * cx + cy * cy + cz * cz) / 2
end
t:check(math.abs(area - c.area) <= 1e-6 * math.max(1, c.area), string.format("%s: area %.9g, want %.9g", label, area, c.area))
if c.facets > 0 then
-- trimesh keeps ASCII coordinates as doubles: compare with them rounded to f32
local function f32(x: number): number
local sb = buffer.create(4)
buffer.writef32(sb, 0, x)
return buffer.readf32(sb, 0)
end
for a = 1, 3 do
t:check(lo[a] == f32(c.bounds[a]) and hi[a] == f32(c.bounds[a + 3]), label .. ": bounds")
end
end
end
local p1 = scene.meshes[1].primitives[1]
if c.col_crc then
t:eq(scene.meta.source.colors, c.colors, label .. ": colour convention")
t:check(p1.attributes.COLOR_0 and p1.attributes.COLOR_0.type == "unorm8" and p1.attributes.COLOR_0.components == 4, label .. ": COLOR_0 unorm8 x4")
t:eq(Crc32.of(p1.attributes.COLOR_0.data), c.col_crc, label .. ": COLOR_0 crc")
else
t:check(p1.attributes.COLOR_0 == nil, label .. ": no colours")
end
if c.defaultColor then
local d = scene.meta.source.defaultColor
t:check(d and d[1] == c.defaultColor[1] and d[2] == c.defaultColor[2] and d[3] == c.defaultColor[3] and d[4] == c.defaultColor[4], label .. ": magics default colour")
t:check(scene.meta.source.material and scene.meta.source.material.specular[1] == 4, label .. ": magics material")
end
if c.attr_crc then
local fa = p1.extras and p1.extras.faceAttributes and p1.extras.faceAttributes.attribute
t:check(fa and fa.type == "u16" and fa.count == c.facets, label .. ": raw attribute words")
t:eq(Crc32.of(fa.data), c.attr_crc, label .. ": attribute words crc")
end
if c.solids then
local prims = scene.meshes[1].primitives
t:eq(#prims, #c.solids, label .. ": one primitive per solid")
for i, name in c.solids do
t:eq(prims[i].extras.solid, name, label .. ": solid name")
t:eq(prims[i].attributes.POSITION.count, c.solidFacets[i] * 3, label .. ": solid facets")
end
end
-- inside a bigger buffer (the Reader's range)
local big = buffer.create(#c.data + 11)
buffer.writestring(big, 5, c.data)
local s2 = Stl.decode(Bytes.reader(big, 5, #c.data))
t:check(s2 and Crc32.of(concat(s2, "POSITION") :: buffer) == c.pos_crc, label .. ": decode from a sub-range")
if label ~= "bin-trailing.stl" then -- no magic, and the size does not match: not recognisable
t:check(Stl.sniff(Bytes.reader(buffer.fromstring(c.data))) >= 0.5, label .. ": sniff")
end
-- re-encode (binary with the file's normals, and ASCII): the same triangles and normals
for _, ascii in { false, true } do
local opts: any = { ascii = ascii, normals = "attribute", colors = if c.col_crc then c.colors else nil }
if c.defaultColor then
opts.defaultColor = c.defaultColor
end
local out, eerr = Stl.encode(scene, opts)
t:check(out, label .. ": encode: " .. tostring(eerr))
local back = decode(out)
t:check(back, label .. ": decode our output")
t:check(buffer.tostring(concat(back, "POSITION") :: buffer) == buffer.tostring(pos), label .. ": re-encoded POSITION (ascii " .. tostring(ascii) .. ")")
t:check(buffer.tostring(concat(back, "NORMAL") :: buffer) == buffer.tostring(concat(scene, "NORMAL") :: buffer), label .. ": re-encoded NORMAL")
if c.col_crc and not ascii then
t:eq(Crc32.of(back.meshes[1].primitives[1].attributes.COLOR_0.data), c.col_crc, label .. ": re-encoded colours")
end
if c.attr_crc and not ascii then
t:eq(Crc32.of(back.meshes[1].primitives[1].extras.faceAttributes.attribute.data), c.attr_crc, label .. ": re-encoded attribute words")
end
if c.solids and ascii then
t:eq(back.meshes[1].primitives[1].extras.solid, c.solids[1], label .. ": solid name round trip")
end
end
end
t:note("%d files match trimesh / the generator", #Fx.cases)
-- 3. the reference tools read our output
for _, v in Fx.ours do
t:check(v.ok, "trimesh / assimp read our " .. v.name .. ": " .. v.detail)
end
t:note("%d encodings read back by trimesh and assimp", #Fx.ours)
-- round trips of the encoder scenes: world-space soup as the generator computed it, colour words, idempotence
local function acc(s: string, ty: string, comps: number, count: number): Types.Accessor
return Types.Scene.accessor(buffer.fromstring(s), ty, comps, count)
end
local function build(spec: any): Types.Scene
local scene = Types.Scene.new()
for i, m in spec.meshes do
local prims = {}
for _, p in m.prims do
local prim: any = { attributes = { POSITION = acc(p.pos, p.posType or "f32", 3, p.count) }, mode = p.mode }
if p.indices then
prim.indices = acc(p.indices, "u32", 1, #p.indices // 4)
end
if p.faces then
prim.faces = acc(p.faces, "u32", 1, #p.faces // 4)
end
if p.color then
prim.attributes.COLOR_0 = acc(p.color, "unorm8", 4, p.count)
end
table.insert(prims, prim)
end
scene.meshes[i] = { name = m.name, primitives = prims }
end
for i, n in spec.nodes do
scene.nodes[i] = { name = n.name, mesh = n.mesh, children = n.children or {}, translation = n.translation, rotation = n.rotation, scale = n.scale, matrix = n.matrix }
end
scene.roots = spec.roots
return scene
end
local OPTS: { [string]: any } = { binary = {}, ascii = { ascii = true }, viscam = { colors = "viscam" }, magics = { colors = "magics" } }
for _, spec in Scenes do
local scene = build(spec)
local want = buffer.fromstring(spec.expect)
local nf = buffer.len(want) // 36
for _, e in spec.encodings do
local label = spec.name .. "/" .. e
local out, err = Stl.encode(scene, OPTS[e])
t:check(out, label .. ": encode: " .. tostring(err))
local back, berr = decode(out)
t:check(back, label .. ": decode: " .. tostring(berr))
local got = concat(back, "POSITION") :: buffer
t:eq(buffer.len(got), nf * 36, label .. ": facets")
local worst = 0
for i = 0, nf * 9 - 1 do
worst = math.max(worst, math.abs(buffer.readf32(got, i * 4) - buffer.readf32(want, i * 4)))
end
t:check(if spec.exact then worst == 0 else worst < 1e-4, string.format("%s: positions off by %g", label, worst))
-- facet normals: unit length, right-hand rule
local nrm = concat(back, "NORMAL") :: buffer
for f = 0, nf - 1 do
local o = f * 36
local n = { buffer.readf32(nrm, o), buffer.readf32(nrm, o + 4), buffer.readf32(nrm, o + 8) }
local len = math.sqrt(n[1] ^ 2 + n[2] ^ 2 + n[3] ^ 2)
t:check(math.abs(len - 1) < 1e-5, label .. ": unit normal")
local p = {}
for k = 0, 8 do
p[k + 1] = buffer.readf32(got, o + k * 4)
end
local cx = (p[5] - p[2]) * (p[9] - p[3]) - (p[6] - p[3]) * (p[8] - p[2])
local cy = (p[6] - p[3]) * (p[7] - p[1]) - (p[4] - p[1]) * (p[9] - p[3])
local cz = (p[4] - p[1]) * (p[8] - p[2]) - (p[5] - p[2]) * (p[7] - p[1])
t:check(cx * n[1] + cy * n[2] + cz * n[3] > 0, label .. ": normal follows the winding")
end
if e == "viscam" or e == "magics" then
local words = if e == "viscam" then spec.viscamWords else spec.magicsWords
for f = 0, nf - 1 do
t:eq(buffer.readu16(out :: buffer, 84 + f * 50 + 48), words[f + 1], label .. ": colour word")
end
t:eq(back.meta.source.colors, e, label .. ": detected convention")
-- the colours are on 5-bit steps: decode(encode()) gives the first vertex colour of each facet back
local col = back.meshes[1].primitives[1].attributes.COLOR_0.data
local src = scene.meshes[1].primitives[1]
local idx = src.indices :: Types.Accessor
for f = 0, nf - 1 do
local a = buffer.readu32(idx.data, f * 12)
t:eq(buffer.readu32(col, f * 12), buffer.readu32(src.attributes.COLOR_0.data, a * 4), label .. ": facet colour")
end
end
-- idempotent: encoding the decoded soup again gives the same file
local again = Stl.encode(back, { ascii = OPTS[e].ascii, colors = OPTS[e].colors, normals = "attribute" }) :: buffer
t:check(buffer.tostring(again) == buffer.tostring(out :: buffer), label .. ": re-encode is identical")
end
end
-- options: header, name, computed vs attribute normals
do
local scene = build(Scenes[1])
local out = Stl.encode(scene, { header = "my header", ascii = false }) :: buffer
t:eq(buffer.readstring(out, 0, 9), "my header", "header option")
t:eq(decode(out).meta.source.header, "my header", "meta.source.header")
local a = buffer.tostring(Stl.encode(scene, { ascii = true, name = "part 7" }) :: buffer)
t:check(string.sub(a, 1, 12) == "solid part 7" and string.find(a, "endsolid part 7", 1, true) ~= nil, "name option")
local m = Stl.encode(scene, { colors = "magics", defaultColor = { 1, 2, 3, 4 } }) :: buffer
local d = decode(m).meta.source.defaultColor
t:check(d[1] == 1 and d[2] == 2 and d[3] == 3 and d[4] == 4, "defaultColor option")
-- points / lines only: an empty STL
local pts = Types.Scene.fromPrimitive({ attributes = { POSITION = Types.Scene.accessor(nil, "f32", 3, 4) }, mode = "points" })
local e0 = Stl.encode(pts) :: buffer
t:eq(buffer.len(e0), 84, "points only: no facets")
-- a scene without nodes uses its meshes
local bare = Types.Scene.new()
bare.meshes[1] = scene.meshes[1]
t:eq(buffer.len(Stl.encode(bare) :: buffer), 84 + 50 * 60, "a scene without nodes")
end
-- 4. error codes
do
local cube = Fx.cases[1].data
local _, e1 = decode(string.sub(cube, 1, 84 + 50 * 3 + 7))
t:check(e1 and e1.code == Err.TRUNCATED, "cut binary: " .. tostring(e1))
local _, e2 = decode("solid x\nfacet normal 1 2 zz\n")
t:check(e2 and e2.code == Err.CORRUPT, "bad number: " .. tostring(e2))
local _, e3 = decode("solid x\nfacet normal 1 2 3\nouter loop\nvertex 1 2 3\n")
t:check(e3 and e3.code == Err.TRUNCATED, "cut ascii: " .. tostring(e3))
local _, e4 = decode("solid x\nfacet normal 0 0 1\nouter loop\nvertex 1 2 3\nvertex 1 2 3\nendloop\nendfacet\nendsolid\n")
t:check(e4 and e4.code == Err.CORRUPT, "two-vertex facet: " .. tostring(e4))
local _, e5 = decode("hello")
t:check(e5 and e5.code == Err.TRUNCATED, "tiny junk: " .. tostring(e5))
local _, e6 = decode(cube, { maxFaces = 10 })
t:check(e6 and e6.code == Err.LIMIT, "maxFaces: " .. tostring(e6))
local _, e7 = decode(cube, { colors = "rainbow" })
t:check(e7 and e7.code == Err.ARG, "bad colors option: " .. tostring(e7))
local _, e8 = decode("solid x\nbanana\n")
t:check(e8 and e8.code == Err.CORRUPT, "bad keyword: " .. tostring(e8))
local hdr = buffer.create(84)
buffer.writeu32(hdr, 80, 1000000)
local _, e9 = Stl.decode(Bytes.reader(hdr))
t:check(e9 and e9.code == Err.TRUNCATED, "huge count: " .. tostring(e9))
local _, a1 = Stl.encode({} :: any)
t:check(a1 and a1.code == Err.ARG, "encode a non-scene: " .. tostring(a1))
local scene = build(Scenes[1])
local _, a2 = Stl.encode(scene, { colors = "rgb" } :: any)
t:check(a2 and a2.code == Err.ARG, "bad colors: " .. tostring(a2))
local bad = Types.Scene.fromPrimitive({ attributes = { POSITION = Types.Scene.accessor(nil, "f32", 3, 3) }, indices = Types.Scene.accessor(nil, "u32", 1, 3), mode = "triangles" })
buffer.writeu32((bad.meshes[1].primitives[1].indices :: Types.Accessor).data, 4, 7)
local _, a3 = Stl.encode(bad)
t:check(a3 and a3.code == Err.ARG, "index out of range: " .. tostring(a3))
local nan = Types.Scene.fromPrimitive({ attributes = { POSITION = Types.Scene.accessor(nil, "f32", 3, 3) }, mode = "triangles" })
buffer.writef32(nan.meshes[1].primitives[1].attributes.POSITION.data, 0, 0 / 0)
local _, a4 = Stl.encode(nan, { ascii = true })
t:check(a4 and a4.code == Err.ARG, "NaN in ASCII: " .. tostring(a4))
t:check(Stl.encode(nan) ~= nil, "NaN in binary is fine")
local cyc = build(Scenes[3])
cyc.nodes[2].children = { 1 }
local _, a5 = Stl.encode(cyc)
t:check(a5 and a5.code == Err.ARG, "cyclic nodes: " .. tostring(a5))
t:eq(Stl.sniff(Bytes.reader(buffer.fromstring("ply\nformat ascii 1.0\n"))), 0, "sniff a PLY")
end
-- 5. fuzz
do
local samples = {}
for i, c in Fx.cases do
if #c.data < 20000 or i % 3 == 0 then
table.insert(samples, c.data)
end
end
t:fuzz("decode", function(b: buffer)
return Stl.decode(Bytes.reader(b))
end, samples, { mutations = 12 })
t:fuzz("decode re-encode", function(b: buffer)
local s = Stl.decode(Bytes.reader(b))
if s then
return Stl.encode(s, { ascii = true })
end
return nil
end, samples, { mutations = 4, garbage = 20 })
end
-- throughput: a synthetic binary STL of 200k facets
do
local n = 200000
local b = buffer.create(84 + 50 * n)
buffer.writeu32(b, 80, n)
for i = 0, n - 1 do
for k = 0, 11 do
buffer.writef32(b, 84 + i * 50 + k * 4, (i * 12 + k) % 1000 * 0.25)
end
end
local t0 = os.clock()
local s = Stl.decode(Bytes.reader(b))
local dt = os.clock() - t0
t:check(s and s.meshes[1].primitives[1].attributes.POSITION.count == n * 3, "bench decode")
t:note("binary decode: %d facets (%.1f MB) in %.3f s, %.0f MB/s", n, buffer.len(b) / 1e6, dt, buffer.len(b) / 1e6 / math.max(dt, 1e-6))
end
t:done()