merge ws/quake

This commit is contained in:
4DBug committed 2026-11-01 20:08:48 -06:00
commit 58df9e8a3a
39 files changed
+10044 -1413

No files matched your search

+190
View File
@@ -1982,3 +1982,193 @@ do
BuildMap.decode(Bytes.reader(map))
end)
end
do
local Xml = require("@rosetta/codecs/text/Xml")
local XB = require("@tests/gen/xml_bench")
local doc = assert(Xml.decode(XB.text))
bench("xml decode (DOM)", 5, #XB.text, function()
Xml.decode(XB.text)
end)
bench("xml events", 5, #XB.text, function()
for _ in Xml.events(XB.text) do
end
end)
bench("xml encode", 5, #XB.text, function()
Xml.encode(doc)
end)
end
-- ws-arch codecs: zstd, brotli, bzip2, xz / lzma
do
-- 3D (ws-3d): a 400 x 400 grid mesh (160k vertices, 318k triangles) through our own writers, then the readers; a
-- 128^3 noise voxel grid through VOX and greedy meshing
local Types = require("@rosetta/Types")
local MeshOps = require("@rosetta/ops/MeshOps")
local Gltf = require("@rosetta/model/gltf")
local Obj = require("@rosetta/model/obj")
local Stl = require("@rosetta/model/stl")
local Ply = require("@rosetta/model/ply")
local Vox = require("@rosetta/model/vox")
local N = 400
local pos = Types.Scene.accessor(nil, "f32", 3, N * N)
local uv = Types.Scene.accessor(nil, "f32", 2, N * N)
for y = 0, N - 1 do
for x = 0, N - 1 do
local i = y * N + x
buffer.writef32(pos.data, i * 12, x / N)
buffer.writef32(pos.data, i * 12 + 4, math.sin(x * 0.1) * math.cos(y * 0.1) * 0.05)
buffer.writef32(pos.data, i * 12 + 8, y / N)
buffer.writef32(uv.data, i * 8, x / N)
buffer.writef32(uv.data, i * 8 + 4, y / N)
end
end
local ind = Types.Scene.accessor(nil, "u32", 1, (N - 1) * (N - 1) * 6)
local k = 0
for y = 0, N - 2 do
for x = 0, N - 2 do
local a = y * N + x
for _, v in { a, a + N, a + 1, a + 1, a + N, a + N + 1 } do
buffer.writeu32(ind.data, k * 4, v)
k += 1
end
end
end
local prim = { attributes = { POSITION = pos, TEXCOORD_0 = uv }, indices = ind, mode = "triangles" } :: any
MeshOps.computeNormals(prim)
local scene = Types.Scene.fromPrimitive(prim, "grid")
bench("meshops computeNormals 318k tris", 3, buffer.len(pos.data), function()
MeshOps.computeNormals(prim)
end)
local glb = assert(Gltf.encode(scene, { binary = true }))
bench("gltf glb decode (" .. buffer.len(glb) // 1000 .. " KB)", 5, buffer.len(glb), function()
Gltf.decode(Bytes.reader(glb))
end)
bench("gltf glb encode", 3, buffer.len(glb), function()
Gltf.encode(scene, { binary = true })
end)
local obj = assert(Obj.encode(scene))
bench("obj decode (" .. buffer.len(obj) // 1000 .. " KB)", 2, buffer.len(obj), function()
Obj.decode(Bytes.reader(obj))
end)
bench("obj encode", 2, buffer.len(obj), function()
Obj.encode(scene)
end)
local stl = assert(Stl.encode(scene))
bench("stl binary decode (" .. buffer.len(stl) // 1000 .. " KB)", 5, buffer.len(stl), function()
Stl.decode(Bytes.reader(stl))
end)
local ply = assert(Ply.encode(scene))
bench("ply binary decode (" .. buffer.len(ply) // 1000 .. " KB)", 5, buffer.len(ply), function()
Ply.decode(Bytes.reader(ply))
end)
local Fbx = require("@rosetta/model/fbx")
local fbx = assert(Fbx.encode(scene))
bench("fbx binary decode (" .. buffer.len(fbx) // 1000 .. " KB)", 3, buffer.len(fbx), function()
Fbx.decode(Bytes.reader(fbx))
end)
bench("fbx binary encode (zlib arrays)", 2, buffer.len(fbx), function()
Fbx.encode(scene)
end)
bench("fbx binary encode (raw arrays)", 3, buffer.len(fbx), function()
Fbx.encode(scene, { compress = false })
end)
local fbxa = assert(Fbx.encode(scene, { ascii = true }))
bench("fbx ascii decode (" .. buffer.len(fbxa) // 1000 .. " KB)", 2, buffer.len(fbxa), function()
Fbx.decode(Bytes.reader(fbxa))
end)
local ThreeMf = require("@rosetta/model/3mf")
local tmf = assert(ThreeMf.encode(scene))
bench("3mf decode (" .. buffer.len(tmf) // 1000 .. " KB zipped)", 2, buffer.len(tmf), function()
ThreeMf.decode(Bytes.reader(tmf))
end)
bench("3mf encode", 2, buffer.len(tmf), function()
ThreeMf.encode(scene)
end)
local Wrl = require("@rosetta/model/vrml")
local X3d = require("@rosetta/model/x3d")
local wrl = assert(Wrl.encode(scene))
bench("vrml decode (" .. buffer.len(wrl) // 1000 .. " KB)", 2, buffer.len(wrl), function()
Wrl.decode(Bytes.reader(wrl))
end)
bench("vrml encode", 2, buffer.len(wrl), function()
Wrl.encode(scene)
end)
local x3d = assert(X3d.encode(scene))
bench("x3d xml decode (" .. buffer.len(x3d) // 1000 .. " KB)", 2, buffer.len(x3d), function()
X3d.decode(Bytes.reader(x3d))
end)
local V = 128
local grid = Types.Voxels.new(V, V, V)
for z = 0, V - 1 do
for y = 0, V - 1 do
for x = 0, V - 1 do
local h = (math.sin(x * 0.11) + math.cos(y * 0.07) + 2) * V / 8 + z * 0
if z < h then
Types.Voxels.set(grid, x, y, z, 1 + (x // 8 + y // 8) % 6)
end
end
end
end
local vox = assert(Vox.encode(grid))
bench("vox decode (" .. buffer.len(vox) // 1000 .. " KB)", 5, buffer.len(vox), function()
Vox.decode(Bytes.reader(vox))
end)
bench("greedy mesh 128^3 (MB of cells)", 3, V * V * V, function()
MeshOps.voxelsToPrimitive(grid)
end)
end
-- ------------------------------------------------------------------------------------------- ws-video2-flv: fps
do
-- H.263 / Sorenson Spark (codecs/video/H263, tools/fixtures/h263.py): CIF mandelbrot zooms (1 Mbit/s, an I picture
-- every 12), one picture per decode, planes only (frameImage copies excluded) and with the yuv420p Image copies
local H263 = require("@rosetta/codecs/video/H263")
local Base64 = require("@rosetta/core/Base64")
local HB = require("@tests/gen/h263_bench")
local function run(tag: string)
for _, c in HB do
local file = Base64.decode(c.file) :: buffer
for _, images in { false, true } do
local n = #c.units
local dt = bench(string.format("%s %dx%d%s%s", c.name, c.width, c.height, if images then " +img" else "", tag), 3, c.width * c.height * 3 // 2 * n, function()
local dec = H263.new({ flv = c.flv })
for _, u in c.units do
if images then
dec:image(file, u[1], u[2])
else
dec:decode(file, u[1], u[2])
end
end
end)
print(string.format("%-8s %-30s %8.1f fps", runtime, " (" .. n .. " frames)", n / dt))
end
end
end
jitTune(false)
run("")
if runtime == "luajit" then
jitTune(true)
run(" (jit tuned)")
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
+50 -1
View File
@@ -5,7 +5,7 @@
# 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
import math, os, shutil, struct, subprocess, tempfile
Q1_LUMPS = ["entities", "planes", "miptex", "vertices", "visibility", "nodes", "texinfo", "faces", "lighting",
"clipnodes", "leaves", "marksurfaces", "edges", "surfedges", "models"]
@@ -151,3 +151,52 @@ def face_plane(b, f):
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
+105 -4
View File
@@ -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)})
+49
View File
@@ -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",
})
+39
View File
@@ -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"]})
+117
View File
@@ -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})
+82
View File
@@ -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})
+77
View File
@@ -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)