merge ws/source: VBSP v19-21, VMF, KeyValues / data/vdf, codecs/model/Displacement (with ws/quake's Brush / Patch / Miptex)
This commit is contained in:
commit
e100366cb8
44 files changed
+18855
-1508
No files matched your search
@@ -219,6 +219,26 @@ do
|
||||
end)
|
||||
end
|
||||
|
||||
-- ws-source: KeyValues text (a 1 MB file of nested blocks) and an entity lump
|
||||
do
|
||||
local KeyValues = require("@rosetta/codecs/text/KeyValues")
|
||||
local parts = { '"root"\n{\n' }
|
||||
local ents = {}
|
||||
for i = 1, 6000 do
|
||||
table.insert(parts, string.format('\t"block%d"\n\t{\n\t\t"name"\t"item %d"\n\t\t"origin"\t"%d 0 64"\n\t\t"path"\t"models/props/x\\\\y.mdl"\n\t}\n', i, i, i))
|
||||
table.insert(ents, string.format('{\n"origin" "%d 0 64"\n"classname" "prop_dynamic"\n"OnTrigger" "a,b,,0,-1"\n}\n', i))
|
||||
end
|
||||
table.insert(parts, "}\n")
|
||||
local text, lump = table.concat(parts), table.concat(ents)
|
||||
assert(KeyValues.parse(text))
|
||||
bench("keyvalues parse", 5, #text, function()
|
||||
KeyValues.parse(text)
|
||||
end)
|
||||
bench("keyvalues entity lump", 5, #lump, function()
|
||||
KeyValues.entities(lump)
|
||||
end)
|
||||
end
|
||||
|
||||
-- ws-arch codecs: zstd, brotli, bzip2, xz / lzma
|
||||
do
|
||||
local Zstd = require("@rosetta/codecs/compress/Zstd")
|
||||
|
||||
@@ -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)
|
||||
@@ -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)
|
||||
@@ -0,0 +1,21 @@
|
||||
# Docs inputs for the Source engine sections of the scene page (tools/fixtures.py; tools/docs_check.py explains the
|
||||
# inputs): the CS:GO-style VBSP of tools/fixtures/vbsp.py (srctools-saved, static props v11) and the Hammer VMF of
|
||||
# tools/fixtures/vmf.py.
|
||||
# tests/gen/docs_source.luau { files = { [name] = bytes }, vars = { vbspBytes = "room.bsp", vmfText = "room.vmf" } }
|
||||
import importlib.util, json, os
|
||||
|
||||
INPUTS = ["tools/docs_check.py", "tools/fixtures/vbsp.py", "tools/fixtures/vmf.py"]
|
||||
|
||||
|
||||
def mod(ctx, name):
|
||||
spec = importlib.util.spec_from_file_location("fx_" + name, os.path.join(ctx.root, "tools", name + ".py") if name == "docs_check" else 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):
|
||||
res = json.loads(ctx.python(["srctools"], mod(ctx, "vbsp").CODE))
|
||||
files = {"room.bsp": next(bytes.fromhex(c["data"]) for c in res["cases"] if c["name"] == "csgo")}
|
||||
files["room.vmf"] = mod(ctx, "vmf").room().encode()
|
||||
mod(ctx, "docs_check").emit_inputs(ctx, files, {"vbspBytes": "room.bsp", "vmfText": "room.vmf"})
|
||||
@@ -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,305 @@
|
||||
# model/vbsp fixtures: a small Source map (a room of brush faces, a non-quad ceiling, a nodraw face, a power-3
|
||||
# displacement floor, a func_brush model, entities with repeated outputs, a pak lump) written here from the SDK's
|
||||
# bspfile.h layouts, then loaded and saved by srctools (BSP.save: static props in game lump versions 4 .. 11, LZMA
|
||||
# compressed lumps, the L4D2 lump header, a v19 header, a srctools-written entity lump). What srctools reads back from
|
||||
# each saved file is the reference: face polygons + texinfo projections, static props, entities, pak file names; the
|
||||
# displacement grid is tessellated here as CCoreDispInfo::GenerateDispSurf does.
|
||||
# tests/gen/vbsp.luau { cases = { { name, data, version, l4d2?, compressed?, props, entities, pak, groups } } }
|
||||
# groups: one per (model, material): { model, material, tris, verts = sorted "x y z u v" lines (%.2f) }.
|
||||
import json
|
||||
|
||||
CODE = r'''
|
||||
import io, json, math, os, struct, sys, tempfile, zipfile
|
||||
import srctools.bsp as B
|
||||
from srctools import Vec, Angle
|
||||
_out, sys.stdout = sys.stdout, sys.stderr # BSP.save prints
|
||||
|
||||
SURF_NODRAW = 0x80
|
||||
|
||||
def build():
|
||||
texdata = [("BRICK/BRICKWALL001A", 512, 512), ("TOOLS/TOOLSNODRAW", 64, 64), ("NATURE/BLENDGRASSDIRT", 256, 256)]
|
||||
texinfo = [ # s xyz shift, t xyz shift, flags, texdata
|
||||
((0.25, 0, 0, 16), (0, 0, -0.25, 8), 0, 0),
|
||||
((0, 0.25, 0, 0), (0, 0, -0.25, 0), 0, 0),
|
||||
((0.25, 0, 0, 0), (0, -0.25, 0, 0), 0, 0),
|
||||
((0.25, 0, 0, 0), (0, 0.25, 0, 0), SURF_NODRAW, 1),
|
||||
((0.125, 0, 0, 0), (0, -0.125, 0, 32), 0, 2),
|
||||
]
|
||||
verts, vindex = [], {}
|
||||
def v(p):
|
||||
p = tuple(float(x) for x in p)
|
||||
if p not in vindex:
|
||||
vindex[p] = len(verts)
|
||||
verts.append(p)
|
||||
return vindex[p]
|
||||
edges, eindex, surfedges = [(0, 0)], {}, []
|
||||
def poly_edges(poly):
|
||||
first = len(surfedges)
|
||||
ids = [v(p) for p in poly]
|
||||
for k in range(len(ids)):
|
||||
a, b = ids[k], ids[(k + 1) % len(ids)]
|
||||
if (b, a) in eindex:
|
||||
surfedges.append(-eindex[(b, a)])
|
||||
else:
|
||||
if (a, b) not in eindex:
|
||||
eindex[(a, b)] = len(edges)
|
||||
edges.append((a, b))
|
||||
surfedges.append(eindex[(a, b)])
|
||||
return first, len(ids)
|
||||
planes = []
|
||||
def plane(n, d):
|
||||
planes.append((n, d))
|
||||
return len(planes) - 1
|
||||
def newell(poly):
|
||||
nx = ny = nz = 0.0
|
||||
for k in range(len(poly)):
|
||||
x1, y1, z1 = poly[k]; x2, y2, z2 = poly[(k + 1) % len(poly)]
|
||||
nx += (y1 - y2) * (z1 + z2); ny += (z1 - z2) * (x1 + x2); nz += (x1 - x2) * (y1 + y2)
|
||||
l = math.sqrt(nx * nx + ny * ny + nz * nz)
|
||||
return (nx / l, ny / l, nz / l)
|
||||
faces = []
|
||||
def face(poly, ti, disp=-1, flip_side=False):
|
||||
# Source winding: clockwise seen from the front, so the front normal is minus Newell's
|
||||
n = tuple(-c for c in newell(poly))
|
||||
d = sum(a * b for a, b in zip(n, poly[0]))
|
||||
if flip_side:
|
||||
pn, side = plane(tuple(-c for c in n), -d), 1
|
||||
else:
|
||||
pn, side = plane(n, d), 0
|
||||
fe, ne = poly_edges(poly)
|
||||
faces.append(dict(plane=pn, side=side, firstedge=fe, numedges=ne, texinfo=ti, disp=disp))
|
||||
return len(faces) - 1
|
||||
S, H = 256.0, 256.0
|
||||
# inward-facing room walls: clockwise seen from inside
|
||||
face([(-S, -S, 0), (-S, -S, H), (S, -S, H), (S, -S, 0)], 0) # south wall, faces +y
|
||||
face([(S, S, 0), (S, S, H), (-S, S, H), (-S, S, 0)], 0, flip_side=True) # north wall, faces -y (plane side 1)
|
||||
face([(-S, S, 0), (-S, S, H), (-S, -S, H), (-S, -S, 0)], 1) # west, faces +x
|
||||
face([(S, -S, 0), (S, -S, H), (S, S, H), (S, S, 0)], 1) # east, faces -x
|
||||
# an octagonal ceiling facing down
|
||||
oc = []
|
||||
for k in range(8):
|
||||
a = -2 * math.pi * k / 8
|
||||
oc.append((round(S * math.cos(a), 3), round(S * math.sin(a), 3), H))
|
||||
face(list(reversed(oc)), 2)
|
||||
face([(-S, -S, H + 8), (S, -S, H + 8), (S, S, H + 8), (-S, S, H + 8)], 3) # nodraw
|
||||
# displacement floor facing up (clockwise seen from above), start position at its second corner
|
||||
floor = [(-S, -S, 0), (-S, S, 0), (S, S, 0), (S, -S, 0)]
|
||||
fdisp = face(floor, 4, disp=0)
|
||||
world_faces = len(faces)
|
||||
# func_brush: a 32-unit cube around its own origin, outward faces
|
||||
c = 16.0
|
||||
cube = [
|
||||
[(-c, -c, c), (-c, c, c), (c, c, c), (c, -c, c)],
|
||||
[(-c, -c, -c), (c, -c, -c), (c, c, -c), (-c, c, -c)],
|
||||
[(-c, -c, -c), (-c, -c, c), (c, -c, c), (c, -c, -c)],
|
||||
[(c, c, -c), (c, c, c), (-c, c, c), (-c, c, -c)],
|
||||
[(-c, c, -c), (-c, c, c), (-c, -c, c), (-c, -c, -c)],
|
||||
[(c, -c, -c), (c, -c, c), (c, c, c), (c, c, -c)],
|
||||
]
|
||||
for p in cube:
|
||||
face(p, 0)
|
||||
models = [((-S, -S, 0), (S, S, H + 8), (0, 0, 0), 0, world_faces), ((-c, -c, -c), (c, c, c), (0, 0, 0), world_faces, len(faces) - world_faces)]
|
||||
power = 3
|
||||
n = 2 ** power + 1
|
||||
dispverts = []
|
||||
for i in range(n):
|
||||
for j in range(n):
|
||||
dist = 24 * math.sin(i * 0.7) * math.cos(j * 0.5) + 8
|
||||
dispverts.append(((0.0, 0.0, 1.0) if dist >= 0 else (0.0, 0.0, -1.0), abs(dist), (i * 31 + j * 7) % 256))
|
||||
dispinfo = dict(start=floor[1], power=power, face=fdisp)
|
||||
ents = (
|
||||
'{\n"world_maxs" "256 256 264"\n"world_mins" "-256 -256 0"\n"skyname" "sky_day01_01"\n"mapversion" "7"\n"classname" "worldspawn"\n}\n'
|
||||
'{\n"origin" "0 0 64"\n"model" "*1"\n"targetname" "door"\n"classname" "func_brush"\n}\n'
|
||||
'{\n"origin" "-128 0 32"\n"angles" "0 90 0"\n"classname" "info_player_start"\n}\n'
|
||||
'{\n"origin" "0 0 200"\n"_light" "255 240 200 300"\n"classname" "light"\n}\n'
|
||||
'{\n"targetname" "relay"\n"OnTrigger" "door,Enable,,0,-1"\n"OnTrigger" "door,Disable,,5,-1"\n"classname" "logic_relay"\n}\n'
|
||||
)
|
||||
pak = io.BytesIO()
|
||||
with zipfile.ZipFile(pak, "w", zipfile.ZIP_STORED) as z:
|
||||
z.writestr("materials/maps/test/cubemapdefault.vtf", b"VTF\0" + bytes(60))
|
||||
z.writestr("materials/custom/note.txt", b"hello from the pak lump\n")
|
||||
return dict(texdata=texdata, texinfo=texinfo, verts=verts, edges=edges, surfedges=surfedges, planes=planes,
|
||||
faces=faces, models=models, dispverts=dispverts, dispinfo=dispinfo, ents=ents, pak=pak.getvalue())
|
||||
|
||||
def write(m, version=20):
|
||||
lumps = {}
|
||||
lumps[0] = m["ents"].encode() + b"\0"
|
||||
lumps[1] = b"".join(struct.pack("<3ffi", *n, d, 0) for n, d in m["planes"])
|
||||
names = b""
|
||||
table = []
|
||||
for name, w, h in m["texdata"]:
|
||||
table.append(len(names))
|
||||
names += name.encode() + b"\0"
|
||||
lumps[43] = names
|
||||
lumps[44] = b"".join(struct.pack("<i", o) for o in table)
|
||||
lumps[2] = b"".join(struct.pack("<3fiiiii", 0.5, 0.5, 0.5, i, w, h, w, h) for i, (name, w, h) in enumerate(m["texdata"]))
|
||||
lumps[3] = b"".join(struct.pack("<3f", *p) for p in m["verts"])
|
||||
lumps[6] = b"".join(struct.pack("<8f8fii", *s, *t, *(0.0625 * x for x in s), *(0.0625 * x for x in t), fl, td) for s, t, fl, td in m["texinfo"])
|
||||
fl, ofl = b"", b""
|
||||
for i, f in enumerate(m["faces"]):
|
||||
for orig in (False, True):
|
||||
rec = struct.pack("<HBBihhhh4BifiiiiiHHI", f["plane"], f["side"], 0, f["firstedge"], f["numedges"], f["texinfo"], f["disp"], -1,
|
||||
0, 255, 255, 255, -1, 0.0, 0, 0, 0, 0, -1 if orig else i, 0, 0, 0)
|
||||
if orig:
|
||||
ofl += rec
|
||||
else:
|
||||
fl += rec
|
||||
lumps[7] = fl
|
||||
lumps[27] = ofl
|
||||
lumps[12] = b"".join(struct.pack("<HH", a, b) for a, b in m["edges"])
|
||||
lumps[13] = b"".join(struct.pack("<i", s) for s in m["surfedges"])
|
||||
lumps[14] = b"".join(struct.pack("<9fiii", *mn, *mx, *o, 0, ff, nf) for mn, mx, o, ff, nf in m["models"])
|
||||
di = m["dispinfo"]
|
||||
n = 2 ** di["power"] + 1
|
||||
lumps[26] = struct.pack("<3fiiiifiHH ii", *di["start"], 0, 0, di["power"], 0, 0.0, 1, di["face"], 0, 0, 0) + bytes(176 - 48)
|
||||
lumps[33] = b"".join(struct.pack("<3fff", *vec, dist, alpha) for vec, dist, alpha in m["dispverts"])
|
||||
lumps[35] = struct.pack("<i", 0)
|
||||
lumps[40] = m["pak"]
|
||||
out = bytearray(1036)
|
||||
struct.pack_into("<4si", out, 0, b"VBSP", version)
|
||||
for i in range(64):
|
||||
data = lumps.get(i, b"")
|
||||
off = len(out) if data else 0
|
||||
if i == 35:
|
||||
sprp = struct.pack("<iii", 0, 0, 0)
|
||||
data = struct.pack("<i4sHHii", 1, b"prps", 0, 5, off + 20, len(sprp)) + sprp
|
||||
struct.pack_into("<iiii", out, 8 + i * 16, off, len(data), 0, 0)
|
||||
out += data
|
||||
while len(out) % 4:
|
||||
out += b"\0"
|
||||
struct.pack_into("<i", out, 1032, 7)
|
||||
return bytes(out)
|
||||
|
||||
PROPS = [
|
||||
("models/props_junk/wood_crate001a.mdl", (64, 32, 0), (0, 45, 0), 1.0, 0),
|
||||
("models/props_c17/oildrum001.mdl", (-96, 80, 0), (10, 0, 5), 1.5, 1),
|
||||
("models/props_junk/wood_crate001a.mdl", (100, -100, 16), (-30, 200, 90), 0.5, 2),
|
||||
]
|
||||
|
||||
def variant(base, name, version=None, sp=B.StaticPropVersion.V5, compress=False, l4d2=False, rewrite_ents=False):
|
||||
d = tempfile.mkdtemp()
|
||||
p = os.path.join(d, "base.bsp")
|
||||
open(p, "wb").write(base)
|
||||
bsp = B.BSP(p)
|
||||
if l4d2:
|
||||
bsp.game_ver = B.GameVersion.L4D2
|
||||
if version is not None:
|
||||
bsp.version = version
|
||||
bsp.static_prop_version = sp
|
||||
bsp.game_lumps[b"sprp"].version = sp.version
|
||||
bsp.props = [B.StaticProp(model, Vec(*o), Angle(*a), scaling=s, skin=k, visleafs=set()) for model, o, a, s, k in PROPS]
|
||||
if rewrite_ents:
|
||||
bsp.ents
|
||||
if compress:
|
||||
for lump in bsp.lumps.values():
|
||||
if lump.data and lump.type is not B.BSP_LUMPS.PAKFILE and lump.type is not B.BSP_LUMPS.GAME_LUMP:
|
||||
lump.is_compressed = True
|
||||
for gl in bsp.game_lumps.values():
|
||||
gl.is_compressed = True
|
||||
out = os.path.join(d, name + ".bsp")
|
||||
bsp.save(out)
|
||||
return open(out, "rb").read()
|
||||
|
||||
def tessellate(m):
|
||||
di = m["dispinfo"]
|
||||
f = m["faces"][di["face"]]
|
||||
corners = []
|
||||
for k in range(f["numedges"]):
|
||||
se = m["surfedges"][f["firstedge"] + k]
|
||||
a, b = m["edges"][abs(se)]
|
||||
corners.append(m["verts"][a if se >= 0 else b])
|
||||
start = min(range(4), key=lambda k: sum((corners[k][i] - di["start"][i]) ** 2 for i in range(3)))
|
||||
p = corners[start:] + corners[:start]
|
||||
n = 2 ** di["power"] + 1
|
||||
out = []
|
||||
lerp = lambda a, b, t: tuple(a[i] + (b[i] - a[i]) * t for i in range(3))
|
||||
for i in range(n):
|
||||
e0 = lerp(p[0], p[1], i / (n - 1))
|
||||
e1 = lerp(p[3], p[2], i / (n - 1))
|
||||
for j in range(n):
|
||||
base = lerp(e0, e1, j / (n - 1))
|
||||
vec, dist, alpha = m["dispverts"][i * n + j]
|
||||
dist = struct.unpack("<f", struct.pack("<f", dist))[0]
|
||||
out.append((base, tuple(base[k] + vec[k] * dist for k in range(3))))
|
||||
return out
|
||||
|
||||
def reference(data, m):
|
||||
d = tempfile.mkdtemp()
|
||||
p = os.path.join(d, "x.bsp")
|
||||
open(p, "wb").write(data)
|
||||
bsp = B.BSP(p)
|
||||
groups = {}
|
||||
model_of = {}
|
||||
raw = bsp.lumps[B.BSP_LUMPS.MODELS].data
|
||||
faces = bsp.faces
|
||||
for mi in range(len(raw) // 48):
|
||||
ff, nf = struct.unpack_from("<ii", raw, mi * 48 + 40)
|
||||
for fi in range(ff, ff + nf):
|
||||
model_of[fi] = mi
|
||||
disp = tessellate(m)
|
||||
for fi, f in enumerate(faces):
|
||||
ti = f.texinfo
|
||||
if ti.flags.value & SURF_NODRAW:
|
||||
continue
|
||||
mat = ti.mat
|
||||
w, h = ti.tex_size
|
||||
key = (model_of[fi], mat)
|
||||
g = groups.setdefault(key, {"model": model_of[fi], "material": mat, "tris": 0, "verts": []})
|
||||
def uv(pos):
|
||||
u = (pos[0] * ti.s_off.x + pos[1] * ti.s_off.y + pos[2] * ti.s_off.z + ti.s_shift) / w
|
||||
v = (pos[0] * ti.t_off.x + pos[1] * ti.t_off.y + pos[2] * ti.t_off.z + ti.t_shift) / h
|
||||
return u, v
|
||||
if f._dispinfo_ind >= 0:
|
||||
pw = 2 ** m["dispinfo"]["power"]
|
||||
g["tris"] += 2 * pw * pw
|
||||
for base, pos in disp:
|
||||
g["verts"].append("%.2f %.2f %.2f %.2f %.2f" % (*pos, *uv(base)))
|
||||
else:
|
||||
poly = [e.a for e in f.edges]
|
||||
g["tris"] += len(poly) - 2
|
||||
for q in poly:
|
||||
g["verts"].append("%.2f %.2f %.2f %.2f %.2f" % (q.x, q.y, q.z, *uv((q.x, q.y, q.z))))
|
||||
for g in groups.values():
|
||||
g["verts"] = "\n".join(sorted(g["verts"]))
|
||||
props = [{"model": sp.model, "origin": list(sp.origin), "angles": [sp.angles.pitch, sp.angles.yaw, sp.angles.roll],
|
||||
"skin": sp.skin, "scale": sp.scaling if isinstance(sp.scaling, float) else sp.scaling.x} for sp in bsp.props]
|
||||
ents = [bsp.ents.spawn] + list(bsp.ents.entities)
|
||||
outputs = sum(len(e.outputs) for e in ents)
|
||||
pak = sorted(bsp.pakfile.namelist())
|
||||
return {"groups": sorted(groups.values(), key=lambda g: (g["model"], g["material"])), "props": props,
|
||||
"entities": len(ents), "outputs": outputs, "classnames": sorted(e["classname"] for e in ents), "pak": pak,
|
||||
"spversion": bsp.static_prop_version.version}
|
||||
|
||||
m = build()
|
||||
base = write(m)
|
||||
cases = []
|
||||
V = B.StaticPropVersion
|
||||
for name, kw in [
|
||||
("v20", dict(sp=V.V6)),
|
||||
("v19", dict(version=19, sp=V.V4)),
|
||||
("v20_v5", dict(sp=V.V5)),
|
||||
("v20_lzma", dict(sp=V.V10, compress=True)),
|
||||
("tf2_v7", dict(sp=V.V7)),
|
||||
("l4d2", dict(version=B.VERSIONS.L4D2, sp=V.V9, l4d2=True)),
|
||||
("csgo", dict(version=21, sp=V.V11)),
|
||||
("csgo_lzma", dict(version=21, sp=V.V11, compress=True)),
|
||||
("l4d_v8", dict(version=20, sp=V.V8)),
|
||||
("srctools_ents", dict(sp=V.V5, rewrite_ents=True)),
|
||||
]:
|
||||
data = variant(base, name, **kw)
|
||||
ref = reference(data, m)
|
||||
ref.update({"name": name, "data": data.hex(), "version": struct.unpack_from("<i", data, 4)[0], "l4d2": bool(kw.get("l4d2")), "compressed": bool(kw.get("compress"))})
|
||||
cases.append(ref)
|
||||
_out.write(json.dumps({"cases": cases, "plain": base.hex()}))
|
||||
'''
|
||||
|
||||
|
||||
def generate(ctx):
|
||||
res = json.loads(ctx.python(["srctools"], CODE))
|
||||
cases = []
|
||||
for c in res["cases"]:
|
||||
c["data"] = bytes.fromhex(c["data"])
|
||||
for g in c["groups"]:
|
||||
g["verts"] = g["verts"].encode()
|
||||
cases.append(c)
|
||||
ctx.emit("vbsp", {"cases": cases, "plain": bytes.fromhex(res["plain"])})
|
||||
@@ -0,0 +1,150 @@
|
||||
# model/vmf fixtures: the Hammer-written VMFs of srctools' test suite (MIT; read from the nix srctools source, not
|
||||
# committed) with every solid's polygons as srctools.geometry clips them, and a VMF written here in Hammer's layout
|
||||
# (a room whose floor is the power-3 displacement of tools/fixtures/vbsp.py, a func_detail, a prop_static, outputs,
|
||||
# nested visgroups, a group, cameras, hidden objects) with what srctools.vmf reads from it.
|
||||
# tests/gen/vmf.luau { files = { { name, data, solids = { canon } } }, room = { data, entities, outputs, visgroups,
|
||||
# cameras, solids, disp } }
|
||||
# canon: a solid's polygons, each its corners "%.2f %.2f %.2f" sorted and joined by ";", sorted and joined by "|".
|
||||
import json, math, os, subprocess, tarfile
|
||||
|
||||
CODE = r'''
|
||||
import json, sys
|
||||
from srctools.vmf import VMF
|
||||
from srctools.keyvalues import Keyvalues
|
||||
from srctools.geometry import Geometry
|
||||
_out, sys.stdout = sys.stdout, sys.stderr
|
||||
inp = json.loads(sys.stdin.read())
|
||||
|
||||
def f2(x):
|
||||
s = "%.2f" % x
|
||||
return "0.00" if s == "-0.00" else s
|
||||
|
||||
def canon(solid):
|
||||
polys = []
|
||||
for p in Geometry.from_brush(solid).polys:
|
||||
polys.append(";".join(sorted("%s %s %s" % (f2(v.x), f2(v.y), f2(v.z)) for v in p.vertices)))
|
||||
return "|".join(sorted(polys))
|
||||
|
||||
res = {"files": [], "room": None}
|
||||
for name, text in inp["files"]:
|
||||
vmf = VMF.parse(Keyvalues.parse(text))
|
||||
solids = [canon(s) for s in vmf.brushes] + [canon(s) for e in vmf.entities for s in e.solids]
|
||||
res["files"].append({"name": name, "solids": solids})
|
||||
vmf = VMF.parse(Keyvalues.parse(inp["room"]))
|
||||
ents = [vmf.spawn] + list(vmf.entities)
|
||||
def visnames(tree):
|
||||
out = []
|
||||
for v in tree:
|
||||
out.append(v.name)
|
||||
out += visnames(v.child_groups)
|
||||
return out
|
||||
res["room"] = {
|
||||
"entities": len(ents),
|
||||
"outputs": sum(len(e.outputs) for e in ents),
|
||||
"visgroups": sorted(visnames(vmf.vis_tree)),
|
||||
"cameras": len(vmf.cameras),
|
||||
"solids": sorted(canon(s) for s in list(vmf.brushes) + [s for e in vmf.entities for s in e.solids]),
|
||||
}
|
||||
_out.write(json.dumps(res))
|
||||
'''
|
||||
|
||||
S, H = 256, 256
|
||||
|
||||
|
||||
def side(i, a, b, c, mat, u, v, extra=""):
|
||||
return ('\t\tside\n\t\t{\n\t\t\t"id" "%d"\n\t\t\t"plane" "(%g %g %g) (%g %g %g) (%g %g %g)"\n\t\t\t"material" "%s"\n'
|
||||
'\t\t\t"uaxis" "[%g %g %g 0] 0.25"\n\t\t\t"vaxis" "[%g %g %g 0] 0.25"\n\t\t\t"rotation" "0"\n'
|
||||
'\t\t\t"lightmapscale" "16"\n\t\t\t"smoothing_groups" "0"\n%s\t\t}\n') % (i, *a, *b, *c, mat, *u, *v, extra)
|
||||
|
||||
|
||||
def box(sid, lo, hi, mat, top=None, extra_top=""):
|
||||
(x0, y0, z0), (x1, y1, z1) = lo, hi
|
||||
m = lambda k: top if (k == 0 and top) else mat
|
||||
sides = [
|
||||
side(sid + 1, (x0, y1, z1), (x1, y1, z1), (x1, y0, z1), m(0), (1, 0, 0), (0, -1, 0), extra_top),
|
||||
side(sid + 2, (x0, y0, z0), (x1, y0, z0), (x1, y1, z0), mat, (1, 0, 0), (0, -1, 0)),
|
||||
side(sid + 3, (x0, y1, z0), (x0, y1, z1), (x0, y0, z1), mat, (0, 1, 0), (0, 0, -1)),
|
||||
side(sid + 4, (x1, y0, z0), (x1, y0, z1), (x1, y1, z1), mat, (0, 1, 0), (0, 0, -1)),
|
||||
side(sid + 5, (x1, y1, z0), (x1, y1, z1), (x0, y1, z1), mat, (1, 0, 0), (0, 0, -1)),
|
||||
side(sid + 6, (x0, y0, z0), (x0, y0, z1), (x1, y0, z1), mat, (1, 0, 0), (0, 0, -1)),
|
||||
]
|
||||
return '\tsolid\n\t{\n\t\t"id" "%d"\n%s\t\teditor\n\t\t{\n\t\t\t"color" "0 180 0"\n\t\t\t"visgroupid" "2"\n\t\t\t"groupid" "40"\n\t\t\t"visgroupshown" "1"\n\t\t\t"visgroupautoshown" "1"\n\t\t}\n\t}\n' % (sid, "".join(sides))
|
||||
|
||||
|
||||
def dispinfo():
|
||||
power = 3
|
||||
n = 2 ** power + 1
|
||||
rows = lambda f, ind="\t\t\t\t": "".join('%s"row%d" "%s"\n' % (ind, i, " ".join(f(i, j) for j in range(n))) for i in range(n))
|
||||
dist = lambda i, j: 24 * math.sin(i * 0.7) * math.cos(j * 0.5) + 8
|
||||
out = ('\t\t\tdispinfo\n\t\t\t{\n\t\t\t\t"power" "3"\n\t\t\t\t"startposition" "[%g %g 0]"\n\t\t\t\t"flags" "0"\n'
|
||||
'\t\t\t\t"elevation" "0"\n\t\t\t\t"subdiv" "0"\n') % (-S, S)
|
||||
out += "\t\t\t\tnormals\n\t\t\t\t{\n" + rows(lambda i, j: "0 0 1" if dist(i, j) >= 0 else "0 0 -1", "\t\t\t\t") + "\t\t\t\t}\n"
|
||||
out += "\t\t\t\tdistances\n\t\t\t\t{\n" + rows(lambda i, j: "%.9g" % abs(dist(i, j)), "\t\t\t\t") + "\t\t\t\t}\n"
|
||||
out += "\t\t\t\toffsets\n\t\t\t\t{\n" + rows(lambda i, j: "0 0 0", "\t\t\t\t") + "\t\t\t\t}\n"
|
||||
out += "\t\t\t\toffset_normals\n\t\t\t\t{\n" + rows(lambda i, j: "0 0 1", "\t\t\t\t") + "\t\t\t\t}\n"
|
||||
out += "\t\t\t\talphas\n\t\t\t\t{\n" + rows(lambda i, j: "%d" % ((i * 31 + j * 7) % 256), "\t\t\t\t") + "\t\t\t\t}\n"
|
||||
out += '\t\t\t\tallowed_verts\n\t\t\t\t{\n\t\t\t\t"10" "-1 -1 -1 -1 -1 -1 -1 -1 -1 -1"\n\t\t\t\t}\n\t\t\t}\n'
|
||||
return out
|
||||
|
||||
|
||||
def room():
|
||||
world = ""
|
||||
world += box(10, (-S, -S, -16), (S, S, 0), "TOOLS/TOOLSNODRAW", top="NATURE/BLENDGRASSDIRT", extra_top=dispinfo())
|
||||
world += box(20, (-S, -S - 16, 0), (S, -S, H), "BRICK/BRICKWALL001A")
|
||||
world += box(30, (-S, S, 0), (S, S + 16, H), "BRICK/BRICKWALL001A")
|
||||
hidden = box(40, (S, -S, 0), (S + 16, S, H), "BRICK/BRICKWALL001A")
|
||||
hidden = "\thidden\n\t{\n" + "\n".join("\t" + l if l else l for l in hidden.split("\n")) + "\t}\n"
|
||||
detail = box(50, (-16, -16, 0), (16, 16, 32), "BRICK/BRICKWALL001A").replace("\n\t", "\n").replace("\tsolid", "solid", 1)
|
||||
detail = "\n".join("\t" + l if l else l for l in detail.split("\n"))
|
||||
text = ('versioninfo\n{\n\t"editorversion" "400"\n\t"editorbuild" "8864"\n\t"mapversion" "3"\n\t"formatversion" "100"\n\t"prefab" "0"\n}\n'
|
||||
'visgroups\n{\n\tvisgroup\n\t{\n\t\t"name" "Walls"\n\t\t"visgroupid" "1"\n\t\t"color" "200 100 0"\n\t\tvisgroup\n\t\t{\n'
|
||||
'\t\t\t"name" "North"\n\t\t\t"visgroupid" "2"\n\t\t\t"color" "0 100 200"\n\t\t}\n\t}\n}\n'
|
||||
'viewsettings\n{\n\t"bSnapToGrid" "1"\n\t"bShowGrid" "1"\n\t"nGridSpacing" "16"\n}\n'
|
||||
'world\n{\n\t"id" "1"\n\t"mapversion" "3"\n\t"classname" "worldspawn"\n\t"skyname" "sky_day01_01"\n'
|
||||
+ world + hidden +
|
||||
'\tgroup\n\t{\n\t\t"id" "40"\n\t\teditor\n\t\t{\n\t\t\t"color" "0 180 0"\n\t\t\t"visgroupshown" "1"\n\t\t\t"visgroupautoshown" "1"\n\t\t}\n\t}\n}\n'
|
||||
'entity\n{\n\t"id" "60"\n\t"classname" "func_detail"\n' + detail + '}\n'
|
||||
'entity\n{\n\t"id" "70"\n\t"classname" "prop_static"\n\t"angles" "0 45 0"\n\t"model" "models/props_junk/wood_crate001a.mdl"\n'
|
||||
'\t"skin" "0"\n\t"origin" "64 32 0"\n\teditor\n\t{\n\t\t"color" "255 255 0"\n\t\t"visgroupshown" "1"\n\t\t"visgroupautoshown" "1"\n'
|
||||
'\t\t"logicalpos" "[0 0]"\n\t}\n}\n'
|
||||
'entity\n{\n\t"id" "80"\n\t"classname" "logic_relay"\n\t"targetname" "relay"\n\tconnections\n\t{\n'
|
||||
'\t\t"OnTrigger" "door,Open,,0,-1"\n\t\t"OnTrigger" "door,Close,,5,-1"\n\t\t"OnSpawn" "relay,Trigger,,1,1"\n\t}\n'
|
||||
'\t"origin" "0 0 128"\n}\n'
|
||||
'entity\n{\n\t"id" "90"\n\t"classname" "info_player_start"\n\t"angles" "0 90 0"\n\t"origin" "-128 0 8"\n}\n'
|
||||
'cameras\n{\n\t"activecamera" "0"\n\tcamera\n\t{\n\t\t"position" "[-200 -200 128]"\n\t\t"look" "[0 0 64]"\n\t}\n'
|
||||
'\tcamera\n\t{\n\t\t"position" "[200 0 64]"\n\t\t"look" "[0 0 64]"\n\t}\n}\n'
|
||||
'cordons\n{\n\t"active" "0"\n}\n')
|
||||
return text
|
||||
|
||||
|
||||
def disp_expected():
|
||||
# tools/fixtures/vbsp.py: the floor corners clockwise from above, corner 0 nearest the start
|
||||
power, n = 3, 9
|
||||
p = [(-S, S, 0), (S, S, 0), (S, -S, 0), (-S, -S, 0)]
|
||||
out = []
|
||||
for i in range(n):
|
||||
e0 = [p[0][k] + (p[1][k] - p[0][k]) * i / (n - 1) for k in range(3)]
|
||||
e1 = [p[3][k] + (p[2][k] - p[3][k]) * i / (n - 1) for k in range(3)]
|
||||
for j in range(n):
|
||||
b = [e0[k] + (e1[k] - e0[k]) * j / (n - 1) for k in range(3)]
|
||||
d = float("%.9g" % (24 * math.sin(i * 0.7) * math.cos(j * 0.5) + 8))
|
||||
out.append("%.2f %.2f %.2f" % (b[0], b[1], b[2] + d))
|
||||
return "\n".join(sorted(out))
|
||||
|
||||
|
||||
def generate(ctx):
|
||||
src = subprocess.run(["nix", "build", "--no-link", "--print-out-paths", "--impure", "--expr",
|
||||
"with import <nixpkgs> {}; python3Packages.srctools.src"], capture_output=True, check=True).stdout.decode().strip()
|
||||
files = []
|
||||
with tarfile.open(src) as tf:
|
||||
for m in tf.getmembers():
|
||||
base = os.path.basename(m.name)
|
||||
if m.isfile() and base.endswith(".vmf") and ("/test_geometry/" in m.name or "/test_vmf/" in m.name) and base != "test_merge.vmf":
|
||||
files.append((base, tf.extractfile(m).read().decode("utf-8")))
|
||||
files.sort()
|
||||
text = room()
|
||||
res = json.loads(ctx.python(["srctools"], CODE, input=json.dumps({"files": files, "room": text}).encode()))
|
||||
out = [{"name": n, "data": d.encode(), "solids": r["solids"]} for (n, d), r in zip(files, res["files"])]
|
||||
r = res["room"]
|
||||
r.update({"data": text.encode(), "disp": disp_expected()})
|
||||
ctx.emit("vmf", {"files": out, "room": r})
|
||||
Reference in new issue
Block a user