ws-3d: model/vox (MagicaVoxel read/write: every chunk, scene graph, materials, layers, render objects, cameras, notes, IMAP, META, unknown chunks kept), ops/MeshOps (triangulate, transform, normals, tangents, weld/unweld, bounds, merge, scale/setUnit/setUp, greedy voxel meshing); Types: Scene.reader/mul/nodeMatrix/flatten helpers; compat: __iter visits t[0] on LuaJIT (was skipped by ipairs)
This commit is contained in:
1 parent
a55b58b102
commit
b37c61a96c
22 files changed
+3269
-1
No files matched your search
+1
-1
@@ -403,7 +403,7 @@ function M.__iter(t, s, c)
|
||||
local mt = getmetatable(t)
|
||||
if rawtype(mt) == "table" and mt.__iter then return mt.__iter(t) end
|
||||
local n = #t
|
||||
if n > 0 and next(t, n) == nil then return ipairs(t) end
|
||||
if n > 0 and t[0] == nil and next(t, n) == nil then return ipairs(t) end -- LuaJIT keeps t[0] in the array part
|
||||
return next, t, nil
|
||||
end
|
||||
|
||||
|
||||
@@ -5,6 +5,8 @@
|
||||
| `src/Formats/codecs/Deflate/` (Inflate, init), `src/Formats/core/Crc32.luau`, `src/Formats/core/Adler32.luau`, `src/Formats/core/Huffman.luau` (table builder) | deflate-luau 1.0.0 (same author), written from RFC 1950-1952 | no licence chosen yet; no third-party code: [deflate-luau-NOTICE.txt](deflate-luau-NOTICE.txt) |
|
||||
| `src/Formats/image/png/` (init, Decode) | png-luau 1.0.0 (same author), written from the PNG specification | no licence chosen yet; no third-party code |
|
||||
| `tests/fixtures/pngsuite/` | PngSuite by Willem van Schaik | [PngSuite-LICENSE.txt](PngSuite-LICENSE.txt) |
|
||||
| `tests/fixtures/vox/{chr_knight,chr_sword,deer,maze}.vox`, `tests/fixtures/vox/MagicaVoxel-file-format-vox*.txt` (the format spec) | ephtracy/voxel-model (MagicaVoxel sample models) | MIT: [voxel-model-LICENSE.txt](voxel-model-LICENSE.txt) |
|
||||
| `tests/fixtures/vox/ogt_*.vox` | jpaver/opengametools `demo/vox/` (files saved by MagicaVoxel 0.99.x) | MIT: [opengametools-LICENSE.txt](opengametools-LICENSE.txt) |
|
||||
|
||||
Ports of third-party code (minimp3, stb_vorbis, libopus, ...) add a row here and their upstream licence text in this
|
||||
folder (see docs/STYLE.md, "Absorbing an existing repo").
|
||||
@@ -0,0 +1,9 @@
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2019 Justin Paver
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
||||
@@ -0,0 +1,21 @@
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2026 ephtracy
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
@@ -404,6 +404,161 @@ function Scene.fromPrimitive(prim: Primitive, name: string?): Scene
|
||||
end
|
||||
Types.Scene = Scene
|
||||
|
||||
-- reader(acc) -> get(i, c): element i (0-based), component c (0-based) as a number; normalized types are converted
|
||||
-- to floats (unorm8 255 -> 1, snorm16 -32767 -> -1, glTF rules). Nil for an unknown type.
|
||||
function Scene.reader(acc: Accessor): ((i: number, c: number) -> number)?
|
||||
local d, n, t = acc.data, acc.components, acc.type
|
||||
local size = COMPONENT_SIZE[t]
|
||||
if not size or type(d) ~= "buffer" then
|
||||
return nil
|
||||
end
|
||||
local stride = n * size
|
||||
local rb = buffer
|
||||
if t == "f32" then
|
||||
local f = rb.readf32
|
||||
return function(i: number, c: number): number
|
||||
return f(d, i * stride + c * 4)
|
||||
end
|
||||
elseif t == "f64" then
|
||||
local f = rb.readf64
|
||||
return function(i: number, c: number): number
|
||||
return f(d, i * stride + c * 8)
|
||||
end
|
||||
elseif t == "u8" or t == "unorm8" then
|
||||
local f, k = rb.readu8, if t == "unorm8" then 1 / 255 else 1
|
||||
return function(i: number, c: number): number
|
||||
return f(d, i * stride + c) * k
|
||||
end
|
||||
elseif t == "u16" or t == "unorm16" then
|
||||
local f, k = rb.readu16, if t == "unorm16" then 1 / 65535 else 1
|
||||
return function(i: number, c: number): number
|
||||
return f(d, i * stride + c * 2) * k
|
||||
end
|
||||
elseif t == "u32" then
|
||||
local f = rb.readu32
|
||||
return function(i: number, c: number): number
|
||||
return f(d, i * stride + c * 4)
|
||||
end
|
||||
elseif t == "i8" then
|
||||
local f = rb.readi8
|
||||
return function(i: number, c: number): number
|
||||
return f(d, i * stride + c)
|
||||
end
|
||||
elseif t == "snorm8" then
|
||||
local f = rb.readi8
|
||||
return function(i: number, c: number): number
|
||||
return math.max(f(d, i * stride + c) / 127, -1)
|
||||
end
|
||||
elseif t == "i16" then
|
||||
local f = rb.readi16
|
||||
return function(i: number, c: number): number
|
||||
return f(d, i * stride + c * 2)
|
||||
end
|
||||
elseif t == "snorm16" then
|
||||
local f = rb.readi16
|
||||
return function(i: number, c: number): number
|
||||
return math.max(f(d, i * stride + c * 2) / 32767, -1)
|
||||
end
|
||||
elseif t == "i32" then
|
||||
local f = rb.readi32
|
||||
return function(i: number, c: number): number
|
||||
return f(d, i * stride + c * 4)
|
||||
end
|
||||
end
|
||||
return nil
|
||||
end
|
||||
|
||||
-- the identity and products of column-major 4x4 matrices (flat arrays of 16)
|
||||
local IDENTITY = table.freeze({ 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1 })
|
||||
Scene.IDENTITY = IDENTITY
|
||||
function Scene.mul(a: { number }, b: { number }): { number }
|
||||
local m = table.create(16, 0)
|
||||
for col = 0, 3 do
|
||||
for row = 0, 3 do
|
||||
local s = 0
|
||||
for k = 0, 3 do
|
||||
s += a[k * 4 + row + 1] * b[col * 4 + k + 1]
|
||||
end
|
||||
m[col * 4 + row + 1] = s
|
||||
end
|
||||
end
|
||||
return m
|
||||
end
|
||||
-- nodeMatrix(node) -> the node's local matrix (node.matrix, or T * R * S)
|
||||
function Scene.nodeMatrix(node: Node): { number }
|
||||
if node.matrix and #node.matrix == 16 then
|
||||
return node.matrix
|
||||
end
|
||||
local t, r, sc = node.translation, node.rotation, node.scale
|
||||
if not t and not r and not sc then
|
||||
return IDENTITY
|
||||
end
|
||||
local tx, ty, tz = 0, 0, 0
|
||||
if t then
|
||||
tx, ty, tz = t[1] or 0, t[2] or 0, t[3] or 0
|
||||
end
|
||||
local x, y, z, w = 0, 0, 0, 1
|
||||
if r then
|
||||
x, y, z, w = r[1] or 0, r[2] or 0, r[3] or 0, r[4] or 1
|
||||
end
|
||||
local sx, sy, sz = 1, 1, 1
|
||||
if sc then
|
||||
sx, sy, sz = sc[1] or 1, sc[2] or 1, sc[3] or 1
|
||||
end
|
||||
local xx, yy, zz, xy, xz, yz, wx, wy, wz = x * x, y * y, z * z, x * y, x * z, y * z, w * x, w * y, w * z
|
||||
return {
|
||||
(1 - 2 * (yy + zz)) * sx, (2 * (xy + wz)) * sx, (2 * (xz - wy)) * sx, 0,
|
||||
(2 * (xy - wz)) * sy, (1 - 2 * (xx + zz)) * sy, (2 * (yz + wx)) * sy, 0,
|
||||
(2 * (xz + wy)) * sz, (2 * (yz - wx)) * sz, (1 - 2 * (xx + yy)) * sz, 0,
|
||||
tx, ty, tz, 1,
|
||||
}
|
||||
end
|
||||
export type Placed = { primitive: Primitive, matrix: { number }, node: number, mesh: number }
|
||||
-- flatten(scene) -> { { primitive, matrix (world), node, mesh } } for every mesh primitive reachable from the roots
|
||||
-- (depth first, in order; cycles and repeated visits are cut). Scenes without roots use every node without a parent.
|
||||
function Scene.flatten(scene: Scene): { Placed }
|
||||
local out: { Placed } = {}
|
||||
local nodes = scene.nodes or {}
|
||||
local roots = scene.roots
|
||||
if not roots or #roots == 0 then
|
||||
local child = {}
|
||||
for _, n in nodes do
|
||||
for _, c in n.children or {} do
|
||||
child[c] = true
|
||||
end
|
||||
end
|
||||
roots = {}
|
||||
for i in nodes do
|
||||
if not child[i] then
|
||||
table.insert(roots, i)
|
||||
end
|
||||
end
|
||||
end
|
||||
local seen: { [number]: boolean } = {}
|
||||
local function visit(i: number, parent: { number })
|
||||
local node = nodes[i]
|
||||
if not node or seen[i] then
|
||||
return
|
||||
end
|
||||
seen[i] = true
|
||||
local m = Scene.nodeMatrix(node)
|
||||
local world = if parent == IDENTITY then m elseif m == IDENTITY then parent else Scene.mul(parent, m)
|
||||
local mesh = node.mesh and scene.meshes[node.mesh]
|
||||
if mesh then
|
||||
for _, p in mesh.primitives do
|
||||
table.insert(out, { primitive = p, matrix = world, node = i, mesh = node.mesh :: number })
|
||||
end
|
||||
end
|
||||
for _, c in node.children or {} do
|
||||
visit(c, world)
|
||||
end
|
||||
end
|
||||
for _, r in roots do
|
||||
visit(r, IDENTITY)
|
||||
end
|
||||
return out
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ Cad
|
||||
-- the STEP entity graph; B-rep bodies and tessellation come from the injected brep plug-in (Formats.plugins.brep)
|
||||
export type StepEntity = { id: number, type: string, args: { any } }
|
||||
|
||||
@@ -0,0 +1,61 @@
|
||||
--!strict
|
||||
--!native
|
||||
-- model/vox/Grid: the voxel loops of the VOX format: XYZI records into a dense grid, and a dense grid back into XYZI
|
||||
-- records. Callers check every range first; nothing here throws.
|
||||
local Grid = {}
|
||||
|
||||
local readu8, writeu8 = buffer.readu8, buffer.writeu8
|
||||
|
||||
-- fill(dst, sx, sy, sz, src, off, n) -> skipped: writes n XYZI records (x, y, z, index bytes at src[off ..]) into the
|
||||
-- dense grid dst (cell x + sx * (y + sy * z)); records outside the grid or with index 0 are skipped and counted.
|
||||
-- The caller guarantees off + 4 * n <= buffer.len(src) and buffer.len(dst) >= sx * sy * sz.
|
||||
function Grid.fill(dst: buffer, sx: number, sy: number, sz: number, src: buffer, off: number, n: number): number
|
||||
local skipped = 0
|
||||
local sxy = sx * sy
|
||||
for k = 0, n - 1 do
|
||||
local p = off + k * 4
|
||||
local x, y, z, i = readu8(src, p), readu8(src, p + 1), readu8(src, p + 2), readu8(src, p + 3)
|
||||
if x < sx and y < sy and z < sz and i ~= 0 then
|
||||
writeu8(dst, x + sx * y + sxy * z, i)
|
||||
else
|
||||
skipped += 1
|
||||
end
|
||||
end
|
||||
return skipped
|
||||
end
|
||||
|
||||
-- count(data, cells) -> the number of non-empty cells in data[0, cells)
|
||||
function Grid.count(data: buffer, cells: number): number
|
||||
local n = 0
|
||||
for k = 0, cells - 1 do
|
||||
if readu8(data, k) ~= 0 then
|
||||
n += 1
|
||||
end
|
||||
end
|
||||
return n
|
||||
end
|
||||
|
||||
-- write(dst, at, data, sx, sy, sz) -> the offset after the last record: one XYZI record per non-empty cell (x fastest).
|
||||
-- The caller sizes dst with count() (sx, sy, sz <= 256).
|
||||
function Grid.write(dst: buffer, at: number, data: buffer, sx: number, sy: number, sz: number): number
|
||||
local p = at
|
||||
local k = 0
|
||||
for z = 0, sz - 1 do
|
||||
for y = 0, sy - 1 do
|
||||
for x = 0, sx - 1 do
|
||||
local i = readu8(data, k)
|
||||
if i ~= 0 then
|
||||
writeu8(dst, p, x)
|
||||
writeu8(dst, p + 1, y)
|
||||
writeu8(dst, p + 2, z)
|
||||
writeu8(dst, p + 3, i)
|
||||
p += 4
|
||||
end
|
||||
k += 1
|
||||
end
|
||||
end
|
||||
end
|
||||
return p
|
||||
end
|
||||
|
||||
return Grid
|
||||
@@ -0,0 +1,903 @@
|
||||
--!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)
|
||||
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)
|
||||
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 = 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 = {}
|
||||
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
|
||||
@@ -0,0 +1,167 @@
|
||||
--!strict
|
||||
--!native
|
||||
-- ops/MeshOps/Greedy: greedy meshing of a dense voxel grid (one byte per cell, 0 = empty): for each axis and each
|
||||
-- slice between two layers of cells, the exposed faces are masked by palette index, and runs of equal faces are merged
|
||||
-- into maximal rectangles (Mikola Lysenko's "Meshing in a Minecraft game", 2012). Faces between two filled cells are
|
||||
-- hidden whatever their indices. Output: 4 vertices and 2 triangles per rectangle, counter-clockwise seen from the
|
||||
-- outside. Never throws; the caller checks buffer.len(data) >= sx * sy * sz.
|
||||
local Greedy = {}
|
||||
|
||||
local readu8, readi32, writei32 = buffer.readu8, buffer.readi32, buffer.writei32
|
||||
local writef32, writeu8, writeu32 = buffer.writef32, buffer.writeu8, buffer.writeu32
|
||||
|
||||
export type Out = {
|
||||
positions: buffer, -- f32 x3 per vertex
|
||||
normals: buffer, -- f32 x3 per vertex
|
||||
index: buffer, -- u8 palette index per vertex
|
||||
indices: buffer, -- u32, 6 per quad
|
||||
vertices: number,
|
||||
quads: number,
|
||||
}
|
||||
|
||||
-- run(data, sx, sy, sz, ox, oy, oz, scale) -> Out: vertex position = (cell corner + (ox, oy, oz)) * scale
|
||||
function Greedy.run(data: buffer, sx: number, sy: number, sz: number, ox: number, oy: number, oz: number, scale: number): Out
|
||||
local cap = 1024
|
||||
local pos = buffer.create(cap * 48)
|
||||
local nrm = buffer.create(cap * 48)
|
||||
local idx = buffer.create(cap * 4)
|
||||
local tri = buffer.create(cap * 24)
|
||||
local quads = 0
|
||||
local maxFace = math.max(sx * sy, sy * sz, sz * sx)
|
||||
local mask = buffer.create(maxFace * 4)
|
||||
local corner = { 0, 0, 0 }
|
||||
for d = 0, 2 do
|
||||
-- u, v: the two other axes, cyclic so that e_u x e_v = e_d
|
||||
local u, v = (d + 1) % 3, (d + 2) % 3
|
||||
local nd = if d == 0 then sx elseif d == 1 then sy else sz
|
||||
local nu = if u == 0 then sx elseif u == 1 then sy else sz
|
||||
local nv = if v == 0 then sx elseif v == 1 then sy else sz
|
||||
local std = if d == 0 then 1 elseif d == 1 then sx else sx * sy
|
||||
local stu = if u == 0 then 1 elseif u == 1 then sx else sx * sy
|
||||
local stv = if v == 0 then 1 elseif v == 1 then sx else sx * sy
|
||||
for slice = -1, nd - 1 do
|
||||
-- the mask of faces between layer slice and slice + 1: +index (faces +d, owned by slice), -index (faces -d)
|
||||
local any = false
|
||||
for j = 0, nv - 1 do
|
||||
for i = 0, nu - 1 do
|
||||
local base = i * stu + j * stv
|
||||
local a = if slice >= 0 then readu8(data, base + slice * std) else 0
|
||||
local b = if slice + 1 < nd then readu8(data, base + (slice + 1) * std) else 0
|
||||
local m = 0
|
||||
if a ~= 0 and b == 0 then
|
||||
m = a
|
||||
elseif a == 0 and b ~= 0 then
|
||||
m = -b
|
||||
end
|
||||
if m ~= 0 then
|
||||
any = true
|
||||
end
|
||||
writei32(mask, (i + j * nu) * 4, m)
|
||||
end
|
||||
end
|
||||
if any then
|
||||
for j = 0, nv - 1 do
|
||||
local i = 0
|
||||
while i < nu do
|
||||
local m = readi32(mask, (i + j * nu) * 4)
|
||||
if m == 0 then
|
||||
i += 1
|
||||
else
|
||||
local w = 1
|
||||
while i + w < nu and readi32(mask, (i + w + j * nu) * 4) == m do
|
||||
w += 1
|
||||
end
|
||||
local h = 1
|
||||
local grow = true
|
||||
while j + h < nv and grow do
|
||||
for k = 0, w - 1 do
|
||||
if readi32(mask, (i + k + (j + h) * nu) * 4) ~= m then
|
||||
grow = false
|
||||
break
|
||||
end
|
||||
end
|
||||
if grow then
|
||||
h += 1
|
||||
end
|
||||
end
|
||||
for jj = j, j + h - 1 do
|
||||
for k = 0, w - 1 do
|
||||
writei32(mask, (i + k + jj * nu) * 4, 0)
|
||||
end
|
||||
end
|
||||
-- emit the rectangle
|
||||
if quads == cap then
|
||||
local ncap = cap * 2
|
||||
local function grow2(b: buffer, per: number): buffer
|
||||
local nb = buffer.create(ncap * per)
|
||||
buffer.copy(nb, 0, b, 0, cap * per)
|
||||
return nb
|
||||
end
|
||||
pos, nrm, idx, tri = grow2(pos, 48), grow2(nrm, 48), grow2(idx, 4), grow2(tri, 24)
|
||||
cap = ncap
|
||||
end
|
||||
corner[d + 1] = slice + 1
|
||||
corner[u + 1] = i
|
||||
corner[v + 1] = j
|
||||
local cx, cy, cz = corner[1], corner[2], corner[3]
|
||||
-- the u and v edge vectors
|
||||
local ux = if u == 0 then w else 0
|
||||
local uy = if u == 1 then w else 0
|
||||
local uz = if u == 2 then w else 0
|
||||
local vx = if v == 0 then h else 0
|
||||
local vy = if v == 1 then h else 0
|
||||
local vz = if v == 2 then h else 0
|
||||
local nsign = if m > 0 then 1 else -1
|
||||
local nx = if d == 0 then nsign else 0
|
||||
local ny = if d == 1 then nsign else 0
|
||||
local nz = if d == 2 then nsign else 0
|
||||
local col = if m > 0 then m else -m
|
||||
local vb = quads * 48
|
||||
local px0, py0, pz0 = (cx + ox) * scale, (cy + oy) * scale, (cz + oz) * scale
|
||||
writef32(pos, vb, px0)
|
||||
writef32(pos, vb + 4, py0)
|
||||
writef32(pos, vb + 8, pz0)
|
||||
writef32(pos, vb + 12, px0 + ux * scale)
|
||||
writef32(pos, vb + 16, py0 + uy * scale)
|
||||
writef32(pos, vb + 20, pz0 + uz * scale)
|
||||
writef32(pos, vb + 24, px0 + (ux + vx) * scale)
|
||||
writef32(pos, vb + 28, py0 + (uy + vy) * scale)
|
||||
writef32(pos, vb + 32, pz0 + (uz + vz) * scale)
|
||||
writef32(pos, vb + 36, px0 + vx * scale)
|
||||
writef32(pos, vb + 40, py0 + vy * scale)
|
||||
writef32(pos, vb + 44, pz0 + vz * scale)
|
||||
for k = 0, 3 do
|
||||
writef32(nrm, vb + k * 12, nx)
|
||||
writef32(nrm, vb + k * 12 + 4, ny)
|
||||
writef32(nrm, vb + k * 12 + 8, nz)
|
||||
writeu8(idx, quads * 4 + k, col)
|
||||
end
|
||||
local v0 = quads * 4
|
||||
local ib = quads * 24
|
||||
if m > 0 then
|
||||
writeu32(tri, ib, v0)
|
||||
writeu32(tri, ib + 4, v0 + 1)
|
||||
writeu32(tri, ib + 8, v0 + 2)
|
||||
writeu32(tri, ib + 12, v0)
|
||||
writeu32(tri, ib + 16, v0 + 2)
|
||||
writeu32(tri, ib + 20, v0 + 3)
|
||||
else
|
||||
writeu32(tri, ib, v0)
|
||||
writeu32(tri, ib + 4, v0 + 2)
|
||||
writeu32(tri, ib + 8, v0 + 1)
|
||||
writeu32(tri, ib + 12, v0)
|
||||
writeu32(tri, ib + 16, v0 + 3)
|
||||
writeu32(tri, ib + 20, v0 + 2)
|
||||
end
|
||||
quads += 1
|
||||
i += w
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
return { positions = pos, normals = nrm, index = idx, indices = tri, vertices = quads * 4, quads = quads }
|
||||
end
|
||||
|
||||
return Greedy
|
||||
File diff suppressed because it is too large.
Load diff
@@ -212,6 +212,12 @@ do
|
||||
count += 1
|
||||
end
|
||||
t:eq(count, 3, "for over a mixed table visits every key")
|
||||
local zero = { [0] = 5, 6, 7 }
|
||||
local zsum = 0
|
||||
for _, v in zero do
|
||||
zsum += v
|
||||
end
|
||||
t:eq(zsum, 18, "for over a table with key 0 visits it (LuaJIT keeps t[0] in the array part)")
|
||||
local w = {}
|
||||
for word in string.gmatch("a b c", "%a") do
|
||||
table.insert(w, word)
|
||||
|
||||
@@ -0,0 +1,165 @@
|
||||
* there can be multiple SIZE and XYZI chunks for multiple models; model id is their index in the stored order
|
||||
* the palette chunk is always stored into the file, so default palette is not needed any more
|
||||
* the MATT chunk is deprecated, replaced by the MATL chunk, see (4)
|
||||
* (a), (b), (c) are special data types; (d) is the scene graph in the world editor
|
||||
|
||||
=================================
|
||||
(a) STRING type
|
||||
|
||||
int32 : buffer size (in bytes)
|
||||
int8xN : buffer (without the ending "\0")
|
||||
|
||||
=================================
|
||||
(b) DICT type
|
||||
|
||||
int32 : num of key-value pairs
|
||||
|
||||
// for each key-value pair
|
||||
{
|
||||
STRING : key
|
||||
STRING : value
|
||||
}xN
|
||||
|
||||
=================================
|
||||
(c) ROTATION type
|
||||
|
||||
store a row-major rotation in the bits of a byte
|
||||
|
||||
for example :
|
||||
R =
|
||||
0 1 0
|
||||
0 0 -1
|
||||
-1 0 0
|
||||
==>
|
||||
unsigned char _r = (1 << 0) | (2 << 2) | (0 << 4) | (1 << 5) | (1 << 6)
|
||||
|
||||
bit | value
|
||||
0-1 : 1 : index of the non-zero entry in the first row
|
||||
2-3 : 2 : index of the non-zero entry in the second row
|
||||
4 : 0 : the sign in the first row (0 : positive; 1 : negative)
|
||||
5 : 1 : the sign in the second row (0 : positive; 1 : negative)
|
||||
6 : 1 : the sign in the third row (0 : positive; 1 : negative)
|
||||
|
||||
=================================
|
||||
(d) Scene Graph
|
||||
|
||||
T : Transform Node
|
||||
G : Group Node
|
||||
S : Shape Node
|
||||
|
||||
T
|
||||
|
|
||||
G
|
||||
/ \
|
||||
T T
|
||||
| |
|
||||
G S
|
||||
/ \
|
||||
T T
|
||||
| |
|
||||
S S
|
||||
|
||||
=================================
|
||||
(1) Transform Node Chunk : "nTRN"
|
||||
|
||||
int32 : node id
|
||||
DICT : node attributes
|
||||
(_name : string)
|
||||
(_hidden : 0/1)
|
||||
int32 : child node id
|
||||
int32 : reserved id (must be -1)
|
||||
int32 : layer id
|
||||
int32 : num of frames (must be greater than 0)
|
||||
|
||||
// for each frame
|
||||
{
|
||||
DICT : frame attributes
|
||||
(_r : int8) ROTATION, see (c)
|
||||
(_t : int32x3) translation
|
||||
(_f : int32) frame index, start from 0
|
||||
}xN
|
||||
|
||||
=================================
|
||||
(2) Group Node Chunk : "nGRP"
|
||||
|
||||
int32 : node id
|
||||
DICT : node attributes
|
||||
int32 : num of children nodes
|
||||
|
||||
// for each child
|
||||
{
|
||||
int32 : child node id
|
||||
}xN
|
||||
|
||||
=================================
|
||||
(3) Shape Node Chunk : "nSHP"
|
||||
|
||||
int32 : node id
|
||||
DICT : node attributes
|
||||
int32 : num of models (must be greater than 0)
|
||||
|
||||
// for each model
|
||||
{
|
||||
int32 : model id
|
||||
DICT : model attributes : reserved
|
||||
(_f : int32) frame index, start from 0
|
||||
}xN
|
||||
|
||||
=================================
|
||||
(4) Material Chunk : "MATL"
|
||||
|
||||
int32 : material id
|
||||
DICT : material properties
|
||||
(_type : str) _diffuse, _metal, _glass, _emit
|
||||
(_weight : float) range 0 ~ 1
|
||||
(_rough : float)
|
||||
(_spec : float)
|
||||
(_ior : float)
|
||||
(_att : float)
|
||||
(_flux : float)
|
||||
(_plastic)
|
||||
|
||||
=================================
|
||||
(5) Layer Chunk : "LAYR"
|
||||
|
||||
int32 : layer id
|
||||
DICT : layer attribute
|
||||
(_name : string)
|
||||
(_hidden : 0/1)
|
||||
int32 : reserved id, must be -1
|
||||
|
||||
=================================
|
||||
(6) Render Objects Chunk : "rOBJ"
|
||||
|
||||
DICT : rendering attributes
|
||||
|
||||
=================================
|
||||
(7) Render Camera Chunk : "rCAM"
|
||||
|
||||
int32 : camera id
|
||||
DICT : camera attribute
|
||||
(_mode : string)
|
||||
(_focus : vec(3))
|
||||
(_angle : vec(3))
|
||||
(_radius : int)
|
||||
(_frustum : float)
|
||||
(_fov : int)
|
||||
|
||||
=================================
|
||||
(8) Palette Note Chunk : "NOTE"
|
||||
|
||||
int32 : num of color names
|
||||
|
||||
// for each name
|
||||
{
|
||||
STRING : color name
|
||||
}xN
|
||||
|
||||
=================================
|
||||
(9) Index MAP Chunk : "IMAP"
|
||||
|
||||
size : 256
|
||||
// for each index
|
||||
{
|
||||
int32 : palette index association
|
||||
}x256
|
||||
+111
@@ -0,0 +1,111 @@
|
||||
MagicaVoxel .vox File Format [10/18/2016]
|
||||
|
||||
1. File Structure : RIFF style
|
||||
-------------------------------------------------------------------------------
|
||||
# Bytes | Type | Value
|
||||
-------------------------------------------------------------------------------
|
||||
1x4 | char | id 'VOX ' : 'V' 'O' 'X' 'space', 'V' is first
|
||||
4 | int | version number : 150
|
||||
|
||||
Chunk 'MAIN'
|
||||
{
|
||||
// pack of models
|
||||
Chunk 'PACK' : optional
|
||||
|
||||
// models
|
||||
Chunk 'SIZE'
|
||||
Chunk 'XYZI'
|
||||
|
||||
Chunk 'SIZE'
|
||||
Chunk 'XYZI'
|
||||
|
||||
...
|
||||
|
||||
Chunk 'SIZE'
|
||||
Chunk 'XYZI'
|
||||
|
||||
// palette
|
||||
Chunk 'RGBA' : optional
|
||||
}
|
||||
-------------------------------------------------------------------------------
|
||||
|
||||
|
||||
2. Chunk Structure
|
||||
-------------------------------------------------------------------------------
|
||||
# Bytes | Type | Value
|
||||
-------------------------------------------------------------------------------
|
||||
1x4 | char | chunk id
|
||||
4 | int | num bytes of chunk content (N)
|
||||
4 | int | num bytes of children chunks (M)
|
||||
|
||||
N | | chunk content
|
||||
|
||||
M | | children chunks
|
||||
-------------------------------------------------------------------------------
|
||||
|
||||
|
||||
3. Chunk id 'MAIN' : the root chunk and parent chunk of all the other chunks
|
||||
|
||||
|
||||
4. Chunk id 'PACK' : if it is absent, only one model in the file; only used for the animation in 0.98.2
|
||||
-------------------------------------------------------------------------------
|
||||
# Bytes | Type | Value
|
||||
-------------------------------------------------------------------------------
|
||||
4 | int | numModels : num of SIZE and XYZI chunks
|
||||
-------------------------------------------------------------------------------
|
||||
|
||||
|
||||
5. Chunk id 'SIZE' : model size
|
||||
-------------------------------------------------------------------------------
|
||||
# Bytes | Type | Value
|
||||
-------------------------------------------------------------------------------
|
||||
4 | int | size x
|
||||
4 | int | size y
|
||||
4 | int | size z : gravity direction
|
||||
-------------------------------------------------------------------------------
|
||||
|
||||
|
||||
6. Chunk id 'XYZI' : model voxels, paired with the SIZE chunk
|
||||
-------------------------------------------------------------------------------
|
||||
# Bytes | Type | Value
|
||||
-------------------------------------------------------------------------------
|
||||
4 | int | numVoxels (N)
|
||||
4 x N | int | (x, y, z, colorIndex) : 1 byte for each component
|
||||
-------------------------------------------------------------------------------
|
||||
|
||||
|
||||
7. Chunk id 'RGBA' : palette
|
||||
-------------------------------------------------------------------------------
|
||||
# Bytes | Type | Value
|
||||
-------------------------------------------------------------------------------
|
||||
4 x 256 | int | (R, G, B, A) : 1 byte for each component
|
||||
| * <NOTICE>
|
||||
| * color [0-254] are mapped to palette index [1-255], e.g :
|
||||
|
|
||||
| for ( int i = 0; i <= 254; i++ ) {
|
||||
| palette[i + 1] = ReadRGBA();
|
||||
| }
|
||||
-------------------------------------------------------------------------------
|
||||
|
||||
|
||||
8. Default Palette : if chunk 'RGBA' is absent
|
||||
-------------------------------------------------------------------------------
|
||||
unsigned int default_palette[256] = {
|
||||
0x00000000, 0xffffffff, 0xffccffff, 0xff99ffff, 0xff66ffff, 0xff33ffff, 0xff00ffff, 0xffffccff, 0xffccccff, 0xff99ccff, 0xff66ccff, 0xff33ccff, 0xff00ccff, 0xffff99ff, 0xffcc99ff, 0xff9999ff,
|
||||
0xff6699ff, 0xff3399ff, 0xff0099ff, 0xffff66ff, 0xffcc66ff, 0xff9966ff, 0xff6666ff, 0xff3366ff, 0xff0066ff, 0xffff33ff, 0xffcc33ff, 0xff9933ff, 0xff6633ff, 0xff3333ff, 0xff0033ff, 0xffff00ff,
|
||||
0xffcc00ff, 0xff9900ff, 0xff6600ff, 0xff3300ff, 0xff0000ff, 0xffffffcc, 0xffccffcc, 0xff99ffcc, 0xff66ffcc, 0xff33ffcc, 0xff00ffcc, 0xffffcccc, 0xffcccccc, 0xff99cccc, 0xff66cccc, 0xff33cccc,
|
||||
0xff00cccc, 0xffff99cc, 0xffcc99cc, 0xff9999cc, 0xff6699cc, 0xff3399cc, 0xff0099cc, 0xffff66cc, 0xffcc66cc, 0xff9966cc, 0xff6666cc, 0xff3366cc, 0xff0066cc, 0xffff33cc, 0xffcc33cc, 0xff9933cc,
|
||||
0xff6633cc, 0xff3333cc, 0xff0033cc, 0xffff00cc, 0xffcc00cc, 0xff9900cc, 0xff6600cc, 0xff3300cc, 0xff0000cc, 0xffffff99, 0xffccff99, 0xff99ff99, 0xff66ff99, 0xff33ff99, 0xff00ff99, 0xffffcc99,
|
||||
0xffcccc99, 0xff99cc99, 0xff66cc99, 0xff33cc99, 0xff00cc99, 0xffff9999, 0xffcc9999, 0xff999999, 0xff669999, 0xff339999, 0xff009999, 0xffff6699, 0xffcc6699, 0xff996699, 0xff666699, 0xff336699,
|
||||
0xff006699, 0xffff3399, 0xffcc3399, 0xff993399, 0xff663399, 0xff333399, 0xff003399, 0xffff0099, 0xffcc0099, 0xff990099, 0xff660099, 0xff330099, 0xff000099, 0xffffff66, 0xffccff66, 0xff99ff66,
|
||||
0xff66ff66, 0xff33ff66, 0xff00ff66, 0xffffcc66, 0xffcccc66, 0xff99cc66, 0xff66cc66, 0xff33cc66, 0xff00cc66, 0xffff9966, 0xffcc9966, 0xff999966, 0xff669966, 0xff339966, 0xff009966, 0xffff6666,
|
||||
0xffcc6666, 0xff996666, 0xff666666, 0xff336666, 0xff006666, 0xffff3366, 0xffcc3366, 0xff993366, 0xff663366, 0xff333366, 0xff003366, 0xffff0066, 0xffcc0066, 0xff990066, 0xff660066, 0xff330066,
|
||||
0xff000066, 0xffffff33, 0xffccff33, 0xff99ff33, 0xff66ff33, 0xff33ff33, 0xff00ff33, 0xffffcc33, 0xffcccc33, 0xff99cc33, 0xff66cc33, 0xff33cc33, 0xff00cc33, 0xffff9933, 0xffcc9933, 0xff999933,
|
||||
0xff669933, 0xff339933, 0xff009933, 0xffff6633, 0xffcc6633, 0xff996633, 0xff666633, 0xff336633, 0xff006633, 0xffff3333, 0xffcc3333, 0xff993333, 0xff663333, 0xff333333, 0xff003333, 0xffff0033,
|
||||
0xffcc0033, 0xff990033, 0xff660033, 0xff330033, 0xff000033, 0xffffff00, 0xffccff00, 0xff99ff00, 0xff66ff00, 0xff33ff00, 0xff00ff00, 0xffffcc00, 0xffcccc00, 0xff99cc00, 0xff66cc00, 0xff33cc00,
|
||||
0xff00cc00, 0xffff9900, 0xffcc9900, 0xff999900, 0xff669900, 0xff339900, 0xff009900, 0xffff6600, 0xffcc6600, 0xff996600, 0xff666600, 0xff336600, 0xff006600, 0xffff3300, 0xffcc3300, 0xff993300,
|
||||
0xff663300, 0xff333300, 0xff003300, 0xffff0000, 0xffcc0000, 0xff990000, 0xff660000, 0xff330000, 0xff0000ee, 0xff0000dd, 0xff0000bb, 0xff0000aa, 0xff000088, 0xff000077, 0xff000055, 0xff000044,
|
||||
0xff000022, 0xff000011, 0xff00ee00, 0xff00dd00, 0xff00bb00, 0xff00aa00, 0xff008800, 0xff007700, 0xff005500, 0xff004400, 0xff002200, 0xff001100, 0xffee0000, 0xffdd0000, 0xffbb0000, 0xffaa0000,
|
||||
0xff880000, 0xff770000, 0xff550000, 0xff440000, 0xff220000, 0xff110000, 0xffeeeeee, 0xffdddddd, 0xffbbbbbb, 0xffaaaaaa, 0xff888888, 0xff777777, 0xff555555, 0xff444444, 0xff222222, 0xff111111
|
||||
};
|
||||
-------------------------------------------------------------------------------
|
||||
Vendored
BIN
Binary file not shown.
Vendored
BIN
Binary file not shown.
Vendored
BIN
Binary file not shown.
Vendored
BIN
Binary file not shown.
BIN
Binary file not shown.
BIN
Binary file not shown.
BIN
Binary file not shown.
Binary file not shown.
@@ -0,0 +1,289 @@
|
||||
-- model/vox tests: MagicaVoxel files (ephtracy samples, opengametools scene files saved by MagicaVoxel 0.99.x) and
|
||||
-- synthetic files with every chunk type, against an independent reader (tools/fixtures/vox.py): grids (CRC), palette,
|
||||
-- the default palette (parsed from the spec text), scene graph world transforms (rotations, mirrors, nesting), layers,
|
||||
-- materials, notes, cameras, render objects; greedy meshes (MeshOps) against the exposed face count; round trips
|
||||
-- through the writer; error codes; the fuzz no-throw pass. Fixtures: tools/fixtures/vox.py.
|
||||
local T = require("@tests/T")
|
||||
local Vox = require("@formats/model/vox")
|
||||
local MeshOps = require("@formats/ops/MeshOps")
|
||||
local Bytes = require("@formats/core/Bytes")
|
||||
local Crc32 = require("@formats/core/Crc32")
|
||||
local Err = require("@formats/core/Err")
|
||||
local Types = require("@formats/Types")
|
||||
local Cases = require("@tests/gen/vox_cases")
|
||||
local DefaultPalette = require("@tests/gen/vox_default_palette")
|
||||
|
||||
local t = T.suite("vox")
|
||||
|
||||
local function decode(data: any, opts: any?): (any, any)
|
||||
local b = if type(data) == "string" then buffer.fromstring(data) else data
|
||||
return Vox.decode(Bytes.reader(b), opts)
|
||||
end
|
||||
|
||||
-- the contract
|
||||
t:eq(Vox.name, "vox", "name")
|
||||
t:eq(Vox.category, "model", "category")
|
||||
t:check(Vox.extensions[1] == "vox" and Vox.caps.decode and Vox.caps.encode, "contract")
|
||||
|
||||
-- the default palette = the spec's array
|
||||
do
|
||||
t:eq(#Vox.DEFAULT_PALETTE, 255, "default palette size")
|
||||
local same = true
|
||||
for i = 1, 255 do
|
||||
for k = 1, 4 do
|
||||
if Vox.DEFAULT_PALETTE[i][k] ~= DefaultPalette[i][k] then
|
||||
same = false
|
||||
end
|
||||
end
|
||||
end
|
||||
t:check(same, "default palette equals the spec's")
|
||||
end
|
||||
|
||||
local function paletteCrc(pal: { { number } }): number
|
||||
local b = buffer.create(255 * 4)
|
||||
for i = 1, 255 do
|
||||
for k = 1, 4 do
|
||||
buffer.writeu8(b, (i - 1) * 4 + k - 1, pal[i][k])
|
||||
end
|
||||
end
|
||||
return Crc32.of(b)
|
||||
end
|
||||
|
||||
local function countKeys(tbl: any): number
|
||||
local n = 0
|
||||
for _ in tbl or {} do
|
||||
n += 1
|
||||
end
|
||||
return n
|
||||
end
|
||||
|
||||
-- shape nodes depth first with world matrices (column-major 4x4)
|
||||
local function shapes(scene: any): { any }
|
||||
local out = {}
|
||||
local function walk(i: number, parent: { number })
|
||||
local node = scene.nodes[i]
|
||||
local world = Types.Scene.mul(parent, Types.Scene.nodeMatrix(node))
|
||||
if node.voxels then
|
||||
table.insert(out, { name = node.name or "", model = node.voxels, world = world })
|
||||
end
|
||||
for _, c in node.children do
|
||||
walk(c, world)
|
||||
end
|
||||
end
|
||||
for _, r in scene.roots do
|
||||
walk(r, Types.Scene.IDENTITY)
|
||||
end
|
||||
return out
|
||||
end
|
||||
|
||||
local function checkScene(scene: any, c: any, label: string)
|
||||
t:eq(scene.kind, "scene", label .. ": a Scene")
|
||||
t:eq(scene.meta.up, "z", label .. ": z up")
|
||||
t:eq(#scene.voxels, #c.models, label .. ": models")
|
||||
for i, m in c.models do
|
||||
local v = scene.voxels[i]
|
||||
t:check(v.size[1] == m.size[1] and v.size[2] == m.size[2] and v.size[3] == m.size[3], label .. ": model " .. i .. " size")
|
||||
t:eq(Crc32.of(v.data), m.crc, label .. ": model " .. i .. " grid")
|
||||
end
|
||||
t:eq(paletteCrc(scene.voxels[1].palette), c.paletteCrc, label .. ": palette")
|
||||
local vm = scene.meta.vox
|
||||
t:eq(#(vm.layers or {}), c.layers, label .. ": layers")
|
||||
t:eq(countKeys(scene.voxels[1].materials), c.materials, label .. ": materials")
|
||||
t:eq(#(vm.notes or {}), c.notes, label .. ": notes")
|
||||
t:eq(#(vm.cameras or {}), c.cameras, label .. ": cameras")
|
||||
t:eq(#(vm.renderObjects or {}), c.robjs, label .. ": render objects")
|
||||
local glass = 0
|
||||
for _, m in scene.voxels[1].materials or {} do
|
||||
if m.type == "glass" then
|
||||
glass += 1
|
||||
end
|
||||
end
|
||||
t:eq(glass, c.glassMaterials, label .. ": glass materials")
|
||||
if #c.shapes > 0 then
|
||||
local got = shapes(scene)
|
||||
t:eq(#got, #c.shapes, label .. ": shape nodes")
|
||||
for k, want in c.shapes do
|
||||
local g = got[k]
|
||||
t:eq(g.name, want.name, label .. ": shape " .. k .. " name")
|
||||
t:eq(g.model, want.model, label .. ": shape " .. k .. " model")
|
||||
local ok = true
|
||||
for row = 0, 2 do
|
||||
for col = 0, 3 do
|
||||
local w = want.world[row * 4 + col + 1]
|
||||
local v = g.world[col * 4 + row + 1]
|
||||
if math.abs(w - v) > 1e-6 then
|
||||
ok = false
|
||||
end
|
||||
end
|
||||
end
|
||||
t:check(ok, label .. ": shape " .. k .. " (" .. want.name .. ") world transform")
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
-- area and winding of a greedy mesh
|
||||
local function meshFacts(prim: any): (number, boolean, number)
|
||||
local pos, nrm = prim.attributes.POSITION.data, prim.attributes.NORMAL.data
|
||||
local ind = prim.indices.data
|
||||
local area, wound = 0, true
|
||||
for tri = 0, prim.indices.count // 3 - 1 do
|
||||
local a, b, c = buffer.readu32(ind, tri * 12), buffer.readu32(ind, tri * 12 + 4), buffer.readu32(ind, tri * 12 + 8)
|
||||
local function p(i: number, k: number): number
|
||||
return buffer.readf32(pos, i * 12 + k * 4)
|
||||
end
|
||||
local e1 = { p(b, 0) - p(a, 0), p(b, 1) - p(a, 1), p(b, 2) - p(a, 2) }
|
||||
local e2 = { p(c, 0) - p(a, 0), p(c, 1) - p(a, 1), p(c, 2) - p(a, 2) }
|
||||
local nx, ny, nz = e1[2] * e2[3] - e1[3] * e2[2], e1[3] * e2[1] - e1[1] * e2[3], e1[1] * e2[2] - e1[2] * e2[1]
|
||||
area += math.sqrt(nx * nx + ny * ny + nz * nz) / 2
|
||||
local dot = nx * buffer.readf32(nrm, a * 12) + ny * buffer.readf32(nrm, a * 12 + 4) + nz * buffer.readf32(nrm, a * 12 + 8)
|
||||
if dot <= 0 then
|
||||
wound = false
|
||||
end
|
||||
end
|
||||
return area, wound, prim.indices.count // 3
|
||||
end
|
||||
|
||||
local totalQuads, totalFaces = 0, 0
|
||||
for _, c in Cases do
|
||||
local label = c.name
|
||||
local scene, err = decode(c.data)
|
||||
t:check(scene, label .. ": decode: " .. tostring(err))
|
||||
checkScene(scene, c, label)
|
||||
t:eq(scene.meta.source.version, c.version, label .. ": version")
|
||||
-- decodeVoxels, and from a sub-range of a bigger buffer
|
||||
local big = buffer.create(#c.data + 9)
|
||||
buffer.writestring(big, 5, c.data)
|
||||
local grids = Vox.decodeVoxels(Bytes.reader(big, 5, #c.data))
|
||||
t:check(grids and #grids == #c.models and Crc32.of(grids[1].data) == c.models[1].crc, label .. ": decodeVoxels from a sub-range")
|
||||
-- greedy meshing: the area is the number of exposed unit faces, every triangle faces its normal
|
||||
for i, m in c.models do
|
||||
local prim, perr = MeshOps.voxelsToPrimitive(scene.voxels[i], { pivot = "corner" })
|
||||
t:check(prim, label .. ": mesh: " .. tostring(perr))
|
||||
local area, wound, tris = meshFacts(prim)
|
||||
t:eq(area, m.faces, label .. ": model " .. i .. " greedy mesh area = exposed faces")
|
||||
t:check(wound, label .. ": model " .. i .. " winding matches the normals")
|
||||
t:check(tris <= m.faces * 2, label .. ": model " .. i .. " no more triangles than faces")
|
||||
totalQuads += tris // 2
|
||||
totalFaces += m.faces
|
||||
end
|
||||
-- round trip through the writer
|
||||
local out, eerr = Vox.encode(scene)
|
||||
t:check(out, label .. ": encode: " .. tostring(eerr))
|
||||
local back, berr = Vox.decode(Bytes.reader(out :: buffer))
|
||||
t:check(back, label .. ": decode our file: " .. tostring(berr))
|
||||
checkScene(back, c, label .. " (round trip)")
|
||||
t:eq(back.meta.source.version, 200, label .. ": written as version 200")
|
||||
local out2 = Vox.encode(back) :: buffer
|
||||
t:check(buffer.tostring(out2) == buffer.tostring(out :: buffer), label .. ": writing is stable")
|
||||
if scene.meta.vox.info then
|
||||
t:check(back.meta.vox.info and back.meta.vox.info._anim_range == scene.meta.vox.info._anim_range, label .. ": META")
|
||||
end
|
||||
end
|
||||
t:note("%d files: grids, palettes, scene graphs and round trips match; greedy: %d quads for %d faces", #Cases, totalQuads, totalFaces)
|
||||
|
||||
-- the synthetic scene in detail: names, hidden, layers, animation frames, materials, notes, IMAP, unknown chunks
|
||||
do
|
||||
local c
|
||||
for _, x in Cases do
|
||||
if x.name == "syn-scene" then
|
||||
c = x
|
||||
end
|
||||
end
|
||||
local scene = decode(c.data)
|
||||
local byName = {}
|
||||
for _, n in scene.nodes do
|
||||
if n.name then
|
||||
byName[n.name] = n
|
||||
end
|
||||
end
|
||||
t:check(byName.group and byName.group.extras.vox.attributes._hidden == "1" and byName.group.extras.vox.layer == 1, "hidden group on layer 1")
|
||||
t:check(byName.b and byName.b.matrix ~= nil, "a mirrored node keeps a matrix")
|
||||
t:check(byName.a and byName.a.matrix == nil and byName.a.rotation == nil and byName.a.translation[3] == 3, "identity rotation: translation only")
|
||||
t:check(byName.anim and #byName.anim.extras.vox.frames == 2 and #byName.anim.extras.vox.shape.models == 2, "animation frames and shape models")
|
||||
local mats = scene.voxels[1].materials
|
||||
t:check(mats[1].type == "glass" and mats[2].type == "emit" and mats[1].rough == 0.25 and mats[1].ior == 1.5 and mats[200].type == "emit", "materials")
|
||||
t:check(scene.meta.vox.notes[2] == "second" and scene.meta.vox.indexMap[256] == 255, "notes, IMAP")
|
||||
t:check(scene.meta.vox.layers[2].name == "one" and scene.meta.vox.layers[2].hidden, "layers")
|
||||
t:check(scene.meta.vox.cameras[1].attributes._fov == "45", "rCAM")
|
||||
t:check(scene.meta.vox.chunks and scene.meta.vox.chunks[1].id == "ZZZZ", "unknown chunk kept")
|
||||
local back = Vox.decode(Bytes.reader(Vox.encode(scene) :: buffer)) :: any
|
||||
local bn = {}
|
||||
for _, n in back.nodes do
|
||||
if n.name then
|
||||
bn[n.name] = n
|
||||
end
|
||||
end
|
||||
t:check(bn.anim and #bn.anim.extras.vox.frames == 2 and bn.anim.extras.vox.frames[2]._t == "4 4 4", "frames round trip")
|
||||
t:check(back.meta.vox.chunks and buffer.tostring(back.meta.vox.chunks[1].content) == "unknown payload", "unknown chunk round trip")
|
||||
t:check(back.voxels[1].materials[200].flux == 2, "material round trip")
|
||||
-- meshVoxels: every shape node gets the mesh of its grid
|
||||
MeshOps.meshVoxels(back)
|
||||
local meshed = 0
|
||||
for _, n in back.nodes do
|
||||
if n.voxels then
|
||||
t:check(n.mesh ~= nil and back.meshes[n.mesh].primitives[1].attributes.COLOR_0 ~= nil, "meshVoxels sets node.mesh")
|
||||
meshed += 1
|
||||
end
|
||||
end
|
||||
t:check(meshed == 4 and #back.meshes == 4, "four shapes meshed")
|
||||
local lo, hi = MeshOps.bounds(back)
|
||||
t:check(lo and hi and hi[1] > lo[1], "scene bounds of the meshed shapes")
|
||||
end
|
||||
|
||||
-- a Voxels grid alone; the centred pivot; sRGB colours
|
||||
do
|
||||
local v = Types.Voxels.new(3, 4, 5, Vox.DEFAULT_PALETTE)
|
||||
Types.Voxels.set(v, 0, 0, 0, 1)
|
||||
Types.Voxels.set(v, 2, 3, 4, 200)
|
||||
local out, err = Vox.encode(v)
|
||||
t:check(out, "encode a Voxels grid: " .. tostring(err))
|
||||
local back = Vox.decode(Bytes.reader(out :: buffer)) :: any
|
||||
t:check(back and #back.voxels == 1 and Types.Voxels.get(back.voxels[1], 2, 3, 4) == 200 and Types.Voxels.get(back.voxels[1], 1, 1, 1) == 0, "Voxels round trip")
|
||||
local prim = MeshOps.voxelsToPrimitive(v, { colors = "srgb", indexAttribute = true }) :: any
|
||||
local lo, hi = MeshOps.bounds(prim)
|
||||
t:check(lo and hi and lo[1] == -1 and lo[2] == -2 and lo[3] == -2 and hi[1] == 2 and hi[2] == 2 and hi[3] == 3, "centre pivot")
|
||||
t:check(prim.attributes.COLOR_0.type == "unorm8" and prim.attributes._PALETTE_INDEX.type == "u8", "srgb colours, index attribute")
|
||||
t:eq(prim.indices.count, 72, "two separate cubes: 12 quads")
|
||||
end
|
||||
|
||||
-- errors
|
||||
do
|
||||
local _, e = decode("nope")
|
||||
t:check(e and e.code == Err.CORRUPT, "junk: " .. tostring(e))
|
||||
local c = Cases[1]
|
||||
local _, e2 = decode(c.data, { maxCells = 10 })
|
||||
t:check(e2 and e2.code == Err.LIMIT, "maxCells: " .. tostring(e2))
|
||||
local _, e3 = decode(string.sub(c.data, 1, 30))
|
||||
t:check(e3 ~= nil, "truncated: " .. tostring(e3))
|
||||
local _, e4 = Vox.encode({} :: any)
|
||||
t:check(e4 and e4.code == Err.ARG, "encode junk")
|
||||
local big = Types.Voxels.new(300, 1, 1)
|
||||
local _, e5 = Vox.encode(big)
|
||||
t:check(e5 and e5.code == Err.ARG, "over 256 cells: " .. tostring(e5))
|
||||
local s = Vox.decode(Bytes.reader(buffer.fromstring(Cases[1].data))) :: any
|
||||
s.nodes[s.roots[1]].rotation = { 0, 0, math.sin(0.3), math.cos(0.3) }
|
||||
local _, e6 = Vox.encode(s)
|
||||
t:check(e6 and e6.code == Err.ARG, "a 34 degree rotation: " .. tostring(e6))
|
||||
local _, e7 = MeshOps.voxelsToPrimitive({} :: any)
|
||||
t:check(e7 and e7.code == Err.ARG, "voxelsToPrimitive of junk")
|
||||
end
|
||||
|
||||
-- fuzz
|
||||
do
|
||||
local samples = {}
|
||||
for _, c in Cases do
|
||||
if #c.data < 100000 then
|
||||
table.insert(samples, c.data)
|
||||
end
|
||||
end
|
||||
t:fuzz("decode", function(b: buffer)
|
||||
local s = Vox.decode(Bytes.reader(b))
|
||||
if s then
|
||||
MeshOps.meshVoxels(s)
|
||||
Vox.encode(s)
|
||||
end
|
||||
return s
|
||||
end, samples, { mutations = 30, keepHeader = 8 })
|
||||
end
|
||||
|
||||
t:done()
|
||||
@@ -0,0 +1,292 @@
|
||||
# VOX fixtures (tools/fixtures.py). There is no MagicaVoxel reader in nixpkgs, so the reference is (1) files saved by
|
||||
# MagicaVoxel itself (tests/fixtures/vox: ephtracy/voxel-model samples, version 150, and jpaver/opengametools demo files
|
||||
# with scene graphs, layers, materials, render objects, cameras, notes and META; licences in licenses/), parsed here
|
||||
# by an independent Python reader written from the spec, and (2) synthetic files written here with every chunk type,
|
||||
# rotations (including mirrors), nested groups, animation frames and odd cases.
|
||||
# tests/gen/vox_cases.luau { name, data, version, models = { { size, count, crc (of the dense x-fastest grid),
|
||||
# faces (exposed unit faces: the greedy mesh area) } }, paletteCrc, chunks = { id = n },
|
||||
# nodes = { { name, world (row-major 3x4: R | t) } } for every shape node, names, layers,
|
||||
# materials, notes, cameras, robjs }
|
||||
import os, struct, zlib
|
||||
|
||||
INPUTS = ["tests/fixtures/vox"]
|
||||
|
||||
def default_palette():
|
||||
steps = [0xff, 0xcc, 0x99, 0x66, 0x33, 0]
|
||||
pal = [(r, g, b, 255) for r in steps for g in steps for b in steps][:215]
|
||||
ramp = [0xee, 0xdd, 0xbb, 0xaa, 0x88, 0x77, 0x55, 0x44, 0x22, 0x11]
|
||||
for ch in range(3):
|
||||
for v in ramp:
|
||||
c = [0, 0, 0, 255]
|
||||
c[ch] = v
|
||||
pal.append(tuple(c))
|
||||
pal += [(v, v, v, 255) for v in ramp]
|
||||
return pal
|
||||
|
||||
|
||||
def spec_palette(text):
|
||||
# the default_palette[256] array of the spec text (ABGR words, entry i = palette index i)
|
||||
body = text[text.index("default_palette[256]"):]
|
||||
body = body[body.index("{") + 1:body.index("}")]
|
||||
words = [int(w, 16) for w in body.replace(",", " ").split()]
|
||||
return [(w & 255, (w >> 8) & 255, (w >> 16) & 255, w >> 24) for w in words]
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------------------------- reader (reference)
|
||||
def rd_dict(d, p):
|
||||
n, = struct.unpack_from("<i", d, p)
|
||||
p += 4
|
||||
out = {}
|
||||
for _ in range(n):
|
||||
kl, = struct.unpack_from("<i", d, p)
|
||||
k = d[p + 4:p + 4 + kl].decode("latin1")
|
||||
p += 4 + kl
|
||||
vl, = struct.unpack_from("<i", d, p)
|
||||
v = d[p + 4:p + 4 + vl].decode("latin1")
|
||||
p += 4 + vl
|
||||
out[k] = v
|
||||
return out, p
|
||||
|
||||
|
||||
def rot(b):
|
||||
i0, i1 = b & 3, (b >> 2) & 3
|
||||
i2 = 3 - i0 - i1
|
||||
R = [[0] * 3 for _ in range(3)]
|
||||
for row, (i, bit) in enumerate(((i0, 4), (i1, 5), (i2, 6))):
|
||||
R[row][i] = -1 if b & (1 << bit) else 1
|
||||
return R
|
||||
|
||||
|
||||
def matmul(A, B): # 3x4 affine (R | t)
|
||||
R = [[sum(A[r][k] * B[k][c] for k in range(3)) for c in range(3)] for r in range(3)]
|
||||
t = [sum(A[r][k] * B[k][3] for k in range(3)) + A[r][3] for r in range(3)]
|
||||
return [R[r] + [t[r]] for r in range(3)]
|
||||
|
||||
|
||||
def parse(d):
|
||||
assert d[:4] == b"VOX "
|
||||
version, = struct.unpack_from("<i", d, 4)
|
||||
assert d[8:12] == b"MAIN"
|
||||
n, m = struct.unpack_from("<ii", d, 12)
|
||||
p = 20 + n
|
||||
end = min(p + m, len(d))
|
||||
models, size, palette = [], None, None
|
||||
graph, counts = {}, {}
|
||||
mats, layers, notes, cams, robjs = {}, [], [], [], []
|
||||
while p + 12 <= end:
|
||||
cid = d[p:p + 4].decode("latin1")
|
||||
n, m = struct.unpack_from("<ii", d, p + 4)
|
||||
c = p + 12
|
||||
counts[cid] = counts.get(cid, 0) + 1
|
||||
if cid == "SIZE":
|
||||
size = struct.unpack_from("<iii", d, c)
|
||||
elif cid == "XYZI":
|
||||
k, = struct.unpack_from("<i", d, c)
|
||||
sx, sy, sz = size
|
||||
grid = bytearray(sx * sy * sz)
|
||||
for i in range(k):
|
||||
x, y, z, ci = d[c + 4 + i * 4:c + 8 + i * 4]
|
||||
if x < sx and y < sy and z < sz and ci:
|
||||
grid[x + sx * (y + sy * z)] = ci
|
||||
models.append((size, grid))
|
||||
elif cid == "RGBA":
|
||||
palette = [tuple(d[c + i * 4:c + i * 4 + 4]) for i in range(255)]
|
||||
elif cid == "MATL":
|
||||
mid, = struct.unpack_from("<i", d, c)
|
||||
mats[mid], _ = rd_dict(d, c + 4)
|
||||
elif cid == "nTRN":
|
||||
nid, = struct.unpack_from("<i", d, c)
|
||||
attrs, q = rd_dict(d, c + 4)
|
||||
child, _, layer, nf = struct.unpack_from("<iiii", d, q)
|
||||
q += 16
|
||||
frames = []
|
||||
for _ in range(nf):
|
||||
f, q = rd_dict(d, q)
|
||||
frames.append(f)
|
||||
graph[nid] = ("T", attrs, child, frames)
|
||||
elif cid == "nGRP":
|
||||
nid, = struct.unpack_from("<i", d, c)
|
||||
attrs, q = rd_dict(d, c + 4)
|
||||
k, = struct.unpack_from("<i", d, q)
|
||||
graph[nid] = ("G", attrs, list(struct.unpack_from("<%di" % k, d, q + 4)))
|
||||
elif cid == "nSHP":
|
||||
nid, = struct.unpack_from("<i", d, c)
|
||||
attrs, q = rd_dict(d, c + 4)
|
||||
k, = struct.unpack_from("<i", d, q)
|
||||
mid, = struct.unpack_from("<i", d, q + 4)
|
||||
graph[nid] = ("S", attrs, mid)
|
||||
elif cid == "LAYR":
|
||||
lid, = struct.unpack_from("<i", d, c)
|
||||
layers.append(rd_dict(d, c + 4)[0])
|
||||
elif cid == "NOTE":
|
||||
k, = struct.unpack_from("<i", d, c)
|
||||
q = c + 4
|
||||
for _ in range(k):
|
||||
l, = struct.unpack_from("<i", d, q)
|
||||
notes.append(d[q + 4:q + 4 + l].decode("latin1"))
|
||||
q += 4 + l
|
||||
elif cid == "rCAM":
|
||||
cams.append(struct.unpack_from("<i", d, c)[0])
|
||||
elif cid == "rOBJ":
|
||||
robjs.append(rd_dict(d, c)[0])
|
||||
p = c + n + m
|
||||
# shape nodes in depth-first order with world transforms
|
||||
shapes = []
|
||||
|
||||
def walk(nid, parent):
|
||||
kind, attrs, child, frames = graph[nid]
|
||||
f = frames[0] if frames else {}
|
||||
R = rot(int(f["_r"])) if "_r" in f else [[1, 0, 0], [0, 1, 0], [0, 0, 1]]
|
||||
t = [int(v) for v in f.get("_t", "0 0 0").split()]
|
||||
world = matmul(parent, [R[r] + [t[r]] for r in range(3)])
|
||||
ch = graph.get(child)
|
||||
if ch and ch[0] == "G":
|
||||
for c2 in ch[2]:
|
||||
walk(c2, world)
|
||||
elif ch and ch[0] == "S":
|
||||
shapes.append({"name": attrs.get("_name", ""), "model": ch[2] + 1, "world": [v for row in world for v in row]})
|
||||
|
||||
if 0 in graph:
|
||||
walk(0, [[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1, 0]])
|
||||
pal = palette or default_palette()
|
||||
out_models = []
|
||||
for (sx, sy, sz), grid in models:
|
||||
faces = 0
|
||||
for z in range(sz):
|
||||
for y in range(sy):
|
||||
for x in range(sx):
|
||||
if grid[x + sx * (y + sy * z)]:
|
||||
for dx, dy, dz in ((1, 0, 0), (-1, 0, 0), (0, 1, 0), (0, -1, 0), (0, 0, 1), (0, 0, -1)):
|
||||
X, Y, Z = x + dx, y + dy, z + dz
|
||||
if not (0 <= X < sx and 0 <= Y < sy and 0 <= Z < sz) or not grid[X + sx * (Y + sy * Z)]:
|
||||
faces += 1
|
||||
out_models.append({"size": [sx, sy, sz], "count": sum(1 for v in grid if v), "crc": zlib.crc32(bytes(grid)), "faces": faces})
|
||||
return {
|
||||
"version": version,
|
||||
"models": out_models,
|
||||
"paletteCrc": zlib.crc32(bytes(v for c in pal for v in c)),
|
||||
"hasPalette": palette is not None,
|
||||
"chunks": counts,
|
||||
"shapes": shapes,
|
||||
"layers": len(layers),
|
||||
"materials": len(mats),
|
||||
"notes": len(notes),
|
||||
"cameras": len(cams),
|
||||
"robjs": len(robjs),
|
||||
"glassMaterials": sum(1 for m in mats.values() if m.get("_type") == "_glass"),
|
||||
}
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------------------------- writer (synthetic files)
|
||||
def s(x):
|
||||
b = x.encode()
|
||||
return struct.pack("<i", len(b)) + b
|
||||
|
||||
|
||||
def dct(d):
|
||||
return struct.pack("<i", len(d)) + b"".join(s(k) + s(v) for k, v in d.items())
|
||||
|
||||
|
||||
def chunk(cid, content, children=b""):
|
||||
return cid.encode() + struct.pack("<ii", len(content), len(children)) + content + children
|
||||
|
||||
|
||||
def vox(chunks, version=200, main_size=None):
|
||||
body = b"".join(chunks)
|
||||
return b"VOX " + struct.pack("<i", version) + b"MAIN" + struct.pack("<ii", 0, main_size if main_size is not None else len(body)) + body
|
||||
|
||||
|
||||
def model(rng, sx, sy, sz, fill=0.4, colors=(1, 255)):
|
||||
vox_list = []
|
||||
for z in range(sz):
|
||||
for y in range(sy):
|
||||
for x in range(sx):
|
||||
if rng.random() < fill:
|
||||
vox_list.append((x, y, z, rng.randrange(*colors)))
|
||||
rng.shuffle(vox_list)
|
||||
return [chunk("SIZE", struct.pack("<iii", sx, sy, sz)), chunk("XYZI", struct.pack("<i", len(vox_list)) + b"".join(bytes(v) for v in vox_list))]
|
||||
|
||||
|
||||
def ntrn(nid, child, attrs=None, frames=None, layer=0):
|
||||
frames = frames or [{}]
|
||||
return chunk("nTRN", struct.pack("<i", nid) + dct(attrs or {}) + struct.pack("<iiii", child, -1, layer, len(frames)) + b"".join(dct(f) for f in frames))
|
||||
|
||||
|
||||
def ngrp(nid, children, attrs=None):
|
||||
return chunk("nGRP", struct.pack("<i", nid) + dct(attrs or {}) + struct.pack("<i", len(children)) + b"".join(struct.pack("<i", c) for c in children))
|
||||
|
||||
|
||||
def nshp(nid, models_):
|
||||
return chunk("nSHP", struct.pack("<i", nid) + dct({}) + struct.pack("<i", len(models_)) + b"".join(struct.pack("<i", m) + dct({"_f": str(i)} if len(models_) > 1 else {}) for i, m in enumerate(models_)))
|
||||
|
||||
|
||||
def rgba(rng):
|
||||
return chunk("RGBA", bytes(rng.randrange(256) for _ in range(1024)))
|
||||
|
||||
|
||||
def synthetic(rng):
|
||||
out = []
|
||||
# 1. a plain v150 model without a palette (the default palette)
|
||||
out.append(("syn-default-palette", vox(model(rng, 7, 5, 3), 150)))
|
||||
# 2. full scene: nested groups, every rotation family, mirrors, hidden, layers, materials, notes, cameras, IMAP, META
|
||||
ch = []
|
||||
for _ in range(4):
|
||||
ch += model(rng, rng.randrange(1, 12), rng.randrange(1, 12), rng.randrange(1, 12))
|
||||
ch += [
|
||||
ntrn(0, 1, layer=-1),
|
||||
ngrp(1, [2, 4, 8]),
|
||||
ntrn(2, 3, {"_name": "a"}, [{"_r": "4", "_t": "1 2 3"}]),
|
||||
nshp(3, [0]),
|
||||
ntrn(4, 5, {"_name": "group", "_hidden": "1"}, [{"_r": "17", "_t": "-5 0 7"}], layer=1), # 90 deg about z
|
||||
ngrp(5, [6, 10]),
|
||||
ntrn(6, 7, {"_name": "b"}, [{"_r": "20", "_t": "0 0 -4"}]), # a mirror (x flipped)
|
||||
nshp(7, [1]),
|
||||
ntrn(8, 9, {"_name": "anim"}, [{"_r": "9", "_t": "3 3 3", "_f": "0"}, {"_r": "4", "_t": "4 4 4", "_f": "5"}]),
|
||||
nshp(9, [2, 3]),
|
||||
ntrn(10, 11, {"_name": "c"}, [{"_r": "98", "_t": "10 -20 30"}]),
|
||||
nshp(11, [3]),
|
||||
chunk("LAYR", struct.pack("<i", 0) + dct({"_name": "zero"}) + struct.pack("<i", -1)),
|
||||
chunk("LAYR", struct.pack("<i", 1) + dct({"_name": "one", "_hidden": "1", "_color": "255 0 0"}) + struct.pack("<i", -1)),
|
||||
rgba(rng),
|
||||
chunk("IMAP", bytes(range(256))),
|
||||
]
|
||||
for mid in (1, 2, 200):
|
||||
ch.append(chunk("MATL", struct.pack("<i", mid) + dct({"_type": ["_diffuse", "_glass", "_emit"][mid % 3], "_rough": "0.25", "_ior": "1.5", "_flux": "2"})))
|
||||
ch.append(chunk("rOBJ", dct({"_type": "_bg", "_color": "0 0 0"})))
|
||||
ch.append(chunk("rCAM", struct.pack("<i", 0) + dct({"_mode": "pers", "_focus": "0 0 0", "_angle": "30 40 0", "_radius": "80", "_frustum": "0.4", "_fov": "45"})))
|
||||
ch.append(chunk("NOTE", struct.pack("<i", 2) + s("first") + s("second")))
|
||||
ch.insert(0, chunk("META", dct({"_anim_range": "0 30"})))
|
||||
ch.append(chunk("ZZZZ", b"unknown payload"))
|
||||
out.append(("syn-scene", vox(ch)))
|
||||
# 3. edge cases: voxels outside the grid, index 0, duplicates, a 1x1x1 model
|
||||
vox_list = [(0, 0, 0, 5), (9, 0, 0, 7), (1, 1, 1, 0), (1, 1, 1, 9), (1, 1, 1, 10)]
|
||||
ch = [chunk("SIZE", struct.pack("<iii", 2, 2, 2)), chunk("XYZI", struct.pack("<i", len(vox_list)) + b"".join(bytes(v) for v in vox_list)), rgba(rng)]
|
||||
out.append(("syn-edge", vox(ch)))
|
||||
out.append(("syn-single", vox([chunk("SIZE", struct.pack("<iii", 1, 1, 1)), chunk("XYZI", struct.pack("<i", 1) + bytes((0, 0, 0, 1)))])))
|
||||
# 4. a full 64^3 block and a 3d checkerboard (worst case for greedy meshing)
|
||||
full = [(x, y, z, 1 + (z % 3)) for z in range(64) for y in range(64) for x in range(64)]
|
||||
out.append(("syn-block64", vox([chunk("SIZE", struct.pack("<iii", 64, 64, 64)), chunk("XYZI", struct.pack("<i", len(full)) + b"".join(bytes(v) for v in full))])))
|
||||
chk = [(x, y, z, 3) for z in range(16) for y in range(16) for x in range(16) if (x + y + z) % 2 == 0]
|
||||
out.append(("syn-checker16", vox([chunk("SIZE", struct.pack("<iii", 16, 16, 16)), chunk("XYZI", struct.pack("<i", len(chk)) + b"".join(bytes(v) for v in chk))])))
|
||||
return out
|
||||
|
||||
|
||||
def generate(ctx):
|
||||
rng = ctx.rng(7)
|
||||
cases = []
|
||||
folder = os.path.join("tests", "fixtures", "vox")
|
||||
for f in sorted(os.listdir(os.path.join(ctx.root, folder))):
|
||||
if f.endswith(".vox"):
|
||||
cases.append((f, ctx.read(os.path.join(folder, f))))
|
||||
cases += synthetic(rng)
|
||||
out = []
|
||||
for name, data in cases:
|
||||
ref = parse(data)
|
||||
ref["name"] = name
|
||||
ref["data"] = data
|
||||
out.append(ref)
|
||||
ctx.emit("vox_cases", out)
|
||||
# the spec's default palette (parsed from the spec text) must equal the formula used by both readers
|
||||
pal = spec_palette(ctx.read(os.path.join(folder, "MagicaVoxel-file-format-vox.txt")).decode())[1:]
|
||||
assert pal == default_palette(), "default palette formula differs from the spec"
|
||||
ctx.emit("vox_default_palette", [list(c) for c in pal])
|
||||
Reference in new issue
Block a user