codecs/model/Brush, codecs/model/Patch, codecs/image/Miptex; Pixels palette helpers

Brush: plane brushes -> polygons (qbsp-style clipping), Quake standard / Valve 220 / brush-primitive projection,
optional coplanar merge and CSG hull; tested against ericw-tools qbsp -nofill (area per plane, texels per corner).
Patch: Bezier control grids moved out of model/bsp/Quake3, per-axis subdivisions (patchDef2 / patchDef3), normals.
Miptex: Quake / GoldSrc miptex decode / encode and the WAD2 / WAD3 directory (model/bsp uses it now).
Pixels: grey, keyed, colorList, colormap, paletteBytes. STYLE: layout block and 2a table list the new modules.
This commit is contained in:
4DBug committed 2026-11-01 18:40:29 -06:00
1 parent 01c044805f
commit 5ad934565d
19 files changed
+4520 -923

No files matched your search

+153
View File
@@ -0,0 +1,153 @@
# 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 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)
+148
View File
@@ -0,0 +1,148 @@
# codecs/model/Brush fixtures (tools/fixtures.py): random convex brushes (boxes on a 16-unit grid, some with corners cut
# by planes through three integer points; overlapping, touching and coplanar ones) written as Quake standard, Valve 220
# and brush-primitive .map files, compiled with ericw-tools' qbsp -nofill (no outside fill: every CSG face survives)
# against a WAD2 of textures with their sizes. Reference: qbsp's faces (plane, corners, texinfo vectors and texture).
# tests/gen/brush.luau { [format] = { brushes = { { { pts = { 9 numbers }, tex, kind, args } } },
# sizes = { [tex] = { w, h } }, faces = { { plane = { 4 }, pts = { 3n }, tex, vecs = { 8 } } } } }
import importlib.util, os
INPUTS = ["tools/fixtures/_qbsp.py"]
TEXTURES = [("brick", 64, 32), ("metal", 32, 128), ("wood", 128, 64), ("stone", 16, 16)]
def helper(ctx):
spec = importlib.util.spec_from_file_location("_qbsp", os.path.join(ctx.root, "tools", "fixtures", "_qbsp.py"))
m = importlib.util.module_from_spec(spec)
spec.loader.exec_module(m)
return m
def sub(a, b):
return (a[0] - b[0], a[1] - b[1], a[2] - b[2])
def cross(u, v):
return (u[1] * v[2] - u[2] * v[1], u[2] * v[0] - u[0] * v[2], u[0] * v[1] - u[1] * v[0])
def dot(u, v):
return u[0] * v[0] + u[1] * v[1] + u[2] * v[2]
def oriented(p1, p2, p3, center):
# qbsp: normal = (p1 - p2) x (p3 - p2) points out of the brush
n = cross(sub(p1, p2), sub(p3, p2))
if dot(n, sub(center, p2)) > 0:
return (p3, p2, p1)
return (p1, p2, p3)
def box_faces(lo, hi):
(x0, y0, z0), (x1, y1, z1) = lo, hi
return [
((x0, y0, z0), (x0, y0 + 1, z0), (x0, y0, z0 + 1)),
((x1, y1, z1), (x1, y1, z1 + 1), (x1, y1 + 1, z1)),
((x0, y0, z0), (x0, y0, z0 + 1), (x0 + 1, y0, z0)),
((x1, y1, z1), (x1 + 1, y1, z1), (x1, y1, z1 + 1)),
((x0, y0, z0), (x0 + 1, y0, z0), (x0, y0 + 1, z0)),
((x1, y1, z1), (x1, y1 + 1, z1), (x1 + 1, y1, z1)),
]
def brushes(rng):
out = []
for i in range(14):
lo = tuple(rng.randrange(-8, 6) * 16 for _ in range(3))
hi = tuple(lo[k] + rng.randrange(2, 7) * 16 for k in range(3))
faces = box_faces(lo, hi)
center = tuple((lo[k] + hi[k]) / 2 for k in range(3))
for _ in range(rng.randrange(0, 3)):
corner = tuple(rng.choice((lo[k], hi[k])) for k in range(3))
pts = []
for k in range(3):
p = list(corner)
size = hi[k] - lo[k]
step = rng.randrange(4, size // 2 + 1)
p[k] += step if corner[k] == lo[k] else -step
pts.append(tuple(p))
faces.append(oriented(pts[0], pts[1], pts[2], center))
out.append(faces)
return out
def num(x):
s = ("%.6f" % x).rstrip("0").rstrip(".")
return "0" if s in ("-0", "") else s
def projection(rng, kind):
if kind == "standard":
return [rng.randrange(-64, 65), rng.randrange(-64, 65), rng.choice([0, 90, 180, 270, 15, 30, 45, 33.5]),
rng.choice([1, 0.5, 2, -1, 0.25, 1.5]), rng.choice([1, 0.5, 2, -1, 0.75])]
if kind == "valve":
u = [round(rng.uniform(-1, 1), 4) for _ in range(3)]
v = [round(rng.uniform(-1, 1), 4) for _ in range(3)]
return u + [rng.randrange(-32, 33)] + v + [rng.randrange(-32, 33), 0, rng.choice([1, 0.5, 2, -1]), rng.choice([1, 0.25, 2])]
while True: # qbsp replaces a singular matrix by the default projection
m = [rng.randrange(-8, 9) / 256, rng.randrange(-8, 9) / 256, rng.randrange(-16, 17) / 16,
rng.randrange(-8, 9) / 256, rng.randrange(-8, 9) / 256, rng.randrange(-16, 17) / 16]
if m[0] * m[4] - m[1] * m[3] != 0:
return m
def face_line(kind, pts, tex, a):
p = " ".join("( %s )" % " ".join(num(c) for c in q) for q in pts)
if kind == "standard":
return "%s %s %s" % (p, tex, " ".join(num(x) for x in a))
if kind == "valve":
return "%s %s [ %s ] [ %s ] %s" % (p, tex, " ".join(num(x) for x in a[0:4]), " ".join(num(x) for x in a[4:8]),
" ".join(num(x) for x in a[8:11]))
return "%s ( ( %s ) ( %s ) ) %s 0 0 0" % (p, " ".join(num(x) for x in a[0:3]), " ".join(num(x) for x in a[3:6]), tex)
def write_map(kind, bl, rng):
lines = ["// Game: Quake", "{", '"classname" "worldspawn"', '"wad" "tex.wad"']
if kind == "valve":
lines.append('"mapversion" "220"')
recs = []
for faces in bl:
lines.append("{")
if kind == "bp":
lines.append("brushDef")
lines.append("{")
rec = []
for pts in faces:
tex = rng.choice(TEXTURES)[0]
a = projection(rng, kind)
lines.append(face_line(kind, pts, tex, a))
rec.append({"pts": [float(c) for q in pts for c in q], "tex": tex, "kind": kind, "args": [float(x) for x in a]})
if kind == "bp":
lines.append("}")
lines.append("}")
recs.append(rec)
lines += ["}", "{", '"classname" "info_player_start"', '"origin" "0 0 0"', "}", ""]
return "\n".join(lines), recs
def generate(ctx):
H = helper(ctx)
rng = ctx.rng(777)
lumps = [(n, 0x44, H.miptex(n, w, h, rng)) for n, w, h in TEXTURES]
w2 = H.wad(lumps)
out = {}
for kind in ("standard", "valve", "bp"):
bl = brushes(rng)
text, recs = write_map(kind, bl, rng)
res = H.compile(ctx, text, {"tex.wad": w2}, ["-nofill", "-noclip", "-nopercent"])
b = H.read_bsp(res["bsp"])
world = b["models"][0]
first, count = world[14], world[15]
faces = []
for f in b["faces"][first:first + count]:
ti = b["texinfo"][f["texinfo"]]
tex = b["textures"][ti[8]][0]
faces.append({"plane": list(H.face_plane(b, f)), "pts": [c for p in H.face_points(b, f) for c in p],
"tex": tex, "vecs": list(ti[0:8])})
out[kind] = {"brushes": recs, "sizes": {n: [w, h] for n, w, h in TEXTURES}, "faces": faces, "map": text}
ctx.emit("brush", out)