Files
rosetta/tools/fixtures/wad.py
T

191 lines
9.4 KiB
Python

# 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]},
})