merge ws/idtech: UDMF (codecs/model/DoomMap), Doom 3 / Quake 4 .map + .proc, Wolf3D VSWAP + GAMEMAPS, codecs/text/Lexer

This commit is contained in:
4DBug committed 2026-11-01 19:48:30 -06:00
commit 0e0b213a80
38 files changed
+11791 -2566

No files matched your search

+21
View File
@@ -1278,6 +1278,27 @@ do
Wad.map(w, "MAP01", { textures = false })
end)
end
do
-- id Tech text (ws-idtech): Freedoom MAP01 as a UDMF TEXTMAP (tools/fixtures/udmf.py) parsed to tables and built
-- into a Scene, a Doom 3 .proc (tools/fixtures/proc.py) to a Scene; MB/s of text
local DoomMap = require("@rosetta/codecs/model/DoomMap")
local Udmf = require("@rosetta/model/udmf")
local Proc = require("@rosetta/model/proc")
local UD = require("@tests/gen/udmf")
local PR = require("@tests/gen/proc")
bench("udmf MAP01 TEXTMAP -> tables", 3, #UD.text, function()
DoomMap.udmf(UD.text)
end)
local ub = buffer.fromstring(UD.text)
bench("udmf MAP01 TEXTMAP -> Scene", 3, #UD.text, function()
Udmf.decode(Bytes.reader(ub))
end)
local big = PR.doom3.text
local pb = buffer.fromstring(big)
bench("proc (" .. #big .. " B) -> Scene", 20, #big, function()
Proc.decode(Bytes.reader(pb))
end)
end
do
-- Draco (codecs/model/Draco): the Stanford bunny (35k points, 69k faces, Edgebreaker valence, normals) and a UV
-- sphere with seams; MB/s of decoded output (u32 indices + f32 attributes per point), plus triangles per second.
+163
View File
@@ -0,0 +1,163 @@
# Doom 3 / Quake 4 .map fixtures (tools/fixtures.py). Doom 3's maps are not redistributable, so the map is written here
# in the editor's layout (the Doom 3 GPL source docs' idMapFile text, read for the layout; no code taken): a box and a
# random convex brush in worldspawn (every side its own material), a func_static with a box, a patchDef3 and a
# patchDef2, a light with a rotation matrix, a player start with an angle, and a Quake III brushDef (skipped). The
# reference: scipy's HalfspaceIntersection (qhull) per brush -> the area of every side; the side's texture vectors by
# Doom 3's ComputeAxisBase + texture matrix; the patchDef3 grid by evaluating the biquadratic Bezier sub-patches.
# tests/gen/d3map.luau { doom3 = <text>, quake4 = <text>, sides = { { material, area, vecs = { 8 } } },
# patch3 = { width, height, points = { x, y, z, ... } }, ... }
import json, math
REF = r"""
import json, sys
import numpy as np
from scipy.spatial import HalfspaceIntersection, ConvexHull
brushes = json.loads(sys.stdin.read())
out = []
for b in brushes:
hs = np.array([s["plane"] for s in b["sides"]], dtype=float)
hi = HalfspaceIntersection(hs, np.array(b["inside"], dtype=float))
pts = hi.intersections
vol = ConvexHull(pts).volume
for s in b["sides"]:
n, d = np.array(s["plane"][:3], dtype=float), s["plane"][3]
on = pts[np.abs(pts @ n + d) < 1e-6]
area = 0.0
if len(on) >= 3:
u = np.cross(n, [1, 0, 0] if abs(n[0]) < 0.9 else [0, 1, 0]); u /= np.linalg.norm(u)
v = np.cross(n, u)
q = np.stack([on @ u, on @ v], axis=1)
q = np.unique(np.round(q, 9), axis=0)
if len(q) >= 3:
area = ConvexHull(q).volume
out.append({"material": s["material"], "area": area})
out.append({"volume": vol})
print(json.dumps(out))
"""
def axis_base(n):
rot_y = -math.atan2(n[2], math.sqrt(n[1] * n[1] + n[0] * n[0]))
rot_z = math.atan2(n[1], n[0])
s = (-math.sin(rot_z), math.cos(rot_z), 0.0)
t = (-math.sin(rot_y) * math.cos(rot_z), -math.sin(rot_y) * math.sin(rot_z), -math.cos(rot_y))
return s, t
def vecs(n, m):
s, t = axis_base(n)
out = []
for i in range(2):
out += [s[k] * m[i][0] + t[k] * m[i][1] for k in range(3)] + [m[i][2]]
return out
def box(x0, y0, z0, x1, y1, z1):
return [((-1, 0, 0), x0), ((1, 0, 0), -x1), ((0, -1, 0), y0), ((0, 1, 0), -y1), ((0, 0, -1), z0), ((0, 0, 1), -z1)]
def g(v):
return repr(round(v, 9)).rstrip("0").rstrip(".") if isinstance(v, float) else str(v)
def bezier(ctrl, w, h, su, sv):
# ctrl[row][col] = (x, y, z, s, t); sub-patches of 3 x 3; su / sv segments per sub-patch
def b(t):
return ((1 - t) ** 2, 2 * t * (1 - t), t * t)
gw, gh = (w - 1) // 2 * su + 1, (h - 1) // 2 * sv + 1
pts = []
for gy in range(gh):
py, ty = min(gy // sv, (h - 1) // 2 - 1), None
ty = gy / sv - py
for gx in range(gw):
px = min(gx // su, (w - 1) // 2 - 1)
tx = gx / su - px
bu, bv = b(tx), b(ty)
p = [0.0] * 3
for j in range(3):
for i in range(3):
c = ctrl[py * 2 + j][px * 2 + i]
for k in range(3):
p[k] += bv[j] * bu[i] * c[k]
pts += p
return gw, gh, pts
def generate(ctx):
rng = ctx.rng(3)
brushes = []
sides = []
def brush(planes, inside, tag):
b = {"inside": inside, "sides": []}
for k, (n, d) in enumerate(planes):
m = [[rng.choice([1 / 64, 1 / 128, -1 / 128]), rng.uniform(-0.01, 0.01), rng.uniform(-1, 1)],
[rng.uniform(-0.01, 0.01), rng.choice([1 / 64, 1 / 128]), rng.uniform(-1, 1)]]
mat = "textures/test/%s_%d" % (tag, k)
b["sides"].append({"plane": [n[0], n[1], n[2], d], "material": mat, "m": m, "vecs": vecs(n, m)})
brushes.append(b)
return b
world = [brush(box(-128, -128, -16, 128, 128, 0), [0, 0, -8], "box")]
planes = []
cx, cy, cz = 200.0, 0.0, 64.0
for _ in range(12):
z = rng.uniform(-1, 1)
a = rng.uniform(0, 2 * math.pi)
n = (math.sqrt(1 - z * z) * math.cos(a), math.sqrt(1 - z * z) * math.sin(a), z)
r = rng.uniform(40, 64)
planes.append((n, -(n[0] * cx + n[1] * cy + n[2] * cz) - r))
for n, d in box(cx - 100, cy - 100, cz - 100, cx + 100, cy + 100, cz + 100):
planes.append((n, d))
world.append(brush(planes, [cx, cy, cz], "rnd"))
crate = brush(box(-16, 284, 0, 16, 316, 32), [0, 300, 16], "crate")
def side_text(s):
p = s["plane"]
m = s["m"]
return ' ( %s %s %s %s ) ( ( %s %s %s ) ( %s %s %s ) ) "%s" 0 0 0' % tuple(
[g(float(x)) for x in p] + [g(float(x)) for x in m[0]] + [g(float(x)) for x in m[1]] + [s["material"]])
def brush_text(i, b):
return "// primitive %d\n{\n brushDef3\n {\n%s\n }\n}" % (i, "\n".join(side_text(s) for s in b["sides"]))
# patchDef3: 3 x 3, a bump; patchDef2: 5 wide x 3 high, a half pipe
p3 = [[(x * 32.0, 300 + y * 32.0, 40 + (16.0 if x == 0 and y == 0 else 0.0), (x + 1) / 2, (y + 1) / 2) for x in (-1, 0, 1)] for y in (-1, 0, 1)]
p2 = [[(-64 + x * 32.0, 400 + y * 64.0, 64 * abs(math.cos(x * math.pi / 4)), x / 4, y / 2) for x in range(5)] for y in range(3)]
def patch_text(kind, ctrl, info):
h, w = len(ctrl), len(ctrl[0])
cols = []
for i in range(w):
cols.append(" ( " + " ".join("( %s )" % " ".join(g(float(v)) for v in ctrl[j][i]) for j in range(h)) + " )")
return '{\n %s\n {\n "textures/test/%s"\n ( %s )\n (\n%s\n )\n }\n}' % (kind, kind, " ".join(str(x) for x in info), "\n".join(cols))
def text(version):
out = ["Version %d" % version, "// entity 0", "{", '"classname" "worldspawn"']
for i, b in enumerate(world):
out.append(brush_text(i, b))
out.append("// primitive 2\n{\nbrushDef\n{\n( ( 0.0078125 0 0 ) ( 0 0.0078125 0 ) ) common/caulk 0 0 0\n}\n}")
out.append("}")
out += ["// entity 1", "{", '"classname" "func_static"', '"name" "crate"', '"origin" "0 300 16"', '"model" "crate"',
brush_text(0, crate), patch_text("patchDef3", p3, [3, 3, 4, 4, 0, 0, 0]),
patch_text("patchDef2", p2, [5, 3, 0, 0, 0]), "}"]
out += ["// entity 2", "{", '"classname" "light"', '"name" "light_1"', '"origin" "10 20 30"',
'"rotation" "0 1 0 -1 0 0 0 0 1"', '"light_radius" "300 300 300"', "}"]
out += ["// entity 3", "{", '"classname" "info_player_start"', '"name" "info_player_start_1"', '"origin" "-64 0 1"',
'"angle" "90"', "}"]
return "\n".join(out) + "\n"
ref = json.loads(ctx.python(["numpy", "scipy"], REF, input=json.dumps(
[{"inside": b["inside"], "sides": [{"plane": s["plane"], "material": s["material"]} for s in b["sides"]]} for b in brushes]).encode()))
vols = [r["volume"] for r in ref if "volume" in r]
areas = [r for r in ref if "volume" not in r]
k = 0
for b in brushes:
for s in b["sides"]:
assert areas[k]["material"] == s["material"]
sides.append({"material": s["material"], "area": areas[k]["area"], "vecs": s["vecs"]})
k += 1
gw, gh, pts = bezier([[c for c in row] for row in p3], 3, 3, 4, 4)
ctx.emit("d3map", {"doom3": text(2), "quake4": text(3), "sides": sides, "volumes": vols,
"patch3": {"width": gw, "height": gh, "points": pts},
"patch2": {"corners": list(p2[0][0][:3]) + list(p2[2][4][:3])}})
+70
View File
@@ -0,0 +1,70 @@
# Docs inputs for the id Tech sections of the scene / tilemap / archive pages (tools/fixtures.py; tools/docs_check.py
# explains the inputs), a hand-written Doom 3 .map, and inputs made by the format fixtures' writers: the hand-written UDMF room (udmf.py), a dmap-layout
# .proc (proc.py), a VSWAP and a one-map GAMEMAPS + MAPHEAD with a random palette (wolf3d.py).
# tests/gen/docs_idtech.luau { files = { [name] = bytes }, vars = { udmfText = "room.udmf", ... } }
import importlib.util, os, struct
INPUTS = ["tools/docs_check.py", "tools/fixtures/udmf.py", "tools/fixtures/proc.py", "tools/fixtures/wolf3d.py"]
D3MAP = """Version 2
// entity 0
{
"classname" "worldspawn"
// primitive 0
{
brushDef3
{
( 0 0 -1 -16 ) ( ( 0.0078125 0 0 ) ( 0 0.0078125 0 ) ) "textures/base_floor/a_sofloor1_d" 0 0 0
( 0 0 1 0 ) ( ( 0.0078125 0 0 ) ( 0 0.0078125 0 ) ) "textures/base_floor/a_sofloor1_d" 0 0 0
( 0 -1 0 -128 ) ( ( 0.0078125 0 0 ) ( 0 0.0078125 0 ) ) "textures/common/caulk" 0 0 0
( 1 0 0 -128 ) ( ( 0.0078125 0 0 ) ( 0 0.0078125 0 ) ) "textures/common/caulk" 0 0 0
( 0 1 0 -128 ) ( ( 0.0078125 0 0 ) ( 0 0.0078125 0 ) ) "textures/common/caulk" 0 0 0
( -1 0 0 -128 ) ( ( 0.0078125 0 0 ) ( 0 0.0078125 0 ) ) "textures/common/caulk" 0 0 0
}
}
}
// entity 1
{
"classname" "info_player_start"
"name" "info_player_start_1"
"origin" "0 0 1"
"angle" "90"
}
"""
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):
check = mod(ctx, "docs_check")
P = mod(ctx, "proc")
models, portals, nodes, areas, shadow = P.level(ctx.rng(2), False)
files = {"room.udmf": mod(ctx, "udmf").ROOM.encode(),
"level.proc": P.write(models, portals, nodes, areas, shadow, "mapProcFile003", False).encode()}
W = mod(ctx, "wolf3d")
rng = ctx.rng(5)
pal = bytes(rng.randrange(64) for _ in range(768))
files["VSWAP.WL6"], _ = W.vswap(rng, pal)
files["wolf.pal"] = pal
g = W.grid(rng, 16, 16, 0)
planes = [W.plane(g), W.plane([0] * 256), W.plane([0] * 256)]
body = bytearray(b"TED5v1.0")
starts = []
for pl in planes:
starts.append(len(body))
body += pl
head = len(body)
body += struct.pack("<iiiHHHHH16s", *starts, *(len(pl) for pl in planes), 16, 16, b"Tiny map") + b"!ID!"
files["GAMEMAPS.WL6"] = bytes(body)
files["MAPHEAD.WL6"] = struct.pack("<H100i", W.TAG, head, *([0] * 99))
files["room.map"] = D3MAP.encode()
vars = {"d3mapText": "room.map", "udmfText": "room.udmf", "procText": "level.proc", "vswapBytes": "VSWAP.WL6", "wolfPaletteBytes": "wolf.pal",
"gamemapsBytes": "GAMEMAPS.WL6", "mapheadBytes": "MAPHEAD.WL6"}
check.emit_inputs(ctx, files, vars)
+124
View File
@@ -0,0 +1,124 @@
# Doom 3 .proc fixtures (tools/fixtures.py). Doom 3's data is not redistributable, so the files are written here in
# dmap's layout (the Doom 3 GPL source's WriteOutputFile, read for the text layout; no code taken): two area models
# made of boxes, an inline entity model, portals, BSP nodes and a shadow model; and a Quake 4 "PROC" "4" file with
# vertex colours. The reference is this script's own geometry: per model and surface the vertex count, CRC-32 of the
# positions / texcoords as f32 LE, and of the indices as u32 LE with every triangle turned counter-clockwise.
# tests/gen/proc.luau { doom3 = { text, models = { { name, surfaces = { { material, verts, pos, uv, idx } } } },
# portals, nodes, areas, shadow = { name, verts, indices } }, quake4 = { ... } }
import struct, zlib
def box(rng, x0, y0, z0, x1, y1, z1):
# 6 quads; triangles clockwise seen from outside (id Tech 4's front faces)
c = [(x0, y0, z0), (x1, y0, z0), (x1, y1, z0), (x0, y1, z0), (x0, y0, z1), (x1, y0, z1), (x1, y1, z1), (x0, y1, z1)]
faces = [((0, 1, 2, 3), (0, 0, -1)), ((4, 7, 6, 5), (0, 0, 1)), ((0, 4, 5, 1), (0, -1, 0)), ((1, 5, 6, 2), (1, 0, 0)),
((2, 6, 7, 3), (0, 1, 0)), ((3, 7, 4, 0), (-1, 0, 0))]
verts, idx = [], []
for quad, n in faces:
b = len(verts)
for k, vi in enumerate(quad):
x, y, z = c[vi]
verts.append((x, y, z, (k & 1) * 2.5 + rng.randint(0, 3) * 0.25, (k >> 1) * -1.5 + 0.0, n[0], n[1], n[2]))
# clockwise triangles about n, whichever way the corners run
(ax, ay, az), (bx, by, bz), (cx, cy, cz) = c[quad[0]], c[quad[1]], c[quad[2]]
ux, uy, uz, vx, vy, vz = bx - ax, by - ay, bz - az, cx - ax, cy - ay, cz - az
ccw = (uy * vz - uz * vy) * n[0] + (uz * vx - ux * vz) * n[1] + (ux * vy - uy * vx) * n[2] > 0
idx += [b, b + 2, b + 1, b, b + 3, b + 2] if ccw else [b, b + 1, b + 2, b, b + 2, b + 3]
return verts, idx
def fmt(v):
return ("%d" % v) if float(v).is_integer() else ("%g" % v)
def write(models, portals, nodes, areas, shadow, header, colors):
out = [header, ""]
for m in models:
out.append('model { /* name = */ "%s" /* numSurfaces = */ %d' % (m["name"], len(m["surfaces"])))
out.append("")
for si, s in enumerate(m["surfaces"]):
out.append('/* surface %d */ { "%s" /* numVerts = */ %d /* numIndexes = */ %d' % (si, s["material"], len(s["verts"]), len(s["idx"])))
line = []
for v in s["verts"]:
vals = list(v) + (s["color"] if colors else [])
line.append("( " + " ".join(fmt(x) for x in vals) + " )")
if len(line) == 3:
out.append(" ".join(line))
line = []
if line:
out.append(" ".join(line))
for k in range(0, len(s["idx"]), 15):
out.append(" ".join(str(i) for i in s["idx"][k:k + 15]) + " ")
out.append("}")
out.append("")
out.append("}")
out.append("")
out.append("shadowModel { /* name = */ \"%s\"" % shadow["name"])
out.append("/* numVerts = */ %d /* noCaps = */ 0 /* noFrontCaps = */ 0 /* numIndexes = */ %d /* planeBits = */ 59"
% (len(shadow["verts"]) // 3, len(shadow["indices"])))
out.append(" ".join("( %s %s %s )" % tuple(fmt(x) for x in shadow["verts"][k:k + 3]) for k in range(0, len(shadow["verts"]), 3)))
out.append(" ".join(str(i) for i in shadow["indices"]))
out.append("}")
out.append("")
out.append("interAreaPortals { /* numAreas = */ %d /* numIAP = */ %d" % (areas, len(portals)))
out.append("")
out.append("/* interAreaPortal format is: numPoints positiveSideArea negativeSideArea ( point) ... */")
for i, p in enumerate(portals):
pts = " ".join("( %s %s %s )" % tuple(fmt(x) for x in p["points"][k:k + 3]) for k in range(0, len(p["points"]), 3))
out.append("/* iap %d */ %d %d %d %s " % (i, len(p["points"]) // 3, p["positive"], p["negative"], pts))
out.append("}")
out.append("")
out.append("nodes { /* numNodes = */ %d" % len(nodes))
out.append("")
out.append("/* node format is: ( planeVector ) positiveChild negativeChild */")
out.append("/* a child number of 0 is an opaque, solid area */")
out.append("/* negative child numbers are areas: (-1-child) */")
for i, n in enumerate(nodes):
out.append("/* node %d */ ( %s ) %d %d " % (i, " ".join(fmt(x) for x in n["plane"]), n["positive"], n["negative"]))
out.append("}")
return "\n".join(out) + "\n"
def ref(models):
res = []
for m in models:
ss = []
for s in m["surfaces"]:
pos = b"".join(struct.pack("<3f", *v[0:3]) for v in s["verts"])
uv = b"".join(struct.pack("<2f", *v[3:5]) for v in s["verts"])
ccw = []
for k in range(0, len(s["idx"]), 3):
a, b, c = s["idx"][k:k + 3]
ccw += [a, c, b]
ss.append({"material": s["material"], "verts": len(s["verts"]), "pos": zlib.crc32(pos), "uv": zlib.crc32(uv),
"idx": zlib.crc32(struct.pack("<%dI" % len(ccw), *ccw)), "tris": len(ccw) // 3})
res.append({"name": m["name"], "surfaces": ss})
return res
def level(rng, colors):
models = []
for a in range(2):
surfs = []
for k in range(2 + a):
v, i = box(rng, a * 512 + k * 64, -128, 0, a * 512 + k * 64 + 48, 128 + rng.randint(0, 4) * 8, 96.5)
surfs.append({"material": "textures/base_wall/lfwall%d" % (k + 1), "verts": v, "idx": i,
"color": [255, 128, 0, 255]})
models.append({"name": "_area%d" % a, "surfaces": surfs})
v, i = box(rng, 100, 0, 8, 116, 16, 24)
models.append({"name": "func_static_1", "surfaces": [{"material": "models/mapobjects/crate", "verts": v, "idx": i, "color": [10, 20, 30, 40]}]})
portals = [{"positive": 1, "negative": 0, "points": [448, -128, 0, 448, 128, 0, 448, 128, 96, 448, -128, 96]}]
nodes = [{"plane": [1, 0, 0, -448], "positive": 1, "negative": -1}, {"plane": [0, 0, 1, 0], "positive": 0, "negative": -2}]
shadow = {"name": "_prelight_light_1", "verts": [0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1], "indices": [0, 1, 2, 0, 2, 3]}
return models, portals, nodes, 2, shadow
def generate(ctx):
rng = ctx.rng(31)
out = {}
for key, header, colors in [("doom3", "mapProcFile003", False), ("quake4", 'PROC "4"', True)]:
models, portals, nodes, areas, shadow = level(rng, colors)
out[key] = {"text": write(models, portals, nodes, areas, shadow, header, colors), "models": ref(models),
"portals": portals, "nodes": nodes, "areas": areas,
"shadow": {"name": shadow["name"], "verts": len(shadow["verts"]) // 3, "indices": len(shadow["indices"])}}
ctx.emit("proc", out)
+112
View File
@@ -0,0 +1,112 @@
# UDMF fixtures (tools/fixtures.py). Freedoom has no UDMF maps, so Freedoom MAP01 (BSD, licenses/freedoom-COPYING.txt;
# the nix freedoom package, cut down as in wad.py) is converted here to a "Doom"-namespace TEXTMAP by the UDMF 1.1
# conversion rules (tag -> id and arg0, flag bits -> booleans). The test checks that the TEXTMAP map gives the same
# tables and the same Scene geometry as the binary lumps. Plus a hand-written ZDoom-namespace room (comments, octal /
# hex, escapes, user_ and unknown keys, an unknown block) with exact areas.
# tests/gen/udmf.luau { binary = <IWAD>, textmap = <PWAD with MAP01 as UDMF>, text = <the TEXTMAP>, room = <text> }
import importlib.util, os, struct
HERE = os.path.dirname(os.path.abspath(__file__))
def wadgen():
spec = importlib.util.spec_from_file_location("_wadfx", os.path.join(HERE, "wad.py"))
m = importlib.util.module_from_spec(spec)
spec.loader.exec_module(m)
return m
def q(s):
return '"' + s.replace("\\", "\\\\").replace('"', '\\"') + '"'
def to_udmf(d):
out = ['namespace = "Doom";', ""]
nm = lambda b: b.split(b"\0")[0].decode("latin1")
for i in range(0, len(d["THINGS"]), 10):
x, y, a, t, f = struct.unpack_from("<hhHHH", d["THINGS"], i)
kv = ["x = %d.0;" % x, "y = %d.0;" % y, "angle = %d;" % a, "type = %d;" % t]
for k, on in [("skill1", f & 1), ("skill2", f & 1), ("skill3", f & 2), ("skill4", f & 4), ("skill5", f & 4),
("ambush", f & 8), ("single", not f & 16), ("dm", not f & 32), ("coop", not f & 64), ("friend", f & 128)]:
if on:
kv.append("%s = true;" % k)
out.append("thing // %d\n{\n%s\n}\n" % (i // 10, "\n".join(kv)))
for i in range(0, len(d["VERTEXES"]), 4):
x, y = struct.unpack_from("<hh", d["VERTEXES"], i)
out.append("vertex { x = %d.000; y = %d.000; }" % (x, y))
bits = ["blocking", "blockmonsters", "twosided", "dontpegtop", "dontpegbottom", "secret", "blocksound", "dontdraw", "mapped"]
for i in range(0, len(d["LINEDEFS"]), 14):
v1, v2, f, sp, tag, fr, bk = struct.unpack_from("<HHHHHHH", d["LINEDEFS"], i)
kv = ["id = %d;" % tag, "v1 = %d;" % v1, "v2 = %d;" % v2, "sidefront = %d;" % fr]
if bk != 0xFFFF:
kv.append("sideback = %d;" % bk)
if sp:
kv += ["special = %d;" % sp, "arg0 = %d;" % tag]
kv += ["%s = true;" % b for k, b in enumerate(bits) if f & (1 << k)]
out.append("linedef\n{\n%s\n}\n" % "\n".join(kv))
for i in range(0, len(d["SIDEDEFS"]), 30):
xo, yo, up, lo, mid, sec = struct.unpack_from("<hh8s8s8sH", d["SIDEDEFS"], i)
kv = ["sector = %d;" % sec]
if xo:
kv.append("offsetx = %d;" % xo)
if yo:
kv.append("offsety = %d;" % yo)
for k, v in [("texturetop", up), ("texturebottom", lo), ("texturemiddle", mid)]:
if nm(v) != "-":
kv.append("%s = %s;" % (k, q(nm(v))))
out.append("sidedef\n{\n%s\n}\n" % "\n".join(kv))
for i in range(0, len(d["SECTORS"]), 26):
fl, ce, ff, cf, li, sp, tag = struct.unpack_from("<hh8s8sHHH", d["SECTORS"], i)
kv = ["heightfloor = %d;" % fl, "heightceiling = %d;" % ce, "texturefloor = %s;" % q(nm(ff)),
"textureceiling = %s;" % q(nm(cf)), "lightlevel = %d;" % li]
if sp:
kv.append("special = %d;" % sp)
if tag:
kv.append("id = %d;" % tag)
out.append("sector\n{\n%s\n}\n" % "\n".join(kv))
return "\n".join(out) + "\n"
ROOM = r'''// a 256 x 256 room (sector 0) with a 64 x 64 pillar sector (1), pillar floor 32
/* written by hand
for the rosetta tests */
NameSpace = "ZDoom";
user_note = "a \"quoted\" \\ note";
vertex { x = 0; y = 0.0; } // 0
vertex { x = 0x100; y = 0; } // 1: hex
vertex { x = 256.0; y = 256e0; } // 2
vertex { x = 0; y = 0400; } // 3: octal 256
vertex { x = 96; y = 96; } vertex { x = 160; y = 96; } vertex { x = 160; y = 160; } vertex { x = 96; y = 160; }
sidedef { sector = 0; texturemiddle = "Wall"; }
sidedef { sector = 0; texturemiddle = "WALL"; }
sidedef { sector = 0; texturemiddle = "WALL"; }
sidedef { sector = 0; texturemiddle = "WALL"; }
sidedef { sector = 0; texturebottom = "STEP"; offsetx_bottom = 4.0; } sidedef { sector = 0; texturebottom = "STEP"; }
sidedef { sector = 0; texturebottom = "STEP"; } sidedef { sector = 0; texturebottom = "STEP"; }
sidedef { sector = 1; } sidedef { sector = 1; } sidedef { sector = 1; } sidedef { sector = 1; }
linedef { v1 = 0; v2 = 3; sidefront = 0; blocking = true; }
linedef { v1 = 3; v2 = 2; sidefront = 1; Blocking = TRUE; }
linedef { v1 = 2; v2 = 1; sidefront = 2; blocking = true; }
linedef { v1 = 1; v2 = 0; sidefront = 3; blocking = true; id = 7; special = 80; arg0 = 3; playeruse = true; repeatspecial = true; }
linedef { v1 = 4; v2 = 5; sidefront = 4; sideback = 8; twosided = true; }
linedef { v1 = 5; v2 = 6; sidefront = 5; sideback = 9; twosided = true; }
linedef { v1 = 6; v2 = 7; sidefront = 6; sideback = 10; twosided = true; }
linedef { v1 = 7; v2 = 4; sidefront = 7; sideback = 11; twosided = true; }
sector { heightfloor = 0; heightceiling = 128; texturefloor = "FLOOR"; textureceiling = "CEIL"; user_gravity = 0.5; }
sector { heightfloor = 32; heightceiling = 128; texturefloor = "FLOOR"; textureceiling = "CEIL"; lightlevel = 200; id = 3; }
thing { x = 32; y = 32; angle = 90; type = 1; skill1 = true; single = true; }
thing { x = 128.5; y = 128; height = 8; type = 2014; id = 5; special = 80; arg0 = 1; dormant = true; }
vavoombox { foo = 1; } // unknown block, kept
'''
def generate(ctx):
W = wadgen()
root = ctx.nix("freedoom", ["sh", "-c", "dirname $(dirname $(readlink -f $(command -v freedoom2)))"]).decode().strip()
full = open(os.path.join(root, W.FREEDOOM), "rb").read()
sel, rng = W.cut(full)
sel += rng("P_START", "P_END", 40) + rng("F_START", "F_END", 40)
binary = W.write(b"IWAD", sel)
text = to_udmf(dict(sel[1:11]))
textmap = W.write(b"PWAD", [("MAP01", b""), ("TEXTMAP", text.encode()), ("ENDMAP", b"")] + sel[11:])
ctx.emit("udmf", {"binary": binary, "textmap": textmap, "text": text, "room": ROOM})
+183
View File
@@ -0,0 +1,183 @@
# Wolfenstein 3D fixtures (tools/fixtures.py). id's data and source are not redistributable / GPL, so everything is
# written here by this script's own writers from the ModdingWiki format descriptions: a random 6-bit palette; a VSWAP
# with walls, sprites (t_compshape posts, with gaps), sound pages and the sound info page; a GAMEMAPS + MAPHEAD pair
# with two maps (slots 1 and 3) whose planes are RLEW then Carmack compressed (near and far copies, literal 0xA7xx /
# 0xA8xx words, RLEW runs and a literal tag value). The references are the source pixels / tiles: CRC-32 of the RGBA
# (6-bit values scaled as (v << 2) | (v >> 4), sprite holes 0) and of the tiles as u16 LE.
# tests/gen/wolf3d.luau { palette, vswap = { data, walls = { crc }, sprites = { crc }, sounds = { { bytes, crc } } },
# gamemaps, maphead, maps = { { slot, name, width, height, planes = { crc } } } }
import struct, zlib
TAG = 0xABCD
def rgba(pal, idx, holes=None):
out = bytearray()
for k, i in enumerate(idx):
if holes is not None and holes[k]:
out += b"\0\0\0\0"
else:
r, g, b = (pal[i * 3 + c] for c in range(3))
out += bytes([(r << 2) | (r >> 4), (g << 2) | (g >> 4), (b << 2) | (b >> 4), 255])
return zlib.crc32(bytes(out))
def sprite(rng):
# columns left..right, each with 1-2 posts; pixel data first, then the column post lists
left, right = rng.randint(0, 10), rng.randint(40, 63)
img = [None] * 4096 # row-major y * 64 + x: palette index, None = hole
pix = bytearray()
cols = []
hdr = 4 + (right - left + 1) * 2
for x in range(left, right + 1):
posts = []
y = rng.randint(0, 8)
for _ in range(rng.randint(1, 2)):
y0 = y
y1 = min(64, y0 + rng.randint(4, 30))
if y0 >= y1:
break
base = hdr + len(pix)
for yy in range(y0, y1):
v = rng.randrange(256)
img[yy * 64 + x] = v
pix.append(v)
posts.append((y1 * 2, base - y0, y0 * 2))
y = y1 + rng.randint(2, 10)
if y >= 60:
break
cols.append(posts)
body = bytearray(pix)
ofs = []
for posts in cols:
ofs.append(hdr + len(body))
for e, s, st in posts:
body += struct.pack("<HhH", e, s, st)
body += struct.pack("<H", 0)
data = struct.pack("<HH", left, right) + b"".join(struct.pack("<H", o) for o in ofs) + bytes(body)
return data, img
def vswap(rng, pal):
walls, sprites, sounds = [], [], []
for _ in range(3):
cm = bytes(rng.randrange(256) for _ in range(4096)) # column-major x * 64 + y
walls.append((cm, rgba(pal, [cm[x * 64 + y] for y in range(64) for x in range(64)])))
for _ in range(3):
data, img = sprite(rng)
sprites.append((data, rgba(pal, [v or 0 for v in img], [v is None for v in img])))
pages = [w for w, _ in walls] + [s for s, _ in sprites]
ss, so = len(walls), len(walls) + len(sprites)
# sound 1: one page; sound 2: two pages (4096 + 1000)
snd = [bytes(rng.randrange(256) for _ in range(700)), bytes(rng.randrange(256) for _ in range(5096))]
spages, info = [], b""
for s in snd:
info += struct.pack("<HH", len(spages), len(s))
for k in range(0, len(s), 4096):
spages.append(s[k:k + 4096])
pages += spages + [info]
n = len(pages)
# a sparse page (offset 0) after the walls is legal: the second wall page stays, an extra sprite slot is sparse
head = struct.pack("<HHH", n, ss, so)
at = 6 + n * 6
at = (at + 511) // 512 * 512
offs, body = [], bytearray()
for p in pages:
offs.append(at + len(body))
body += p
body += b"\0" * ((-len(body)) % 512)
out = head + b"".join(struct.pack("<I", o) for o in offs) + b"".join(struct.pack("<H", len(p)) for p in pages)
out += b"\0" * (at - len(out)) + bytes(body)
return out, {"walls": [c for _, c in walls], "sprites": [c for _, c in sprites],
"sounds": [{"bytes": len(s), "first": s[0], "last": s[-1]} for s in snd]}
def rlew(words):
out = []
i = 0
while i < len(words):
j = i
while j < len(words) and words[j] == words[i] and j - i < 0xFFFF:
j += 1
if j - i > 3 or words[i] == TAG:
out += [TAG, j - i, words[i]]
else:
out += words[i:j]
i = j
return out
def carmack(words):
out = bytearray()
pos = {}
i = 0
while i < len(words):
best, bo = 0, 0
for cand in reversed(pos.get((words[i], words[i + 1]) if i + 1 < len(words) else None, [])[-32:]):
k = 0
while i + k < len(words) and words[cand + k] == words[i + k] and k < 255 and cand + k < i:
k += 1
if k > best:
best, bo = k, cand
if best >= 2:
if i - bo <= 255:
out += struct.pack("<HB", 0xA700 | best, i - bo)
else:
out += struct.pack("<HH", 0xA800 | best, bo)
step = best
else:
w = words[i]
if w >> 8 in (0xA7, 0xA8):
out += struct.pack("<HB", w & 0xFF00, w & 0xFF)
else:
out += struct.pack("<H", w)
step = 1
for k in range(i, i + step):
if k + 1 < len(words):
pos.setdefault((words[k], words[k + 1]), []).append(k)
i += step
return bytes(out)
def plane(words):
r = [len(words) * 2] + rlew(words)
return struct.pack("<H", len(r) * 2) + carmack(r)
def grid(rng, w, h, k):
g = []
for y in range(h):
for x in range(w):
if k == 0:
v = 1 if x in (0, w - 1) or y in (0, h - 1) else (rng.choice([108, 108, 108, 2, 90]) if rng.random() < 0.2 else 108)
elif k == 1:
v = rng.choice([0] * 20 + [19, 23, 0xA7FF, 0xA801, TAG])
else:
v = 0
g.append(v)
return g
def generate(ctx):
rng = ctx.rng(64)
pal = bytes(rng.randrange(64) for _ in range(768))
vs, vref = vswap(rng, pal)
maps, body = [], bytearray(b"TED5v1.0")
heads = [0] * 100
for slot, (name, w, h) in [(1, ("Wolf1 Map1", 64, 64)), (3, ("Test map", 20, 12))]:
planes, crcs = [], []
for k in range(3):
g = grid(rng, w, h, k)
crcs.append(zlib.crc32(struct.pack("<%dH" % len(g), *g)))
planes.append(plane(g))
starts = []
for p in planes:
starts.append(len(body))
body += p
heads[slot - 1] = len(body)
body += struct.pack("<iiiHHHHH16s", *starts, *(len(p) for p in planes), w, h, name.encode())
body += b"!ID!"
maps.append({"slot": slot, "name": name, "width": w, "height": h, "planes": crcs})
heads[1] = -1
maphead = struct.pack("<H100i", TAG, *heads)
ctx.emit("wolf3d", {"palette": pal, "vswap": dict(vref, data=vs), "gamemaps": bytes(body), "maphead": maphead, "maps": maps})