merge ws/game
This commit is contained in:
commit
3cebe7d4e7
72 files changed
+10473
-6
No files matched your search
@@ -1138,6 +1138,48 @@ do
|
||||
jitTune(false)
|
||||
end
|
||||
end
|
||||
do
|
||||
-- game formats (ws-game): PKWARE DCL explode (StormLib's implode streams from tools/fixtures/mpq.py), reading every
|
||||
-- file of a StormLib MPQ (MB/s of file data), Freedoom's MAP01 to a Scene (tools/fixtures/wad.py: sector
|
||||
-- outlines, triangulation, walls; MB/s of map lumps), an MD2 with every frame as a morph target
|
||||
local Explode = require("@formats/codecs/compress/Explode")
|
||||
local Mpq = require("@formats/archive/mpq")
|
||||
local Wad = require("@formats/archive/wad")
|
||||
local MQ = require("@tests/gen/mpq")
|
||||
local WD = require("@tests/gen/wad")
|
||||
for _, c in MQ.implode do
|
||||
if c.name == "text" or c.name == "ascii-4096" or c.name == "binary-2048" then
|
||||
local data = buffer.fromstring(c.data)
|
||||
bench("explode " .. c.name .. " (" .. c.size .. " B)", 20, c.size, function()
|
||||
Explode.decompress(data)
|
||||
end)
|
||||
end
|
||||
end
|
||||
local arch = MQ.archives[1]
|
||||
local mb = buffer.fromstring(arch.data)
|
||||
local a = assert(Mpq.decode(Bytes.reader(mb)))
|
||||
local total = 0
|
||||
for _, e in a:list() do
|
||||
total += e.size
|
||||
end
|
||||
bench("mpq read every file (v1)", 5, total, function()
|
||||
local m = Mpq.decode(Bytes.reader(mb))
|
||||
for _, e in m:list() do
|
||||
m:read(e.name)
|
||||
end
|
||||
end)
|
||||
local wb = buffer.fromstring(WD.freedoom.data)
|
||||
local w = assert(Wad.decode(Bytes.reader(wb)))
|
||||
local lumps = 0
|
||||
for _, l in Wad.lumps(w) :: any do
|
||||
if l.map == "MAP01" then
|
||||
lumps += l.size
|
||||
end
|
||||
end
|
||||
bench("wad MAP01 -> Scene (no textures)", 3, lumps, function()
|
||||
Wad.map(w, "MAP01", { textures = false })
|
||||
end)
|
||||
end
|
||||
do
|
||||
-- Draco (codecs/model/Draco): the Stanford bunny (35k points, 69k faces, Edgebreaker valence, normals) and a UV
|
||||
-- sphere with seams; MB/s of decoded output (u32 indices + f32 attributes per point), plus triangles per second.
|
||||
|
||||
@@ -0,0 +1,36 @@
|
||||
# Shared helpers for the Quake-family model fixtures (md2.py, md3.py, mdl.py): assimp's triangle soup.
|
||||
# assimp_soup(ctx, data, ext) -> { pos = [floats], uv = [floats], meshes, faces } | { failed = True }: every triangle
|
||||
# mesh of `assimp export -f assjson`, faces in order, each face's corners in assimp's index order (positions x3,
|
||||
# texture coordinates u, v of set 0); per = [ { name, start } ]: each mesh's name and first face
|
||||
import json, os, shutil, subprocess, tempfile
|
||||
|
||||
|
||||
def assimp_soup(ctx, data, ext):
|
||||
tmp = tempfile.mkdtemp(prefix="formats-quake-")
|
||||
try:
|
||||
src = os.path.join(tmp, "in." + ext)
|
||||
open(src, "wb").write(data)
|
||||
out = os.path.join(tmp, "out.json")
|
||||
try:
|
||||
ctx.nix("assimp", ["assimp", "export", src, out, "-f", "assjson"])
|
||||
except subprocess.CalledProcessError:
|
||||
return {"failed": True}
|
||||
j = json.load(open(out))
|
||||
finally:
|
||||
shutil.rmtree(tmp)
|
||||
pos, uv, faces, meshes, per = [], [], 0, 0, []
|
||||
for m in j.get("meshes", []):
|
||||
if m.get("primitivetypes") != 4:
|
||||
continue
|
||||
meshes += 1
|
||||
per.append({"name": m.get("name", ""), "start": faces})
|
||||
v = m["vertices"]
|
||||
t = (m.get("texturecoords") or [[]])[0]
|
||||
nc = (m.get("numuvcomponents") or [2])[0]
|
||||
for f in m["faces"]:
|
||||
faces += 1
|
||||
for i in f:
|
||||
pos += v[i * 3:i * 3 + 3]
|
||||
if t:
|
||||
uv += t[i * nc:i * nc + 2]
|
||||
return {"pos": pos, "uv": uv, "faces": faces, "meshes": meshes, "per": per}
|
||||
@@ -0,0 +1,22 @@
|
||||
-- tools/fixtures/_smd_encode.luau: run by tools/fixtures/smd.py under the luau CLI: decodes the reference SMDs of
|
||||
-- tests/gen/smd_src and writes them back with our encoder (bind pose; links; and the animation as an animation SMD),
|
||||
-- printing "<name>\t<hex>" lines for assimp to read back.
|
||||
local Smd = require("@formats/model/smd")
|
||||
local Bytes = require("@formats/core/Bytes")
|
||||
local Src = require("@tests/gen/smd_src")
|
||||
|
||||
local function hex(b: buffer): string
|
||||
return (string.gsub(buffer.tostring(b), ".", function(c: string): string
|
||||
return string.format("%02x", string.byte(c))
|
||||
end))
|
||||
end
|
||||
|
||||
for _, c in Src do
|
||||
local s = Smd.decode(Bytes.reader(buffer.fromstring(c.data)))
|
||||
if s then
|
||||
print(c.name .. "\t" .. hex(Smd.encode(s) :: buffer))
|
||||
if #s.animations > 0 then
|
||||
print(c.name .. "-anim\t" .. hex(Smd.encode(s, { animation = 1 }) :: buffer))
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,20 @@
|
||||
-- tools/fixtures/_vpk_encode.luau: run by tools/fixtures/vpk.py under the luau CLI: writes the files of
|
||||
-- tests/gen/vpk_src as VPK version 1 and 2 with our encoder and prints "<name>\t<hex>" lines for Python's vpk
|
||||
-- package to read back (and verify the version 2 MD5s).
|
||||
local Vpk = require("@formats/archive/vpk")
|
||||
local Src = require("@tests/gen/vpk_src")
|
||||
|
||||
local function hex(b: buffer): string
|
||||
local s = buffer.tostring(b)
|
||||
return (string.gsub(s, ".", function(c: string): string
|
||||
return string.format("%02x", string.byte(c))
|
||||
end))
|
||||
end
|
||||
|
||||
for _, version in { 1, 2 } do
|
||||
local a = Vpk.new(version)
|
||||
for _, f in Src do
|
||||
a:add(f.name, f.data)
|
||||
end
|
||||
print("v" .. version .. "\t" .. hex(a:write() :: buffer))
|
||||
end
|
||||
@@ -0,0 +1,159 @@
|
||||
# Blizzard BLP fixtures (tools/fixtures.py). Pillow (nix python3 pillow) is the reference decoder: it writes BLP2
|
||||
# palette files itself (not BLP1: Pillow 12 writes BLP1 mip offsets as if the header were BLP2's, 8 bytes short), and decodes the files written here from the wowdev.wiki layout: BLP2 DXT1 / DXT3 / DXT5
|
||||
# (random blocks), palette with 1 / 4 / 8-bit alpha planes, mip chains, and BLP1 JPEG (a Pillow
|
||||
# JPEG split into the shared header and the mip data). Pillow's RGBA -> CRC-32. Two cases Pillow reads differently
|
||||
# from the games (or not at all) are checked against this writer instead: uncompressed BGRA (Pillow 12 has no
|
||||
# encoding 3), BLP1 palette files with an 8-bit alpha plane, and BLP1
|
||||
# JPEGs of 4 components (BGRA without colour conversion: CMYK written inverted by Pillow, its Adobe marker removed)
|
||||
# whose reference is the source pixels (PSNR).
|
||||
# tests/gen/blp.luau { { name, data, width, height, crc?, rgba?, psnr? } }
|
||||
import io, json, struct, zlib
|
||||
|
||||
CODE = r"""
|
||||
import io, json, sys, zlib, random, struct
|
||||
from PIL import Image
|
||||
args = json.loads(sys.stdin.read())
|
||||
rng = random.Random(args["seed"])
|
||||
out = {}
|
||||
|
||||
def rgba_crc(im):
|
||||
return zlib.crc32(im.convert("RGBA").tobytes())
|
||||
|
||||
# 1. Pillow-written palette BLPs
|
||||
pal_img = Image.new("P", (13, 7))
|
||||
pal_img.putpalette(bytes(rng.randrange(256) for _ in range(768)))
|
||||
pal_img.putdata([rng.randrange(256) for _ in range(13 * 7)])
|
||||
for v in ("BLP2",):
|
||||
b = io.BytesIO()
|
||||
pal_img.save(b, "BLP", blp_version=v)
|
||||
data = b.getvalue()
|
||||
out["pillow-" + v.lower()] = {"data": data.hex(), "crc": rgba_crc(Image.open(io.BytesIO(data))), "w": 13, "h": 7}
|
||||
|
||||
# 2. Pillow decodes the hand-made files
|
||||
for name, hexdata in args["files"].items():
|
||||
try:
|
||||
im = Image.open(io.BytesIO(bytes.fromhex(hexdata)))
|
||||
im.load()
|
||||
out[name] = {"crc": rgba_crc(im), "w": im.size[0], "h": im.size[1], "rgba": im.convert("RGBA").tobytes().hex()}
|
||||
except Exception as e:
|
||||
out[name] = {"failed": str(e)}
|
||||
|
||||
# 3. JPEGs for BLP1: a 3-component one and a 4-component (CMYK) one
|
||||
src = Image.new("RGB", (24, 16))
|
||||
src.putdata([(rng.randrange(256), rng.randrange(256), rng.randrange(256)) for _ in range(24 * 16)])
|
||||
src = src.resize((24, 16))
|
||||
b = io.BytesIO(); src.save(b, "JPEG", quality=95)
|
||||
out["jpeg3"] = b.getvalue().hex()
|
||||
# smooth RGBA source pixels for the 4-component file, stored as B, G, R, A components
|
||||
px = [((x * 10) % 256, (y * 15) % 256, ((x + y) * 7) % 256, (255 - x * 8) % 256) for y in range(16) for x in range(24)]
|
||||
cm = Image.new("CMYK", (24, 16))
|
||||
# Pillow stores CMYK inverted: write 255 - (b, g, r, a) so the stored components are B, G, R, A
|
||||
cm.putdata([(255 - p[2], 255 - p[1], 255 - p[0], 255 - p[3]) for p in px])
|
||||
b = io.BytesIO(); cm.save(b, "JPEG", quality=98)
|
||||
out["jpeg4"] = b.getvalue().hex()
|
||||
out["jpeg4src"] = bytes(c for p in px for c in p).hex()
|
||||
print(json.dumps(out))
|
||||
"""
|
||||
|
||||
|
||||
def blp2(kind, comp, adepth, atype, w, h, mips, palette=b"\0" * 1024):
|
||||
offs, lens, at = [], [], 1172
|
||||
for m in mips:
|
||||
offs.append(at)
|
||||
lens.append(len(m))
|
||||
at += len(m)
|
||||
offs += [0] * (16 - len(mips))
|
||||
lens += [0] * (16 - len(mips))
|
||||
head = b"BLP2" + struct.pack("<IBBBBII", kind, comp, adepth, atype, 1 if len(mips) > 1 else 0, w, h)
|
||||
return head + struct.pack("<16I", *offs) + struct.pack("<16I", *lens) + palette + b"".join(mips)
|
||||
|
||||
|
||||
def blp1(comp, adepth, w, h, mips, extra=b""):
|
||||
base = 156 + len(extra)
|
||||
offs, lens, at = [], [], base
|
||||
for m in mips:
|
||||
offs.append(at)
|
||||
lens.append(len(m))
|
||||
at += len(m)
|
||||
offs += [0] * (16 - len(mips))
|
||||
lens += [0] * (16 - len(mips))
|
||||
return b"BLP1" + struct.pack("<6I", comp, adepth, w, h, 4, 1 if len(mips) > 1 else 0) + struct.pack("<16I", *offs) + struct.pack("<16I", *lens) + extra + b"".join(mips)
|
||||
|
||||
|
||||
def split_jpeg(j):
|
||||
# the shared header: everything before the first SOS marker
|
||||
k = j.index(b"\xff\xda")
|
||||
return j[:k], j[k:]
|
||||
|
||||
|
||||
def strip_adobe(j):
|
||||
i = j.find(b"\xff\xee")
|
||||
if i < 0:
|
||||
return j
|
||||
n = struct.unpack(">H", j[i + 2:i + 4])[0]
|
||||
return j[:i] + j[i + 2 + n:]
|
||||
|
||||
|
||||
def generate(ctx):
|
||||
rng = ctx.rng(121)
|
||||
w, h = 16, 12
|
||||
files = {}
|
||||
for name, atype, bs in (("dxt1", 0, 8), ("dxt3", 1, 16), ("dxt5", 7, 16)):
|
||||
blocks = rng.randbytes((w // 4) * (h // 4) * bs)
|
||||
files[name] = blp2(1, 2, 1 if name == "dxt1" else 8, atype, w, h, [blocks, rng.randbytes(2 * 2 * bs)]) # mip 1: 8 x 6
|
||||
bgra = rng.randbytes(w * h * 4)
|
||||
own = [{"name": "bgra", "data": blp2(1, 3, 8, 8, w, h, [bgra]), "width": w, "height": h,
|
||||
"rgba": b"".join(bytes((bgra[i + 2], bgra[i + 1], bgra[i], bgra[i + 3])) for i in range(0, len(bgra), 4))}]
|
||||
pal = bytes(rng.randrange(256) for _ in range(1024))
|
||||
alphas = {}
|
||||
for depth in (0, 1, 4, 8):
|
||||
idx = rng.randbytes(w * h)
|
||||
alpha = rng.randbytes({0: 0, 1: w * h // 8, 4: w * h // 2, 8: w * h}[depth])
|
||||
files["palette-a%d" % depth] = blp2(1, 1, depth, 0, w, h, [idx + alpha], pal)
|
||||
# the alpha plane (LSB first), expanded to 8 bits
|
||||
if depth == 1:
|
||||
alphas[depth] = bytes(255 if alpha[i // 8] >> (i % 8) & 1 else 0 for i in range(w * h))
|
||||
elif depth == 4:
|
||||
alphas[depth] = bytes(((alpha[i // 2] >> (4 * (i % 2))) & 15) * 17 for i in range(w * h))
|
||||
elif depth == 8:
|
||||
alphas[depth] = alpha
|
||||
res = json.loads(ctx.python(["pillow"], CODE, input=json.dumps({"seed": 5, "files": {k: v.hex() for k, v in files.items()}}).encode()))
|
||||
out = []
|
||||
for name in ("pillow-blp2",):
|
||||
r = res[name]
|
||||
out.append({"name": name, "data": bytes.fromhex(r["data"]), "width": r["w"], "height": r["h"], "crc": r["crc"]})
|
||||
for name, data in files.items():
|
||||
r = res[name]
|
||||
if "failed" in r:
|
||||
raise SystemExit("blp: Pillow cannot read %s: %s" % (name, r["failed"]))
|
||||
e = {"name": name, "data": data, "width": r["w"], "height": r["h"]}
|
||||
if name.startswith("dxt"):
|
||||
# Pillow's own DXT decoder expands the 5 / 6-bit endpoints by shifting only (r << 3), the D3D rule
|
||||
# replicates the top bits (r << 3 | r >> 2), and divides by 3 without rounding: colours compared within
|
||||
# 8, alpha exactly
|
||||
e["ref"], e["tol"] = bytes.fromhex(r["rgba"]), 8
|
||||
elif name.startswith("palette-a") and name != "palette-a0":
|
||||
# Pillow ignores the alpha plane (it takes the palette's alpha): RGB from Pillow, alpha from the writer
|
||||
e["rgbref"], e["alpha"] = bytes.fromhex(r["rgba"]), alphas[int(name[-1])]
|
||||
else:
|
||||
e["crc"] = r["crc"]
|
||||
out.append(e)
|
||||
out += own
|
||||
# BLP1 JPEG, 3 components: Pillow decodes it (YCbCr -> RGB, then R / B swapped)
|
||||
j3 = bytes.fromhex(res["jpeg3"])
|
||||
hd, body = split_jpeg(j3)
|
||||
d = blp1(0, 0, 24, 16, [body], struct.pack("<I", len(hd)) + hd)
|
||||
r = json.loads(ctx.python(["pillow"], CODE.split("# 1.")[0] + "im = Image.open(io.BytesIO(bytes.fromhex(args['d'])))\nprint(json.dumps({'crc': rgba_crc(im)}))\n", input=json.dumps({"seed": 1, "d": d.hex()}).encode()))
|
||||
out.append({"name": "blp1-jpeg3", "data": d, "width": 24, "height": 16, "crc": r["crc"]})
|
||||
# BLP1 JPEG, 4 components (BGRA)
|
||||
j4 = strip_adobe(bytes.fromhex(res["jpeg4"]))
|
||||
hd, body = split_jpeg(j4)
|
||||
d = blp1(0, 8, 24, 16, [body], struct.pack("<I", len(hd)) + hd)
|
||||
out.append({"name": "blp1-jpeg4", "data": d, "width": 24, "height": 16, "rgba": bytes.fromhex(res["jpeg4src"]), "psnr": 30})
|
||||
# BLP1 palette with an 8-bit alpha plane: indexes then alpha
|
||||
idx = rng.randbytes(w * h)
|
||||
alpha = rng.randbytes(w * h)
|
||||
d = blp1(1, 8, w, h, [idx + alpha], pal)
|
||||
rgba = b"".join(bytes((pal[i * 4 + 2], pal[i * 4 + 1], pal[i * 4], alpha[k])) for k, i in enumerate(idx))
|
||||
out.append({"name": "blp1-palette-a8", "data": d, "width": w, "height": h, "rgba": rgba})
|
||||
ctx.emit("blp", out)
|
||||
@@ -0,0 +1,238 @@
|
||||
# BSP fixtures (tools/fixtures.py): maps written here from the bspfile.h layouts of the Quake / Quake II source
|
||||
# releases and the Unofficial Quake 3 Map Specs: two boxes (the world and a brush entity "*1"), faces stored
|
||||
# clockwise as the games do (some with side = 1 on a flipped plane), texture vectors, entities.
|
||||
# q1 / hl: miptex lump with one embedded texture (Half-Life: with its palette) and one kept in a WAD (offsets 0);
|
||||
# q2: texture names (.wal sizes through opts.files);
|
||||
# q3: polygon, mesh and patch faces, two lightmaps, vertex colours; plus a .pk3 (zip) of it for assimp.
|
||||
# References: the expected triangles per model and texture (positions, normals, texture coordinates, computed here
|
||||
# with the documented rules), texture CRCs, entities; assimp's soup of the Quake III map.
|
||||
# tests/gen/bsp.luau { q1 = { data, palette, models = { [model] = { [texture] = { pos, uv, nrm } } }, textures,
|
||||
# entities }, hl = ..., q2 = { ..., wal }, q3 = { ..., lightmaps, patchArea, assimp } }
|
||||
import importlib.util, io, math, os, struct, zipfile, zlib
|
||||
|
||||
INPUTS = ["tools/fixtures/_quake_ref.py"]
|
||||
|
||||
|
||||
def ref(ctx):
|
||||
spec = importlib.util.spec_from_file_location("_quake_ref", os.path.join(ctx.root, "tools", "fixtures", "_quake_ref.py"))
|
||||
m = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(m)
|
||||
return m
|
||||
|
||||
|
||||
def f32(x):
|
||||
return struct.unpack("<f", struct.pack("<f", x))[0]
|
||||
|
||||
|
||||
ENTS = b'{\n"classname" "worldspawn"\n"message" "fixture map"\n}\n{\n"classname" "info_player_start"\n"origin" "16 16 24"\n}\n{\n"classname" "func_door"\n"model" "*1"\n}\n\0'
|
||||
|
||||
|
||||
def box(lo, hi):
|
||||
# 6 quads, each clockwise seen from outside (the games' winding), with the outward normal
|
||||
(x0, y0, z0), (x1, y1, z1) = lo, hi
|
||||
return [
|
||||
([(x0, y0, z1), (x0, y1, z1), (x1, y1, z1), (x1, y0, z1)], (0, 0, 1)),
|
||||
([(x0, y0, z0), (x1, y0, z0), (x1, y1, z0), (x0, y1, z0)], (0, 0, -1)),
|
||||
([(x1, y0, z0), (x1, y0, z1), (x1, y1, z1), (x1, y1, z0)], (1, 0, 0)),
|
||||
([(x0, y0, z0), (x0, y1, z0), (x0, y1, z1), (x0, y0, z1)], (-1, 0, 0)),
|
||||
([(x0, y1, z0), (x1, y1, z0), (x1, y1, z1), (x0, y1, z1)], (0, 1, 0)),
|
||||
([(x0, y0, z0), (x0, y0, z1), (x1, y0, z1), (x1, y0, z0)], (0, -1, 0)),
|
||||
]
|
||||
|
||||
|
||||
def ccw_fan(poly, n):
|
||||
# the decoder's rule: counter-clockwise about the face normal (Newell), fan from the first vertex
|
||||
ax = ay = az = 0.0
|
||||
k = len(poly)
|
||||
for i in range(k):
|
||||
(x1, y1, z1), (x2, y2, z2) = poly[i], poly[(i + 1) % k]
|
||||
ax += (y1 - y2) * (z1 + z2)
|
||||
ay += (z1 - z2) * (x1 + x2)
|
||||
az += (x1 - x2) * (y1 + y2)
|
||||
order = list(range(k)) if ax * n[0] + ay * n[1] + az * n[2] >= 0 else [0] + [k - i for i in range(1, k)]
|
||||
out = []
|
||||
for i in range(1, k - 1):
|
||||
out += [order[0], order[i], order[i + 1]]
|
||||
return out
|
||||
|
||||
|
||||
def brush_map(rng, variant, pal):
|
||||
q2 = variant == "q2"
|
||||
faces = [(f, 0) for f in box((-64, -64, 0), (64, 64, 128))] + [(f, 1) for f in box((-8, -8, 8), (8, 8, 40))]
|
||||
verts, edges, surfedges, planes, texinfo, flist = [], [(0, 0)], [], [], [], []
|
||||
vindex = {}
|
||||
|
||||
def vid(p):
|
||||
p = tuple(f32(c) for c in p)
|
||||
if p not in vindex:
|
||||
vindex[p] = len(verts)
|
||||
verts.append(p)
|
||||
return vindex[p]
|
||||
texnames = ["brick", "door"] if q2 else ["brick", "+0door"]
|
||||
sizes = [(16, 8), (8, 8)]
|
||||
tis = []
|
||||
for t in range(2):
|
||||
s = [f32(rng.uniform(-1, 1)) for _ in range(3)] + [f32(rng.uniform(-8, 8))]
|
||||
tt = [f32(rng.uniform(-1, 1)) for _ in range(3)] + [f32(rng.uniform(-8, 8))]
|
||||
tis.append((s, tt))
|
||||
texinfo.append((s, tt, t))
|
||||
models = {}
|
||||
for i, ((poly, n), model) in enumerate(faces):
|
||||
tex = model
|
||||
side = i % 3 == 2
|
||||
pn = tuple(-c for c in n) if side else n
|
||||
planes.append((pn, 0.0))
|
||||
first = len(surfedges)
|
||||
ids = [vid(p) for p in poly]
|
||||
for k in range(len(ids)):
|
||||
a, b = ids[k], ids[(k + 1) % len(ids)]
|
||||
if k % 2 == 0:
|
||||
edges.append((a, b))
|
||||
surfedges.append(len(edges) - 1)
|
||||
else:
|
||||
edges.append((b, a))
|
||||
surfedges.append(-(len(edges) - 1))
|
||||
flist.append((len(planes) - 1, 1 if side else 0, first, len(ids), tex))
|
||||
# expected triangles
|
||||
fp = [tuple(f32(c) for c in p) for p in poly]
|
||||
s, tt = tis[tex]
|
||||
w, h = (sizes[tex] if variant != "q2" else (sizes[tex] if tex == 0 else (1, 1)))
|
||||
e = models.setdefault(model, {}).setdefault(texnames[tex], {"pos": [], "uv": [], "nrm": []})
|
||||
for c in ccw_fan(fp, n):
|
||||
x, y, z = fp[c]
|
||||
e["pos"] += [x, y, z]
|
||||
e["nrm"] += list(n)
|
||||
e["uv"] += [(x * s[0] + y * s[1] + z * s[2] + s[3]) / w, (x * tt[0] + y * tt[1] + z * tt[2] + tt[3]) / h]
|
||||
# lumps
|
||||
L = {}
|
||||
L["entities"] = ENTS
|
||||
L["planes"] = b"".join(struct.pack("<4fi", *n, d, 0) for n, d in planes)
|
||||
L["vertices"] = b"".join(struct.pack("<3f", *v) for v in verts)
|
||||
L["edges"] = b"".join(struct.pack("<2H", *e) for e in edges)
|
||||
L["surfedges"] = b"".join(struct.pack("<i", s) for s in surfedges)
|
||||
L["faces"] = b"".join(struct.pack("<HHiHH4Bi", p, sd, fe, ne, ti, 0, 255, 255, 255, -1) for p, sd, fe, ne, ti in flist)
|
||||
if q2:
|
||||
L["texinfo"] = b"".join(struct.pack("<8fii32si", *s, *t, 0, 0, texnames[k].encode(), -1) for s, t, k in texinfo)
|
||||
L["models"] = b"".join(struct.pack("<9fiii", *([0.0] * 9), 0, first, 6) for first in (0, 6))
|
||||
else:
|
||||
L["texinfo"] = b"".join(struct.pack("<8fii", *s, *t, k, 0) for s, t, k in texinfo)
|
||||
L["models"] = b"".join(struct.pack("<9f4iiii", *([0.0] * 9), 0, 0, 0, 0, 0, first, 6) for first in (0, 6))
|
||||
# miptex: texture 0 embedded (+ palette for HL), texture 1 in a WAD
|
||||
mips, crcs = [], []
|
||||
w, h = sizes[0]
|
||||
pix = bytes(rng.randrange(256) for _ in range(w * h))
|
||||
mip = struct.pack("<16sII", texnames[0].encode(), w, h)
|
||||
o0 = 40
|
||||
o1 = o0 + w * h
|
||||
o2 = o1 + w * h // 4
|
||||
o3 = o2 + w * h // 16
|
||||
mip += struct.pack("<4I", o0, o1, o2, o3) + pix + bytes(w * h // 4 + w * h // 16 + w * h // 64)
|
||||
hp = bytes(rng.randrange(256) for _ in range(768))
|
||||
if variant == "hl":
|
||||
mip += struct.pack("<H", 256) + hp + b"\0\0"
|
||||
usepal = hp if variant == "hl" else pal
|
||||
crcs.append(zlib.crc32(b"".join(usepal[i * 3:i * 3 + 3] + b"\xff" for i in pix)))
|
||||
mip2 = struct.pack("<16sII4I", texnames[1].encode(), 8, 8, 0, 0, 0, 0)
|
||||
lump = struct.pack("<ii", 2, 12) + struct.pack("<i", 12 + len(mip)) + mip + mip2
|
||||
L["miptex"] = lump
|
||||
mips = crcs
|
||||
names = (["entities", "planes", "vertices", "visibility", "nodes", "texinfo", "faces", "lighting", "leaves",
|
||||
"leaffaces", "leafbrushes", "edges", "surfedges", "models", "brushes", "brushsides", "pop", "areas", "areaportals"]
|
||||
if q2 else ["entities", "planes", "miptex", "vertices", "visibility", "nodes", "texinfo", "faces", "lighting",
|
||||
"clipnodes", "leaves", "marksurfaces", "edges", "surfedges", "models"])
|
||||
head = (b"IBSP" + struct.pack("<i", 38)) if q2 else struct.pack("<i", 30 if variant == "hl" else 29)
|
||||
off = len(head) + 8 * len(names)
|
||||
body, dirs = b"", []
|
||||
for n in names:
|
||||
d = L.get(n, b"")
|
||||
dirs.append((off + len(body), len(d)))
|
||||
body += d + b"\0" * ((4 - len(d) % 4) % 4)
|
||||
data = head + b"".join(struct.pack("<ii", *d) for d in dirs) + body
|
||||
out = {"data": data, "models": {str(k): v for k, v in models.items()}, "names": texnames}
|
||||
if not q2:
|
||||
out["textures"] = mips
|
||||
else:
|
||||
out["wal"] = struct.pack("<32sII", b"brick", 16, 8) + bytes(24)
|
||||
return out
|
||||
|
||||
|
||||
def q3_map(rng):
|
||||
verts, meshverts, faces = [], [], []
|
||||
expect = {}
|
||||
def v(p, uv, lm, n, col):
|
||||
verts.append((p, uv, lm, n, col))
|
||||
return len(verts) - 1
|
||||
# 2 polygon quads (shader 0, lightmap 0 / 1), one mesh triangle pair (shader 1), model 1 gets the last
|
||||
quads = [([(0, 0, 0), (64, 0, 0), (64, 64, 0), (0, 64, 0)], 0, 0, 0), ([(0, 0, 64), (0, 64, 64), (64, 64, 64), (64, 0, 64)], 0, 1, 0),
|
||||
([(8, 8, 8), (8, 8, 24), (24, 8, 24), (24, 8, 8)], 1, 0, 1)]
|
||||
for poly, sh, lm, model in quads:
|
||||
first = len(verts)
|
||||
# the stored order is clockwise seen from the front (Quake III's culling): the normal is minus Newell's
|
||||
(ax, ay, az), (bx, by, bz), (cx, cy, cz) = poly[0], poly[1], poly[2]
|
||||
u, w = (bx - ax, by - ay, bz - az), (cx - ax, cy - ay, cz - az)
|
||||
cr = (u[1] * w[2] - u[2] * w[1], u[2] * w[0] - u[0] * w[2], u[0] * w[1] - u[1] * w[0])
|
||||
ln = math.sqrt(sum(c * c for c in cr))
|
||||
nrm = tuple(f32(-c / ln) for c in cr)
|
||||
for p in poly:
|
||||
v(tuple(f32(c) for c in p), (f32(rng.random()), f32(rng.random())), (f32(rng.random()), f32(rng.random())), nrm, tuple(rng.randrange(256) for _ in range(4)))
|
||||
mv = len(meshverts)
|
||||
meshverts += [0, 1, 2, 0, 2, 3]
|
||||
faces.append((sh, 1 if model == 0 else 3, first, 4, mv, 6, lm))
|
||||
e = expect.setdefault(str(model), {}).setdefault("%d:%d" % (sh, lm), {"pos": [], "uv": [], "lm": [], "col": []})
|
||||
for tri in ((0, 1, 2), (0, 2, 3)):
|
||||
for c in reversed(tri):
|
||||
p, uv, lmuv, n, col = verts[first + c]
|
||||
e["pos"] += list(p)
|
||||
e["uv"] += list(uv)
|
||||
e["lm"] += list(lmuv)
|
||||
e["col"] += list(col)
|
||||
# a flat 3x3 patch over [0, 32] x [0, 32] at z = 100, facing down (clockwise from below: rows along +y)
|
||||
first = len(verts)
|
||||
for j in range(3):
|
||||
for i in range(3):
|
||||
v((f32(i * 16.0), f32(j * 16.0), f32(100.0)), (i / 2, j / 2), (0.0, 0.0), (0.0, 0.0, -1.0), (255, 255, 255, 255))
|
||||
faces.append((1, 2, first, 9, 0, 0, -1, 3, 3))
|
||||
shaders = [b"textures/base/wall", b"textures/base/floor"]
|
||||
L = {}
|
||||
L["entities"] = ENTS
|
||||
L["textures"] = b"".join(struct.pack("<64sii", s, 0, 1) for s in shaders)
|
||||
L["planes"] = struct.pack("<4f", 0, 0, 1, 0)
|
||||
L["models"] = struct.pack("<6fiiii", *([0.0] * 6), 0, 2, 0, 0) + struct.pack("<6fiiii", *([0.0] * 6), 2, 2, 0, 0)
|
||||
# reorder: model 0 = faces 0, 1 (quads of model 0) ... the patch is face 3 (model 1 range is 2..3)
|
||||
L["vertexes"] = b"".join(struct.pack("<10f4B", *p, *uv, *lm, *n, *c) for p, uv, lm, n, c in verts)
|
||||
L["meshverts"] = b"".join(struct.pack("<i", m) for m in meshverts)
|
||||
fb = b""
|
||||
for f in faces:
|
||||
sh, kind, first, n, mv, nmv, lm = f[:7]
|
||||
w, h = (f[7], f[8]) if len(f) > 7 else (0, 0)
|
||||
fb += struct.pack("<8i2i2i3f6f3f2i", sh, -1, kind, first, n, mv, nmv, lm, 0, 0, 0, 0, *([0.0] * 12), w, h)
|
||||
L["faces"] = fb
|
||||
lms = [bytes(rng.randrange(256) for _ in range(128 * 128 * 3)) for _ in range(2)]
|
||||
L["lightmaps"] = b"".join(lms)
|
||||
names = ["entities", "textures", "planes", "nodes", "leafs", "leaffaces", "leafbrushes", "models", "brushes",
|
||||
"brushsides", "vertexes", "meshverts", "effects", "faces", "lightmaps", "lightvols", "visdata"]
|
||||
off = 8 + 8 * len(names)
|
||||
body, dirs = b"", []
|
||||
for n in names:
|
||||
d = L.get(n, b"")
|
||||
dirs.append((off + len(body), len(d)))
|
||||
body += d + b"\0" * ((4 - len(d) % 4) % 4)
|
||||
data = b"IBSP" + struct.pack("<i", 46) + b"".join(struct.pack("<ii", *d) for d in dirs) + body
|
||||
lmcrc = [zlib.crc32(b"".join(l[k * 3:k * 3 + 3] + b"\xff" for k in range(128 * 128))) for l in lms]
|
||||
return {"data": data, "models": expect, "lightmaps": lmcrc, "patchArea": 32.0 * 32.0, "shaders": [s.decode() for s in shaders]}
|
||||
|
||||
|
||||
def generate(ctx):
|
||||
rng = ctx.rng(101)
|
||||
R = ref(ctx)
|
||||
pal = bytes(rng.randrange(256) for _ in range(768))
|
||||
q1 = brush_map(rng, "q1", pal)
|
||||
q1["palette"] = pal
|
||||
hl = brush_map(rng, "hl", pal)
|
||||
q2 = brush_map(rng, "q2", pal)
|
||||
q3 = q3_map(rng)
|
||||
zbuf = io.BytesIO()
|
||||
with zipfile.ZipFile(zbuf, "w") as z:
|
||||
z.writestr("maps/test.bsp", q3["data"])
|
||||
q3["assimp"] = R.assimp_soup(ctx, zbuf.getvalue(), "pk3")
|
||||
ctx.emit("bsp", {"q1": q1, "hl": hl, "q2": q2, "q3": q3})
|
||||
@@ -0,0 +1,78 @@
|
||||
# Docs inputs for the game formats sections of the archive / scene / image pages (tools/fixtures.py;
|
||||
# tools/docs_check.py explains the inputs), made with the writers of the format fixtures: a Quake PAK
|
||||
# (tools/fixtures/pak.py), a PWAD with a room map, a flat and a tall patch (wad.py), a Build GRP, a VPK (Python's vpk
|
||||
# package, through vpk.py), an MPQ (StormLib, through mpq.py), an MD2 (md2.py), an .md5mesh + .md5anim (md5.py), an
|
||||
# SMD (smd.py), a Half-Life BSP (bsp.py), a PlayStation TIM (tim.py), a BLP2 (blp.py) and a VTF 7.2.
|
||||
# tests/gen/docs_game.luau { files = { [name] = bytes }, vars = { pakBytes = "pak0.pak", ... } }
|
||||
import importlib.util, json, os, struct, tempfile, shutil
|
||||
|
||||
INPUTS = ["tools/docs_check.py"]
|
||||
|
||||
|
||||
def mod(ctx, name):
|
||||
spec = importlib.util.spec_from_file_location("fx_" + name, os.path.join(ctx.root, "tools", "fixtures", name + ".py"))
|
||||
m = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(m)
|
||||
return m
|
||||
|
||||
|
||||
def vtf72(w, h, rgba):
|
||||
hd = bytearray(80)
|
||||
struct.pack_into("<4sIIIHHIHH", hd, 0, b"VTF\0", 7, 2, 80, w, h, 0, 1, 0)
|
||||
struct.pack_into("<f", hd, 48, 1.0)
|
||||
struct.pack_into("<iBiBBH", hd, 52, 0, 1, -1, 0, 0, 1)
|
||||
return bytes(hd) + rgba
|
||||
|
||||
|
||||
def generate(ctx):
|
||||
rng = ctx.rng(3)
|
||||
spec = importlib.util.spec_from_file_location("docs_check", os.path.join(ctx.root, "tools", "docs_check.py"))
|
||||
check = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(check)
|
||||
files = {}
|
||||
files["pak0.pak"] = mod(ctx, "pak").write([("maps/start.bsp", rng.randbytes(64)), ("gfx/palette.lmp", bytes(range(256)) * 3),
|
||||
("progs/player.mdl", rng.randbytes(32)), ("default.cfg", b"bind w +forward\n")])
|
||||
files["room.wad"], _ = mod(ctx, "wad").room()
|
||||
files["duke.grp"] = mod(ctx, "grp").write([("GAME.CON", b"define X 1\n"), ("E1L1.MAP", rng.randbytes(40))])
|
||||
# VPK: the vpk package
|
||||
vpk = mod(ctx, "vpk")
|
||||
tmp = tempfile.mkdtemp(prefix="formats-docs-game-")
|
||||
try:
|
||||
src = os.path.join(tmp, "src")
|
||||
for name, data in (("materials/brick/wall.vmt", b"LightmappedGeneric { }"), ("scripts/game.txt", b"\"game\" { }\n")):
|
||||
p = os.path.join(src, name)
|
||||
os.makedirs(os.path.dirname(p), exist_ok=True)
|
||||
open(p, "wb").write(data)
|
||||
out = os.path.join(tmp, "pak01_dir.vpk")
|
||||
ctx.python(["vpk"], vpk.WRITE, input=json.dumps({"src": src, "version": 2, "out": out}).encode())
|
||||
files["pak01_dir.vpk"] = open(out, "rb").read()
|
||||
# MPQ: StormLib
|
||||
mpq = mod(ctx, "mpq")
|
||||
txt = os.path.join(tmp, "readme.txt")
|
||||
open(txt, "wb").write(b"Warcraft III map notes\n" * 20)
|
||||
arch = {"name": "map", "path": os.path.join(tmp, "map.w3x"), "create": 0x00100000,
|
||||
"files": [{"name": "war3map.j", "src": txt, "flags": mpq.COMPRESS | mpq.REPLACE, "comp": mpq.ZLIB},
|
||||
{"name": "readme.txt", "src": txt, "flags": mpq.IMPLODE | mpq.REPLACE, "comp": mpq.PKWARE}]}
|
||||
ctx.python([], mpq.CODE, input=json.dumps({"lib": mpq.lib_path(), "archives": [arch], "implode": [], "modes": []}).encode())
|
||||
files["map.w3x"] = open(arch["path"], "rb").read()
|
||||
finally:
|
||||
shutil.rmtree(tmp)
|
||||
files["tank.md2"], _, _ = mod(ctx, "md2").md2(rng, 12, 12, 10, ["stand1", "stand2", "run1", "run2", "run3"], ["models/tank/skin.pcx"])
|
||||
md5 = mod(ctx, "md5")
|
||||
text, info = md5.mesh(rng)
|
||||
files["imp.md5mesh"] = text.encode()
|
||||
atext, _ = md5.anim(rng, info["joints"], 5, 24, "idle")
|
||||
files["idle.md5anim"] = atext.encode()
|
||||
stext, _ = mod(ctx, "smd").smd(rng, 3, 4, 6, ["skin.bmp"], True, False)
|
||||
files["barney.smd"] = stext.encode()
|
||||
files["crossfire.bsp"] = mod(ctx, "bsp").brush_map(rng, "hl", bytes(768))["data"]
|
||||
tdata, _, _, _ = mod(ctx, "tim").tim(rng, 16, 8, 4)
|
||||
files["face.tim"] = tdata
|
||||
files["icon.blp"] = mod(ctx, "blp").blp2(1, 3, 8, 8, 4, 4, [rng.randbytes(64)])
|
||||
files["wall.vtf"] = vtf72(4, 4, rng.randbytes(64))
|
||||
check.emit_inputs(ctx, files, {
|
||||
"pakBytes": "pak0.pak", "wadBytes": "room.wad", "grpBytes": "duke.grp", "vpkBytes": "pak01_dir.vpk",
|
||||
"mpqBytes": "map.w3x", "md2Bytes": "tank.md2", "md5meshBytes": "imp.md5mesh", "md5animBytes": "idle.md5anim",
|
||||
"smdBytes": "barney.smd", "bspBytes": "crossfire.bsp", "timBytes": "face.tim", "blpBytes": "icon.blp",
|
||||
"vtfBytes": "wall.vtf",
|
||||
})
|
||||
@@ -0,0 +1,35 @@
|
||||
# Build GRP fixtures (tools/fixtures.py): GRP files written here from Ken Silverman's layout ("KenSilverman", count,
|
||||
# 12-byte names + u32 sizes, files back to back), with the entries an independent Python reader sees.
|
||||
# tests/gen/grp.luau { { name, data, entries = { { name, size, crc } }, files = { { name, data } } } }
|
||||
import struct, zlib
|
||||
|
||||
|
||||
def write(files):
|
||||
out = bytearray(b"KenSilverman" + struct.pack("<I", len(files)))
|
||||
for name, data in files:
|
||||
out += struct.pack("<12sI", name.encode(), len(data))
|
||||
for _, data in files:
|
||||
out += data
|
||||
return bytes(out)
|
||||
|
||||
|
||||
def read(data):
|
||||
n = struct.unpack_from("<I", data, 12)[0]
|
||||
at, out = 16 + 16 * n, []
|
||||
for i in range(n):
|
||||
name, size = struct.unpack_from("<12sI", data, 16 + 16 * i)
|
||||
out.append({"name": name.split(b"\0")[0].decode(), "size": size, "crc": zlib.crc32(data[at:at + size])})
|
||||
at += size
|
||||
return out
|
||||
|
||||
|
||||
def generate(ctx):
|
||||
rng = ctx.rng(23)
|
||||
base = [("TILES000.ART", rng.randbytes(4000)), ("PALETTE.DAT", rng.randbytes(768 + 2 + 32 * 256)),
|
||||
("GAME.CON", b"// con\ndefine X 1\n"), ("E1L1.MAP", rng.randbytes(900)), ("EMPTY.VOC", b""),
|
||||
("TWELVECHARSX", b"12 bytes, no NUL")]
|
||||
out = []
|
||||
for name, files in (("duke", base), ("empty", []), ("one", base[:1])):
|
||||
data = write(files)
|
||||
out.append({"name": name, "data": data, "entries": read(data), "files": [{"name": n, "data": d} for n, d in files]})
|
||||
ctx.emit("grp", out)
|
||||
@@ -0,0 +1,75 @@
|
||||
# Quake II MD2 fixtures (tools/fixtures.py): MD2 files written here from the dmdl_t layout (random frames with
|
||||
# scale / translate, distinct-vertex triangles, texture coordinates, skins, frame names in groups); references:
|
||||
# assimp's triangle soup of frame 0 (positions, texture coordinates: assimp flips v) and this writer's own exact
|
||||
# positions of every frame (CRC-32 of the f32 soup in our corner order: reversed to counter-clockwise).
|
||||
# tests/gen/md2.luau { { name, data, frames = n, names, skins, tris, crcs = { per frame }, assimp = { pos, uv } } }
|
||||
import importlib.util, os, struct, zlib
|
||||
|
||||
INPUTS = ["tools/fixtures/_quake_ref.py"]
|
||||
|
||||
|
||||
def ref(ctx):
|
||||
spec = importlib.util.spec_from_file_location("_quake_ref", os.path.join(ctx.root, "tools", "fixtures", "_quake_ref.py"))
|
||||
m = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(m)
|
||||
return m
|
||||
|
||||
|
||||
def f32(x):
|
||||
return struct.unpack("<f", struct.pack("<f", x))[0]
|
||||
|
||||
|
||||
def md2(rng, nverts, nst, ntris, frames, skins, sw=64, sh=32):
|
||||
st = [(rng.randrange(sw), rng.randrange(sh)) for _ in range(nst)]
|
||||
tris = []
|
||||
for _ in range(ntris):
|
||||
tris.append((tuple(rng.sample(range(nverts), 3)), tuple(rng.randrange(nst) for _ in range(3))))
|
||||
fr = []
|
||||
for name in frames:
|
||||
scale = tuple(f32(rng.uniform(0.05, 0.2)) for _ in range(3))
|
||||
tr = tuple(f32(rng.uniform(-20, 20)) for _ in range(3))
|
||||
vs = [(rng.randrange(256), rng.randrange(256), rng.randrange(256), rng.randrange(162)) for _ in range(nverts)]
|
||||
fr.append((scale, tr, name, vs))
|
||||
framesize = 40 + 4 * nverts
|
||||
o_skins = 68
|
||||
o_st = o_skins + 64 * len(skins)
|
||||
o_tris = o_st + 4 * nst
|
||||
o_frames = o_tris + 12 * ntris
|
||||
o_gl = o_frames + framesize * len(fr)
|
||||
out = struct.pack("<4s16i", b"IDP2", 8, sw, sh, framesize, len(skins), nverts, nst, ntris, 1, len(fr), o_skins, o_st, o_tris, o_frames, o_gl, o_gl + 4)
|
||||
for s in skins:
|
||||
out += s.encode().ljust(64, b"\0")
|
||||
for s, t in st:
|
||||
out += struct.pack("<hh", s, t)
|
||||
for v, t in tris:
|
||||
out += struct.pack("<6H", *v, *t)
|
||||
for scale, tr, name, vs in fr:
|
||||
out += struct.pack("<6f", *scale, *tr) + name.encode().ljust(16, b"\0")
|
||||
for v in vs:
|
||||
out += bytes(v)
|
||||
out += struct.pack("<i", 0)
|
||||
crcs = []
|
||||
for scale, tr, name, vs in fr:
|
||||
soup = b""
|
||||
for v, t in tris:
|
||||
for c in (2, 1, 0):
|
||||
p = vs[v[c]]
|
||||
soup += struct.pack("<3f", *(p[k] * scale[k] + tr[k] for k in range(3)))
|
||||
crcs.append(zlib.crc32(soup))
|
||||
return out, crcs, len(tris)
|
||||
|
||||
|
||||
def generate(ctx):
|
||||
rng = ctx.rng(52)
|
||||
R = ref(ctx)
|
||||
specs = [
|
||||
("monster", 40, 50, 60, ["stand01", "stand02", "stand03", "run1", "run2", "run3", "run4", "attack1", "attack2", "pain"], ["models/monsters/test/skin.pcx", "models/monsters/test/pain.pcx"]),
|
||||
("single", 12, 12, 8, ["frame"], ["skin.pcx"]),
|
||||
("noskin", 20, 30, 25, ["a1", "a2"], []),
|
||||
]
|
||||
out = []
|
||||
for name, nv, nst, nt, frames, skins in specs:
|
||||
data, crcs, ntris = md2(rng, nv, nst, nt, frames, skins)
|
||||
out.append({"name": name, "data": data, "frames": len(frames), "names": frames, "skins": skins, "tris": ntris,
|
||||
"crcs": crcs, "assimp": R.assimp_soup(ctx, data, "md2")})
|
||||
ctx.emit("md2", out)
|
||||
@@ -0,0 +1,93 @@
|
||||
# Quake III MD3 fixtures (tools/fixtures.py): MD3 files written here from the md3Header_t / md3Surface_t layout
|
||||
# (several surfaces with shaders, frames of 1/64-unit i16 positions with lat / long normals, tags per frame);
|
||||
# references: assimp's triangle soup of frame 0 (every surface: positions, texture coordinates) and this writer's
|
||||
# exact positions and decoded normals of every frame (CRC-32 of the f32 soup in our corner order), tag origins.
|
||||
# tests/gen/md3.luau { { name, data, frames, surfaces = { { name, shader, tris, crcs, ncrcs } }, tags = { ... },
|
||||
# assimp = { pos, uv, meshes } } }
|
||||
import importlib.util, math, os, struct, zlib
|
||||
|
||||
INPUTS = ["tools/fixtures/_quake_ref.py"]
|
||||
|
||||
|
||||
def ref(ctx):
|
||||
spec = importlib.util.spec_from_file_location("_quake_ref", os.path.join(ctx.root, "tools", "fixtures", "_quake_ref.py"))
|
||||
m = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(m)
|
||||
return m
|
||||
|
||||
|
||||
def f32(x):
|
||||
return struct.unpack("<f", struct.pack("<f", x))[0]
|
||||
|
||||
|
||||
def normal(n):
|
||||
lat = ((n >> 8) & 255) * math.pi / 128
|
||||
lng = (n & 255) * math.pi / 128
|
||||
return (math.cos(lat) * math.sin(lng), math.sin(lat) * math.sin(lng), math.cos(lng))
|
||||
|
||||
|
||||
def surface(rng, name, shader, nframes, nverts, ntris):
|
||||
tris = [tuple(rng.sample(range(nverts), 3)) for _ in range(ntris)]
|
||||
st = [(f32(rng.uniform(0, 1)), f32(rng.uniform(0, 1))) for _ in range(nverts)]
|
||||
xyz = [[(rng.randrange(-3000, 3000), rng.randrange(-3000, 3000), rng.randrange(-3000, 3000), rng.randrange(65536)) for _ in range(nverts)] for _ in range(nframes)]
|
||||
o_tri = 108
|
||||
o_sh = o_tri + 12 * ntris
|
||||
o_st = o_sh + 68
|
||||
o_xyz = o_st + 8 * nverts
|
||||
o_end = o_xyz + 8 * nverts * nframes
|
||||
out = struct.pack("<4s64siiiiiiiiii", b"IDP3", name.encode(), 0, nframes, 1, nverts, ntris, o_tri, o_sh, o_st, o_xyz, o_end)
|
||||
for t in tris:
|
||||
out += struct.pack("<3i", *t)
|
||||
out += struct.pack("<64si", shader.encode(), 0)
|
||||
for s in st:
|
||||
out += struct.pack("<2f", *s)
|
||||
for f in xyz:
|
||||
for x, y, z, n in f:
|
||||
out += struct.pack("<3hH", x, y, z, n)
|
||||
crcs, ncrcs = [], []
|
||||
for f in xyz:
|
||||
soup, nsoup = b"", b""
|
||||
for t in tris:
|
||||
for c in (2, 1, 0):
|
||||
x, y, z, n = f[t[c]]
|
||||
soup += struct.pack("<3f", x / 64, y / 64, z / 64)
|
||||
nsoup += struct.pack("<3f", *normal(n))
|
||||
crcs.append(zlib.crc32(soup))
|
||||
ncrcs.append(zlib.crc32(nsoup))
|
||||
return out, {"name": name, "shader": shader, "tris": ntris, "crcs": crcs, "ncrcs": ncrcs}
|
||||
|
||||
|
||||
def md3(rng, nframes, surfs, ntags):
|
||||
frames = b""
|
||||
for i in range(nframes):
|
||||
frames += struct.pack("<10f16s", *([0.0] * 10), b"frame%d" % i)
|
||||
tags, tagref = b"", []
|
||||
for f in range(nframes):
|
||||
for k in range(ntags):
|
||||
o = tuple(f32(rng.uniform(-10, 10)) for _ in range(3))
|
||||
ang = rng.uniform(0, math.pi)
|
||||
ax = ((math.cos(ang), math.sin(ang), 0.0), (-math.sin(ang), math.cos(ang), 0.0), (0.0, 0.0, 1.0))
|
||||
tags += struct.pack("<64s12f", b"tag_%d" % k, *o, *[c for a in ax for c in a])
|
||||
tagref.append({"name": "tag_%d" % k, "frame": f + 1, "origin": list(o), "angle": ang})
|
||||
body, info = b"", []
|
||||
for args in surfs:
|
||||
s, i = surface(rng, args[0], args[1], nframes, args[2], args[3])
|
||||
body += s
|
||||
info.append(i)
|
||||
o_frames = 108
|
||||
o_tags = o_frames + len(frames)
|
||||
o_surf = o_tags + len(tags)
|
||||
o_end = o_surf + len(body)
|
||||
head = struct.pack("<4si64siiiiiiiii", b"IDP3", 15, b"models/test/test.md3", 0, nframes, ntags, len(surfs), 0, o_frames, o_tags, o_surf, o_end)
|
||||
return head + frames + tags + body, info, tagref
|
||||
|
||||
|
||||
def generate(ctx):
|
||||
rng = ctx.rng(63)
|
||||
R = ref(ctx)
|
||||
out = []
|
||||
for name, nframes, surfs, ntags in [("two-surfaces", 4, [("body", "models/test/body.tga", 30, 40), ("head", "models/test/head", 12, 10)], 2),
|
||||
("one-frame", 1, [("s", "textures/x.tga", 8, 6)], 0)]:
|
||||
data, info, tags = md3(rng, nframes, surfs, ntags)
|
||||
out.append({"name": name, "data": data, "frames": nframes, "surfaces": info, "tags": tags, "assimp": R.assimp_soup(ctx, data, "md3")})
|
||||
ctx.emit("md3", out)
|
||||
@@ -0,0 +1,145 @@
|
||||
# Doom 3 MD5 fixtures (tools/fixtures.py): an .md5mesh (random joint hierarchy in model space, two meshes whose
|
||||
# vertices hang off 1-3 weights) and two .md5anim files (animated component flags, baseframe, frames) written here
|
||||
# from the format notes; references: assimp's triangle soup of the bind pose (positions, texture coordinates) and
|
||||
# this writer's own values (bind positions from the weights, joints, every frame's parent-relative pose).
|
||||
# tests/gen/md5.luau { mesh = { data, joints, positions = { per mesh: { x, y, z, ... } }, tris, assimp },
|
||||
# anims = { { name, data, frames, rate, poses = { [frame] = { [joint] = { t, q } } } } } }
|
||||
import importlib.util, math, os, random
|
||||
|
||||
INPUTS = ["tools/fixtures/_quake_ref.py"]
|
||||
|
||||
|
||||
def ref(ctx):
|
||||
spec = importlib.util.spec_from_file_location("_quake_ref", os.path.join(ctx.root, "tools", "fixtures", "_quake_ref.py"))
|
||||
m = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(m)
|
||||
return m
|
||||
|
||||
|
||||
def r6(v):
|
||||
return float("%.6f" % v)
|
||||
|
||||
|
||||
def quat_w(x, y, z):
|
||||
t = 1 - x * x - y * y - z * z
|
||||
return 0.0 if t < 0 else -math.sqrt(t)
|
||||
|
||||
|
||||
def rand_q(rng):
|
||||
# a random unit quaternion with w <= 0 (stored as x, y, z)
|
||||
while True:
|
||||
q = [rng.uniform(-1, 1) for _ in range(4)]
|
||||
n = math.sqrt(sum(c * c for c in q))
|
||||
if n > 0.1:
|
||||
q = [c / n for c in q]
|
||||
if q[3] > 0:
|
||||
q = [-c for c in q]
|
||||
return [r6(q[0]), r6(q[1]), r6(q[2])]
|
||||
|
||||
|
||||
def rotate(q, v):
|
||||
qx, qy, qz, qw = q
|
||||
vx, vy, vz = v
|
||||
tx, ty, tz = 2 * (qy * vz - qz * vy), 2 * (qz * vx - qx * vz), 2 * (qx * vy - qy * vx)
|
||||
return (vx + qw * tx + (qy * tz - qz * ty), vy + qw * ty + (qz * tx - qx * tz), vz + qw * tz + (qx * ty - qy * tx))
|
||||
|
||||
|
||||
def mesh(rng, njoints=5):
|
||||
joints = []
|
||||
lines = ["MD5Version 10", 'commandline "written by tools/fixtures/md5.py"', "", "numJoints %d" % njoints, "numMeshes 2", "", "joints {"]
|
||||
for i in range(njoints):
|
||||
parent = -1 if i == 0 else rng.randrange(i)
|
||||
p = [r6(rng.uniform(-30, 30)) for _ in range(3)]
|
||||
q = rand_q(rng)
|
||||
joints.append({"name": "joint%d" % i, "parent": parent + 1, "pos": p, "q": q + [quat_w(*q)]})
|
||||
lines.append('\t"joint%d"\t%d ( %s ) ( %s )\t\t// comment' % (i, parent, " ".join("%.6f" % c for c in p), " ".join("%.6f" % c for c in q)))
|
||||
lines.append("}")
|
||||
positions, tris_all, uvs = [], [], []
|
||||
for m in range(2):
|
||||
nverts, ntris = 8 + m * 4, 6 + m * 2
|
||||
verts, weights = [], []
|
||||
for v in range(nverts):
|
||||
k = rng.randrange(1, 4)
|
||||
ws = [rng.uniform(0.2, 1) for _ in range(k)]
|
||||
s = sum(ws)
|
||||
ws = [r6(w / s) for w in ws]
|
||||
start = len(weights)
|
||||
for j, w in zip(rng.sample(range(njoints), k), ws): # distinct joints per vertex (assimp 6 crashes on repeats)
|
||||
weights.append((j, w, [r6(rng.uniform(-5, 5)) for _ in range(3)]))
|
||||
verts.append(([r6(rng.random()), r6(rng.random())], start, k))
|
||||
# every vertex in some triangle (assimp 6's MD5 loader corrupts memory on unused vertices)
|
||||
order = list(range(nverts))
|
||||
rng.shuffle(order)
|
||||
tris = [(order[i % nverts], order[(i + 1) % nverts], order[(i + 2) % nverts]) for i in range(0, nverts, 3)]
|
||||
tris += [tuple(rng.sample(range(nverts), 3)) for _ in range(ntris - len(tris))]
|
||||
lines += ["", "mesh {", '\tshader "models/test/skin%d"' % m, "", "\tnumverts %d" % nverts]
|
||||
for i, (st, start, k) in enumerate(verts):
|
||||
lines.append("\tvert %d ( %.6f %.6f ) %d %d" % (i, st[0], st[1], start, k))
|
||||
lines.append("\n\tnumtris %d" % ntris)
|
||||
for i, t in enumerate(tris):
|
||||
lines.append("\ttri %d %d %d %d" % (i, *t))
|
||||
lines.append("\n\tnumweights %d" % len(weights))
|
||||
for i, (j, b, p) in enumerate(weights):
|
||||
lines.append("\tweight %d %d %.6f ( %s )" % (i, j, b, " ".join("%.6f" % c for c in p)))
|
||||
lines.append("}")
|
||||
pos = []
|
||||
for st, start, k in verts:
|
||||
acc = [0.0, 0.0, 0.0]
|
||||
for j, b, p in weights[start:start + k]:
|
||||
jt = joints[j]
|
||||
r = rotate(jt["q"], p)
|
||||
for c in range(3):
|
||||
acc[c] += (jt["pos"][c] + r[c]) * b
|
||||
pos += acc
|
||||
positions.append(pos)
|
||||
tris_all.append(len(tris))
|
||||
uvs.append([c for st, s, k in verts for c in st])
|
||||
return "\n".join(lines) + "\n", {"joints": joints, "positions": positions, "tris": tris_all, "uvs": uvs}
|
||||
|
||||
|
||||
def anim(rng, joints, nframes, rate, name):
|
||||
nj = len(joints)
|
||||
flags = [rng.randrange(64) for _ in range(nj)]
|
||||
base = [[r6(rng.uniform(-10, 10)) for _ in range(3)] + rand_q(rng) for _ in range(nj)]
|
||||
starts, n = [], 0
|
||||
for f in flags:
|
||||
starts.append(n)
|
||||
n += bin(f).count("1")
|
||||
lines = ["MD5Version 10", 'commandline ""', "", "numFrames %d" % nframes, "numJoints %d" % nj, "frameRate %d" % rate, "numAnimatedComponents %d" % n, "", "hierarchy {"]
|
||||
for i, j in enumerate(joints):
|
||||
lines.append('\t"%s"\t%d %d %d' % (j["name"], j["parent"] - 1, flags[i], starts[i]))
|
||||
lines += ["}", "", "bounds {"] + ["\t( -1 -1 -1 ) ( 1 1 1 )"] * nframes + ["}", "", "baseframe {"]
|
||||
for b in base:
|
||||
lines.append("\t( %s ) ( %s )" % (" ".join("%.6f" % c for c in b[:3]), " ".join("%.6f" % c for c in b[3:])))
|
||||
lines.append("}")
|
||||
poses = []
|
||||
for f in range(nframes):
|
||||
vals, pose = [], []
|
||||
for i in range(nj):
|
||||
v = list(base[i])
|
||||
for bit in range(6):
|
||||
if flags[i] & (1 << bit):
|
||||
if bit < 3:
|
||||
x = r6(rng.uniform(-10, 10))
|
||||
else:
|
||||
x = r6(rng.uniform(-0.5, 0.5))
|
||||
v[bit] = x
|
||||
vals.append(x)
|
||||
pose.append({"t": v[:3], "q": v[3:] + [quat_w(*v[3:])]})
|
||||
poses.append(pose)
|
||||
lines += ["", "frame %d {" % f, "\t" + " ".join("%.6f" % x for x in vals), "}"]
|
||||
return "\n".join(lines) + "\n", {"name": name, "frames": nframes, "rate": rate, "poses": poses}
|
||||
|
||||
|
||||
def generate(ctx):
|
||||
rng = ctx.rng(97)
|
||||
R = ref(ctx)
|
||||
text, info = mesh(rng)
|
||||
data = text.encode()
|
||||
info.update({"data": data, "assimp": R.assimp_soup(ctx, data, "md5mesh")})
|
||||
anims = []
|
||||
for name, nf, rate in (("idle", 4, 24), ("walk", 7, 30)):
|
||||
t, a = anim(rng, info["joints"], nf, rate, name)
|
||||
a["data"] = t.encode()
|
||||
anims.append(a)
|
||||
ctx.emit("md5", {"mesh": info, "anims": anims})
|
||||
@@ -0,0 +1,261 @@
|
||||
# MDL fixtures (tools/fixtures.py). Quake 1 ("IDPO" 6) and Half-Life 1 ("IDST" 10) models written here from the
|
||||
# Quake specs / studio.h layouts, with random data; references: assimp's triangle soup (frame 0 / bind pose:
|
||||
# positions, texture coordinates; for Quake from a copy without the skin group, which assimp 6 misreads) and this writer's own exact values:
|
||||
# quake: every frame's positions (CRC-32 of the f32 soup in our corner order), the skins through a test palette
|
||||
# (CRC-32 of the RGBA pixels), frame names;
|
||||
# halflife: bones (bind pose), body parts / meshes / triangle strips and fans, two textures with their own
|
||||
# palettes and a skin family, two sequences with run-length coded animation values (the values per frame
|
||||
# and bone, computed here).
|
||||
# tests/gen/mdl.luau { quake = { ... }, halflife = { ... } }
|
||||
import importlib.util, math, os, struct, zlib
|
||||
|
||||
INPUTS = ["tools/fixtures/_quake_ref.py"]
|
||||
|
||||
|
||||
def ref(ctx):
|
||||
spec = importlib.util.spec_from_file_location("_quake_ref", os.path.join(ctx.root, "tools", "fixtures", "_quake_ref.py"))
|
||||
m = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(m)
|
||||
return m
|
||||
|
||||
|
||||
def f32(x):
|
||||
return struct.unpack("<f", struct.pack("<f", x))[0]
|
||||
|
||||
|
||||
def palette(rng):
|
||||
return bytes(rng.randrange(256) for _ in range(768))
|
||||
|
||||
|
||||
def rgba(pix, pal):
|
||||
return b"".join(pal[i * 3:i * 3 + 3] + b"\xff" for i in pix)
|
||||
|
||||
|
||||
# ------------------------------------------------------------------------------------------------ Quake 1
|
||||
def quake(rng, pal, nverts=24, ntris=30, sw=32, sh=16, frames=("stand1", "stand2", "walk1", "walk2", "walk3"), group=("death1", "death2")):
|
||||
scale = tuple(f32(rng.uniform(0.05, 0.3)) for _ in range(3))
|
||||
origin = tuple(f32(rng.uniform(-20, 20)) for _ in range(3))
|
||||
nframes = len(frames) + (1 if group else 0)
|
||||
out = struct.pack("<4si3f3ff3fiiiiiiiif", b"IDPO", 6, *scale, *origin, 10.0, 0, 0, 0, 2, sw, sh, nverts, ntris, nframes, 0, 0, 1.0)
|
||||
skins = []
|
||||
s1 = bytes(rng.randrange(256) for _ in range(sw * sh))
|
||||
out += struct.pack("<i", 0) + s1
|
||||
skins.append(s1)
|
||||
s2 = [bytes(rng.randrange(256) for _ in range(sw * sh)) for _ in range(2)]
|
||||
out += struct.pack("<ii2f", 1, 2, 0.1, 0.2) + s2[0] + s2[1]
|
||||
skins.append(s2[0])
|
||||
st = [(rng.randrange(2), rng.randrange(sw // 2), rng.randrange(sh)) for _ in range(nverts)]
|
||||
for s in st:
|
||||
out += struct.pack("<3i", *s)
|
||||
tris = [(rng.randrange(2), tuple(rng.sample(range(nverts), 3))) for _ in range(ntris)]
|
||||
for front, v in tris:
|
||||
out += struct.pack("<4i", front, *v)
|
||||
allframes = []
|
||||
|
||||
def simple(name):
|
||||
vs = [(rng.randrange(256), rng.randrange(256), rng.randrange(256), rng.randrange(162)) for _ in range(nverts)]
|
||||
allframes.append((name, vs))
|
||||
return bytes(4) + bytes(4) + name.encode().ljust(16, b"\0") + b"".join(bytes(v) for v in vs)
|
||||
|
||||
for f in frames:
|
||||
out += struct.pack("<i", 0) + simple(f)
|
||||
if group:
|
||||
out += struct.pack("<ii", 1, len(group)) + bytes(8) + struct.pack("<%df" % len(group), *[0.1] * len(group))
|
||||
for f in group:
|
||||
out += simple(f)
|
||||
crcs = []
|
||||
for name, vs in allframes:
|
||||
soup = b""
|
||||
for front, v in tris:
|
||||
for c in (2, 1, 0):
|
||||
p = vs[v[c]]
|
||||
soup += struct.pack("<3f", *(p[k] * scale[k] + origin[k] for k in range(3)))
|
||||
crcs.append(zlib.crc32(soup))
|
||||
uv = []
|
||||
for front, v in tris:
|
||||
for c in (2, 1, 0):
|
||||
onseam, s, t = st[v[c]]
|
||||
if onseam and not front:
|
||||
s += sw / 2
|
||||
uv += [f32((s + 0.5) / sw), f32((t + 0.5) / sh)]
|
||||
# assimp 6 misreads skin groups (the intervals): its reference copy has the first skin only
|
||||
plain = bytearray(out[:84 + 4 + sw * sh] + out[84 + 4 + sw * sh + 16 + 2 * sw * sh:])
|
||||
struct.pack_into("<i", plain, 48, 1)
|
||||
return out, {"plain": bytes(plain), "crcs": crcs, "names": [n for n, _ in allframes], "skins": [zlib.crc32(rgba(s, pal)) for s in skins],
|
||||
"grey": zlib.crc32(b"".join(bytes([i, i, i, 255]) for i in skins[0])), "tris": ntris, "uv": uv}
|
||||
|
||||
|
||||
# ------------------------------------------------------------------------------------------------ Half-Life 1
|
||||
def angle_quat(x, y, z):
|
||||
sy, cy = math.sin(z / 2), math.cos(z / 2)
|
||||
sp, cp = math.sin(y / 2), math.cos(y / 2)
|
||||
sr, cr = math.sin(x / 2), math.cos(x / 2)
|
||||
return (sr * cp * cy - cr * sp * sy, cr * sp * cy + sr * cp * sy, cr * cp * sy - sr * sp * cy, cr * cp * cy + sr * sp * sy)
|
||||
|
||||
|
||||
def rle(values):
|
||||
# mstudioanimvalue runs: (valid, total) then `valid` values; a run repeats its last value for total - valid frames
|
||||
out, i = b"", 0
|
||||
while i < len(values):
|
||||
j = i + 1
|
||||
while j < len(values) and j - i < 4 and values[j] != values[j - 1]:
|
||||
j += 1
|
||||
run = values[i:j]
|
||||
k = j
|
||||
while k < len(values) and values[k] == run[-1] and k - i < 250:
|
||||
k += 1
|
||||
out += bytes([len(run), k - i]) + struct.pack("<%dh" % len(run), *run)
|
||||
i = k
|
||||
return out
|
||||
|
||||
|
||||
def halflife(rng):
|
||||
bones = [("root", -1, [0.0, 0.0, 10.0, 0.0, 0.0, 0.3]), ("spine", 0, [5.0, 0.0, 0.0, 0.2, 0.1, 0.0]),
|
||||
("head", 1, [0.0, 4.0, 1.0, 0.0, 0.5, -0.2])]
|
||||
scales = [f32(rng.uniform(0.001, 0.01)) for _ in range(6)]
|
||||
nb = len(bones)
|
||||
# geometry: verts in bone space
|
||||
nverts, nnorms = 12, 12
|
||||
verts = [tuple(f32(rng.uniform(-8, 8)) for _ in range(3)) for _ in range(nverts)]
|
||||
vbone = [rng.randrange(nb) for _ in range(nverts)]
|
||||
norms = []
|
||||
for _ in range(nnorms):
|
||||
v = [rng.uniform(-1, 1) for _ in range(3)]
|
||||
l = math.sqrt(sum(c * c for c in v))
|
||||
norms.append(tuple(f32(c / l) for c in v))
|
||||
nbone = [rng.randrange(nb) for _ in range(nnorms)]
|
||||
texs = [("skin_a.bmp", 16, 8), ("skin_b.bmp", 8, 8)]
|
||||
# two meshes: a strip of 5 and a fan of 4 (+ a strip of 3) per mesh, texels per corner
|
||||
def cmds(tw, th):
|
||||
out, corners = b"", []
|
||||
for kind, n in (("strip", 5), ("fan", 4), ("strip", 3)):
|
||||
vs = [(rng.randrange(nverts), rng.randrange(nnorms), rng.randrange(tw), rng.randrange(th)) for _ in range(n)]
|
||||
out += struct.pack("<h", n if kind == "strip" else -n) + b"".join(struct.pack("<4h", *v) for v in vs)
|
||||
corners.append((kind, vs))
|
||||
return out + struct.pack("<h", 0), corners
|
||||
meshes = [cmds(16, 8) + (0,), cmds(8, 8) + (1,)]
|
||||
seqs = [("idle", 10.0, 6), ("walk", 15.0, 9)]
|
||||
# anim values per sequence, bone, channel
|
||||
animvals = []
|
||||
for name, fps, nf in seqs:
|
||||
per = []
|
||||
for bi in range(nb):
|
||||
ch = []
|
||||
for k in range(6):
|
||||
if rng.random() < 0.3:
|
||||
ch.append(None) # offset 0: the bone default
|
||||
else:
|
||||
ch.append([rng.randrange(-300, 300) if rng.random() < 0.6 or f == 0 else None for f in range(nf)])
|
||||
for f in range(1, nf):
|
||||
if ch[-1][f] is None:
|
||||
ch[-1][f] = ch[-1][f - 1]
|
||||
per.append(ch)
|
||||
animvals.append(per)
|
||||
# --- layout
|
||||
hdr = 244
|
||||
o_bones = hdr
|
||||
o_seq = o_bones + 112 * nb
|
||||
o_anim = o_seq + 176 * len(seqs)
|
||||
anim_blobs, anim_offsets = b"", []
|
||||
for per in animvals:
|
||||
anim_offsets.append(o_anim + len(anim_blobs))
|
||||
table = bytearray(12 * nb)
|
||||
data = b""
|
||||
for bi, ch in enumerate(per):
|
||||
for k, vals in enumerate(ch):
|
||||
if vals is None:
|
||||
continue
|
||||
off = 12 * nb - 12 * bi + len(data) # from this bone's mstudioanim_t
|
||||
struct.pack_into("<H", table, bi * 12 + k * 2, off)
|
||||
data += rle(vals)
|
||||
anim_blobs += bytes(table) + data
|
||||
if len(anim_blobs) % 2:
|
||||
anim_blobs += b"\0"
|
||||
o_groups = o_anim + len(anim_blobs)
|
||||
o_parts = o_groups + 104
|
||||
o_models = o_parts + 76
|
||||
o_meshes = o_models + 112
|
||||
o_vinfo = o_meshes + 20 * len(meshes)
|
||||
o_ninfo = o_vinfo + nverts
|
||||
o_verts = (o_ninfo + nnorms + 3) // 4 * 4
|
||||
o_norms = o_verts + 12 * nverts
|
||||
o_cmds = o_norms + 12 * nnorms
|
||||
cmd_offsets, cmd_blob = [], b""
|
||||
for c, corners, tex in meshes:
|
||||
cmd_offsets.append(o_cmds + len(cmd_blob))
|
||||
cmd_blob += c
|
||||
o_tex = o_cmds + len(cmd_blob)
|
||||
o_skin = o_tex + 80 * len(texs)
|
||||
o_texdata = o_skin + 2 * 2 * 2 # 2 families x 2 refs
|
||||
tex_blob, tex_offsets, tex_pix = b"", [], []
|
||||
for name, w, h in texs:
|
||||
tex_offsets.append(o_texdata + len(tex_blob))
|
||||
pix = bytes(rng.randrange(256) for _ in range(w * h))
|
||||
pal = palette(rng)
|
||||
tex_blob += pix + pal
|
||||
tex_pix.append(zlib.crc32(rgba(pix, pal)))
|
||||
length = o_texdata + len(tex_blob)
|
||||
out = bytearray(length)
|
||||
struct.pack_into("<4si64si", out, 0, b"IDST", 10, b"test/model.mdl", length)
|
||||
struct.pack_into("<ii", out, 140, nb, o_bones)
|
||||
struct.pack_into("<ii", out, 164, len(seqs), o_seq)
|
||||
struct.pack_into("<iii", out, 180, len(texs), o_tex, o_texdata)
|
||||
struct.pack_into("<iii", out, 192, 2, 2, o_skin)
|
||||
struct.pack_into("<ii", out, 204, 1, o_parts)
|
||||
struct.pack_into("<ii", out, 172, 1, o_groups)
|
||||
struct.pack_into("<32s64sii", out, o_groups, b"default", b"", 0, 0)
|
||||
for i, (name, parent, value) in enumerate(bones):
|
||||
struct.pack_into("<32sii6i6f6f", out, o_bones + 112 * i, name.encode(), parent, 0, *([-1] * 6), *value, *scales)
|
||||
for i, (name, fps, nf) in enumerate(seqs):
|
||||
o = o_seq + 176 * i
|
||||
struct.pack_into("<32sf", out, o, name.encode(), fps)
|
||||
struct.pack_into("<i", out, o + 56, nf)
|
||||
struct.pack_into("<ii", out, o + 120, 1, anim_offsets[i])
|
||||
struct.pack_into("<i", out, o + 156, 0)
|
||||
out[o_anim:o_anim + len(anim_blobs)] = anim_blobs
|
||||
struct.pack_into("<64siii", out, o_parts, b"body", 1, 0, o_models)
|
||||
struct.pack_into("<64sif10i", out, o_models, b"body_ref", 0, 20.0, len(meshes), o_meshes, nverts, o_vinfo, o_verts, nnorms, o_ninfo, o_norms, 0, 0)
|
||||
for i, (c, corners, tex) in enumerate(meshes):
|
||||
ntris = sum(n - 2 for kind, vs in corners for n in [len(vs)])
|
||||
struct.pack_into("<5i", out, o_meshes + 20 * i, ntris, cmd_offsets[i], tex, 0, 0)
|
||||
out[o_vinfo:o_vinfo + nverts] = bytes(vbone)
|
||||
out[o_ninfo:o_ninfo + nnorms] = bytes(nbone)
|
||||
for i, v in enumerate(verts):
|
||||
struct.pack_into("<3f", out, o_verts + 12 * i, *v)
|
||||
for i, n in enumerate(norms):
|
||||
struct.pack_into("<3f", out, o_norms + 12 * i, *n)
|
||||
out[o_cmds:o_cmds + len(cmd_blob)] = cmd_blob
|
||||
for i, (name, w, h) in enumerate(texs):
|
||||
struct.pack_into("<64siiii", out, o_tex + 80 * i, name.encode(), 0, w, h, tex_offsets[i])
|
||||
# skin families: family 0 = (0, 1), family 1 = (1, 0)
|
||||
struct.pack_into("<4h", out, o_skin, 0, 1, 1, 0)
|
||||
out[o_texdata:] = tex_blob
|
||||
# expected animation values: bone default + value * scale
|
||||
expect = []
|
||||
for si, (name, fps, nf) in enumerate(seqs):
|
||||
per = []
|
||||
for bi, (bname, parent, value) in enumerate(bones):
|
||||
frames = []
|
||||
for f in range(nf):
|
||||
v = []
|
||||
for k in range(6):
|
||||
vals = animvals[si][bi][k]
|
||||
v.append(value[k] + (vals[f] if vals else 0) * scales[k])
|
||||
frames.append({"t": v[:3], "q": list(angle_quat(*v[3:]))})
|
||||
per.append(frames)
|
||||
expect.append({"name": name, "fps": fps, "frames": nf, "bones": per})
|
||||
ntris = [sum(len(vs) - 2 for kind, vs in corners) for c, corners, tex in meshes]
|
||||
return bytes(out), {"bones": [{"name": n, "parent": p + 1, "t": v[:3], "q": list(angle_quat(*v[3:]))} for n, p, v in bones],
|
||||
"sequences": expect, "textures": [{"name": n, "width": w, "height": h, "crc": tex_pix[i]} for i, (n, w, h) in enumerate(texs)],
|
||||
"tris": ntris}
|
||||
|
||||
|
||||
def generate(ctx):
|
||||
rng = ctx.rng(71)
|
||||
R = ref(ctx)
|
||||
pal = palette(rng)
|
||||
qdata, qinfo = quake(rng, pal)
|
||||
qinfo.update({"data": qdata, "palette": pal, "assimp": R.assimp_soup(ctx, qinfo.pop("plain"), "mdl")})
|
||||
hdata, hinfo = halflife(rng)
|
||||
hinfo.update({"data": hdata, "assimp": R.assimp_soup(ctx, hdata, "mdl")})
|
||||
ctx.emit("mdl", {"quake": qinfo, "halflife": hinfo})
|
||||
@@ -0,0 +1,201 @@
|
||||
# MPQ fixtures (tools/fixtures.py). StormLib (nix stormlib, through ctypes) writes the archives from random files:
|
||||
# header versions 1-4, every sector compression it offers (zlib, PKWARE implode, bzip2, LZMA, sparse + zlib /
|
||||
# bzip2), MPQ_FILE_IMPLODE files, single-unit files, encrypted files (plain and fix-key), sector CRCs, several
|
||||
# sector sizes, a (listfile) and (attributes); one archive behind a 1024-byte prefix, one without a listfile (files
|
||||
# named by block index), one with a Huffman (WAVE) sector. Raw PKWARE DCL streams from StormLib's SCompImplode
|
||||
# (binary and ASCII modes, 1 / 2 / 4 KB dictionaries) for codecs/compress/Explode.
|
||||
# tests/gen/mpq.luau { archives = { { name, data, version, files = { { name, size, crc } }, unnamed? } },
|
||||
# implode = { { name, data, size, crc } }, huffman = data }
|
||||
import ctypes, json, os, shutil, subprocess, tempfile, zlib
|
||||
|
||||
INPUTS = []
|
||||
|
||||
CODE = r"""
|
||||
import ctypes, json, os, sys, zlib
|
||||
args = json.loads(sys.stdin.read())
|
||||
lib = ctypes.CDLL(args["lib"])
|
||||
lib.SFileCreateArchive.argtypes = [ctypes.c_char_p, ctypes.c_uint32, ctypes.c_uint32, ctypes.POINTER(ctypes.c_void_p)]
|
||||
lib.SFileAddFileEx.argtypes = [ctypes.c_void_p, ctypes.c_char_p, ctypes.c_char_p, ctypes.c_uint32, ctypes.c_uint32, ctypes.c_uint32]
|
||||
lib.SFileCloseArchive.argtypes = [ctypes.c_void_p]
|
||||
lib.SFileSetMaxFileCount.argtypes = [ctypes.c_void_p, ctypes.c_uint32]
|
||||
lib.SCompImplode.argtypes = [ctypes.c_void_p, ctypes.POINTER(ctypes.c_int), ctypes.c_void_p, ctypes.c_int]
|
||||
lib.SCompImplode.restype = ctypes.c_int
|
||||
out = {}
|
||||
for a in args["archives"]:
|
||||
h = ctypes.c_void_p()
|
||||
path = a["path"].encode()
|
||||
if os.path.exists(path):
|
||||
os.remove(path)
|
||||
if not lib.SFileCreateArchive(path, a["create"], 64, ctypes.byref(h)):
|
||||
raise SystemExit("create failed: %s" % a["path"])
|
||||
for f in a["files"]:
|
||||
if not lib.SFileAddFileEx(h, f["src"].encode(), f["name"].encode(), f["flags"], f["comp"], f["comp"]):
|
||||
raise SystemExit("add failed: %s %s" % (f["name"], ctypes.get_errno()))
|
||||
lib.SFileCloseArchive(h)
|
||||
lib.SFileOpenArchive.argtypes = [ctypes.c_char_p, ctypes.c_uint32, ctypes.c_uint32, ctypes.POINTER(ctypes.c_void_p)]
|
||||
lib.SFileHasFile.argtypes = [ctypes.c_void_p, ctypes.c_char_p]
|
||||
present = {}
|
||||
for a in args["archives"]:
|
||||
h = ctypes.c_void_p()
|
||||
if not lib.SFileOpenArchive(a["path"].encode(), 0, 0x100, ctypes.byref(h)):
|
||||
raise SystemExit("open failed: %s" % a["path"])
|
||||
present[a["name"]] = [f["name"] for f in a["files"] if lib.SFileHasFile(h, f["name"].encode())]
|
||||
lib.SFileCloseArchive(h)
|
||||
res = []
|
||||
for s in args["implode"]:
|
||||
data = open(s["src"], "rb").read()
|
||||
buf = ctypes.create_string_buffer(len(data) * 2 + 64)
|
||||
n = ctypes.c_int(len(buf))
|
||||
src = ctypes.create_string_buffer(data, len(data))
|
||||
# SCompImplode always uses binary mode, dictionary by size; StormLib picks 4 KB for big inputs
|
||||
ok = lib.SCompImplode(buf, ctypes.byref(n), src, len(data))
|
||||
res.append({"name": s["name"], "data": buf.raw[:n.value].hex(), "size": len(data), "crc": zlib.crc32(data)})
|
||||
# pklib's implode() directly: ASCII (coded literals) and binary modes, every dictionary size
|
||||
READ = ctypes.CFUNCTYPE(ctypes.c_uint, ctypes.POINTER(ctypes.c_char), ctypes.POINTER(ctypes.c_uint), ctypes.c_void_p)
|
||||
WRITE = ctypes.CFUNCTYPE(None, ctypes.POINTER(ctypes.c_char), ctypes.POINTER(ctypes.c_uint), ctypes.c_void_p)
|
||||
lib.implode.argtypes = [READ, WRITE, ctypes.c_void_p, ctypes.c_void_p, ctypes.POINTER(ctypes.c_uint), ctypes.POINTER(ctypes.c_uint)]
|
||||
for s in args["modes"]:
|
||||
data = open(s["src"], "rb").read()
|
||||
state = {"pos": 0, "out": bytearray()}
|
||||
def rd(buf, size, param):
|
||||
n = min(size[0], len(data) - state["pos"])
|
||||
ctypes.memmove(buf, data[state["pos"]:state["pos"] + n], n)
|
||||
state["pos"] += n
|
||||
return n
|
||||
def wr(buf, size, param):
|
||||
state["out"] += ctypes.string_at(buf, size[0])
|
||||
rcb, wcb = READ(rd), WRITE(wr)
|
||||
work = ctypes.create_string_buffer(65536)
|
||||
lib.implode(rcb, wcb, work, None, ctypes.byref(ctypes.c_uint(s["type"])), ctypes.byref(ctypes.c_uint(s["dsize"])))
|
||||
res.append({"name": s["name"], "data": bytes(state["out"]).hex(), "size": len(data), "crc": zlib.crc32(data)})
|
||||
print(json.dumps({"implode": res, "present": present}))
|
||||
"""
|
||||
|
||||
IMPLODE, COMPRESS, ENCRYPTED, FIX_KEY, SINGLE, SECTOR_CRC, REPLACE = 0x100, 0x200, 0x10000, 0x20000, 0x1000000, 0x4000000, 0x80000000
|
||||
ZLIB, PKWARE, BZIP2, SPARSE, LZMA, HUFF, ADPCM_MONO = 0x02, 0x08, 0x10, 0x20, 0x12, 0x01, 0x40
|
||||
|
||||
|
||||
# an independent MPQ crypt (the format description's algorithm) to delete the (listfile) hash entry of "nolist"
|
||||
def crypt_table():
|
||||
t, seed = [0] * 0x500, 0x00100001
|
||||
for i1 in range(256):
|
||||
i2 = i1
|
||||
for _ in range(5):
|
||||
seed = (seed * 125 + 3) % 0x2AAAAB
|
||||
t1 = (seed & 0xFFFF) << 16
|
||||
seed = (seed * 125 + 3) % 0x2AAAAB
|
||||
t[i2] = t1 | (seed & 0xFFFF)
|
||||
i2 += 0x100
|
||||
return t
|
||||
|
||||
|
||||
CT = crypt_table()
|
||||
M = 0xFFFFFFFF
|
||||
|
||||
|
||||
def mpq_hash(s, kind):
|
||||
s1, s2 = 0x7FED7FED, 0xEEEEEEEE
|
||||
for c in s.upper().replace("/", "\\").encode():
|
||||
s1 = CT[kind * 0x100 + c] ^ ((s1 + s2) & M)
|
||||
s2 = (c + s1 + s2 + (s2 << 5) + 3) & M
|
||||
return s1
|
||||
|
||||
|
||||
def crypt(words, key, decrypt):
|
||||
s2, out = 0xEEEEEEEE, []
|
||||
for v in words:
|
||||
s2 = (s2 + CT[0x400 + (key & 0xFF)]) & M
|
||||
ch = v ^ ((key + s2) & M)
|
||||
key = ((((~key) << 0x15) + 0x11111111) & M) | (key >> 0x0B)
|
||||
s2 = ((ch if decrypt else v) + s2 + (s2 << 5) + 3) & M
|
||||
out.append(ch)
|
||||
return out
|
||||
|
||||
|
||||
def drop_listfile(data):
|
||||
import struct
|
||||
hash_pos, n = struct.unpack_from("<I", data, 16)[0], struct.unpack_from("<I", data, 24)[0]
|
||||
words = list(struct.unpack_from("<%dI" % (n * 4), data, hash_pos))
|
||||
key = mpq_hash("(hash table)", 3)
|
||||
plain = crypt(words, key, True)
|
||||
a, b = mpq_hash("(listfile)", 1), mpq_hash("(listfile)", 2)
|
||||
for i in range(n):
|
||||
if plain[i * 4] == a and plain[i * 4 + 1] == b:
|
||||
plain[i * 4 + 3] = 0xFFFFFFFE
|
||||
enc = crypt(plain, key, False)
|
||||
out = bytearray(data)
|
||||
struct.pack_into("<%dI" % (n * 4), out, hash_pos, *enc)
|
||||
return bytes(out)
|
||||
|
||||
|
||||
def lib_path():
|
||||
out = subprocess.run(["nix", "build", "--no-link", "--print-out-paths", "nixpkgs#stormlib"], capture_output=True, check=True).stdout.decode().split()[0]
|
||||
return os.path.join(out, "lib", "libstorm.so")
|
||||
|
||||
|
||||
def generate(ctx):
|
||||
rng = ctx.rng(41)
|
||||
tmp = tempfile.mkdtemp(prefix="formats-mpq-")
|
||||
try:
|
||||
def file(name, data):
|
||||
p = os.path.join(tmp, "src_" + str(abs(hash(name)) % 10 ** 9) + "_" + str(len(data)))
|
||||
open(p, "wb").write(data)
|
||||
return p
|
||||
text = b"".join(b"line %d of a text file with some repetition\n" % i for i in range(400))
|
||||
sparse = bytes(3000) + rng.randbytes(100) + bytes(9000)
|
||||
noise = rng.randbytes(9000)
|
||||
content = [
|
||||
("units\\human\\footman.txt", text, COMPRESS, ZLIB),
|
||||
("units\\orc\\grunt.txt", text, COMPRESS, PKWARE),
|
||||
("data\\bz.dat", text + noise, COMPRESS, BZIP2),
|
||||
("data\\lzma.dat", text, COMPRESS, LZMA),
|
||||
("data\\sparse.dat", sparse, COMPRESS, SPARSE | ZLIB),
|
||||
("data\\sparsebz.dat", sparse, COMPRESS, SPARSE | BZIP2),
|
||||
("data\\noise.bin", noise, COMPRESS, ZLIB),
|
||||
("old\\imploded.txt", text, IMPLODE, PKWARE),
|
||||
("single\\unit.txt", text, COMPRESS | SINGLE, ZLIB),
|
||||
("single\\stored.bin", noise[:777], SINGLE, 0),
|
||||
("stored\\plain.bin", noise, 0, 0),
|
||||
("secret\\enc.txt", text, COMPRESS | ENCRYPTED, ZLIB),
|
||||
("secret\\fixkey.txt", text, COMPRESS | ENCRYPTED | FIX_KEY, ZLIB),
|
||||
("secret\\stored.bin", noise, ENCRYPTED, 0),
|
||||
("secret\\single.txt", text, COMPRESS | ENCRYPTED | SINGLE, ZLIB),
|
||||
("crc\\sectors.txt", text, COMPRESS | SECTOR_CRC, ZLIB),
|
||||
("empty.txt", b"", COMPRESS, ZLIB),
|
||||
("tiny.txt", b"x", COMPRESS, ZLIB),
|
||||
]
|
||||
specs = []
|
||||
for name, create, sel in [("v1", 0x00100000 | 0x00200000, None), ("v2", 0x01100000, None), ("v3", 0x02100000, None),
|
||||
("v4", 0x03100000, None), ("nolist", 0, 6), ("v1-basic", 0x00100000, 3)]:
|
||||
files = content if sel is None else content[:sel]
|
||||
if name.startswith("v3") or name.startswith("v4"):
|
||||
files = [f for f in files if not (f[2] & IMPLODE)]
|
||||
specs.append({"name": name, "path": os.path.join(tmp, name + ".mpq"), "create": create,
|
||||
"files": [{"name": n, "src": file(n, d), "flags": fl | REPLACE, "comp": c} for n, d, fl, c in files],
|
||||
"want": files})
|
||||
# a WAVE-style Huffman sector (Huffman + ADPCM is what Blizzard uses for .wav)
|
||||
specs.append({"name": "huffman", "path": os.path.join(tmp, "huffman.mpq"), "create": 0x00100000,
|
||||
"files": [{"name": "sound\\a.wav", "src": file("wav", text), "flags": COMPRESS | REPLACE, "comp": HUFF | ZLIB}],
|
||||
"want": [("sound\\a.wav", text, COMPRESS, HUFF | ZLIB)]})
|
||||
imp = [{"name": "text", "src": file("i1", text)}, {"name": "noise", "src": file("i2", noise[:5000])},
|
||||
{"name": "small", "src": file("i3", b"abcabcabcabcabcabc")}, {"name": "zeros", "src": file("i4", bytes(20000))}]
|
||||
modes = [{"name": "ascii-%d" % d, "src": file("m1", text), "type": 1, "dsize": d} for d in (1024, 2048, 4096)]
|
||||
modes += [{"name": "binary-%d" % d, "src": file("m2", text + noise[:3000]), "type": 0, "dsize": d} for d in (1024, 2048)]
|
||||
modes += [{"name": "ascii-noise", "src": file("m3", noise[:4000]), "type": 1, "dsize": 4096}]
|
||||
send = [{k: v for k, v in s.items() if k != "want"} for s in specs]
|
||||
res = json.loads(ctx.python([], CODE, input=json.dumps({"lib": lib_path(), "archives": send, "implode": imp, "modes": modes}).encode()))
|
||||
present = res["present"]
|
||||
res = res["implode"]
|
||||
archives = []
|
||||
for s in specs:
|
||||
data = open(s["path"], "rb").read()
|
||||
if s["name"] == "nolist":
|
||||
data = drop_listfile(data)
|
||||
if s["name"] == "v1-basic":
|
||||
data = b"\x7f" * 1024 + data # a prefixed archive (installer stub): the header at a 512-byte boundary
|
||||
archives.append({"name": s["name"], "data": data, "unnamed": s["name"] == "nolist",
|
||||
"files": [{"name": n, "size": len(d), "crc": zlib.crc32(d), "huffman": bool(c & HUFF)} for n, d, fl, c in s["want"] if n in present[s["name"]]]})
|
||||
implode = [{"name": r["name"], "data": bytes.fromhex(r["data"]), "size": r["size"], "crc": r["crc"]} for r in res]
|
||||
finally:
|
||||
shutil.rmtree(tmp)
|
||||
ctx.emit("mpq", {"archives": archives, "implode": implode})
|
||||
@@ -0,0 +1,122 @@
|
||||
# Valve SMD fixtures (tools/fixtures.py): SMD files written here (a skeleton of random bones, triangles with Source
|
||||
# links / GoldSrc parent-only vertices, several materials, a multi-frame skeleton, comments, quoted names; an
|
||||
# animation-only SMD); references: assimp's triangle soup (positions and texture coordinates per material mesh)
|
||||
# and the writer's own values (bind pose TRS, per-vertex weights, frame poses); our encoder's output
|
||||
# (tools/fixtures/_smd_encode.luau) read back by assimp (vertex / face counts, bounds).
|
||||
# tests/gen/smd_src.luau { { name, data } }
|
||||
# tests/gen/smd.luau { cases = { { name, data, bones, frames, tris, materials, verts, assimp } }, ours = { [name] = assimp info } }
|
||||
import importlib.util, json, math, os, shutil, struct, subprocess, tempfile
|
||||
|
||||
INPUTS = ["tools/fixtures/_quake_ref.py", "tools/fixtures/_smd_encode.luau", "src/Formats/model/smd"]
|
||||
|
||||
|
||||
def mod(ctx, name):
|
||||
spec = importlib.util.spec_from_file_location(name, os.path.join(ctx.root, "tools", "fixtures", name + ".py"))
|
||||
m = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(m)
|
||||
return m
|
||||
|
||||
|
||||
def angle_quat(x, y, z):
|
||||
sy, cy = math.sin(z / 2), math.cos(z / 2)
|
||||
sp, cp = math.sin(y / 2), math.cos(y / 2)
|
||||
sr, cr = math.sin(x / 2), math.cos(x / 2)
|
||||
return [sr * cp * cy - cr * sp * sy, cr * sp * cy + sr * cp * sy, cr * cp * sy - sr * sp * cy, cr * cp * cy + sr * sp * sy]
|
||||
|
||||
|
||||
def r6(v):
|
||||
return float("%.6f" % v)
|
||||
|
||||
|
||||
def smd(rng, nbones, nframes, ntris, materials, links=True, anim_only=False):
|
||||
lines = ["// written by tools/fixtures/smd.py", "version 1", "nodes"]
|
||||
bones = []
|
||||
for i in range(nbones):
|
||||
parent = -1 if i == 0 else rng.randrange(i)
|
||||
bones.append({"name": "bone %d" % i if i % 2 else "bone_%d" % i, "parent": parent + 1})
|
||||
lines.append('%d "%s" %d' % (i, bones[-1]["name"], parent))
|
||||
lines.append("end")
|
||||
lines.append("skeleton")
|
||||
frames = []
|
||||
for f in range(nframes):
|
||||
lines.append("time %d" % f)
|
||||
pose = []
|
||||
for i in range(nbones):
|
||||
v = [r6(rng.uniform(-5, 5)) for _ in range(3)] + [r6(rng.uniform(-math.pi, math.pi)) for _ in range(3)]
|
||||
lines.append("%d %s" % (i, " ".join("%.6f" % x for x in v)))
|
||||
pose.append({"t": v[:3], "q": angle_quat(*v[3:])})
|
||||
frames.append(pose)
|
||||
lines.append("end")
|
||||
tris = []
|
||||
if not anim_only:
|
||||
lines.append("triangles")
|
||||
for t in range(ntris):
|
||||
mat = materials[t % len(materials)]
|
||||
lines.append(mat)
|
||||
corners = []
|
||||
for c in range(3):
|
||||
parent = rng.randrange(nbones)
|
||||
p = [r6(rng.uniform(-20, 20)) for _ in range(3)]
|
||||
n = [rng.uniform(-1, 1) for _ in range(3)]
|
||||
ln = math.sqrt(sum(x * x for x in n))
|
||||
n = [r6(x / ln) for x in n]
|
||||
uv = [r6(rng.random()), r6(rng.random())]
|
||||
s = "%d %s" % (parent, " ".join("%.6f" % x for x in p + n + uv))
|
||||
weights = {parent: 1.0}
|
||||
if links and rng.random() < 0.7:
|
||||
k = rng.randrange(1, 3)
|
||||
picks = rng.sample(range(nbones), min(k, nbones))
|
||||
ws = [r6(rng.uniform(0.1, 0.45)) for _ in picks]
|
||||
s += " %d %s" % (len(picks), " ".join("%d %.6f" % (b, w) for b, w in zip(picks, ws)))
|
||||
weights = {}
|
||||
for b, w in zip(picks, ws):
|
||||
weights[b] = weights.get(b, 0) + w
|
||||
rest = 1 - sum(ws)
|
||||
if rest > 0.001:
|
||||
weights[parent] = weights.get(parent, 0) + rest
|
||||
lines.append(s)
|
||||
corners.append({"p": p, "n": n, "uv": uv, "w": [[b, w] for b, w in sorted(weights.items(), key=lambda x: -x[1])]})
|
||||
tris.append({"material": mat, "corners": corners})
|
||||
lines.append("end")
|
||||
return "\r\n".join(lines) + "\r\n", {"bones": bones, "frames": frames, "tris": tris}
|
||||
|
||||
|
||||
def assimp_info(ctx, data, Q):
|
||||
tmp = tempfile.mkdtemp(prefix="formats-smd-")
|
||||
try:
|
||||
p = os.path.join(tmp, "in.smd")
|
||||
open(p, "wb").write(data)
|
||||
try:
|
||||
txt = ctx.nix("assimp", ["assimp", "info", p]).decode("utf-8", "replace")
|
||||
except subprocess.CalledProcessError:
|
||||
return {"failed": True}
|
||||
finally:
|
||||
shutil.rmtree(tmp)
|
||||
import re
|
||||
def num(label):
|
||||
m = re.search(r"^" + label + r":\s+(\d+)", txt, re.M)
|
||||
return int(m.group(1)) if m else -1
|
||||
return {"faces": num("Faces"), "bones": num("Bones"), "animations": num("Animations")}
|
||||
|
||||
|
||||
def generate(ctx):
|
||||
rng = ctx.rng(83)
|
||||
Q = mod(ctx, "_quake_ref")
|
||||
specs = [("source", 5, 3, 12, ["skin.bmp", "metal.vtf"], True, False), ("goldsrc", 3, 1, 8, ["chrome.bmp"], False, False),
|
||||
("animation", 4, 6, 0, [], True, True)]
|
||||
cases, src = [], []
|
||||
for name, nb, nf, nt, mats, links, anim in specs:
|
||||
text, info = smd(rng, nb, nf, nt, mats, links, anim)
|
||||
data = text.encode()
|
||||
src.append({"name": name, "data": data})
|
||||
info.update({"name": name, "data": data, "assimp": Q.assimp_soup(ctx, data, "smd") if not anim else {"failed": True},
|
||||
"materials": mats})
|
||||
cases.append(info)
|
||||
ctx.emit("smd_src", src)
|
||||
import importlib
|
||||
ours = {}
|
||||
m = mod(ctx, "_model_ref")
|
||||
for k, b in m.luau_encode(ctx, "tools/fixtures/_smd_encode.luau").items():
|
||||
ours[k] = assimp_info(ctx, b, Q)
|
||||
ours[k]["soup"] = Q.assimp_soup(ctx, b, "smd") if not k.endswith("-anim") else {"failed": True}
|
||||
ctx.emit("smd", {"cases": cases, "ours": ours})
|
||||
@@ -0,0 +1,73 @@
|
||||
# PlayStation TIM fixtures (tools/fixtures.py): TIM files written here (4-bit with two CLUTs, 8-bit, 15-bit direct
|
||||
# with STP bits and 0x0000 transparency, 24-bit with an odd width, VRAM positions) decoded by ImageMagick's TIM
|
||||
# reader (nix imagemagick, RGB: it ignores alpha) -> CRC-32 of the RGB bytes per CLUT row, plus the transparent
|
||||
# pixel count (colour 0x0000) computed here.
|
||||
# ImageMagick cannot read several CLUT rows: the 2-row file's reference is a copy with row 0 only.
|
||||
# tests/gen/tim.luau { { name, data, width, height, bpp, rgb = { crc of CLUT row 0 }, transparent, cluts } }
|
||||
import os, shutil, struct, tempfile, zlib
|
||||
|
||||
|
||||
def tim(rng, bpp, w, h, cluts=1):
|
||||
flags = {4: 0, 8: 1, 16: 2, 24: 3}[bpp]
|
||||
out = b""
|
||||
colours = []
|
||||
if bpp <= 8:
|
||||
n = 16 if bpp == 4 else 256
|
||||
flags |= 8
|
||||
for _ in range(cluts):
|
||||
row = [rng.randrange(65536) for _ in range(n)]
|
||||
row[0] = 0
|
||||
row[1] = 0x8000
|
||||
colours.append(row)
|
||||
out += struct.pack("<IHHHH", 12 + n * 2 * cluts, 16, 480, n, cluts) + b"".join(struct.pack("<H", c) for r in colours for c in r)
|
||||
if bpp == 4:
|
||||
iw = (w + 3) // 4
|
||||
elif bpp == 8:
|
||||
iw = (w + 1) // 2
|
||||
elif bpp == 16:
|
||||
iw = w
|
||||
else:
|
||||
iw = (w * 3 + 1) // 2
|
||||
stride = iw * 2
|
||||
rows = []
|
||||
transparent = 0
|
||||
for y in range(h):
|
||||
if bpp == 4:
|
||||
idx = [rng.randrange(16) for _ in range(iw * 4)]
|
||||
transparent += sum(1 for i in idx[:w] if colours[0][i] == 0)
|
||||
rows.append(bytes(idx[2 * k] | (idx[2 * k + 1] << 4) for k in range(iw * 2)))
|
||||
elif bpp == 8:
|
||||
idx = [rng.randrange(256) for _ in range(iw * 2)]
|
||||
transparent += sum(1 for i in idx[:w] if colours[0][i] == 0)
|
||||
rows.append(bytes(idx))
|
||||
elif bpp == 16:
|
||||
cs = [rng.choice([0, 0x8000, rng.randrange(65536)]) if rng.random() < 0.2 else rng.randrange(65536) for _ in range(iw)]
|
||||
transparent += sum(1 for c in cs if c == 0)
|
||||
rows.append(b"".join(struct.pack("<H", c) for c in cs))
|
||||
else:
|
||||
rows.append(bytes(rng.randrange(256) for _ in range(stride)))
|
||||
image = struct.pack("<IHHHH", 12 + stride * h, 320, 0, iw, h) + b"".join(rows)
|
||||
data = struct.pack("<II", 0x10, flags) + out + image
|
||||
# ImageMagick reads one CLUT row only: its reference copy keeps row 0
|
||||
ref = data
|
||||
if bpp <= 8 and cluts > 1:
|
||||
n = 16 if bpp == 4 else 256
|
||||
ref = struct.pack("<II", 0x10, flags) + struct.pack("<IHHHH", 12 + n * 2, 16, 480, n, 1) + b"".join(struct.pack("<H", c) for c in colours[0]) + image
|
||||
return data, ref, transparent, (iw * 4 if bpp == 4 else iw * 2 if bpp == 8 else iw if bpp == 16 else (iw * 2) // 3)
|
||||
|
||||
|
||||
def generate(ctx):
|
||||
rng = ctx.rng(111)
|
||||
specs = [("4bit", 4, 16, 6, 2), ("8bit", 8, 10, 7, 1), ("16bit", 16, 9, 5, 1), ("24bit", 24, 5, 4, 1), ("4bit-odd", 4, 13, 3, 1)]
|
||||
out = []
|
||||
tmp = tempfile.mkdtemp(prefix="formats-tim-")
|
||||
try:
|
||||
for name, bpp, w, h, cluts in specs:
|
||||
data, ref, transparent, width = tim(rng, bpp, w, h, cluts)
|
||||
p = os.path.join(tmp, name + ".tim")
|
||||
open(p, "wb").write(ref)
|
||||
rgb = [zlib.crc32(ctx.nix("imagemagick", ["magick", "TIM:" + p, "rgb:-"]))]
|
||||
out.append({"name": name, "data": data, "bpp": bpp, "width": width, "height": h, "rgb": rgb, "transparent": transparent, "cluts": cluts})
|
||||
finally:
|
||||
shutil.rmtree(tmp)
|
||||
ctx.emit("tim", out)
|
||||
@@ -0,0 +1,122 @@
|
||||
# Valve VPK fixtures (tools/fixtures.py). References:
|
||||
# - Python's vpk package (nix python3Packages.vpk) writes version 1 and 2 directory files (data embedded, MD5
|
||||
# section) from a folder of random files; its reader lists them (names, sizes, CRC-32s);
|
||||
# - a multi-part archive written here from the VDC layout: a pak01_dir.vpk whose entries live in pak01_000.vpk /
|
||||
# pak01_001.vpk, with preload bytes in the tree, plus an embedded one;
|
||||
# - our encoder's output (tools/fixtures/_vpk_encode.luau through the luau CLI) read back by the vpk package, with
|
||||
# version 2's MD5 verify(): verdicts in `ours`.
|
||||
# tests/gen/vpk_src.luau { { name, data } } (the files)
|
||||
# tests/gen/vpk.luau { cases = { { name, data, version, entries = { { name, size, crc } } } }, multi = { dir,
|
||||
# parts = { [name] = data }, entries }, ours = { v1 = { ok, entries }, v2 = ... } }
|
||||
import importlib.util, json, os, shutil, struct, tempfile, zlib
|
||||
|
||||
INPUTS = ["src/Formats/archive/vpk", "tools/fixtures/_vpk_encode.luau"]
|
||||
|
||||
|
||||
def luau_encode(ctx, script):
|
||||
spec = importlib.util.spec_from_file_location("_model_ref", os.path.join(ctx.root, "tools", "fixtures", "_model_ref.py"))
|
||||
m = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(m)
|
||||
return m.luau_encode(ctx, script)
|
||||
|
||||
READ = r"""
|
||||
import json, sys, vpk, zlib
|
||||
out = {}
|
||||
for name, path in json.loads(sys.stdin.read()).items():
|
||||
p = vpk.open(path)
|
||||
ents = []
|
||||
for f in sorted(p):
|
||||
d = p.get_file(f).read()
|
||||
ents.append({"name": f, "size": len(d), "crc": zlib.crc32(d)})
|
||||
ok = True
|
||||
if p.version == 2:
|
||||
try:
|
||||
ok = bool(p.verify())
|
||||
except Exception as e:
|
||||
ok = False
|
||||
out[name] = {"version": p.version, "entries": ents, "ok": ok}
|
||||
print(json.dumps(out))
|
||||
"""
|
||||
|
||||
WRITE = r"""
|
||||
import json, sys, vpk
|
||||
args = json.loads(sys.stdin.read())
|
||||
n = vpk.new(args["src"])
|
||||
n.version = args["version"]
|
||||
n.save(args["out"])
|
||||
"""
|
||||
|
||||
|
||||
def files(rng):
|
||||
out = [("scripts/game.txt", b"\"game\" { }\n"), ("materials/brick/wall01.vmt", b"LightmappedGeneric { }"),
|
||||
("materials/brick/wall01.vtf", rng.randbytes(3000)), ("models/props/crate.mdl", rng.randbytes(2048)),
|
||||
("models/props/crate.vvd", rng.randbytes(777)), ("readme.txt", b"root file"), ("sound/empty.wav", b""),
|
||||
("maps/de_test.bsp", rng.randbytes(5000))]
|
||||
return out
|
||||
|
||||
|
||||
def multi(rng):
|
||||
# entries: (path, ext, name, preload, archive index, data)
|
||||
ents = [("materials", "vmt", "a", b"pre", 0, b"material a body"), ("materials", "vmt", "b", b"", 1, rng.randbytes(500)),
|
||||
("models", "mdl", "c", b"\x01\x02", 0, rng.randbytes(300)), (" ", "txt", "root", b"", 0x7fff, b"embedded"),
|
||||
("sound", "wav", "d", b"only preload", 1, b"")]
|
||||
parts = {0: bytearray(), 1: bytearray()}
|
||||
embedded = bytearray()
|
||||
tree = bytearray()
|
||||
exts = []
|
||||
for e in ents:
|
||||
if e[1] not in exts:
|
||||
exts.append(e[1])
|
||||
for ext in exts:
|
||||
tree += ext.encode() + b"\0"
|
||||
paths = []
|
||||
for e in ents:
|
||||
if e[1] == ext and e[0] not in paths:
|
||||
paths.append(e[0])
|
||||
for path in paths:
|
||||
tree += path.encode() + b"\0"
|
||||
for (p, x, name, pre, idx, data) in ents:
|
||||
if p == path and x == ext:
|
||||
target = embedded if idx == 0x7fff else parts[idx]
|
||||
off = len(target)
|
||||
target += data
|
||||
tree += name.encode() + b"\0" + struct.pack("<IHHIIH", zlib.crc32(pre + data), len(pre), idx, off, len(data), 0xffff) + pre
|
||||
tree += b"\0"
|
||||
tree += b"\0"
|
||||
tree += b"\0"
|
||||
d = struct.pack("<III", 0x55aa1234, 1, len(tree)) + bytes(tree) + bytes(embedded)
|
||||
entries = [{"name": ("" if p == " " else p + "/") + n + "." + x, "size": len(pre) + len(data), "crc": zlib.crc32(pre + data)} for (p, x, n, pre, i, data) in ents]
|
||||
return {"dir": d, "parts": {"pak01_000.vpk": bytes(parts[0]), "pak01_001.vpk": bytes(parts[1])}, "entries": entries}
|
||||
|
||||
|
||||
def generate(ctx):
|
||||
rng = ctx.rng(31)
|
||||
fs = files(rng)
|
||||
tmp = tempfile.mkdtemp(prefix="formats-vpk-")
|
||||
try:
|
||||
src = os.path.join(tmp, "src")
|
||||
for name, data in fs:
|
||||
p = os.path.join(src, name)
|
||||
os.makedirs(os.path.dirname(p), exist_ok=True)
|
||||
open(p, "wb").write(data)
|
||||
paths = {}
|
||||
for v in (1, 2):
|
||||
out = os.path.join(tmp, "v%d_dir.vpk" % v)
|
||||
ctx.python(["vpk"], WRITE, input=json.dumps({"src": src, "version": v, "out": out}).encode())
|
||||
paths["v%d" % v] = out
|
||||
ctx.emit("vpk_src", [{"name": n, "data": d} for n, d in fs])
|
||||
ours = luau_encode(ctx, "tools/fixtures/_vpk_encode.luau")
|
||||
for k, b in ours.items():
|
||||
p = os.path.join(tmp, "ours_" + k + "_dir.vpk")
|
||||
open(p, "wb").write(b)
|
||||
paths["ours_" + k] = p
|
||||
ref = json.loads(ctx.python(["vpk"], READ, input=json.dumps(paths).encode()))
|
||||
cases = []
|
||||
for v in (1, 2):
|
||||
k = "v%d" % v
|
||||
cases.append({"name": "python-" + k, "version": v, "data": open(paths[k], "rb").read(), "entries": ref[k]["entries"]})
|
||||
verdicts = {k: {"ok": ref["ours_" + k]["ok"], "version": ref["ours_" + k]["version"], "entries": ref["ours_" + k]["entries"]} for k in ours}
|
||||
finally:
|
||||
shutil.rmtree(tmp)
|
||||
want = sorted([{"name": n, "size": len(d), "crc": zlib.crc32(d)} for n, d in fs], key=lambda e: e["name"])
|
||||
ctx.emit("vpk", {"cases": cases, "multi": multi(rng), "ours": verdicts, "want": want})
|
||||
@@ -0,0 +1,102 @@
|
||||
# Valve VTF fixtures (tools/fixtures.py). srctools (nix python3Packages.srctools: a VTF reader / writer with
|
||||
# libsquish for DXT) writes VTFs of random pixels in every texel format it supports, in versions 7.2 / 7.4 / 7.5,
|
||||
# with mips and several frames; its reader decodes them back -> the RGBA of frame 0, mip 0 (and the last frame) as
|
||||
# reference. Formats whose conversion differs from the DXT rule (srctools / libsquish round 5 / 6-bit endpoints
|
||||
# differently) are compared within a tolerance.
|
||||
# tests/gen/vtf.luau { { name, data, width, height, frames, version, fmt, rgba, last?, tol } }
|
||||
import json
|
||||
|
||||
CODE = r"""
|
||||
import io, json, random, sys
|
||||
import srctools.vtf as V
|
||||
args = json.loads(sys.stdin.read())
|
||||
rng = random.Random(args["seed"])
|
||||
out = []
|
||||
FMTS = ["RGBA8888", "ABGR8888", "RGB888", "BGR888", "RGB565", "I8", "IA88", "A8", "RGB888_BLUESCREEN", "BGR888_BLUESCREEN",
|
||||
"ARGB8888", "BGRA8888", "DXT1", "DXT3", "DXT5", "BGRX8888", "BGR565", "BGRX5551", "BGRA4444", "DXT1_ONEBITALPHA",
|
||||
"BGRA5551", "UV88", "UVWQ8888", "RGBA16161616F", "RGBA16161616", "UVLX8888", "ATI1N", "ATI2N"]
|
||||
for i, name in enumerate(FMTS):
|
||||
fmt = V.ImageFormats[name]
|
||||
version = [(7, 2), (7, 4), (7, 5)][i % 3]
|
||||
w, h = [(16, 8), (8, 8), (4, 16)][i % 3] if not name.startswith(("DXT", "ATI")) else (16, 8)
|
||||
frames = 2 if i % 4 == 0 else 1
|
||||
try:
|
||||
vtf = V.VTF(w, h, version, fmt=fmt, frames=frames)
|
||||
for f in range(frames):
|
||||
px = bytes(rng.randrange(256) for _ in range(w * h * 4))
|
||||
if "BLUESCREEN" in name:
|
||||
px = bytearray(px)
|
||||
for k in range(0, len(px), 16):
|
||||
px[k:k + 4] = b"\x00\x00\xff\xff"
|
||||
px = bytes(px)
|
||||
vtf.get(frame=f).copy_from(px)
|
||||
b = io.BytesIO()
|
||||
vtf.save(b)
|
||||
data = b.getvalue()
|
||||
back = V.VTF.read(io.BytesIO(data))
|
||||
back.load()
|
||||
rgba = bytes(back.get(frame=0)._data)
|
||||
e = {"name": name, "data": data.hex(), "width": w, "height": h, "frames": frames, "version": "%d.%d" % version, "rgba": rgba.hex()}
|
||||
if frames > 1:
|
||||
e["last"] = bytes(back.get(frame=frames - 1)._data).hex()
|
||||
out.append(e)
|
||||
except Exception as ex:
|
||||
out.append({"name": name, "failed": repr(ex)})
|
||||
print(json.dumps(out))
|
||||
"""
|
||||
|
||||
# codecs/image/Texel rescales 5 / 6-bit fields with rounding (round(v * 255 / 31)); srctools replicates bits
|
||||
# (v << 3 | v >> 2): within 1
|
||||
TOL = {"RGB565": 1, "BGR565": 1, "BGRX5551": 1, "BGRA5551": 1, "DXT1": 8, "DXT3": 8, "DXT5": 8, "DXT1_ONEBITALPHA": 8, "ATI1N": 2, "ATI2N": 2, "RGBA16161616F": 1, "RGBA16161616": 1}
|
||||
|
||||
|
||||
def own(rng):
|
||||
# 7.2 files written here for the formats srctools cannot write (one mip, no thumbnail); expected RGBA by the
|
||||
# documented rules: halves / floats clamped to 0..1 and rounded, 16-bit integers (v + 128) // 257
|
||||
import struct, math
|
||||
out = []
|
||||
w, h = 4, 4
|
||||
def header(fmt):
|
||||
hd = bytearray(80)
|
||||
struct.pack_into("<4sIIIHHIHH", hd, 0, b"VTF\0", 7, 2, 80, w, h, 0, 1, 0)
|
||||
struct.pack_into("<f", hd, 48, 1.0)
|
||||
struct.pack_into("<iBiBBH", hd, 52, fmt, 1, -1, 0, 0, 1)
|
||||
return bytes(hd)
|
||||
def c8(f):
|
||||
return 0 if f != f or f <= 0 else 255 if f >= 1 else math.floor(f * 255 + 0.5)
|
||||
for name, fmt, kind, ch in (("RGBA16161616F", 24, "e", 4), ("RGBA16161616", 25, "H", 4), ("R32F", 27, "f", 1),
|
||||
("RGB323232F", 28, "f", 3), ("RGBA32323232F", 29, "f", 4)):
|
||||
vals, rgba = [], bytearray()
|
||||
for i in range(w * h):
|
||||
px = [0, 0, 0, 255]
|
||||
for k in range(ch):
|
||||
if kind == "H":
|
||||
v = rng.randrange(65536)
|
||||
px[k] = (v + 128) // 257
|
||||
else:
|
||||
v = rng.uniform(-0.5, 1.5)
|
||||
v = struct.unpack("<" + kind, struct.pack("<" + kind, v))[0]
|
||||
px[k] = c8(v)
|
||||
vals.append(v)
|
||||
if ch == 1:
|
||||
px[1] = px[2] = px[0]
|
||||
rgba += bytes(px)
|
||||
data = header(fmt) + struct.pack("<%d%s" % (len(vals), kind), *vals)
|
||||
out.append({"name": name, "data": data, "width": w, "height": h, "frames": 1, "version": "7.2", "rgba": bytes(rgba), "tol": 1 if kind == "H" else 0, "mips": 1})
|
||||
return out
|
||||
|
||||
|
||||
def generate(ctx):
|
||||
res = json.loads(ctx.python(["srctools", "pillow"], CODE, input=json.dumps({"seed": 7}).encode()))
|
||||
out = []
|
||||
for e in res:
|
||||
if "failed" in e:
|
||||
print("fixtures: vtf: srctools cannot write %s: %s" % (e["name"], e["failed"]))
|
||||
continue
|
||||
c = {"name": e["name"], "data": bytes.fromhex(e["data"]), "width": e["width"], "height": e["height"], "frames": e["frames"],
|
||||
"version": e["version"], "rgba": bytes.fromhex(e["rgba"]), "tol": TOL.get(e["name"], 0)}
|
||||
if "last" in e:
|
||||
c["last"] = bytes.fromhex(e["last"])
|
||||
out.append(c)
|
||||
out += own(ctx.rng(9))
|
||||
ctx.emit("vtf", out)
|
||||
@@ -0,0 +1,190 @@
|
||||
# Doom WAD fixtures (tools/fixtures.py). Freedoom (BSD licence, licenses/freedoom-COPYING.txt; the nix freedoom
|
||||
# package, never committed) is cut down to a small IWAD here: MAP01's lumps, PLAYPAL, COLORMAP, PNAMES, TEXTURE1,
|
||||
# TITLEPIC, and the first sprites / patches / flats of each namespace (the WAD writer below keeps Freedoom's layout:
|
||||
# lumps in order, the directory at the end). References:
|
||||
# - DeuTex (nix deutex) extracts every graphic of the cut-down WAD as PNG; Pillow turns them into RGBA (DeuTex's
|
||||
# transparent index -> 0, 0, 0, 0; flats compared as RGB, all opaque) -> CRC-32 per lump;
|
||||
# - an independent Python parse of the map lumps: counts, the things, and each sector's floor area by Green's
|
||||
# theorem over its directed sides (no outline chaining), for the triangulation;
|
||||
# - a hand-made PWAD: a square room with a square pillar sector inside (exact areas and walls), a UDMF map stub,
|
||||
# tall-patch and namespace cases.
|
||||
# tests/gen/wad.luau { freedoom = { data, lumps = { { name, entry, size, crc, namespace? } }, images = { { name,
|
||||
# kind, width, height, left, top, crc } }, map = { name, things, linedefs, sidedefs,
|
||||
# vertices, sectors, floorArea, thingList = { { x, y, type, angle } } }, textures = { ... } },
|
||||
# room = { data, ... } }
|
||||
import glob, os, shutil, struct, subprocess, tempfile, zlib
|
||||
|
||||
FREEDOOM = "share/games/doom/freedoom2.wad"
|
||||
|
||||
TO_RGBA = r"""
|
||||
import json, sys, zlib
|
||||
from PIL import Image
|
||||
out = {}
|
||||
for path in json.loads(sys.stdin.read()):
|
||||
im = Image.open(path)
|
||||
t = im.info.get("transparency")
|
||||
idx = im.load()
|
||||
rgba = im.convert("RGBA")
|
||||
px = bytearray(rgba.tobytes())
|
||||
if t is not None and "/flats/" not in path:
|
||||
w, h = im.size
|
||||
for y in range(h):
|
||||
for x in range(w):
|
||||
if idx[x, y] == t:
|
||||
o = (y * w + x) * 4
|
||||
px[o:o + 4] = b"\0\0\0\0"
|
||||
else:
|
||||
for o in range(3, len(px), 4):
|
||||
px[o] = 255
|
||||
out[path] = {"w": im.size[0], "h": im.size[1], "crc": zlib.crc32(bytes(px))}
|
||||
print(json.dumps(out))
|
||||
"""
|
||||
|
||||
|
||||
def lumps_of(data):
|
||||
n, ofs = struct.unpack_from("<ii", data, 4)
|
||||
out = []
|
||||
for i in range(n):
|
||||
p, s, nm = struct.unpack_from("<ii8s", data, ofs + 16 * i)
|
||||
out.append((nm.split(b"\0")[0].decode("latin1").upper(), data[p:p + s]))
|
||||
return out
|
||||
|
||||
|
||||
def write(kind, lumps):
|
||||
out = bytearray(kind + b"\0" * 8)
|
||||
dirs = []
|
||||
for nm, b in lumps:
|
||||
dirs.append((len(out), len(b), nm))
|
||||
out += b
|
||||
o = len(out)
|
||||
for p, s, nm in dirs:
|
||||
out += struct.pack("<ii8s", p, s, nm.encode())
|
||||
struct.pack_into("<ii", out, 4, len(lumps), o)
|
||||
return bytes(out)
|
||||
|
||||
|
||||
def cut(full):
|
||||
lumps = lumps_of(full)
|
||||
names = [l[0] for l in lumps]
|
||||
sel = list(lumps[0:11])
|
||||
for m in ["PLAYPAL", "COLORMAP", "PNAMES", "TEXTURE1", "TITLEPIC"]:
|
||||
sel.append(lumps[names.index(m)])
|
||||
# the patches TEXTURE1's first textures use, so composed textures can be checked
|
||||
def rng(a, b, k, want=()):
|
||||
i, j = names.index(a), names.index(b)
|
||||
inner = [l for l in lumps[i + 1:j] if l[1]]
|
||||
pick = inner[:k] + [l for l in inner[k:] if l[0] in want]
|
||||
return [lumps[i]] + pick + [lumps[j]]
|
||||
return sel, rng
|
||||
|
||||
|
||||
def map_ref(lumps):
|
||||
d = dict(lumps[1:11])
|
||||
verts = [struct.unpack_from("<hh", d["VERTEXES"], i) for i in range(0, len(d["VERTEXES"]), 4)]
|
||||
sides = [struct.unpack_from("<hh8s8s8sH", d["SIDEDEFS"], i) for i in range(0, len(d["SIDEDEFS"]), 30)]
|
||||
secs = [struct.unpack_from("<hh8s8sHHH", d["SECTORS"], i) for i in range(0, len(d["SECTORS"]), 26)]
|
||||
lines = [struct.unpack_from("<HHHHHHH", d["LINEDEFS"], i) for i in range(0, len(d["LINEDEFS"]), 14)]
|
||||
things = [struct.unpack_from("<hhHHH", d["THINGS"], i) for i in range(0, len(d["THINGS"]), 10)]
|
||||
area = [0.0] * len(secs)
|
||||
for v1, v2, flags, special, tag, fr, bk in lines:
|
||||
fs = sides[fr][5] if fr != 0xFFFF else None
|
||||
bs = sides[bk][5] if bk != 0xFFFF else None
|
||||
if fs == bs:
|
||||
continue
|
||||
(ax, ay), (bx, by) = verts[v1], verts[v2]
|
||||
c = ax * by - bx * ay
|
||||
if fs is not None:
|
||||
area[fs] -= c / 2
|
||||
if bs is not None:
|
||||
area[bs] += c / 2
|
||||
return {"things": len(things), "linedefs": len(lines), "sidedefs": len(sides), "vertices": len(verts),
|
||||
"sectors": len(secs), "floorArea": sum(area), "sectorAreas": area,
|
||||
"thingList": [{"x": t[0], "y": t[1], "angle": t[2], "type": t[3]} for t in things[:20]]}
|
||||
|
||||
|
||||
def room():
|
||||
# a 256 x 256 room (sector 0) with a 64 x 64 pillar sector (1) in the middle, floor 0 / ceiling 128, pillar floor 32
|
||||
v = [(0, 0), (256, 0), (256, 256), (0, 256), (96, 96), (160, 96), (160, 160), (96, 160)]
|
||||
verts = b"".join(struct.pack("<hh", *p) for p in v)
|
||||
sides = b""
|
||||
sides += b"".join(struct.pack("<hh8s8s8sH", 0, 0, b"-", b"-", b"WALL", 0) for _ in range(4)) # 0..3 room walls
|
||||
sides += b"".join(struct.pack("<hh8s8s8sH", 0, 0, b"-", b"STEP", b"-", 0) for _ in range(4)) # 4..7 room side of pillar
|
||||
sides += b"".join(struct.pack("<hh8s8s8sH", 0, 0, b"-", b"-", b"-", 1) for _ in range(4)) # 8..11 pillar side
|
||||
# outer walls: room on the right of v1 -> v2 (clockwise); pillar lines: front = room (outside), back = pillar
|
||||
lines = b""
|
||||
for i, (a, b) in enumerate([(0, 3), (3, 2), (2, 1), (1, 0)]):
|
||||
lines += struct.pack("<HHHHHHH", a, b, 1, 0, 0, i, 0xFFFF)
|
||||
for i, (a, b) in enumerate([(4, 5), (5, 6), (6, 7), (7, 4)]):
|
||||
lines += struct.pack("<HHHHHHH", a, b, 4, 0, 0, 4 + i, 8 + i)
|
||||
secs = struct.pack("<hh8s8sHHH", 0, 128, b"FLOOR", b"CEIL", 160, 0, 0) + struct.pack("<hh8s8sHHH", 32, 128, b"FLOOR", b"CEIL", 160, 0, 0)
|
||||
things = struct.pack("<hhHHH", 32, 32, 90, 1, 7) + struct.pack("<hhHHH", 128, 128, 0, 2014, 7)
|
||||
flat = bytes((x ^ y) & 255 for y in range(64) for x in range(64))
|
||||
pal = bytes(c for i in range(256) for c in (i, 255 - i, (i * 3) & 255)) * 14
|
||||
# a tall patch (DeePsea): 1 x 300, a post at 100 (50 rows), then topdelta 50 <= 100: relative, rows 150..249
|
||||
col = bytes([100, 50, 0]) + bytes([7] * 50) + b"\0" + bytes([50, 100, 0]) + bytes([9] * 100) + b"\0" + b"\xff"
|
||||
tall = struct.pack("<HHhhI", 1, 300, 0, 0, 12) + col
|
||||
lumps = [("E1M1", b""), ("THINGS", things), ("LINEDEFS", lines), ("SIDEDEFS", sides), ("VERTEXES", verts),
|
||||
("SECTORS", secs), ("PLAYPAL", pal), ("F_START", b""), ("FLOOR", flat), ("CEIL", flat), ("F_END", b""),
|
||||
("P_START", b""), ("TALL", tall), ("P_END", b""), ("E1M2", b""), ("TEXTMAP", b'namespace = "zdoom";'),
|
||||
("ENDMAP", b""), ("DEMO1", b"x"), ("DEMO1", b"yy")]
|
||||
return write(b"PWAD", lumps), lumps
|
||||
|
||||
|
||||
def generate(ctx):
|
||||
root = ctx.nix("freedoom", ["sh", "-c", "dirname $(dirname $(readlink -f $(command -v freedoom2)))"]).decode().strip()
|
||||
full = open(os.path.join(root, FREEDOOM), "rb").read()
|
||||
sel, rng = cut(full)
|
||||
tex1 = dict(lumps_of(full))["TEXTURE1"]
|
||||
pn = dict(lumps_of(full))["PNAMES"]
|
||||
pnames = [pn[4 + 8 * i:12 + 8 * i].split(b"\0")[0].decode("latin1").upper() for i in range(struct.unpack_from("<i", pn)[0])]
|
||||
# the first three textures and their patches
|
||||
n = struct.unpack_from("<i", tex1)[0]
|
||||
textures, want = [], set()
|
||||
for i in range(3):
|
||||
o = struct.unpack_from("<i", tex1, 4 + 4 * i)[0]
|
||||
name = tex1[o:o + 8].split(b"\0")[0].decode("latin1").upper()
|
||||
w, h = struct.unpack_from("<hh", tex1, o + 12)
|
||||
pc = struct.unpack_from("<h", tex1, o + 20)[0]
|
||||
pats = []
|
||||
for k in range(pc):
|
||||
x, y, p = struct.unpack_from("<hhh", tex1, o + 22 + 10 * k)
|
||||
pats.append(pnames[p])
|
||||
want.add(pnames[p])
|
||||
textures.append({"name": name, "width": w, "height": h, "patches": pats})
|
||||
sel += rng("S_START", "S_END", 6) + rng("P_START", "P_END", 6, want) + rng("F_START", "F_END", 6)
|
||||
data = write(b"IWAD", sel)
|
||||
tmp = tempfile.mkdtemp(prefix="formats-wad-")
|
||||
try:
|
||||
open(os.path.join(tmp, "doom2.wad"), "wb").write(data)
|
||||
os.makedirs(os.path.join(tmp, "x"))
|
||||
ctx.nix("deutex", ["deutex", "-doom2", tmp, "-dir", os.path.join(tmp, "x"), "-xtract"])
|
||||
pngs = sorted(glob.glob(os.path.join(tmp, "x", "*", "*.png")))
|
||||
import json
|
||||
ref = json.loads(ctx.python(["pillow"], TO_RGBA, input=json.dumps(pngs).encode()))
|
||||
offsets = {}
|
||||
info = open(os.path.join(tmp, "x", "wadinfo.txt")).read().split("\n")
|
||||
for line in info:
|
||||
parts = line.split()
|
||||
if len(parts) == 3 and parts[1].lstrip("-").isdigit():
|
||||
offsets[parts[0].upper()] = (int(parts[1]), int(parts[2]))
|
||||
images = []
|
||||
for p in pngs:
|
||||
name = os.path.basename(p)[:-4].upper()
|
||||
kind = os.path.basename(os.path.dirname(p))
|
||||
e = {"name": name, "kind": kind, "width": ref[p]["w"], "height": ref[p]["h"], "crc": ref[p]["crc"]}
|
||||
if name in offsets and kind != "flats":
|
||||
e["left"], e["top"] = offsets[name]
|
||||
images.append(e)
|
||||
finally:
|
||||
shutil.rmtree(tmp)
|
||||
lumps = []
|
||||
seen = {}
|
||||
for nm, b in sel:
|
||||
lumps.append({"name": nm, "size": len(b), "crc": zlib.crc32(b)})
|
||||
mp = map_ref(sel)
|
||||
mp["name"] = "MAP01"
|
||||
rdata, rlumps = room()
|
||||
ctx.emit("wad", {
|
||||
"freedoom": {"data": data, "lumps": lumps, "images": images, "map": mp, "textures": textures},
|
||||
"room": {"data": rdata, "lumps": [{"name": n, "size": len(b)} for n, b in rlumps]},
|
||||
})
|
||||
Reference in new issue
Block a user