diff --git a/src/Formats/codecs/MeshFlatten.luau b/src/Formats/codecs/MeshFlatten.luau new file mode 100644 index 0000000..298a577 --- /dev/null +++ b/src/Formats/codecs/MeshFlatten.luau @@ -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 diff --git a/src/Formats/model/off/init.luau b/src/Formats/model/off/init.luau new file mode 100644 index 0000000..92b4107 --- /dev/null +++ b/src/Formats/model/off/init.luau @@ -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 diff --git a/src/Formats/model/ply/Binary.luau b/src/Formats/model/ply/Binary.luau new file mode 100644 index 0000000..5bfdf92 --- /dev/null +++ b/src/Formats/model/ply/Binary.luau @@ -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 diff --git a/src/Formats/model/ply/init.luau b/src/Formats/model/ply/init.luau new file mode 100644 index 0000000..8b9350e --- /dev/null +++ b/src/Formats/model/ply/init.luau @@ -0,0 +1,1148 @@ +--!strict +-- model/ply: PLY (Stanford polygon file format, Greg Turk 1994), ascii / binary_little_endian / binary_big_endian, +-- read + write. Written from the format description (paulbourke.net/dataformats/ply, the rply / plyfile behaviour). +-- Decode: the vertex element maps x y z -> POSITION f32 x3, nx ny nz -> NORMAL f32 x3, red green blue [alpha] -> +-- COLOR_0 (uchar: unorm8 x4, ushort: unorm16 x4, float / double: f32 x4; alpha full when absent), u v / s t / texture_u +-- texture_v / texture_s texture_t -> TEXCOORD_0 f32 x2, every other property -> "_" .. name in its own type (char -> +-- i8, uchar -> u8, ..., double -> f64). Doubles in x / y / z / normals / texcoords become f32. The face element's +-- vertex_indices / vertex_index list gives the faces: triangles stay triangles (u32 indices), n-gons are +-- fan-triangulated (opts.triangulate, default true: right for convex faces; faces of fewer than 3 vertices are +-- dropped) or kept as mode "polygons" (prim.faces = vertex count per face). No faces: a point cloud (mode "points", +-- no indices). Other face properties: prim.extras.faceAttributes[name] (one value per file face, its own type), face +-- lists: prim.extras.faceLists[name] = { countType, itemType, sizes (u32 accessor), items (accessor) }; after +-- triangulating n-gons prim.extras.faceOfTriangle (u32, 0-based) maps triangles to file faces. Other elements (edge, +-- material, ...) are kept raw in scene.meta.ply.elements (in their types) and written back, as are comments +-- (meta.ply.comments), obj_info lines (meta.ply.objInfo), the element order and the vertex / face property order and +-- types. meta.source = { format, encoding, vertices, faces }. +-- Encode: every primitive in world space (node transforms applied) into one vertex list: POSITION, NORMAL, COLOR_0, +-- TEXCOORD_0 and "_" attributes (under their name, in their type; several components: name_0, name_1, ...), faces +-- (triangles and polygons natively as `property list uchar int vertex_indices`, a wider count / uint index type when +-- needed), point clouds without a face element; lines are skipped. Floats print as %.9g (f32-exact), doubles %.17g. +-- Not supported: list properties in the vertex element (UNSUPPORTED). + +-- ------------------------------------------------------------------------------------------------ requires +local Err = require("@formats/core/Err") +local Bytes = require("@formats/core/Bytes") +local Types = require("@formats/Types") +local Binary = require("@formats/model/ply/Binary") +local Flatten = require("@formats/codecs/MeshFlatten") + +-- ------------------------------------------------------------------------------------------------ contract +local Ply = { + name = "ply", + category = "model", + extensions = { "ply" }, + mime = { "model/ply", "application/ply" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/MeshFlatten" }, + caps = { decode = true, encode = true, ascii = true, binary = true, polygons = true, points = true, colors = true }, +} + +-- ------------------------------------------------------------------------------------------------ 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?, -- faces, and rows of any other element (default 2^25) +} +export type EncodeOptions = { + format: ("binary_little_endian" | "binary_big_endian" | "ascii")?, -- default "binary_little_endian" + comments: { string }?, -- extra comment lines (after those in scene.meta.ply.comments) +} + +type Prop = { name: string, ply: string, code: number, list: boolean, countPly: string?, countCode: number? } +type Elem = { name: string, count: number, props: { Prop } } + +-- ------------------------------------------------------------------------------------------------ constants +local CODES: { [string]: number } = { + char = 1, + int8 = 1, + uchar = 2, + uint8 = 2, + short = 3, + int16 = 3, + ushort = 4, + uint16 = 4, + int = 5, + int32 = 5, + uint = 6, + uint32 = 6, + float = 7, + float32 = 7, + double = 8, + float64 = 8, +} +local ACC_TYPE = { "i8", "u8", "i16", "u16", "i32", "u32", "f32", "f64" } +local PLY_NAME = { "char", "uchar", "short", "ushort", "int", "uint", "float", "double" } +local CODE_OF_ACC: { [string]: number } = { i8 = 1, u8 = 2, i16 = 3, u16 = 4, i32 = 5, u32 = 6, f32 = 7, f64 = 8, unorm8 = 2, unorm16 = 4, snorm8 = 1, snorm16 = 3 } +local RANGE = { { -128, 127 }, { 0, 255 }, { -32768, 32767 }, { 0, 65535 }, { -2147483648, 2147483647 }, { 0, 4294967295 } } +local SIZE = Binary.SIZE +local ENCODINGS = { ascii = true, binary_little_endian = true, binary_big_endian = true } +local MAX_HEADER = 1048576 +local TEXCOORD_PAIRS = { { "u", "v" }, { "s", "t" }, { "texture_u", "texture_v" }, { "texture_s", "texture_t" } } + +-- ------------------------------------------------------------------------------------------------ sniff +function Ply.sniff(r: Bytes.Reader): number + local h = r:peek(4) + return if h == "ply\n" or h == "ply\r" then 1 else 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +type Header = { encoding: string, elems: { Elem }, comments: { string }, objInfo: { string }, dataStart: number } + +local function parseHeader(r: Bytes.Reader): (Header?, Err.Err?) + local b, base, size = r.buf, r.base, r.limit - r.base + local text = buffer.readstring(b, base, math.min(size, MAX_HEADER)) + if string.sub(text, 1, 3) ~= "ply" or not string.match(string.sub(text, 4, 5), "^\r?\n") then + return nil, Err.new(Err.CORRUPT, "bad signature", base) + end + local h: Header = { encoding = "", elems = {}, comments = {}, objInfo = {}, dataStart = -1 } + local at = 1 + local first = true + while true do + local e = string.find(text, "\n", at, true) + if not e then + if size > MAX_HEADER then + return nil, Err.new(Err.LIMIT, "header longer than 1 MB") + end + return nil, Err.new(Err.TRUNCATED, "no end_header", base + at - 1) + end + local line = string.sub(text, at, e - 1) + if string.sub(line, -1) == "\r" then + line = string.sub(line, 1, -2) + end + local lineAt = base + at - 1 + at = e + 1 + local kw = string.match(line, "^%s*(%S+)") + if first then + first = false -- "ply" + elseif kw == nil then + -- blank line + elseif kw == "end_header" then + h.dataStart = base + at - 1 + break + elseif kw == "comment" or kw == "obj_info" then + local rest = string.match(line, "^%s*%S+ ?(.*)$") or "" + table.insert(if kw == "comment" then h.comments else h.objInfo, rest) + elseif kw == "format" then + local enc, ver = string.match(line, "^%s*format%s+(%S+)%s+(%S+)") + if not enc or not ENCODINGS[enc] then + return nil, Err.new(Err.UNSUPPORTED, "unknown format " .. tostring(enc), lineAt) + end + if string.sub(ver, 1, 1) ~= "1" then + return nil, Err.new(Err.UNSUPPORTED, "version " .. ver, lineAt) + end + h.encoding = enc + elseif kw == "element" then + local name, count = string.match(line, "^%s*element%s+(%S+)%s+(%d+)%s*$") + local n = tonumber(count) + if not name or not n then + return nil, Err.new(Err.CORRUPT, "bad element line", lineAt) + end + table.insert(h.elems, { name = name, count = n, props = {} }) + elseif kw == "property" then + local el = h.elems[#h.elems] + if not el then + return nil, Err.new(Err.CORRUPT, "property before any element", lineAt) + end + local words = {} + for w in string.gmatch(line, "%S+") do + table.insert(words, w) + end + local p: Prop + if words[2] == "list" and #words == 5 then + local cc, ic = CODES[words[3]], CODES[words[4]] + if not cc or not ic then + return nil, Err.new(Err.CORRUPT, "unknown property type in " .. line, lineAt) + end + p = { name = words[5], ply = words[4], code = ic, list = true, countPly = words[3], countCode = cc } + elseif #words == 3 and CODES[words[2]] then + p = { name = words[3], ply = words[2], code = CODES[words[2]], list = false } + else + return nil, Err.new(Err.CORRUPT, "bad property line: " .. string.sub(line, 1, 60), lineAt) + end + for _, q in el.props do + if q.name == p.name then + return nil, Err.new(Err.CORRUPT, "duplicate property " .. p.name, lineAt) + end + end + table.insert(el.props, p) + else + return nil, Err.new(Err.CORRUPT, "unknown header line: " .. string.sub(line, 1, 60), lineAt) + end + end + if h.encoding == "" then + return nil, Err.new(Err.CORRUPT, "no format line", base) + end + return h, nil +end + +-- the reading plan of one element: per property, where its values go +type Plan = { + code: { number }, + isList: { boolean }, + countCode: { number }, + dst: { buffer }, + dOff: { number }, + dStride: { number }, + dCode: { number }, + sizes: { buffer }, + bound: { number }, + totals: { number }, +} + +local function newPlan(e: Elem): Plan + local np = #e.props + local pl: Plan = { + code = table.create(np, 0), + isList = table.create(np, false), + countCode = table.create(np, 2), + dst = table.create(np), + dOff = table.create(np, 0), + dStride = table.create(np, 0), + dCode = table.create(np, 0), + sizes = table.create(np), + bound = table.create(np, -1), + totals = table.create(np, 0), + } + for k, p in e.props do + pl.code[k] = p.code + pl.isList[k] = p.list + pl.countCode[k] = p.countCode or 2 + pl.dCode[k] = p.code + pl.dStride[k] = SIZE[p.code] + end + return pl +end + +-- unset scalar destinations get their own native buffer +local function ownBuffers(e: Elem, pl: Plan) + for k, p in e.props do + if not p.list and pl.dst[k] == nil then + pl.dst[k] = buffer.create(e.count * SIZE[p.code]) + end + end +end + +-- read one element's rows (binary) into the plan; returns the next offset or nil, Err +local function readBinary(r: Bytes.Reader, p: number, e: Elem, pl: Plan, be: boolean): (number?, Err.Err?) + local b, limit, n, np = r.buf, r.limit, e.count, #e.props + local hasList, rowSize = false, 0 + for k, pr in e.props do + if pr.list then + hasList = true + rowSize += SIZE[pr.countCode :: number] + else + rowSize += SIZE[pr.code] + end + end + if n * rowSize > limit - p then + return nil, Err.new(Err.TRUNCATED, string.format("element %s: %d rows need at least %d bytes", e.name, n, n * rowSize), p) + end + if not hasList then + ownBuffers(e, pl) + local srcOff = table.create(np, 0) + local o = 0 + for k, pr in e.props do + srcOff[k] = o + o += SIZE[pr.code] + end + Binary.fixed(b, p, n, rowSize, np, srcOff, pl.code, be, pl.dst, pl.dOff, pl.dStride, pl.dCode) + return p + n * rowSize, nil + end + local q, totals = Binary.scan(b, p, limit, n, np, pl.code, pl.isList, pl.countCode, be) + if q < 0 then + return nil, Err.new(if totals == "bad list count" then Err.CORRUPT else Err.TRUNCATED, "element " .. e.name .. ": " .. tostring(totals), p) + end + ownBuffers(e, pl) + for k, pr in e.props do + if pr.list then + pl.totals[k] = totals[k] + pl.sizes[k] = buffer.create(n * 4) + pl.dst[k] = buffer.create(totals[k] * SIZE[pl.dCode[k]]) + end + end + local ok, msg = Binary.rows(b, p, n, np, pl.code, pl.isList, pl.countCode, be, pl.dst, pl.dOff, pl.dStride, pl.dCode, pl.sizes, pl.bound) + if not ok then + return nil, Err.new(Err.CORRUPT, "element " .. e.name .. ": " .. tostring(msg), p) + end + return q, nil +end + +-- a token as a value of type code, or nil +local function value(tok: string?, code: number): number? + if tok == nil then + return nil + end + local v = tonumber(tok) + if v == nil then + return nil + end + local rg = RANGE[code] + if rg and (v ~= v // 1 or v < rg[1] or v > rg[2]) then + return nil + end + return v +end + +-- read one element's rows (ascii) from the token stream +local function readAscii(nextTok: () -> string?, e: Elem, pl: Plan): Err.Err? + ownBuffers(e, pl) + local n = e.count + local listSizes: { [number]: { number } } = {} + local listItems: { [number]: { number } } = {} + for k, p in e.props do + if p.list then + listSizes[k] = table.create(n) + listItems[k] = {} + end + end + local wr = Binary.wr + for i = 0, n - 1 do + for k, p in e.props do + if p.list then + local t = nextTok() + local c = value(t, p.countCode :: number) + if c == nil or c < 0 or c % 1 ~= 0 then + return Err.new(if t == nil then Err.TRUNCATED else Err.CORRUPT, string.format("element %s row %d: bad list count", e.name, i)) + end + listSizes[k][i + 1] = c + local items, bd, code = listItems[k], pl.bound[k], p.code + for _ = 1, c do + local t2 = nextTok() + local v = value(t2, code) + if v == nil then + return Err.new(if t2 == nil then Err.TRUNCATED else Err.CORRUPT, string.format("element %s row %d: bad value", e.name, i)) + end + if bd >= 0 and (v < 0 or v >= bd or v ~= v // 1) then + return Err.new(Err.CORRUPT, string.format("element %s row %d: vertex index out of range", e.name, i)) + end + table.insert(items, v) + end + else + local t = nextTok() + local v = value(t, p.code) + if v == nil then + return Err.new(if t == nil then Err.TRUNCATED else Err.CORRUPT, string.format("element %s row %d: bad %s value", e.name, i, p.name)) + end + wr(pl.dst[k], pl.dOff[k] + i * pl.dStride[k], pl.dCode[k], v) + end + end + end + for k in listSizes do + local sz, items = listSizes[k], listItems[k] + local s = buffer.create(n * 4) + for i = 1, n do + buffer.writeu32(s, (i - 1) * 4, sz[i]) + end + local dc = pl.dCode[k] + local d = buffer.create(#items * SIZE[dc]) + for j = 1, #items do + wr(d, (j - 1) * SIZE[dc], dc, items[j]) + end + pl.sizes[k], pl.dst[k], pl.totals[k] = s, d, #items + end + return nil +end + +local function propIndex(e: Elem, name: string): number? + for k, p in e.props do + if p.name == name then + return k + end + end + return nil +end + +-- vertex element -> attributes: sets the plan's destinations, returns the attribute table +local function planVertex(e: Elem, pl: Plan): ({ [string]: Types.Accessor }?, Err.Err?) + local nv = e.count + local attrs: { [string]: Types.Accessor } = {} + local taken: { [number]: boolean } = {} + for _, p in e.props do + if p.list then + return nil, Err.new(Err.UNSUPPORTED, "list property " .. p.name .. " in the vertex element") + end + end + -- group(attr, names, required, ok, comps, fill): the first `required` names must exist, the others are optional + local function group(attr: string, names: { string }, required: number, ok: (codes: { number }) -> number?, comps: number, fillValue: number?) + local ks: { [number]: number } = {} + local codes = {} + for i, nm in names do + local k = propIndex(e, nm) + if k == nil then + if i <= required then + return + end + else + ks[i] = k + table.insert(codes, e.props[k].code) + end + end + local dc = ok(codes) + if dc == nil then + return + end + local sz = SIZE[dc] + local buf = buffer.create(nv * comps * sz) + if fillValue then + for i = 0, nv - 1 do + Binary.wr(buf, (i * comps + comps - 1) * sz, dc, fillValue) + end + end + for i, k in ks do + pl.dst[k], pl.dOff[k], pl.dStride[k], pl.dCode[k] = buf, (i - 1) * sz, comps * sz, dc + taken[k] = true + end + local accType = if attr == "COLOR_0" and dc == 2 then "unorm8" elseif attr == "COLOR_0" and dc == 4 then "unorm16" else ACC_TYPE[dc] + attrs[attr] = Types.Scene.accessor(buf, accType, comps, nv) + end + local function floats(codes: { number }): number? + for _, c in codes do + if c ~= 7 and c ~= 8 then + return nil + end + end + return 7 + end + local function anyNumber(_codes: { number }): number? + return 7 + end + group("POSITION", { "x", "y", "z" }, 3, anyNumber, 3, nil) + group("NORMAL", { "nx", "ny", "nz" }, 3, floats, 3, nil) + -- colours: one type class for all channels + do + local rk, gk, bk, ak = propIndex(e, "red"), propIndex(e, "green"), propIndex(e, "blue"), propIndex(e, "alpha") + if rk and gk and bk then + local codes = { e.props[rk].code, e.props[gk].code, e.props[bk].code } + if ak then + table.insert(codes, e.props[ak].code) + end + local cls: number? = codes[1] + for _, c in codes do + local a = if c == 8 then 7 else c + local b0 = if cls == 8 then 7 else cls + if a ~= b0 then + cls = nil + end + end + local dc = if cls == 2 then 2 elseif cls == 4 then 4 elseif cls == 7 or cls == 8 then 7 else nil + if dc then + group("COLOR_0", { "red", "green", "blue", "alpha" }, 3, function() + return dc + end, 4, if dc == 2 then 255 elseif dc == 4 then 65535 else 1) + end + end + end + for _, pair in TEXCOORD_PAIRS do + if attrs.TEXCOORD_0 == nil then + group("TEXCOORD_0", pair, 2, floats, 2, nil) + end + end + for k, p in e.props do + if not taken[k] then + local buf = buffer.create(nv * SIZE[p.code]) + pl.dst[k] = buf + attrs["_" .. p.name] = Types.Scene.accessor(buf, ACC_TYPE[p.code], 1, nv) + end + end + return attrs, nil +end + +-- the fan triangulation of faces with sizes / corners; returns indices (u32), triangle count, faceOfTriangle +local function fan(sizes: buffer, corners: buffer, nf: number): (buffer, number, buffer) + local nt = 0 + for f = 0, nf - 1 do + local s = buffer.readu32(sizes, f * 4) + if s >= 3 then + nt += s - 2 + end + end + local idx, fot = buffer.create(nt * 12), buffer.create(nt * 4) + local p, t = 0, 0 + local readu32, writeu32 = buffer.readu32, buffer.writeu32 + for f = 0, nf - 1 do + local s = readu32(sizes, f * 4) + local a = readu32(corners, p * 4) + for k = 1, s - 2 do + writeu32(idx, t * 12, a) + writeu32(idx, t * 12 + 4, readu32(corners, (p + k) * 4)) + writeu32(idx, t * 12 + 8, readu32(corners, (p + k + 1) * 4)) + writeu32(fot, t * 4, f) + t += 1 + end + p += s + end + return idx, nt, fot +end + +function Ply.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 h, herr = parseHeader(r) + if not h then + return nil, herr + end + local vi, fi, idxK + for i, e in h.elems do + if e.name == "vertex" and vi == nil then + vi = i + if e.count > maxVertices then + return nil, Err.new(Err.LIMIT, string.format("%d vertices is over the %d vertex limit", e.count, maxVertices)) + end + elseif e.name == "face" and fi == nil then + local k = propIndex(e, "vertex_indices") or propIndex(e, "vertex_index") + if k and e.props[k].list then + fi, idxK = i, k + end + end + if e.count > maxFaces then + return nil, Err.new(Err.LIMIT, string.format("element %s: %d rows is over the %d limit", e.name, e.count, maxFaces)) + end + end + if vi == nil then + return nil, Err.new(Err.CORRUPT, "no vertex element") + end + local nv = h.elems[vi].count + local be = h.encoding == "binary_big_endian" + local ascii = h.encoding == "ascii" + local nextTok: () -> string? = function() + return nil + end + if ascii then + local body = buffer.readstring(r.buf, h.dataStart, r.limit - h.dataStart) + -- each value takes at least 2 bytes (a digit and a separator): bound the counts before allocating + local need = 0 + for _, e in h.elems do + need += e.count * #e.props + end + if need > (#body + 1) // 2 then + return nil, Err.new(Err.TRUNCATED, "fewer values than the element counts need", h.dataStart) + end + nextTok = string.gmatch(body, "%S+") :: any + end + local plans: { Plan } = {} + local attrs: { [string]: Types.Accessor } = {} + local p = h.dataStart + if not ascii then + -- every row takes at least its scalar sizes and list counts: bound the counts before allocating + local need = 0 + for _, e in h.elems do + local row = 0 + for _, pr in e.props do + row += SIZE[if pr.list then pr.countCode :: number else pr.code] + end + need += e.count * row + end + if need > r.limit - h.dataStart then + return nil, Err.new(Err.TRUNCATED, string.format("the elements need at least %d bytes, %d left", need, r.limit - h.dataStart), h.dataStart) + end + end + for i, e in h.elems do + local pl = newPlan(e) + plans[i] = pl + if i == vi then + local a, aerr = planVertex(e, pl) + if not a then + return nil, aerr + end + attrs = a + elseif i == fi then + pl.dCode[idxK] = 6 + pl.bound[idxK] = nv + end + if ascii then + local err = readAscii(nextTok, e, pl) + if err then + return nil, err + end + else + local q, err = readBinary(r, p, e, pl, be) + if not q then + return nil, err + end + p = q + end + end + -- the primitive + local prim: Types.Primitive = { attributes = attrs, mode = "points" } + local nf = 0 + local extras: { [string]: any } = {} + local faceProps: { any } = {} + if fi then + local e, pl = h.elems[fi], plans[fi] + nf = e.count + local sizes, corners, total = pl.sizes[idxK], pl.dst[idxK], pl.totals[idxK] + local faceAttributes: { [string]: Types.Accessor } = {} + local faceLists: { [string]: any } = {} + local anyExtra = false + for k, pr in e.props do + table.insert(faceProps, { name = pr.name, type = pr.ply, countType = pr.countPly }) + if k ~= idxK then + anyExtra = true + if pr.list then + faceLists[pr.name] = { + countType = pr.countPly, + itemType = pr.ply, + sizes = Types.Scene.accessor(pl.sizes[k], "u32", 1, nf), + items = Types.Scene.accessor(pl.dst[k], ACC_TYPE[pr.code], 1, pl.totals[k]), + } + else + faceAttributes[pr.name] = Types.Scene.accessor(pl.dst[k], ACC_TYPE[pr.code], 1, nf) + end + end + end + if next(faceAttributes) then + extras.faceAttributes = faceAttributes + end + if next(faceLists) then + extras.faceLists = faceLists + end + if nf > 0 then + 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(corners, "u32", 1, total) + elseif triangulate then + local idx, nt, fot = fan(sizes, corners, nf) + prim.mode = "triangles" + prim.indices = Types.Scene.accessor(idx, "u32", 1, nt * 3) + if anyExtra then + extras.faceOfTriangle = Types.Scene.accessor(fot, "u32", 1, nt) + end + else + prim.mode = "polygons" + prim.indices = Types.Scene.accessor(corners, "u32", 1, total) + prim.faces = Types.Scene.accessor(sizes, "u32", 1, nf) + end + end + end + if next(extras) then + prim.extras = extras + end + -- raw elements, element order, property order + local elements: { any } = {} + local order: { string } = {} + for i, e in h.elems do + table.insert(order, e.name) + if i ~= vi and i ~= fi then + local pl = plans[i] + local props = {} + for k, pr in e.props do + props[k] = { name = pr.name, type = pr.ply, countType = pr.countPly, values = pl.dst[k], sizes = pl.sizes[k], total = if pr.list then pl.totals[k] else nil } + end + table.insert(elements, { name = e.name, count = e.count, properties = props }) + end + end + local vprops = {} + for _, pr in h.elems[vi].props do + table.insert(vprops, { name = pr.name, type = pr.ply }) + end + local scene = Types.Scene.fromPrimitive(prim, nil) + scene.meta.source = { format = "ply", encoding = h.encoding, vertices = nv, faces = nf } + scene.meta.ply = { + comments = h.comments, + objInfo = h.objInfo, + elements = elements, + order = order, + vertexProperties = vprops, + faceProperties = if fi then faceProps else nil, + } + return scene, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +-- a column to write: ply type code + spelling, the values (one per row, or per row * stride at offset) +type Column = { name: string, ply: string, code: number, values: { number }, stride: number, offset: number } +type ListColumn = { name: string, ply: string, code: number, countPly: string, countCode: number, sizes: { number }, items: { number } } + +local function keep(name: string): boolean + return name == "NORMAL" or name == "COLOR_0" or name == "TEXCOORD_0" or string.sub(name, 1, 1) == "_" +end + +-- the spelling `want` from the source file when it means the same type as code, else the classic name +local function spell(want: string?, code: number): string + if want and CODES[want] == code then + return want + end + return PLY_NAME[code] +end + +local function toInt(v: number, code: number): number + local rg = RANGE[code] + if rg then + if v ~= v then + return 0 + end + return math.clamp(math.floor(v + 0.5), rg[1], rg[2]) + end + return v +end + +-- write rows of columns (+ list columns, in `order`) for n rows: ascii lines into out, binary into the writer +type Row = { kind: "s", col: Column } | { kind: "l", col: ListColumn } + +local function rowsAscii(out: { string }, n: number, cols: { Row }) + local fmt = string.format + local function num(code: number, v: number): string + if code == 7 then + return fmt("%.9g", v) + elseif code == 8 then + return fmt("%.17g", v) + end + return fmt("%d", toInt(v, code)) + end + local at: { [number]: number } = {} + for i = 0, n - 1 do + local parts = {} + for k, c in cols do + if c.kind == "s" then + local col = c.col :: Column + table.insert(parts, num(col.code, col.values[i * col.stride + col.offset + 1])) + else + local col = c.col :: ListColumn + local s = col.sizes[i + 1] + table.insert(parts, fmt("%d", s)) + local a = at[k] or 0 + for j = 1, s do + table.insert(parts, num(col.code, col.items[a + j])) + end + at[k] = a + s + end + end + table.insert(out, table.concat(parts, " ")) + end +end + +local function rowsBinary(w: Bytes.Writer, n: number, cols: { Row }, be: boolean) + local size = 0 + for _, c in cols do + if c.kind == "s" then + size += n * SIZE[(c.col :: Column).code] + else + local col = c.col :: ListColumn + size += n * SIZE[col.countCode] + #col.items * SIZE[col.code] + end + end + local o = w:reserve(size) + local d = w.buf + local put = Binary.put + local at: { [number]: number } = {} + for i = 0, n - 1 do + for k, c in cols do + if c.kind == "s" then + local col = c.col :: Column + local code = col.code + put(d, o, code, toInt(col.values[i * col.stride + col.offset + 1], code), be) + o += SIZE[code] + else + local col = c.col :: ListColumn + local s = col.sizes[i + 1] + put(d, o, col.countCode, s, be) + o += SIZE[col.countCode] + local a, code = at[k] or 0, col.code + for j = 1, s do + put(d, o, code, toInt(col.items[a + j], code), be) + o += SIZE[code] + end + at[k] = a + s + end + end + end + w.pos = o +end + +-- numbers of a raw element column (buffer of a ply type) +local function bufNumbers(b: any, code: number, count: number): { number }? + if type(b) ~= "buffer" or buffer.len(b) < count * SIZE[code] then + return nil + end + local out = table.create(count) + for i = 0, count - 1 do + out[i + 1] = Binary.rd(b, i * SIZE[code], code, false) + end + return out +end + +-- the list count type for a maximum count +local function countCodeFor(maxCount: number): number + return if maxCount <= 255 then 2 elseif maxCount <= 65535 then 4 else 6 +end + +function Ply.encode(scene: Types.Scene, opts: EncodeOptions?): (buffer?, Err.Err?) + local o: EncodeOptions = opts or {} + local enc = o.format or "binary_little_endian" + if not ENCODINGS[enc] then + return nil, Err.new(Err.ARG, "format must be ascii, binary_little_endian or binary_big_endian") + end + local m, merr = Flatten.merge(scene, keep, { triangulate = false }) + if not m then + return nil, Err.new(Err.ARG, tostring(merr)) + end + local meta: any = if type(scene) == "table" and type(scene.meta) == "table" and type(scene.meta.ply) == "table" then scene.meta.ply else {} + local nv = m.count + -- source property spellings / order + local srcType: { [string]: string } = {} + local srcOrder: { [string]: number } = {} + if type(meta.vertexProperties) == "table" then + for i, vp in meta.vertexProperties do + if type(vp) == "table" and type(vp.name) == "string" then + srcType[vp.name] = vp.type + srcOrder[vp.name] = i + end + end + end + local cols: { Column } = {} + local function add(name: string, code: number, a: Flatten.Attr, comp: number) + table.insert(cols, { name = name, ply = spell(srcType[name], code), code = code, values = a.values, stride = a.components, offset = comp }) + end + local function floatCode(name: string): number + return if CODES[srcType[name] or ""] == 8 then 8 else 7 + end + local A = m.attrs + for i, nm in { "x", "y", "z" } do + add(nm, floatCode(nm), A.POSITION, i - 1) + end + if A.NORMAL then + for i, nm in { "nx", "ny", "nz" } do + add(nm, floatCode(nm), A.NORMAL, i - 1) + end + end + local C = A.COLOR_0 + if C then + local code = if C.raw and C.type == "unorm8" then 2 elseif C.raw and C.type == "unorm16" then 4 else 7 + if C.raw and code == 7 then + -- another normalized type: as floats + local vals = table.create(#C.values) + local scale = if C.type == "snorm8" then 127 else 32767 + for i, v in C.values do + vals[i] = math.max(v / scale, -1) + end + C = { type = "f32", components = C.components, raw = false, values = vals } + end + local cc = C :: Flatten.Attr + for i, nm in { "red", "green", "blue" } do + if i <= cc.components then + add(nm, code, cc, i - 1) + end + end + if cc.components >= 4 then + local full = if code == 2 then 255 elseif code == 4 then 65535 else 1 + local need = srcOrder.alpha ~= nil + if not need then + for i = 0, nv - 1 do + if cc.values[i * cc.components + 4] ~= full then + need = true + break + end + end + end + if need then + add("alpha", code, cc, 3) + end + end + end + if A.TEXCOORD_0 then + local names = { "s", "t" } + for _, pair in TEXCOORD_PAIRS do + if srcOrder[pair[1]] and srcOrder[pair[2]] then + names = pair + break + end + end + local tc = A.TEXCOORD_0 + if tc.raw then + return nil, Err.new(Err.ARG, "TEXCOORD_0 of a normalized integer type") + end + add(names[1], floatCode(names[1]), tc, 0) + if tc.components >= 2 then + add(names[2], floatCode(names[2]), tc, 1) + end + end + local customs = {} + for name in A do + if string.sub(name, 1, 1) == "_" then + table.insert(customs, name) + end + end + table.sort(customs) + for _, name in customs do + local a = A[name] + local code = CODE_OF_ACC[a.type] or 7 + local base = string.sub(name, 2) + if a.components == 1 then + add(base, code, a, 0) + else + for c = 0, a.components - 1 do + add(base .. "_" .. c, code, a, c) + end + end + end + -- the source order first (stable for the rest) + local rank: { [Column]: number } = {} + for i, c in cols do + rank[c] = (srcOrder[c.name] or (1000000 + i)) + end + table.sort(cols, function(a: Column, b: Column): boolean + return rank[a] < rank[b] + end) + -- faces + local faceRows: { Row }? = nil + local nf = 0 + if m.sizes then + local sizes = m.sizes :: { number } + nf = #sizes + local maxS, maxI = 0, 0 + for _, s in sizes do + maxS = math.max(maxS, s) + end + for _, c in m.corners do + maxI = math.max(maxI, c) + end + local fprops: { any } = if type(meta.faceProperties) == "table" then meta.faceProperties else {} + local idxName, idxType, idxCount = "vertex_indices", nil, nil + for _, fp in fprops do + if type(fp) == "table" and (fp.name == "vertex_indices" or fp.name == "vertex_index") then + idxName, idxType, idxCount = fp.name, fp.type, fp.countType + end + end + local cc = countCodeFor(maxS) + local srcCC = CODES[idxCount or ""] + if srcCC and srcCC <= 6 and SIZE[srcCC] >= SIZE[cc] then + cc = srcCC + end + local ic = if maxI < 2147483648 then 5 else 6 + local srcIC = CODES[idxType or ""] + if srcIC == 6 or (srcIC and srcIC <= 6 and maxI <= RANGE[srcIC][2]) then + ic = srcIC + end + local rows: { Row } = { + { kind = "l", col = { name = idxName, ply = spell(idxType, ic), code = ic, countPly = spell(idxCount, cc), countCode = cc, sizes = sizes, items = m.corners } }, + } + -- per-face data of a single primitive + if #m.parts == 1 then + local ex = m.parts[1].prim.extras + local fot: { number }? = nil + if type(ex) == "table" and ex.faceOfTriangle then + fot = Flatten.numbers(ex.faceOfTriangle, true) + end + local function perFace(vals: { number }, count: number): { number }? + if count == nf then + return vals + elseif fot and #fot == nf then + local out = table.create(nf) + for i = 1, nf do + local v = vals[fot[i] + 1] + if v == nil then + return nil + end + out[i] = v + end + return out + end + return nil + end + local extraRows: { [string]: Row } = {} + if type(ex) == "table" and type(ex.faceAttributes) == "table" then + for name, acc in ex.faceAttributes do + local vals = Flatten.numbers(acc, true) + local code = CODE_OF_ACC[acc.type] + if vals and code and acc.components == 1 then + local pv = perFace(vals, acc.count) + if pv then + extraRows[name] = { kind = "s", col = { name = name, ply = PLY_NAME[code], code = code, values = pv, stride = 1, offset = 0 } } + end + end + end + end + if type(ex) == "table" and type(ex.faceLists) == "table" then + for name, fl in ex.faceLists do + local sz = type(fl) == "table" and Flatten.numbers(fl.sizes, true) + local items = type(fl) == "table" and Flatten.numbers(fl.items, true) + local code = type(fl) == "table" and (CODES[fl.itemType or ""] or CODE_OF_ACC[fl.items and fl.items.type or ""]) + if sz and items and code and #sz == nf and fot == nil then + local mx = 0 + for _, s in sz do + mx = math.max(mx, s) + end + local lcc = countCodeFor(mx) + local scc = CODES[fl.countType or ""] + if scc and scc <= 6 and SIZE[scc] >= SIZE[lcc] then + lcc = scc + end + extraRows[name] = { kind = "l", col = { name = name, ply = spell(fl.itemType, code), code = code, countPly = spell(fl.countType, lcc), countCode = lcc, sizes = sz, items = items } } + end + end + end + -- the source order, then the rest by name + local placed: { [string]: boolean } = { [idxName] = true } + local ordered: { Row } = {} + for _, fp in fprops do + if type(fp) == "table" then + if fp.name == idxName then + table.insert(ordered, rows[1]) + elseif extraRows[fp.name] then + table.insert(ordered, extraRows[fp.name]) + placed[fp.name] = true + end + end + end + if not table.find(ordered, rows[1]) then + table.insert(ordered, 1, rows[1]) + end + local rest = {} + for name in extraRows do + if not placed[name] then + table.insert(rest, name) + end + end + table.sort(rest) + for _, name in rest do + table.insert(ordered, extraRows[name]) + end + rows = ordered + end + faceRows = rows + end + -- raw elements + type Raw = { name: string, count: number, rows: { Row } } + local raws: { [string]: Raw } = {} + local rawOrder: { string } = {} + if type(meta.elements) == "table" then + for _, el in meta.elements do + if type(el) == "table" and type(el.name) == "string" and type(el.count) == "number" and type(el.properties) == "table" and el.name ~= "vertex" and not raws[el.name] then + if el.name == "face" and faceRows then + continue + end + local rows: { Row } = {} + for _, pr in el.properties do + local code = CODES[pr.type or ""] + if not code then + return nil, Err.new(Err.ARG, "element " .. el.name .. ": unknown property type") + end + if pr.countType then + local cc = CODES[pr.countType] + local sz = cc and bufNumbers(pr.sizes, 6, el.count) + local total = 0 + if sz then + for _, s in sz do + total += s + end + end + local items = sz and bufNumbers(pr.values, code, total) + if not (cc and sz and items) then + return nil, Err.new(Err.ARG, "element " .. el.name .. ": bad list property " .. tostring(pr.name)) + end + table.insert(rows, { kind = "l", col = { name = pr.name, ply = pr.type, code = code, countPly = pr.countType, countCode = cc, sizes = sz, items = items } }) + else + local vals = bufNumbers(pr.values, code, el.count) + if not vals then + return nil, Err.new(Err.ARG, "element " .. el.name .. ": bad property " .. tostring(pr.name)) + end + table.insert(rows, { kind = "s", col = { name = pr.name, ply = pr.type, code = code, values = vals, stride = 1, offset = 0 } }) + end + end + raws[el.name] = { name = el.name, count = el.count, rows = rows } + table.insert(rawOrder, el.name) + end + end + end + -- element order: the source's, then vertex, face, the rest + local order: { string } = {} + local seen: { [string]: boolean } = {} + local function want(name: string) + if seen[name] then + return + end + if name == "vertex" or (name == "face" and faceRows) or raws[name] then + seen[name] = true + table.insert(order, name) + end + end + if type(meta.order) == "table" then + for _, name in meta.order do + if type(name) == "string" then + want(name) + end + end + end + want("vertex") + want("face") + for _, name in rawOrder do + want(name) + end + -- header + local vrows: { Row } = {} + for _, c in cols do + table.insert(vrows, { kind = "s", col = c }) + end + local lines = { "ply", "format " .. enc .. " 1.0" } + local function noNewline(s: any): string + return (string.gsub(tostring(s), "[\r\n]", " ")) + end + for _, c in (if type(meta.comments) == "table" then meta.comments else {}) :: { any } do + table.insert(lines, "comment " .. noNewline(c)) + end + for _, c in o.comments or {} do + table.insert(lines, "comment " .. noNewline(c)) + end + for _, c in (if type(meta.objInfo) == "table" then meta.objInfo else {}) :: { any } do + table.insert(lines, "obj_info " .. noNewline(c)) + end + local function elementRows(name: string): (number, { Row }) + if name == "vertex" then + return nv, vrows + elseif name == "face" and faceRows then + return nf, faceRows + end + local raw = raws[name] + return raw.count, raw.rows + end + for _, name in order do + local n, rows = elementRows(name) + table.insert(lines, "element " .. noNewline(name) .. " " .. string.format("%d", n)) + for _, rw in rows do + if rw.kind == "s" then + local c = rw.col :: Column + table.insert(lines, "property " .. c.ply .. " " .. noNewline(c.name)) + else + local c = rw.col :: ListColumn + table.insert(lines, "property list " .. c.countPly .. " " .. c.ply .. " " .. noNewline(c.name)) + end + end + end + table.insert(lines, "end_header") + local header = table.concat(lines, "\n") .. "\n" + if enc == "ascii" then + local out = { header } + local body: { string } = {} + for _, name in order do + local n, rows = elementRows(name) + rowsAscii(body, n, rows) + end + if #body > 0 then + table.insert(out, table.concat(body, "\n")) + table.insert(out, "\n") + end + return buffer.fromstring(table.concat(out)), nil + end + local w = Bytes.writer(#header + nv * 32 + nf * 16) + w:string(header) + for _, name in order do + local n, rows = elementRows(name) + rowsBinary(w, n, rows, enc == "binary_big_endian") + end + return w:finish(), nil +end + +return Ply diff --git a/src/Formats/model/stl/Decode.luau b/src/Formats/model/stl/Decode.luau new file mode 100644 index 0000000..d99ad3c --- /dev/null +++ b/src/Formats/model/stl/Decode.luau @@ -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 diff --git a/src/Formats/model/stl/init.luau b/src/Formats/model/stl/init.luau new file mode 100644 index 0000000..50cfe41 --- /dev/null +++ b/src/Formats/model/stl/init.luau @@ -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 diff --git a/tests/model/off.luau b/tests/model/off.luau new file mode 100644 index 0000000..5a72e5b --- /dev/null +++ b/tests/model/off.luau @@ -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() diff --git a/tests/model/ply.luau b/tests/model/ply.luau new file mode 100644 index 0000000..961f453 --- /dev/null +++ b/tests/model/ply.luau @@ -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 } = { [" 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() diff --git a/tools/fixtures/_off_encode.luau b/tools/fixtures/_off_encode.luau new file mode 100644 index 0000000..2fbb49c --- /dev/null +++ b/tools/fixtures/_off_encode.luau @@ -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 "/ " 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 diff --git a/tools/fixtures/_off_reference.py b/tools/fixtures/_off_reference.py new file mode 100644 index 0000000..89f961a --- /dev/null +++ b/tools/fixtures/_off_reference.py @@ -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("= 0: + res["faces"] = [[int(x) for x in f] for f in np.asarray(faces)] + out[name] = res +json.dump(out, sys.stdout) diff --git a/tools/fixtures/_ply_encode.luau b/tools/fixtures/_ply_encode.luau new file mode 100644 index 0000000..0418d8a --- /dev/null +++ b/tools/fixtures/_ply_encode.luau @@ -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 "/ " 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 diff --git a/tools/fixtures/_ply_reference.py b/tools/fixtures/_ply_reference.py new file mode 100644 index 0000000..99e5381 --- /dev/null +++ b/tools/fixtures/_ply_reference.py @@ -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", "" 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(" 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) diff --git a/tools/fixtures/_stl_encode.luau b/tools/fixtures/_stl_encode.luau new file mode 100644 index 0000000..df10a1f --- /dev/null +++ b/tools/fixtures/_stl_encode.luau @@ -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 "/ " 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 diff --git a/tools/fixtures/_stl_reference.py b/tools/fixtures/_stl_reference.py new file mode 100644 index 0000000..efbd5f1 --- /dev/null +++ b/tools/fixtures/_stl_reference.py @@ -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, " 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) diff --git a/tools/fixtures/off.py b/tools/fixtures/off.py new file mode 100644 index 0000000..a44c626 --- /dev/null +++ b/tools/fixtures/off.py @@ -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(" 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}) diff --git a/tools/fixtures/ply.py b/tools/fixtures/ply.py new file mode 100644 index 0000000..327f05b --- /dev/null +++ b/tools/fixtures/ply.py @@ -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(" 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}) diff --git a/tools/fixtures/stl.py b/tools/fixtures/stl.py new file mode 100644 index 0000000..c5baef9 --- /dev/null +++ b/tools/fixtures/stl.py @@ -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(" 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 "/ " 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("