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

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

No files matched your search

+556
View File
@@ -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
+480
View File
@@ -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
+212
View File
@@ -0,0 +1,212 @@
--!strict
--!native
--!optimize 2
-- model/ply/Binary: PLY element data loops. Value read / write by type code (1 i8, 2 u8, 3 i16, 4 u16, 5 i32, 6 u32,
-- 7 f32, 8 f64) in either byte order, the column copy of fixed-size rows (scalar properties only) and the row walk of
-- rows with lists (a scan for the list totals, then the fill). The caller (init) sizes every destination from the
-- header counts and the scan, and checks the rows fit in the data first, so every index here is in range; a bad list
-- count or an out-of-range vertex index returns false / -1 with a message. Nothing here throws.
local readu8, readi8, readu16, readi16, readu32, readi32 = buffer.readu8, buffer.readi8, buffer.readu16, buffer.readi16, buffer.readu32, buffer.readi32
local readf32, readf64 = buffer.readf32, buffer.readf64
local writeu8, writei8, writeu16, writei16, writeu32, writei32 = buffer.writeu8, buffer.writei8, buffer.writeu16, buffer.writei16, buffer.writeu32, buffer.writei32
local writef32, writef64 = buffer.writef32, buffer.writef64
local byteswap, band, rshift = bit32.byteswap, bit32.band, bit32.rshift
local Binary = {}
Binary.SIZE = { 1, 1, 2, 2, 4, 4, 4, 8 }
local SIZE = Binary.SIZE
local scratch = buffer.create(8)
local function swap16(v: number): number
return rshift(v, 8) + band(v, 255) * 256
end
-- rd(b, q, code, be) -> the value at q
local function rd(b: buffer, q: number, code: number, be: boolean): number
if not be then
if code == 7 then
return readf32(b, q)
elseif code == 2 then
return readu8(b, q)
elseif code == 5 then
return readi32(b, q)
elseif code == 6 then
return readu32(b, q)
elseif code == 8 then
return readf64(b, q)
elseif code == 1 then
return readi8(b, q)
elseif code == 3 then
return readi16(b, q)
end
return readu16(b, q)
end
if code <= 2 then
return if code == 1 then readi8(b, q) else readu8(b, q)
elseif code <= 4 then
local v = swap16(readu16(b, q))
return if code == 3 and v >= 32768 then v - 65536 else v
elseif code <= 7 then
local v = byteswap(readu32(b, q))
if code == 6 then
return v
elseif code == 5 then
return if v >= 2147483648 then v - 4294967296 else v
end
writeu32(scratch, 0, v)
return readf32(scratch, 0)
end
writeu32(scratch, 0, byteswap(readu32(b, q + 4)))
writeu32(scratch, 4, byteswap(readu32(b, q)))
return readf64(scratch, 0)
end
Binary.rd = rd
-- wr(d, o, code, v): v as code, little endian
local function wr(d: buffer, o: number, code: number, v: number)
if code == 7 then
writef32(d, o, v)
elseif code == 6 then
writeu32(d, o, v)
elseif code == 5 then
writei32(d, o, v)
elseif code == 2 then
writeu8(d, o, v)
elseif code == 8 then
writef64(d, o, v)
elseif code == 1 then
writei8(d, o, v)
elseif code == 3 then
writei16(d, o, v)
else
writeu16(d, o, v)
end
end
Binary.wr = wr
-- put(d, o, code, v, be): v as code in either byte order (the writer)
function Binary.put(d: buffer, o: number, code: number, v: number, be: boolean)
if not be or code <= 2 then
wr(d, o, code, v)
return
end
wr(scratch, 0, code, v)
if code <= 4 then
writeu16(d, o, swap16(readu16(scratch, 0)))
elseif code <= 7 then
writeu32(d, o, byteswap(readu32(scratch, 0)))
else
writeu32(d, o, byteswap(readu32(scratch, 4)))
writeu32(d, o + 4, byteswap(readu32(scratch, 0)))
end
end
-- fixed(b, p, n, rowSize, np, srcOff, code, be, dst, dOff, dStride, dCode): column copies of n fixed-size rows at p
function Binary.fixed(b: buffer, p: number, n: number, rowSize: number, np: number, srcOff: { number }, code: { number }, be: boolean, dst: { buffer }, dOff: { number }, dStride: { number }, dCode: { number })
for k = 1, np do
local sc, dc, d = code[k], dCode[k], dst[k]
local q0, o0, st = p + srcOff[k], dOff[k], dStride[k]
if sc == dc and not be then
local sz = SIZE[sc]
if sz == 4 then
for i = 0, n - 1 do
writeu32(d, o0 + i * st, readu32(b, q0 + i * rowSize))
end
elseif sz == 1 then
for i = 0, n - 1 do
writeu8(d, o0 + i * st, readu8(b, q0 + i * rowSize))
end
elseif sz == 2 then
for i = 0, n - 1 do
writeu16(d, o0 + i * st, readu16(b, q0 + i * rowSize))
end
else
for i = 0, n - 1 do
writeu32(d, o0 + i * st, readu32(b, q0 + i * rowSize))
writeu32(d, o0 + i * st + 4, readu32(b, q0 + i * rowSize + 4))
end
end
else
for i = 0, n - 1 do
wr(d, o0 + i * st, dc, rd(b, q0 + i * rowSize, sc, be))
end
end
end
end
-- scan(b, p, limit, n, np, code, isList, countCode, be) -> the end offset and the item total of each list property,
-- or -1, message (truncated rows, a negative / fractional count)
function Binary.scan(b: buffer, p: number, limit: number, n: number, np: number, code: { number }, isList: { boolean }, countCode: { number }, be: boolean): (number, any)
local totals = table.create(np, 0)
local q = p
for _ = 1, n do
for k = 1, np do
if isList[k] then
local cc = countCode[k]
local csz = SIZE[cc]
if q + csz > limit then
return -1, "list runs past the end"
end
local c = rd(b, q, cc, be)
if c < 0 or c ~= c // 1 then
return -1, "bad list count"
end
q += csz + c * SIZE[code[k]]
if q > limit then
return -1, "list runs past the end"
end
totals[k] += c
else
q += SIZE[code[k]]
if q > limit then
return -1, "row runs past the end"
end
end
end
end
return q, totals
end
-- rows(b, p, n, np, code, isList, countCode, be, dst, dOff, dStride, dCode, sizes, bound) -> true | false, message.
-- Scalars go to dst[k] at dOff + row * dStride as dCode; lists write their count to sizes[k] (u32 per row) and their
-- items one after the other into dst[k] as dCode; bound[k] >= 0 checks items are integers in 0 .. bound - 1. The rows
-- must have passed scan() with the same arguments.
function Binary.rows(b: buffer, p: number, n: number, np: number, code: { number }, isList: { boolean }, countCode: { number }, be: boolean, dst: { buffer }, dOff: { number }, dStride: { number }, dCode: { number }, sizes: { buffer }, bound: { number }): (boolean, string?)
local at = table.create(np, 0)
local q = p
for i = 0, n - 1 do
for k = 1, np do
local sc, dc, d = code[k], dCode[k], dst[k]
if isList[k] then
local cc = countCode[k]
local c = rd(b, q, cc, be)
q += SIZE[cc]
writeu32(sizes[k], i * 4, c)
local ia, ssz, dsz, bd = at[k], SIZE[sc], SIZE[dc], bound[k]
if bd >= 0 then
for j = 0, c - 1 do
local v = rd(b, q, sc, be)
q += ssz
if v < 0 or v >= bd or v ~= v // 1 then
return false, "vertex index out of range"
end
wr(d, (ia + j) * dsz, dc, v)
end
else
for j = 0, c - 1 do
wr(d, (ia + j) * dsz, dc, rd(b, q, sc, be))
q += ssz
end
end
at[k] = ia + c
else
wr(d, dOff[k] + i * dStride[k], dc, rd(b, q, sc, be))
q += SIZE[sc]
end
end
end
return true, nil
end
return Binary
File diff suppressed because it is too large. Load diff
+77
View File
@@ -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
+467
View File
@@ -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