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
Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
1 parent
0276eda0e1
commit
c2bfa471a8
18 files changed
+5408
No files matched your search
@@ -0,0 +1,556 @@
|
||||
--!strict
|
||||
-- codecs/MeshFlatten: a Scene to one world-space mesh, for the writers of mesh-only formats (STL, PLY, OFF). Walks
|
||||
-- scene.roots recursively (TRS or column-major `matrix` per node; a scene without nodes uses its meshes as they are),
|
||||
-- applies the transforms to POSITION (and the inverse transpose to NORMAL), reverses the winding under mirroring
|
||||
-- transforms, reads every accessor type to numbers and concatenates all primitives (triangles with or without indices,
|
||||
-- polygons, strips, fans, points; lines are skipped). Shared here because a format cannot require another one
|
||||
-- (ops/MeshOps.merge is the editing-side equivalent).
|
||||
-- Never throws: bad input returns nil, message.
|
||||
local Types = require("@formats/Types")
|
||||
|
||||
local Flatten = {}
|
||||
|
||||
local readf32, readf64 = buffer.readf32, buffer.readf64
|
||||
local readu8, readu16, readu32 = buffer.readu8, buffer.readu16, buffer.readu32
|
||||
local readi8, readi16, readi32 = buffer.readi8, buffer.readi16, buffer.readi32
|
||||
|
||||
local SIZE = Types.COMPONENT_SIZE
|
||||
-- normalized integer types: their scale (raw / scale = the normalized value)
|
||||
local NORM: { [string]: number } = { unorm8 = 255, unorm16 = 65535, snorm8 = 127, snorm16 = 32767 }
|
||||
|
||||
export type Attr = {
|
||||
type: string, -- the accessor type shared by every part ("f32" when the parts disagree)
|
||||
components: number,
|
||||
raw: boolean, -- values are raw integers of a normalized type (unorm8: 0..255), else plain numbers
|
||||
values: { number }, -- count * components
|
||||
}
|
||||
export type PartInfo = {
|
||||
prim: Types.Primitive,
|
||||
mesh: Types.Mesh?,
|
||||
node: Types.Node?,
|
||||
firstVertex: number, -- 0-based offset of the part's vertices in the merged mesh
|
||||
vertexCount: number,
|
||||
firstFace: number, -- 0-based offset of the part's faces
|
||||
faceCount: number,
|
||||
identity: boolean, -- no transform was applied
|
||||
}
|
||||
export type Merged = {
|
||||
count: number, -- vertices
|
||||
attrs: { [string]: Attr }, -- POSITION and NORMAL in world space (f32 values), the others as read
|
||||
sizes: { number }?, -- vertices per face (nil: no part has faces, a point cloud)
|
||||
corners: { number }, -- 0-based vertex indices, face after face
|
||||
parts: { PartInfo },
|
||||
}
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ accessors
|
||||
-- numbers(acc, raw) -> the accessor's count * components values (normalized types divided out unless raw), or nil, msg
|
||||
function Flatten.numbers(acc: any, raw: boolean?): ({ number }?, string?)
|
||||
if type(acc) ~= "table" or type(acc.data) ~= "buffer" then
|
||||
return nil, "accessor without a data buffer"
|
||||
end
|
||||
local t, comps, count = acc.type, acc.components, acc.count
|
||||
local size = SIZE[t]
|
||||
if size == nil then
|
||||
return nil, "unknown accessor type " .. tostring(t)
|
||||
end
|
||||
if type(comps) ~= "number" or type(count) ~= "number" or comps < 1 or comps > 16 or count < 0 or comps % 1 ~= 0 or count % 1 ~= 0 then
|
||||
return nil, "bad accessor components / count"
|
||||
end
|
||||
local n = count * comps
|
||||
local d: buffer = acc.data
|
||||
if buffer.len(d) < n * size then
|
||||
return nil, "accessor data shorter than count * components"
|
||||
end
|
||||
local out = table.create(n)
|
||||
if t == "f32" then
|
||||
for i = 0, n - 1 do
|
||||
out[i + 1] = readf32(d, i * 4)
|
||||
end
|
||||
elseif t == "f64" then
|
||||
for i = 0, n - 1 do
|
||||
out[i + 1] = readf64(d, i * 8)
|
||||
end
|
||||
elseif t == "u8" or t == "unorm8" then
|
||||
for i = 0, n - 1 do
|
||||
out[i + 1] = readu8(d, i)
|
||||
end
|
||||
elseif t == "u16" or t == "unorm16" then
|
||||
for i = 0, n - 1 do
|
||||
out[i + 1] = readu16(d, i * 2)
|
||||
end
|
||||
elseif t == "u32" then
|
||||
for i = 0, n - 1 do
|
||||
out[i + 1] = readu32(d, i * 4)
|
||||
end
|
||||
elseif t == "i8" or t == "snorm8" then
|
||||
for i = 0, n - 1 do
|
||||
out[i + 1] = readi8(d, i)
|
||||
end
|
||||
elseif t == "i16" or t == "snorm16" then
|
||||
for i = 0, n - 1 do
|
||||
out[i + 1] = readi16(d, i * 2)
|
||||
end
|
||||
else -- i32
|
||||
for i = 0, n - 1 do
|
||||
out[i + 1] = readi32(d, i * 4)
|
||||
end
|
||||
end
|
||||
local scale = NORM[t]
|
||||
if scale and not raw then
|
||||
local signed = t == "snorm8" or t == "snorm16"
|
||||
for i = 1, n do
|
||||
local v = out[i] / scale
|
||||
out[i] = if signed and v < -1 then -1 else v
|
||||
end
|
||||
end
|
||||
return out, nil
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ transforms
|
||||
local IDENTITY = { 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1 }
|
||||
|
||||
-- column-major 4x4 product a * b
|
||||
local function mul(a: { number }, b: { number }): { number }
|
||||
local m = table.create(16, 0)
|
||||
for c = 0, 3 do
|
||||
for r = 0, 3 do
|
||||
local s = 0
|
||||
for k = 0, 3 do
|
||||
s += a[k * 4 + r + 1] * b[c * 4 + k + 1]
|
||||
end
|
||||
m[c * 4 + r + 1] = s
|
||||
end
|
||||
end
|
||||
return m
|
||||
end
|
||||
|
||||
local function numList(v: any, n: number): boolean
|
||||
if type(v) ~= "table" then
|
||||
return false
|
||||
end
|
||||
for i = 1, n do
|
||||
if type(v[i]) ~= "number" then
|
||||
return false
|
||||
end
|
||||
end
|
||||
return true
|
||||
end
|
||||
|
||||
-- a node's local matrix (nil: none), or nil, message
|
||||
local function localMatrix(node: any): ({ number }?, string?)
|
||||
if node.matrix ~= nil then
|
||||
if not numList(node.matrix, 16) then
|
||||
return nil, "node matrix is not 16 numbers"
|
||||
end
|
||||
local m = table.create(16)
|
||||
for i = 1, 16 do
|
||||
m[i] = node.matrix[i]
|
||||
end
|
||||
return m, nil
|
||||
end
|
||||
local t, q, s = node.translation, node.rotation, node.scale
|
||||
if t == nil and q == nil and s == nil then
|
||||
return nil, nil
|
||||
end
|
||||
if (t ~= nil and not numList(t, 3)) or (q ~= nil and not numList(q, 4)) or (s ~= nil and not numList(s, 3)) then
|
||||
return nil, "bad node translation / rotation / scale"
|
||||
end
|
||||
local x, y, z, w = 0, 0, 0, 1
|
||||
if q then
|
||||
x, y, z, w = q[1], q[2], q[3], q[4]
|
||||
end
|
||||
local sx, sy, sz = 1, 1, 1
|
||||
if s then
|
||||
sx, sy, sz = s[1], s[2], s[3]
|
||||
end
|
||||
local tx, ty, tz = 0, 0, 0
|
||||
if t then
|
||||
tx, ty, tz = t[1], t[2], t[3]
|
||||
end
|
||||
return {
|
||||
(1 - 2 * (y * y + z * z)) * sx,
|
||||
(2 * (x * y + z * w)) * sx,
|
||||
(2 * (x * z - y * w)) * sx,
|
||||
0,
|
||||
(2 * (x * y - z * w)) * sy,
|
||||
(1 - 2 * (x * x + z * z)) * sy,
|
||||
(2 * (y * z + x * w)) * sy,
|
||||
0,
|
||||
(2 * (x * z + y * w)) * sz,
|
||||
(2 * (y * z - x * w)) * sz,
|
||||
(1 - 2 * (x * x + y * y)) * sz,
|
||||
0,
|
||||
tx,
|
||||
ty,
|
||||
tz,
|
||||
1,
|
||||
},
|
||||
nil
|
||||
end
|
||||
|
||||
local function isIdentity(m: { number }): boolean
|
||||
for i = 1, 16 do
|
||||
if m[i] ~= IDENTITY[i] then
|
||||
return false
|
||||
end
|
||||
end
|
||||
return true
|
||||
end
|
||||
|
||||
type Instance = { prim: Types.Primitive, mesh: Types.Mesh?, node: Types.Node?, matrix: { number }? }
|
||||
|
||||
-- the primitive instances of a scene in traversal order, or nil, message
|
||||
local function instances(scene: any): ({ Instance }?, string?)
|
||||
local out: { Instance } = {}
|
||||
local nodes, meshes = scene.nodes, scene.meshes
|
||||
if type(nodes) ~= "table" or type(meshes) ~= "table" then
|
||||
return nil, "scene without nodes / meshes tables"
|
||||
end
|
||||
local function addMesh(mi: any, node: Types.Node?, m: { number }?): string?
|
||||
local mesh = meshes[mi]
|
||||
if type(mesh) ~= "table" or type(mesh.primitives) ~= "table" then
|
||||
return "node refers to a missing mesh " .. tostring(mi)
|
||||
end
|
||||
for _, prim in mesh.primitives do
|
||||
if type(prim) ~= "table" or type(prim.attributes) ~= "table" then
|
||||
return "bad primitive"
|
||||
end
|
||||
table.insert(out, { prim = prim, mesh = mesh, node = node, matrix = m })
|
||||
end
|
||||
return nil
|
||||
end
|
||||
local visiting: { [number]: boolean } = {}
|
||||
local function visit(ni: any, parent: { number }?, depth: number): string?
|
||||
local node = nodes[ni]
|
||||
if type(node) ~= "table" then
|
||||
return "missing node " .. tostring(ni)
|
||||
end
|
||||
if depth > 256 or visiting[ni] then
|
||||
return "node hierarchy is cyclic or too deep"
|
||||
end
|
||||
visiting[ni] = true
|
||||
local m, merr = localMatrix(node)
|
||||
if merr then
|
||||
return merr
|
||||
end
|
||||
local world = if m and parent then mul(parent, m) elseif m then m else parent
|
||||
if node.mesh ~= nil then
|
||||
local e = addMesh(node.mesh, node, world)
|
||||
if e then
|
||||
return e
|
||||
end
|
||||
end
|
||||
if type(node.children) == "table" then
|
||||
for _, c in node.children do
|
||||
local e = visit(c, world, depth + 1)
|
||||
if e then
|
||||
return e
|
||||
end
|
||||
end
|
||||
end
|
||||
visiting[ni] = nil
|
||||
return nil
|
||||
end
|
||||
local roots = scene.roots
|
||||
if type(roots) == "table" and #roots > 0 then
|
||||
for _, ri in roots do
|
||||
local e = visit(ri, nil, 0)
|
||||
if e then
|
||||
return nil, e
|
||||
end
|
||||
end
|
||||
elseif #nodes > 0 then
|
||||
local isChild: { [number]: boolean } = {}
|
||||
for _, n in nodes do
|
||||
if type(n) == "table" and type(n.children) == "table" then
|
||||
for _, c in n.children do
|
||||
isChild[c] = true
|
||||
end
|
||||
end
|
||||
end
|
||||
for i = 1, #nodes do
|
||||
if not isChild[i] then
|
||||
local e = visit(i, nil, 0)
|
||||
if e then
|
||||
return nil, e
|
||||
end
|
||||
end
|
||||
end
|
||||
else
|
||||
for i = 1, #meshes do
|
||||
local e = addMesh(i, nil, nil)
|
||||
if e then
|
||||
return nil, e
|
||||
end
|
||||
end
|
||||
end
|
||||
return out, nil
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ faces
|
||||
-- the faces of a primitive: sizes (nil = all triangles), corners (0-based), or "points" / "skip", or nil, message
|
||||
local function faces(prim: any, nv: number): (any, any, string?)
|
||||
local mode = prim.mode or "triangles"
|
||||
if mode == "points" then
|
||||
return "points", nil, nil
|
||||
elseif mode == "lines" or mode == "line_strip" or mode == "line_loop" then
|
||||
return "skip", nil, nil
|
||||
end
|
||||
local idx: { number }
|
||||
if prim.indices ~= nil then
|
||||
local v, err = Flatten.numbers(prim.indices, true)
|
||||
if not v then
|
||||
return nil, nil, "indices: " .. tostring(err)
|
||||
end
|
||||
idx = v
|
||||
else
|
||||
idx = table.create(nv)
|
||||
for i = 1, nv do
|
||||
idx[i] = i - 1
|
||||
end
|
||||
end
|
||||
for i = 1, #idx do
|
||||
local v = idx[i]
|
||||
if v < 0 or v >= nv or v % 1 ~= 0 then
|
||||
return nil, nil, string.format("index %s out of range (%d vertices)", tostring(v), nv)
|
||||
end
|
||||
end
|
||||
if mode == "triangles" then
|
||||
local n = #idx - #idx % 3
|
||||
if n ~= #idx then
|
||||
local c = table.create(n)
|
||||
table.move(idx, 1, n, 1, c)
|
||||
idx = c
|
||||
end
|
||||
return false, idx, nil
|
||||
elseif mode == "polygons" then
|
||||
if prim.faces == nil then
|
||||
return nil, nil, "polygons primitive without faces"
|
||||
end
|
||||
local sizes, err = Flatten.numbers(prim.faces, true)
|
||||
if not sizes then
|
||||
return nil, nil, "faces: " .. tostring(err)
|
||||
end
|
||||
local total = 0
|
||||
for i = 1, #sizes do
|
||||
local s = sizes[i]
|
||||
if s < 0 or s % 1 ~= 0 then
|
||||
return nil, nil, "bad face size"
|
||||
end
|
||||
total += s
|
||||
end
|
||||
if total ~= #idx then
|
||||
return nil, nil, "face sizes do not add up to the index count"
|
||||
end
|
||||
return sizes, idx, nil
|
||||
elseif mode == "triangle_strip" or mode == "triangle_fan" then
|
||||
local c = {}
|
||||
for i = 3, #idx do
|
||||
if mode == "triangle_fan" then
|
||||
table.insert(c, idx[1])
|
||||
table.insert(c, idx[i - 1])
|
||||
table.insert(c, idx[i])
|
||||
elseif i % 2 == 1 then
|
||||
table.insert(c, idx[i - 2])
|
||||
table.insert(c, idx[i - 1])
|
||||
table.insert(c, idx[i])
|
||||
else
|
||||
table.insert(c, idx[i - 1])
|
||||
table.insert(c, idx[i - 2])
|
||||
table.insert(c, idx[i])
|
||||
end
|
||||
end
|
||||
return false, c, nil
|
||||
end
|
||||
return nil, nil, "unknown primitive mode " .. tostring(mode)
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ merge
|
||||
-- the fill value of a missing attribute component: colours default to opaque white, everything else to 0
|
||||
local function fill(name: string, t: string, raw: boolean): number
|
||||
if string.sub(name, 1, 6) ~= "COLOR_" then
|
||||
return 0
|
||||
end
|
||||
return if raw and NORM[t] then NORM[t] else 1
|
||||
end
|
||||
|
||||
local function f32(v: number): number
|
||||
local b = buffer.create(4)
|
||||
buffer.writef32(b, 0, v)
|
||||
return buffer.readf32(b, 0)
|
||||
end
|
||||
|
||||
-- merge(scene, keep, opts) -> Merged | nil, message. keep(name) says which attributes to carry (POSITION always).
|
||||
-- opts.triangulate fan-triangulates polygons (faces of fewer than 3 vertices are dropped then).
|
||||
function Flatten.merge(scene: any, keep: (string) -> boolean, opts: { triangulate: boolean? }?): (Merged?, string?)
|
||||
if type(scene) ~= "table" then
|
||||
return nil, "not a scene"
|
||||
end
|
||||
local list, lerr = instances(scene)
|
||||
if not list then
|
||||
return nil, lerr
|
||||
end
|
||||
local triangulate = opts and opts.triangulate or false
|
||||
-- the attribute set: union over parts, a type every part agrees on (else f32), the widest component count
|
||||
local types: { [string]: string } = {}
|
||||
local comps: { [string]: number } = {}
|
||||
local used: { Instance } = {}
|
||||
for _, inst in list do
|
||||
local mode = inst.prim.mode or "triangles"
|
||||
if mode ~= "lines" and mode ~= "line_strip" and mode ~= "line_loop" then
|
||||
local pos = inst.prim.attributes.POSITION
|
||||
if type(pos) ~= "table" then
|
||||
return nil, "primitive without POSITION"
|
||||
end
|
||||
table.insert(used, inst)
|
||||
for name, acc in inst.prim.attributes do
|
||||
if type(name) == "string" and (name == "POSITION" or keep(name)) and type(acc) == "table" then
|
||||
local t = acc.type
|
||||
if types[name] == nil then
|
||||
types[name] = t
|
||||
elseif types[name] ~= t then
|
||||
types[name] = "f32"
|
||||
end
|
||||
comps[name] = math.max(comps[name] or 0, tonumber(acc.components) or 0)
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
if (comps.POSITION or 3) < 3 then
|
||||
return nil, "POSITION needs 3 components"
|
||||
end
|
||||
local attrs: { [string]: Attr } = {}
|
||||
for name, t in types do
|
||||
local raw = NORM[t] ~= nil
|
||||
if name == "POSITION" or name == "NORMAL" then
|
||||
raw = false
|
||||
end
|
||||
attrs[name] = { type = if name == "POSITION" or name == "NORMAL" then "f32" else t, components = if name == "POSITION" or name == "NORMAL" then 3 else comps[name], raw = raw, values = {} }
|
||||
end
|
||||
local merged: Merged = { count = 0, attrs = attrs, sizes = nil, corners = {}, parts = {} }
|
||||
local sizes: { number } = {}
|
||||
local anyFaces = false
|
||||
local corners = merged.corners
|
||||
for _, inst in used do
|
||||
local prim: any = inst.prim
|
||||
local posAcc = prim.attributes.POSITION
|
||||
local nv = tonumber(posAcc.count) or 0
|
||||
local m = inst.matrix
|
||||
local identity = m == nil or isIdentity(m :: { number })
|
||||
local info: PartInfo = { prim = prim, mesh = inst.mesh, node = inst.node, firstVertex = merged.count, vertexCount = nv, firstFace = #sizes, faceCount = 0, identity = identity }
|
||||
for name, a in attrs do
|
||||
local acc = prim.attributes[name]
|
||||
local dst = a.values
|
||||
local n0 = #dst
|
||||
local ac = a.components
|
||||
if acc == nil then
|
||||
local f = fill(name, a.type, a.raw)
|
||||
for i = 1, nv * ac do
|
||||
dst[n0 + i] = f
|
||||
end
|
||||
else
|
||||
if acc.count ~= nv then
|
||||
return nil, name .. " count differs from POSITION"
|
||||
end
|
||||
local vals, err = Flatten.numbers(acc, a.raw and acc.type == a.type)
|
||||
if not vals then
|
||||
return nil, name .. ": " .. tostring(err)
|
||||
end
|
||||
local sc = acc.components
|
||||
if a.raw and acc.type ~= a.type then
|
||||
return nil, name .. ": mixed accessor types"
|
||||
end
|
||||
local f = fill(name, a.type, a.raw)
|
||||
if name == "POSITION" and not identity then
|
||||
local mm = m :: { number }
|
||||
for i = 0, nv - 1 do
|
||||
local x, y, z = vals[i * sc + 1], vals[i * sc + 2], vals[i * sc + 3]
|
||||
dst[n0 + i * 3 + 1] = f32(mm[1] * x + mm[5] * y + mm[9] * z + mm[13])
|
||||
dst[n0 + i * 3 + 2] = f32(mm[2] * x + mm[6] * y + mm[10] * z + mm[14])
|
||||
dst[n0 + i * 3 + 3] = f32(mm[3] * x + mm[7] * y + mm[11] * z + mm[15])
|
||||
end
|
||||
elseif name == "NORMAL" and not identity and sc >= 3 then
|
||||
local mm = m :: { number }
|
||||
-- the cofactor matrix of the upper 3x3 = det * inverse transpose; the sign of det keeps the direction
|
||||
local a1, a2, a3, b1, b2, b3, c1, c2, c3 = mm[1], mm[2], mm[3], mm[5], mm[6], mm[7], mm[9], mm[10], mm[11]
|
||||
local n11, n12, n13 = b2 * c3 - b3 * c2, b3 * c1 - b1 * c3, b1 * c2 - b2 * c1
|
||||
local n21, n22, n23 = c2 * a3 - c3 * a2, c3 * a1 - c1 * a3, c1 * a2 - c2 * a1
|
||||
local n31, n32, n33 = a2 * b3 - a3 * b2, a3 * b1 - a1 * b3, a1 * b2 - a2 * b1
|
||||
local sgn = if a1 * n11 + a2 * n12 + a3 * n13 < 0 then -1 else 1
|
||||
for i = 0, nv - 1 do
|
||||
local x, y, z = vals[i * sc + 1], vals[i * sc + 2], vals[i * sc + 3]
|
||||
-- column j of the cofactor matrix multiplies component j: (inverse transpose) * n
|
||||
local nx = n11 * x + n21 * y + n31 * z
|
||||
local ny = n12 * x + n22 * y + n32 * z
|
||||
local nz = n13 * x + n23 * y + n33 * z
|
||||
local l = math.sqrt(nx * nx + ny * ny + nz * nz)
|
||||
if l > 0 then
|
||||
nx, ny, nz = sgn * nx / l, sgn * ny / l, sgn * nz / l
|
||||
end
|
||||
dst[n0 + i * 3 + 1] = f32(nx)
|
||||
dst[n0 + i * 3 + 2] = f32(ny)
|
||||
dst[n0 + i * 3 + 3] = f32(nz)
|
||||
end
|
||||
else
|
||||
for i = 0, nv - 1 do
|
||||
for c = 1, ac do
|
||||
dst[n0 + i * ac + c] = if c <= sc then vals[i * sc + c] else f
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
local fs, cs, ferr = faces(prim, nv)
|
||||
if ferr then
|
||||
return nil, ferr
|
||||
end
|
||||
local flip = false
|
||||
if not identity then
|
||||
local mm = m :: { number }
|
||||
local det = mm[1] * (mm[6] * mm[11] - mm[7] * mm[10]) - mm[5] * (mm[2] * mm[11] - mm[3] * mm[10]) + mm[9] * (mm[2] * mm[7] - mm[3] * mm[6])
|
||||
flip = det < 0
|
||||
end
|
||||
if fs ~= "points" and fs ~= "skip" then
|
||||
anyFaces = true
|
||||
local base = merged.count
|
||||
local cl: { number } = cs
|
||||
local p = 0
|
||||
local nf = if fs then #fs else #cl // 3
|
||||
for f = 1, nf do
|
||||
local s = if fs then fs[f] else 3
|
||||
if triangulate then
|
||||
for k = 2, s - 1 do
|
||||
table.insert(sizes, 3)
|
||||
local a, b, c = cl[p + 1], cl[p + k], cl[p + k + 1]
|
||||
if flip then
|
||||
b, c = c, b
|
||||
end
|
||||
table.insert(corners, base + a)
|
||||
table.insert(corners, base + b)
|
||||
table.insert(corners, base + c)
|
||||
end
|
||||
else
|
||||
table.insert(sizes, s)
|
||||
if flip then
|
||||
table.insert(corners, base + cl[p + 1])
|
||||
for k = s, 2, -1 do
|
||||
table.insert(corners, base + cl[p + k])
|
||||
end
|
||||
else
|
||||
for k = 1, s do
|
||||
table.insert(corners, base + cl[p + k])
|
||||
end
|
||||
end
|
||||
end
|
||||
p += s
|
||||
end
|
||||
end
|
||||
info.faceCount = #sizes - info.firstFace
|
||||
merged.count += nv
|
||||
table.insert(merged.parts, info)
|
||||
end
|
||||
merged.sizes = if anyFaces then sizes else nil
|
||||
return merged, nil
|
||||
end
|
||||
|
||||
return Flatten
|
||||
@@ -0,0 +1,480 @@
|
||||
--!strict
|
||||
-- model/off: OFF (Geomview Object File Format), text, read + write. Written from the Geomview OFF description
|
||||
-- (geomview.org/docs/html/OFF.html).
|
||||
-- Decode: the header keyword [ST][C][N]OFF (texture coordinates, vertex colours, normals; the counts may follow on the
|
||||
-- same line), `nv nf [ne]`, vertex lines `x y z [nx ny nz] [r g b [a]] [s t]`, face lines `n i1 .. in [colour]`;
|
||||
-- `#` comments and blank lines anywhere. Vertices: POSITION f32 x3, NORMAL f32 x3, TEXCOORD_0 f32 x2, COLOR_0: unorm8
|
||||
-- x4 when the colours are integers (0..255) and some value is above 1, else f32 x4 (alpha full when only RGB is given).
|
||||
-- Faces: triangles as u32 indices; n-gons fan-triangulated (opts.triangulate, default true: right for convex faces;
|
||||
-- faces of fewer than 3 vertices are dropped, prim.extras.faceOfTriangle maps triangles to file faces when there are
|
||||
-- face colours) or kept as mode "polygons" (prim.faces). Face colours (3 or 4 values after the indices; integers or
|
||||
-- floats as for vertices; faces without one get opaque white): prim.extras.faceColors, one per file face. A single
|
||||
-- value after the indices (a colormap index) is ignored (meta.source.colormap = true). No faces: mode "points".
|
||||
-- meta.source = { format, keyword, vertices, faces, edges }.
|
||||
-- Encode: every primitive in world space (node transforms applied) into one vertex list, NOFF / COFF / STOFF prefixes
|
||||
-- for NORMAL / COLOR_0 / TEXCOORD_0 (unorm8 colours as integers 0..255, other colour types as floats 0..1), n-gons
|
||||
-- natively, face colours from prim.extras.faceColors (a single primitive), point clouds with 0 faces; lines are
|
||||
-- skipped. Floats print as %.9g (f32-exact). Not supported: 4OFF / nOFF (homogeneous / n-dimensional) and binary OFF
|
||||
-- (UNSUPPORTED).
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ requires
|
||||
local Err = require("@formats/core/Err")
|
||||
local Bytes = require("@formats/core/Bytes")
|
||||
local Types = require("@formats/Types")
|
||||
local Flatten = require("@formats/codecs/MeshFlatten")
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ contract
|
||||
local Off = {
|
||||
name = "off",
|
||||
category = "model",
|
||||
extensions = { "off" },
|
||||
mime = { "model/off", "text/plain" },
|
||||
deps = { "core/Err", "core/Bytes", "Types", "codecs/MeshFlatten" },
|
||||
caps = { decode = true, encode = true, polygons = true, points = true, colors = true, binary = false },
|
||||
}
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ types
|
||||
export type DecodeOptions = {
|
||||
triangulate: boolean?, -- fan-triangulate n-gons (default true); false keeps them as mode "polygons"
|
||||
maxVertices: number?, -- default 2^24
|
||||
maxFaces: number?, -- default 2^25
|
||||
}
|
||||
export type EncodeOptions = {
|
||||
colors: boolean?, -- write COLOR_0 (COFF) and prim.extras.faceColors when present (default true)
|
||||
normals: boolean?, -- write NORMAL (NOFF) when present (default true)
|
||||
texcoords: boolean?, -- write TEXCOORD_0 (STOFF) when present (default true)
|
||||
comment: string?, -- a "# ..." line after the header keyword
|
||||
}
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ constants
|
||||
local writef32, writeu8, writeu32 = buffer.writef32, buffer.writeu8, buffer.writeu32
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ sniff
|
||||
function Off.sniff(r: Bytes.Reader): number
|
||||
local head = r:peek(512)
|
||||
for _ = 1, 16 do -- leading comment lines
|
||||
local rest = string.match(head, "^%s*#[^\n]*\n(.*)$")
|
||||
if not rest then
|
||||
break
|
||||
end
|
||||
head = rest
|
||||
end
|
||||
local kw = string.match(head, "^%s*(%w+)")
|
||||
if kw and string.match(kw, "^S?T?C?N?4?n?OFF$") then
|
||||
return 0.9
|
||||
end
|
||||
return 0
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ decode
|
||||
-- colours: a list of numbers + whether a token looked like a float; decide unorm8 or f32
|
||||
type ColorSet = { values: { number }, float: boolean, max: number }
|
||||
|
||||
local function colorType(c: ColorSet): string
|
||||
return if not c.float and c.max > 1 then "unorm8" else "f32"
|
||||
end
|
||||
|
||||
-- the colour accessor for count entries of 4 values (nan = absent: opaque white)
|
||||
local function colorAccessor(c: ColorSet, count: number): (Types.Accessor?, string?)
|
||||
local t = colorType(c)
|
||||
local buf = buffer.create(count * (if t == "unorm8" then 4 else 16))
|
||||
local vals = c.values
|
||||
for i = 0, count * 4 - 1 do
|
||||
local v = vals[i + 1]
|
||||
if t == "unorm8" then
|
||||
if v ~= v then
|
||||
v = 255
|
||||
elseif v < 0 or v > 255 or v % 1 ~= 0 then
|
||||
return nil, "colour value out of range"
|
||||
end
|
||||
writeu8(buf, i, v)
|
||||
else
|
||||
writef32(buf, i * 4, if v ~= v then 1 else v)
|
||||
end
|
||||
end
|
||||
return Types.Scene.accessor(buf, t, 4, count), nil
|
||||
end
|
||||
|
||||
local function addColor(c: ColorSet, toks: { string }, from: number, n: number)
|
||||
local vals = c.values
|
||||
for k = 0, 3 do
|
||||
if k < n then
|
||||
local s = toks[from + k]
|
||||
local v = tonumber(s) :: number
|
||||
table.insert(vals, v)
|
||||
if not c.float and string.find(s, "[%.eEnN]") then
|
||||
c.float = true
|
||||
end
|
||||
if v > c.max then
|
||||
c.max = v
|
||||
end
|
||||
else
|
||||
table.insert(vals, 0 / 0) -- absent: full (opaque white)
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
function Off.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Scene?, Err.Err?)
|
||||
local triangulate = true
|
||||
if opts and opts.triangulate == false then
|
||||
triangulate = false
|
||||
end
|
||||
local maxVertices = opts and opts.maxVertices or 2 ^ 24
|
||||
local maxFaces = opts and opts.maxFaces or 2 ^ 25
|
||||
local text = buffer.readstring(r.buf, r.base, r.limit - r.base)
|
||||
-- the next non-empty line's tokens (comments stripped)
|
||||
local at = 1
|
||||
local lineNo = 0
|
||||
local function line(): { string }?
|
||||
while at <= #text do
|
||||
local e = string.find(text, "\n", at, true) or (#text + 1)
|
||||
local s = string.sub(text, at, e - 1)
|
||||
at = e + 1
|
||||
lineNo += 1
|
||||
local hash = string.find(s, "#", 1, true)
|
||||
if hash then
|
||||
s = string.sub(s, 1, hash - 1)
|
||||
end
|
||||
local toks = {}
|
||||
for w in string.gmatch(s, "%S+") do
|
||||
table.insert(toks, w)
|
||||
end
|
||||
if #toks > 0 then
|
||||
return toks
|
||||
end
|
||||
end
|
||||
return nil
|
||||
end
|
||||
local head = line()
|
||||
if not head then
|
||||
return nil, Err.new(Err.TRUNCATED, "empty file")
|
||||
end
|
||||
local kw = head[1]
|
||||
local rest = kw
|
||||
local st, hasC, hasN = false, false, false
|
||||
if string.sub(rest, 1, 2) == "ST" then
|
||||
st, rest = true, string.sub(rest, 3)
|
||||
end
|
||||
if string.sub(rest, 1, 1) == "C" then
|
||||
hasC, rest = true, string.sub(rest, 2)
|
||||
end
|
||||
if string.sub(rest, 1, 1) == "N" then
|
||||
hasN, rest = true, string.sub(rest, 2)
|
||||
end
|
||||
if rest == "4OFF" or rest == "nOFF" or rest == "4nOFF" then
|
||||
return nil, Err.new(Err.UNSUPPORTED, kw .. " (homogeneous / n-dimensional vertices)")
|
||||
elseif rest ~= "OFF" then
|
||||
return nil, Err.new(Err.CORRUPT, "bad header keyword " .. string.sub(kw, 1, 20))
|
||||
end
|
||||
local counts: { string }
|
||||
if head[2] == "BINARY" then
|
||||
return nil, Err.new(Err.UNSUPPORTED, "binary OFF")
|
||||
elseif #head >= 3 then
|
||||
counts = { head[2], head[3], head[4] }
|
||||
else
|
||||
local c = line()
|
||||
if not c then
|
||||
return nil, Err.new(Err.TRUNCATED, "no counts line")
|
||||
end
|
||||
counts = c
|
||||
end
|
||||
local nv, nf, ne = tonumber(counts[1]), tonumber(counts[2]), tonumber(counts[3] or "0")
|
||||
if not nv or not nf or nv < 0 or nf < 0 or nv % 1 ~= 0 or nf % 1 ~= 0 then
|
||||
return nil, Err.new(Err.CORRUPT, "bad counts line")
|
||||
end
|
||||
if nv > maxVertices then
|
||||
return nil, Err.new(Err.LIMIT, string.format("%d vertices is over the %d vertex limit", nv, maxVertices))
|
||||
end
|
||||
if nf > maxFaces then
|
||||
return nil, Err.new(Err.LIMIT, string.format("%d faces is over the %d face limit", nf, maxFaces))
|
||||
end
|
||||
-- every vertex / face line takes at least 6 / 2 bytes
|
||||
if nv * 6 + nf * 2 > #text - at + 2 then
|
||||
return nil, Err.new(Err.TRUNCATED, "fewer lines than the counts need")
|
||||
end
|
||||
local fixed = 3 + (if hasN then 3 else 0) + (if st then 2 else 0)
|
||||
local pos = buffer.create(nv * 12)
|
||||
local nrm = if hasN then buffer.create(nv * 12) else nil
|
||||
local tex = if st then buffer.create(nv * 8) else nil
|
||||
local vcol: ColorSet = { values = {}, float = false, max = 0 }
|
||||
for i = 0, nv - 1 do
|
||||
local t = line()
|
||||
if not t then
|
||||
return nil, Err.new(Err.TRUNCATED, string.format("vertex %d missing", i))
|
||||
end
|
||||
local n = #t
|
||||
local nc = 0
|
||||
if hasC then
|
||||
nc = n - fixed
|
||||
if nc ~= 3 and nc ~= 4 then
|
||||
return nil, Err.new(Err.CORRUPT, string.format("vertex %d: expected %d values and an RGB / RGBA colour", i, fixed))
|
||||
end
|
||||
elseif n < fixed then
|
||||
return nil, Err.new(Err.CORRUPT, string.format("vertex %d: expected %d values", i, fixed))
|
||||
end
|
||||
for k = 1, fixed + nc do
|
||||
if tonumber(t[k]) == nil then
|
||||
return nil, Err.new(Err.CORRUPT, string.format("vertex %d: bad number", i))
|
||||
end
|
||||
end
|
||||
writef32(pos, i * 12, tonumber(t[1]) :: number)
|
||||
writef32(pos, i * 12 + 4, tonumber(t[2]) :: number)
|
||||
writef32(pos, i * 12 + 8, tonumber(t[3]) :: number)
|
||||
local k = 4
|
||||
if nrm then
|
||||
writef32(nrm, i * 12, tonumber(t[4]) :: number)
|
||||
writef32(nrm, i * 12 + 4, tonumber(t[5]) :: number)
|
||||
writef32(nrm, i * 12 + 8, tonumber(t[6]) :: number)
|
||||
k = 7
|
||||
end
|
||||
if hasC then
|
||||
addColor(vcol, t, k, nc)
|
||||
k += nc
|
||||
end
|
||||
if tex then
|
||||
writef32(tex, i * 8, tonumber(t[k]) :: number)
|
||||
writef32(tex, i * 8 + 4, tonumber(t[k + 1]) :: number)
|
||||
end
|
||||
end
|
||||
local sizes = buffer.create(nf * 4)
|
||||
local corners: { number } = {}
|
||||
local fcol: ColorSet = { values = {}, float = false, max = 0 }
|
||||
local anyFaceColor, colormap = false, false
|
||||
for f = 0, nf - 1 do
|
||||
local t = line()
|
||||
if not t then
|
||||
return nil, Err.new(Err.TRUNCATED, string.format("face %d missing", f))
|
||||
end
|
||||
local n = tonumber(t[1])
|
||||
if n == nil or n < 0 or n % 1 ~= 0 or #t < n + 1 then
|
||||
return nil, Err.new(Err.CORRUPT, string.format("face %d: bad vertex count", f))
|
||||
end
|
||||
writeu32(sizes, f * 4, n)
|
||||
for k = 2, n + 1 do
|
||||
local v = tonumber(t[k])
|
||||
if v == nil or v < 0 or v >= nv or v % 1 ~= 0 then
|
||||
return nil, Err.new(Err.CORRUPT, string.format("face %d: vertex index out of range", f))
|
||||
end
|
||||
table.insert(corners, v)
|
||||
end
|
||||
local nc = #t - n - 1
|
||||
if nc == 3 or nc == 4 then
|
||||
for k = n + 2, #t do
|
||||
if tonumber(t[k]) == nil then
|
||||
return nil, Err.new(Err.CORRUPT, string.format("face %d: bad colour", f))
|
||||
end
|
||||
end
|
||||
addColor(fcol, t, n + 2, nc)
|
||||
anyFaceColor = true
|
||||
else
|
||||
if nc == 1 then
|
||||
colormap = true
|
||||
end
|
||||
addColor(fcol, t, 1, 0)
|
||||
end
|
||||
end
|
||||
-- the primitive
|
||||
local attrs: { [string]: Types.Accessor } = { POSITION = Types.Scene.accessor(pos, "f32", 3, nv) }
|
||||
if nrm then
|
||||
attrs.NORMAL = Types.Scene.accessor(nrm, "f32", 3, nv)
|
||||
end
|
||||
if hasC then
|
||||
local acc, cerr = colorAccessor(vcol, nv)
|
||||
if not acc then
|
||||
return nil, Err.new(Err.CORRUPT, "vertex " .. tostring(cerr))
|
||||
end
|
||||
attrs.COLOR_0 = acc
|
||||
end
|
||||
if tex then
|
||||
attrs.TEXCOORD_0 = Types.Scene.accessor(tex, "f32", 2, nv)
|
||||
end
|
||||
local prim: Types.Primitive = { attributes = attrs, mode = "points" }
|
||||
local extras: { [string]: any } = {}
|
||||
if anyFaceColor then
|
||||
local acc, cerr = colorAccessor(fcol, nf)
|
||||
if not acc then
|
||||
return nil, Err.new(Err.CORRUPT, "face " .. tostring(cerr))
|
||||
end
|
||||
extras.faceColors = acc
|
||||
end
|
||||
if nf > 0 then
|
||||
local total = #corners
|
||||
local cbuf = buffer.create(total * 4)
|
||||
for i = 1, total do
|
||||
writeu32(cbuf, (i - 1) * 4, corners[i])
|
||||
end
|
||||
local allTri = total == nf * 3
|
||||
if allTri then
|
||||
for f = 0, nf - 1 do
|
||||
if buffer.readu32(sizes, f * 4) ~= 3 then
|
||||
allTri = false
|
||||
break
|
||||
end
|
||||
end
|
||||
end
|
||||
if allTri then
|
||||
prim.mode = "triangles"
|
||||
prim.indices = Types.Scene.accessor(cbuf, "u32", 1, total)
|
||||
elseif triangulate then
|
||||
local tris: { number } = {}
|
||||
local fot: { number } = {}
|
||||
local p = 0
|
||||
for f = 0, nf - 1 do
|
||||
local s = buffer.readu32(sizes, f * 4)
|
||||
for k = 1, s - 2 do
|
||||
table.insert(tris, corners[p + 1])
|
||||
table.insert(tris, corners[p + k + 1])
|
||||
table.insert(tris, corners[p + k + 2])
|
||||
table.insert(fot, f)
|
||||
end
|
||||
p += s
|
||||
end
|
||||
local ib = buffer.create(#tris * 4)
|
||||
for i, v in tris do
|
||||
writeu32(ib, (i - 1) * 4, v)
|
||||
end
|
||||
prim.mode = "triangles"
|
||||
prim.indices = Types.Scene.accessor(ib, "u32", 1, #tris)
|
||||
if anyFaceColor then
|
||||
local fb = buffer.create(#fot * 4)
|
||||
for i, v in fot do
|
||||
writeu32(fb, (i - 1) * 4, v)
|
||||
end
|
||||
extras.faceOfTriangle = Types.Scene.accessor(fb, "u32", 1, #fot)
|
||||
end
|
||||
else
|
||||
prim.mode = "polygons"
|
||||
prim.indices = Types.Scene.accessor(cbuf, "u32", 1, total)
|
||||
prim.faces = Types.Scene.accessor(sizes, "u32", 1, nf)
|
||||
end
|
||||
end
|
||||
if next(extras) then
|
||||
prim.extras = extras
|
||||
end
|
||||
local scene = Types.Scene.fromPrimitive(prim, nil)
|
||||
scene.meta.source = { format = "off", keyword = kw, vertices = nv, faces = nf, edges = ne or 0, colormap = colormap or nil }
|
||||
return scene, nil
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ encode
|
||||
local scratch = buffer.create(4)
|
||||
local function fnum(v: number): string?
|
||||
writef32(scratch, 0, v)
|
||||
v = buffer.readf32(scratch, 0)
|
||||
if v ~= v or v == math.huge or v == -math.huge then
|
||||
return nil
|
||||
end
|
||||
return string.format("%.9g", v)
|
||||
end
|
||||
|
||||
-- a colour attribute's 4 components of entry i (0-based) as text
|
||||
local function colorText(a: Flatten.Attr, vals: { number }, comps: number, i: number): string
|
||||
local out = table.create(4)
|
||||
for c = 1, 4 do
|
||||
local v = if c <= comps then vals[i * comps + c] else nil
|
||||
if a.raw and a.type == "unorm8" then
|
||||
out[c] = string.format("%d", if v == nil then 255 else math.clamp(v, 0, 255))
|
||||
else
|
||||
if v == nil then
|
||||
v = 1
|
||||
elseif a.raw then
|
||||
v = if a.type == "unorm16" then v / 65535 elseif a.type == "snorm8" then math.max(v / 127, -1) else math.max(v / 32767, -1)
|
||||
end
|
||||
out[c] = fnum(v :: number) or "0"
|
||||
end
|
||||
end
|
||||
return table.concat(out, " ")
|
||||
end
|
||||
|
||||
function Off.encode(scene: Types.Scene, opts: EncodeOptions?): (buffer?, Err.Err?)
|
||||
local o: EncodeOptions = opts or {}
|
||||
local wantC, wantN, wantT = o.colors ~= false, o.normals ~= false, o.texcoords ~= false
|
||||
local m, merr = Flatten.merge(scene, function(name: string): boolean
|
||||
return (name == "NORMAL" and wantN) or (name == "COLOR_0" and wantC) or (name == "TEXCOORD_0" and wantT)
|
||||
end, { triangulate = false })
|
||||
if not m then
|
||||
return nil, Err.new(Err.ARG, tostring(merr))
|
||||
end
|
||||
local A = m.attrs
|
||||
local P, N, C, T = A.POSITION, A.NORMAL, A.COLOR_0, A.TEXCOORD_0
|
||||
if T and T.raw then
|
||||
return nil, Err.new(Err.ARG, "TEXCOORD_0 of a normalized integer type")
|
||||
end
|
||||
local nv = m.count
|
||||
local sizes = m.sizes or {}
|
||||
local nf = #sizes
|
||||
local out = table.create(nv + nf + 3)
|
||||
table.insert(out, (if T then "ST" else "") .. (if C then "C" else "") .. (if N then "N" else "") .. "OFF")
|
||||
if o.comment then
|
||||
table.insert(out, "# " .. string.gsub(o.comment, "[\r\n]", " "))
|
||||
end
|
||||
table.insert(out, string.format("%d %d 0", nv, nf))
|
||||
local pv = P.values
|
||||
for i = 0, nv - 1 do
|
||||
local x, y, z = fnum(pv[i * 3 + 1]), fnum(pv[i * 3 + 2]), fnum(pv[i * 3 + 3])
|
||||
if not (x and y and z) then
|
||||
return nil, Err.new(Err.ARG, "OFF cannot hold a non-finite coordinate")
|
||||
end
|
||||
local s = x .. " " .. y .. " " .. z
|
||||
if N then
|
||||
local nvv = N.values
|
||||
s ..= " " .. (fnum(nvv[i * 3 + 1]) or "0") .. " " .. (fnum(nvv[i * 3 + 2]) or "0") .. " " .. (fnum(nvv[i * 3 + 3]) or "0")
|
||||
end
|
||||
if C then
|
||||
s ..= " " .. colorText(C, C.values, C.components, i)
|
||||
end
|
||||
if T then
|
||||
local tv, tc = T.values, T.components
|
||||
s ..= " " .. (fnum(tv[i * tc + 1]) or "0") .. " " .. (fnum(if tc >= 2 then tv[i * tc + 2] else 0) or "0")
|
||||
end
|
||||
table.insert(out, s)
|
||||
end
|
||||
-- face colours of a single primitive (per file face, or through faceOfTriangle)
|
||||
local fc: Flatten.Attr? = nil
|
||||
local fcMap: { number }? = nil
|
||||
if wantC and #m.parts == 1 and nf > 0 then
|
||||
local ex = m.parts[1].prim.extras
|
||||
local acc = type(ex) == "table" and ex.faceColors
|
||||
if acc then
|
||||
local raw = acc.type == "unorm8" or acc.type == "unorm16" or acc.type == "snorm8" or acc.type == "snorm16"
|
||||
local vals = Flatten.numbers(acc, raw)
|
||||
if vals then
|
||||
local a: Flatten.Attr = { type = acc.type, components = acc.components, raw = raw, values = vals }
|
||||
if acc.count == nf then
|
||||
fc = a
|
||||
elseif ex.faceOfTriangle then
|
||||
local fot = Flatten.numbers(ex.faceOfTriangle, true)
|
||||
if fot and #fot == nf then
|
||||
fc, fcMap = a, fot
|
||||
for _, f in fot do
|
||||
if f < 0 or f >= acc.count then
|
||||
fc = nil
|
||||
break
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
local corners = m.corners
|
||||
local p = 0
|
||||
for f = 1, nf do
|
||||
local s = sizes[f]
|
||||
local line = table.create(s + 2)
|
||||
line[1] = string.format("%d", s)
|
||||
for k = 1, s do
|
||||
line[k + 1] = string.format("%d", corners[p + k])
|
||||
end
|
||||
p += s
|
||||
if fc then
|
||||
local src = if fcMap then fcMap[f] else f - 1
|
||||
table.insert(line, colorText(fc, fc.values, fc.components, src))
|
||||
end
|
||||
table.insert(out, table.concat(line, " "))
|
||||
end
|
||||
table.insert(out, "")
|
||||
return buffer.fromstring(table.concat(out, "\n")), nil
|
||||
end
|
||||
|
||||
return Off
|
||||
@@ -0,0 +1,212 @@
|
||||
--!strict
|
||||
--!native
|
||||
--!optimize 2
|
||||
-- model/ply/Binary: PLY element data loops. Value read / write by type code (1 i8, 2 u8, 3 i16, 4 u16, 5 i32, 6 u32,
|
||||
-- 7 f32, 8 f64) in either byte order, the column copy of fixed-size rows (scalar properties only) and the row walk of
|
||||
-- rows with lists (a scan for the list totals, then the fill). The caller (init) sizes every destination from the
|
||||
-- header counts and the scan, and checks the rows fit in the data first, so every index here is in range; a bad list
|
||||
-- count or an out-of-range vertex index returns false / -1 with a message. Nothing here throws.
|
||||
local readu8, readi8, readu16, readi16, readu32, readi32 = buffer.readu8, buffer.readi8, buffer.readu16, buffer.readi16, buffer.readu32, buffer.readi32
|
||||
local readf32, readf64 = buffer.readf32, buffer.readf64
|
||||
local writeu8, writei8, writeu16, writei16, writeu32, writei32 = buffer.writeu8, buffer.writei8, buffer.writeu16, buffer.writei16, buffer.writeu32, buffer.writei32
|
||||
local writef32, writef64 = buffer.writef32, buffer.writef64
|
||||
local byteswap, band, rshift = bit32.byteswap, bit32.band, bit32.rshift
|
||||
|
||||
local Binary = {}
|
||||
|
||||
Binary.SIZE = { 1, 1, 2, 2, 4, 4, 4, 8 }
|
||||
local SIZE = Binary.SIZE
|
||||
local scratch = buffer.create(8)
|
||||
|
||||
local function swap16(v: number): number
|
||||
return rshift(v, 8) + band(v, 255) * 256
|
||||
end
|
||||
|
||||
-- rd(b, q, code, be) -> the value at q
|
||||
local function rd(b: buffer, q: number, code: number, be: boolean): number
|
||||
if not be then
|
||||
if code == 7 then
|
||||
return readf32(b, q)
|
||||
elseif code == 2 then
|
||||
return readu8(b, q)
|
||||
elseif code == 5 then
|
||||
return readi32(b, q)
|
||||
elseif code == 6 then
|
||||
return readu32(b, q)
|
||||
elseif code == 8 then
|
||||
return readf64(b, q)
|
||||
elseif code == 1 then
|
||||
return readi8(b, q)
|
||||
elseif code == 3 then
|
||||
return readi16(b, q)
|
||||
end
|
||||
return readu16(b, q)
|
||||
end
|
||||
if code <= 2 then
|
||||
return if code == 1 then readi8(b, q) else readu8(b, q)
|
||||
elseif code <= 4 then
|
||||
local v = swap16(readu16(b, q))
|
||||
return if code == 3 and v >= 32768 then v - 65536 else v
|
||||
elseif code <= 7 then
|
||||
local v = byteswap(readu32(b, q))
|
||||
if code == 6 then
|
||||
return v
|
||||
elseif code == 5 then
|
||||
return if v >= 2147483648 then v - 4294967296 else v
|
||||
end
|
||||
writeu32(scratch, 0, v)
|
||||
return readf32(scratch, 0)
|
||||
end
|
||||
writeu32(scratch, 0, byteswap(readu32(b, q + 4)))
|
||||
writeu32(scratch, 4, byteswap(readu32(b, q)))
|
||||
return readf64(scratch, 0)
|
||||
end
|
||||
Binary.rd = rd
|
||||
|
||||
-- wr(d, o, code, v): v as code, little endian
|
||||
local function wr(d: buffer, o: number, code: number, v: number)
|
||||
if code == 7 then
|
||||
writef32(d, o, v)
|
||||
elseif code == 6 then
|
||||
writeu32(d, o, v)
|
||||
elseif code == 5 then
|
||||
writei32(d, o, v)
|
||||
elseif code == 2 then
|
||||
writeu8(d, o, v)
|
||||
elseif code == 8 then
|
||||
writef64(d, o, v)
|
||||
elseif code == 1 then
|
||||
writei8(d, o, v)
|
||||
elseif code == 3 then
|
||||
writei16(d, o, v)
|
||||
else
|
||||
writeu16(d, o, v)
|
||||
end
|
||||
end
|
||||
Binary.wr = wr
|
||||
|
||||
-- put(d, o, code, v, be): v as code in either byte order (the writer)
|
||||
function Binary.put(d: buffer, o: number, code: number, v: number, be: boolean)
|
||||
if not be or code <= 2 then
|
||||
wr(d, o, code, v)
|
||||
return
|
||||
end
|
||||
wr(scratch, 0, code, v)
|
||||
if code <= 4 then
|
||||
writeu16(d, o, swap16(readu16(scratch, 0)))
|
||||
elseif code <= 7 then
|
||||
writeu32(d, o, byteswap(readu32(scratch, 0)))
|
||||
else
|
||||
writeu32(d, o, byteswap(readu32(scratch, 4)))
|
||||
writeu32(d, o + 4, byteswap(readu32(scratch, 0)))
|
||||
end
|
||||
end
|
||||
|
||||
-- fixed(b, p, n, rowSize, np, srcOff, code, be, dst, dOff, dStride, dCode): column copies of n fixed-size rows at p
|
||||
function Binary.fixed(b: buffer, p: number, n: number, rowSize: number, np: number, srcOff: { number }, code: { number }, be: boolean, dst: { buffer }, dOff: { number }, dStride: { number }, dCode: { number })
|
||||
for k = 1, np do
|
||||
local sc, dc, d = code[k], dCode[k], dst[k]
|
||||
local q0, o0, st = p + srcOff[k], dOff[k], dStride[k]
|
||||
if sc == dc and not be then
|
||||
local sz = SIZE[sc]
|
||||
if sz == 4 then
|
||||
for i = 0, n - 1 do
|
||||
writeu32(d, o0 + i * st, readu32(b, q0 + i * rowSize))
|
||||
end
|
||||
elseif sz == 1 then
|
||||
for i = 0, n - 1 do
|
||||
writeu8(d, o0 + i * st, readu8(b, q0 + i * rowSize))
|
||||
end
|
||||
elseif sz == 2 then
|
||||
for i = 0, n - 1 do
|
||||
writeu16(d, o0 + i * st, readu16(b, q0 + i * rowSize))
|
||||
end
|
||||
else
|
||||
for i = 0, n - 1 do
|
||||
writeu32(d, o0 + i * st, readu32(b, q0 + i * rowSize))
|
||||
writeu32(d, o0 + i * st + 4, readu32(b, q0 + i * rowSize + 4))
|
||||
end
|
||||
end
|
||||
else
|
||||
for i = 0, n - 1 do
|
||||
wr(d, o0 + i * st, dc, rd(b, q0 + i * rowSize, sc, be))
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
-- scan(b, p, limit, n, np, code, isList, countCode, be) -> the end offset and the item total of each list property,
|
||||
-- or -1, message (truncated rows, a negative / fractional count)
|
||||
function Binary.scan(b: buffer, p: number, limit: number, n: number, np: number, code: { number }, isList: { boolean }, countCode: { number }, be: boolean): (number, any)
|
||||
local totals = table.create(np, 0)
|
||||
local q = p
|
||||
for _ = 1, n do
|
||||
for k = 1, np do
|
||||
if isList[k] then
|
||||
local cc = countCode[k]
|
||||
local csz = SIZE[cc]
|
||||
if q + csz > limit then
|
||||
return -1, "list runs past the end"
|
||||
end
|
||||
local c = rd(b, q, cc, be)
|
||||
if c < 0 or c ~= c // 1 then
|
||||
return -1, "bad list count"
|
||||
end
|
||||
q += csz + c * SIZE[code[k]]
|
||||
if q > limit then
|
||||
return -1, "list runs past the end"
|
||||
end
|
||||
totals[k] += c
|
||||
else
|
||||
q += SIZE[code[k]]
|
||||
if q > limit then
|
||||
return -1, "row runs past the end"
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
return q, totals
|
||||
end
|
||||
|
||||
-- rows(b, p, n, np, code, isList, countCode, be, dst, dOff, dStride, dCode, sizes, bound) -> true | false, message.
|
||||
-- Scalars go to dst[k] at dOff + row * dStride as dCode; lists write their count to sizes[k] (u32 per row) and their
|
||||
-- items one after the other into dst[k] as dCode; bound[k] >= 0 checks items are integers in 0 .. bound - 1. The rows
|
||||
-- must have passed scan() with the same arguments.
|
||||
function Binary.rows(b: buffer, p: number, n: number, np: number, code: { number }, isList: { boolean }, countCode: { number }, be: boolean, dst: { buffer }, dOff: { number }, dStride: { number }, dCode: { number }, sizes: { buffer }, bound: { number }): (boolean, string?)
|
||||
local at = table.create(np, 0)
|
||||
local q = p
|
||||
for i = 0, n - 1 do
|
||||
for k = 1, np do
|
||||
local sc, dc, d = code[k], dCode[k], dst[k]
|
||||
if isList[k] then
|
||||
local cc = countCode[k]
|
||||
local c = rd(b, q, cc, be)
|
||||
q += SIZE[cc]
|
||||
writeu32(sizes[k], i * 4, c)
|
||||
local ia, ssz, dsz, bd = at[k], SIZE[sc], SIZE[dc], bound[k]
|
||||
if bd >= 0 then
|
||||
for j = 0, c - 1 do
|
||||
local v = rd(b, q, sc, be)
|
||||
q += ssz
|
||||
if v < 0 or v >= bd or v ~= v // 1 then
|
||||
return false, "vertex index out of range"
|
||||
end
|
||||
wr(d, (ia + j) * dsz, dc, v)
|
||||
end
|
||||
else
|
||||
for j = 0, c - 1 do
|
||||
wr(d, (ia + j) * dsz, dc, rd(b, q, sc, be))
|
||||
q += ssz
|
||||
end
|
||||
end
|
||||
at[k] = ia + c
|
||||
else
|
||||
wr(d, dOff[k] + i * dStride[k], dc, rd(b, q, sc, be))
|
||||
q += SIZE[sc]
|
||||
end
|
||||
end
|
||||
end
|
||||
return true, nil
|
||||
end
|
||||
|
||||
return Binary
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,77 @@
|
||||
--!strict
|
||||
--!native
|
||||
--!optimize 2
|
||||
-- model/stl/Decode: the binary STL facet loop (50 bytes per facet: normal, 3 vertices, u16 attribute) and the 5-5-5
|
||||
-- colour expansion of the VisCAM / SolidView and Materialise Magics conventions. The caller (init) has checked that
|
||||
-- the facets fit in the data and allocated the outputs, so every index here is in range; nothing here throws.
|
||||
local readu16, readu32, writeu8, writeu16, writeu32 = buffer.readu16, buffer.readu32, buffer.writeu8, buffer.writeu16, buffer.writeu32
|
||||
local band, bor, rshift = bit32.band, bit32.bor, bit32.rshift
|
||||
|
||||
local Decode = {}
|
||||
|
||||
-- binary(b, p, n, pos, nrm, attr) -> the OR of every attribute word. Copies the vertices (f32 bits as they are) into
|
||||
-- pos (n * 36 bytes), the facet normal three times into nrm (n * 36 bytes) and the attributes into attr (n * 2 bytes).
|
||||
function Decode.binary(b: buffer, p: number, n: number, pos: buffer, nrm: buffer, attr: buffer): number
|
||||
local any = 0
|
||||
for i = 0, n - 1 do
|
||||
local q = p + i * 50
|
||||
local o = i * 36
|
||||
local nx, ny, nz = readu32(b, q), readu32(b, q + 4), readu32(b, q + 8)
|
||||
writeu32(nrm, o, nx)
|
||||
writeu32(nrm, o + 4, ny)
|
||||
writeu32(nrm, o + 8, nz)
|
||||
writeu32(nrm, o + 12, nx)
|
||||
writeu32(nrm, o + 16, ny)
|
||||
writeu32(nrm, o + 20, nz)
|
||||
writeu32(nrm, o + 24, nx)
|
||||
writeu32(nrm, o + 28, ny)
|
||||
writeu32(nrm, o + 32, nz)
|
||||
writeu32(pos, o, readu32(b, q + 12))
|
||||
writeu32(pos, o + 4, readu32(b, q + 16))
|
||||
writeu32(pos, o + 8, readu32(b, q + 20))
|
||||
writeu32(pos, o + 12, readu32(b, q + 24))
|
||||
writeu32(pos, o + 16, readu32(b, q + 28))
|
||||
writeu32(pos, o + 20, readu32(b, q + 32))
|
||||
writeu32(pos, o + 24, readu32(b, q + 36))
|
||||
writeu32(pos, o + 28, readu32(b, q + 40))
|
||||
writeu32(pos, o + 32, readu32(b, q + 44))
|
||||
local a = readu16(b, q + 48)
|
||||
writeu16(attr, i * 2, a)
|
||||
any = bor(any, a)
|
||||
end
|
||||
return any
|
||||
end
|
||||
|
||||
-- 5-bit -> 8-bit, rounded
|
||||
local function x8(v: number): number
|
||||
return (v * 255 + 15) // 31
|
||||
end
|
||||
|
||||
-- colors(attr, n, magics, r, g, b, a, out): unorm8 RGBA per vertex (n * 12 bytes). VisCAM: bit 15 set = valid,
|
||||
-- red in bits 10..14, blue in 0..4 (invalid facets get r, g, b, a). Magics: bit 15 clear = the facet's own colour,
|
||||
-- red in bits 0..4, blue in 10..14 (set: the object colour r, g, b, a).
|
||||
function Decode.colors(attr: buffer, n: number, magics: boolean, dr: number, dg: number, db: number, da: number, out: buffer)
|
||||
for i = 0, n - 1 do
|
||||
local w = readu16(attr, i * 2)
|
||||
local r, g, bl, al = dr, dg, db, da
|
||||
local own = if magics then w < 0x8000 else w >= 0x8000
|
||||
if own then
|
||||
local lo, mid, hi = x8(band(w, 31)), x8(band(rshift(w, 5), 31)), x8(band(rshift(w, 10), 31))
|
||||
g, al = mid, 255
|
||||
if magics then
|
||||
r, bl = lo, hi
|
||||
else
|
||||
r, bl = hi, lo
|
||||
end
|
||||
end
|
||||
local o = i * 12
|
||||
for k = 0, 2 do
|
||||
writeu8(out, o + k * 4, r)
|
||||
writeu8(out, o + k * 4 + 1, g)
|
||||
writeu8(out, o + k * 4 + 2, bl)
|
||||
writeu8(out, o + k * 4 + 3, al)
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
return Decode
|
||||
@@ -0,0 +1,467 @@
|
||||
--!strict
|
||||
-- model/stl: STL (3D Systems stereolithography), ASCII and binary, read + write. Written from the format description
|
||||
-- (Wikipedia "STL (file format)" and the 3D Systems SLC spec).
|
||||
-- Decode: a triangle soup, 3 vertices per facet, no indices: POSITION f32 x3, NORMAL f32 x3 (the facet normal from the
|
||||
-- file on each of its vertices), COLOR_0 unorm8 x4 when the binary file uses a colour convention (VisCAM / SolidView:
|
||||
-- attribute bit 15 = colour valid, RGB 5-5-5 with red high; Materialise Magics: "COLOR=" rgba in the header is the
|
||||
-- object colour, bit 15 clear = the facet's own colour, red low). Other non-zero attribute words are kept per facet in
|
||||
-- prim.extras.faceAttributes.attribute (u16). Binary files may start with "solid": a file whose size is exactly
|
||||
-- 84 + 50 * count is binary. ASCII: keywords in any case, any whitespace, several solids (one primitive per solid in
|
||||
-- one mesh, prim.extras.solid = its name), facets with more than 3 vertices are fan-triangulated, a missing final
|
||||
-- endsolid is tolerated. meta.up = "z"; meta.source = { format, binary, header, colors, defaultColor, material,
|
||||
-- solids, facets }.
|
||||
-- Encode: every primitive of the scene in world space (node transforms applied; polygons / strips / fans
|
||||
-- fan-triangulated, points and lines skipped), binary (default) or ASCII (one solid per primitive, named after
|
||||
-- prim.extras.solid / the mesh / the node, made distinct), facet normals computed from the triangle
|
||||
-- (right-hand rule) unless opts.normals = "attribute", colours from COLOR_0 (the facet's first vertex) in either
|
||||
-- convention. Not supported: binary-only extensions other than the two colour conventions.
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ requires
|
||||
local Err = require("@formats/core/Err")
|
||||
local Bytes = require("@formats/core/Bytes")
|
||||
local Types = require("@formats/Types")
|
||||
local Decode = require("@formats/model/stl/Decode")
|
||||
local Flatten = require("@formats/codecs/MeshFlatten")
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ contract
|
||||
local Stl = {
|
||||
name = "stl",
|
||||
category = "model",
|
||||
extensions = { "stl" },
|
||||
mime = { "model/stl", "application/sla" },
|
||||
deps = { "core/Err", "core/Bytes", "Types", "codecs/MeshFlatten" },
|
||||
caps = { decode = true, encode = true, ascii = true, binary = true, colors = true, indexed = false },
|
||||
}
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ types
|
||||
export type DecodeOptions = {
|
||||
maxFaces: number?, -- refuse more facets (default 2^25)
|
||||
colors: ("auto" | "viscam" | "magics" | "none")?, -- binary colour convention (default "auto": "COLOR=" in the
|
||||
-- header = magics, else any attribute with bit 15 set = viscam, else none)
|
||||
}
|
||||
export type EncodeOptions = {
|
||||
ascii: boolean?, -- default false (binary)
|
||||
colors: ("viscam" | "magics")?, -- write COLOR_0 (the first vertex of each facet) in that convention (binary only)
|
||||
defaultColor: { number }?, -- magics: the object colour r, g, b, a 0..255 (default opaque white); facets of exactly
|
||||
-- that colour refer to it, the others carry their own (alpha 255)
|
||||
name: string?, -- the ASCII solid name (default: the mesh / node name, else "mesh")
|
||||
header: string?, -- the binary header text (at most 80 bytes; default "formats-luau STL")
|
||||
normals: ("compute" | "attribute")?, -- facet normals from the triangle (default) or the first vertex's NORMAL
|
||||
}
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ constants
|
||||
local readu8, readu32 = buffer.readu8, buffer.readu32
|
||||
local writef32, writeu16, writeu32 = buffer.writef32, buffer.writeu16, buffer.writeu32
|
||||
|
||||
local function lower5(s: string): boolean
|
||||
return string.lower(s) == "solid"
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ sniff
|
||||
function Stl.sniff(r: Bytes.Reader): number
|
||||
local size = r:remaining()
|
||||
if size >= 84 then
|
||||
local c = r:peek(4, 80)
|
||||
local n = string.byte(c, 1) + string.byte(c, 2) * 256 + string.byte(c, 3) * 65536 + string.byte(c, 4) * 16777216
|
||||
if 84 + 50 * n == size then
|
||||
return 0.9
|
||||
end
|
||||
end
|
||||
local head = r:peek(512)
|
||||
local s = string.match(head, "^%s*(%a+)")
|
||||
if s and lower5(s) then
|
||||
local l = string.lower(head)
|
||||
return if string.find(l, "facet", 1, true) or string.find(l, "endsolid", 1, true) then 0.9 else 0.5
|
||||
end
|
||||
return 0
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ decode
|
||||
local function soupPrim(n: number, pos: buffer, nrm: buffer): Types.Primitive
|
||||
return {
|
||||
attributes = {
|
||||
POSITION = Types.Scene.accessor(pos, "f32", 3, n * 3),
|
||||
NORMAL = Types.Scene.accessor(nrm, "f32", 3, n * 3),
|
||||
},
|
||||
mode = "triangles",
|
||||
}
|
||||
end
|
||||
|
||||
local function decodeBinary(r: Bytes.Reader, maxFaces: number, colors: string): (Types.Scene?, Err.Err?)
|
||||
local b, base, size = r.buf, r.base, r.limit - r.base
|
||||
local n = readu32(b, base + 80)
|
||||
if n > maxFaces then
|
||||
return nil, Err.new(Err.LIMIT, string.format("%d facets is over the %d facet limit", n, maxFaces), base + 80)
|
||||
end
|
||||
if 84 + 50 * n > size then
|
||||
return nil, Err.new(Err.TRUNCATED, string.format("%d facets need %d bytes, the file has %d", n, 84 + 50 * n, size), base + 80)
|
||||
end
|
||||
local pos, nrm, attr = buffer.create(n * 36), buffer.create(n * 36), buffer.create(n * 2)
|
||||
local any = Decode.binary(b, base + 84, n, pos, nrm, attr)
|
||||
local header = buffer.readstring(b, base, 80)
|
||||
local cut = string.find(header, "\0", 1, true) -- the text before the first NUL
|
||||
local text = if cut then string.sub(header, 1, cut - 1) else header
|
||||
local mode = colors
|
||||
local ci = string.find(header, "COLOR=", 1, true)
|
||||
if mode == "auto" then
|
||||
mode = if ci and ci + 9 <= 80 then "magics" elseif any >= 0x8000 then "viscam" else "none"
|
||||
end
|
||||
local prim = soupPrim(n, pos, nrm)
|
||||
local source: { [string]: any } = { format = "stl", binary = true, header = text, facets = n }
|
||||
if mode == "viscam" or mode == "magics" then
|
||||
local dc = { 255, 255, 255, 255 }
|
||||
if mode == "magics" and ci and ci + 9 <= 80 then
|
||||
local o = base + ci + 5 -- the 4 bytes after "COLOR=" (ci is 1-based)
|
||||
dc = { readu8(b, o), readu8(b, o + 1), readu8(b, o + 2), readu8(b, o + 3) }
|
||||
source.defaultColor = dc
|
||||
local mi = string.find(header, "MATERIAL=", 1, true)
|
||||
if mi and mi + 8 + 12 <= 80 then
|
||||
local m = base + mi + 8
|
||||
local function rgba(k: number): { number }
|
||||
return { readu8(b, m + k), readu8(b, m + k + 1), readu8(b, m + k + 2), readu8(b, m + k + 3) }
|
||||
end
|
||||
source.material = { diffuse = rgba(0), specular = rgba(4), ambient = rgba(8) }
|
||||
end
|
||||
end
|
||||
local col = buffer.create(n * 12)
|
||||
Decode.colors(attr, n, mode == "magics", dc[1], dc[2], dc[3], dc[4], col)
|
||||
prim.attributes.COLOR_0 = Types.Scene.accessor(col, "unorm8", 4, n * 3)
|
||||
source.colors = mode
|
||||
elseif any ~= 0 then
|
||||
prim.extras = { faceAttributes = { attribute = Types.Scene.accessor(attr, "u16", 1, n) } }
|
||||
end
|
||||
local scene = Types.Scene.fromPrimitive(prim, nil)
|
||||
scene.meta.up = "z"
|
||||
scene.meta.source = source :: any
|
||||
return scene, nil
|
||||
end
|
||||
|
||||
local function decodeAscii(r: Bytes.Reader, maxFaces: number): (Types.Scene?, Err.Err?)
|
||||
local text = buffer.readstring(r.buf, r.base, r.limit - r.base)
|
||||
local at = 1
|
||||
local function tok(): string?
|
||||
local s, e = string.find(text, "%S+", at)
|
||||
if not s then
|
||||
return nil
|
||||
end
|
||||
at = (e :: number) + 1
|
||||
return string.sub(text, s, e)
|
||||
end
|
||||
local function restOfLine(): string
|
||||
local e = string.find(text, "\n", at, true) or (#text + 1)
|
||||
local line = string.sub(text, at, e - 1)
|
||||
at = e + 1
|
||||
return string.match(line, "^%s*(.-)%s*$") or ""
|
||||
end
|
||||
local function num(): number?
|
||||
local t = tok()
|
||||
return if t then tonumber(t) else nil
|
||||
end
|
||||
type Solid = { name: string, pos: { number }, nrm: { number } }
|
||||
local solids: { Solid } = {}
|
||||
local facets = 0
|
||||
while true do
|
||||
local t = tok()
|
||||
if t == nil then
|
||||
break
|
||||
end
|
||||
if string.lower(t) ~= "solid" then
|
||||
return nil, Err.new(Err.CORRUPT, "expected solid, found " .. string.sub(t, 1, 20))
|
||||
end
|
||||
local cur: Solid = { name = restOfLine(), pos = {}, nrm = {} }
|
||||
table.insert(solids, cur)
|
||||
local pos, nrm = cur.pos, cur.nrm
|
||||
while true do
|
||||
local w = tok()
|
||||
if w == nil then
|
||||
break -- a missing endsolid at the end
|
||||
end
|
||||
local lw = string.lower(w)
|
||||
if lw == "endsolid" then
|
||||
restOfLine()
|
||||
break
|
||||
elseif lw ~= "facet" then
|
||||
return nil, Err.new(Err.CORRUPT, "expected facet or endsolid, found " .. string.sub(w, 1, 20))
|
||||
end
|
||||
local nx, ny, nz = 0, 0, 0
|
||||
local k = tok()
|
||||
if k and string.lower(k) == "normal" then
|
||||
local a, bb, c = num(), num(), num()
|
||||
if a == nil or bb == nil or c == nil then
|
||||
return nil, Err.new(if at > #text then Err.TRUNCATED else Err.CORRUPT, "bad facet normal")
|
||||
end
|
||||
nx, ny, nz = a, bb, c
|
||||
k = tok()
|
||||
end
|
||||
local l2 = tok()
|
||||
if k == nil or l2 == nil then
|
||||
return nil, Err.new(Err.TRUNCATED, "facet cut short")
|
||||
end
|
||||
if string.lower(k) ~= "outer" or string.lower(l2) ~= "loop" then
|
||||
return nil, Err.new(Err.CORRUPT, "expected outer loop")
|
||||
end
|
||||
local vs: { number } = {}
|
||||
while true do
|
||||
local v = tok()
|
||||
if v == nil then
|
||||
return nil, Err.new(Err.TRUNCATED, "facet cut short")
|
||||
end
|
||||
local lv = string.lower(v)
|
||||
if lv == "endloop" then
|
||||
break
|
||||
elseif lv ~= "vertex" then
|
||||
return nil, Err.new(Err.CORRUPT, "expected vertex or endloop, found " .. string.sub(v, 1, 20))
|
||||
end
|
||||
local x, y, z = num(), num(), num()
|
||||
if x == nil or y == nil or z == nil then
|
||||
return nil, Err.new(if at > #text then Err.TRUNCATED else Err.CORRUPT, "bad vertex")
|
||||
end
|
||||
table.insert(vs, x)
|
||||
table.insert(vs, y)
|
||||
table.insert(vs, z)
|
||||
end
|
||||
local e = tok()
|
||||
if e == nil then
|
||||
return nil, Err.new(Err.TRUNCATED, "facet cut short")
|
||||
elseif string.lower(e) ~= "endfacet" then
|
||||
return nil, Err.new(Err.CORRUPT, "expected endfacet")
|
||||
end
|
||||
local nvs = #vs // 3
|
||||
if nvs < 3 then
|
||||
return nil, Err.new(Err.CORRUPT, "facet with fewer than 3 vertices")
|
||||
end
|
||||
for j = 2, nvs - 1 do
|
||||
for _, vi in { 0, j - 1, j } do
|
||||
table.insert(pos, vs[vi * 3 + 1])
|
||||
table.insert(pos, vs[vi * 3 + 2])
|
||||
table.insert(pos, vs[vi * 3 + 3])
|
||||
table.insert(nrm, nx)
|
||||
table.insert(nrm, ny)
|
||||
table.insert(nrm, nz)
|
||||
end
|
||||
facets += 1
|
||||
end
|
||||
if facets > maxFaces then
|
||||
return nil, Err.new(Err.LIMIT, string.format("over the %d facet limit", maxFaces))
|
||||
end
|
||||
end
|
||||
end
|
||||
if #solids == 0 then
|
||||
return nil, Err.new(Err.TRUNCATED, "no solid")
|
||||
end
|
||||
local prims: { Types.Primitive } = {}
|
||||
local names: { string } = {}
|
||||
for i, s in solids do
|
||||
local n = #s.pos // 9
|
||||
local pos, nrm = buffer.create(n * 36), buffer.create(n * 36)
|
||||
for j = 1, n * 9 do
|
||||
writef32(pos, (j - 1) * 4, s.pos[j])
|
||||
writef32(nrm, (j - 1) * 4, s.nrm[j])
|
||||
end
|
||||
local prim = soupPrim(n, pos, nrm)
|
||||
prim.extras = { solid = s.name }
|
||||
prims[i] = prim
|
||||
names[i] = s.name
|
||||
end
|
||||
local first = solids[1].name
|
||||
local scene = Types.Scene.fromPrimitive(prims[1], if first ~= "" then first else nil)
|
||||
for i = 2, #prims do
|
||||
table.insert(scene.meshes[1].primitives, prims[i])
|
||||
end
|
||||
scene.meta.up = "z"
|
||||
scene.meta.source = { format = "stl", binary = false, solids = names, facets = facets }
|
||||
return scene, nil
|
||||
end
|
||||
|
||||
function Stl.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Scene?, Err.Err?)
|
||||
local maxFaces = opts and opts.maxFaces or 2 ^ 25
|
||||
local colors = opts and opts.colors or "auto"
|
||||
if colors ~= "auto" and colors ~= "viscam" and colors ~= "magics" and colors ~= "none" then
|
||||
return nil, Err.new(Err.ARG, "colors must be auto, viscam, magics or none")
|
||||
end
|
||||
local size = r.limit - r.base
|
||||
if size >= 84 and 84 + 50 * readu32(r.buf, r.base + 80) == size then
|
||||
return decodeBinary(r, maxFaces, colors)
|
||||
end
|
||||
local s = string.match(buffer.readstring(r.buf, r.base, math.min(size, 256)), "^%s*(%a+)")
|
||||
if s and lower5(s) then
|
||||
return decodeAscii(r, maxFaces)
|
||||
end
|
||||
if size < 84 then
|
||||
return nil, Err.new(Err.TRUNCATED, "shorter than a binary STL header", r.base)
|
||||
end
|
||||
-- binary with extra bytes after the facets (tolerated) or too few (TRUNCATED)
|
||||
return decodeBinary(r, maxFaces, colors)
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ encode
|
||||
local scratch = buffer.create(4)
|
||||
local function f32(v: number): number
|
||||
writef32(scratch, 0, v)
|
||||
return buffer.readf32(scratch, 0)
|
||||
end
|
||||
|
||||
-- a COLOR_0 component as 0..255
|
||||
local function byte(a: Flatten.Attr, v: number): number
|
||||
if a.raw then
|
||||
if a.type == "unorm16" then
|
||||
return (v * 255 + 32767) // 65535
|
||||
end
|
||||
return math.clamp(v, 0, 255)
|
||||
end
|
||||
return math.floor(math.clamp(v, 0, 1) * 255 + 0.5)
|
||||
end
|
||||
|
||||
local function to5(c: number): number
|
||||
return (c * 31 + 127) // 255
|
||||
end
|
||||
|
||||
local function keep(name: string): boolean
|
||||
return name == "NORMAL" or name == "COLOR_0"
|
||||
end
|
||||
|
||||
function Stl.encode(scene: Types.Scene, opts: EncodeOptions?): (buffer?, Err.Err?)
|
||||
local o: EncodeOptions = opts or {}
|
||||
local colors = o.colors
|
||||
if colors ~= nil and colors ~= "viscam" and colors ~= "magics" then
|
||||
return nil, Err.new(Err.ARG, "colors must be viscam or magics")
|
||||
end
|
||||
if o.normals ~= nil and o.normals ~= "compute" and o.normals ~= "attribute" then
|
||||
return nil, Err.new(Err.ARG, "normals must be compute or attribute")
|
||||
end
|
||||
if o.header ~= nil and (type(o.header) ~= "string" or #o.header > 80) then
|
||||
return nil, Err.new(Err.ARG, "header must be a string of at most 80 bytes")
|
||||
end
|
||||
local m, merr = Flatten.merge(scene, keep, { triangulate = true })
|
||||
if not m then
|
||||
return nil, Err.new(Err.ARG, tostring(merr))
|
||||
end
|
||||
local P = m.attrs.POSITION.values
|
||||
local N = if o.normals == "attribute" and m.attrs.NORMAL then m.attrs.NORMAL.values else nil
|
||||
local C = m.attrs.COLOR_0
|
||||
local corners = m.corners
|
||||
local nf = #corners // 3
|
||||
-- facet normal (computed in double from the f32 vertices) and colour of facet f (0-based)
|
||||
local function normal(f: number): (number, number, number)
|
||||
local a, b, c = corners[f * 3 + 1], corners[f * 3 + 2], corners[f * 3 + 3]
|
||||
if N then
|
||||
return N[a * 3 + 1], N[a * 3 + 2], N[a * 3 + 3]
|
||||
end
|
||||
local ax, ay, az = P[a * 3 + 1], P[a * 3 + 2], P[a * 3 + 3]
|
||||
local ux, uy, uz = P[b * 3 + 1] - ax, P[b * 3 + 2] - ay, P[b * 3 + 3] - az
|
||||
local vx, vy, vz = P[c * 3 + 1] - ax, P[c * 3 + 2] - ay, P[c * 3 + 3] - az
|
||||
local nx, ny, nz = uy * vz - uz * vy, uz * vx - ux * vz, ux * vy - uy * vx
|
||||
local l = math.sqrt(nx * nx + ny * ny + nz * nz)
|
||||
if l > 0 and l < math.huge then
|
||||
return nx / l, ny / l, nz / l
|
||||
end
|
||||
return 0, 0, 0
|
||||
end
|
||||
if o.ascii then
|
||||
local out = table.create(nf * 7 + 2 * #m.parts)
|
||||
local used: { [string]: boolean } = {}
|
||||
local function fmt(v: number): string?
|
||||
v = f32(v)
|
||||
if v ~= v or v == math.huge or v == -math.huge then
|
||||
return nil
|
||||
end
|
||||
return string.format("%.9g", v)
|
||||
end
|
||||
for _, part in m.parts do
|
||||
local name = o.name
|
||||
if name == nil then
|
||||
local ex = part.prim.extras
|
||||
name = if ex and type(ex.solid) == "string" then ex.solid elseif part.mesh and part.mesh.name then part.mesh.name elseif part.node and part.node.name then part.node.name else "mesh"
|
||||
end
|
||||
name = string.gsub(tostring(name), "[\r\n]", " ")
|
||||
if used[name] then -- distinct names: some readers merge solids by name
|
||||
local k = 2
|
||||
while used[name .. "_" .. k] do
|
||||
k += 1
|
||||
end
|
||||
name = name .. "_" .. k
|
||||
end
|
||||
used[name] = true
|
||||
table.insert(out, "solid " .. name .. "\n")
|
||||
for f = part.firstFace, part.firstFace + part.faceCount - 1 do
|
||||
local nx, ny, nz = normal(f)
|
||||
table.insert(out, string.format(" facet normal %s %s %s\n outer loop\n", fmt(nx) or "0", fmt(ny) or "0", fmt(nz) or "0"))
|
||||
for k = 1, 3 do
|
||||
local v = corners[f * 3 + k] * 3
|
||||
local x, y, z = fmt(P[v + 1]), fmt(P[v + 2]), fmt(P[v + 3])
|
||||
if not (x and y and z) then
|
||||
return nil, Err.new(Err.ARG, "ASCII STL cannot hold a non-finite coordinate")
|
||||
end
|
||||
table.insert(out, " vertex " .. x .. " " .. y .. " " .. z .. "\n")
|
||||
end
|
||||
table.insert(out, " endloop\n endfacet\n")
|
||||
end
|
||||
table.insert(out, "endsolid " .. name .. "\n")
|
||||
end
|
||||
if #m.parts == 0 then
|
||||
table.insert(out, "solid " .. (o.name or "mesh") .. "\nendsolid " .. (o.name or "mesh") .. "\n")
|
||||
end
|
||||
return buffer.fromstring(table.concat(out)), nil
|
||||
end
|
||||
-- binary
|
||||
local buf = buffer.create(84 + 50 * nf)
|
||||
local header = o.header or "formats-luau STL"
|
||||
if colors == "magics" then
|
||||
local dc = o.defaultColor or { 255, 255, 255, 255 }
|
||||
if type(dc) ~= "table" or #dc < 4 then
|
||||
return nil, Err.new(Err.ARG, "defaultColor must be { r, g, b, a }")
|
||||
end
|
||||
header = string.sub(header, 1, 69) .. " COLOR=" .. string.char(math.clamp(dc[1], 0, 255) // 1, math.clamp(dc[2], 0, 255) // 1, math.clamp(dc[3], 0, 255) // 1, math.clamp(dc[4], 0, 255) // 1)
|
||||
end
|
||||
local dcol: { number }? = nil
|
||||
if colors == "magics" then
|
||||
local dc = o.defaultColor or { 255, 255, 255, 255 }
|
||||
dcol = { dc[1] // 1, dc[2] // 1, dc[3] // 1, dc[4] // 1 }
|
||||
end
|
||||
buffer.writestring(buf, 0, header)
|
||||
writeu32(buf, 80, nf)
|
||||
-- the attribute words: colours, or the raw words of a single STL-decoded primitive
|
||||
local rawAttr: { number }? = nil
|
||||
if colors == nil and #m.parts == 1 then
|
||||
local ex = m.parts[1].prim.extras
|
||||
local fa = ex and ex.faceAttributes
|
||||
local acc = fa and fa.attribute
|
||||
if acc and acc.count == nf then
|
||||
rawAttr = Flatten.numbers(acc, true)
|
||||
end
|
||||
end
|
||||
for f = 0, nf - 1 do
|
||||
local q = 84 + f * 50
|
||||
local nx, ny, nz = normal(f)
|
||||
writef32(buf, q, nx)
|
||||
writef32(buf, q + 4, ny)
|
||||
writef32(buf, q + 8, nz)
|
||||
for k = 0, 2 do
|
||||
local v = corners[f * 3 + k + 1] * 3
|
||||
writef32(buf, q + 12 + k * 12, P[v + 1])
|
||||
writef32(buf, q + 16 + k * 12, P[v + 2])
|
||||
writef32(buf, q + 20 + k * 12, P[v + 3])
|
||||
end
|
||||
local w = 0
|
||||
if colors and C then
|
||||
local a = corners[f * 3 + 1] * C.components
|
||||
local cv = C.values
|
||||
local r5, g5, b5 = to5(byte(C, cv[a + 1])), to5(byte(C, cv[a + 2] or 0)), to5(byte(C, cv[a + 3] or 0))
|
||||
if colors == "viscam" then
|
||||
w = 0x8000 + r5 * 1024 + g5 * 32 + b5
|
||||
elseif dcol and byte(C, cv[a + 1]) == dcol[1] and byte(C, cv[a + 2] or 0) == dcol[2] and byte(C, cv[a + 3] or 0) == dcol[3] and (if C.components >= 4 then byte(C, cv[a + 4]) else 255) == dcol[4] then
|
||||
w = 0x8000 -- the object colour
|
||||
else
|
||||
w = r5 + g5 * 32 + b5 * 1024
|
||||
end
|
||||
elseif colors == "magics" then
|
||||
w = 0x8000 -- the object colour
|
||||
elseif rawAttr then
|
||||
w = math.clamp(rawAttr[f + 1] // 1, 0, 65535)
|
||||
end
|
||||
writeu16(buf, q + 48, w)
|
||||
end
|
||||
return buf, nil
|
||||
end
|
||||
|
||||
return Stl
|
||||
@@ -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()
|
||||
@@ -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()
|
||||
@@ -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()
|
||||
@@ -0,0 +1,56 @@
|
||||
-- tools/fixtures/_off_encode.luau: run by tools/fixtures/off.py under the luau CLI (no file I/O): encodes the scenes of
|
||||
-- tests/gen/off_scenes with each listed option set ("default" = {}, "plain" = no colours / normals / texcoords) and
|
||||
-- prints "<scene>/<encoding> <hex>" lines, which the fixture step hands to trimesh, assimp and its own reader.
|
||||
local Off = require("@formats/model/off")
|
||||
local Types = require("@formats/Types")
|
||||
local Scenes = require("@tests/gen/off_scenes")
|
||||
|
||||
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
|
||||
|
||||
local function hex(b: buffer): string
|
||||
local out = table.create(buffer.len(b))
|
||||
for i = 0, buffer.len(b) - 1 do
|
||||
out[i + 1] = string.format("%02x", buffer.readu8(b, i))
|
||||
end
|
||||
return table.concat(out)
|
||||
end
|
||||
|
||||
local OPTS: { [string]: any } = { default = {}, plain = { colors = false, normals = false, texcoords = false } }
|
||||
for _, spec in Scenes do
|
||||
local scene = build(spec)
|
||||
for e in spec.encodings do
|
||||
local b, err = Off.encode(scene, OPTS[e])
|
||||
if not b then
|
||||
error(spec.name .. "/" .. e .. ": " .. tostring(err))
|
||||
end
|
||||
print(spec.name .. "/" .. e .. " " .. hex(b))
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,32 @@
|
||||
# OFF reference values (run by tools/fixtures/off.py through ctx.python(["trimesh", "numpy"], ...), python -I).
|
||||
# stdin: JSON {"dir": tmp, "make": [name], "read": [name]}
|
||||
# stdout: JSON {name (only the files trimesh reads): {"vertices": n, "pos_crc": crc of the f32 vertices, "faces": [[...]] or None (n-gons over 4)}}
|
||||
# make: OFF files written by trimesh (an icosphere, a capsule)
|
||||
# read: every file read with trimesh.exchange.off.load_off (positions; faces when all are triangles / quads, the
|
||||
# only polygons trimesh keeps as they are)
|
||||
import json, os, sys, zlib
|
||||
import numpy as np
|
||||
import trimesh
|
||||
from trimesh.exchange import off as toff
|
||||
|
||||
req = json.load(sys.stdin)
|
||||
d = req["dir"]
|
||||
out = {}
|
||||
for name in req["make"]:
|
||||
m = trimesh.creation.icosphere(subdivisions=2, radius=3.0) if "ico" in name else trimesh.creation.capsule(height=2.0, radius=0.5)
|
||||
with open(os.path.join(d, name), "w") as f:
|
||||
f.write(toff.export_off(m, digits=9))
|
||||
for name in req["read"]:
|
||||
try:
|
||||
with open(os.path.join(d, name), "rb") as f:
|
||||
r = toff.load_off(f)
|
||||
except Exception: # noqa: BLE001 - trimesh fails on polygons of more than 4 vertices: no reference then
|
||||
continue
|
||||
v = np.asarray(r["vertices"], dtype=np.float64).reshape(-1, 3)
|
||||
res = {"vertices": len(v), "pos_crc": zlib.crc32(v.astype("<f4").tobytes())}
|
||||
faces = r.get("faces")
|
||||
res["tris"] = int(len(faces)) if faces is not None and len(np.shape(faces)) == 2 and np.shape(faces)[1] == 3 else -1
|
||||
if res["tris"] >= 0:
|
||||
res["faces"] = [[int(x) for x in f] for f in np.asarray(faces)]
|
||||
out[name] = res
|
||||
json.dump(out, sys.stdout)
|
||||
@@ -0,0 +1,52 @@
|
||||
-- tools/fixtures/_ply_encode.luau: run by tools/fixtures/ply.py under the luau CLI (no file I/O): encodes the scenes of
|
||||
-- tests/gen/ply_scenes in the three encodings and prints "<scene>/<encoding> <hex>" lines, which the fixture step
|
||||
-- hands to plyfile and assimp.
|
||||
local Ply = require("@formats/model/ply")
|
||||
local Types = require("@formats/Types")
|
||||
local Scenes = require("@tests/gen/ply_scenes")
|
||||
|
||||
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 function hex(b: buffer): string
|
||||
local out = table.create(buffer.len(b))
|
||||
for i = 0, buffer.len(b) - 1 do
|
||||
out[i + 1] = string.format("%02x", buffer.readu8(b, i))
|
||||
end
|
||||
return table.concat(out)
|
||||
end
|
||||
|
||||
for _, spec in Scenes do
|
||||
local scene = build(spec)
|
||||
for _, e in { "ascii", "binary_little_endian", "binary_big_endian" } do
|
||||
local b, err = Ply.encode(scene, { format = e })
|
||||
if not b then
|
||||
error(spec.name .. "/" .. e .. ": " .. tostring(err))
|
||||
end
|
||||
print(spec.name .. "/" .. e .. " " .. hex(b))
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,307 @@
|
||||
# PLY reference values (run by tools/fixtures/ply.py through ctx.python(["plyfile", "numpy"], ...), python -I).
|
||||
# stdin: JSON {"dir": tmp, "make": [name], "ref": [name], "ours": [{name, file, scene}]}
|
||||
# stdout: JSON {"ref": {name: {...}}, "ours": {name: [ok, detail]}}
|
||||
# make: PLY files written by plyfile (every encoding, every property type, odd orders, lists, extra elements)
|
||||
# ref: every file read with plyfile, mapped to the library's Scene conventions here (independently of the Luau
|
||||
# code): CRC-32 of each attribute's packed little-endian bytes, the triangulated / polygon indices, face
|
||||
# properties, raw elements, comments
|
||||
# ours: our encoder's output read back by plyfile and compared property by property with the scene it came from
|
||||
import json, os, sys, zlib
|
||||
import numpy as np
|
||||
from plyfile import PlyData, PlyElement
|
||||
|
||||
req = json.load(sys.stdin)
|
||||
d = req["dir"]
|
||||
out = {"ref": {}, "ours": {}}
|
||||
|
||||
|
||||
def path(n):
|
||||
return os.path.join(d, n)
|
||||
|
||||
|
||||
def crc(a):
|
||||
return zlib.crc32(np.ascontiguousarray(a).tobytes())
|
||||
|
||||
|
||||
def le(a):
|
||||
a = np.asarray(a)
|
||||
return a.astype(a.dtype.newbyteorder("<"))
|
||||
|
||||
|
||||
def sphere(rng, n):
|
||||
"""a UV sphere with n x n quads (poles as triangle fans): vertices, quads and triangles"""
|
||||
vs = [(0.0, 0.0, 1.0)]
|
||||
for i in range(1, n):
|
||||
th = np.pi * i / n
|
||||
for j in range(n):
|
||||
ph = 2 * np.pi * j / n
|
||||
vs.append((np.sin(th) * np.cos(ph), np.sin(th) * np.sin(ph), np.cos(th)))
|
||||
vs.append((0.0, 0.0, -1.0))
|
||||
faces = []
|
||||
for j in range(n):
|
||||
faces.append([0, 1 + j, 1 + (j + 1) % n])
|
||||
for i in range(n - 2):
|
||||
for j in range(n):
|
||||
a = 1 + i * n + j
|
||||
b = 1 + i * n + (j + 1) % n
|
||||
faces.append([a, a + n, b + n, b])
|
||||
last = len(vs) - 1
|
||||
for j in range(n):
|
||||
a = 1 + (n - 2) * n
|
||||
faces.append([last, a + (j + 1) % n, a + j])
|
||||
return np.array(vs) * (1 + 0.05 * rng.random((len(vs), 1))), faces
|
||||
|
||||
|
||||
def faces_el(faces, ct="u1", it="i4", name="vertex_indices", extra=()):
|
||||
dt = [(name, "O")] + [(n, t) for n, t, _ in extra]
|
||||
a = np.empty(len(faces), dtype=dt)
|
||||
a[name] = [np.array(f, dtype=it) for f in faces]
|
||||
for n, t, vals in extra:
|
||||
a[n] = vals
|
||||
return PlyElement.describe(a, "face", len_types={name: ct}, val_types={name: it[1:] if it[0] in "<>" else it})
|
||||
|
||||
|
||||
def make(name):
|
||||
seed = sum(map(ord, name))
|
||||
rng = np.random.default_rng(seed)
|
||||
comments, obj_info = [], []
|
||||
if name == "cube-le.ply":
|
||||
v = np.array([(x, y, z) for x in (0, 1) for y in (0, 1) for z in (0, 1)], dtype=[("x", "f4"), ("y", "f4"), ("z", "f4")])
|
||||
quads = [[0, 1, 3, 2], [4, 6, 7, 5], [0, 4, 5, 1], [2, 3, 7, 6], [0, 2, 6, 4], [1, 5, 7, 3]]
|
||||
tris = [t for q in quads for t in ([q[0], q[1], q[2]], [q[0], q[2], q[3]])]
|
||||
els = [PlyElement.describe(v, "vertex"), faces_el(tris)]
|
||||
text, byte_order = False, "<"
|
||||
elif name == "colors-be.ply":
|
||||
pos, faces = sphere(rng, 12)
|
||||
n = len(pos)
|
||||
v = np.empty(n, dtype=[("x", "f4"), ("y", "f4"), ("z", "f4"), ("nx", "f4"), ("ny", "f4"), ("nz", "f4"), ("red", "u1"),
|
||||
("green", "u1"), ("blue", "u1"), ("alpha", "u1"), ("quality", "f4"), ("flags", "u2")])
|
||||
v["x"], v["y"], v["z"] = pos.T
|
||||
nn = pos / np.linalg.norm(pos, axis=1)[:, None]
|
||||
v["nx"], v["ny"], v["nz"] = nn.T
|
||||
for c in ("red", "green", "blue", "alpha"):
|
||||
v[c] = rng.integers(0, 256, n)
|
||||
v["quality"] = rng.random(n)
|
||||
v["flags"] = rng.integers(0, 65536, n)
|
||||
els = [PlyElement.describe(v, "vertex"), faces_el(faces, "u1", "u4")]
|
||||
comments = ["made by plyfile", "big endian, quads and triangles"]
|
||||
text, byte_order = False, ">"
|
||||
elif name == "ascii-mixed.ply":
|
||||
n = 40
|
||||
v = np.empty(n, dtype=[("red", "u1"), ("z", "f8"), ("y", "f8"), ("x", "f8"), ("s", "f4"), ("t", "f4"), ("intensity", "i1"), ("id", "i4")])
|
||||
v["red"] = rng.integers(0, 256, n)
|
||||
for c in ("x", "y", "z"):
|
||||
v[c] = rng.random(n) * 20 - 10
|
||||
v["s"], v["t"] = rng.random(n), rng.random(n)
|
||||
v["intensity"] = rng.integers(-128, 128, n)
|
||||
v["id"] = rng.integers(-2 ** 31, 2 ** 31, n)
|
||||
faces = [list(rng.choice(n, size=int(rng.integers(3, 7)), replace=False)) for _ in range(25)]
|
||||
f = faces_el(faces, "u1", "i4", "vertex_index", extra=[("material", "u1", rng.integers(0, 4, 25)), ("weight", "f4", rng.random(25))])
|
||||
e = np.empty(10, dtype=[("vertex1", "i4"), ("vertex2", "i4"), ("crease", "u1")])
|
||||
e["vertex1"], e["vertex2"], e["crease"] = rng.integers(0, n, 10), rng.integers(0, n, 10), rng.integers(0, 256, 10)
|
||||
m = np.empty(3, dtype=[("params", "O"), ("index", "i2")])
|
||||
m["params"] = [np.array(rng.random(k), dtype="f4") for k in (2, 0, 5)]
|
||||
m["index"] = [-1, 0, 7]
|
||||
els = [PlyElement.describe(v, "vertex"), f, PlyElement.describe(e, "edge"),
|
||||
PlyElement.describe(m, "material", len_types={"params": "u1"}, val_types={"params": "f4"})]
|
||||
comments = ["ascii with odd property order", ""]
|
||||
obj_info = ["num_cols 5", "num_rows 8"]
|
||||
text, byte_order = True, "="
|
||||
elif name == "points-le.ply":
|
||||
n = 500
|
||||
v = np.empty(n, dtype=[("x", "f4"), ("y", "f4"), ("z", "f4"), ("red", "u1"), ("green", "u1"), ("blue", "u1")])
|
||||
for c in ("x", "y", "z"):
|
||||
v[c] = rng.random(n) * 100
|
||||
for c in ("red", "green", "blue"):
|
||||
v[c] = rng.integers(0, 256, n)
|
||||
els = [PlyElement.describe(v, "vertex")]
|
||||
text, byte_order = False, "<"
|
||||
elif name == "points-ascii-float.ply":
|
||||
n = 60
|
||||
v = np.empty(n, dtype=[("x", "f4"), ("y", "f4"), ("z", "f4"), ("red", "f4"), ("green", "f4"), ("blue", "f4"), ("u", "f4"), ("v", "f4")])
|
||||
for c in v.dtype.names:
|
||||
v[c] = rng.random(n)
|
||||
els = [PlyElement.describe(v, "vertex")]
|
||||
text, byte_order = True, "="
|
||||
elif name == "types-be.ply":
|
||||
n = 400
|
||||
types = [("a", "i1"), ("b", "u1"), ("c", "i2"), ("d", "u2"), ("e", "i4"), ("f", "u4"), ("g", "f4"), ("h", "f8")]
|
||||
v = np.empty(n, dtype=[("x", "f4"), ("y", "f4"), ("z", "f4")] + types)
|
||||
v["x"], v["y"] = np.cos(np.arange(n) * 2 * np.pi / n), np.sin(np.arange(n) * 2 * np.pi / n)
|
||||
v["z"] = 0
|
||||
for nm, t in types:
|
||||
info = np.iinfo(t) if t[0] in "iu" else None
|
||||
v[nm] = rng.integers(info.min, info.max, n, endpoint=True, dtype=t) if info else rng.standard_normal(n) * 1e3
|
||||
faces = [list(range(n - 1, 99, -1)), list(range(0, 100))] # a 300-gon (ushort count) and a 100-gon
|
||||
els = [PlyElement.describe(v, "vertex"), faces_el(faces, "u2", "i4")]
|
||||
text, byte_order = False, ">"
|
||||
elif name == "big-le.ply":
|
||||
pos, faces = sphere(rng, 180)
|
||||
tris = [t for q in faces for t in (([q[0], q[1], q[2]], [q[0], q[2], q[3]]) if len(q) == 4 else ([q[0], q[1], q[2]],))]
|
||||
v = np.empty(len(pos), dtype=[("x", "f4"), ("y", "f4"), ("z", "f4")])
|
||||
v["x"], v["y"], v["z"] = pos.T
|
||||
els = [PlyElement.describe(v, "vertex"), faces_el(tris, "u1", "i4")]
|
||||
text, byte_order = False, "<"
|
||||
elif name == "tristrips.ply":
|
||||
v = np.array([(i, i % 2, 0) for i in range(8)], dtype=[("x", "f4"), ("y", "f4"), ("z", "f4")])
|
||||
s = np.empty(1, dtype=[("vertex_indices", "O")])
|
||||
s["vertex_indices"] = [np.array([0, 1, 2, 3, 4, -1, 4, 5, 6, 7], dtype="i4")]
|
||||
els = [PlyElement.describe(v, "vertex"), PlyElement.describe(s, "tristrips", len_types={"vertex_indices": "i4"}, val_types={"vertex_indices": "i4"})]
|
||||
text, byte_order = False, "<"
|
||||
else:
|
||||
raise ValueError(name)
|
||||
PlyData(els, text=text, byte_order=byte_order, comments=comments, obj_info=obj_info).write(path(name))
|
||||
|
||||
|
||||
for name in req["make"]:
|
||||
make(name)
|
||||
|
||||
ACC = {"i1": "i8", "u1": "u8", "i2": "i16", "u2": "u16", "i4": "i32", "u4": "u32", "f4": "f32", "f8": "f64"}
|
||||
PAIRS = [("u", "v"), ("s", "t"), ("texture_u", "texture_v"), ("texture_s", "texture_t")]
|
||||
|
||||
|
||||
def kind(a):
|
||||
return np.dtype(a.dtype).str[1:]
|
||||
|
||||
|
||||
def index_list(f):
|
||||
for n in ("vertex_indices", "vertex_index"):
|
||||
if n in f.data.dtype.names and f.properties[[p.name for p in f.properties].index(n)].__class__.__name__ == "PlyListProperty":
|
||||
return n
|
||||
return None
|
||||
|
||||
|
||||
def reference(name):
|
||||
ply = PlyData.read(path(name))
|
||||
v = ply["vertex"].data
|
||||
names = v.dtype.names
|
||||
taken = set()
|
||||
attrs = {}
|
||||
|
||||
def group(attr, cols, acc_type, dt, fill=None):
|
||||
arr = np.stack([v[c].astype(dt) for c in cols] + ([np.full(len(v), fill, dtype=dt)] if fill is not None else []), axis=1)
|
||||
attrs[attr] = {"type": acc_type, "components": arr.shape[1], "crc": crc(le(arr))}
|
||||
taken.update(cols)
|
||||
|
||||
if all(c in names for c in "xyz"):
|
||||
group("POSITION", ["x", "y", "z"], "f32", "<f4")
|
||||
if all(c in names for c in ("nx", "ny", "nz")) and all(kind(v[c])[0] == "f" for c in ("nx", "ny", "nz")):
|
||||
group("NORMAL", ["nx", "ny", "nz"], "f32", "<f4")
|
||||
if all(c in names for c in ("red", "green", "blue")):
|
||||
cols = ["red", "green", "blue"] + (["alpha"] if "alpha" in names else [])
|
||||
ks = {"f" if kind(v[c])[0] == "f" else kind(v[c]) for c in cols}
|
||||
if ks == {"u1"}:
|
||||
group("COLOR_0", cols, "unorm8", "u1", None if "alpha" in names else 255)
|
||||
elif ks == {"u2"}:
|
||||
group("COLOR_0", cols, "unorm16", "<u2", None if "alpha" in names else 65535)
|
||||
elif ks == {"f"}:
|
||||
group("COLOR_0", cols, "f32", "<f4", None if "alpha" in names else 1.0)
|
||||
for a, b in PAIRS:
|
||||
if a in names and b in names and kind(v[a])[0] == "f" and kind(v[b])[0] == "f":
|
||||
group("TEXCOORD_0", [a, b], "f32", "<f4")
|
||||
break
|
||||
for c in names:
|
||||
if c not in taken:
|
||||
attrs["_" + c] = {"type": ACC[kind(v[c])], "components": 1, "crc": crc(le(v[c]))}
|
||||
encoding = "ascii" if ply.text else ("binary_big_endian" if ply.byte_order == ">" else "binary_little_endian")
|
||||
res = {"vertices": len(v), "attrs": attrs, "encoding": encoding,
|
||||
"comments": list(ply.comments), "objInfo": list(ply.obj_info), "order": [e.name for e in ply.elements]}
|
||||
face = None
|
||||
if "face" in ply:
|
||||
f = ply["face"]
|
||||
il = index_list(f)
|
||||
if il:
|
||||
face = f
|
||||
if face is not None and len(face.data):
|
||||
lists = [np.asarray(x, dtype=np.int64) for x in face.data[il]]
|
||||
sizes = [len(x) for x in lists]
|
||||
corners = np.concatenate(lists) if lists else np.zeros(0, dtype=np.int64)
|
||||
res["faces"] = len(lists)
|
||||
res["corners_crc"] = crc(corners.astype("<u4"))
|
||||
res["sizes_crc"] = crc(np.array(sizes, dtype="<u4"))
|
||||
tris, fot = [], []
|
||||
for i, x in enumerate(lists):
|
||||
for k in range(1, len(x) - 1):
|
||||
tris += [x[0], x[k], x[k + 1]]
|
||||
fot.append(i)
|
||||
res["tri_crc"] = crc(np.array(tris, dtype="<u4"))
|
||||
res["tris"] = len(tris) // 3
|
||||
res["fot_crc"] = crc(np.array(fot, dtype="<u4"))
|
||||
res["allTri"] = all(s == 3 for s in sizes)
|
||||
fa = {}
|
||||
for p in face.properties:
|
||||
if p.name == il:
|
||||
continue
|
||||
col = face.data[p.name]
|
||||
if p.__class__.__name__ == "PlyListProperty":
|
||||
items = np.concatenate([np.asarray(x) for x in col]) if len(col) else np.zeros(0)
|
||||
fa[p.name] = {"list": True, "sizes_crc": crc(np.array([len(x) for x in col], dtype="<u4")),
|
||||
"items_crc": crc(le(np.asarray(items, dtype=np.dtype(p.val_dtype))))}
|
||||
else:
|
||||
fa[p.name] = {"type": ACC[kind(col)], "crc": crc(le(col))}
|
||||
res["faceAttributes"] = fa
|
||||
else:
|
||||
res["faces"] = 0
|
||||
els = []
|
||||
for e in ply.elements:
|
||||
if e.name == "vertex" or (face is not None and e is face):
|
||||
continue
|
||||
props = []
|
||||
for p in e.properties:
|
||||
col = e.data[p.name]
|
||||
if p.__class__.__name__ == "PlyListProperty":
|
||||
vd = np.dtype(p.val_dtype)
|
||||
items = np.concatenate([np.asarray(x, dtype=vd) for x in col]) if len(col) else np.zeros(0, dtype=vd)
|
||||
props.append({"name": p.name, "list": True, "sizes_crc": crc(np.array([len(x) for x in col], dtype="<u4")),
|
||||
"values_crc": crc(le(items))})
|
||||
else:
|
||||
props.append({"name": p.name, "crc": crc(le(col))})
|
||||
els.append({"name": e.name, "count": len(e.data), "props": props})
|
||||
res["elements"] = els
|
||||
return res
|
||||
|
||||
|
||||
for name in req["ref"]:
|
||||
out["ref"][name] = reference(name)
|
||||
|
||||
# our encoder's output: every expected vertex property (name, kind, values) and the faces
|
||||
for o in req["ours"]:
|
||||
name = o["name"]
|
||||
try:
|
||||
ply = PlyData.read(path(o["file"]))
|
||||
v = ply["vertex"].data
|
||||
ok, detail = True, "%d vertices" % len(v)
|
||||
want_names = [p["name"] for p in o["props"]]
|
||||
if list(v.dtype.names) != want_names:
|
||||
ok, detail = False, "vertex properties %s, want %s" % (list(v.dtype.names), want_names)
|
||||
else:
|
||||
for p in o["props"]:
|
||||
got = np.asarray(v[p["name"]])
|
||||
want = np.frombuffer(bytes.fromhex(p["values"]), dtype=p["dtype"])
|
||||
if kind(got) != np.dtype(p["dtype"]).str[1:]:
|
||||
ok, detail = False, "%s: type %s, want %s" % (p["name"], kind(got), p["dtype"])
|
||||
break
|
||||
if p.get("tol"):
|
||||
if got.shape != want.shape or float(np.abs(got.astype(np.float64) - want).max(initial=0)) > p["tol"]:
|
||||
ok, detail = False, "%s: values differ" % p["name"]
|
||||
break
|
||||
elif not np.array_equal(got, want):
|
||||
ok, detail = False, "%s: values differ" % p["name"]
|
||||
break
|
||||
if ok:
|
||||
if o.get("faces") is None:
|
||||
if "face" in ply:
|
||||
ok, detail = False, "a point cloud with a face element"
|
||||
else:
|
||||
f = ply["face"].data
|
||||
il = "vertex_indices" if "vertex_indices" in f.dtype.names else "vertex_index"
|
||||
got = [list(map(int, x)) for x in f[il]]
|
||||
if got != o["faces"]:
|
||||
ok, detail = False, "faces differ"
|
||||
else:
|
||||
detail += ", %d faces" % len(got)
|
||||
out["ours"][name] = [ok, detail]
|
||||
except Exception as e: # noqa: BLE001 - a reference failure is a verdict
|
||||
out["ours"][name] = [False, "plyfile: %s" % e]
|
||||
|
||||
json.dump(out, sys.stdout)
|
||||
@@ -0,0 +1,56 @@
|
||||
-- tools/fixtures/_stl_encode.luau: run by tools/fixtures/stl.py under the luau CLI (no file I/O): encodes the scenes of
|
||||
-- tests/gen/stl_scenes with every encoding they list and prints "<scene>/<encoding> <hex>" lines, which the fixture
|
||||
-- step hands to trimesh and assimp.
|
||||
local Stl = require("@formats/model/stl")
|
||||
local Types = require("@formats/Types")
|
||||
local Scenes = require("@tests/gen/stl_scenes")
|
||||
|
||||
local function acc(s: string, t: string, comps: number, count: number): Types.Accessor
|
||||
return Types.Scene.accessor(buffer.fromstring(s), t, 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 function hex(b: buffer): string
|
||||
local out = table.create(buffer.len(b))
|
||||
for i = 0, buffer.len(b) - 1 do
|
||||
out[i + 1] = string.format("%02x", buffer.readu8(b, i))
|
||||
end
|
||||
return table.concat(out)
|
||||
end
|
||||
|
||||
local OPTS: { [string]: any } = { binary = {}, ascii = { ascii = true }, viscam = { colors = "viscam" }, magics = { colors = "magics" } }
|
||||
for _, spec in Scenes do
|
||||
local scene = build(spec)
|
||||
for _, e in spec.encodings do
|
||||
local b, err = Stl.encode(scene, OPTS[e])
|
||||
if not b then
|
||||
error(spec.name .. "/" .. e .. ": " .. tostring(err))
|
||||
end
|
||||
print(spec.name .. "/" .. e .. " " .. hex(b))
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,112 @@
|
||||
# STL reference values (run by tools/fixtures/stl.py through ctx.python(["trimesh", "numpy"], ...), python -I).
|
||||
# stdin: JSON {"dir": tmp, "make": [[name, kind, file_type, seed]], "ref": [name], "ours": [{name, file, ...}]}
|
||||
# stdout: JSON {"ref": {name: {...}}, "ours": {name: [ok, detail]}}
|
||||
# make: meshes made and exported by trimesh itself (binary / ascii STL)
|
||||
# ref: every file read with trimesh.exchange.stl.load_stl (the raw arrays, no processing): facet count, CRC-32 of
|
||||
# the f32 triangle vertices / facet normals (as the file has them), area, bounds, the raw attribute words
|
||||
# ours: our encoder's output read back by trimesh and compared with the expected world-space triangles
|
||||
import json, os, sys, zlib
|
||||
import numpy as np
|
||||
import trimesh
|
||||
from trimesh.exchange import stl as tstl
|
||||
|
||||
req = json.load(sys.stdin)
|
||||
d = req["dir"]
|
||||
out = {"ref": {}, "ours": {}}
|
||||
|
||||
|
||||
def path(n):
|
||||
return os.path.join(d, n)
|
||||
|
||||
|
||||
for name, kind, ftype, seed in req["make"]:
|
||||
rng = np.random.default_rng(seed)
|
||||
if kind == "icosphere":
|
||||
m = trimesh.creation.icosphere(subdivisions=3, radius=2.5)
|
||||
elif kind == "box":
|
||||
m = trimesh.creation.box(extents=(1.5, 2.0, 0.25))
|
||||
elif kind == "capsule":
|
||||
m = trimesh.creation.capsule(height=3.0, radius=0.7)
|
||||
else:
|
||||
tri = (rng.random((1500, 3, 3)) * 200 - 100).astype(np.float32)
|
||||
m = trimesh.Trimesh(vertices=tri.reshape(-1, 3), faces=np.arange(4500).reshape(-1, 3), process=False)
|
||||
data = m.export(file_type=ftype)
|
||||
with open(path(name), "wb") as f:
|
||||
f.write(data.encode() if isinstance(data, str) else data)
|
||||
|
||||
|
||||
def load(name):
|
||||
with open(path(name), "rb") as f:
|
||||
r = tstl.load_stl(f)
|
||||
if "geometry" in r: # several solids
|
||||
parts = list(r["geometry"].values())
|
||||
if not parts:
|
||||
return np.zeros((0, 3)), np.zeros((0, 3), dtype=np.int64), np.zeros((0, 3)), None
|
||||
vs, fs, ns, off = [], [], [], 0
|
||||
for g in parts:
|
||||
vs.append(g["vertices"])
|
||||
fs.append(np.asarray(g["faces"]) + off)
|
||||
ns.append(g["face_normals"])
|
||||
off += len(g["vertices"])
|
||||
# trimesh does not read normals written on the "outer loop" line: no normals then
|
||||
nrm = None if any(x is None for x in ns) else np.concatenate(ns)
|
||||
return np.concatenate(vs), np.concatenate(fs), nrm, None
|
||||
attr = r.get("face_attributes", {}).get("stl")
|
||||
return np.asarray(r["vertices"]), np.asarray(r["faces"]), np.asarray(r["face_normals"]), attr
|
||||
|
||||
|
||||
def crc(a, dt):
|
||||
return zlib.crc32(np.ascontiguousarray(np.asarray(a).astype(dt)).tobytes())
|
||||
|
||||
|
||||
for name in req["ref"]:
|
||||
v, f, n, attr = load(name)
|
||||
tri = v[f].astype(np.float32) # (n, 3, 3)
|
||||
m = trimesh.Trimesh(vertices=v, faces=f, process=False)
|
||||
res = {
|
||||
"facets": int(len(f)),
|
||||
"pos_crc": crc(tri, "<f4"),
|
||||
"area": float(m.area) if len(f) else 0.0,
|
||||
"bounds": [float(x) for x in (m.bounds.reshape(-1) if len(f) else np.zeros(6))],
|
||||
}
|
||||
if n is not None:
|
||||
res["nrm_crc"] = crc(np.repeat(np.asarray(n, dtype=np.float32), 3, axis=0), "<f4")
|
||||
if attr is not None:
|
||||
res["attr"] = [int(x) for x in attr]
|
||||
out["ref"][name] = res
|
||||
|
||||
# our encoder's files
|
||||
for o in req["ours"]:
|
||||
name = o["name"]
|
||||
try:
|
||||
v, f, n, attr = load(o["file"])
|
||||
tri = v[f].astype(np.float32).reshape(-1, 9)
|
||||
want = np.frombuffer(bytes.fromhex(o["expect"]), dtype="<f4").reshape(-1, 9)
|
||||
if tri.shape != want.shape:
|
||||
out["ours"][name] = [False, "facet count %s, want %s" % (tri.shape, want.shape)]
|
||||
continue
|
||||
tol = 0 if o["exact"] else 1e-5 * max(1.0, float(np.abs(want).max()))
|
||||
err = float(np.abs(tri.astype(np.float64) - want.astype(np.float64)).max()) if len(want) else 0.0
|
||||
if err > tol:
|
||||
out["ours"][name] = [False, "positions differ by %g" % err]
|
||||
continue
|
||||
# the stored facet normals: the right-hand rule normal of each triangle
|
||||
t = want.astype(np.float64).reshape(-1, 3, 3)
|
||||
cn = np.cross(t[:, 1] - t[:, 0], t[:, 2] - t[:, 0])
|
||||
ln = np.linalg.norm(cn, axis=1)
|
||||
cn[ln > 0] /= ln[ln > 0, None]
|
||||
nerr = float(np.abs(np.asarray(n, dtype=np.float64) - cn).max()) if len(want) else 0.0
|
||||
if nerr > 1e-4:
|
||||
out["ours"][name] = [False, "facet normals differ by %g" % nerr]
|
||||
continue
|
||||
if "colors" in o:
|
||||
want_words = o["colors"]
|
||||
got = [int(x) for x in attr] if attr is not None else []
|
||||
if got != want_words:
|
||||
out["ours"][name] = [False, "attribute words differ"]
|
||||
continue
|
||||
out["ours"][name] = [True, "%d facets, max error %g" % (len(want), err)]
|
||||
except Exception as e: # noqa: BLE001 - a reference failure is a verdict
|
||||
out["ours"][name] = [False, "trimesh: %s" % e]
|
||||
|
||||
json.dump(out, sys.stdout)
|
||||
@@ -0,0 +1,343 @@
|
||||
# OFF fixtures (tools/fixtures.py).
|
||||
# tests/gen/off_scenes.luau scenes for the encoder (STCNOFF mesh, polygons under a TRS node, a float-colour point
|
||||
# cloud, polygons with face colours) with the expected file content, computed here
|
||||
# tests/gen/off.luau cases: OFF files written by trimesh and by hand here (COFF with integer / float colours,
|
||||
# RGB / RGBA, NOFF, STOFF, STCNOFF, face colours of both kinds, colormap indices, comments
|
||||
# everywhere, counts on the header line, CRLF and tabs, n-gons, a point cloud), with the
|
||||
# values they were written from (positions cross-checked with trimesh's OFF reader);
|
||||
# `ours`: our encoder's output (luau CLI: tools/fixtures/_off_encode.luau) read back by
|
||||
# trimesh, assimp and a small reader here, as verdicts
|
||||
import json, math, os, shutil, struct, subprocess, tempfile, zlib
|
||||
|
||||
INPUTS = ["src/Formats/model/off", "tools/fixtures/_off_reference.py", "tools/fixtures/_off_encode.luau"]
|
||||
|
||||
|
||||
def f32(x):
|
||||
return struct.unpack("<f", struct.pack("<f", x))[0]
|
||||
|
||||
|
||||
def pack(fmt, vals):
|
||||
return struct.pack("<%d%s" % (len(vals), fmt), *vals)
|
||||
|
||||
|
||||
def crc(b):
|
||||
return zlib.crc32(b)
|
||||
|
||||
|
||||
def fan(faces):
|
||||
tris, fot = [], []
|
||||
for i, f in enumerate(faces):
|
||||
for k in range(1, len(f) - 1):
|
||||
tris += [f[0], f[k], f[k + 1]]
|
||||
fot.append(i)
|
||||
return tris, fot
|
||||
|
||||
|
||||
def random_faces(rng, nv, nf, sizes=(3, 4, 5, 6)):
|
||||
out = []
|
||||
for _ in range(nf):
|
||||
s = rng.choice(sizes)
|
||||
out.append(rng.sample(range(nv), s))
|
||||
return out
|
||||
|
||||
|
||||
def colour_tokens(rng, kind, comps):
|
||||
if kind == "int":
|
||||
vals = [rng.randrange(256) for _ in range(comps)]
|
||||
return [str(v) for v in vals], vals
|
||||
vals = [round(rng.random(), 6) for _ in range(comps)]
|
||||
return ["%.6f" % v for v in vals], vals
|
||||
|
||||
|
||||
def colour_bytes(kind, vals_list, comps_list):
|
||||
"""the expected COLOR_0 / faceColors bytes (unorm8 x4 or f32 x4; missing alpha / colour = full)"""
|
||||
out = b""
|
||||
for vals, comps in zip(vals_list, comps_list):
|
||||
if kind == "int":
|
||||
v = list(vals) + [255] * (4 - len(vals))
|
||||
out += bytes(v)
|
||||
else:
|
||||
v = list(vals) + [1.0] * (4 - len(vals))
|
||||
out += pack("f", v)
|
||||
return out
|
||||
|
||||
|
||||
def make_case(rng, name, nv, faces, normals=False, st=False, vcol=None, fcol=None, style=None):
|
||||
"""an OFF file and the values it holds. vcol / fcol = (kind "int" | "float" | "map", comps)"""
|
||||
style = style or {}
|
||||
kw = ("ST" if st else "") + ("C" if vcol else "") + ("N" if normals else "") + "OFF"
|
||||
nl = "\r\n" if style.get("crlf") else "\n"
|
||||
sep = "\t" if style.get("tabs") else " "
|
||||
lines = []
|
||||
if style.get("comments"):
|
||||
lines.append("# a comment before the keyword")
|
||||
if style.get("inline"):
|
||||
lines.append("%s %d %d 0" % (kw, nv, len(faces)))
|
||||
else:
|
||||
lines.append(kw + (" # keyword" if style.get("comments") else ""))
|
||||
if style.get("comments"):
|
||||
lines += ["", "# counts next"]
|
||||
lines.append("%d %d %d" % (nv, len(faces), 0))
|
||||
pos, nrm, tex, vc_vals, vc_comps = [], [], [], [], []
|
||||
for i in range(nv):
|
||||
p = [f32(rng.uniform(-10, 10)) for _ in range(3)]
|
||||
pos += p
|
||||
toks = [repr(c) for c in p]
|
||||
if normals:
|
||||
v = [rng.uniform(-1, 1) for _ in range(3)]
|
||||
ln = math.sqrt(sum(c * c for c in v))
|
||||
n = [f32(c / ln) for c in v]
|
||||
nrm += n
|
||||
toks += [repr(c) for c in n]
|
||||
if vcol:
|
||||
comps = vcol[1] if vcol[1] != "mixed" else rng.choice((3, 4))
|
||||
ct, cv = colour_tokens(rng, vcol[0], comps)
|
||||
toks += ct
|
||||
vc_vals.append(cv)
|
||||
vc_comps.append(comps)
|
||||
if st:
|
||||
t = [f32(rng.random()) for _ in range(2)]
|
||||
tex += t
|
||||
toks += [repr(c) for c in t]
|
||||
line = sep.join(toks)
|
||||
if style.get("comments") and i % 3 == 0:
|
||||
line += " # vertex %d" % i
|
||||
lines.append(line)
|
||||
if style.get("comments") and i == 1:
|
||||
lines.append("")
|
||||
lines.append(" # an indented comment line")
|
||||
fc_vals, fc_comps, any_fc, colormap = [], [], False, False
|
||||
for i, f in enumerate(faces):
|
||||
toks = [str(len(f))] + [str(x) for x in f]
|
||||
if fcol and not (fcol[1] == "some" and i % 3 == 1):
|
||||
if fcol[0] == "map":
|
||||
toks.append(str(rng.randrange(16)))
|
||||
colormap = True
|
||||
fc_vals.append([])
|
||||
fc_comps.append(0)
|
||||
else:
|
||||
comps = 4 if fcol[1] in (4, "some") else 3
|
||||
ct, cv = colour_tokens(rng, fcol[0], comps)
|
||||
toks += ct
|
||||
fc_vals.append(cv)
|
||||
fc_comps.append(comps)
|
||||
any_fc = True
|
||||
else:
|
||||
fc_vals.append([])
|
||||
fc_comps.append(0)
|
||||
lines.append(sep.join(toks))
|
||||
data = (nl.join(lines) + nl).encode()
|
||||
exp = {"name": name, "data": data, "keyword": kw, "vertices": nv, "faces": len(faces), "pos_crc": crc(pack("f", pos))}
|
||||
if normals:
|
||||
exp["nrm_crc"] = crc(pack("f", nrm))
|
||||
if st:
|
||||
exp["tex_crc"] = crc(pack("f", tex))
|
||||
if vcol:
|
||||
exp["color"] = {"type": "unorm8" if vcol[0] == "int" else "f32", "crc": crc(colour_bytes(vcol[0], vc_vals, vc_comps))}
|
||||
if any_fc:
|
||||
exp["faceColors"] = {"type": "unorm8" if fcol[0] == "int" else "f32", "crc": crc(colour_bytes(fcol[0], fc_vals, fc_comps))}
|
||||
if colormap:
|
||||
exp["colormap"] = True
|
||||
tris, fot = fan(faces)
|
||||
exp["allTri"] = all(len(f) == 3 for f in faces)
|
||||
exp["tris"] = len(tris) // 3
|
||||
exp["tri_crc"] = crc(pack("I", tris))
|
||||
exp["fot_crc"] = crc(pack("I", fot))
|
||||
exp["corners_crc"] = crc(pack("I", [c for f in faces for c in f]))
|
||||
exp["sizes_crc"] = crc(pack("I", [len(f) for f in faces]))
|
||||
return exp
|
||||
|
||||
|
||||
def handmade(rng):
|
||||
cases = []
|
||||
cases.append(make_case(rng, "coff-int.off", 30, random_faces(rng, 30, 20), vcol=("int", 4), fcol=("int", 3), style={"comments": True}))
|
||||
cases.append(make_case(rng, "coff-float-rgb.off", 25, random_faces(rng, 25, 12, (3, 4)), vcol=("float", 3), fcol=("float", 4)))
|
||||
cases.append(make_case(rng, "coff-mixed-alpha.off", 12, random_faces(rng, 12, 6, (3,)), vcol=("int", "mixed")))
|
||||
cases.append(make_case(rng, "noff.off", 20, random_faces(rng, 20, 10, (3,)), normals=True))
|
||||
cases.append(make_case(rng, "stoff.off", 16, random_faces(rng, 16, 9), st=True, style={"tabs": True}))
|
||||
cases.append(make_case(rng, "stcnoff.off", 18, random_faces(rng, 18, 11), normals=True, st=True, vcol=("int", 4), fcol=("int", "some")))
|
||||
cases.append(make_case(rng, "inline-crlf.off", 10, random_faces(rng, 10, 5, (3, 4)), style={"inline": True, "crlf": True}))
|
||||
cases.append(make_case(rng, "colormap.off", 9, random_faces(rng, 9, 4, (3, 4)), fcol=("map", 1)))
|
||||
cases.append(make_case(rng, "points.off", 40, []))
|
||||
cases.append(make_case(rng, "big-ngon.off", 300, [list(range(300)), list(range(0, 300, 7))]))
|
||||
return cases
|
||||
|
||||
|
||||
# --- encoder scenes
|
||||
def mat_trs(node):
|
||||
x, y, z, w = node.get("rotation", [0, 0, 0, 1])
|
||||
sx, sy, sz = node.get("scale", [1, 1, 1])
|
||||
tx, ty, tz = node.get("translation", [0, 0, 0])
|
||||
r = [
|
||||
[1 - 2 * (y * y + z * z), 2 * (x * y - z * w), 2 * (x * z + y * w)],
|
||||
[2 * (x * y + z * w), 1 - 2 * (x * x + z * z), 2 * (y * z - x * w)],
|
||||
[2 * (x * z - y * w), 2 * (y * z + x * w), 1 - 2 * (x * x + y * y)],
|
||||
]
|
||||
return [[r[i][0] * sx, r[i][1] * sy, r[i][2] * sz, (tx, ty, tz)[i]] for i in range(3)]
|
||||
|
||||
|
||||
def scenes(rng):
|
||||
out = []
|
||||
n = 12
|
||||
pos = [f32(rng.uniform(-5, 5)) for _ in range(n * 3)]
|
||||
nrm = [f32(rng.uniform(-1, 1)) for _ in range(n * 3)]
|
||||
col = [rng.randrange(256) for _ in range(n * 4)]
|
||||
tex = [f32(rng.random()) for _ in range(n * 2)]
|
||||
idx = [rng.randrange(n) for _ in range(30)]
|
||||
faces = [idx[i:i + 3] for i in range(0, 30, 3)]
|
||||
vlines = [pos[i * 3:i * 3 + 3] + nrm[i * 3:i * 3 + 3] + col[i * 4:i * 4 + 4] + tex[i * 2:i * 2 + 2] for i in range(n)]
|
||||
out.append({"name": "mesh", "nodes": [{"mesh": 1}], "roots": [1], "meshes": [{"prims": [{
|
||||
"mode": "triangles", "count": n, "indices": pack("I", idx),
|
||||
"attrs": {"POSITION": ["f32", 3, pack("f", pos)], "NORMAL": ["f32", 3, pack("f", nrm)], "COLOR_0": ["unorm8", 4, bytes(col)],
|
||||
"TEXCOORD_0": ["f32", 2, pack("f", tex)]}}]}],
|
||||
"encodings": {"default": {"keyword": "STCNOFF", "vertices": vlines, "faces": faces},
|
||||
"plain": {"keyword": "OFF", "vertices": [v[:3] for v in vlines], "faces": faces}}})
|
||||
pv = [0, 0, 0, 1, 0, 0, 1, 1, 0, 0, 1, 0, 2, 0, 0, 3, 0.5, 0, 2.5, 1.5, 0.2, 1.5, 1.2, 0.1, 0, 0, 1]
|
||||
q = [rng.uniform(-1, 1) for _ in range(4)]
|
||||
ln = math.sqrt(sum(c * c for c in q))
|
||||
node = {"mesh": 1, "translation": [1, 2, 3], "rotation": [c / ln for c in q], "scale": [2, 0.5, 1.5]}
|
||||
m = mat_trs(node)
|
||||
w = [[m[i][0] * pv[k * 3] + m[i][1] * pv[k * 3 + 1] + m[i][2] * pv[k * 3 + 2] + m[i][3] for i in range(3)] for k in range(9)]
|
||||
pf = [[0, 1, 2, 3], [1, 4, 5, 6, 7, 2], [0, 3, 8]]
|
||||
out.append({"name": "polys", "nodes": [node], "roots": [1], "meshes": [{"prims": [{
|
||||
"mode": "polygons", "count": 9, "indices": pack("I", [c for f in pf for c in f]), "faces": pack("I", [len(f) for f in pf]),
|
||||
"attrs": {"POSITION": ["f32", 3, pack("f", pv)]}}]}],
|
||||
"encodings": {"default": {"keyword": "OFF", "vertices": w, "faces": pf, "tol": 1e-5}}})
|
||||
n = 20
|
||||
pos = [f32(rng.uniform(-50, 50)) for _ in range(n * 3)]
|
||||
col = [f32(rng.random()) for _ in range(n * 4)]
|
||||
out.append({"name": "cloud", "nodes": [{"mesh": 1}], "roots": [1], "meshes": [{"prims": [{
|
||||
"mode": "points", "count": n, "attrs": {"POSITION": ["f32", 3, pack("f", pos)], "COLOR_0": ["f32", 4, pack("f", col)]}}]}],
|
||||
"encodings": {"default": {"keyword": "COFF", "vertices": [pos[i * 3:i * 3 + 3] + col[i * 4:i * 4 + 4] for i in range(n)], "faces": []}}})
|
||||
# face colours on planar polygons (assimp triangulates non-planar ones its own way)
|
||||
pf = [[0, 1, 2, 3], [1, 4, 5, 6, 7, 2], [0, 3, 8]]
|
||||
pos = [f32(v) for v in pv]
|
||||
fc = [rng.randrange(256) for _ in range(12)]
|
||||
out.append({"name": "facecolors", "nodes": [{"mesh": 1}], "roots": [1], "meshes": [{"prims": [{
|
||||
"mode": "polygons", "count": 9, "indices": pack("I", [c for f in pf for c in f]), "faces": pack("I", [len(f) for f in pf]),
|
||||
"attrs": {"POSITION": ["f32", 3, pack("f", pos)]}, "faceColors": bytes(fc)}]}],
|
||||
"encodings": {"default": {"keyword": "OFF", "vertices": [pos[i * 3:i * 3 + 3] for i in range(9)], "faces": pf,
|
||||
"faceColors": [fc[i * 4:i * 4 + 4] for i in range(3)]}}})
|
||||
return out
|
||||
|
||||
|
||||
def parse_off(text):
|
||||
"""a small OFF reader for checking our output: keyword, vertex rows (numbers), faces, face colour rows"""
|
||||
rows = []
|
||||
for line in text.split("\n"):
|
||||
line = line.split("#", 1)[0].strip()
|
||||
if line:
|
||||
rows.append(line.split())
|
||||
kw = rows[0][0]
|
||||
nv, nf = int(rows[1][0]), int(rows[1][1])
|
||||
verts = [[float(x) for x in r] for r in rows[2:2 + nv]]
|
||||
faces, fcols = [], []
|
||||
for r in rows[2 + nv:2 + nv + nf]:
|
||||
k = int(r[0])
|
||||
faces.append([int(x) for x in r[1:1 + k]])
|
||||
fcols.append([float(x) for x in r[1 + k:]])
|
||||
return kw, verts, faces, fcols, len(rows) == 2 + nv + nf
|
||||
|
||||
|
||||
def check_ours(text, want):
|
||||
kw, verts, faces, fcols, exact_rows = parse_off(text)
|
||||
if kw != want["keyword"]:
|
||||
return False, "keyword %s, want %s" % (kw, want["keyword"])
|
||||
if not exact_rows:
|
||||
return False, "extra or missing rows"
|
||||
if len(verts) != len(want["vertices"]):
|
||||
return False, "vertex count"
|
||||
tol = want.get("tol", 0)
|
||||
for got, exp in zip(verts, want["vertices"]):
|
||||
if len(got) != len(exp):
|
||||
return False, "vertex row length %d, want %d" % (len(got), len(exp))
|
||||
for g, e in zip(got, exp):
|
||||
if (abs(f32(g) - f32(e)) > tol * max(1, abs(e))) if tol else f32(g) != f32(e):
|
||||
return False, "vertex value %r, want %r" % (g, e)
|
||||
if faces != want["faces"]:
|
||||
return False, "faces differ"
|
||||
if "faceColors" in want:
|
||||
if [list(map(int, c)) for c in fcols] != want["faceColors"]:
|
||||
return False, "face colours differ"
|
||||
elif any(fcols):
|
||||
return False, "unexpected face colours"
|
||||
return True, "%d vertices, %d faces" % (len(verts), len(faces))
|
||||
|
||||
|
||||
def luau_cmd():
|
||||
exe = shutil.which("luau")
|
||||
return [exe] if exe else ["nix", "shell", "nixpkgs#luau", "-c", "luau"]
|
||||
|
||||
|
||||
def assimp_faces(ctx, path):
|
||||
txt = ctx.nix("assimp", ["assimp", "info", path]).decode(errors="replace")
|
||||
for line in txt.split("\n"):
|
||||
if line.startswith("Faces:"):
|
||||
return int(line.split()[1])
|
||||
return None
|
||||
|
||||
|
||||
def generate(ctx):
|
||||
rng = ctx.rng(53)
|
||||
tmp = tempfile.mkdtemp(prefix="formats-off-")
|
||||
try:
|
||||
_generate(ctx, rng, tmp)
|
||||
finally:
|
||||
shutil.rmtree(tmp, ignore_errors=True)
|
||||
|
||||
|
||||
def _generate(ctx, rng, tmp):
|
||||
sc = scenes(rng)
|
||||
ctx.emit("off_scenes", sc)
|
||||
cases = handmade(rng)
|
||||
for c in cases:
|
||||
with open(os.path.join(tmp, c["name"]), "wb") as f:
|
||||
f.write(c["data"])
|
||||
make = ["trimesh-ico.off", "trimesh-capsule.off"]
|
||||
enc = subprocess.run(luau_cmd() + [os.path.join(ctx.root, "tools", "fixtures", "_off_encode.luau")], capture_output=True, check=True, cwd=ctx.root).stdout.decode()
|
||||
ours = []
|
||||
byname = {s["name"]: s for s in sc}
|
||||
for line in enc.split("\n"):
|
||||
if not line.strip():
|
||||
continue
|
||||
label, hexdata = line.split(" ", 1)
|
||||
scene_name, encoding = label.split("/")
|
||||
fn = "ours-%s-%s.off" % (scene_name, encoding)
|
||||
data = bytes.fromhex(hexdata.strip())
|
||||
with open(os.path.join(tmp, fn), "wb") as f:
|
||||
f.write(data)
|
||||
ours.append((label, fn, data, byname[scene_name]["encodings"][encoding]))
|
||||
names = [c["name"] for c in cases if c["vertices"] > 0] + make + [o[1] for o in ours]
|
||||
code = open(os.path.join(ctx.root, "tools", "fixtures", "_off_reference.py")).read()
|
||||
try:
|
||||
ref = json.loads(ctx.python(["trimesh", "numpy"], code, input=json.dumps({"dir": tmp, "make": make, "read": names}).encode()))
|
||||
except subprocess.CalledProcessError as e:
|
||||
raise RuntimeError("off reference: " + e.stderr.decode(errors="replace")[-3000:])
|
||||
# trimesh agrees with the values the files were written from
|
||||
for c in cases:
|
||||
r = ref.get(c["name"])
|
||||
if r:
|
||||
assert r["vertices"] == c["vertices"] and r["pos_crc"] == c["pos_crc"], c["name"]
|
||||
for name in make:
|
||||
with open(os.path.join(tmp, name), "rb") as f:
|
||||
data = f.read()
|
||||
r = ref[name]
|
||||
tris = [x for f in r["faces"] for x in f]
|
||||
cases.append({"name": name, "data": data, "keyword": "OFF", "vertices": r["vertices"], "faces": r["tris"], "pos_crc": r["pos_crc"],
|
||||
"allTri": True, "tris": r["tris"], "tri_crc": crc(pack("I", tris)), "corners_crc": crc(pack("I", tris)),
|
||||
"sizes_crc": crc(pack("I", [3] * r["tris"]))})
|
||||
verdicts = []
|
||||
for label, fn, data, want in ours:
|
||||
ok, detail = check_ours(data.decode(), want)
|
||||
r = ref.get(fn)
|
||||
if ok and r and not want.get("tol"):
|
||||
exp = pack("f", [c for v in want["vertices"] for c in v[:3]])
|
||||
if r["pos_crc"] != crc(exp):
|
||||
ok, detail = False, "trimesh reads other positions"
|
||||
if ok and want["faces"]:
|
||||
got = assimp_faces(ctx, os.path.join(tmp, fn))
|
||||
exp_f = sum(len(f) - 2 for f in want["faces"])
|
||||
if got != exp_f:
|
||||
ok, detail = False, "assimp reads %s faces, want %d" % (got, exp_f)
|
||||
verdicts.append({"name": label, "ok": ok, "detail": detail})
|
||||
ctx.emit("off", {"cases": cases, "ours": verdicts})
|
||||
@@ -0,0 +1,192 @@
|
||||
# PLY fixtures (tools/fixtures.py).
|
||||
# tests/gen/ply_scenes.luau scenes for the encoder (an indexed mesh with every attribute kind and custom properties,
|
||||
# polygons under a TRS node, a float-colour point cloud, two meshes merged, a mirrored
|
||||
# polygon) with the expected vertex properties (names, types, values) and faces, computed
|
||||
# here
|
||||
# tests/gen/ply.luau cases: PLY files written by plyfile (ascii / binary LE / BE, every property type, odd
|
||||
# orders, n-gons up to 300 vertices, face properties and lists, edge / material / tristrips
|
||||
# elements, comments, obj_info, point clouds, a 65k-vertex sphere) and by assimp (OFF / OBJ
|
||||
# -> PLY), each with reference values from plyfile mapped to the Scene conventions;
|
||||
# `ours`: our encoder's output (luau CLI: tools/fixtures/_ply_encode.luau) read back by
|
||||
# plyfile and assimp, as verdicts
|
||||
import json, math, os, shutil, struct, subprocess, tempfile
|
||||
|
||||
INPUTS = ["src/Formats/model/ply", "tools/fixtures/_ply_reference.py", "tools/fixtures/_ply_encode.luau"]
|
||||
|
||||
|
||||
def f32(x):
|
||||
return struct.unpack("<f", struct.pack("<f", x))[0]
|
||||
|
||||
|
||||
def pack(fmt, vals):
|
||||
return struct.pack("<%d%s" % (len(vals), fmt), *vals)
|
||||
|
||||
|
||||
def mat_trs(node):
|
||||
x, y, z, w = node.get("rotation", [0, 0, 0, 1])
|
||||
sx, sy, sz = node.get("scale", [1, 1, 1])
|
||||
tx, ty, tz = node.get("translation", [0, 0, 0])
|
||||
r = [
|
||||
[1 - 2 * (y * y + z * z), 2 * (x * y - z * w), 2 * (x * z + y * w)],
|
||||
[2 * (x * y + z * w), 1 - 2 * (x * x + z * z), 2 * (y * z - x * w)],
|
||||
[2 * (x * z - y * w), 2 * (y * z + x * w), 1 - 2 * (x * x + y * y)],
|
||||
]
|
||||
return [[r[i][0] * sx, r[i][1] * sy, r[i][2] * sz, (tx, ty, tz)[i]] for i in range(3)]
|
||||
|
||||
|
||||
def quat(rng):
|
||||
q = [rng.uniform(-1, 1) for _ in range(4)]
|
||||
ln = math.sqrt(sum(c * c for c in q))
|
||||
return [c / ln for c in q]
|
||||
|
||||
|
||||
def scenes(rng):
|
||||
out = []
|
||||
# an indexed mesh with every attribute kind
|
||||
W, H = 5, 4
|
||||
n = W * H
|
||||
pos = [f32(v) for y in range(H) for x in range(W) for v in (x, y, rng.uniform(-1, 1))]
|
||||
nrm = []
|
||||
for _ in range(n):
|
||||
v = [rng.uniform(-1, 1) for _ in range(3)]
|
||||
ln = math.sqrt(sum(c * c for c in v))
|
||||
nrm += [f32(c / ln) for c in v]
|
||||
col = [rng.randrange(256) for _ in range(n * 4)]
|
||||
tex = [f32(rng.random()) for _ in range(n * 2)]
|
||||
quality = [f32(rng.uniform(0, 10)) for _ in range(n)]
|
||||
label = [rng.randrange(65536) for _ in range(n)]
|
||||
idx = []
|
||||
for y in range(H - 1):
|
||||
for x in range(W - 1):
|
||||
a = y * W + x
|
||||
idx += [a, a + 1, a + W + 1, a, a + W + 1, a + W]
|
||||
out.append({"name": "mesh", "nodes": [{"mesh": 1}], "roots": [1], "meshes": [{"prims": [{
|
||||
"mode": "triangles", "count": n, "indices": pack("I", idx),
|
||||
"attrs": {"POSITION": ["f32", 3, pack("f", pos)], "NORMAL": ["f32", 3, pack("f", nrm)], "COLOR_0": ["unorm8", 4, bytes(col)],
|
||||
"TEXCOORD_0": ["f32", 2, pack("f", tex)], "_quality": ["f32", 1, pack("f", quality)], "_label": ["u16", 1, pack("H", label)]}}]}],
|
||||
"props": [("x", "<f4", pos[0::3]), ("y", "<f4", pos[1::3]), ("z", "<f4", pos[2::3]), ("nx", "<f4", nrm[0::3]), ("ny", "<f4", nrm[1::3]),
|
||||
("nz", "<f4", nrm[2::3]), ("red", "u1", col[0::4]), ("green", "u1", col[1::4]), ("blue", "u1", col[2::4]), ("alpha", "u1", col[3::4]),
|
||||
("s", "<f4", tex[0::2]), ("t", "<f4", tex[1::2]), ("label", "<u2", label), ("quality", "<f4", quality)],
|
||||
"faces": [idx[i:i + 3] for i in range(0, len(idx), 3)]})
|
||||
# polygons under a TRS node (positions transformed: compared with a tolerance)
|
||||
pv = [0, 0, 0, 1, 0, 0, 1, 1, 0, 0, 1, 0, 2, 0, 0, 3, 0.5, 0, 2.5, 1.5, 0.2, 1.5, 1.2, 0.1, 0, 0, 1]
|
||||
node = {"mesh": 1, "translation": [1, 2, 3], "rotation": quat(rng), "scale": [2, 0.5, 1.5]}
|
||||
m = mat_trs(node)
|
||||
w = [[f32(m[i][0] * pv[k * 3] + m[i][1] * pv[k * 3 + 1] + m[i][2] * pv[k * 3 + 2] + m[i][3]) for i in range(3)] for k in range(9)]
|
||||
out.append({"name": "polys", "nodes": [node], "roots": [1], "meshes": [{"prims": [{
|
||||
"mode": "polygons", "count": 9, "indices": pack("I", [0, 1, 2, 3, 1, 4, 5, 6, 7, 2, 0, 3, 8]), "faces": pack("I", [4, 6, 3]),
|
||||
"attrs": {"POSITION": ["f32", 3, pack("f", pv)]}}]}],
|
||||
"props": [("x", "<f4", [p[0] for p in w], 1e-5), ("y", "<f4", [p[1] for p in w], 1e-5), ("z", "<f4", [p[2] for p in w], 1e-5)],
|
||||
"faces": [[0, 1, 2, 3], [1, 4, 5, 6, 7, 2], [0, 3, 8]], "transformed": True})
|
||||
# a point cloud with float colours (alpha all 1: not written)
|
||||
n = 30
|
||||
pos = [f32(rng.uniform(-50, 50)) for _ in range(n * 3)]
|
||||
col = [f32(rng.random()) if k % 4 != 3 else 1.0 for k in range(n * 4)]
|
||||
out.append({"name": "cloud", "nodes": [{"mesh": 1}], "roots": [1], "meshes": [{"prims": [{
|
||||
"mode": "points", "count": n, "attrs": {"POSITION": ["f32", 3, pack("f", pos)], "COLOR_0": ["f32", 4, pack("f", col)]}}]}],
|
||||
"props": [("x", "<f4", pos[0::3]), ("y", "<f4", pos[1::3]), ("z", "<f4", pos[2::3]), ("red", "<f4", col[0::4]),
|
||||
("green", "<f4", col[1::4]), ("blue", "<f4", col[2::4])]})
|
||||
# two meshes merged: the second has no colours (filled with opaque white: alpha not written)
|
||||
pa = [0, 0, 0, 1, 0, 0, 1, 1, 0, 0, 1, 0]
|
||||
ca = [10, 20, 30, 255, 40, 50, 60, 255, 70, 80, 90, 255, 100, 110, 120, 255]
|
||||
pb = [5, 5, 5, 6, 5, 5, 6, 6, 5, 5, 6, 5.5]
|
||||
allp = pa + pb
|
||||
allc = ca + [255] * 16
|
||||
out.append({"name": "multi", "nodes": [{"mesh": 1}, {"mesh": 2}], "roots": [1, 2], "meshes": [
|
||||
{"prims": [{"mode": "triangles", "count": 4, "indices": pack("I", [0, 1, 2, 0, 2, 3]),
|
||||
"attrs": {"POSITION": ["f32", 3, pack("f", pa)], "COLOR_0": ["unorm8", 4, bytes(ca)]}}]},
|
||||
{"prims": [{"mode": "polygons", "count": 4, "indices": pack("I", [0, 1, 2, 3]), "faces": pack("I", [4]),
|
||||
"attrs": {"POSITION": ["f32", 3, pack("f", pb)]}}]}],
|
||||
"props": [("x", "<f4", allp[0::3]), ("y", "<f4", allp[1::3]), ("z", "<f4", allp[2::3]), ("red", "u1", allc[0::4]),
|
||||
("green", "u1", allc[1::4]), ("blue", "u1", allc[2::4])],
|
||||
"faces": [[0, 1, 2], [0, 2, 3], [4, 5, 6, 7]]})
|
||||
# a mirrored polygon: the winding reverses (first corner kept)
|
||||
pm = [0, 0, 0, 1, 0, 0, 1.5, 1, 0, 0.5, 1.5, 0, -0.5, 1, 0]
|
||||
out.append({"name": "mirror", "nodes": [{"mesh": 1, "scale": [-1, 1, 1]}], "roots": [1], "meshes": [{"prims": [{
|
||||
"mode": "polygons", "count": 5, "indices": pack("I", [0, 1, 2, 3, 4]), "faces": pack("I", [5]),
|
||||
"attrs": {"POSITION": ["f32", 3, pack("f", pm)]}}]}],
|
||||
"props": [("x", "<f4", [-v for v in pm[0::3]]), ("y", "<f4", pm[1::3]), ("z", "<f4", pm[2::3])],
|
||||
"faces": [[0, 4, 3, 2, 1]], "transformed": True})
|
||||
for sc in out:
|
||||
sc["props"] = [{"name": p[0], "dtype": p[1], "values": struct.pack("<%d%s" % (len(p[2]), {"<f4": "f", "u1": "B", "<u2": "H"}[p[1]]), *p[2]),
|
||||
**({"tol": p[3]} if len(p) > 3 else {})} for p in sc["props"]]
|
||||
if "faces" in sc:
|
||||
sc["faceSizes"] = pack("I", [len(f) for f in sc["faces"]])
|
||||
sc["faceCorners"] = pack("I", [c for f in sc["faces"] for c in f])
|
||||
return out
|
||||
|
||||
|
||||
def luau_cmd():
|
||||
exe = shutil.which("luau")
|
||||
return [exe] if exe else ["nix", "shell", "nixpkgs#luau", "-c", "luau"]
|
||||
|
||||
|
||||
def assimp_faces(ctx, path):
|
||||
txt = ctx.nix("assimp", ["assimp", "info", path]).decode(errors="replace")
|
||||
for line in txt.split("\n"):
|
||||
if line.startswith("Faces:"):
|
||||
return int(line.split()[1])
|
||||
return None
|
||||
|
||||
|
||||
def generate(ctx):
|
||||
rng = ctx.rng(47)
|
||||
tmp = tempfile.mkdtemp(prefix="formats-ply-")
|
||||
try:
|
||||
_generate(ctx, rng, tmp)
|
||||
finally:
|
||||
shutil.rmtree(tmp, ignore_errors=True)
|
||||
|
||||
|
||||
def _generate(ctx, rng, tmp):
|
||||
sc = scenes(rng)
|
||||
ctx.emit("ply_scenes", sc)
|
||||
make = ["cube-le.ply", "colors-be.ply", "ascii-mixed.ply", "points-le.ply", "points-ascii-float.ply", "types-be.ply", "big-le.ply", "tristrips.ply"]
|
||||
# assimp conversions: OFF -> PLY (ascii), OBJ -> PLY (binary)
|
||||
off = "OFF\n6 3 0\n" + "".join("%r %r %r\n" % (f32(rng.uniform(-5, 5)), f32(rng.uniform(-5, 5)), f32(rng.uniform(-5, 5))) for _ in range(6))
|
||||
off += "3 0 1 2\n4 1 3 4 2\n3 4 5 2\n"
|
||||
obj = "".join("v %r %r %r\n" % (f32(rng.uniform(-5, 5)), f32(rng.uniform(-5, 5)), f32(rng.uniform(-5, 5))) for _ in range(8))
|
||||
obj += "vn 0 0 1\nf 1//1 2//1 3//1 4//1\nf 5//1 6//1 7//1\nf 1//1 8//1 5//1\n"
|
||||
with open(os.path.join(tmp, "in.off"), "w") as f:
|
||||
f.write(off)
|
||||
with open(os.path.join(tmp, "in.obj"), "w") as f:
|
||||
f.write(obj)
|
||||
ctx.nix("assimp", ["assimp", "export", os.path.join(tmp, "in.off"), os.path.join(tmp, "assimp-off.ply"), "-fply"])
|
||||
ctx.nix("assimp", ["assimp", "export", os.path.join(tmp, "in.obj"), os.path.join(tmp, "assimp-obj-b.ply"), "-fplyb"])
|
||||
refs = make + ["assimp-off.ply", "assimp-obj-b.ply"]
|
||||
enc = subprocess.run(luau_cmd() + [os.path.join(ctx.root, "tools", "fixtures", "_ply_encode.luau")], capture_output=True, check=True, cwd=ctx.root).stdout.decode()
|
||||
ours = []
|
||||
byname = {s["name"]: s for s in sc}
|
||||
for line in enc.split("\n"):
|
||||
if not line.strip():
|
||||
continue
|
||||
label, hexdata = line.split(" ", 1)
|
||||
scene_name, encoding = label.split("/")
|
||||
s = byname[scene_name]
|
||||
fn = "ours-%s-%s.ply" % (scene_name, encoding)
|
||||
with open(os.path.join(tmp, fn), "wb") as f:
|
||||
f.write(bytes.fromhex(hexdata.strip()))
|
||||
ours.append({"name": label, "file": fn, "props": [{**p, "values": p["values"].hex()} for p in s["props"]], "faces": s.get("faces")})
|
||||
code = open(os.path.join(ctx.root, "tools", "fixtures", "_ply_reference.py")).read()
|
||||
try:
|
||||
res = json.loads(ctx.python(["plyfile", "numpy"], code, input=json.dumps({"dir": tmp, "make": make, "ref": refs, "ours": ours}).encode()))
|
||||
except subprocess.CalledProcessError as e:
|
||||
raise RuntimeError("ply reference: " + e.stderr.decode(errors="replace")[-3000:])
|
||||
verdicts = []
|
||||
for o in ours:
|
||||
ok, detail = res["ours"][o["name"]]
|
||||
if o["faces"]:
|
||||
want = sum(len(f) - 2 for f in o["faces"])
|
||||
got = assimp_faces(ctx, os.path.join(tmp, o["file"]))
|
||||
if got != want:
|
||||
ok, detail = False, "assimp reads %s faces, want %d" % (got, want)
|
||||
verdicts.append({"name": o["name"], "ok": ok, "detail": detail})
|
||||
cases = []
|
||||
for name in refs:
|
||||
with open(os.path.join(tmp, name), "rb") as f:
|
||||
data = f.read()
|
||||
r = res["ref"][name]
|
||||
c = {"name": name, "data": data}
|
||||
c.update({k: v for k, v in r.items() if v is not None})
|
||||
cases.append(c)
|
||||
ctx.emit("ply", {"cases": cases, "ours": verdicts})
|
||||
@@ -0,0 +1,383 @@
|
||||
# STL fixtures (tools/fixtures.py).
|
||||
# tests/gen/stl_scenes.luau scenes for the encoder (indexed grid with colours, polygons under a TRS node, a node tree
|
||||
# with a matrix, a mirror and u16 positions) with the expected world-space triangle soup
|
||||
# (computed here with numpy) and the expected colour attribute words
|
||||
# tests/gen/stl.luau cases: STL files made by trimesh (binary / ascii), by assimp (obj / ply -> stl / stlb)
|
||||
# and by hand here (binary starting with "solid", VisCAM and Magics colours, raw attribute
|
||||
# words, odd ASCII: case, tabs, CRLF, several solids, quads, no endsolid, trailing bytes,
|
||||
# empty), each with reference values from trimesh's raw STL reader (facets, CRC-32 of the
|
||||
# f32 vertices and normals, area, bounds, attribute words); `ours`: our encoder's output
|
||||
# (run through the luau CLI: tools/fixtures/_stl_encode.luau) read back by trimesh and
|
||||
# assimp, as verdicts
|
||||
import json, math, os, shutil, struct, subprocess, tempfile, zlib
|
||||
|
||||
INPUTS = ["src/Formats/model/stl", "tools/fixtures/_stl_reference.py", "tools/fixtures/_stl_encode.luau"]
|
||||
|
||||
|
||||
def f32(x):
|
||||
return struct.unpack("<f", struct.pack("<f", x))[0]
|
||||
|
||||
|
||||
def binary_stl(header, tris, normals=None, attrs=None, extra=b""):
|
||||
out = bytearray(header.ljust(80, b"\0")[:80])
|
||||
out += struct.pack("<I", len(tris))
|
||||
for i, t in enumerate(tris):
|
||||
n = normals[i] if normals else (0.0, 0.0, 0.0)
|
||||
out += struct.pack("<3f", *n)
|
||||
for v in t:
|
||||
out += struct.pack("<3f", *v)
|
||||
out += struct.pack("<H", attrs[i] if attrs else 0)
|
||||
return bytes(out) + extra
|
||||
|
||||
|
||||
def rand_tris(rng, n, scale=10.0):
|
||||
return [[tuple(f32(rng.uniform(-scale, scale)) for _ in range(3)) for _ in range(3)] for _ in range(n)]
|
||||
|
||||
|
||||
def unit_normal(t):
|
||||
ux, uy, uz = (t[1][k] - t[0][k] for k in range(3))
|
||||
vx, vy, vz = (t[2][k] - t[0][k] for k in range(3))
|
||||
n = (uy * vz - uz * vy, uz * vx - ux * vz, ux * vy - uy * vx)
|
||||
ln = math.sqrt(sum(c * c for c in n)) or 1.0
|
||||
return tuple(f32(c / ln) for c in n)
|
||||
|
||||
|
||||
def x8(v):
|
||||
return (v * 255 + 15) // 31
|
||||
|
||||
|
||||
def to5(c):
|
||||
return (c * 31 + 127) // 255
|
||||
|
||||
|
||||
def soup_bytes(tris):
|
||||
return b"".join(struct.pack("<3f", *v) for t in tris for v in t)
|
||||
|
||||
|
||||
def crc(b):
|
||||
return zlib.crc32(b)
|
||||
|
||||
|
||||
# --- hand-made files: (name, data, expected) where expected holds what trimesh cannot tell us
|
||||
def handmade(rng):
|
||||
cases = []
|
||||
tris = rand_tris(rng, 12)
|
||||
cases.append(("bin-solid-header.stl", binary_stl(b"solid this is binary all the same", tris, [unit_normal(t) for t in tris]), {}))
|
||||
# VisCAM: bit 15 = valid, red high; some facets invalid
|
||||
tris = rand_tris(rng, 40)
|
||||
words, cols = [], []
|
||||
for i in range(40):
|
||||
r, g, b = rng.randrange(32), rng.randrange(32), rng.randrange(32)
|
||||
if i % 7 == 3:
|
||||
words.append(rng.randrange(0x8000)) # not valid: the default (opaque white)
|
||||
cols.append((255, 255, 255, 255))
|
||||
else:
|
||||
words.append(0x8000 | r << 10 | g << 5 | b)
|
||||
cols.append((x8(r), x8(g), x8(b), 255))
|
||||
cases.append(("viscam.stl", binary_stl(b"VisCAM colours", tris, None, words), {"colors": "viscam", "cols": cols}))
|
||||
# Magics: COLOR= object colour, bit 15 clear = own colour, red low
|
||||
tris = rand_tris(rng, 40)
|
||||
dc = (200, 100, 50, 180)
|
||||
header = b"magics part COLOR=" + bytes(dc) + b",MATERIAL=" + bytes(range(12))
|
||||
words, cols = [], []
|
||||
for i in range(40):
|
||||
r, g, b = rng.randrange(32), rng.randrange(32), rng.randrange(32)
|
||||
if i % 5 == 0:
|
||||
words.append(0x8000 | rng.randrange(0x8000))
|
||||
cols.append(dc)
|
||||
else:
|
||||
words.append(r | g << 5 | b << 10)
|
||||
cols.append((x8(r), x8(g), x8(b), 255))
|
||||
cases.append(("magics.stl", binary_stl(header, tris, None, words), {"colors": "magics", "cols": cols, "defaultColor": list(dc)}))
|
||||
# raw attribute words (no colour convention)
|
||||
tris = rand_tris(rng, 9)
|
||||
words = [rng.randrange(1, 0x8000) for _ in range(9)]
|
||||
cases.append(("attrs.stl", binary_stl(b"attribute words", tris, None, words), {"words": words}))
|
||||
cases.append(("bin-empty.stl", binary_stl(b"empty", []), {}))
|
||||
# ASCII oddities: case, tabs, CRLF, exponents, two solids (one unnamed), blank lines
|
||||
t1, t2 = rand_tris(rng, 3), rand_tris(rng, 2)
|
||||
s = "SOLID first part\r\n"
|
||||
for t in t1:
|
||||
s += "\tFACET NORMAL %.6e %.6e %.6e\r\n\t\tOUTER LOOP\r\n" % unit_normal(t)
|
||||
for v in t:
|
||||
s += "\t\t\tVERTEX %.9g\t%.9e %r\r\n" % (v[0], v[1], v[2])
|
||||
s += "\t\tENDLOOP\r\n\tENDFACET\r\n\r\n"
|
||||
s += "ENDSOLID first part\r\n\nsolid\n"
|
||||
for t in t2:
|
||||
s += "facet normal %r %r %r outer loop\n" % unit_normal(t)
|
||||
s += " ".join("vertex %r %r %r" % v for v in t) + "\nendloop endfacet\n"
|
||||
s += "endsolid\n"
|
||||
normals = [tuple(f32(float("%.6e" % c)) for c in unit_normal(t)) for t in t1] + [unit_normal(t) for t in t2]
|
||||
cases.append(("ascii-odd.stl", s.encode(), {"solids": ["first part", ""], "solidFacets": [3, 2], "normals": normals}))
|
||||
# a quad facet (fan-triangulated: trimesh cannot read it, the expectation is computed here)
|
||||
q = [(0.0, 0.0, 0.0), (2.0, 0.0, 0.0), (2.0, 1.0, 0.0), (0.0, 1.0, 0.5)]
|
||||
s = "solid quad\nfacet normal 0 0 1\nouter loop\n" + "".join("vertex %r %r %r\n" % v for v in q) + "endloop\nendfacet\nendsolid quad\n"
|
||||
qt = [[q[0], q[1], q[2]], [q[0], q[2], q[3]]]
|
||||
cases.append(("ascii-quad.stl", s.encode(), {"self": True, "tris": qt, "normals": [(0.0, 0.0, 1.0)] * 2}))
|
||||
# no final endsolid
|
||||
t3 = rand_tris(rng, 2)
|
||||
s = "solid open\n" + "".join("facet normal 0 0 0\nouter loop\n" + "".join("vertex %r %r %r\n" % v for v in t) + "endloop\nendfacet\n" for t in t3)
|
||||
cases.append(("ascii-noend.stl", s.encode(), {"self": True, "tris": t3, "normals": [(0.0, 0.0, 0.0)] * 2}))
|
||||
# binary with trailing bytes (size != 84 + 50 n: trimesh refuses, we tolerate)
|
||||
t4 = rand_tris(rng, 5)
|
||||
n4 = [unit_normal(t) for t in t4]
|
||||
cases.append(("bin-trailing.stl", binary_stl(b"trailing junk", t4, n4, extra=b"JUNK!!!"), {"self": True, "tris": t4, "normals": n4}))
|
||||
return cases
|
||||
|
||||
|
||||
# --- encoder scenes (also used by tests/model/stl.luau for round trips)
|
||||
def quat(rng):
|
||||
q = [rng.uniform(-1, 1) for _ in range(4)]
|
||||
ln = math.sqrt(sum(c * c for c in q))
|
||||
return [c / ln for c in q]
|
||||
|
||||
|
||||
def mmul(a, b):
|
||||
return [[sum(a[i][k] * b[k][j] for k in range(4)) for j in range(4)] for i in range(4)]
|
||||
|
||||
|
||||
def det3(m):
|
||||
return (m[0][0] * (m[1][1] * m[2][2] - m[1][2] * m[2][1]) - m[0][1] * (m[1][0] * m[2][2] - m[1][2] * m[2][0])
|
||||
+ m[0][2] * (m[1][0] * m[2][1] - m[1][1] * m[2][0]))
|
||||
|
||||
|
||||
EYE = [[1.0 if i == j else 0.0 for j in range(4)] for i in range(4)]
|
||||
|
||||
|
||||
def mat_trs(node):
|
||||
"""row-major 4x4 of a node (glTF: column-major matrix, or T * R * S)"""
|
||||
if "matrix" in node:
|
||||
c = node["matrix"]
|
||||
return [[c[j * 4 + i] for j in range(4)] for i in range(4)]
|
||||
x, y, z, w = node.get("rotation", [0, 0, 0, 1])
|
||||
sx, sy, sz = node.get("scale", [1, 1, 1])
|
||||
tx, ty, tz = node.get("translation", [0, 0, 0])
|
||||
r = [
|
||||
[1 - 2 * (y * y + z * z), 2 * (x * y - z * w), 2 * (x * z + y * w)],
|
||||
[2 * (x * y + z * w), 1 - 2 * (x * x + z * z), 2 * (y * z - x * w)],
|
||||
[2 * (x * z - y * w), 2 * (y * z + x * w), 1 - 2 * (x * x + y * y)],
|
||||
]
|
||||
return [[r[0][0] * sx, r[0][1] * sy, r[0][2] * sz, tx], [r[1][0] * sx, r[1][1] * sy, r[1][2] * sz, ty],
|
||||
[r[2][0] * sx, r[2][1] * sy, r[2][2] * sz, tz], [0.0, 0.0, 0.0, 1.0]]
|
||||
|
||||
|
||||
def unpack(fmt, data):
|
||||
n = len(data) // struct.calcsize("<" + fmt)
|
||||
return list(struct.unpack("<%d%s" % (n, fmt), data))
|
||||
|
||||
|
||||
def expected_soup(sc):
|
||||
"""world-space triangles (fan-triangulated polygons, reversed winding under a mirror) as f32 bytes, and the
|
||||
colour of each facet's first vertex"""
|
||||
out, cols = [], []
|
||||
|
||||
def prim_tris(p):
|
||||
n = p["count"]
|
||||
flat = unpack("H" if p.get("posType") == "u16" else "f", p["pos"])
|
||||
pos = [flat[i * 3:i * 3 + 3] for i in range(n)]
|
||||
idx = unpack("I", p["indices"]) if "indices" in p else list(range(n))
|
||||
if p["mode"] == "polygons":
|
||||
tris, at = [], 0
|
||||
for s in unpack("I", p["faces"]):
|
||||
for k in range(1, s - 1):
|
||||
tris.append((idx[at], idx[at + k], idx[at + k + 1]))
|
||||
at += s
|
||||
else:
|
||||
tris = [tuple(idx[i:i + 3]) for i in range(0, len(idx) - len(idx) % 3, 3)]
|
||||
return pos, tris
|
||||
|
||||
def walk(ni, parent):
|
||||
node = sc["nodes"][ni - 1]
|
||||
has = any(k in node for k in ("matrix", "translation", "rotation", "scale"))
|
||||
m = mmul(parent, mat_trs(node)) if has else parent
|
||||
if "mesh" in node:
|
||||
for p in sc["meshes"][node["mesh"] - 1]["prims"]:
|
||||
pos, tris = prim_tris(p)
|
||||
flip = det3(m) < 0
|
||||
w = [[m[i][0] * v[0] + m[i][1] * v[1] + m[i][2] * v[2] + m[i][3] for i in range(3)] for v in pos]
|
||||
col = p.get("color")
|
||||
for a, b, c in tris:
|
||||
if flip:
|
||||
b, c = c, b
|
||||
out.append(w[a] + w[b] + w[c])
|
||||
if col is not None:
|
||||
cols.append(tuple(col[a * 4:a * 4 + 4]))
|
||||
for c in node.get("children", []):
|
||||
walk(c, m)
|
||||
|
||||
for r in sc["roots"]:
|
||||
walk(r, EYE)
|
||||
return b"".join(struct.pack("<9f", *t) for t in out), cols
|
||||
|
||||
|
||||
def pack(fmt, vals):
|
||||
return struct.pack("<%d%s" % (len(vals), fmt), *vals)
|
||||
|
||||
|
||||
def scenes(rng):
|
||||
out = []
|
||||
# grid: indexed, colours on 5-bit steps, no transform
|
||||
W, H = 7, 6
|
||||
pos = [v for y in range(H) for x in range(W) for v in (x * 0.5, y * 0.5, rng.uniform(-1, 1))]
|
||||
idx = []
|
||||
for y in range(H - 1):
|
||||
for x in range(W - 1):
|
||||
a = y * W + x
|
||||
idx += [a, a + 1, a + W + 1, a, a + W + 1, a + W]
|
||||
col = bytes(v for _ in range(W * H) for v in (x8(rng.randrange(32)), x8(rng.randrange(32)), x8(rng.randrange(32)), 255))
|
||||
out.append({"name": "grid", "nodes": [{"mesh": 1, "name": "grid"}], "roots": [1], "meshes": [{"name": "grid", "prims": [
|
||||
{"mode": "triangles", "count": W * H, "pos": pack("f", pos), "indices": pack("I", idx), "color": col}]}],
|
||||
"encodings": ["binary", "ascii", "viscam", "magics"]})
|
||||
# polygons under a TRS node
|
||||
pv = [0, 0, 0, 1, 0, 0, 1, 1, 0, 0, 1, 0, 2, 0, 0, 3, 0.5, 0, 2.5, 1.5, 0.2, 1.5, 1.2, 0.1, 0, 0, 1]
|
||||
corners = [0, 1, 2, 3, 1, 4, 5, 6, 7, 2, 0, 3, 8]
|
||||
out.append({"name": "polys", "nodes": [{"mesh": 1, "translation": [1, 2, 3], "rotation": quat(rng), "scale": [2, 0.5, 1.5]}], "roots": [1],
|
||||
"meshes": [{"name": "polys", "prims": [{"mode": "polygons", "count": 9, "pos": pack("f", pv),
|
||||
"indices": pack("I", corners), "faces": pack("I", [4, 6, 3])}]}],
|
||||
"encodings": ["binary", "ascii"]})
|
||||
# a node tree: a matrix root, a mirrored child (winding flips), a child without its own transform, u16 positions,
|
||||
# a soup without indices
|
||||
soup = [rng.uniform(-3, 3) for _ in range(45)]
|
||||
u16 = [rng.randrange(0, 100) for _ in range(18)]
|
||||
c, s = math.cos(0.7), math.sin(0.7)
|
||||
m = [c, s, 0, 0, -s, c, 0, 0, 0, 0, 1, 0, 5, -2, 0.5, 1] # column-major: rotate about z, translate
|
||||
out.append({"name": "tree", "nodes": [
|
||||
{"mesh": 2, "matrix": m, "children": [2, 3]},
|
||||
{"mesh": 1, "scale": [-1, 1, 1], "translation": [0, 0, 1]},
|
||||
{"mesh": 3, "name": "plain"},
|
||||
], "roots": [1], "meshes": [
|
||||
{"name": "soup", "prims": [{"mode": "triangles", "count": 15, "pos": pack("f", soup)}]},
|
||||
{"name": "u16", "prims": [{"mode": "triangles", "count": 6, "posType": "u16", "pos": pack("H", u16),
|
||||
"indices": pack("I", [0, 1, 2, 2, 3, 4, 4, 5, 0, 1, 3, 5])}]},
|
||||
{"name": "pair", "prims": [{"mode": "triangles", "count": 4, "pos": pack("f", [0, 0, 0, 1, 0, 0, 1, 1, 0, 0, 1, 0.25]),
|
||||
"indices": pack("I", [0, 1, 2, 0, 2, 3])}]},
|
||||
], "encodings": ["binary", "ascii"]})
|
||||
for sc in out:
|
||||
soup_b, cols = expected_soup(sc)
|
||||
sc["expect"] = soup_b
|
||||
sc["exact"] = sc["name"] == "grid"
|
||||
if cols:
|
||||
sc["viscamWords"] = [0x8000 | to5(r) << 10 | to5(g) << 5 | to5(b) for r, g, b, _ in cols]
|
||||
sc["magicsWords"] = [to5(r) | to5(g) << 5 | to5(b) << 10 for r, g, b, _ in cols]
|
||||
return out
|
||||
|
||||
|
||||
def luau_cmd():
|
||||
exe = shutil.which("luau")
|
||||
return [exe] if exe else ["nix", "shell", "nixpkgs#luau", "-c", "luau"]
|
||||
|
||||
|
||||
def assimp_info(ctx, path):
|
||||
txt = ctx.nix("assimp", ["assimp", "info", path]).decode(errors="replace")
|
||||
faces = verts = None
|
||||
for line in txt.split("\n"):
|
||||
if line.startswith("Faces:"):
|
||||
faces = int(line.split()[1])
|
||||
if line.startswith("Vertices:"):
|
||||
verts = int(line.split()[1])
|
||||
return faces, verts
|
||||
|
||||
|
||||
def generate(ctx):
|
||||
rng = ctx.rng(31)
|
||||
tmp = tempfile.mkdtemp(prefix="formats-stl-")
|
||||
try:
|
||||
_generate(ctx, rng, tmp)
|
||||
finally:
|
||||
shutil.rmtree(tmp, ignore_errors=True)
|
||||
|
||||
|
||||
def _generate(ctx, rng, tmp):
|
||||
# scenes first: the encoder script reads them
|
||||
sc = scenes(rng)
|
||||
ctx.emit("stl_scenes", sc)
|
||||
files = {}
|
||||
hand = handmade(rng)
|
||||
for name, data, _ in hand:
|
||||
files[name] = data
|
||||
# assimp conversions: an OBJ with quads and a PLY -> ASCII and binary STL
|
||||
obj = "".join("v %r %r %r\n" % (f32(rng.uniform(-5, 5)), f32(rng.uniform(-5, 5)), f32(rng.uniform(-5, 5))) for _ in range(12))
|
||||
obj += "f 1 2 3 4\nf 5 6 7\nf 8 9 10 11 12\nf 2 4 6\n"
|
||||
ply = "ply\nformat ascii 1.0\nelement vertex 5\nproperty float x\nproperty float y\nproperty float z\nelement face 3\nproperty list uchar int vertex_indices\nend_header\n"
|
||||
ply += "".join("%r %r %r\n" % (f32(rng.uniform(-5, 5)), f32(rng.uniform(-5, 5)), f32(rng.uniform(-5, 5))) for _ in range(5))
|
||||
ply += "3 0 1 2\n4 0 2 3 4\n3 4 3 1\n"
|
||||
with open(os.path.join(tmp, "in.obj"), "w") as f:
|
||||
f.write(obj)
|
||||
with open(os.path.join(tmp, "in.ply"), "w") as f:
|
||||
f.write(ply)
|
||||
for src, dst, fid in (("in.obj", "assimp-obj.stl", "stl"), ("in.obj", "assimp-obj-b.stl", "stlb"), ("in.ply", "assimp-ply-b.stl", "stlb")):
|
||||
ctx.nix("assimp", ["assimp", "export", os.path.join(tmp, src), os.path.join(tmp, dst), "-f" + fid])
|
||||
for name, data in files.items():
|
||||
with open(os.path.join(tmp, name), "wb") as f:
|
||||
f.write(data)
|
||||
make = [["trimesh-icosphere.stl", "icosphere", "stl", 1], ["trimesh-icosphere-ascii.stl", "icosphere", "stl_ascii", 1],
|
||||
["trimesh-box.stl", "box", "stl", 2], ["trimesh-capsule-ascii.stl", "capsule", "stl_ascii", 3],
|
||||
["trimesh-soup.stl", "soup", "stl", 4], ["trimesh-soup-ascii.stl", "soup", "stl_ascii", 5]]
|
||||
refnames = [m[0] for m in make] + ["assimp-obj.stl", "assimp-obj-b.stl", "assimp-ply-b.stl"]
|
||||
refnames += [n for n, _, e in hand if not e.get("self")]
|
||||
# our encoder's output (the luau CLI prints "<scene>/<encoding> <hex>" lines)
|
||||
enc = subprocess.run(luau_cmd() + [os.path.join(ctx.root, "tools", "fixtures", "_stl_encode.luau")], capture_output=True, check=True, cwd=ctx.root).stdout.decode()
|
||||
ours = []
|
||||
byname = {s["name"]: s for s in sc}
|
||||
for line in enc.split("\n"):
|
||||
if not line.strip():
|
||||
continue
|
||||
label, hexdata = line.split(" ", 1)
|
||||
scene_name, encoding = label.split("/")
|
||||
s = byname[scene_name]
|
||||
fn = "ours-%s-%s.stl" % (scene_name, encoding)
|
||||
with open(os.path.join(tmp, fn), "wb") as f:
|
||||
f.write(bytes.fromhex(hexdata.strip()))
|
||||
o = {"name": label, "file": fn, "expect": s["expect"].hex(), "exact": s["exact"]}
|
||||
if encoding == "viscam":
|
||||
o["colors"] = s["viscamWords"]
|
||||
elif encoding == "magics":
|
||||
o["colors"] = s["magicsWords"]
|
||||
ours.append(o)
|
||||
code = open(os.path.join(ctx.root, "tools", "fixtures", "_stl_reference.py")).read()
|
||||
try:
|
||||
res = json.loads(ctx.python(["trimesh", "numpy"], code, input=json.dumps({"dir": tmp, "make": make, "ref": refnames, "ours": ours}).encode()))
|
||||
except subprocess.CalledProcessError as e:
|
||||
raise RuntimeError("stl reference: " + e.stderr.decode(errors="replace")[-3000:])
|
||||
verdicts = []
|
||||
for o in ours:
|
||||
ok, detail = res["ours"][o["name"]]
|
||||
# assimp reads it too
|
||||
faces, _ = assimp_info(ctx, os.path.join(tmp, o["file"]))
|
||||
want = len(bytes.fromhex(o["expect"])) // 36
|
||||
if faces != want:
|
||||
ok, detail = False, "assimp reads %s faces, want %d" % (faces, want)
|
||||
verdicts.append({"name": o["name"], "ok": ok, "detail": detail})
|
||||
cases = []
|
||||
for name in refnames:
|
||||
with open(os.path.join(tmp, name), "rb") as f:
|
||||
data = f.read()
|
||||
r = res["ref"][name]
|
||||
c = {"name": name, "data": data, "facets": r["facets"], "pos_crc": r["pos_crc"], "area": r["area"], "bounds": r["bounds"]}
|
||||
extra = next((e for n, _, e in hand if n == name), {})
|
||||
if "nrm_crc" in r:
|
||||
c["nrm_crc"] = r["nrm_crc"]
|
||||
elif "normals" in extra: # the normals written here (%.6e / repr of f32 values, read as f32)
|
||||
c["nrm_crc"] = crc(b"".join(struct.pack("<3f", *n) * 3 for n in extra["normals"]))
|
||||
if "cols" in extra:
|
||||
c["colors"] = extra["colors"]
|
||||
c["col_crc"] = crc(b"".join(bytes(col) * 3 for col in extra["cols"]))
|
||||
# the colour words trimesh read must be the ones written
|
||||
assert r.get("attr") is not None
|
||||
if "defaultColor" in extra:
|
||||
c["defaultColor"] = extra["defaultColor"]
|
||||
if "words" in extra:
|
||||
assert r["attr"] == extra["words"]
|
||||
c["attr_crc"] = crc(struct.pack("<%dH" % len(extra["words"]), *extra["words"]))
|
||||
if "solids" in extra:
|
||||
c["solids"] = extra["solids"]
|
||||
c["solidFacets"] = extra["solidFacets"]
|
||||
c["binary"] = not data.lstrip()[:5].lower() == b"solid" or (len(data) >= 84 and 84 + 50 * struct.unpack("<I", data[80:84])[0] == len(data))
|
||||
cases.append(c)
|
||||
for name, data, e in hand:
|
||||
if e.get("self"):
|
||||
tris = e["tris"]
|
||||
cases.append({"name": name, "data": data, "facets": len(tris), "pos_crc": crc(soup_bytes(tris)),
|
||||
"nrm_crc": crc(b"".join(struct.pack("<3f", *n) * 3 for n in e["normals"])),
|
||||
"binary": not data.startswith(b"solid")})
|
||||
ctx.emit("stl", {"cases": cases, "ours": verdicts})
|
||||
Reference in new issue
Block a user