904 lines
27 KiB
Luau
904 lines
27 KiB
Luau
--!strict
|
|
-- model/vox: MagicaVoxel .vox, from ephtracy's spec (voxel-model/MagicaVoxel-file-format-vox.txt and -vox-extension.txt)
|
|
-- and the files MagicaVoxel 0.99.x saves (version 150 and 200).
|
|
-- Reads every chunk: SIZE + XYZI models, RGBA palette (the default palette when absent), the scene graph (nTRN / nGRP /
|
|
-- nSHP, with names, hidden flags, layers, 90-degree rotations, translations and animation frames), MATL materials,
|
|
-- LAYR layers, rOBJ render settings, rCAM cameras, NOTE palette notes, IMAP, META; PACK and MATT (old) and unknown
|
|
-- chunks are kept raw and written back.
|
|
-- decode -> a Scene (meta.up = "z", units = voxels): scene.voxels holds the grids (Types.Voxels: size, one byte per
|
|
-- cell, palette, materials), each scene node from an nTRN, its nGRP children as node.children, its nSHP model as
|
|
-- node.voxels. Vox.decodeVoxels gives the grids alone. Meshes: ops/MeshOps.meshVoxels(scene) (greedy meshing; a shape is
|
|
-- centred on its node like MagicaVoxel does: cell (x, y, z) spans x - floor(sx / 2) .. + 1). A format never meshes.
|
|
-- encode <- a Scene with voxels (or one Types.Voxels): models, the node tree back as nTRN / nGRP / nSHP (rotations must
|
|
-- be multiples of 90 degrees; translations are rounded to whole voxels), palette, materials and every meta chunk.
|
|
-- Not supported: models over 256 cells per axis on write (MagicaVoxel's limit); node scale other than mirroring.
|
|
|
|
-- ------------------------------------------------------------------------------------------------ requires
|
|
local Err = require("@formats/core/Err")
|
|
local Bytes = require("@formats/core/Bytes")
|
|
local Types = require("@formats/Types")
|
|
local Grid = require("@formats/model/vox/Grid")
|
|
|
|
-- ------------------------------------------------------------------------------------------------ contract
|
|
local Vox = {
|
|
name = "vox",
|
|
category = "model",
|
|
extensions = { "vox" },
|
|
mime = { "model/x-vox" },
|
|
deps = { "core/Err", "core/Bytes", "Types" },
|
|
caps = { decode = true, encode = true, voxels = true, sceneGraph = true, materials = true },
|
|
}
|
|
|
|
-- ------------------------------------------------------------------------------------------------ types
|
|
export type DecodeOptions = {
|
|
maxCells: number?, -- refuse files whose grids hold more cells in total (default 2^27)
|
|
}
|
|
export type EncodeOptions = {
|
|
version: number?, -- the file version (default 200, what MagicaVoxel 0.99.7 writes; 150 is the older one)
|
|
}
|
|
type Dict = { [string]: string }
|
|
type GraphNode = {
|
|
kind: string,
|
|
id: number,
|
|
attrs: Dict,
|
|
child: number?,
|
|
layer: number?,
|
|
frames: { Dict }?,
|
|
children: { number }?,
|
|
models: { { model: number, attributes: Dict } }?,
|
|
}
|
|
|
|
-- ------------------------------------------------------------------------------------------------ constants
|
|
-- the default palette (spec section 8): a 6 x 6 x 6 colour cube without black, then red, green, blue and grey ramps
|
|
local DEFAULT_PALETTE: { { number } } = {}
|
|
do
|
|
local steps = { 0xff, 0xcc, 0x99, 0x66, 0x33, 0x00 }
|
|
for _, r in steps do
|
|
for _, g in steps do
|
|
for _, b in steps do
|
|
if #DEFAULT_PALETTE < 215 then
|
|
table.insert(DEFAULT_PALETTE, { r, g, b, 255 })
|
|
end
|
|
end
|
|
end
|
|
end
|
|
local ramp = { 0xee, 0xdd, 0xbb, 0xaa, 0x88, 0x77, 0x55, 0x44, 0x22, 0x11 }
|
|
for ch = 1, 4 do
|
|
for _, v in ramp do
|
|
local c = { 0, 0, 0, 255 }
|
|
if ch == 4 then
|
|
c = { v, v, v, 255 }
|
|
else
|
|
c[ch] = v
|
|
end
|
|
table.insert(DEFAULT_PALETTE, c)
|
|
end
|
|
end
|
|
end
|
|
Vox.DEFAULT_PALETTE = DEFAULT_PALETTE
|
|
|
|
local IDENTITY_R = 4 -- _r of the identity: row 0 -> column 0, row 1 -> column 1, no signs
|
|
local MAX_DEPTH = 256
|
|
|
|
-- ------------------------------------------------------------------------------------------------ sniff
|
|
function Vox.sniff(r: Bytes.Reader): number
|
|
return if r:peek(4) == "VOX " and r:peek(4, 8) == "MAIN" then 1 elseif r:peek(4) == "VOX " then 0.8 else 0
|
|
end
|
|
|
|
-- ------------------------------------------------------------------------------------------------ decode
|
|
local function str(r: Bytes.Reader): string
|
|
local n = r:i32le()
|
|
if n < 0 or n > r:remaining() then
|
|
r:fail(Err.CORRUPT, "bad string length")
|
|
return ""
|
|
end
|
|
return r:string(n)
|
|
end
|
|
|
|
local function dict(r: Bytes.Reader): Dict
|
|
local d: Dict = {}
|
|
local n = r:i32le()
|
|
if n < 0 or n * 8 > r:remaining() then
|
|
r:fail(Err.CORRUPT, "bad dictionary size")
|
|
return d
|
|
end
|
|
for _ = 1, n do
|
|
local k = str(r)
|
|
local v = str(r)
|
|
if r.err then
|
|
break
|
|
end
|
|
d[k] = v
|
|
end
|
|
return d
|
|
end
|
|
|
|
local function ints(s: string?): { number }
|
|
local out = {}
|
|
if s then
|
|
for w in string.gmatch(s, "%S+") do
|
|
table.insert(out, tonumber(w) or 0)
|
|
end
|
|
end
|
|
return out
|
|
end
|
|
|
|
-- _r byte -> the row-major 3 x 3 rotation (rows of { column, sign }) | nil when the byte is not a permutation
|
|
local function rotation(b: number): { { number } }?
|
|
local i0, i1 = bit32.band(b, 3), bit32.band(bit32.rshift(b, 2), 3)
|
|
if i0 > 2 or i1 > 2 or i0 == i1 then
|
|
return nil
|
|
end
|
|
local i2 = 3 - i0 - i1
|
|
local function sign(bit: number): number
|
|
return if bit32.band(b, bit32.lshift(1, bit)) ~= 0 then -1 else 1
|
|
end
|
|
return { { i0, sign(4) }, { i1, sign(5) }, { i2, sign(6) } }
|
|
end
|
|
|
|
-- the node transform of a frame dictionary (_r, _t)
|
|
local function applyFrame(node: Types.Node, f: Dict)
|
|
local t = ints(f._t)
|
|
local tx, ty, tz = t[1] or 0, t[2] or 0, t[3] or 0
|
|
local rb = tonumber(f._r)
|
|
local rows = if rb and rb ~= IDENTITY_R then rotation(rb) else nil
|
|
if not rows then
|
|
if tx ~= 0 or ty ~= 0 or tz ~= 0 then
|
|
node.translation = { tx, ty, tz }
|
|
end
|
|
return
|
|
end
|
|
-- R[row][col], then the determinant: +1 -> a quaternion, -1 (a mirror) -> a matrix
|
|
local R = { { 0, 0, 0 }, { 0, 0, 0 }, { 0, 0, 0 } }
|
|
for row = 1, 3 do
|
|
R[row][rows[row][1] + 1] = rows[row][2]
|
|
end
|
|
local det = R[1][1] * (R[2][2] * R[3][3] - R[2][3] * R[3][2]) - R[1][2] * (R[2][1] * R[3][3] - R[2][3] * R[3][1]) + R[1][3] * (R[2][1] * R[3][2] - R[2][2] * R[3][1])
|
|
if det < 0 then
|
|
node.matrix = {
|
|
R[1][1], R[2][1], R[3][1], 0,
|
|
R[1][2], R[2][2], R[3][2], 0,
|
|
R[1][3], R[2][3], R[3][3], 0,
|
|
tx, ty, tz, 1,
|
|
}
|
|
return
|
|
end
|
|
local m00, m11, m22 = R[1][1], R[2][2], R[3][3]
|
|
local tr = m00 + m11 + m22
|
|
local x, y, z, w
|
|
if tr > 0 then
|
|
local s = math.sqrt(tr + 1) * 2
|
|
w, x, y, z = 0.25 * s, (R[3][2] - R[2][3]) / s, (R[1][3] - R[3][1]) / s, (R[2][1] - R[1][2]) / s
|
|
elseif m00 > m11 and m00 > m22 then
|
|
local s = math.sqrt(1 + m00 - m11 - m22) * 2
|
|
w, x, y, z = (R[3][2] - R[2][3]) / s, 0.25 * s, (R[1][2] + R[2][1]) / s, (R[1][3] + R[3][1]) / s
|
|
elseif m11 > m22 then
|
|
local s = math.sqrt(1 + m11 - m00 - m22) * 2
|
|
w, x, y, z = (R[1][3] - R[3][1]) / s, (R[1][2] + R[2][1]) / s, 0.25 * s, (R[2][3] + R[3][2]) / s
|
|
else
|
|
local s = math.sqrt(1 + m22 - m00 - m11) * 2
|
|
w, x, y, z = (R[2][1] - R[1][2]) / s, (R[1][3] + R[3][1]) / s, (R[2][3] + R[3][2]) / s, 0.25 * s
|
|
end
|
|
node.rotation = { x, y, z, w }
|
|
if tx ~= 0 or ty ~= 0 or tz ~= 0 then
|
|
node.translation = { tx, ty, tz }
|
|
end
|
|
end
|
|
|
|
-- MATL dictionary -> VoxelMaterial: _type -> type (without "_"), the other keys without their "_", numbers as numbers
|
|
local function material(d: Dict): Types.VoxelMaterial
|
|
local m: Types.VoxelMaterial = { type = "diffuse" }
|
|
for k, v in d do
|
|
local key = if string.sub(k, 1, 1) == "_" then string.sub(k, 2) else k
|
|
if key == "type" then
|
|
m.type = if string.sub(v, 1, 1) == "_" then string.sub(v, 2) else v
|
|
else
|
|
m[key] = tonumber(v) or v
|
|
end
|
|
end
|
|
return m
|
|
end
|
|
|
|
type Parsed = {
|
|
version: number,
|
|
models: { Types.Voxels },
|
|
palette: { { number } }?,
|
|
materials: { [number]: Types.VoxelMaterial },
|
|
graph: { [number]: GraphNode },
|
|
meta: { [string]: any },
|
|
skipped: number,
|
|
}
|
|
|
|
local function parse(r: Bytes.Reader, opts: DecodeOptions?): (Parsed?, Err.Err?)
|
|
local maxCells = opts and opts.maxCells or 2 ^ 27
|
|
if r:string(4) ~= "VOX " then
|
|
return nil, Err.new(Err.CORRUPT, "bad signature", r.base)
|
|
end
|
|
local version = r:u32le()
|
|
if r:string(4) ~= "MAIN" then
|
|
if r.err then
|
|
return nil, r.err
|
|
end
|
|
return nil, Err.new(Err.CORRUPT, "missing MAIN chunk", 8)
|
|
end
|
|
local mainN, mainM = r:i32le(), r:i32le()
|
|
if r.err then
|
|
return nil, r.err
|
|
end
|
|
if mainN < 0 or mainM < 0 or not r:skip(mainN) then
|
|
return nil, Err.new(Err.CORRUPT, "bad MAIN chunk", 12)
|
|
end
|
|
local out: Parsed = { version = version, models = {}, palette = nil, materials = {}, graph = {}, meta = {}, skipped = 0 }
|
|
local meta = out.meta
|
|
local unknown: { any } = {}
|
|
local layers, robjs, cams = {}, {}, {}
|
|
local stop = r:tell() + mainM
|
|
if stop > r:size() then
|
|
return nil, Err.new(Err.TRUNCATED, "the MAIN chunk runs past the end", r.base + 16)
|
|
end
|
|
local pending: { number }? = nil
|
|
local cells = 0
|
|
while r:tell() + 12 <= stop do
|
|
local at = r:tell()
|
|
local id = r:string(4)
|
|
local n, m = r:i32le(), r:i32le()
|
|
if n < 0 or m < 0 then
|
|
return nil, Err.new(Err.CORRUPT, "bad size of chunk " .. id, at)
|
|
elseif n > stop - r:tell() or m > stop - r:tell() - n then
|
|
return nil, Err.new(Err.TRUNCATED, "chunk " .. id .. " runs past the end", at)
|
|
end
|
|
local c = r:slice(n)
|
|
if id == "SIZE" then
|
|
local sx, sy, sz = c:i32le(), c:i32le(), c:i32le()
|
|
if c.err or sx < 1 or sy < 1 or sz < 1 then
|
|
return nil, Err.new(Err.CORRUPT, "bad model size", at)
|
|
end
|
|
cells += sx * sy * sz
|
|
if cells > maxCells then
|
|
return nil, Err.new(Err.LIMIT, string.format("models hold over %d cells", maxCells), at)
|
|
end
|
|
pending = { sx, sy, sz }
|
|
elseif id == "XYZI" then
|
|
local size = pending
|
|
if not size then
|
|
return nil, Err.new(Err.CORRUPT, "XYZI without SIZE", at)
|
|
end
|
|
pending = nil
|
|
local count = c:i32le()
|
|
if c.err or count < 0 or count * 4 > c:remaining() then
|
|
return nil, Err.new(Err.CORRUPT, "bad voxel count", at)
|
|
end
|
|
local v = Types.Voxels.new(size[1], size[2], size[3], DEFAULT_PALETTE)
|
|
out.skipped += Grid.fill(v.data, size[1], size[2], size[3], c.buf, c.base + c:tell(), count)
|
|
table.insert(out.models, v)
|
|
elseif id == "RGBA" then
|
|
if n < 1024 then
|
|
return nil, Err.new(Err.CORRUPT, "short RGBA chunk", at)
|
|
end
|
|
local pal = table.create(255) :: { { number } }
|
|
for i = 1, 255 do
|
|
pal[i] = { c:u8(), c:u8(), c:u8(), c:u8() }
|
|
end
|
|
out.palette = pal
|
|
elseif id == "MATL" then
|
|
local mid = c:i32le()
|
|
local d = dict(c)
|
|
if c.err then
|
|
return nil, Err.new(Err.CORRUPT, "bad MATL chunk", at)
|
|
end
|
|
out.materials[mid] = material(d)
|
|
elseif id == "nTRN" then
|
|
local node: GraphNode = { kind = id, id = c:i32le(), attrs = dict(c), child = c:i32le() }
|
|
c:i32le() -- reserved
|
|
node.layer = c:i32le()
|
|
local nf = c:i32le()
|
|
if c.err or nf < 0 or nf * 4 > c:remaining() then
|
|
return nil, Err.new(Err.CORRUPT, "bad nTRN chunk", at)
|
|
end
|
|
local frames = {}
|
|
for k = 1, nf do
|
|
frames[k] = dict(c)
|
|
end
|
|
node.frames = frames
|
|
if c.err then
|
|
return nil, Err.new(Err.CORRUPT, "bad nTRN frames", at)
|
|
end
|
|
out.graph[node.id] = node
|
|
elseif id == "nGRP" then
|
|
local node: GraphNode = { kind = id, id = c:i32le(), attrs = dict(c) }
|
|
local nc = c:i32le()
|
|
if c.err or nc < 0 or nc * 4 > c:remaining() then
|
|
return nil, Err.new(Err.CORRUPT, "bad nGRP chunk", at)
|
|
end
|
|
local children = table.create(nc) :: { number }
|
|
for k = 1, nc do
|
|
children[k] = c:i32le()
|
|
end
|
|
node.children = children
|
|
out.graph[node.id] = node
|
|
elseif id == "nSHP" then
|
|
local node: GraphNode = { kind = id, id = c:i32le(), attrs = dict(c) }
|
|
local nm = c:i32le()
|
|
if c.err or nm < 0 or nm * 8 > c:remaining() then
|
|
return nil, Err.new(Err.CORRUPT, "bad nSHP chunk", at)
|
|
end
|
|
local models = {}
|
|
for k = 1, nm do
|
|
models[k] = { model = c:i32le() + 1, attributes = dict(c) }
|
|
end
|
|
if c.err then
|
|
return nil, Err.new(Err.CORRUPT, "bad nSHP models", at)
|
|
end
|
|
node.models = models
|
|
out.graph[node.id] = node
|
|
elseif id == "LAYR" then
|
|
local lid = c:i32le()
|
|
local d = dict(c)
|
|
if c.err then
|
|
return nil, Err.new(Err.CORRUPT, "bad LAYR chunk", at)
|
|
end
|
|
table.insert(layers, { id = lid, name = d._name, hidden = d._hidden == "1", attributes = d })
|
|
elseif id == "rOBJ" then
|
|
local d = dict(c)
|
|
if c.err then
|
|
return nil, Err.new(Err.CORRUPT, "bad rOBJ chunk", at)
|
|
end
|
|
table.insert(robjs, d)
|
|
elseif id == "rCAM" then
|
|
local cid = c:i32le()
|
|
local d = dict(c)
|
|
if c.err then
|
|
return nil, Err.new(Err.CORRUPT, "bad rCAM chunk", at)
|
|
end
|
|
table.insert(cams, { id = cid, attributes = d })
|
|
elseif id == "NOTE" then
|
|
local nn = c:i32le()
|
|
if c.err or nn < 0 or nn * 4 > c:remaining() then
|
|
return nil, Err.new(Err.CORRUPT, "bad NOTE chunk", at)
|
|
end
|
|
local notes = table.create(nn)
|
|
for k = 1, nn do
|
|
notes[k] = str(c)
|
|
end
|
|
if c.err then
|
|
return nil, Err.new(Err.CORRUPT, "bad NOTE names", at)
|
|
end
|
|
meta.notes = notes
|
|
elseif id == "IMAP" then
|
|
local map = {}
|
|
for k = 1, math.min(n, 256) do
|
|
map[k] = c:u8()
|
|
end
|
|
meta.indexMap = map
|
|
elseif id == "META" then
|
|
local d = dict(c)
|
|
if c.err then
|
|
return nil, Err.new(Err.CORRUPT, "bad META chunk", at)
|
|
end
|
|
meta.info = d
|
|
else
|
|
if id == "PACK" then
|
|
meta.pack = c:i32le()
|
|
end
|
|
table.insert(unknown, { id = id, content = c:sub(0, n):bytes(n), children = nil :: buffer? })
|
|
end
|
|
if m > 0 then
|
|
local kids = r:bytes(math.min(m, r:remaining()))
|
|
if #unknown > 0 and unknown[#unknown].children == nil and unknown[#unknown].id == id then
|
|
unknown[#unknown].children = kids
|
|
end
|
|
end
|
|
if r.err then
|
|
return nil, r.err
|
|
end
|
|
end
|
|
if r:tell() < stop then
|
|
return nil, Err.new(Err.TRUNCATED, "a partial chunk at the end", r.base + r:tell())
|
|
end
|
|
if #out.models == 0 then
|
|
return nil, Err.new(Err.CORRUPT, "no models")
|
|
end
|
|
if #layers > 0 then
|
|
meta.layers = layers
|
|
end
|
|
if #robjs > 0 then
|
|
meta.renderObjects = robjs
|
|
end
|
|
if #cams > 0 then
|
|
meta.cameras = cams
|
|
end
|
|
if #unknown > 0 then
|
|
meta.chunks = unknown
|
|
end
|
|
return out, nil
|
|
end
|
|
|
|
-- the Scene node tree from the nTRN at id (nil for a missing / looping / non-transform node)
|
|
local function build(scene: Types.Scene, graph: { [number]: GraphNode }, id: number, depth: number, visiting: { [number]: boolean }, nmodels: number): number?
|
|
local t = graph[id]
|
|
if not t or t.kind ~= "nTRN" or depth > MAX_DEPTH or visiting[id] then
|
|
return nil
|
|
end
|
|
visiting[id] = true
|
|
local node: Types.Node = { name = t.attrs._name, children = {} }
|
|
local index = #scene.nodes + 1
|
|
scene.nodes[index] = node
|
|
local frames = t.frames or {}
|
|
if frames[1] then
|
|
applyFrame(node, frames[1])
|
|
end
|
|
local vox: { [string]: any } = { attributes = t.attrs, layer = t.layer }
|
|
if #frames > 1 or (frames[1] and frames[1]._f) then
|
|
vox.frames = frames
|
|
end
|
|
node.extras = { vox = vox }
|
|
local child = if t.child then graph[t.child] else nil
|
|
if child and child.kind == "nGRP" then
|
|
vox.group = child.attrs
|
|
for _, c in child.children or {} do
|
|
local ci = build(scene, graph, c, depth + 1, visiting, nmodels)
|
|
if ci then
|
|
table.insert(node.children, ci)
|
|
end
|
|
end
|
|
elseif child and child.kind == "nSHP" then
|
|
local models = child.models or {}
|
|
vox.shape = { attributes = child.attrs, models = models }
|
|
local first = models[1]
|
|
if first and first.model >= 1 and first.model <= nmodels then
|
|
node.voxels = first.model
|
|
end
|
|
end
|
|
visiting[id] = nil
|
|
return index
|
|
end
|
|
|
|
-- decodeVoxels(r, opts?) -> { Voxels } (every model, in file order) | nil, Err
|
|
function Vox.decodeVoxels(r: Bytes.Reader, opts: DecodeOptions?): ({ Types.Voxels }?, Err.Err?)
|
|
local p, err = parse(r, opts)
|
|
if not p then
|
|
return nil, err
|
|
end
|
|
local pal = p.palette or DEFAULT_PALETTE
|
|
local mats = if next(p.materials) then p.materials else nil
|
|
for _, v in p.models do
|
|
v.palette = pal
|
|
v.materials = mats
|
|
end
|
|
return p.models, nil
|
|
end
|
|
|
|
function Vox.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Scene?, Err.Err?)
|
|
local p, err = parse(r, opts)
|
|
if not p then
|
|
return nil, err
|
|
end
|
|
local scene = Types.Scene.new()
|
|
local pal = p.palette or DEFAULT_PALETTE
|
|
local mats = if next(p.materials) then p.materials else nil
|
|
for _, v in p.models do
|
|
v.palette = pal
|
|
v.materials = mats
|
|
end
|
|
scene.voxels = p.models
|
|
if p.graph[0] then
|
|
local root = build(scene, p.graph, 0, 0, {}, #p.models)
|
|
if root then
|
|
scene.roots = { root }
|
|
end
|
|
end
|
|
if #scene.nodes == 0 then
|
|
-- no scene graph (version 150 files): one node per model
|
|
for i = 1, #p.models do
|
|
scene.nodes[i] = { children = {}, voxels = i }
|
|
scene.roots[i] = i
|
|
end
|
|
end
|
|
scene.meta.up = "z"
|
|
scene.meta.vox = p.meta
|
|
scene.meta.source = { format = "vox", version = p.version, models = #p.models, palette = p.palette ~= nil, skippedVoxels = p.skipped }
|
|
return scene, nil
|
|
end
|
|
|
|
-- ------------------------------------------------------------------------------------------------ encode
|
|
local function number(v: any): string
|
|
if type(v) ~= "number" then
|
|
return tostring(v)
|
|
end
|
|
if v == math.floor(v) and math.abs(v) < 2 ^ 53 then
|
|
return string.format("%d", v)
|
|
end
|
|
for _, f in { "%.6g", "%.9g", "%.17g" } do
|
|
local s = string.format(f, v)
|
|
if tonumber(s) == v then
|
|
return s
|
|
end
|
|
end
|
|
return string.format("%.17g", v)
|
|
end
|
|
|
|
local function sortedKeys(d: { [string]: any }): { string }
|
|
local keys = {}
|
|
for k in d do
|
|
if type(k) == "string" then
|
|
table.insert(keys, k)
|
|
end
|
|
end
|
|
table.sort(keys)
|
|
return keys
|
|
end
|
|
|
|
local function wstr(w: Bytes.Writer, s: string)
|
|
w:u32le(#s)
|
|
w:string(s)
|
|
end
|
|
|
|
local function wdict(w: Bytes.Writer, d: { [string]: any }?)
|
|
if not d then
|
|
w:u32le(0)
|
|
return
|
|
end
|
|
local keys = sortedKeys(d)
|
|
w:u32le(#keys)
|
|
for _, k in keys do
|
|
wstr(w, k)
|
|
wstr(w, number(d[k]))
|
|
end
|
|
end
|
|
|
|
-- a node's transform as a frame dictionary (_r, _t) | nil, message
|
|
local function frameOf(node: Types.Node, base: Dict?): (Dict?, string?)
|
|
local f: Dict = {}
|
|
if base then
|
|
for k, v in base do
|
|
if k ~= "_r" and k ~= "_t" then
|
|
f[k] = v
|
|
end
|
|
end
|
|
end
|
|
local m = Types.Scene.nodeMatrix(node)
|
|
local cols, signs = {}, {}
|
|
for row = 0, 2 do
|
|
local best, bv, rest = 0, 0, 0
|
|
for col = 0, 2 do
|
|
local v = m[col * 4 + row + 1]
|
|
if math.abs(v) > math.abs(bv) then
|
|
rest = math.max(rest, math.abs(bv))
|
|
best, bv = col, v
|
|
else
|
|
rest = math.max(rest, math.abs(v))
|
|
end
|
|
end
|
|
if math.abs(math.abs(bv) - 1) > 1e-4 or rest > 1e-4 or table.find(cols, best) then
|
|
return nil, "node rotation is not a multiple of 90 degrees (or has a scale)"
|
|
end
|
|
table.insert(cols, best)
|
|
signs[row + 1] = if bv < 0 then 1 else 0
|
|
end
|
|
local rb = cols[1] + cols[2] * 4 + signs[1] * 16 + signs[2] * 32 + signs[3] * 64
|
|
if rb ~= IDENTITY_R then
|
|
f._r = tostring(rb)
|
|
end
|
|
local tx, ty, tz = math.floor(m[13] + 0.5), math.floor(m[14] + 0.5), math.floor(m[15] + 0.5)
|
|
if tx ~= 0 or ty ~= 0 or tz ~= 0 then
|
|
f._t = string.format("%d %d %d", tx, ty, tz)
|
|
end
|
|
return f, nil
|
|
end
|
|
|
|
type Record = { kind: string, id: number, attrs: { [string]: any }?, child: number?, layer: number?, frames: { Dict }?, children: { number }?, models: { { model: number, attributes: Dict? } }? }
|
|
|
|
function Vox.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?)
|
|
local version = opts and opts.version or 200
|
|
if type(version) ~= "number" or version < 0 then
|
|
return nil, Err.new(Err.ARG, "bad version")
|
|
end
|
|
if type(value) ~= "table" then
|
|
return nil, Err.new(Err.ARG, "needs a Scene with voxels or a Voxels grid")
|
|
end
|
|
local scene: Types.Scene
|
|
if value.kind == "voxels" then
|
|
scene = Types.Scene.new()
|
|
scene.voxels = { value }
|
|
scene.nodes[1] = { children = {}, voxels = 1 }
|
|
scene.roots[1] = 1
|
|
elseif value.kind == "scene" then
|
|
scene = value
|
|
else
|
|
return nil, Err.new(Err.ARG, "needs a Scene with voxels or a Voxels grid")
|
|
end
|
|
local models = scene.voxels
|
|
if type(models) ~= "table" or #models == 0 then
|
|
return nil, Err.new(Err.ARG, "the scene has no voxels (MeshOps cannot voxelize meshes yet)")
|
|
end
|
|
for i, v in models do
|
|
local s = v.size
|
|
if type(s) ~= "table" or type(v.data) ~= "buffer" then
|
|
return nil, Err.new(Err.ARG, "voxels " .. i .. ": not a Voxels grid")
|
|
end
|
|
for k = 1, 3 do
|
|
if type(s[k]) ~= "number" or s[k] < 1 or s[k] > 256 or s[k] ~= math.floor(s[k]) then
|
|
return nil, Err.new(Err.ARG, "voxels " .. i .. ": size must be 1..256 per axis")
|
|
end
|
|
end
|
|
if buffer.len(v.data) < s[1] * s[2] * s[3] then
|
|
return nil, Err.new(Err.ARG, "voxels " .. i .. ": data is smaller than the grid")
|
|
end
|
|
end
|
|
local meta: any = if type(scene.meta) == "table" and type(scene.meta.vox) == "table" then scene.meta.vox else {}
|
|
local w = Bytes.writer(65536)
|
|
w:string("VOX ")
|
|
w:u32le(version)
|
|
w:string("MAIN")
|
|
w:u32le(0)
|
|
local mAt = w:tell()
|
|
w:u32le(0)
|
|
local function chunk(id: string, body: () -> ())
|
|
w:string(id)
|
|
local at = w:tell()
|
|
w:u32le(0)
|
|
w:u32le(0)
|
|
body()
|
|
w:setU32le(at, w:tell() - at - 8)
|
|
end
|
|
if type(meta.info) == "table" then
|
|
chunk("META", function()
|
|
wdict(w, meta.info)
|
|
end)
|
|
end
|
|
-- models
|
|
for _, v in models do
|
|
local sx, sy, sz = v.size[1], v.size[2], v.size[3]
|
|
chunk("SIZE", function()
|
|
w:u32le(sx)
|
|
w:u32le(sy)
|
|
w:u32le(sz)
|
|
end)
|
|
local count = Grid.count(v.data, sx * sy * sz)
|
|
chunk("XYZI", function()
|
|
w:u32le(count)
|
|
local at = w:reserve(count * 4)
|
|
Grid.write(w.buf, at, v.data, sx, sy, sz)
|
|
w.pos = at + count * 4
|
|
end)
|
|
end
|
|
-- the scene graph
|
|
local records: { Record } = {}
|
|
local nextId = 0
|
|
local function alloc(): number
|
|
local id = nextId
|
|
nextId += 1
|
|
return id
|
|
end
|
|
local nodes = scene.nodes or {}
|
|
local visiting: { [number]: boolean } = {}
|
|
local failure: string? = nil
|
|
local function shape(model: number, vx: any?): number
|
|
local id = alloc()
|
|
local ms: { { model: number, attributes: Dict? } } = {}
|
|
local saved = vx and vx.shape
|
|
if saved and type(saved.models) == "table" and saved.models[1] and saved.models[1].model == model then
|
|
for _, sm in saved.models do
|
|
if type(sm.model) == "number" and sm.model >= 1 and sm.model <= #models then
|
|
table.insert(ms, { model = sm.model - 1, attributes = sm.attributes })
|
|
end
|
|
end
|
|
end
|
|
if #ms == 0 then
|
|
ms[1] = { model = model - 1, attributes = nil }
|
|
end
|
|
table.insert(records, { kind = "nSHP", id = id, attrs = saved and saved.attributes, models = ms })
|
|
return id
|
|
end
|
|
local function visit(index: number, depth: number, layer: number?): number?
|
|
local node = nodes[index]
|
|
if not node or visiting[index] or depth > MAX_DEPTH then
|
|
failure = failure or "the node tree has a loop or is too deep"
|
|
return nil
|
|
end
|
|
visiting[index] = true
|
|
local vx = if type(node.extras) == "table" and type(node.extras.vox) == "table" then node.extras.vox else nil
|
|
local id = alloc()
|
|
local attrs: { [string]: any } = {}
|
|
if vx and type(vx.attributes) == "table" then
|
|
for k, v in vx.attributes do
|
|
attrs[k] = v
|
|
end
|
|
end
|
|
attrs._name = node.name
|
|
local saved = vx and type(vx.frames) == "table" and vx.frames or nil
|
|
local f, ferr = frameOf(node, saved and saved[1])
|
|
if not f then
|
|
failure = failure or ferr
|
|
f = {}
|
|
end
|
|
local frames = { f :: Dict }
|
|
if saved then
|
|
for k = 2, #saved do
|
|
frames[k] = saved[k]
|
|
end
|
|
end
|
|
local rec: Record = { kind = "nTRN", id = id, attrs = attrs, layer = layer or (vx and tonumber(vx.layer)) or 0, frames = frames }
|
|
table.insert(records, rec)
|
|
local kids = node.children or {}
|
|
local hasVox = type(node.voxels) == "number" and node.voxels >= 1 and node.voxels <= #models
|
|
if hasVox and #kids == 0 then
|
|
rec.child = shape(node.voxels :: number, vx)
|
|
else
|
|
local gid = alloc()
|
|
local grp: Record = { kind = "nGRP", id = gid, attrs = vx and vx.group, children = {} }
|
|
table.insert(records, grp)
|
|
rec.child = gid
|
|
if hasVox then
|
|
local tid = alloc()
|
|
local t2: Record = { kind = "nTRN", id = tid, attrs = {}, layer = 0, frames = { {} } }
|
|
table.insert(records, t2)
|
|
table.insert(grp.children :: { number }, tid)
|
|
t2.child = shape(node.voxels :: number, vx)
|
|
end
|
|
for _, c in kids do
|
|
local cid = visit(c, depth + 1, nil)
|
|
if cid then
|
|
table.insert(grp.children :: { number }, cid)
|
|
end
|
|
end
|
|
end
|
|
visiting[index] = nil
|
|
return id
|
|
end
|
|
local roots = scene.roots or {}
|
|
local single = if #roots == 1 then nodes[roots[1]] else nil
|
|
if single and single.voxels == nil then
|
|
visit(roots[1], 0, -1)
|
|
elseif #roots > 0 then
|
|
local rid = alloc()
|
|
local gid = alloc()
|
|
local rec: Record = { kind = "nTRN", id = rid, attrs = {}, child = gid, layer = -1, frames = { {} } }
|
|
local grp: Record = { kind = "nGRP", id = gid, attrs = nil, children = {} }
|
|
table.insert(records, rec)
|
|
table.insert(records, grp)
|
|
for _, ri in roots do
|
|
local cid = visit(ri, 1, nil)
|
|
if cid then
|
|
table.insert(grp.children :: { number }, cid)
|
|
end
|
|
end
|
|
end
|
|
if failure then
|
|
return nil, Err.new(Err.ARG, failure)
|
|
end
|
|
for _, rec in records do
|
|
chunk(rec.kind, function()
|
|
w:u32le(rec.id)
|
|
wdict(w, rec.attrs)
|
|
if rec.kind == "nTRN" then
|
|
w:u32le(rec.child or 0)
|
|
w:u32le(0xFFFFFFFF)
|
|
w:u32le((rec.layer or 0) % 4294967296)
|
|
local frames = rec.frames or { {} }
|
|
w:u32le(#frames)
|
|
for _, f in frames do
|
|
wdict(w, f)
|
|
end
|
|
elseif rec.kind == "nGRP" then
|
|
local ch = rec.children or {}
|
|
w:u32le(#ch)
|
|
for _, c in ch do
|
|
w:u32le(c)
|
|
end
|
|
else
|
|
local ms = rec.models or {}
|
|
w:u32le(#ms)
|
|
for _, sm in ms do
|
|
w:u32le(sm.model)
|
|
wdict(w, sm.attributes)
|
|
end
|
|
end
|
|
end)
|
|
end
|
|
-- layers
|
|
if type(meta.layers) == "table" then
|
|
for _, l in meta.layers do
|
|
chunk("LAYR", function()
|
|
w:u32le(tonumber(l.id) or 0)
|
|
local d: { [string]: any } = {}
|
|
if type(l.attributes) == "table" then
|
|
for k, v in l.attributes do
|
|
d[k] = v
|
|
end
|
|
end
|
|
d._name = l.name
|
|
d._hidden = if l.hidden then "1" elseif d._hidden ~= nil then "0" else nil
|
|
wdict(w, d)
|
|
w:u32le(0xFFFFFFFF)
|
|
end)
|
|
end
|
|
end
|
|
-- palette
|
|
local pal = models[1].palette or DEFAULT_PALETTE
|
|
chunk("RGBA", function()
|
|
for i = 1, 256 do
|
|
local c = pal[i]
|
|
if type(c) == "table" then
|
|
w:u8(math.clamp(math.floor(tonumber(c[1]) or 0), 0, 255))
|
|
w:u8(math.clamp(math.floor(tonumber(c[2]) or 0), 0, 255))
|
|
w:u8(math.clamp(math.floor(tonumber(c[3]) or 0), 0, 255))
|
|
w:u8(math.clamp(math.floor(tonumber(c[4]) or 255), 0, 255))
|
|
else
|
|
w:u32le(0)
|
|
end
|
|
end
|
|
end)
|
|
if type(meta.indexMap) == "table" then
|
|
chunk("IMAP", function()
|
|
for k = 1, 256 do
|
|
w:u8(math.clamp(math.floor(tonumber(meta.indexMap[k]) or 0), 0, 255))
|
|
end
|
|
end)
|
|
end
|
|
-- materials
|
|
local mats = models[1].materials
|
|
if type(mats) == "table" then
|
|
local ids = {}
|
|
for id in mats do
|
|
if type(id) == "number" then
|
|
table.insert(ids, id)
|
|
end
|
|
end
|
|
table.sort(ids)
|
|
for _, id in ids do
|
|
local m = mats[id]
|
|
chunk("MATL", function()
|
|
w:u32le(id)
|
|
local d: { [string]: any } = { _type = "_" .. tostring(m.type or "diffuse") }
|
|
for k, v in m do
|
|
if k ~= "type" and type(k) == "string" then
|
|
d["_" .. k] = v
|
|
end
|
|
end
|
|
wdict(w, d)
|
|
end)
|
|
end
|
|
end
|
|
if type(meta.renderObjects) == "table" then
|
|
for _, d in meta.renderObjects do
|
|
chunk("rOBJ", function()
|
|
wdict(w, d)
|
|
end)
|
|
end
|
|
end
|
|
if type(meta.cameras) == "table" then
|
|
for _, cam in meta.cameras do
|
|
chunk("rCAM", function()
|
|
w:u32le(tonumber(cam.id) or 0)
|
|
wdict(w, cam.attributes)
|
|
end)
|
|
end
|
|
end
|
|
if type(meta.notes) == "table" then
|
|
chunk("NOTE", function()
|
|
w:u32le(#meta.notes)
|
|
for _, s in meta.notes do
|
|
wstr(w, tostring(s))
|
|
end
|
|
end)
|
|
end
|
|
if type(meta.chunks) == "table" then
|
|
for _, u in meta.chunks do
|
|
if type(u.id) == "string" and #u.id == 4 and type(u.content) == "buffer" and u.id ~= "PACK" then
|
|
w:string(u.id)
|
|
w:u32le(buffer.len(u.content))
|
|
w:u32le(if u.children then buffer.len(u.children) else 0)
|
|
w:bytes(u.content)
|
|
if u.children then
|
|
w:bytes(u.children)
|
|
end
|
|
end
|
|
end
|
|
end
|
|
w:setU32le(mAt, w:tell() - mAt - 4)
|
|
return w:finish(), nil
|
|
end
|
|
|
|
return Vox
|