diff --git a/compat/luajit.lua b/compat/luajit.lua index 3b7a194..8635a4a 100644 --- a/compat/luajit.lua +++ b/compat/luajit.lua @@ -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 diff --git a/licenses/NOTICE.md b/licenses/NOTICE.md index 5d28e73..383183a 100644 --- a/licenses/NOTICE.md +++ b/licenses/NOTICE.md @@ -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"). diff --git a/licenses/opengametools-LICENSE.txt b/licenses/opengametools-LICENSE.txt new file mode 100644 index 0000000..eadf720 --- /dev/null +++ b/licenses/opengametools-LICENSE.txt @@ -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. diff --git a/licenses/voxel-model-LICENSE.txt b/licenses/voxel-model-LICENSE.txt new file mode 100644 index 0000000..d6af977 --- /dev/null +++ b/licenses/voxel-model-LICENSE.txt @@ -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. diff --git a/src/Formats/Types.luau b/src/Formats/Types.luau index 92b0812..655f439 100644 --- a/src/Formats/Types.luau +++ b/src/Formats/Types.luau @@ -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 } } diff --git a/src/Formats/model/vox/Grid.luau b/src/Formats/model/vox/Grid.luau new file mode 100644 index 0000000..4a6601e --- /dev/null +++ b/src/Formats/model/vox/Grid.luau @@ -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 diff --git a/src/Formats/model/vox/init.luau b/src/Formats/model/vox/init.luau new file mode 100644 index 0000000..81277aa --- /dev/null +++ b/src/Formats/model/vox/init.luau @@ -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 diff --git a/src/Formats/ops/MeshOps/Greedy.luau b/src/Formats/ops/MeshOps/Greedy.luau new file mode 100644 index 0000000..26ddb50 --- /dev/null +++ b/src/Formats/ops/MeshOps/Greedy.luau @@ -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 diff --git a/src/Formats/ops/MeshOps/init.luau b/src/Formats/ops/MeshOps/init.luau new file mode 100644 index 0000000..92ce069 --- /dev/null +++ b/src/Formats/ops/MeshOps/init.luau @@ -0,0 +1,1087 @@ +--!strict +-- ops/MeshOps: editing meshes in the standard Scene type (Types.luau): triangulate (strips, fans, n-gons by fan or ear +-- clipping), transform (positions, normals, tangents; winding kept for mirrors), computeNormals (area weighted, or flat), +-- computeTangents (per-triangle UV derivatives, Lengyel 2001, Gram-Schmidt + handedness in w), weld (exact or within an +-- epsilon), bounds, merge (a whole scene baked into world space, one primitive or one per material), unit and up-axis +-- changes, and greedy meshing of voxel grids (VOX: voxelsToPrimitive, meshVoxels). +-- Every function takes / returns Primitives and Scenes as decoded by the model formats; inputs may use any accessor type +-- (f32, unorm8, snorm16, ...): outputs are f32 attributes and u32 indices. Bad arguments return nil, Err (never throw). +-- +-- local MeshOps = require("@formats/ops/MeshOps") -- F.ops.mesh in the api (when it lists ops) +-- local prim = MeshOps.merge(scene) -- one triangle primitive in world space +-- MeshOps.computeNormals(prim) +-- MeshOps.meshVoxels(voxScene) -- greedy meshes for every voxel shape +local Err = require("@formats/core/Err") +local Types = require("@formats/Types") +local Greedy = require("@formats/ops/MeshOps/Greedy") + +local MeshOps = {} + +type Accessor = Types.Accessor +type Primitive = Types.Primitive +type Scene = Types.Scene + +local Scene = Types.Scene +local readf32, writef32 = buffer.readf32, buffer.writef32 +local readu32, writeu32 = buffer.readu32, buffer.writeu32 + +-- ------------------------------------------------------------------------------------------------ accessors +-- f32(acc) -> the accessor as f32 (the same accessor when it already is), nil for a broken one +function MeshOps.f32(acc: Accessor): Accessor? + if acc.type == "f32" then + return acc + end + local get = Scene.reader(acc) + if not get then + return nil + end + local n, c = acc.count, acc.components + local out = buffer.create(n * c * 4) + for i = 0, n - 1 do + for k = 0, c - 1 do + writef32(out, (i * c + k) * 4, get(i, k)) + end + end + local a = Scene.accessor(out, "f32", c, n) + a.matrix = acc.matrix + return a +end + +-- the index list of a primitive (u32 buffer, count): its indices, or 0 .. n - 1 +local function indexBuffer(prim: Primitive): (buffer, number) + local ind = prim.indices + if ind then + if ind.type == "u32" and ind.components == 1 then + return ind.data, ind.count + end + local get = Scene.reader(ind) + local out = buffer.create(ind.count * 4) + if get then + for i = 0, ind.count - 1 do + writeu32(out, i * 4, get(i, 0)) + end + end + return out, ind.count + end + local pos = prim.attributes.POSITION + local n = if pos then pos.count else 0 + local out = buffer.create(n * 4) + for i = 0, n - 1 do + writeu32(out, i * 4, i) + end + return out, n +end + +local function vertexCount(prim: Primitive): number + local pos = prim.attributes.POSITION + return if pos then pos.count else 0 +end + +local function checkPrim(prim: any): Err.Err? + if type(prim) ~= "table" or type(prim.attributes) ~= "table" then + return Err.new(Err.ARG, "expected a Primitive") + end + local pos = prim.attributes.POSITION + if not pos or type(pos.data) ~= "buffer" or pos.components < 3 then + return Err.new(Err.ARG, "primitive without a POSITION accessor") + end + local n = pos.count + for name, a in prim.attributes do + local size = Types.COMPONENT_SIZE[a.type] + if not size or type(a.data) ~= "buffer" or buffer.len(a.data) < a.count * a.components * size then + return Err.new(Err.ARG, "attribute " .. tostring(name) .. ": bad accessor") + end + if a.count ~= n then + return Err.new(Err.ARG, "attribute " .. tostring(name) .. ": count differs from POSITION") + end + end + if prim.indices then + local ind = prim.indices + local size = Types.COMPONENT_SIZE[ind.type] + if not size or type(ind.data) ~= "buffer" or buffer.len(ind.data) < ind.count * size then + return Err.new(Err.ARG, "bad indices accessor") + end + local get = Scene.reader(ind) + if get then + for i = 0, ind.count - 1 do + if get(i, 0) >= n then + return Err.new(Err.ARG, "index out of range") + end + end + end + end + return nil +end +MeshOps.check = checkPrim + +-- ------------------------------------------------------------------------------------------------ triangulate +-- ear clipping of one polygon (corner indices into px / py / pz) -> triangles appended to out; fan when it gets stuck +local function earclip(poly: { number }, P: (number, number) -> number, out: { number }) + local k = #poly + if k < 3 then + return + end + if k == 3 then + table.insert(out, poly[1]) + table.insert(out, poly[2]) + table.insert(out, poly[3]) + return + end + -- Newell normal -> the projection plane (drop the dominant axis) + local nx, ny, nz = 0, 0, 0 + for a = 1, k do + local i, j = poly[a], poly[a % k + 1] + local xi, yi, zi = P(i, 0), P(i, 1), P(i, 2) + local xj, yj, zj = P(j, 0), P(j, 1), P(j, 2) + nx += (yi - yj) * (zi + zj) + ny += (zi - zj) * (xi + xj) + nz += (xi - xj) * (yi + yj) + end + local ax, ay, az = math.abs(nx), math.abs(ny), math.abs(nz) + local cu, cv, sign = 0, 1, nz + if ax >= ay and ax >= az then + cu, cv, sign = 1, 2, nx + elseif ay >= az then + cu, cv, sign = 2, 0, ny + end + local function uv(i: number): (number, number) + return P(i, cu), P(i, cv) + end + local s = if sign < 0 then -1 else 1 + local ring = table.clone(poly) + local guard = 0 + while #ring > 3 and guard < k * k do + guard += 1 + local n = #ring + local clipped = false + for a = 1, n do + local ia, ib, ic = ring[(a - 2) % n + 1], ring[a], ring[a % n + 1] + local ax2, ay2 = uv(ia) + local bx, by = uv(ib) + local cx, cy = uv(ic) + local cross = ((bx - ax2) * (cy - ay2) - (by - ay2) * (cx - ax2)) * s + if cross > 0 then + local inside = false + for q = 1, n do + local iq = ring[q] + if iq ~= ia and iq ~= ib and iq ~= ic then + local qx, qy = uv(iq) + local d1 = ((bx - ax2) * (qy - ay2) - (by - ay2) * (qx - ax2)) * s + local d2 = ((cx - bx) * (qy - by) - (cy - by) * (qx - bx)) * s + local d3 = ((ax2 - cx) * (qy - cy) - (ay2 - cy) * (qx - cx)) * s + if d1 >= 0 and d2 >= 0 and d3 >= 0 then + inside = true + break + end + end + end + if not inside then + table.insert(out, ia) + table.insert(out, ib) + table.insert(out, ic) + table.remove(ring, a) + clipped = true + break + end + end + end + if not clipped then + break + end + end + -- whatever is left (3 corners, or a degenerate / self-intersecting rest): a fan + for a = 2, #ring - 1 do + table.insert(out, ring[1]) + table.insert(out, ring[a]) + table.insert(out, ring[a + 1]) + end +end + +local function u32(list: { number }): Accessor + local n = #list + local b = buffer.create(n * 4) + for i = 1, n do + writeu32(b, (i - 1) * 4, list[i]) + end + return Scene.accessor(b, "u32", 1, n) +end + +-- triangulate(prim, opts?) -> a new triangle Primitive (the same attributes) | nil, Err. opts.method: "earclip" +-- (default; handles concave n-gons) or "fan". Strips and fans are unrolled (strip winding alternates as glTF says). +-- Lines and points come back unchanged. +function MeshOps.triangulate(prim: Primitive, opts: { method: string? }?): (Primitive?, Err.Err?) + local err = checkPrim(prim) + if err then + return nil, err + end + local mode = prim.mode or "triangles" + if mode == "lines" or mode == "points" or mode == "line_strip" or mode == "line_loop" then + return prim, nil + end + local method = opts and opts.method or "earclip" + local ib, n = indexBuffer(prim) + local out: { number } = {} + if mode == "triangles" then + local m = n - n % 3 + for i = 0, m - 1 do + out[i + 1] = readu32(ib, i * 4) + end + elseif mode == "triangle_strip" then + for i = 0, n - 3 do + local a, b, c = readu32(ib, i * 4), readu32(ib, i * 4 + 4), readu32(ib, i * 4 + 8) + if i % 2 == 1 then + a, b = b, a + end + if a ~= b and b ~= c and a ~= c then + table.insert(out, a) + table.insert(out, b) + table.insert(out, c) + end + end + elseif mode == "triangle_fan" then + for i = 1, n - 2 do + table.insert(out, readu32(ib, 0)) + table.insert(out, readu32(ib, i * 4)) + table.insert(out, readu32(ib, i * 4 + 4)) + end + elseif mode == "polygons" then + local faces = prim.faces + if not faces then + return nil, Err.new(Err.ARG, "polygons primitive without faces") + end + local getf = Scene.reader(faces) + if not getf then + return nil, Err.new(Err.ARG, "bad faces accessor") + end + local pos = MeshOps.f32(prim.attributes.POSITION) :: Accessor + local pd = pos.data + local P = function(i: number, c: number): number + return readf32(pd, (i * 3 + c) * 4) + end + local at = 0 + for f = 0, faces.count - 1 do + local k = getf(f, 0) + if at + k > n then + return nil, Err.new(Err.ARG, "faces run past the indices") + end + if k >= 3 then + if method == "fan" or k == 3 then + for a = 1, k - 2 do + table.insert(out, readu32(ib, at * 4)) + table.insert(out, readu32(ib, (at + a) * 4)) + table.insert(out, readu32(ib, (at + a + 1) * 4)) + end + else + local poly = table.create(k) + for a = 0, k - 1 do + poly[a + 1] = readu32(ib, (at + a) * 4) + end + earclip(poly, P, out) + end + end + at += k + end + else + return nil, Err.new(Err.ARG, "unknown mode " .. tostring(mode)) + end + return { + attributes = prim.attributes, + indices = u32(out), + mode = "triangles", + material = prim.material, + targets = prim.targets, + extras = prim.extras, + }, nil +end + +-- ------------------------------------------------------------------------------------------------ transform +local function det3(m: { number }): number + return m[1] * (m[6] * m[11] - m[10] * m[7]) - m[5] * (m[2] * m[11] - m[10] * m[3]) + m[9] * (m[2] * m[7] - m[6] * m[3]) +end + +-- the inverse transpose of m's 3 x 3 part (column-major 9), for normals +local function normalMatrix(m: { number }): { number } + local a, b, c = m[1], m[5], m[9] + local d, e, f = m[2], m[6], m[10] + local g, h, i = m[3], m[7], m[11] + local det = a * (e * i - f * h) - b * (d * i - f * g) + c * (d * h - e * g) + if det == 0 then + det = 1 + end + local k = 1 / det + -- cofactor matrix / det (= inverse transpose), column-major + return { + (e * i - f * h) * k, -(b * i - c * h) * k, (b * f - c * e) * k, + -(d * i - f * g) * k, (a * i - c * g) * k, -(a * f - c * d) * k, + (d * h - e * g) * k, -(a * h - b * g) * k, (a * e - b * d) * k, + } +end + +-- transform(prim, matrix) -> prim (changed in place: POSITION, NORMAL, TANGENT become f32; morph target deltas too). +-- A mirroring matrix (negative determinant) also reverses the triangle winding so faces stay front-facing. +function MeshOps.transform(prim: Primitive, m: { number }): (Primitive?, Err.Err?) + local err = checkPrim(prim) + if err then + return nil, err + end + if type(m) ~= "table" or #m ~= 16 then + return nil, Err.new(Err.ARG, "expected a column-major 4x4 matrix (16 numbers)") + end + local nm = normalMatrix(m) + local function points(acc: Accessor?, w: number): Accessor? + if not acc then + return nil + end + local a = MeshOps.f32(acc) :: Accessor + if a == acc then + a = Scene.accessor(buffer.create(buffer.len(acc.data)), "f32", acc.components, acc.count) + buffer.copy(a.data, 0, acc.data, 0, acc.count * acc.components * 4) + end + local d, c = a.data, a.components + for i = 0, a.count - 1 do + local o = i * c * 4 + local x, y, z = readf32(d, o), readf32(d, o + 4), readf32(d, o + 8) + writef32(d, o, m[1] * x + m[5] * y + m[9] * z + m[13] * w) + writef32(d, o + 4, m[2] * x + m[6] * y + m[10] * z + m[14] * w) + writef32(d, o + 8, m[3] * x + m[7] * y + m[11] * z + m[15] * w) + end + return a + end + local function dirs(acc: Accessor?, mat: { number }, normalize: boolean, flipW: boolean): Accessor? + if not acc then + return nil + end + local a = MeshOps.f32(acc) :: Accessor + if a == acc then + a = Scene.accessor(buffer.create(buffer.len(acc.data)), "f32", acc.components, acc.count) + buffer.copy(a.data, 0, acc.data, 0, acc.count * acc.components * 4) + end + local d, c = a.data, a.components + for i = 0, a.count - 1 do + local o = i * c * 4 + local x, y, z = readf32(d, o), readf32(d, o + 4), readf32(d, o + 8) + local nx = mat[1] * x + mat[4] * y + mat[7] * z + local ny = mat[2] * x + mat[5] * y + mat[8] * z + local nz = mat[3] * x + mat[6] * y + mat[9] * z + if normalize then + local l = math.sqrt(nx * nx + ny * ny + nz * nz) + if l > 0 then + nx, ny, nz = nx / l, ny / l, nz / l + end + end + writef32(d, o, nx) + writef32(d, o + 4, ny) + writef32(d, o + 8, nz) + if flipW and c >= 4 then + writef32(d, o + 12, -readf32(d, o + 12)) + end + end + return a + end + local mirror = det3(m) < 0 + local m3 = { m[1], m[2], m[3], m[5], m[6], m[7], m[9], m[10], m[11] } + local attrs = prim.attributes + attrs.POSITION = points(attrs.POSITION, 1) :: Accessor + attrs.NORMAL = dirs(attrs.NORMAL, nm, true, false) + attrs.TANGENT = dirs(attrs.TANGENT, m3, true, mirror) + if prim.targets then + for _, t in prim.targets do + t.POSITION = points(t.POSITION, 0) + t.NORMAL = dirs(t.NORMAL, nm, false, false) + t.TANGENT = dirs(t.TANGENT, m3, false, false) + end + end + if mirror and (prim.mode == "triangles" or prim.mode == nil) then + local ib, n = indexBuffer(prim) + local nb = buffer.create(n * 4) + buffer.copy(nb, 0, ib, 0, n * 4) + for t = 0, n // 3 - 1 do + local o = t * 12 + local b = readu32(nb, o + 4) + writeu32(nb, o + 4, readu32(nb, o + 8)) + writeu32(nb, o + 8, b) + end + prim.indices = Scene.accessor(nb, "u32", 1, n) + elseif mirror and prim.mode == "polygons" and prim.faces then + local ib, n = indexBuffer(prim) + local nb = buffer.create(n * 4) + local getf = Scene.reader(prim.faces) + local at = 0 + if getf then + for f = 0, prim.faces.count - 1 do + local k = getf(f, 0) + for a = 0, k - 1 do + if at + a < n then + writeu32(nb, (at + a) * 4, readu32(ib, (at + k - 1 - a) * 4)) + end + end + at += k + end + end + prim.indices = Scene.accessor(nb, "u32", 1, n) + end + return prim, nil +end + +-- ------------------------------------------------------------------------------------------------ normals / tangents +-- computeNormals(prim, opts?) -> prim with NORMAL (f32, area-weighted average of the triangle normals of each vertex) | +-- nil, Err. opts.flat = true: split every triangle's corners first (unwelded, one face normal per corner). Non-triangle +-- modes are triangulated first (the returned primitive is then a new one). +function MeshOps.computeNormals(prim: Primitive, opts: { flat: boolean? }?): (Primitive?, Err.Err?) + local p = prim + if (prim.mode or "triangles") ~= "triangles" then + local t, err = MeshOps.triangulate(prim) + if not t then + return nil, err + end + p = t + else + local err = checkPrim(prim) + if err then + return nil, err + end + end + if p.mode ~= "triangles" then + return p, nil -- lines / points: nothing to do + end + if opts and opts.flat then + p = MeshOps.unweld(p) + end + local pos = MeshOps.f32(p.attributes.POSITION) :: Accessor + local pd = pos.data + local nv = pos.count + local ib, n = indexBuffer(p) + local acc = table.create(nv * 3, 0) + for t = 0, n // 3 - 1 do + local a, b, c = readu32(ib, t * 12), readu32(ib, t * 12 + 4), readu32(ib, t * 12 + 8) + local ax, ay, az = readf32(pd, a * 12), readf32(pd, a * 12 + 4), readf32(pd, a * 12 + 8) + local e1x, e1y, e1z = readf32(pd, b * 12) - ax, readf32(pd, b * 12 + 4) - ay, readf32(pd, b * 12 + 8) - az + local e2x, e2y, e2z = readf32(pd, c * 12) - ax, readf32(pd, c * 12 + 4) - ay, readf32(pd, c * 12 + 8) - az + -- the cross product is twice the area times the unit normal: area weighting for free + local nx, ny, nz = e1y * e2z - e1z * e2y, e1z * e2x - e1x * e2z, e1x * e2y - e1y * e2x + for _, v in { a, b, c } do + acc[v * 3 + 1] += nx + acc[v * 3 + 2] += ny + acc[v * 3 + 3] += nz + end + end + local out = buffer.create(nv * 12) + for v = 0, nv - 1 do + local x, y, z = acc[v * 3 + 1], acc[v * 3 + 2], acc[v * 3 + 3] + local l = math.sqrt(x * x + y * y + z * z) + if l > 0 then + x, y, z = x / l, y / l, z / l + else + x, y, z = 0, 0, 1 + end + writef32(out, v * 12, x) + writef32(out, v * 12 + 4, y) + writef32(out, v * 12 + 8, z) + end + p.attributes.NORMAL = Scene.accessor(out, "f32", 3, nv) + return p, nil +end + +-- computeTangents(prim, opts?) -> prim with TANGENT (f32 vec4: xyz orthogonal to the normal, w = +-1 handedness) | +-- nil, Err. Needs triangles, NORMAL (computed when missing) and TEXCOORD_. +function MeshOps.computeTangents(prim: Primitive, opts: { texCoord: number? }?): (Primitive?, Err.Err?) + local p = prim + if not p.attributes.NORMAL or (p.mode or "triangles") ~= "triangles" then + local q, err = MeshOps.computeNormals(prim) + if not q then + return nil, err + end + p = q + end + local err = checkPrim(p) + if err then + return nil, err + end + local uvAcc = p.attributes["TEXCOORD_" .. tostring(opts and opts.texCoord or 0)] + if not uvAcc then + return nil, Err.new(Err.ARG, "computeTangents needs texture coordinates") + end + local pos = MeshOps.f32(p.attributes.POSITION) :: Accessor + local nrm = MeshOps.f32(p.attributes.NORMAL :: Accessor) :: Accessor + local uv = MeshOps.f32(uvAcc) :: Accessor + local pd, nd, ud = pos.data, nrm.data, uv.data + local nv = pos.count + local ib, n = indexBuffer(p) + local tan = table.create(nv * 3, 0) + local bit = table.create(nv * 3, 0) + for t = 0, n // 3 - 1 do + local a, b, c = readu32(ib, t * 12), readu32(ib, t * 12 + 4), readu32(ib, t * 12 + 8) + local ax, ay, az = readf32(pd, a * 12), readf32(pd, a * 12 + 4), readf32(pd, a * 12 + 8) + local x1, y1, z1 = readf32(pd, b * 12) - ax, readf32(pd, b * 12 + 4) - ay, readf32(pd, b * 12 + 8) - az + local x2, y2, z2 = readf32(pd, c * 12) - ax, readf32(pd, c * 12 + 4) - ay, readf32(pd, c * 12 + 8) - az + local us, vs = readf32(ud, a * 8), readf32(ud, a * 8 + 4) + local s1, t1 = readf32(ud, b * 8) - us, readf32(ud, b * 8 + 4) - vs + local s2, t2 = readf32(ud, c * 8) - us, readf32(ud, c * 8 + 4) - vs + local den = s1 * t2 - s2 * t1 + if den ~= 0 then + local r = 1 / den + local tx, ty, tz = (t2 * x1 - t1 * x2) * r, (t2 * y1 - t1 * y2) * r, (t2 * z1 - t1 * z2) * r + local bx, by, bz = (s1 * x2 - s2 * x1) * r, (s1 * y2 - s2 * y1) * r, (s1 * z2 - s2 * z1) * r + for _, v in { a, b, c } do + tan[v * 3 + 1] += tx + tan[v * 3 + 2] += ty + tan[v * 3 + 3] += tz + bit[v * 3 + 1] += bx + bit[v * 3 + 2] += by + bit[v * 3 + 3] += bz + end + end + end + local out = buffer.create(nv * 16) + for v = 0, nv - 1 do + local nx, ny, nz = readf32(nd, v * 12), readf32(nd, v * 12 + 4), readf32(nd, v * 12 + 8) + local tx, ty, tz = tan[v * 3 + 1], tan[v * 3 + 2], tan[v * 3 + 3] + local dot = nx * tx + ny * ty + nz * tz + tx, ty, tz = tx - nx * dot, ty - ny * dot, tz - nz * dot + local l = math.sqrt(tx * tx + ty * ty + tz * tz) + if l > 1e-20 then + tx, ty, tz = tx / l, ty / l, tz / l + else + -- no UV gradient: any unit vector orthogonal to the normal + if math.abs(nx) < 0.9 then + tx, ty, tz = 0, nz, -ny + else + tx, ty, tz = -nz, 0, nx + end + local l2 = math.sqrt(tx * tx + ty * ty + tz * tz) + if l2 > 0 then + tx, ty, tz = tx / l2, ty / l2, tz / l2 + end + end + -- handedness: (n x t) . b + local cx, cy, cz = ny * tz - nz * ty, nz * tx - nx * tz, nx * ty - ny * tx + local w = if cx * bit[v * 3 + 1] + cy * bit[v * 3 + 2] + cz * bit[v * 3 + 3] < 0 then -1 else 1 + writef32(out, v * 16, tx) + writef32(out, v * 16 + 4, ty) + writef32(out, v * 16 + 8, tz) + writef32(out, v * 16 + 12, w) + end + p.attributes.TANGENT = Scene.accessor(out, "f32", 4, nv) + return p, nil +end + +-- ------------------------------------------------------------------------------------------------ weld / unweld +local function gather(acc: Accessor, ib: buffer, n: number): Accessor + local size = (Types.COMPONENT_SIZE[acc.type] or 4) * acc.components + local out = buffer.create(n * size) + for i = 0, n - 1 do + buffer.copy(out, i * size, acc.data, readu32(ib, i * 4) * size, size) + end + local a = Scene.accessor(out, acc.type, acc.components, n) + a.matrix = acc.matrix + return a +end + +-- unweld(prim) -> a new primitive with one vertex per index (no indices; triangle soups, flat normals) +function MeshOps.unweld(prim: Primitive): Primitive + local ib, n = indexBuffer(prim) + local attrs = {} + for name, a in prim.attributes do + attrs[name] = gather(a, ib, n) + end + local targets = nil + if prim.targets then + targets = {} + for k, t in prim.targets do + local tt = {} + for name, a in t do + tt[name] = gather(a, ib, n) + end + targets[k] = tt + end + end + return { attributes = attrs, indices = nil, mode = prim.mode, faces = prim.faces, material = prim.material, targets = targets, extras = prim.extras } +end + +-- weld(prim, opts?) -> a new indexed primitive where vertices with identical attributes are one | nil, Err. +-- opts.epsilon > 0: positions within epsilon (on a grid of that size) merge too, keeping the first vertex's other +-- attributes only when they are equal (opts.positionsOnly = true merges by position alone, keeping the first vertex). +-- Morph targets are kept per merged vertex (the first one's). +function MeshOps.weld(prim: Primitive, opts: { epsilon: number?, positionsOnly: boolean? }?): (Primitive?, Err.Err?) + local err = checkPrim(prim) + if err then + return nil, err + end + local eps = opts and opts.epsilon or 0 + local posOnly = opts and opts.positionsOnly or false + local names = {} + for name in prim.attributes do + if not (posOnly and name ~= "POSITION") and not (eps > 0 and name == "POSITION") then + table.insert(names, name) + end + end + table.sort(names) + local nv = vertexCount(prim) + local pos = MeshOps.f32(prim.attributes.POSITION) :: Accessor + local pd = pos.data + local inv = if eps > 0 then 1 / eps else 0 + local remap = buffer.create(nv * 4) + local keep: { number } = {} + local seen: { [string]: number } = {} + local parts = table.create(#names + 1) + for v = 0, nv - 1 do + local np = 0 + if eps > 0 then + np += 1 + parts[np] = string.format("%d,%d,%d", math.floor(readf32(pd, v * 12) * inv + 0.5), math.floor(readf32(pd, v * 12 + 4) * inv + 0.5), math.floor(readf32(pd, v * 12 + 8) * inv + 0.5)) + end + for _, name in names do + local a = prim.attributes[name] + local size = (Types.COMPONENT_SIZE[a.type] or 4) * a.components + np += 1 + parts[np] = buffer.readstring(a.data, v * size, size) + end + local key = table.concat(parts, "\1", 1, np) + local k = seen[key] + if k == nil then + k = #keep + seen[key] = k + table.insert(keep, v) + end + writeu32(remap, v * 4, k) + end + local kb = buffer.create(#keep * 4) + for i, v in keep do + writeu32(kb, (i - 1) * 4, v) + end + local attrs = {} + for name, a in prim.attributes do + attrs[name] = gather(a, kb, #keep) + end + local targets = nil + if prim.targets then + targets = {} + for k, t in prim.targets do + local tt = {} + for name, a in t do + tt[name] = gather(a, kb, #keep) + end + targets[k] = tt + end + end + local ib, n = indexBuffer(prim) + local out = buffer.create(n * 4) + for i = 0, n - 1 do + writeu32(out, i * 4, readu32(remap, readu32(ib, i * 4) * 4)) + end + return { + attributes = attrs, + indices = Scene.accessor(out, "u32", 1, n), + mode = prim.mode, + faces = prim.faces, + material = prim.material, + targets = targets, + extras = prim.extras, + }, nil +end + +-- ------------------------------------------------------------------------------------------------ bounds +-- bounds(primitive | scene) -> min { x, y, z }, max { x, y, z } (a scene: in world space, every mesh primitive and +-- voxel shape cell corners excluded) | nil, nil when there are no positions +function MeshOps.bounds(x: any): ({ number }?, { number }?) + local lo = { math.huge, math.huge, math.huge } + local hi = { -math.huge, -math.huge, -math.huge } + local function add(prim: Primitive, m: { number }?) + local pos = prim.attributes and prim.attributes.POSITION + if not pos then + return + end + local get = Scene.reader(pos) + if not get then + return + end + for i = 0, pos.count - 1 do + local px, py, pz = get(i, 0), get(i, 1), get(i, 2) + if m and m ~= Scene.IDENTITY then + px, py, pz = m[1] * px + m[5] * py + m[9] * pz + m[13], m[2] * px + m[6] * py + m[10] * pz + m[14], m[3] * px + m[7] * py + m[11] * pz + m[15] + end + if px < lo[1] then + lo[1] = px + end + if py < lo[2] then + lo[2] = py + end + if pz < lo[3] then + lo[3] = pz + end + if px > hi[1] then + hi[1] = px + end + if py > hi[2] then + hi[2] = py + end + if pz > hi[3] then + hi[3] = pz + end + end + end + if type(x) ~= "table" then + return nil, nil + end + if x.kind == "scene" then + for _, pl in Scene.flatten(x) do + add(pl.primitive, pl.matrix) + end + else + add(x, nil) + end + if lo[1] > hi[1] then + return nil, nil + end + return lo, hi +end + +-- ------------------------------------------------------------------------------------------------ merge +-- the value of an attribute nobody had (COLOR_n white, WEIGHTS_0 { 1, 0, 0, 0 }, the rest zero) +local function defaultFor(name: string, k: number): number + if string.sub(name, 1, 6) == "COLOR_" then + return 1 + end + if string.sub(name, 1, 8) == "WEIGHTS_" then + return if k == 0 then 1 else 0 + end + return 0 +end + +-- merge(scene | { Primitive }, opts?) -> one triangle Primitive with every mesh primitive baked into world space | +-- { Primitive } with opts.byMaterial (one per material, in material order) | nil, Err. Attributes present in any input +-- appear in the output (f32; missing ones filled with defaults: white colours, zeros); custom "_x" attributes too. +-- Lines and points are skipped (opts.keepPoints = true keeps a point-only input as points). Skins and morph targets +-- are not applied (the rest pose). +function MeshOps.merge(input: any, opts: { byMaterial: boolean?, method: string? }?): (any, Err.Err?) + local placed: { Types.Placed } = {} + if type(input) ~= "table" then + return nil, Err.new(Err.ARG, "merge: expected a Scene or a list of Primitives") + end + if input.kind == "scene" then + placed = Scene.flatten(input) + else + for i, p in input do + placed[i] = { primitive = p, matrix = Scene.IDENTITY, node = 0, mesh = 0 } + end + end + -- triangulate + bake each + local groups: { [number]: { Primitive } } = {} + local order: { number } = {} + local allPoints = #placed > 0 + for _, pl in placed do + if pl.primitive.mode ~= "points" then + allPoints = false + end + end + for _, pl in placed do + local p = pl.primitive + local mode = p.mode or "triangles" + if mode ~= "lines" and mode ~= "line_strip" and mode ~= "line_loop" and (mode ~= "points" or allPoints) then + local t, err = if mode == "points" then p else MeshOps.triangulate(p, opts) + if not t then + return nil, err + end + -- a private copy of the attributes to bake + local copy: Primitive = { attributes = {}, indices = t.indices, mode = t.mode, material = t.material } + for name, a in t.attributes do + copy.attributes[name] = MeshOps.f32(a) + end + if pl.matrix ~= Scene.IDENTITY then + local ok, terr = MeshOps.transform(copy, pl.matrix) + if not ok then + return nil, terr + end + end + local key = if opts and opts.byMaterial then (copy.material or 0) else 0 + if not groups[key] then + groups[key] = {} + table.insert(order, key) + end + table.insert(groups[key], copy) + end + end + table.sort(order) + local function concat(list: { Primitive }, material: number?): Primitive + local names: { [string]: number } = {} + local nv, ni = 0, 0 + local points = false + for _, p in list do + for name, a in p.attributes do + names[name] = math.max(names[name] or 0, a.components) + end + nv += vertexCount(p) + local _, n = indexBuffer(p) + ni += n + points = points or p.mode == "points" + end + local attrs: { [string]: Accessor } = {} + for name, comps in names do + local out = buffer.create(nv * comps * 4) + local base = 0 + for _, p in list do + local a = p.attributes[name] + local cnt = vertexCount(p) + for v = 0, cnt - 1 do + for k = 0, comps - 1 do + local value = if a and k < a.components then readf32(a.data, (v * a.components + k) * 4) else defaultFor(name, k) + writef32(out, ((base + v) * comps + k) * 4, value) + end + end + base += cnt + end + attrs[name] = Scene.accessor(out, "f32", comps, nv) + end + local idx = buffer.create(ni * 4) + local base, at = 0, 0 + for _, p in list do + local ib, n = indexBuffer(p) + for i = 0, n - 1 do + writeu32(idx, (at + i) * 4, readu32(ib, i * 4) + base) + end + at += n + base += vertexCount(p) + end + return { + attributes = attrs, + indices = if points then nil else Scene.accessor(idx, "u32", 1, ni), + mode = if points then "points" else "triangles", + material = material, + } + end + if opts and opts.byMaterial then + local out = {} + for _, key in order do + table.insert(out, concat(groups[key], if key == 0 then nil else key)) + end + return out, nil + end + local all = groups[0] or {} + local first = all[1] + return concat(all, first and first.material), nil +end + +-- ------------------------------------------------------------------------------------------------ units / up axis +local function scaleAccessor(acc: Accessor?, f: number): Accessor? + if not acc then + return nil + end + local a = MeshOps.f32(acc) :: Accessor + if a == acc then + a = Scene.accessor(buffer.create(acc.count * acc.components * 4), "f32", acc.components, acc.count) + buffer.copy(a.data, 0, acc.data, 0, acc.count * acc.components * 4) + end + for i = 0, a.count * a.components - 1 do + writef32(a.data, i * 4, readf32(a.data, i * 4) * f) + end + return a +end + +-- scale(scene, factor) -> scene, scaled in place: mesh positions and morph target deltas, node translations (TRS and +-- matrices), translation animations, inverse bind matrices, camera clip planes, light ranges; meta.unit is divided by +-- factor (the same physical size in smaller units). +function MeshOps.scale(scene: Scene, f: number): (Scene?, Err.Err?) + if type(scene) ~= "table" or scene.kind ~= "scene" or type(f) ~= "number" or f ~= f or f == 0 then + return nil, Err.new(Err.ARG, "scale: expected a Scene and a non-zero factor") + end + local done: { [any]: boolean } = {} + for _, mesh in scene.meshes do + for _, p in mesh.primitives do + if not done[p] then + done[p] = true + p.attributes.POSITION = scaleAccessor(p.attributes.POSITION, f) :: Accessor + for _, t in p.targets or {} do + t.POSITION = scaleAccessor(t.POSITION, f) + end + end + end + end + for _, n in scene.nodes do + if n.translation then + n.translation = { n.translation[1] * f, n.translation[2] * f, n.translation[3] * f } + end + if n.matrix then + local m = table.clone(n.matrix) + m[13], m[14], m[15] = m[13] * f, m[14] * f, m[15] * f + n.matrix = m + end + end + for _, a in scene.animations do + for _, c in a.channels do + if c.path == "translation" and not done[c.output] then + done[c.output] = true + c.output = scaleAccessor(c.output, f) :: Accessor + end + end + end + for _, s in scene.skins do + local ibm = s.inverseBindMatrices + if ibm and not done[ibm] then + local a = MeshOps.f32(ibm) :: Accessor + if a == ibm then + a = Scene.accessor(buffer.create(ibm.count * 64), "f32", 16, ibm.count) + buffer.copy(a.data, 0, ibm.data, 0, ibm.count * 64) + end + for i = 0, a.count - 1 do + for k = 12, 14 do + writef32(a.data, (i * 16 + k) * 4, readf32(a.data, (i * 16 + k) * 4) * f) + end + end + a.matrix = true + s.inverseBindMatrices = a + done[a] = true + end + end + for _, c in scene.cameras do + if c.type == "perspective" then + c.znear *= math.abs(f) + if c.zfar then + c.zfar *= math.abs(f) + end + else + c.znear *= math.abs(f) + if c.zfar then + c.zfar *= math.abs(f) + end + c.xmag = c.xmag and c.xmag * math.abs(f) + c.ymag = c.ymag and c.ymag * math.abs(f) + end + end + for _, l in scene.lights do + if l.range then + l.range *= math.abs(f) + end + end + scene.meta.unit = (scene.meta.unit or 1) / f + return scene, nil +end + +-- setUnit(scene, metresPerUnit) -> scene scaled so that one unit is metresPerUnit (from meta.unit, default 1 m) +function MeshOps.setUnit(scene: Scene, metresPerUnit: number): (Scene?, Err.Err?) + if type(scene) ~= "table" or type(metresPerUnit) ~= "number" or metresPerUnit <= 0 then + return nil, Err.new(Err.ARG, "setUnit: expected a Scene and a positive unit") + end + local from = scene.meta.unit or 1 + return MeshOps.scale(scene, from / metresPerUnit) +end + +-- setUp(scene, "y" | "z") -> scene with a new root node rotating the old roots from meta.up (default "y") to up. +-- Nothing is baked: the vertex data stays as it is (MeshOps.merge bakes it). +function MeshOps.setUp(scene: Scene, up: string): (Scene?, Err.Err?) + if type(scene) ~= "table" or scene.kind ~= "scene" or (up ~= "y" and up ~= "z") then + return nil, Err.new(Err.ARG, "setUp: expected a Scene and \"y\" or \"z\"") + end + local from = scene.meta.up or "y" + if from == up then + return scene, nil + end + local h = math.sqrt(0.5) + -- z-up -> y-up: -90 degrees about x; y-up -> z-up: +90 degrees about x + local q = if up == "y" then { -h, 0, 0, h } else { h, 0, 0, h } + table.insert(scene.nodes, { name = "up_" .. up, children = scene.roots, rotation = q }) + scene.roots = { #scene.nodes } + scene.meta.up = up :: any + return scene, nil +end + +-- ------------------------------------------------------------------------------------------------ voxels +local function linear(c: number): number + local s = c / 255 + return if s <= 0.04045 then s / 12.92 else ((s + 0.055) / 1.055) ^ 2.4 +end + +-- voxelsToPrimitive(voxels, opts?) -> a triangle Primitive of the grid's visible faces, greedily merged (POSITION, +-- NORMAL f32; COLOR_0 from the palette; u32 indices) | nil, Err. +-- opts.pivot: "center" (default: MagicaVoxel's placement, cell x spans x - floor(sx / 2) ..) or "corner" (0 .. sx); +-- opts.scale: units per voxel (default 1); opts.colors: "linear" (default: f32 linear RGBA, glTF's COLOR_0 meaning) or +-- "srgb" (unorm8, the palette bytes as they are); opts.indexAttribute = true adds "_PALETTE_INDEX" (u8 per vertex). +function MeshOps.voxelsToPrimitive(v: Types.Voxels, opts: { pivot: string?, scale: number?, colors: string?, indexAttribute: boolean? }?): (Primitive?, Err.Err?) + if type(v) ~= "table" or type(v.size) ~= "table" or type(v.data) ~= "buffer" then + return nil, Err.new(Err.ARG, "expected a Voxels grid") + end + local sx, sy, sz = v.size[1], v.size[2], v.size[3] + if type(sx) ~= "number" or type(sy) ~= "number" or type(sz) ~= "number" or sx < 1 or sy < 1 or sz < 1 or buffer.len(v.data) < sx * sy * sz then + return nil, Err.new(Err.ARG, "bad voxel grid size") + end + local pivot = opts and opts.pivot or "center" + local scale = opts and opts.scale or 1 + local ox, oy, oz = 0, 0, 0 + if pivot == "center" then + ox, oy, oz = -(sx // 2), -(sy // 2), -(sz // 2) + end + local g = Greedy.run(v.data, sx, sy, sz, ox, oy, oz, scale) + local nv = g.vertices + local function trim(b: buffer, size: number): buffer + local out = buffer.create(size) + buffer.copy(out, 0, b, 0, size) + return out + end + local attrs: { [string]: Accessor } = { + POSITION = Scene.accessor(trim(g.positions, nv * 12), "f32", 3, nv), + NORMAL = Scene.accessor(trim(g.normals, nv * 12), "f32", 3, nv), + } + local pal = v.palette or {} + local srgb = opts and opts.colors == "srgb" + local col = buffer.create(nv * (if srgb then 4 else 16)) + local lut: { { number } } = {} + for i = 1, 255 do + local c = pal[i] or { 255, 255, 255, 255 } + if srgb then + lut[i] = { c[1] or 0, c[2] or 0, c[3] or 0, c[4] or 255 } + else + lut[i] = { linear(c[1] or 0), linear(c[2] or 0), linear(c[3] or 0), (c[4] or 255) / 255 } + end + end + for k = 0, nv - 1 do + local c = lut[buffer.readu8(g.index, k)] or lut[1] + if srgb then + for j = 0, 3 do + buffer.writeu8(col, k * 4 + j, c[j + 1]) + end + else + for j = 0, 3 do + writef32(col, k * 16 + j * 4, c[j + 1]) + end + end + end + attrs.COLOR_0 = Scene.accessor(col, if srgb then "unorm8" else "f32", 4, nv) + if opts and opts.indexAttribute then + attrs._PALETTE_INDEX = Scene.accessor(trim(g.index, nv), "u8", 1, nv) + end + return { attributes = attrs, indices = Scene.accessor(trim(g.indices, g.quads * 24), "u32", 1, g.quads * 6), mode = "triangles" }, nil +end + +-- meshVoxels(scene, opts?) -> scene with a mesh for every voxel grid (scene.voxels) and node.mesh set on every node +-- that shows one (node.voxels); one shared material (white, rough, not metallic: the colours are per vertex). Options as +-- voxelsToPrimitive. Grids that already have a mesh made by this function are meshed again. +function MeshOps.meshVoxels(scene: Scene, opts: { pivot: string?, scale: number?, colors: string?, indexAttribute: boolean? }?): (Scene?, Err.Err?) + if type(scene) ~= "table" or scene.kind ~= "scene" then + return nil, Err.new(Err.ARG, "expected a Scene") + end + local grids = scene.voxels or {} + local mat = 0 + local meshOf: { [number]: number } = {} + for i, v in grids do + local prim, err = MeshOps.voxelsToPrimitive(v, opts) + if not prim then + return nil, err + end + if mat == 0 then + local m = Scene.material("voxels") + m.metallic = 0 + table.insert(scene.materials, m) + mat = #scene.materials + end + prim.material = mat + table.insert(scene.meshes, { name = v.name or ("voxels " .. i), primitives = { prim } }) + meshOf[i] = #scene.meshes + end + for _, n in scene.nodes do + if n.voxels and meshOf[n.voxels] then + n.mesh = meshOf[n.voxels] + end + end + return scene, nil +end + +return MeshOps diff --git a/tests/compat.luau b/tests/compat.luau index 6576b84..7a6d70b 100644 --- a/tests/compat.luau +++ b/tests/compat.luau @@ -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) diff --git a/tests/fixtures/vox/MagicaVoxel-file-format-vox-extension.txt b/tests/fixtures/vox/MagicaVoxel-file-format-vox-extension.txt new file mode 100644 index 0000000..181b376 --- /dev/null +++ b/tests/fixtures/vox/MagicaVoxel-file-format-vox-extension.txt @@ -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 diff --git a/tests/fixtures/vox/MagicaVoxel-file-format-vox.txt b/tests/fixtures/vox/MagicaVoxel-file-format-vox.txt new file mode 100644 index 0000000..d15efe7 --- /dev/null +++ b/tests/fixtures/vox/MagicaVoxel-file-format-vox.txt @@ -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 + | * + | * 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 +}; +------------------------------------------------------------------------------- diff --git a/tests/fixtures/vox/chr_knight.vox b/tests/fixtures/vox/chr_knight.vox new file mode 100644 index 0000000..3ec1006 Binary files /dev/null and b/tests/fixtures/vox/chr_knight.vox differ diff --git a/tests/fixtures/vox/chr_sword.vox b/tests/fixtures/vox/chr_sword.vox new file mode 100644 index 0000000..870b63e Binary files /dev/null and b/tests/fixtures/vox/chr_sword.vox differ diff --git a/tests/fixtures/vox/deer.vox b/tests/fixtures/vox/deer.vox new file mode 100644 index 0000000..759e055 Binary files /dev/null and b/tests/fixtures/vox/deer.vox differ diff --git a/tests/fixtures/vox/maze.vox b/tests/fixtures/vox/maze.vox new file mode 100644 index 0000000..2d14dd4 Binary files /dev/null and b/tests/fixtures/vox/maze.vox differ diff --git a/tests/fixtures/vox/ogt_chr_knight.vox b/tests/fixtures/vox/ogt_chr_knight.vox new file mode 100644 index 0000000..a5017f1 Binary files /dev/null and b/tests/fixtures/vox/ogt_chr_knight.vox differ diff --git a/tests/fixtures/vox/ogt_test_groups.vox b/tests/fixtures/vox/ogt_test_groups.vox new file mode 100644 index 0000000..41c26d5 Binary files /dev/null and b/tests/fixtures/vox/ogt_test_groups.vox differ diff --git a/tests/fixtures/vox/ogt_test_meta_chunk.vox b/tests/fixtures/vox/ogt_test_meta_chunk.vox new file mode 100644 index 0000000..9b566a0 Binary files /dev/null and b/tests/fixtures/vox/ogt_test_meta_chunk.vox differ diff --git a/tests/fixtures/vox/ogt_test_multiple_model_scene.vox b/tests/fixtures/vox/ogt_test_multiple_model_scene.vox new file mode 100644 index 0000000..2e74aeb Binary files /dev/null and b/tests/fixtures/vox/ogt_test_multiple_model_scene.vox differ diff --git a/tests/model/vox.luau b/tests/model/vox.luau new file mode 100644 index 0000000..77d0ec2 --- /dev/null +++ b/tests/model/vox.luau @@ -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() diff --git a/tools/fixtures/vox.py b/tools/fixtures/vox.py new file mode 100644 index 0000000..405c886 --- /dev/null +++ b/tools/fixtures/vox.py @@ -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("> 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(" 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("