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

+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