merge ws/quake (codecs/model/Brush for model/t3d)
This commit is contained in:
commit
37aa29d03e
49 files changed
+15426
-1411
No files matched your search
@@ -1902,3 +1902,24 @@ do
|
||||
jitTune(false)
|
||||
end
|
||||
end
|
||||
|
||||
-- ws-quake: .map brushes to polygons (codecs/model/Brush clip + CSG hull + merge; MB/s of map text) and a compiled
|
||||
-- BSP with its lightmap atlas and tree (MB/s of file); fixtures tools/fixtures/map.py, tools/fixtures/bsp.py
|
||||
do
|
||||
local MapFmt = require("@rosetta/model/map")
|
||||
local BspFmt = require("@rosetta/model/bsp")
|
||||
local Bytes = require("@rosetta/core/Bytes")
|
||||
local MF = require("@tests/gen/map")
|
||||
local BF = require("@tests/gen/bsp")
|
||||
local text = buffer.fromstring(MF.quake.text)
|
||||
bench("map decode (brushes)", 5, buffer.len(text), function()
|
||||
assert(MapFmt.decode(Bytes.reader(text), { files = MF.quake.files }))
|
||||
end)
|
||||
bench("map decode (hull + merge)", 5, buffer.len(text), function()
|
||||
assert(MapFmt.decode(Bytes.reader(text), { files = MF.quake.files, hull = true, merge = true }))
|
||||
end)
|
||||
local bsp = buffer.fromstring(BF.ericw.bsp29.data)
|
||||
bench("bsp decode (lightmaps, tree)", 5, buffer.len(bsp), function()
|
||||
assert(BspFmt.decode(Bytes.reader(bsp)))
|
||||
end)
|
||||
end
|
||||
@@ -0,0 +1,202 @@
|
||||
# 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
|
||||
@@ -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)
|
||||
+105
-4
@@ -6,11 +6,14 @@
|
||||
# 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.
|
||||
# ericw: the room of map.py compiled by ericw-tools (qbsp with hulls + vis) as BSP 29, BSP2 and 2PSB; the lighting lump
|
||||
# filled here at the extents of CalcSurfaceExtents (the nix light has no ray tracer), plus a .lit; expected: lightmap
|
||||
# sizes per face, the PVS of every leaf (Mod_DecompressVis), contents at probe points in hulls 0..2 (SV_HullPointContents).
|
||||
# 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"]
|
||||
INPUTS = ["tools/fixtures/_quake_ref.py", "tools/fixtures/_qbsp.py", "tools/fixtures/map.py"]
|
||||
|
||||
|
||||
def ref(ctx):
|
||||
@@ -110,7 +113,23 @@ def brush_map(rng, variant, pal):
|
||||
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)
|
||||
# Half-Life / Quake II: RGB lightmaps at the CalcSurfaceExtents sizes (Quake 1 is covered by the ericw maps)
|
||||
light, lms, fb = b"", [], b""
|
||||
for fi, (p, sd, fe, ne, ti) in enumerate(flist):
|
||||
if variant == "q1":
|
||||
fb += struct.pack("<HHiHH4Bi", p, sd, fe, ne, ti, 255, 255, 255, 255, -1)
|
||||
continue
|
||||
s4, t4 = tis[ti]
|
||||
pts = [verts[edges[abs(surfedges[fe + k])][0 if surfedges[fe + k] >= 0 else 1]] for k in range(ne)]
|
||||
size = []
|
||||
for v in (s4, t4):
|
||||
vals = [q[0] * v[0] + q[1] * v[1] + q[2] * v[2] + v[3] for q in pts]
|
||||
size.append(math.ceil(max(vals) / 16) - math.floor(min(vals) / 16) + 1)
|
||||
lms.append({"face": fi, "w": size[0], "h": size[1], "ofs": len(light)})
|
||||
fb += struct.pack("<HHiHH4Bi", p, sd, fe, ne, ti, 0, 255, 255, 255, len(light))
|
||||
light += bytes(rng.randrange(256) for _ in range(size[0] * size[1] * 3))
|
||||
L["faces"] = fb
|
||||
L["lighting"] = light
|
||||
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))
|
||||
@@ -148,7 +167,7 @@ def brush_map(rng, variant, pal):
|
||||
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}
|
||||
out = {"data": data, "models": {str(k): v for k, v in models.items()}, "names": texnames, "lightmaps": lms}
|
||||
if not q2:
|
||||
out["textures"] = mips
|
||||
else:
|
||||
@@ -222,6 +241,88 @@ def q3_map(rng):
|
||||
return {"data": data, "models": expect, "lightmaps": lmcrc, "patchArea": 32.0 * 32.0, "shaders": [s.decode() for s in shaders]}
|
||||
|
||||
|
||||
def load(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 pvs(b, leaf):
|
||||
lf = b["leaves"][leaf]
|
||||
vis, ofs = b["lumps"]["visibility"], lf[1]
|
||||
n = b["models"][0][13]
|
||||
if leaf == 0 or ofs < 0:
|
||||
return []
|
||||
bits, i = [], 0
|
||||
while len(bits) < n and ofs < len(vis):
|
||||
c = vis[ofs]
|
||||
if c:
|
||||
bits += [(c >> k) & 1 for k in range(8)]
|
||||
ofs += 1
|
||||
else:
|
||||
bits += [0] * (8 * vis[ofs + 1])
|
||||
ofs += 2
|
||||
return [k + 1 for k in range(n) if k < len(bits) and bits[k]]
|
||||
|
||||
|
||||
def contents(b, hull, p):
|
||||
def side(plane):
|
||||
nx, ny, nz, d, _ = b["planes"][plane]
|
||||
return p[0] * nx + p[1] * ny + p[2] * nz - d
|
||||
head = b["models"][0][9 + hull]
|
||||
if hull == 0:
|
||||
n = head
|
||||
nn = len(b["nodes"])
|
||||
while True:
|
||||
nd = b["nodes"][n]
|
||||
c = nd[1] if side(nd[0]) >= 0 else nd[2]
|
||||
if b["variant"] == "bsp29":
|
||||
c &= 0xFFFF
|
||||
if c >= nn:
|
||||
return b["leaves"][65535 - c][0]
|
||||
elif c < 0:
|
||||
return b["leaves"][-c - 1][0]
|
||||
n = c
|
||||
n = head
|
||||
nc = len(b["clipnodes"])
|
||||
while n >= 0:
|
||||
cn = b["clipnodes"][n]
|
||||
c = cn[1] if side(cn[0]) >= 0 else cn[2]
|
||||
if b["variant"] == "bsp29":
|
||||
c &= 0xFFFF
|
||||
if c > nc:
|
||||
c -= 65536
|
||||
n = c
|
||||
return n
|
||||
|
||||
|
||||
def ericw(ctx, rng):
|
||||
H = load(ctx, "_qbsp")
|
||||
M = load(ctx, "map")
|
||||
B = load(ctx, "brush")
|
||||
world, door = M.layout(rng)
|
||||
wad = H.wad([(n, 0x44, H.miptex(n, w, h, rng)) for n, w, h in M.TEX])
|
||||
text = M.write(B, "quake", world, door, rng, "tex.wad")
|
||||
probes = [(0, 0, 220), (-128, -128, 24), (200, 200, 100), (0, 0, 100), (-264, 0, 100), (0, 0, -8), (40, 0, 100),
|
||||
(-240, -240, 30), (100, -150, 64), (300, 300, 300)]
|
||||
out = {}
|
||||
for name, args in (("bsp29", []), ("bsp2", ["-bsp2"]), ("2psb", ["-2psb"])):
|
||||
res = H.compile(ctx, text, {"tex.wad": wad}, ["-nopercent"] + args, vis=True)
|
||||
b = H.read_bsp(res["bsp"])
|
||||
data, lm = H.light(b, rng)
|
||||
b = H.read_bsp(data)
|
||||
lit = b"QLIT" + struct.pack("<i", 1) + bytes(rng.randrange(256) for _ in range(len(b["lumps"]["lighting"]) * 3))
|
||||
out[name] = {
|
||||
"data": data, "lit": lit,
|
||||
"lightmaps": [{"face": f, "w": w, "h": h, "ofs": o} for f, (w, h, o) in sorted(lm.items())],
|
||||
"pvs": [pvs(b, i) for i in range(len(b["leaves"]))],
|
||||
"probes": [{"p": list(p), "c": [contents(b, h, p) for h in range(3)]} for p in probes],
|
||||
"faces": len(b["faces"]), "leaves": len(b["leaves"]), "visible": len(b["lumps"]["visibility"]),
|
||||
}
|
||||
return out
|
||||
|
||||
|
||||
def generate(ctx):
|
||||
rng = ctx.rng(101)
|
||||
R = ref(ctx)
|
||||
@@ -235,4 +336,4 @@ def generate(ctx):
|
||||
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})
|
||||
ctx.emit("bsp", {"q1": q1, "hl": hl, "q2": q2, "q3": q3, "ericw": ericw(ctx, rng)})
|
||||
@@ -0,0 +1,49 @@
|
||||
# Docs inputs for the Quake sections of the scene / archive / image / data pages (tools/fixtures.py; tools/docs_check.py
|
||||
# explains the inputs): the room .map of map.py with its WAD2, the same room compiled by ericw-tools (qbsp + vis, the
|
||||
# lighting lump filled by _qbsp.light), a gfx.wad-like WAD2 (wad2.py's writer), a qpic .lmp and a random palette.lmp
|
||||
# (Quake's own is GPL), a Half-Life sprite (spr.py), a shader script and a .skin (q3shader.py).
|
||||
# tests/gen/docs_quake.luau { files = { [name] = bytes }, vars = { roomMapText = "room.map", ... } }
|
||||
import importlib.util, os, struct
|
||||
|
||||
INPUTS = ["tools/docs_check.py", "tools/fixtures/_qbsp.py", "tools/fixtures/map.py", "tools/fixtures/spr.py",
|
||||
"tools/fixtures/q3shader.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 generate(ctx):
|
||||
rng = ctx.rng(9)
|
||||
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)
|
||||
H, M, B = mod(ctx, "_qbsp"), mod(ctx, "map"), mod(ctx, "brush")
|
||||
files = {}
|
||||
pal = bytes(rng.randrange(256) for _ in range(768))
|
||||
texwad = H.wad([(n, 0x44, H.miptex(n, w, h, rng)) for n, w, h in M.TEX])
|
||||
world, door = M.layout(rng)
|
||||
text = M.write(B, "quake", world, door, rng, "gfx/tex.wad")
|
||||
files["room.map"] = text
|
||||
files["tex.wad"] = texwad
|
||||
res = H.compile(ctx, text.replace("gfx/tex.wad", "tex.wad"), {"tex.wad": texwad}, ["-nopercent"], vis=True)
|
||||
files["room.bsp"], _ = H.light(H.read_bsp(res["bsp"]), rng)
|
||||
qp = bytes(rng.randrange(256) for _ in range(24 * 24))
|
||||
files["palette.lmp"] = pal
|
||||
files["disc.lmp"] = struct.pack("<II", 24, 24) + qp
|
||||
mips = [bytes(rng.randrange(256) for _ in range((32 >> m) * (32 >> m))) for m in range(4)]
|
||||
files["gfx.wad"] = H.wad([("palette", 0x40, pal), ("disc", 0x42, files["disc.lmp"]),
|
||||
("brick", 0x44, H.miptex("brick", 32, 32, rng, pixels=mips))])
|
||||
S = mod(ctx, "spr")
|
||||
files["flame.spr"] = S.sprite(rng, 2, [("single", (-16, 16, 32, 32)), ("group", [0.1, 0.2], [(-8, 8, 16, 16), (-8, 8, 16, 16)])], pal)["data"]
|
||||
Q = mod(ctx, "q3shader")
|
||||
files["base.shader"] = Q.SCRIPTS[0]
|
||||
files["sarge.skin"] = Q.SKINS[0]
|
||||
check.emit_inputs(ctx, files, {
|
||||
"roomMapText": "room.map", "texWadBytes": "tex.wad", "roomBspBytes": "room.bsp", "quakePaletteBytes": "palette.lmp",
|
||||
"discLmpBytes": "disc.lmp", "gfxWadBytes": "gfx.wad", "flameSprBytes": "flame.spr", "shaderText": "base.shader",
|
||||
"skinText": "sarge.skin",
|
||||
})
|
||||
@@ -0,0 +1,39 @@
|
||||
# image/lmp fixtures (tools/fixtures.py): qpic .lmp pictures, a palette.lmp and a colormap.lmp written from wad.h /
|
||||
# draw.c; reference rgba from Pillow (a "P" image with the palette, index 255 transparent for qpics). The palette is
|
||||
# random: Quake's own is GPL and never committed.
|
||||
# tests/gen/lmp.luau { palette, pics = { { name, data, w, h, crc, crcOpaque } }, colormap = { data, crc }, palcrc }
|
||||
import json, struct, zlib
|
||||
|
||||
CODE = r"""
|
||||
import json, sys, zlib, io
|
||||
from PIL import Image
|
||||
job = json.loads(sys.stdin.read())
|
||||
out = {}
|
||||
pal = bytes.fromhex(job["pal"])
|
||||
for k, (w, h, hexpix, key) in job["imgs"].items():
|
||||
im = Image.frombytes("P", (w, h), bytes.fromhex(hexpix))
|
||||
im.putpalette(pal)
|
||||
if key is not None:
|
||||
im.info["transparency"] = key
|
||||
out[k] = zlib.crc32(im.convert("RGBA").tobytes())
|
||||
print(json.dumps(out))
|
||||
"""
|
||||
|
||||
|
||||
def generate(ctx):
|
||||
rng = ctx.rng(31)
|
||||
pal = bytes(rng.randrange(256) for _ in range(768))
|
||||
imgs, pics = {}, []
|
||||
for name, w, h in (("disc", 24, 24), ("conback", 64, 40), ("num_0", 24, 24), ("wide", 3, 1)):
|
||||
pix = bytes(rng.randrange(256) for _ in range(w * h))
|
||||
imgs[name] = [w, h, pix.hex(), 255]
|
||||
imgs[name + "_o"] = [w, h, pix.hex(), None]
|
||||
pics.append({"name": name, "data": struct.pack("<II", w, h) + pix, "w": w, "h": h})
|
||||
cmap = bytes(rng.randrange(256) for _ in range(64 * 256)) + b"\0"
|
||||
imgs["colormap"] = [256, 64, cmap[:16384].hex(), None]
|
||||
imgs["palette"] = [16, 16, bytes(range(256)).hex(), None]
|
||||
ref = json.loads(ctx.python(["pillow"], CODE, input=json.dumps({"pal": pal.hex(), "imgs": imgs}).encode()))
|
||||
for p in pics:
|
||||
p["crc"] = ref[p["name"]]
|
||||
p["crcOpaque"] = ref[p["name"] + "_o"]
|
||||
ctx.emit("lmp", {"palette": pal, "pics": pics, "colormap": {"data": cmap, "crc": ref["colormap"]}, "palcrc": ref["palette"]})
|
||||
@@ -0,0 +1,172 @@
|
||||
# model/map fixtures (tools/fixtures.py): .map files written here in the four dialects and compiled with ericw-tools
|
||||
# qbsp -nofill (Quake 1 BSP; it reads all four). Reference: qbsp's faces per model (plane, corners, texinfo vectors,
|
||||
# texture and its size from the WAD), so the test checks our CSG'd polygons and texture coordinates per entity.
|
||||
# quake: a room (6 wall boxes), a pillar, a func_door, point entities, Quake standard faces, "wad" -> tex.wad (WAD2)
|
||||
# valve: the same layout in Valve 220 with a WAD3 named by a Windows path
|
||||
# quake2: Quake II faces with contents / flags / value; sizes from textures/<name>.wal
|
||||
# quake3: brushDef faces + a patchDef2 (qbsp compiles the brushes of a copy without the patch; the patch reference is
|
||||
# evaluated here: biquadratic Bezier, 4 segments per sub-patch)
|
||||
# tests/gen/map.luau { [name] = { text, files = { [name] = bytes }, models = { [model] = { faces } }, sizes, patch? } }
|
||||
import importlib.util, os
|
||||
|
||||
INPUTS = ["tools/fixtures/_qbsp.py", "tools/fixtures/brush.py"]
|
||||
|
||||
TEX = [("brick", 64, 32), ("metal", 32, 128), ("wood", 128, 64), ("+0lava", 64, 64), ("stone", 16, 16)]
|
||||
|
||||
|
||||
def load(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 layout(rng):
|
||||
world = []
|
||||
# room [-256, 256] x [-256, 256] x [0, 256], walls 16 thick
|
||||
lo, hi = (-256, -256, 0), (256, 256, 256)
|
||||
t = 16
|
||||
world.append(((lo[0] - t, lo[1] - t, lo[2] - t), (hi[0] + t, hi[1] + t, lo[2])))
|
||||
world.append(((lo[0] - t, lo[1] - t, hi[2]), (hi[0] + t, hi[1] + t, hi[2] + t)))
|
||||
world.append(((lo[0] - t, lo[1] - t, lo[2]), (lo[0], hi[1] + t, hi[2])))
|
||||
world.append(((hi[0], lo[1] - t, lo[2]), (hi[0] + t, hi[1] + t, hi[2])))
|
||||
world.append(((lo[0], lo[1] - t, lo[2]), (hi[0], lo[1], hi[2])))
|
||||
world.append(((lo[0], hi[1], lo[2]), (hi[0], hi[1] + t, hi[2])))
|
||||
world.append(((-32, -32, 0), (32, 32, 192))) # pillar standing on the floor
|
||||
world.append(((64, 64, -8), (160, 128, 48))) # a box sunk into the floor
|
||||
door = [((100, -200, 0), (116, -120, 128))]
|
||||
return world, door
|
||||
|
||||
|
||||
def faces_for(B, box, rng, kind):
|
||||
out = []
|
||||
for pts in B.box_faces(*box):
|
||||
tex = rng.choice(TEX)[0]
|
||||
out.append((pts, tex, B.projection(rng, "bp" if kind == "quake3" else ("valve" if kind == "valve" else "standard"))))
|
||||
return out
|
||||
|
||||
|
||||
def face_text(B, kind, pts, tex, a, flags):
|
||||
k = {"quake": "standard", "quake2": "standard", "valve": "valve", "quake3": "bp"}[kind]
|
||||
line = B.face_line(k, pts, tex, a)
|
||||
if kind == "quake3":
|
||||
line = line[: -len(" 0 0 0")] + " " + " ".join(str(x) for x in flags)
|
||||
elif kind == "quake2":
|
||||
line += " " + " ".join(str(x) for x in flags)
|
||||
return line
|
||||
|
||||
|
||||
def write(B, kind, world, door, rng, wadkey, patch=None):
|
||||
head = {"quake": "// Game: Quake\n// Format: Standard\n", "valve": "// Game: Half-Life\n// Format: Valve\n",
|
||||
"quake2": "// Game: Quake 2\n// Format: Quake2\n", "quake3": "// Game: Quake 3\n// Format: Quake3\n"}[kind]
|
||||
lines = [head + "{", '"classname" "worldspawn"', '"message" "fixture room"']
|
||||
if wadkey:
|
||||
lines.append('"wad" "%s"' % wadkey)
|
||||
if kind == "valve":
|
||||
lines.append('"mapversion" "220"')
|
||||
for box in world:
|
||||
lines.append("{")
|
||||
if kind == "quake3":
|
||||
lines += ["brushDef", "{"]
|
||||
for pts, tex, a in faces_for(B, box, rng, kind):
|
||||
lines.append(face_text(B, kind, pts, tex, a, [0, rng.randrange(0, 4), 0]))
|
||||
if kind == "quake3":
|
||||
lines.append("}")
|
||||
lines.append("}")
|
||||
if patch:
|
||||
lines.append(patch)
|
||||
lines += ["}", "{", '"classname" "func_door"', '"targetname" "door1"', '"angle" "90"']
|
||||
for box in door:
|
||||
lines.append("{")
|
||||
if kind == "quake3":
|
||||
lines += ["brushDef", "{"]
|
||||
for pts, tex, a in faces_for(B, box, rng, kind):
|
||||
lines.append(face_text(B, kind, pts, tex, a, [1, 0, 5]))
|
||||
if kind == "quake3":
|
||||
lines.append("}")
|
||||
lines.append("}")
|
||||
lines += ["}", "{", '"classname" "info_player_start"', '"origin" "-128 -128 24"', '"angle" "45"', "}",
|
||||
"{", '"classname" "light"', '"origin" "0 0 200"', '"light" "300"', "}", ""]
|
||||
return "\n".join(lines)
|
||||
|
||||
|
||||
def bezier_patch(w, h, ctrl, level):
|
||||
# ctrl[(i * w + j)] row-major (row i, column j) of (x, y, z, s, t); quadratic Bezier per 3 x 3 sub-patch
|
||||
px, py = (w - 1) // 2, (h - 1) // 2
|
||||
gw, gh = px * level + 1, py * level + 1
|
||||
out = []
|
||||
for gy in range(gh):
|
||||
sy = min(gy // level, py - 1)
|
||||
tv = (gy - sy * level) / level
|
||||
bv = [(1 - tv) ** 2, 2 * tv * (1 - tv), tv * tv]
|
||||
for gx in range(gw):
|
||||
sx = min(gx // level, px - 1)
|
||||
tu = (gx - sx * level) / level
|
||||
bu = [(1 - tu) ** 2, 2 * tu * (1 - tu), tu * tu]
|
||||
p = [0.0] * 5
|
||||
for j in range(3):
|
||||
for i in range(3):
|
||||
c = ctrl[(sy * 2 + j) * w + sx * 2 + i]
|
||||
for k in range(5):
|
||||
p[k] += c[k] * bu[i] * bv[j]
|
||||
out.append(p)
|
||||
return out, gw, gh
|
||||
|
||||
|
||||
def compile_faces(H, ctx, text, files):
|
||||
res = H.compile(ctx, text, files, ["-nofill", "-noclip", "-nopercent"])
|
||||
b = H.read_bsp(res["bsp"])
|
||||
models = {}
|
||||
for mi, m in enumerate(b["models"]):
|
||||
first, count = m[14], m[15]
|
||||
faces = []
|
||||
for f in b["faces"][first:first + count]:
|
||||
ti = b["texinfo"][f["texinfo"]]
|
||||
name, w, h = b["textures"][ti[8]]
|
||||
assert name and w and h, "qbsp did not find the texture WAD"
|
||||
faces.append({"plane": list(H.face_plane(b, f)), "pts": [c for p in H.face_points(b, f) for c in p],
|
||||
"tex": name, "vecs": list(ti[0:8]), "size": [w, h]})
|
||||
models[str(mi)] = faces
|
||||
return models
|
||||
|
||||
|
||||
def generate(ctx):
|
||||
H = load(ctx, "_qbsp")
|
||||
B = load(ctx, "brush")
|
||||
rng = ctx.rng(4242)
|
||||
world, door = layout(rng)
|
||||
out = {}
|
||||
wad2 = H.wad([(n, 0x44, H.miptex(n, w, h, rng)) for n, w, h in TEX])
|
||||
pal = bytes(rng.randrange(256) for _ in range(768))
|
||||
wad3 = H.wad([(n, 0x43, H.miptex(n, w, h, rng, pal)) for n, w, h in TEX], b"WAD3")
|
||||
sizes = {n: [w, h] for n, w, h in TEX}
|
||||
# quake
|
||||
text = write(B, "quake", world, door, rng, "gfx/tex.wad")
|
||||
out["quake"] = {"text": text, "files": {"gfx/tex.wad": wad2}, "models": compile_faces(H, ctx, text.replace("gfx/tex.wad", "tex.wad"), {"tex.wad": wad2}), "sizes": sizes}
|
||||
# valve 220 with a WAD3 under a Windows path
|
||||
text = write(B, "valve", world, door, rng, "\\half-life\\valve\\tex3.wad")
|
||||
qtext = text.replace("\\half-life\\valve\\tex3.wad", "tex3.wad")
|
||||
out["valve"] = {"text": text, "files": {"tex3.wad": wad3}, "models": compile_faces(H, ctx, qtext, {"tex3.wad": wad3}), "sizes": sizes}
|
||||
# quake 2: .wal sizes (qbsp is given the same sizes through a WAD of the same names)
|
||||
text = write(B, "quake2", world, door, rng, None)
|
||||
wals = {}
|
||||
for n, w, h in TEX:
|
||||
wals["textures/" + n + ".wal"] = (n.encode() + b"\0" * (32 - len(n))) + w.to_bytes(4, "little") + h.to_bytes(4, "little") + bytes(60)
|
||||
qtext = text.replace('"message" "fixture room"', '"message" "fixture room"\n"wad" "tex.wad"')
|
||||
out["quake2"] = {"text": text, "files": wals, "models": compile_faces(H, ctx, qtext, {"tex.wad": wad2}), "sizes": sizes}
|
||||
# quake 3: brushDef + a 5 x 3 patch
|
||||
W, Hh = 5, 3
|
||||
ctrl = []
|
||||
for i in range(Hh):
|
||||
for j in range(W):
|
||||
ctrl.append([-200 + j * 40, 100 + i * 50, 64 + (48 if i == 1 else 0) + (24 if j % 2 else 0), j / 4, i / 2])
|
||||
rows = []
|
||||
for j in range(W): # file order: column by column
|
||||
rows.append("( " + " ".join("( %s )" % " ".join(B.num(x) for x in ctrl[i * W + j]) for i in range(Hh)) + " )")
|
||||
patch = "{\npatchDef2\n{\nbase/curve\n( %d %d 0 0 0 )\n(\n%s\n)\n}\n}" % (W, Hh, "\n".join(rows))
|
||||
text = write(B, "quake3", world, door, rng, "tex.wad", patch)
|
||||
plain = text.replace(patch + "\n", "")
|
||||
grid, gw, gh = bezier_patch(W, Hh, ctrl, 4)
|
||||
out["quake3"] = {"text": text, "files": {"tex.wad": wad2}, "models": compile_faces(H, ctx, plain, {"tex.wad": wad2}), "sizes": sizes,
|
||||
"patch": {"grid": [c for p in grid for c in p], "w": gw, "h": gh}}
|
||||
ctx.emit("map", out)
|
||||
@@ -0,0 +1,117 @@
|
||||
# data/q3shader and data/q3skin fixtures (tools/fixtures.py): shader scripts in the style of the Quake III Arena
|
||||
# Shader Manual (comments, quoted tokens, braces on their own lines or not, several stages) and .skin files; reference
|
||||
# structure from an independent tokenizer here (COM_ParseExt rules: tokens per line, // and /* */ comments).
|
||||
# tests/gen/q3shader.luau { scripts = { { text, shaders = { { name, directives, stages } } } }, skins = { { text, entries } } }
|
||||
import re
|
||||
|
||||
SCRIPTS = [
|
||||
"""// base walls
|
||||
textures/base_wall/metalfloor_wall_10
|
||||
{
|
||||
qer_editorimage textures/base_wall/metalfloor_wall_10.tga
|
||||
surfaceparm metalsteps
|
||||
{
|
||||
map $lightmap
|
||||
rgbGen identity
|
||||
}
|
||||
{
|
||||
map textures/base_wall/metalfloor_wall_10.tga
|
||||
blendFunc GL_DST_COLOR GL_ZERO
|
||||
rgbGen identity
|
||||
}
|
||||
}
|
||||
|
||||
textures/sfx/flame1 {
|
||||
surfaceparm nolightmap
|
||||
cull none /* both sides */
|
||||
q3map_surfacelight 2500
|
||||
{
|
||||
animMap 10 textures/sfx/flame1.tga textures/sfx/flame2.tga textures/sfx/flame3.tga
|
||||
blendFunc GL_ONE GL_ONE
|
||||
tcMod scale 1 1 // per frame
|
||||
}
|
||||
}
|
||||
""",
|
||||
"""/*
|
||||
* a sky and a quoted path
|
||||
*/
|
||||
textures/skies/hellsky
|
||||
{
|
||||
skyparms "env/hell sky" 512 -
|
||||
surfaceparm noimpact
|
||||
surfaceparm sky
|
||||
{ map textures/skies/clouds.tga
|
||||
tcMod scroll 0.05 0.06 }
|
||||
}
|
||||
models/players/sarge/band
|
||||
{
|
||||
deformVertexes wave 100 sin 0 2 0 1
|
||||
{
|
||||
map models/players/sarge/band.tga
|
||||
alphaFunc GE128
|
||||
depthWrite
|
||||
}
|
||||
}
|
||||
""",
|
||||
]
|
||||
|
||||
SKINS = [
|
||||
"tag_head,\ntag_torso,\nh_head,models/players/sarge/band.tga\nh_cap,models/players/sarge/cigar.tga\n",
|
||||
"u_torso,models/players/sarge/default.tga\r\nl_legs,models/players/sarge/default.tga\r\n",
|
||||
]
|
||||
|
||||
|
||||
def tokenize(text):
|
||||
text = re.sub(r"/\*.*?\*/", lambda m: "\n" * m.group(0).count("\n"), text, flags=re.S)
|
||||
lines = []
|
||||
for raw in text.split("\n"):
|
||||
raw = raw.split("//")[0] if '"' not in raw else raw
|
||||
cur = []
|
||||
for m in re.finditer(r'"([^"]*)"|([{}])|([^\s{}"]+)', raw):
|
||||
if m.group(2):
|
||||
if cur:
|
||||
lines.append(cur)
|
||||
cur = []
|
||||
lines.append([m.group(2)])
|
||||
else:
|
||||
cur.append(m.group(1) if m.group(1) is not None else m.group(3))
|
||||
if cur:
|
||||
lines.append(cur)
|
||||
return lines
|
||||
|
||||
|
||||
def parse(text):
|
||||
lines = tokenize(text)
|
||||
out, k = [], 0
|
||||
while k < len(lines):
|
||||
sh = {"name": lines[k][0], "directives": [], "stages": []}
|
||||
k += 2
|
||||
stage = None
|
||||
while True:
|
||||
d = lines[k]
|
||||
k += 1
|
||||
if d == ["{"]:
|
||||
stage = []
|
||||
elif d == ["}"]:
|
||||
if stage is None:
|
||||
break
|
||||
sh["stages"].append(stage)
|
||||
stage = None
|
||||
elif stage is not None:
|
||||
stage.append(d)
|
||||
else:
|
||||
sh["directives"].append(d)
|
||||
out.append(sh)
|
||||
return out
|
||||
|
||||
|
||||
def generate(ctx):
|
||||
skins = []
|
||||
for s in SKINS:
|
||||
entries = []
|
||||
for line in s.replace("\r", "").split("\n"):
|
||||
if line.strip():
|
||||
a, b = line.split(",", 1)
|
||||
entries.append({"surface": a.strip(), "shader": b.strip()})
|
||||
skins.append({"text": s, "entries": entries})
|
||||
ctx.emit("q3shader", {"scripts": [{"text": s, "shaders": parse(s)} for s in SCRIPTS], "skins": skins})
|
||||
@@ -0,0 +1,82 @@
|
||||
# image/spr fixtures (tools/fixtures.py): sprites written from spritegn.h (Quake IDSP 1: two single frames and a
|
||||
# group of three; Half-Life IDSP 2 with its palette, alpha test and index alpha; DarkPlaces SPR32); expected frame
|
||||
# pixels (rgba CRCs), canvas positions from the frame origins, and group delays from the cumulative intervals.
|
||||
# tests/gen/spr.luau { palette, sprites = { { name, data, version, w, h, origin, frames = { { x, y, w, h, crc, delay } } } } }
|
||||
import struct, zlib
|
||||
|
||||
|
||||
def frame_bytes(rng, w, h, bpp):
|
||||
return bytes(rng.randrange(256) for _ in range(w * h * bpp))
|
||||
|
||||
|
||||
def rgba(pix, pal, key=None, mode=None):
|
||||
out = bytearray()
|
||||
for i in pix:
|
||||
if mode == "indexalpha":
|
||||
out += pal[255 * 3:255 * 3 + 3] + bytes([i])
|
||||
elif key is not None and i == key:
|
||||
out += pal[i * 3:i * 3 + 3] + b"\0"
|
||||
else:
|
||||
out += pal[i * 3:i * 3 + 3] + b"\xff"
|
||||
return zlib.crc32(bytes(out))
|
||||
|
||||
|
||||
def sprite(rng, version, layout, pal, tex=3):
|
||||
# layout: list of ("single", (ox, oy, w, h)) or ("group", [intervals], [(ox, oy, w, h)])
|
||||
singles = []
|
||||
body = b""
|
||||
frames = []
|
||||
for item in layout:
|
||||
if item[0] == "single":
|
||||
body += struct.pack("<i", 0)
|
||||
entries = [(item[1], 0.1)]
|
||||
else:
|
||||
ivs = item[1]
|
||||
body += struct.pack("<ii", 1, len(ivs)) + b"".join(struct.pack("<f", v) for v in ivs)
|
||||
entries = [(f, ivs[k] - (ivs[k - 1] if k else 0)) for k, f in enumerate(item[2])]
|
||||
for (ox, oy, w, h), delay in entries:
|
||||
pix = frame_bytes(rng, w, h, 4 if version == 32 else 1)
|
||||
body += struct.pack("<iiii", ox, oy, w, h) + pix
|
||||
if version == 32:
|
||||
crc = zlib.crc32(pix)
|
||||
elif version == 2 and tex == 2:
|
||||
crc = rgba(pix, pal, mode="indexalpha")
|
||||
elif version == 2 and tex != 3:
|
||||
crc = rgba(pix, pal)
|
||||
else:
|
||||
crc = rgba(pix, pal, 255)
|
||||
frames.append({"ox": ox, "oy": oy, "w": w, "h": h, "crc": crc, "delay": struct.unpack("<f", struct.pack("<f", delay))[0]})
|
||||
n = len(layout)
|
||||
mw = max(f["w"] for f in frames)
|
||||
mh = max(f["h"] for f in frames)
|
||||
if version == 2:
|
||||
head = b"IDSP" + struct.pack("<iiifiiifi", 2, 2, tex, 16.0, mw, mh, n, 0.0, 0) + struct.pack("<H", 256) + pal
|
||||
else:
|
||||
head = b"IDSP" + struct.pack("<iifiiifi", version, 2, 16.0, mw, mh, n, 0.0, 0)
|
||||
minx = min(f["ox"] for f in frames)
|
||||
maxy = max(f["oy"] for f in frames)
|
||||
for f in frames:
|
||||
f["x"], f["y"] = f["ox"] - minx, maxy - f["oy"]
|
||||
w = max(f["ox"] + f["w"] for f in frames) - minx
|
||||
h = maxy - min(f["oy"] - f["h"] for f in frames)
|
||||
return {"data": head + body, "version": version, "w": w, "h": h, "origin": [-minx, maxy], "frames": frames}
|
||||
|
||||
|
||||
def generate(ctx):
|
||||
rng = ctx.rng(64)
|
||||
pal = bytes(rng.randrange(256) for _ in range(768))
|
||||
hlpal = bytes(rng.randrange(256) for _ in range(768))
|
||||
sprites = []
|
||||
q = sprite(rng, 1, [("single", (-8, 8, 16, 16)), ("single", (-12, 20, 24, 28)),
|
||||
("group", [0.1, 0.25, 0.5], [(-4, 4, 8, 8), (-6, 6, 12, 12), (-8, 10, 16, 20)])], pal)
|
||||
q["name"] = "quake"
|
||||
sprites.append(q)
|
||||
for tex, name in ((3, "hl_alphatest"), (2, "hl_indexalpha"), (0, "hl_normal")):
|
||||
s = sprite(rng, 2, [("single", (-16, 16, 32, 32)), ("single", (-10, 12, 20, 24))], hlpal, tex)
|
||||
s["name"] = name
|
||||
s["tex"] = tex
|
||||
sprites.append(s)
|
||||
s32 = sprite(rng, 32, [("single", (-5, 5, 10, 10)), ("group", [0.2, 0.4], [(-5, 5, 10, 10), (-3, 9, 6, 12)])], pal)
|
||||
s32["name"] = "spr32"
|
||||
sprites.append(s32)
|
||||
ctx.emit("spr", {"palette": pal, "hlpalette": hlpal, "sprites": sprites})
|
||||
@@ -0,0 +1,77 @@
|
||||
# archive/wad2 fixtures (tools/fixtures.py): a Quake gfx.wad-like WAD2 (palette, conchars, a qpic, miptex textures, one
|
||||
# '{' keyed) and a Half-Life WAD3 (miptex with their palettes, a qpic with its palette, a font), written with
|
||||
# tools/fixtures/_qbsp.py's WAD writer from wad.h; expected pixels decoded here (index -> palette, 255 or 0 keyed);
|
||||
# plus the WAD2 compiled into a map by ericw-tools qbsp (it reads the miptex lumps: the BSP's copies must match).
|
||||
# tests/gen/wad2.luau { wad2 = { data, palette, images = { [name] = { w, h, crc, kind } } }, wad3 = ..., bsp }
|
||||
import importlib.util, os, struct, zlib
|
||||
|
||||
INPUTS = ["tools/fixtures/_qbsp.py"]
|
||||
|
||||
|
||||
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 rgba(pix, pal, key=None):
|
||||
out = bytearray()
|
||||
for i in pix:
|
||||
if key is not None and i == key:
|
||||
out += pal[i * 3:i * 3 + 3] + b"\0"
|
||||
else:
|
||||
out += pal[i * 3:i * 3 + 3] + b"\xff"
|
||||
return zlib.crc32(bytes(out))
|
||||
|
||||
|
||||
def generate(ctx):
|
||||
H = helper(ctx)
|
||||
rng = ctx.rng(22)
|
||||
pal = bytes(rng.randrange(256) for _ in range(768))
|
||||
images = {}
|
||||
lumps = [("palette", 0x40, pal)]
|
||||
con = bytes(rng.randrange(256) for _ in range(128 * 128))
|
||||
lumps.append(("conchars", 0x44, con))
|
||||
images["conchars"] = {"w": 128, "h": 128, "crc": rgba(con, pal, 0), "kind": "conchars"}
|
||||
qw, qh = 24, 10
|
||||
qp = bytes(rng.randrange(256) for _ in range(qw * qh))
|
||||
lumps.append(("disc", 0x42, struct.pack("<II", qw, qh) + qp))
|
||||
images["disc"] = {"w": qw, "h": qh, "crc": rgba(qp, pal, 255), "kind": "qpic"}
|
||||
for name, w, h in (("brick", 32, 16), ("{fence", 16, 16)):
|
||||
mips = [bytes(rng.randrange(256) for _ in range((w >> m) * (h >> m))) for m in range(4)]
|
||||
lumps.append((name, 0x44, H.miptex(name, w, h, rng, pixels=mips)))
|
||||
images[name] = {"w": w, "h": h, "crc": rgba(mips[0], pal, 255 if name[0] == "{" else None), "kind": "miptex",
|
||||
"mip2": rgba(mips[2], pal, 255 if name[0] == "{" else None)}
|
||||
wad2 = H.wad(lumps)
|
||||
out = {"wad2": {"data": wad2, "palette": pal, "images": images, "names": [l[0] for l in lumps]}}
|
||||
# WAD3
|
||||
images3 = {}
|
||||
lumps3 = []
|
||||
for name, w, h in (("CRETE", 32, 32), ("{GRATE", 16, 32)):
|
||||
p3 = bytes(rng.randrange(256) for _ in range(768))
|
||||
mips = [bytes(rng.randrange(256) for _ in range((w >> m) * (h >> m))) for m in range(4)]
|
||||
lumps3.append((name, 0x43, H.miptex(name, w, h, rng, p3, pixels=mips)))
|
||||
images3[name] = {"w": w, "h": h, "crc": rgba(mips[0], p3, 255 if name[0] == "{" else None), "kind": "miptex"}
|
||||
p3 = bytes(rng.randrange(256) for _ in range(768))
|
||||
qp = bytes(rng.randrange(256) for _ in range(20 * 12))
|
||||
lumps3.append(("LOGO", 0x42, struct.pack("<II", 20, 12) + qp + struct.pack("<H", 256) + p3))
|
||||
images3["LOGO"] = {"w": 20, "h": 12, "crc": rgba(qp, p3, 255), "kind": "qpic"}
|
||||
fw, fh = 256, 16
|
||||
fp = bytes(rng.randrange(256) for _ in range(fw * fh))
|
||||
chars = b"".join(struct.pack("<HH", (c % 32) * 8, 8) for c in range(256))
|
||||
lumps3.append(("CONCHARS", 0x46, struct.pack("<IIII", fw, fh, 2, 8) + chars + fp + struct.pack("<H", 256) + p3))
|
||||
images3["CONCHARS"] = {"w": fw, "h": fh, "crc": rgba(fp, p3, 255), "kind": "font"}
|
||||
out["wad3"] = {"data": H.wad(lumps3, b"WAD3"), "images": images3, "names": [l[0] for l in lumps3]}
|
||||
# qbsp copies the miptex it uses into the BSP
|
||||
text = ('{\n"classname" "worldspawn"\n"wad" "gfx.wad"\n{\n'
|
||||
"( 0 0 0 ) ( 0 1 0 ) ( 0 0 1 ) brick 0 0 0 1 1\n( 0 0 0 ) ( 0 0 1 ) ( 1 0 0 ) brick 0 0 0 1 1\n"
|
||||
"( 0 0 0 ) ( 1 0 0 ) ( 0 1 0 ) brick 0 0 0 1 1\n( 64 64 64 ) ( 64 65 64 ) ( 65 64 64 ) brick 0 0 0 1 1\n"
|
||||
"( 64 64 64 ) ( 65 64 64 ) ( 64 64 65 ) brick 0 0 0 1 1\n( 64 64 64 ) ( 64 64 65 ) ( 64 65 64 ) brick 0 0 0 1 1\n"
|
||||
'}\n}\n{\n"classname" "info_player_start"\n"origin" "32 32 32"\n}\n')
|
||||
res = H.compile(ctx, text, {"gfx.wad": wad2}, ["-nofill", "-noclip", "-nopercent"])
|
||||
b = H.read_bsp(res["bsp"])
|
||||
L = b["lumps"]["miptex"]
|
||||
o = struct.unpack_from("<i", L, 4)[0]
|
||||
out["bsp"] = {"miptex": L[o:o + 40 + 32 * 16 * 85 // 64]}
|
||||
ctx.emit("wad2", out)
|
||||
Reference in new issue
Block a user