Bsp.leafAt / contents / pvs point queries; tested on ericw-tools qbsp + vis output in all three Quake 1 layouts.
203 lines
8.3 KiB
Python
203 lines
8.3 KiB
Python
# Shared helpers for the Quake map fixtures (brush.py, map.py, bsp.py, wad2.py): WAD2 / WAD3 writing, running
|
|
# ericw-tools (qbsp, light, vis from nixpkgs) on a .map, and a reader of the Quake 1 family BSP files they write
|
|
# (BSP 29, BSP2, 2PSB: layouts from bspfile.h of the Quake source release and ericw-tools; no code taken).
|
|
# wad(lumps, magic) -> bytes: lumps = [(name, type, data)]
|
|
# miptex(name, w, h, rng, palette=None) -> bytes (four mip levels of random indices; WAD3 / BSP 30 add the palette)
|
|
# compile(ctx, text, files, qbsp_args, light_args=None, vis=False) -> { bsp, obj?, log }
|
|
# read_bsp(data) -> dict of the parsed lumps
|
|
import math, os, shutil, struct, subprocess, tempfile
|
|
|
|
Q1_LUMPS = ["entities", "planes", "miptex", "vertices", "visibility", "nodes", "texinfo", "faces", "lighting",
|
|
"clipnodes", "leaves", "marksurfaces", "edges", "surfedges", "models"]
|
|
|
|
|
|
def wad(lumps, magic=b"WAD2"):
|
|
body = b""
|
|
dirs = []
|
|
for name, typ, data in lumps:
|
|
dirs.append(struct.pack("<iiiBBH16s", 12 + len(body), len(data), len(data), typ, 0, 0, name.encode()))
|
|
body += data
|
|
body += b"\0" * ((4 - len(body) % 4) % 4)
|
|
return magic + struct.pack("<ii", len(lumps), 12 + len(body)) + body + b"".join(dirs)
|
|
|
|
|
|
def miptex(name, w, h, rng, palette=None, pixels=None):
|
|
out = struct.pack("<16sII", name.encode(), w, h)
|
|
o = 40
|
|
offs, levels = [], []
|
|
for m in range(4):
|
|
lw, lh = w >> m, h >> m
|
|
px = pixels[m] if pixels else bytes(rng.randrange(256) for _ in range(lw * lh))
|
|
offs.append(o)
|
|
levels.append(px)
|
|
o += lw * lh
|
|
out += struct.pack("<4I", *offs) + b"".join(levels)
|
|
if palette is not None:
|
|
out += struct.pack("<H", 256) + palette + b"\0\0"
|
|
return out
|
|
|
|
|
|
def compile(ctx, text, files, qbsp_args, light_args=None, vis=False):
|
|
tmp = tempfile.mkdtemp(prefix="rosetta-qbsp-")
|
|
try:
|
|
for name, data in files.items():
|
|
open(os.path.join(tmp, name), "wb").write(data)
|
|
src = os.path.join(tmp, "map.map")
|
|
open(src, "w").write(text)
|
|
script = "cd %s && qbsp %s map.map > log.txt 2>&1" % (tmp, " ".join(qbsp_args))
|
|
if vis:
|
|
script += " && vis map.bsp >> log.txt 2>&1"
|
|
if light_args is not None:
|
|
script += " && light %s map.bsp >> log.txt 2>&1" % " ".join(light_args)
|
|
try:
|
|
ctx.nix("ericw-tools", ["sh", "-c", script])
|
|
except subprocess.CalledProcessError:
|
|
raise RuntimeError("ericw-tools failed:\n" + open(os.path.join(tmp, "log.txt")).read())
|
|
out = {"bsp": open(os.path.join(tmp, "map.bsp"), "rb").read(), "log": open(os.path.join(tmp, "log.txt")).read()}
|
|
if os.path.exists(os.path.join(tmp, "map.obj")):
|
|
out["obj"] = open(os.path.join(tmp, "map.obj")).read()
|
|
if os.path.exists(os.path.join(tmp, "map.lit")):
|
|
out["lit"] = open(os.path.join(tmp, "map.lit"), "rb").read()
|
|
return out
|
|
finally:
|
|
shutil.rmtree(tmp)
|
|
|
|
|
|
def read_bsp(data):
|
|
magic = data[:4]
|
|
if magic in (b"BSP2", b"2PSB"):
|
|
variant = magic.decode()
|
|
else:
|
|
variant = "bsp%d" % struct.unpack_from("<i", data, 0)[0]
|
|
lumps = {}
|
|
for i, n in enumerate(Q1_LUMPS):
|
|
o, s = struct.unpack_from("<ii", data, 4 + i * 8)
|
|
lumps[n] = data[o:o + s]
|
|
big = variant in ("BSP2", "2PSB")
|
|
out = {"variant": variant, "lumps": lumps}
|
|
L = lumps["planes"]
|
|
out["planes"] = [struct.unpack_from("<4fi", L, k) for k in range(0, len(L), 20)]
|
|
L = lumps["vertices"]
|
|
out["vertices"] = [struct.unpack_from("<3f", L, k) for k in range(0, len(L), 12)]
|
|
L = lumps["edges"]
|
|
es = 8 if big else 4
|
|
out["edges"] = [struct.unpack_from("<2I" if big else "<2H", L, k) for k in range(0, len(L), es)]
|
|
L = lumps["surfedges"]
|
|
out["surfedges"] = [struct.unpack_from("<i", L, k)[0] for k in range(0, len(L), 4)]
|
|
L = lumps["texinfo"]
|
|
out["texinfo"] = [struct.unpack_from("<8fii", L, k) for k in range(0, len(L), 40)]
|
|
L = lumps["faces"]
|
|
faces = []
|
|
if big:
|
|
for k in range(0, len(L), 28):
|
|
p, side, fe, ne, ti = struct.unpack_from("<iiiii", L, k)
|
|
faces.append({"plane": p, "side": side, "firstedge": fe, "numedges": ne, "texinfo": ti,
|
|
"styles": list(L[k + 20:k + 24]), "lightofs": struct.unpack_from("<i", L, k + 24)[0]})
|
|
else:
|
|
for k in range(0, len(L), 20):
|
|
p, side, fe, ne, ti = struct.unpack_from("<hhihh", L, k)
|
|
faces.append({"plane": p, "side": side, "firstedge": fe, "numedges": ne, "texinfo": ti,
|
|
"styles": list(L[k + 12:k + 16]), "lightofs": struct.unpack_from("<i", L, k + 16)[0]})
|
|
out["faces"] = faces
|
|
L = lumps["miptex"]
|
|
tex = []
|
|
if len(L) >= 4:
|
|
n = struct.unpack_from("<i", L, 0)[0]
|
|
for i in range(n):
|
|
o = struct.unpack_from("<i", L, 4 + i * 4)[0]
|
|
if o < 0:
|
|
tex.append(("", 0, 0))
|
|
continue
|
|
name, w, h = struct.unpack_from("<16sII", L, o)
|
|
tex.append((name.split(b"\0")[0].decode(), w, h))
|
|
out["textures"] = tex
|
|
L = lumps["models"]
|
|
out["models"] = [struct.unpack_from("<9f4i3i", L, k) for k in range(0, len(L), 64)]
|
|
if variant == "BSP2":
|
|
ls, lf = 44, "<ii3f3fII4B"
|
|
ns, nf = 44, "<i2i3f3fII"
|
|
cs, cf = 12, "<i2i"
|
|
elif variant == "2PSB":
|
|
ls, lf = 32, "<ii3h3hII4B"
|
|
ns, nf = 32, "<i2i3h3hII"
|
|
cs, cf = 12, "<i2i"
|
|
else:
|
|
ls, lf = 28, "<ii3h3hHH4B"
|
|
ns, nf = 24, "<i2h3h3hHH"
|
|
cs, cf = 8, "<i2h"
|
|
L = lumps["leaves"]
|
|
out["leaves"] = [struct.unpack_from(lf, L, k) for k in range(0, len(L), ls)]
|
|
L = lumps["nodes"]
|
|
out["nodes"] = [struct.unpack_from(nf, L, k) for k in range(0, len(L), ns)]
|
|
L = lumps["clipnodes"]
|
|
out["clipnodes"] = [struct.unpack_from(cf, L, k) for k in range(0, len(L), cs)]
|
|
L = lumps["marksurfaces"]
|
|
ms = 4 if big else 2
|
|
out["marksurfaces"] = [struct.unpack_from("<I" if big else "<H", L, k)[0] for k in range(0, len(L), ms)]
|
|
return out
|
|
|
|
|
|
def face_points(b, f):
|
|
pts = []
|
|
for k in range(f["numedges"]):
|
|
se = b["surfedges"][f["firstedge"] + k]
|
|
e = b["edges"][abs(se)]
|
|
pts.append(b["vertices"][e[0] if se >= 0 else e[1]])
|
|
return pts
|
|
|
|
|
|
def face_plane(b, f):
|
|
nx, ny, nz, d, _ = b["planes"][f["plane"]]
|
|
if f["side"]:
|
|
return (-nx, -ny, -nz, -d)
|
|
return (nx, ny, nz, d)
|
|
|
|
|
|
def write_bsp(b, lumps):
|
|
# reassembles a Quake 1 family BSP (b from read_bsp: its variant decides the header) from raw lumps
|
|
head = {"BSP2": b"BSP2", "2PSB": b"2PSB"}.get(b["variant"]) or struct.pack("<i", int(b["variant"][3:]))
|
|
off = len(head) + 8 * len(Q1_LUMPS)
|
|
body, dirs = b"", []
|
|
for n in Q1_LUMPS:
|
|
d = lumps[n]
|
|
dirs.append(struct.pack("<ii", off + len(body), len(d)))
|
|
body += d + b"\0" * ((4 - len(d) % 4) % 4)
|
|
return head + b"".join(dirs) + body
|
|
|
|
|
|
def extents(b, f):
|
|
# CalcSurfaceExtents: lightmap size in luxels (16 texels each) and the texture mins
|
|
ti = b["texinfo"][f["texinfo"]]
|
|
pts = face_points(b, f)
|
|
out = []
|
|
for j in range(2):
|
|
vals = [p[0] * ti[j * 4] + p[1] * ti[j * 4 + 1] + p[2] * ti[j * 4 + 2] + ti[j * 4 + 3] for p in pts]
|
|
lo, hi = math.floor(min(vals) / 16), math.ceil(max(vals) / 16)
|
|
out.append(hi - lo + 1)
|
|
return out
|
|
|
|
|
|
def light(b, rng, rgb=False):
|
|
# fills the lighting lump with random luxels at the extents of every face that is not TEX_SPECIAL (the nix light
|
|
# has no ray tracing backend); returns the new BSP bytes and { face: (w, h, ofs) }
|
|
big = b["variant"] in ("BSP2", "2PSB")
|
|
faces = bytearray(b["lumps"]["faces"])
|
|
size = 28 if big else 20
|
|
data = b""
|
|
out = {}
|
|
for i, f in enumerate(b["faces"]):
|
|
ti = b["texinfo"][f["texinfo"]]
|
|
o = i * size + (20 if big else 12)
|
|
if ti[9] & 1:
|
|
faces[o:o + 8] = bytes([255, 255, 255, 255]) + struct.pack("<i", -1)
|
|
continue
|
|
w, h = extents(b, f)
|
|
ofs = len(data)
|
|
data += bytes(rng.randrange(256) for _ in range(w * h * (3 if rgb else 1)))
|
|
faces[o:o + 8] = bytes([0, 255, 255, 255]) + struct.pack("<i", ofs)
|
|
out[i] = (w, h, ofs)
|
|
lumps = dict(b["lumps"])
|
|
lumps["faces"] = bytes(faces)
|
|
lumps["lighting"] = data
|
|
return write_bsp(b, lumps), out
|