557 lines
17 KiB
Luau
557 lines
17 KiB
Luau
--!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
|