Files

293 lines
13 KiB
Python

# VOX fixtures (tools/fixtures.py). There is no MagicaVoxel reader in nixpkgs, so the reference is (1) files saved by
# MagicaVoxel itself (tests/fixtures/vox: ephtracy/voxel-model samples, version 150, and jpaver/opengametools demo files
# with scene graphs, layers, materials, render objects, cameras, notes and META; licences in licenses/), parsed here
# by an independent Python reader written from the spec, and (2) synthetic files written here with every chunk type,
# rotations (including mirrors), nested groups, animation frames and odd cases.
# tests/gen/vox_cases.luau { name, data, version, models = { { size, count, crc (of the dense x-fastest grid),
# faces (exposed unit faces: the greedy mesh area) } }, paletteCrc, chunks = { id = n },
# nodes = { { name, world (row-major 3x4: R | t) } } for every shape node, names, layers,
# materials, notes, cameras, robjs }
import os, struct, zlib
INPUTS = ["tests/fixtures/vox"]
def default_palette():
steps = [0xff, 0xcc, 0x99, 0x66, 0x33, 0]
pal = [(r, g, b, 255) for r in steps for g in steps for b in steps][:215]
ramp = [0xee, 0xdd, 0xbb, 0xaa, 0x88, 0x77, 0x55, 0x44, 0x22, 0x11]
for ch in range(3):
for v in ramp:
c = [0, 0, 0, 255]
c[ch] = v
pal.append(tuple(c))
pal += [(v, v, v, 255) for v in ramp]
return pal
def spec_palette(text):
# the default_palette[256] array of the spec text (ABGR words, entry i = palette index i)
body = text[text.index("default_palette[256]"):]
body = body[body.index("{") + 1:body.index("}")]
words = [int(w, 16) for w in body.replace(",", " ").split()]
return [(w & 255, (w >> 8) & 255, (w >> 16) & 255, w >> 24) for w in words]
# ---------------------------------------------------------------------------------------------- reader (reference)
def rd_dict(d, p):
n, = struct.unpack_from("<i", d, p)
p += 4
out = {}
for _ in range(n):
kl, = struct.unpack_from("<i", d, p)
k = d[p + 4:p + 4 + kl].decode("latin1")
p += 4 + kl
vl, = struct.unpack_from("<i", d, p)
v = d[p + 4:p + 4 + vl].decode("latin1")
p += 4 + vl
out[k] = v
return out, p
def rot(b):
i0, i1 = b & 3, (b >> 2) & 3
i2 = 3 - i0 - i1
R = [[0] * 3 for _ in range(3)]
for row, (i, bit) in enumerate(((i0, 4), (i1, 5), (i2, 6))):
R[row][i] = -1 if b & (1 << bit) else 1
return R
def matmul(A, B): # 3x4 affine (R | t)
R = [[sum(A[r][k] * B[k][c] for k in range(3)) for c in range(3)] for r in range(3)]
t = [sum(A[r][k] * B[k][3] for k in range(3)) + A[r][3] for r in range(3)]
return [R[r] + [t[r]] for r in range(3)]
def parse(d):
assert d[:4] == b"VOX "
version, = struct.unpack_from("<i", d, 4)
assert d[8:12] == b"MAIN"
n, m = struct.unpack_from("<ii", d, 12)
p = 20 + n
end = min(p + m, len(d))
models, size, palette = [], None, None
graph, counts = {}, {}
mats, layers, notes, cams, robjs = {}, [], [], [], []
while p + 12 <= end:
cid = d[p:p + 4].decode("latin1")
n, m = struct.unpack_from("<ii", d, p + 4)
c = p + 12
counts[cid] = counts.get(cid, 0) + 1
if cid == "SIZE":
size = struct.unpack_from("<iii", d, c)
elif cid == "XYZI":
k, = struct.unpack_from("<i", d, c)
sx, sy, sz = size
grid = bytearray(sx * sy * sz)
for i in range(k):
x, y, z, ci = d[c + 4 + i * 4:c + 8 + i * 4]
if x < sx and y < sy and z < sz and ci:
grid[x + sx * (y + sy * z)] = ci
models.append((size, grid))
elif cid == "RGBA":
palette = [tuple(d[c + i * 4:c + i * 4 + 4]) for i in range(255)]
elif cid == "MATL":
mid, = struct.unpack_from("<i", d, c)
mats[mid], _ = rd_dict(d, c + 4)
elif cid == "nTRN":
nid, = struct.unpack_from("<i", d, c)
attrs, q = rd_dict(d, c + 4)
child, _, layer, nf = struct.unpack_from("<iiii", d, q)
q += 16
frames = []
for _ in range(nf):
f, q = rd_dict(d, q)
frames.append(f)
graph[nid] = ("T", attrs, child, frames)
elif cid == "nGRP":
nid, = struct.unpack_from("<i", d, c)
attrs, q = rd_dict(d, c + 4)
k, = struct.unpack_from("<i", d, q)
graph[nid] = ("G", attrs, list(struct.unpack_from("<%di" % k, d, q + 4)))
elif cid == "nSHP":
nid, = struct.unpack_from("<i", d, c)
attrs, q = rd_dict(d, c + 4)
k, = struct.unpack_from("<i", d, q)
mid, = struct.unpack_from("<i", d, q + 4)
graph[nid] = ("S", attrs, mid)
elif cid == "LAYR":
lid, = struct.unpack_from("<i", d, c)
layers.append(rd_dict(d, c + 4)[0])
elif cid == "NOTE":
k, = struct.unpack_from("<i", d, c)
q = c + 4
for _ in range(k):
l, = struct.unpack_from("<i", d, q)
notes.append(d[q + 4:q + 4 + l].decode("latin1"))
q += 4 + l
elif cid == "rCAM":
cams.append(struct.unpack_from("<i", d, c)[0])
elif cid == "rOBJ":
robjs.append(rd_dict(d, c)[0])
p = c + n + m
# shape nodes in depth-first order with world transforms
shapes = []
def walk(nid, parent):
kind, attrs, child, frames = graph[nid]
f = frames[0] if frames else {}
R = rot(int(f["_r"])) if "_r" in f else [[1, 0, 0], [0, 1, 0], [0, 0, 1]]
t = [int(v) for v in f.get("_t", "0 0 0").split()]
world = matmul(parent, [R[r] + [t[r]] for r in range(3)])
ch = graph.get(child)
if ch and ch[0] == "G":
for c2 in ch[2]:
walk(c2, world)
elif ch and ch[0] == "S":
shapes.append({"name": attrs.get("_name", ""), "model": ch[2] + 1, "world": [v for row in world for v in row]})
if 0 in graph:
walk(0, [[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1, 0]])
pal = palette or default_palette()
out_models = []
for (sx, sy, sz), grid in models:
faces = 0
for z in range(sz):
for y in range(sy):
for x in range(sx):
if grid[x + sx * (y + sy * z)]:
for dx, dy, dz in ((1, 0, 0), (-1, 0, 0), (0, 1, 0), (0, -1, 0), (0, 0, 1), (0, 0, -1)):
X, Y, Z = x + dx, y + dy, z + dz
if not (0 <= X < sx and 0 <= Y < sy and 0 <= Z < sz) or not grid[X + sx * (Y + sy * Z)]:
faces += 1
out_models.append({"size": [sx, sy, sz], "count": sum(1 for v in grid if v), "crc": zlib.crc32(bytes(grid)), "faces": faces})
return {
"version": version,
"models": out_models,
"paletteCrc": zlib.crc32(bytes(v for c in pal for v in c)),
"hasPalette": palette is not None,
"chunks": counts,
"shapes": shapes,
"layers": len(layers),
"materials": len(mats),
"notes": len(notes),
"cameras": len(cams),
"robjs": len(robjs),
"glassMaterials": sum(1 for m in mats.values() if m.get("_type") == "_glass"),
}
# ---------------------------------------------------------------------------------------------- writer (synthetic files)
def s(x):
b = x.encode()
return struct.pack("<i", len(b)) + b
def dct(d):
return struct.pack("<i", len(d)) + b"".join(s(k) + s(v) for k, v in d.items())
def chunk(cid, content, children=b""):
return cid.encode() + struct.pack("<ii", len(content), len(children)) + content + children
def vox(chunks, version=200, main_size=None):
body = b"".join(chunks)
return b"VOX " + struct.pack("<i", version) + b"MAIN" + struct.pack("<ii", 0, main_size if main_size is not None else len(body)) + body
def model(rng, sx, sy, sz, fill=0.4, colors=(1, 255)):
vox_list = []
for z in range(sz):
for y in range(sy):
for x in range(sx):
if rng.random() < fill:
vox_list.append((x, y, z, rng.randrange(*colors)))
rng.shuffle(vox_list)
return [chunk("SIZE", struct.pack("<iii", sx, sy, sz)), chunk("XYZI", struct.pack("<i", len(vox_list)) + b"".join(bytes(v) for v in vox_list))]
def ntrn(nid, child, attrs=None, frames=None, layer=0):
frames = frames or [{}]
return chunk("nTRN", struct.pack("<i", nid) + dct(attrs or {}) + struct.pack("<iiii", child, -1, layer, len(frames)) + b"".join(dct(f) for f in frames))
def ngrp(nid, children, attrs=None):
return chunk("nGRP", struct.pack("<i", nid) + dct(attrs or {}) + struct.pack("<i", len(children)) + b"".join(struct.pack("<i", c) for c in children))
def nshp(nid, models_):
return chunk("nSHP", struct.pack("<i", nid) + dct({}) + struct.pack("<i", len(models_)) + b"".join(struct.pack("<i", m) + dct({"_f": str(i)} if len(models_) > 1 else {}) for i, m in enumerate(models_)))
def rgba(rng):
return chunk("RGBA", bytes(rng.randrange(256) for _ in range(1024)))
def synthetic(rng):
out = []
# 1. a plain v150 model without a palette (the default palette)
out.append(("syn-default-palette", vox(model(rng, 7, 5, 3), 150)))
# 2. full scene: nested groups, every rotation family, mirrors, hidden, layers, materials, notes, cameras, IMAP, META
ch = []
for _ in range(4):
ch += model(rng, rng.randrange(1, 12), rng.randrange(1, 12), rng.randrange(1, 12))
ch += [
ntrn(0, 1, layer=-1),
ngrp(1, [2, 4, 8]),
ntrn(2, 3, {"_name": "a"}, [{"_r": "4", "_t": "1 2 3"}]),
nshp(3, [0]),
ntrn(4, 5, {"_name": "group", "_hidden": "1"}, [{"_r": "17", "_t": "-5 0 7"}], layer=1), # 90 deg about z
ngrp(5, [6, 10]),
ntrn(6, 7, {"_name": "b"}, [{"_r": "20", "_t": "0 0 -4"}]), # a mirror (x flipped)
nshp(7, [1]),
ntrn(8, 9, {"_name": "anim"}, [{"_r": "9", "_t": "3 3 3", "_f": "0"}, {"_r": "4", "_t": "4 4 4", "_f": "5"}]),
nshp(9, [2, 3]),
ntrn(10, 11, {"_name": "c"}, [{"_r": "98", "_t": "10 -20 30"}]),
nshp(11, [3]),
chunk("LAYR", struct.pack("<i", 0) + dct({"_name": "zero"}) + struct.pack("<i", -1)),
chunk("LAYR", struct.pack("<i", 1) + dct({"_name": "one", "_hidden": "1", "_color": "255 0 0"}) + struct.pack("<i", -1)),
rgba(rng),
chunk("IMAP", bytes(range(256))),
]
for mid in (1, 2, 200):
ch.append(chunk("MATL", struct.pack("<i", mid) + dct({"_type": ["_diffuse", "_glass", "_emit"][mid % 3], "_rough": "0.25", "_ior": "1.5", "_flux": "2"})))
ch.append(chunk("rOBJ", dct({"_type": "_bg", "_color": "0 0 0"})))
ch.append(chunk("rCAM", struct.pack("<i", 0) + dct({"_mode": "pers", "_focus": "0 0 0", "_angle": "30 40 0", "_radius": "80", "_frustum": "0.4", "_fov": "45"})))
ch.append(chunk("NOTE", struct.pack("<i", 2) + s("first") + s("second")))
ch.insert(0, chunk("META", dct({"_anim_range": "0 30"})))
ch.append(chunk("ZZZZ", b"unknown payload"))
out.append(("syn-scene", vox(ch)))
# 3. edge cases: voxels outside the grid, index 0, duplicates, a 1x1x1 model
vox_list = [(0, 0, 0, 5), (9, 0, 0, 7), (1, 1, 1, 0), (1, 1, 1, 9), (1, 1, 1, 10)]
ch = [chunk("SIZE", struct.pack("<iii", 2, 2, 2)), chunk("XYZI", struct.pack("<i", len(vox_list)) + b"".join(bytes(v) for v in vox_list)), rgba(rng)]
out.append(("syn-edge", vox(ch)))
out.append(("syn-single", vox([chunk("SIZE", struct.pack("<iii", 1, 1, 1)), chunk("XYZI", struct.pack("<i", 1) + bytes((0, 0, 0, 1)))])))
# 4. a full 64^3 block and a 3d checkerboard (worst case for greedy meshing)
full = [(x, y, z, 1 + (z % 3)) for z in range(64) for y in range(64) for x in range(64)]
out.append(("syn-block64", vox([chunk("SIZE", struct.pack("<iii", 64, 64, 64)), chunk("XYZI", struct.pack("<i", len(full)) + b"".join(bytes(v) for v in full))])))
chk = [(x, y, z, 3) for z in range(16) for y in range(16) for x in range(16) if (x + y + z) % 2 == 0]
out.append(("syn-checker16", vox([chunk("SIZE", struct.pack("<iii", 16, 16, 16)), chunk("XYZI", struct.pack("<i", len(chk)) + b"".join(bytes(v) for v in chk))])))
return out
def generate(ctx):
rng = ctx.rng(7)
cases = []
folder = os.path.join("tests", "fixtures", "vox")
for f in sorted(os.listdir(os.path.join(ctx.root, folder))):
if f.endswith(".vox"):
cases.append((f, ctx.read(os.path.join(folder, f))))
cases += synthetic(rng)
out = []
for name, data in cases:
ref = parse(data)
ref["name"] = name
ref["data"] = data
out.append(ref)
ctx.emit("vox_cases", out)
# the spec's default palette (parsed from the spec text) must equal the formula used by both readers
pal = spec_palette(ctx.read(os.path.join(folder, "MagicaVoxel-file-format-vox.txt")).decode())[1:]
assert pal == default_palette(), "default palette formula differs from the spec"
ctx.emit("vox_default_palette", [list(c) for c in pal])