model/map: Quake / Valve 220 / Quake II / Quake III editor maps, read and write

Entities as nodes (keys in extras, brushes as parsed), brushes through codecs/model/Brush, patchDef2 / patchDef3
through codecs/model/Patch, texture sizes from WAD2 / WAD3 / .wal / images; tested against ericw-tools qbsp.
This commit is contained in:
4DBug committed 2026-11-01 18:52:31 -06:00
1 parent 5ad934565d
commit 2704653a3e
13 files changed
+4885 -1077

No files matched your search

+2 -1
View File
@@ -44,7 +44,7 @@ print(F.detect(webp), #F.formats()) -- "webp", the format list
## Formats
<!-- formats:begin -->
174 formats. Generated from the format contracts by `tools/gen_registry.py`; [docs/FORMATS.md](docs/FORMATS.md)
175 formats. Generated from the format contracts by `tools/gen_registry.py`; [docs/FORMATS.md](docs/FORMATS.md)
adds each format's capabilities.
| Category | Format | Extensions | Read | Write |
@@ -116,6 +116,7 @@ adds each format's capabilities.
| 3D models | iqm | .iqm | yes | yes |
| 3D models | ldraw | .ldr .mpd .dat | yes | - |
| 3D models | lwo | .lwo .lxo | yes | - |
| 3D models | map | .map | yes | yes |
| 3D models | mca | .mca .mcr | yes | - |
| 3D models | md2 | .md2 | yes | - |
| 3D models | md3 | .md3 | yes | - |
+1103
View File
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
+1103
View File
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
+1
View File
@@ -72,6 +72,7 @@ is tested under both runtimes (luau `--codegen -O2` and LuaJIT through the build
| model | iqm | .iqm | yes | yes | materials: true, skins: true, animation: true, vertexColors: true | `tests/model/iqm.luau` |
| model | ldraw | .ldr .mpd .dat | yes | - | materials: true, lines: true, instancing: true | `tests/model/ldraw.luau` |
| model | lwo | .lwo .lxo | yes | - | materials: true, polygons: true, vertexColors: true, morphTargets: true | `tests/model/lwo.luau` |
| model | map | .map | yes | yes | variants: "quake", "valve220", "quake2", "quake3", patches: true | `tests/model/map.luau` |
| model | mca | .mca .mcr | yes | - | voxels: true, blocks: true | `tests/model/mca.luau` |
| model | md2 | .md2 | yes | - | morph: true, animation: true | `tests/model/md2.luau` |
| model | md3 | .md3 | yes | - | morph: true, animation: true, tags: true | `tests/model/md3.luau` |
+12
View File
@@ -818,6 +818,18 @@ local list: { Entry } = {
return require("@rosetta/model/lwo")
end,
},
{
name = "map",
category = "model",
path = "model/map",
extensions = { "map" },
mime = { "text/x-quake-map" },
deps = { "core/Err", "core/Bytes", "core/Input", "Types", "codecs/image/Miptex", "codecs/model/Brush", "codecs/model/Patch" },
caps = { decode = true, encode = true, variants = { "quake", "valve220", "quake2", "quake3" }, patches = true },
load = function()
return require("@rosetta/model/map")
end,
},
{
name = "mca",
category = "model",
+241
View File
@@ -0,0 +1,241 @@
--!strict
-- model/map/Build: parsed entities -> Scene: brushes through codecs/model/Brush, patches through codecs/model/Patch,
-- a mesh per entity with brushes, a primitive per texture, entities as nodes (keys in extras), z up, map units.
local Types = require("@rosetta/Types")
local Brush = require("@rosetta/codecs/model/Brush")
local Patch = require("@rosetta/codecs/model/Patch")
local Parse = require("@rosetta/model/map/Parse")
local Build = {}
local Scene = Types.Scene
local writef32, writeu32 = buffer.writef32, buffer.writeu32
export type Options = {
variant: string, -- "quake" | "valve220" | "quake2" | "quake3"
size: (name: string) -> (number, number, boolean), -- width, height, known
hull: boolean?,
merge: boolean?,
epsilon: number?,
patchLevel: number?,
skip: { string }?,
maxPolygons: number?,
}
function Build.face(f: Parse.Face): Brush.Face?
local p = f.points
local plane = Brush.planeFromPoints({ p[1], p[2], p[3] }, { p[4], p[5], p[6] }, { p[7], p[8], p[9] })
if not plane then
return nil
end
local out: Brush.Face = { plane = plane, texture = f.texture }
if f.matrix then
out.bp = f.matrix
elseif f.u and f.v then
local sc = f.scale or { 1, 1 }
out.vecs = Brush.valveVecs(f.u, f.v, sc[1], sc[2])
else
local o, sc = f.offset or { 0, 0 }, f.scale or { 1, 1 }
out.vecs = Brush.quakeVecs(plane, o[1], o[2], f.rotation or 0, sc[1], sc[2])
end
return out
end
type Acc = { pos: { number }, nrm: { number }, uv: { number }, idx: { number } }
local function patchPrim(b: Parse.Brush, level: number, acc: Acc): boolean
local size, pts = b.size :: { number }, b.points :: { number }
local w: number, h: number = size[1] :: number, size[2] :: number
if not Patch.valid(w, h, #pts // 5) then
return false
end
-- file order is column by column (q3map2 ParsePatch: verts[i * width + j] for column j, point i)
local ctrl = table.create(w * h * 5, 0) :: { number }
for j = 0, w - 1 do
for i = 0, h - 1 do
table.move(pts, (j * h + i) * 5 + 1, (j * h + i) * 5 + 5, (i * w + j) * 5 + 1, ctrl)
end
end
local params: { number } = b.params or {}
local explicit = b.type == "patchDef3"
local lu: number = if explicit then math.max(1, params[1] or 1) else level
local lv: number = if explicit then math.max(1, params[2] or 1) else level
local g, gw, gh = Patch.grid(ctrl, w, h, 5, lu, lv)
if not g then
return false
end
local nrm = Patch.normals(g, 5, gw, gh)
local base = #acc.pos // 3
for k = 0, gw * gh - 1 do
local o = k * 5
table.insert(acc.pos, g[o + 1])
table.insert(acc.pos, g[o + 2])
table.insert(acc.pos, g[o + 3])
table.insert(acc.uv, g[o + 4])
table.insert(acc.uv, g[o + 5])
table.insert(acc.nrm, nrm[k * 3 + 1])
table.insert(acc.nrm, nrm[k * 3 + 2])
table.insert(acc.nrm, nrm[k * 3 + 3])
end
for _, v in Patch.triangles(gw, gh) do
table.insert(acc.idx, base + v)
end
return true
end
local function primitive(a: Acc): Types.Primitive
local nv, ni = #a.pos // 3, #a.idx
local pb, nb, ub, ib = buffer.create(nv * 12), buffer.create(nv * 12), buffer.create(nv * 8), buffer.create(ni * 4)
for k = 1, nv * 3 do
writef32(pb, (k - 1) * 4, a.pos[k])
writef32(nb, (k - 1) * 4, a.nrm[k])
end
for k = 1, nv * 2 do
writef32(ub, (k - 1) * 4, a.uv[k])
end
for k = 1, ni do
writeu32(ib, (k - 1) * 4, a.idx[k])
end
return {
attributes = { POSITION = Scene.accessor(pb, "f32", 3, nv), NORMAL = Scene.accessor(nb, "f32", 3, nv), TEXCOORD_0 = Scene.accessor(ub, "f32", 2, nv) },
indices = Scene.accessor(ib, "u32", 1, ni),
mode = "triangles",
}
end
local function vec3(s: string?): { number }?
if not s then
return nil
end
local x, y, z = string.match(s, "^%s*(%S+)%s+(%S+)%s+(%S+)")
local a, b, c = tonumber(x), tonumber(y), tonumber(z)
if a and b and c then
return { a, b, c }
end
return nil
end
function Build.scene(map: Parse.Map, o: Options): (Types.Scene?, string?)
local scene = Scene.new()
scene.meta.up = "z"
local skip: { [string]: boolean } = {}
for _, n in o.skip or {} do
skip[string.lower(n)] = true
end
local matOf: { [string]: number } = {}
local function material(name: string): number
local m = matOf[name]
if m then
return m
end
local w, h, known = o.size(name)
local uri = name
if o.variant == "quake2" then
uri = "textures/" .. name .. ".wal"
elseif o.variant == "quake3" then
uri = "textures/" .. name
end
table.insert(scene.textures, { name = name, uri = uri })
local mat = Scene.material(name)
mat.metallic = 0
mat.baseColorTexture = { texture = #scene.textures }
mat.extras = { map = { width = w, height = h, sizeKnown = known } }
table.insert(scene.materials, mat)
matOf[name] = #scene.materials
return #scene.materials
end
local root: Types.Node = { name = "map", children = {} }
table.insert(scene.nodes, root)
scene.roots[1] = 1
local skipped = { faces = 0, patches = 0 }
local counts = { brushes = 0, patches = 0 }
local entities: { { [string]: string } } = {}
local polyTotal = 0
for ei, ent in map.entities do
local keys = ent.keys
table.insert(entities, keys)
local node: Types.Node = { name = keys.targetname or keys.classname or ("entity " .. (ei - 1)), children = {},
extras = { classname = keys.classname, keys = keys, brushes = ent.brushes, entity = ei - 1 } }
local brushes: { { Brush.Face } } = {}
local patchAcc: { [string]: Acc } = {}
local patchOrder: { string } = {}
for _, b in ent.brushes do
if b.faces then
counts.brushes += 1
local faces: { Brush.Face } = {}
for _, f in b.faces do
local bf = Build.face(f)
if bf then
table.insert(faces, bf)
else
skipped.faces += 1
end
end
table.insert(brushes, faces)
else
counts.patches += 1
local tex = b.texture or ""
if not skip[string.lower(tex)] then
local acc = patchAcc[tex]
if not acc then
acc = { pos = {}, nrm = {}, uv = {}, idx = {} }
patchAcc[tex] = acc
table.insert(patchOrder, tex)
end
if not patchPrim(b, o.patchLevel or 4, acc :: Acc) then
skipped.patches += 1
end
end
end
end
local prims: { Types.Primitive } = {}
if #brushes > 0 then
local polys, err = Brush.polygons(brushes, { hull = o.hull, merge = o.merge, epsilon = o.epsilon, maxPolygons = o.maxPolygons })
if not polys then
return nil, err
end
polyTotal += #polys
if polyTotal > (o.maxPolygons or 2 ^ 20) then
return nil, "limit: too many polygons"
end
local kept: { Brush.Polygon } = {}
for _, p in polys do
local t = brushes[p.brush][p.face].texture or ""
if not skip[string.lower(t)] then
table.insert(kept, p)
end
end
local built = Brush.primitives(kept, brushes, function(name: string): (number, number)
local m = scene.materials[material(name)]
local e = (m.extras :: any).map
return e.width, e.height
end)
for _, bt in built do
bt.primitive.material = material(bt.texture)
table.insert(prims, bt.primitive)
end
end
for _, tex in patchOrder do
local acc = patchAcc[tex]
if #acc.idx > 0 then
local prim = primitive(acc)
prim.material = material(tex)
table.insert(prims, prim)
end
end
if #prims > 0 then
table.insert(scene.meshes, { name = node.name, primitives = prims })
node.mesh = #scene.meshes
elseif #ent.brushes == 0 then
node.translation = vec3(keys.origin)
end
table.insert(scene.nodes, node)
table.insert(root.children, #scene.nodes)
end
scene.meta.entities = entities
scene.meta.skipped = skipped
scene.meta.counts = counts
return scene, nil
end
return Build
+383
View File
@@ -0,0 +1,383 @@
--!strict
-- model/map/Parse: .map text -> entities (key / value pairs in order, brushes and patches as written). Grammar of the
-- Quake / Quake II / Half-Life (Valve 220) / Quake III editors (qbsp / q3map2 map parsers; no code taken).
local Types = require("@rosetta/Types")
local Parse = {}
export type Face = {
points: { number }, -- 3 points: x, y, z each
texture: string,
offset: { number }?, -- Quake standard: x, y offset
rotation: number?, -- standard / Valve 220 (degrees)
scale: { number }?, -- standard / Valve 220
u: { number }?, -- Valve 220: axis x, y, z, offset
v: { number }?,
matrix: { { number } }?, -- Quake III brush primitives: 2 x 3
flags: { number }?, -- trailing numbers: Quake II / III contents, surface flags, value (Hexen II: light)
}
export type Brush = {
type: string, -- "brush" | "brushDef" | "patchDef2" | "patchDef3"
faces: { Face }?,
texture: string?, -- patches
size: { number }?, -- patches: width, height (columns, points per column as written)
params: { number }?, -- patches: the header numbers after width, height
points: { number }?, -- patches: 5 numbers (x, y, z, s, t) per control point, in file order (column by column)
}
export type Entity = { keys: { [string]: string }, brushes: { Brush } } -- keys: an ordered object (Types.object)
export type Map = { entities: { Entity }, game: string?, mapFormat: string?, comments: { string } }
type St = { s: string, pos: number, n: number, comments: { string } }
local function skip(st: St)
local s = st.s
while true do
local p = string.find(s, "[^%s]", st.pos)
if not p then
st.pos = st.n + 1
return
end
if string.sub(s, p, p + 1) == "//" then
local e = string.find(s, "\n", p, true) or st.n
table.insert(st.comments, (string.gsub(string.sub(s, p + 2, e), "^%s*(.-)%s*$", "%1")))
st.pos = e + 1
else
st.pos = p
return
end
end
end
local function peek(st: St): string
skip(st)
return string.sub(st.s, st.pos, st.pos)
end
local function expect(st: St, c: string): string?
if peek(st) ~= c then
return "expected '" .. c .. "' at " .. (st.pos - 1)
end
st.pos += 1
return nil
end
local function word(st: St): string?
skip(st)
local a, b = string.find(st.s, "^[^%s]+", st.pos)
if not a then
return nil
end
st.pos = (b :: number) + 1
return string.sub(st.s, a, b)
end
local function number(st: St): number?
skip(st)
local a, b = string.find(st.s, "^[^%s%(%)%[%]{}]+", st.pos)
if not a then
return nil
end
local v = tonumber(string.sub(st.s, a, b))
if v then
st.pos = (b :: number) + 1
end
return v
end
local function quoted(st: St): string?
if peek(st) ~= '"' then
return nil
end
local e = string.find(st.s, '"', st.pos + 1, true)
if not e then
return nil
end
local v = string.sub(st.s, st.pos + 1, e - 1)
st.pos = e + 1
return v
end
local function numbers(st: St, n: number, out: { number }): string?
for _ = 1, n do
local v = number(st)
if not v then
return "expected a number at " .. (st.pos - 1)
end
table.insert(out, v)
end
return nil
end
local function vec(st: St, n: number, open: string, close: string): ({ number }?, string?)
local e = expect(st, open)
if e then
return nil, e
end
local out = {}
e = numbers(st, n, out)
if e then
return nil, e
end
e = expect(st, close)
if e then
return nil, e
end
return out, nil
end
local function trailing(st: St): { number }?
local out: { number } = {}
while true do
local c = peek(st)
if not string.match(c, "[%d%-%+%.]") then
break
end
local v = number(st)
if not v then
break
end
table.insert(out, v)
end
return if #out > 0 then out else nil
end
local function plane(st: St): ({ number }?, string?)
local pts: { number } = {}
for _ = 1, 3 do
local p, e = vec(st, 3, "(", ")")
if not p then
return nil, e
end
table.move(p, 1, 3, #pts + 1, pts)
end
return pts, nil
end
local function face(st: St, bp: boolean): (Face?, string?)
local pts, e = plane(st)
if not pts then
return nil, e
end
local f: Face = { points = pts, texture = "" }
if bp then
e = expect(st, "(")
if e then
return nil, e
end
local r1, e1 = vec(st, 3, "(", ")")
if not r1 then
return nil, e1
end
local r2, e2 = vec(st, 3, "(", ")")
if not r2 then
return nil, e2
end
e = expect(st, ")")
if e then
return nil, e
end
f.matrix = { r1, r2 }
end
local tex = word(st)
if not tex then
return nil, "expected a texture name at " .. (st.pos - 1)
end
f.texture = tex
if not bp then
if peek(st) == "[" then
local u, eu = vec(st, 4, "[", "]")
if not u then
return nil, eu
end
local v, ev = vec(st, 4, "[", "]")
if not v then
return nil, ev
end
local rest = {}
e = numbers(st, 3, rest)
if e then
return nil, e
end
f.u, f.v, f.rotation, f.scale = u, v, rest[1], { rest[2], rest[3] }
else
local rest = {}
e = numbers(st, 5, rest)
if e then
return nil, e
end
f.offset, f.rotation, f.scale = { rest[1], rest[2] }, rest[3], { rest[4], rest[5] }
end
end
f.flags = trailing(st)
return f, nil
end
local function patch(st: St, kind: string, maxPoints: number): (Brush?, string?)
local e = expect(st, "{")
if e then
return nil, e
end
local tex = word(st)
if not tex then
return nil, "expected a patch texture"
end
local hn = if kind == "patchDef3" then 7 else 5
local head, eh = vec(st, hn, "(", ")")
if not head then
return nil, eh
end
local w, h = head[1], head[2]
if w ~= math.floor(w) or h ~= math.floor(h) or w < 1 or h < 1 or w * h > maxPoints then
return nil, "bad patch size " .. w .. " x " .. h
end
local pts: { number } = {}
e = expect(st, "(")
if e then
return nil, e
end
for _ = 1, w do
e = expect(st, "(")
if e then
return nil, e
end
for _ = 1, h do
local p, ep = vec(st, 5, "(", ")")
if not p then
return nil, ep
end
table.move(p, 1, 5, #pts + 1, pts)
end
e = expect(st, ")")
if e then
return nil, e
end
end
e = expect(st, ")")
if e then
return nil, e
end
e = expect(st, "}")
if e then
return nil, e
end
return { type = kind, texture = tex, size = { w, h }, params = { table.unpack(head, 3) }, points = pts }, nil
end
local function brush(st: St, maxPoints: number): (Brush?, string?)
local c = peek(st)
if c == "(" then
local faces: { Face } = {}
while peek(st) == "(" do
local f, e = face(st, false)
if not f then
return nil, e
end
table.insert(faces, f)
end
local e = expect(st, "}")
if e then
return nil, e
end
return { type = "brush", faces = faces }, nil
end
if c == "}" then
st.pos += 1
return { type = "brush", faces = {} }, nil
end
local kw = word(st)
local out: any, err: string?
if kw == "brushDef" then
local e = expect(st, "{")
if e then
return nil, e
end
local faces: { Face } = {}
while peek(st) == "(" do
local f, ef = face(st, true)
if not f then
return nil, ef
end
table.insert(faces, f)
end
e = expect(st, "}")
if e then
return nil, e
end
out = { type = "brushDef", faces = faces }
elseif kw == "patchDef2" or kw == "patchDef3" then
out, err = patch(st, kw, maxPoints)
if not out then
return nil, err
end
elseif kw == "brushDef3" then
return nil, "unsupported: Doom 3 / Quake 4 brushDef3"
else
return nil, "unexpected '" .. tostring(kw) .. "' in a brush at " .. (st.pos - 1)
end
local e = expect(st, "}")
if e then
return nil, e
end
return out, nil
end
function Parse.parse(s: string, maxBrushes: number?): (Map?, string?, number?)
local st: St = { s = s, pos = 1, n = #s, comments = {} }
if string.sub(s, 1, 3) == "\239\187\191" then
st.pos = 4
end
local limit = maxBrushes or 2 ^ 20
local count = 0
local ents: { Entity } = {}
while peek(st) ~= "" do
local at = st.pos - 1
local e = expect(st, "{")
if e then
return nil, e, at
end
local keys: { [string]: string } = {}
local order: { string } = {}
local brushes: { Brush } = {}
while true do
local c = peek(st)
if c == "}" then
st.pos += 1
break
elseif c == '"' then
local k = quoted(st)
local v = quoted(st)
if not k or not v then
return nil, "bad key / value at " .. (st.pos - 1), st.pos - 1
end
if keys[k] == nil then
table.insert(order, k)
end
keys[k] = v
elseif c == "{" then
st.pos += 1
local b, eb = brush(st, limit)
if not b then
return nil, eb, st.pos - 1
end
count += 1
if count > limit then
return nil, "limit: too many brushes", st.pos - 1
end
table.insert(brushes, b)
elseif c == "" then
return nil, "truncated entity", st.pos - 1
else
return nil, "unexpected '" .. c .. "' in an entity at " .. (st.pos - 1), st.pos - 1
end
end
table.insert(ents, { keys = Types.object(keys, order) :: { [string]: string }, brushes = brushes })
end
local game, fmt
for _, c in st.comments do
game = game or string.match(c, "^Game:%s*(.-)%s*$")
fmt = fmt or string.match(c, "^Format:%s*(.-)%s*$")
end
return { entities = ents, game = game, mapFormat = fmt, comments = st.comments }, nil, nil
end
return Parse
+144
View File
@@ -0,0 +1,144 @@
--!strict
-- model/map/Write: entities (model/map/Parse's layout) -> .map text in the editors' layout (TrenchBroom / Radiant:
-- one face per line, numbers in their shortest exact form).
local Types = require("@rosetta/Types")
local Parse = require("@rosetta/model/map/Parse")
local Write = {}
function Write.num(x: number): string
if x ~= x or x == math.huge or x == -math.huge then
return "0"
end
if x == math.floor(x) and math.abs(x) < 2 ^ 53 then
return string.format("%d", x)
end
for p = 6, 17 do
local s = string.format("%." .. p .. "g", x)
if tonumber(s) == x then
return s
end
end
return string.format("%.17g", x)
end
local function nums(t: { number }, a: number, b: number): string
local out = table.create(b - a + 1) :: { string }
for i = a, b do
out[#out + 1] = Write.num(t[i] or 0)
end
return table.concat(out, " ")
end
local function faceLine(f: Parse.Face, bp: boolean): (string?, string?)
local p = f.points
if type(p) ~= "table" or #p < 9 or type(f.texture) ~= "string" or f.texture == "" or string.find(f.texture, "%s") then
return nil, "a face needs 9 point numbers and a texture name without spaces"
end
local parts: { string } = { "( " .. nums(p, 1, 3) .. " ) ( " .. nums(p, 4, 6) .. " ) ( " .. nums(p, 7, 9) .. " )" }
if bp then
local m = f.matrix
if not m or not m[1] or not m[2] then
return nil, "a brushDef face needs a texture matrix"
end
table.insert(parts, "( ( " .. nums(m[1], 1, 3) .. " ) ( " .. nums(m[2], 1, 3) .. " ) )")
table.insert(parts, f.texture)
elseif f.u and f.v then
local sc = f.scale or { 1, 1 }
table.insert(parts, f.texture)
table.insert(parts, "[ " .. nums(f.u, 1, 4) .. " ] [ " .. nums(f.v, 1, 4) .. " ] " .. Write.num(f.rotation or 0) .. " " .. nums(sc, 1, 2))
else
local o, sc = f.offset or { 0, 0 }, f.scale or { 1, 1 }
table.insert(parts, f.texture)
table.insert(parts, nums(o, 1, 2) .. " " .. Write.num(f.rotation or 0) .. " " .. nums(sc, 1, 2))
end
if f.flags and #f.flags > 0 then
table.insert(parts, nums(f.flags, 1, #f.flags))
end
return table.concat(parts, " "), nil
end
local function patchText(b: Parse.Brush, out: { string }): string?
local size, pts = b.size, b.points
if not size or not pts or type(b.texture) ~= "string" then
return "a patch needs a texture, a size and control points"
end
local w, h = size[1], size[2]
if #pts < w * h * 5 then
return "a patch needs width * height * 5 control numbers"
end
local params = b.params or {}
local nParams = if b.type == "patchDef3" then 5 else 3
table.insert(out, b.type)
table.insert(out, "{")
table.insert(out, b.texture)
table.insert(out, "( " .. Write.num(w) .. " " .. Write.num(h) .. " " .. nums(params, 1, nParams) .. " )")
table.insert(out, "(")
for i = 0, w - 1 do
local row = { "(" }
for j = 0, h - 1 do
local o = (i * h + j) * 5
table.insert(row, "( " .. nums(pts, o + 1, o + 5) .. " )")
end
table.insert(row, ")")
table.insert(out, table.concat(row, " "))
end
table.insert(out, ")")
table.insert(out, "}")
return nil
end
function Write.text(map: Parse.Map): (string?, string?)
local out: { string } = {}
if map.game then
table.insert(out, "// Game: " .. map.game)
end
if map.mapFormat then
table.insert(out, "// Format: " .. map.mapFormat)
end
for ei, ent in map.entities do
table.insert(out, "// entity " .. (ei - 1))
table.insert(out, "{")
for _, k in Types.keys(ent.keys) do
local v = ent.keys[k]
if v ~= nil then
if string.find(k, '"', 1, true) or string.find(tostring(v), '"', 1, true) or string.find(k, "[\r\n]") or string.find(tostring(v), "[\r\n]") then
return nil, "keys and values cannot hold quotes or line breaks: " .. k
end
table.insert(out, '"' .. k .. '" "' .. tostring(v) .. '"')
end
end
for bi, b in ent.brushes or {} do
table.insert(out, "// brush " .. (bi - 1))
table.insert(out, "{")
if b.type == "patchDef2" or b.type == "patchDef3" then
local e = patchText(b, out)
if e then
return nil, e
end
else
local bp = b.type == "brushDef"
if bp then
table.insert(out, "brushDef")
table.insert(out, "{")
end
for _, f in b.faces or {} do
local line, e = faceLine(f, bp)
if not line then
return nil, e
end
table.insert(out, line)
end
if bp then
table.insert(out, "}")
end
end
table.insert(out, "}")
end
table.insert(out, "}")
end
table.insert(out, "")
return table.concat(out, "\n"), nil
end
return Write
+315
View File
@@ -0,0 +1,315 @@
--!strict
-- model/map: editor .map files of Quake, Half-Life (Valve 220), Quake II (surface / content flags) and Quake III
-- (brushDef brush primitives, patchDef2; patchDef3 meshes), read and write. Grammar of the qbsp / q3map2 parsers (no
-- code taken). Brushes become polygons through codecs/model/Brush (optionally CSG'd and merged), patches through
-- codecs/model/Patch; a mesh per entity with brushes; entities as nodes with their keys in extras. Texture sizes from
-- opts.textureSizes, the worldspawn's WADs, .wal files or images through resolve; else 64 x 64. Not supported: Doom 3
-- brushDef3, Build engine maps (binary: model/buildmap), compiling (no BSP, vis or light).
-- ------------------------------------------------------------------------------------------------ requires
local Err = require("@rosetta/core/Err")
local Bytes = require("@rosetta/core/Bytes")
local Input = require("@rosetta/core/Input")
local Types = require("@rosetta/Types")
local Miptex = require("@rosetta/codecs/image/Miptex")
local Brush = require("@rosetta/codecs/model/Brush")
local Parse = require("@rosetta/model/map/Parse")
local Write = require("@rosetta/model/map/Write")
local Build = require("@rosetta/model/map/Build")
-- ------------------------------------------------------------------------------------------------ contract
local Map = {
name = "map",
category = "model",
extensions = { "map" },
mime = { "text/x-quake-map" },
deps = { "core/Err", "core/Bytes", "core/Input", "Types", "codecs/image/Miptex", "codecs/model/Brush", "codecs/model/Patch" },
caps = { decode = true, encode = true, variants = { "quake", "valve220", "quake2", "quake3" }, patches = true },
}
-- ------------------------------------------------------------------------------------------------ types
export type DecodeOptions = {
hull: boolean?, -- drop faces inside / touching other brushes of the same entity, default false
merge: boolean?, -- merge coplanar faces with the same texture projection, default false
epsilon: number?, -- default 1e-3
patchLevel: number?, -- patchDef2 segments per sub-patch, default 4
skip: { string }?, -- texture names left out of the meshes ("clip", "skip", "common/caulk", ...)
textureSizes: { [string]: { number } }?, -- name -> { width, height }
resolve: ((uri: string) -> (buffer | string)?)?,
files: { [string]: buffer | string }?,
decodeImage: ((buf: buffer) -> (Types.Image?, Err.Err?))?, -- Quake III: texture image sizes
maxBrushes: number?, -- default 2^20
maxPolygons: number?, -- default 2^20
}
export type EncodeOptions = {
variant: string?, -- "valve220" converts Quake standard faces to Valve 220 axes; default: as stored
}
-- ------------------------------------------------------------------------------------------------ sniff
function Map.sniff(r: Bytes.Reader): number
local head = r:peek(math.min(r:remaining(), 4096))
if #head < 2 or string.find(head, "[%z\1-\8\14-\31]") then
return 0
end
if string.sub(head, 1, 3) == "\239\187\191" then
head = string.sub(head, 4)
end
local s = head
local game = false
while true do
local c = string.match(s, "^%s*//[^\n]*\n?()")
if not c then
break
end
if string.match(s, "^%s*//%s*Game:") then
game = true
end
s = string.sub(s, c :: number)
end
local body = string.match(s, '^%s*{%s*"[^"\n]*"%s*"') or string.match(s, "^%s*{%s*{%s*[%(bp]")
if not body then
return if game and string.match(s, "^%s*{") then 0.6 else 0
end
return if game or string.find(head, '"classname"', 1, true) then 0.9 else 0.6
end
-- ------------------------------------------------------------------------------------------------ decode
local function variantOf(m: Parse.Map): string
local game = string.lower(m.game or "")
local fmt = string.lower(m.mapFormat or "")
local q2, valve, q3 = false, false, false
for _, e in m.entities do
if e.keys.mapversion == "220" then
valve = true
end
for _, b in e.brushes do
if b.type ~= "brush" then
q3 = true
end
for _, f in b.faces or {} do
if f.u then
valve = true
elseif f.flags and #f.flags >= 3 then
q2 = true
end
end
end
end
if q3 or string.find(game, "quake 3") or string.find(game, "quake iii") or fmt == "quake3" or fmt == "quake3 (valve)" then
return "quake3"
end
if string.find(game, "quake 2") or string.find(game, "quake ii") or fmt == "quake2" or fmt == "quake2 (valve)" then
return "quake2"
end
if valve or fmt == "valve" then
return "valve220"
end
return if q2 then "quake2" else "quake"
end
local function sizer(m: Parse.Map, variant: string, opts: DecodeOptions?): (name: string) -> (number, number, boolean)
local cache: { [string]: { number } } = {}
local wads: { { buf: buffer, lumps: { Miptex.Lump } } }? = nil
local function loadWads(): { { buf: buffer, lumps: { Miptex.Lump } } }
local list = {}
local ws = m.entities[1] and m.entities[1].keys
local spec = ws and (ws.wad or ws._wad) or ""
for path in string.gmatch(spec, "[^;]+") do
local p = string.gsub(path, "\\", "/")
local b = Input.sibling(opts, p) or Input.sibling(opts, string.match(p, "([^/]+)$") or p)
if b then
local lumps = Miptex.wad(b, 0, buffer.len(b))
if lumps then
table.insert(list, { buf = b, lumps = lumps })
end
end
end
return list
end
return function(name: string): (number, number, boolean)
local c = cache[name]
if c then
return c[1], c[2], c[3] == 1
end
local w: number, h: number = 0, 0
local given = opts and opts.textureSizes and opts.textureSizes[name]
if type(given) == "table" and type(given[1]) == "number" and type(given[2]) == "number" then
w, h = given[1] :: number, given[2] :: number
elseif variant == "quake" or variant == "valve220" then
wads = wads or loadWads()
for i = #(wads :: any), 1, -1 do
local wd = (wads :: any)[i]
local l = Miptex.find(wd.lumps, name)
if l then
local hd = Miptex.header(wd.buf, l.offset, l.disksize)
if hd then
w, h = hd.width, hd.height
break
end
end
end
elseif variant == "quake2" then
local wal = Input.sibling(opts, "textures/" .. name .. ".wal")
if wal and buffer.len(wal) >= 40 then
w, h = buffer.readu32(wal, 32), buffer.readu32(wal, 36)
end
elseif opts and opts.decodeImage then
for _, ext in { ".tga", ".jpg", ".png" } do
local b = Input.sibling(opts, "textures/" .. name .. ext)
if b then
local ok, img = pcall(opts.decodeImage :: any, b)
if ok and img then
w, h = img.width, img.height
break
end
end
end
end
local fw: number, fh: number = w :: number, h :: number
local known = fw > 0 and fh > 0
if not known then
fw, fh = 64, 64
end
cache[name] = { fw, fh, if known then 1 else 0 }
return fw, fh, known
end
end
function Map.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Scene?, Err.Err?)
local text = buffer.readstring(r.buf, r.base, r.limit - r.base)
local m, msg, at = Parse.parse(text, opts and opts.maxBrushes)
if not m then
return nil, Err.from(msg, at)
end
if #m.entities == 0 then
return nil, Err.new(Err.CORRUPT, "no entities", 0)
end
local variant = variantOf(m)
local scene, err = Build.scene(m, {
variant = variant,
size = sizer(m, variant, opts),
hull = opts and opts.hull,
merge = opts and opts.merge,
epsilon = opts and opts.epsilon,
patchLevel = opts and opts.patchLevel,
skip = opts and opts.skip,
maxPolygons = opts and opts.maxPolygons,
})
if not scene then
return nil, Err.from(err)
end
local counts = scene.meta.counts
scene.meta.counts = nil
scene.meta.source = { format = "map", variant = variant, game = m.game, mapFormat = m.mapFormat, entities = #m.entities, brushes = counts.brushes, patches = counts.patches }
return scene, nil
end
-- ------------------------------------------------------------------------------------------------ encode
local function toValve(f: Parse.Face): Parse.Face
if f.u or f.matrix then
return f
end
local bf = Build.face(f)
if not bf or not bf.vecs then
return f
end
local v = bf.vecs
local out = table.clone(f)
out.offset = nil
out.u, out.v = { v[1][1], v[1][2], v[1][3], v[1][4] }, { v[2][1], v[2][2], v[2][3], v[2][4] }
out.rotation, out.scale = 0, { 1, 1 }
return out
end
local function fmtNum(x: number): string
return Write.num(x)
end
function Map.encode(scene: Types.Scene, opts: EncodeOptions?): (buffer?, Err.Err?)
if type(scene) ~= "table" or type(scene.nodes) ~= "table" then
return nil, Err.new(Err.ARG, "expected a Scene")
end
local valve = opts and opts.variant == "valve220"
local ents: { any } = {}
for _, node in scene.nodes do
local ex: any = node.extras
if type(ex) == "table" and type(ex.keys) == "table" then
local keys = ex.keys
local brushes: { Parse.Brush } = if type(ex.brushes) == "table" then ex.brushes else {}
if node.translation and keys.origin and #brushes == 0 then
local t = node.translation
keys = Types.object(table.clone(keys), Types.keys(keys))
keys.origin = fmtNum(t[1]) .. " " .. fmtNum(t[2]) .. " " .. fmtNum(t[3])
end
if valve then
local conv: { Parse.Brush } = {}
for _, b in brushes do
if b.faces then
local nb = table.clone(b)
local faces = {}
for i, f in b.faces do
faces[i] = toValve(f)
end
nb.faces = faces
table.insert(conv, nb)
else
table.insert(conv, b)
end
end
brushes = conv
if #ents == 0 and keys.mapversion ~= "220" then
keys = Types.object(table.clone(keys), Types.keys(keys))
Types.set(keys, "mapversion", "220")
end
end
table.insert(ents, { keys = keys, brushes = brushes })
end
end
if #ents == 0 then
return nil, Err.new(Err.ARG, "no map entities (nodes with extras.keys, as model/map loads them)")
end
local src: any = scene.meta and scene.meta.source
local fromMap = type(src) == "table" and src.format == "map"
local text, err = Write.text({
entities = ents :: { Parse.Entity },
game = if fromMap then src.game else nil,
mapFormat = if valve then "Valve" elseif fromMap then src.mapFormat else nil,
comments = {},
})
if not text then
return nil, Err.new(Err.ARG, err or "bad entity")
end
return buffer.fromstring(text), nil
end
-- ------------------------------------------------------------------------------------------------ extras
-- the entities as parsed: { entities = { { keys, brushes } }, game, mapFormat }
function Map.parse(src: buffer | string): (Parse.Map?, Err.Err?)
local text = if type(src) == "buffer" then buffer.tostring(src) elseif type(src) == "string" then src else nil
if not text then
return nil, Err.new(Err.ARG, "expected a buffer or a string")
end
local m, msg, at = Parse.parse(text)
if not m then
return nil, Err.from(msg, at)
end
return m, nil
end
function Map.write(m: Parse.Map): (string?, Err.Err?)
if type(m) ~= "table" or type(m.entities) ~= "table" then
return nil, Err.new(Err.ARG, "expected { entities = ... }")
end
local text, err = Write.text(m)
if not text then
return nil, Err.new(Err.ARG, err or "bad entity")
end
return text, nil
end
-- a parsed face -> its Brush face (plane and projection): Brush.uv / Brush.polygons take it
function Map.face(f: Parse.Face): Brush.Face?
return Build.face(f)
end
return Map
+325
View File
@@ -0,0 +1,325 @@
-- model/map tests: Quake / Valve 220 / Quake II / Quake III .map files against ericw-tools qbsp (CSG'd face area per
-- plane and texture coordinates at every compiled corner, per entity), texture sizes from WAD2 / WAD3 / .wal through
-- files, the patchDef2 against a Bezier evaluation, entities as nodes, write round trips, errors, the fuzz pass.
-- Fixtures: tools/fixtures/map.py.
local T = require("@tests/T")
local F = require("@rosetta")
local MapFmt = require("@rosetta/model/map")
local Bytes = require("@rosetta/core/Bytes")
local Err = require("@rosetta/core/Err")
local Types = require("@rosetta/Types")
local Fx = require("@tests/gen/map")
local t = T.suite("map")
t:eq(MapFmt.name, "map", "name")
local function r(x: number, k: number): number
return math.floor(x * k + 0.5)
end
local function key(nx: number, ny: number, nz: number, d: number): string
return string.format("%d %d %d %d", r(nx, 1000), r(ny, 1000), r(nz, 1000), r(d, 100))
end
type Tri = { p: { number }, uv: { number }, n: { number }, tex: string }
local function triangles(s: any, mesh: any): { Tri }
local out: { Tri } = {}
for _, p in mesh.primitives do
local pos = Types.Scene.reader(p.attributes.POSITION) :: any
local uv = Types.Scene.reader(p.attributes.TEXCOORD_0) :: any
local nrm = Types.Scene.reader(p.attributes.NORMAL) :: any
local tex = s.materials[p.material].name
for k = 0, p.indices.count - 1, 3 do
local tri: Tri = { p = {}, uv = {}, n = {}, tex = tex }
for c = 0, 2 do
local v = buffer.readu32(p.indices.data, (k + c) * 4)
for a = 0, 2 do
table.insert(tri.p, pos(v, a))
end
table.insert(tri.uv, uv(v, 0))
table.insert(tri.uv, uv(v, 1))
if c == 0 then
tri.n = { nrm(v, 0), nrm(v, 1), nrm(v, 2) }
end
end
table.insert(out, tri)
end
end
return out
end
local function area(p: { number }): number
local ux, uy, uz = p[4] - p[1], p[5] - p[2], p[6] - p[3]
local vx, vy, vz = p[7] - p[1], p[8] - p[2], p[9] - p[3]
local cx, cy, cz = uy * vz - uz * vy, uz * vx - ux * vz, ux * vy - uy * vx
return math.sqrt(cx * cx + cy * cy + cz * cz) / 2
end
local function polyArea(p: { number }): number
local a = 0
for k = 1, #p // 3 - 2 do
a += area({ p[1], p[2], p[3], p[k * 3 + 1], p[k * 3 + 2], p[k * 3 + 3], p[k * 3 + 4], p[k * 3 + 5], p[k * 3 + 6] })
end
return a
end
-- barycentric coordinates of x on the triangle's plane (nil when outside)
local function bary(tri: Tri, x: number, y: number, z: number): (number?, number?)
local p = tri.p
local ux, uy, uz = p[4] - p[1], p[5] - p[2], p[6] - p[3]
local vx, vy, vz = p[7] - p[1], p[8] - p[2], p[9] - p[3]
local wx, wy, wz = x - p[1], y - p[2], z - p[3]
local uu, uv, vv = ux * ux + uy * uy + uz * uz, ux * vx + uy * vy + uz * vz, vx * vx + vy * vy + vz * vz
local wu, wv = wx * ux + wy * uy + wz * uz, wx * vx + wy * vy + wz * vz
local den = uu * vv - uv * uv
if den == 0 then
return nil, nil
end
local b = (vv * wu - uv * wv) / den
local c = (uu * wv - uv * wu) / den
local tol = 1e-4
if b < -tol or c < -tol or b + c > 1 + tol then
return nil, nil
end
return b, c
end
local function compare(label: string, s: any, model: string, faces: any)
local node
for _, n in s.nodes do
if n.extras and n.extras.entity == tonumber(model) then
node = n
end
end
t:check(node and node.mesh, label .. ": entity " .. model .. " has a mesh")
local tris = {}
for _, tri in triangles(s, s.meshes[node.mesh]) do
if tri.tex ~= "base/curve" then -- the patch: qbsp has no patches
table.insert(tris, tri)
end
end
local ours, theirs = {}, {}
for _, tri in tris do
local n = tri.n
local k = key(n[1], n[2], n[3], n[1] * tri.p[1] + n[2] * tri.p[2] + n[3] * tri.p[3])
ours[k] = (ours[k] or 0) + area(tri.p)
end
for _, f in faces do
local k = key(f.plane[1], f.plane[2], f.plane[3], f.plane[4])
theirs[k] = (theirs[k] or 0) + polyArea(f.pts)
end
local bad = 0
for k, a in theirs do
if math.abs((ours[k] or 0) - a) > 0.05 then
bad += 1
t:note("%s model %s plane %s: %s vs qbsp %s", label, model, k, tostring(ours[k]), tostring(a))
end
end
for k in ours do
if not theirs[k] then
bad += 1
end
end
t:eq(bad, 0, label .. ": model " .. model .. " face area per plane")
local miss, off = 0, 0
for _, f in faces do
local fk = key(f.plane[1], f.plane[2], f.plane[3], f.plane[4])
for c = 0, #f.pts // 3 - 1 do
local x, y, z = f.pts[c * 3 + 1], f.pts[c * 3 + 2], f.pts[c * 3 + 3]
local s0 = (f.vecs[1] * x + f.vecs[2] * y + f.vecs[3] * z + f.vecs[4]) / f.size[1]
local t0 = (f.vecs[5] * x + f.vecs[6] * y + f.vecs[7] * z + f.vecs[8]) / f.size[2]
local found, best = false, math.huge
for _, tri in tris do
local n = tri.n
if tri.tex == f.tex and key(n[1], n[2], n[3], n[1] * tri.p[1] + n[2] * tri.p[2] + n[3] * tri.p[3]) == fk then
local b, cc = bary(tri, x, y, z)
if b and cc then
found = true
local u = tri.uv[1] + b * (tri.uv[3] - tri.uv[1]) + cc * (tri.uv[5] - tri.uv[1])
local v = tri.uv[2] + b * (tri.uv[4] - tri.uv[2]) + cc * (tri.uv[6] - tri.uv[2])
best = math.min(best, math.max(math.abs(u - s0) * f.size[1], math.abs(v - t0) * f.size[2]))
end
end
end
if not found then
miss += 1
if miss <= 3 then
local on = {}
for _, tri in tris do
local n = tri.n
if key(n[1], n[2], n[3], n[1] * tri.p[1] + n[2] * tri.p[2] + n[3] * tri.p[3]) == fk then
table.insert(on, tri.tex)
end
end
t:note("%s model %s: corner %s %s %s (%s) on %s, ours there: %s", label, model, x, y, z, f.tex, fk, table.concat(on, ","))
end
elseif best > 0.05 then
off += 1
end
end
end
t:eq(miss, 0, label .. ": model " .. model .. " every qbsp corner on one of our triangles")
t:eq(off, 0, label .. ": model " .. model .. " texture coordinates match qbsp")
end
for _, label in { "quake", "valve", "quake2", "quake3" } do
local c = Fx[label]
t:eq(F.detect(c.text), "map", label .. ": F.detect")
local s, err = MapFmt.decode(Bytes.reader(buffer.fromstring(c.text)), { files = c.files, hull = true })
t:check(s, label .. ": " .. tostring(err))
local scene = s :: any
t:eq(scene.meta.source.variant, ({ quake = "quake", valve = "valve220", quake2 = "quake2", quake3 = "quake3" } :: any)[label], label .. ": variant")
t:eq(scene.meta.up, "z", label .. ": z up")
for model, faces in c.models do
compare(label, scene, model, faces)
end
-- texture sizes found in the WAD / .wal files (Quake III needs images: 64 x 64 without decodeImage)
for _, m in scene.materials do
local want = c.sizes[m.name]
if want and label ~= "quake3" then
t:check(m.extras.map.width == want[1] and m.extras.map.height == want[2] and m.extras.map.sizeKnown, label .. ": size of " .. m.name)
end
end
-- entities: nodes with their keys in order
t:eq(#scene.meta.entities, 4, label .. ": entities")
local door = scene.nodes[3]
t:eq(door.name, "door1", label .. ": brush entity named by targetname")
t:eq(door.extras.classname, "func_door", label .. ": classname")
t:eq(table.concat(Types.keys(door.extras.keys), ","), "classname,targetname,angle", label .. ": key order")
local start = scene.nodes[4]
t:eq(start.translation and table.concat(start.translation, " "), "-128 -128 24", label .. ": point entity at its origin")
t:check(start.mesh == nil, label .. ": point entity without a mesh")
-- round trip: write, read again, same entities and geometry
local out, eerr = MapFmt.encode(scene)
t:check(out, label .. ": encode " .. tostring(eerr))
local again = MapFmt.decode(Bytes.reader(out :: buffer), { files = c.files, hull = true }) :: any
t:check(again ~= nil, label .. ": reload")
local a1, a2 = MapFmt.parse(c.text) :: any, MapFmt.parse(out :: buffer) :: any
local same = #a1.entities == #a2.entities
for i, e in a1.entities do
local e2 = a2.entities[i]
same = same and e2 ~= nil and #e.brushes == #e2.brushes
for k, v in e.keys do
same = same and e2.keys[k] == v
end
for bi, b in e.brushes do
local b2 = e2.brushes[bi]
same = same and b.type == b2.type and #(b.faces or {}) == #(b2.faces or {})
for fi, f in b.faces or {} do
local f2 = b2.faces[fi]
same = same and f.texture == f2.texture and table.concat(f.points, " ") == table.concat(f2.points, " ")
for _, fld in { "offset", "scale", "u", "v", "flags" } do
same = same and table.concat((f :: any)[fld] or {}, " ") == table.concat((f2 :: any)[fld] or {}, " ")
end
same = same and f.rotation == f2.rotation
if f.matrix then
same = same and table.concat(f.matrix[1], " ") == table.concat(f2.matrix[1], " ") and table.concat(f.matrix[2], " ") == table.concat(f2.matrix[2], " ")
end
end
if b.points then
same = same and table.concat(b.points, " ") == table.concat(b2.points, " ")
end
end
end
t:check(same, label .. ": write -> parse gives the same entities, brushes and faces")
t:eq(again.meta.source.variant, scene.meta.source.variant, label .. ": variant survives the round trip")
t:eq(#again.meshes, #scene.meshes, label .. ": meshes survive the round trip")
end
-- the Quake III patch: our grid = the Bezier evaluation
do
local c = Fx.quake3
local s = MapFmt.decode(Bytes.reader(buffer.fromstring(c.text)), { files = c.files }) :: any
t:eq(s.meta.source.patches, 1, "quake3: one patch")
local prim
for _, p in s.meshes[1].primitives do
if s.materials[p.material].name == "base/curve" then
prim = p
end
end
t:check(prim, "quake3: patch primitive")
local pos = Types.Scene.reader(prim.attributes.POSITION) :: any
local uv = Types.Scene.reader(prim.attributes.TEXCOORD_0) :: any
t:eq(prim.attributes.POSITION.count, c.patch.w * c.patch.h, "quake3: grid size")
local worst = 0
for k = 0, c.patch.w * c.patch.h - 1 do
for a = 0, 2 do
worst = math.max(worst, math.abs(pos(k, a) - c.patch.grid[k * 5 + a + 1]))
end
worst = math.max(worst, math.abs(uv(k, 0) - c.patch.grid[k * 5 + 4]) * 64, math.abs(uv(k, 1) - c.patch.grid[k * 5 + 5]) * 64)
end
t:check(worst < 1e-4, "quake3: patch points match the Bezier evaluation (" .. worst .. ")")
t:eq(s.textures[s.materials[prim.material].baseColorTexture.texture].uri, "textures/base/curve", "quake3: texture URI")
local lean = MapFmt.decode(Bytes.reader(buffer.fromstring(c.text)), { patchLevel = 1, skip = { "brick" } }) :: any
for _, p in lean.meshes[1].primitives do
t:check(lean.materials[p.material].name ~= "brick", "skip: brick left out")
end
end
-- options and conversions
do
local c = Fx.quake
local merged = MapFmt.decode(Bytes.reader(buffer.fromstring(c.text)), { files = c.files, hull = true, merge = true }) :: any
local plain = MapFmt.decode(Bytes.reader(buffer.fromstring(c.text)), { files = c.files }) :: any
local function count(sc: any): number
local n = 0
for _, p in sc.meshes[1].primitives do
n += p.indices.count
end
return n
end
t:check(count(merged) < count(plain), "hull + merge: fewer triangles than every face")
t:eq(plain.materials[1].extras.map.sizeKnown, true, "sizes from the worldspawn WAD")
local nowad = MapFmt.decode(Bytes.reader(buffer.fromstring(c.text))) :: any
t:eq(nowad.materials[1].extras.map.width, 64, "no WAD: 64 x 64")
local sized = MapFmt.decode(Bytes.reader(buffer.fromstring(c.text)), { textureSizes = { brick = { 8, 8 } } }) :: any
for _, m in sized.materials do
if m.name == "brick" then
t:eq(m.extras.map.width, 8, "textureSizes")
end
end
-- Quake standard -> Valve 220: same texture coordinates
local valve = assert(MapFmt.encode(plain, { variant = "valve220" }))
local v = MapFmt.decode(Bytes.reader(valve), { files = c.files }) :: any
t:eq(v.meta.source.variant, "valve220", "converted to Valve 220")
local u1 = Types.Scene.reader(plain.meshes[1].primitives[1].attributes.TEXCOORD_0) :: any
local u2 = Types.Scene.reader(v.meshes[1].primitives[1].attributes.TEXCOORD_0) :: any
local worst = 0
for k = 0, plain.meshes[1].primitives[1].attributes.TEXCOORD_0.count - 1 do
worst = math.max(worst, math.abs(u1(k, 0) - u2(k, 0)), math.abs(u1(k, 1) - u2(k, 1)))
end
t:check(worst < 1e-5, "Valve 220 conversion keeps the texture coordinates (" .. worst .. ")")
-- edits: a moved point entity writes its new origin
plain.nodes[4].translation = { 1, 2, 3 }
local moved = MapFmt.parse(assert(MapFmt.encode(plain))) :: any
t:eq(moved.entities[3].keys.origin, "1 2 3", "moved entity origin")
-- through the api
local viaApi = assert(F.model.load(c.text, { files = c.files }))
t:eq(viaApi.meta.source.format, "map", "F.model.load")
local saved = assert(F.save(viaApi, nil, { format = "map" }))
t:check(buffer.len(saved) > 100, "F.save as map")
end
-- sniffing and errors
do
local build = buffer.create(64)
buffer.writeu32(build, 0, 7)
t:eq(MapFmt.sniff(Bytes.reader(build)), 0, "Build engine (binary) .map: not ours")
t:eq(MapFmt.sniff(Bytes.reader(buffer.fromstring('{"classname": "x"}'))), 0, "JSON: not a map")
t:check(MapFmt.sniff(Bytes.reader(buffer.fromstring('{\n"classname" "worldspawn"\n}'))) > 0.5, "minimal map")
local _, e1 = MapFmt.decode(Bytes.reader(buffer.fromstring('{ "classname" "worldspawn" { ( 0 0 0 ) ( 1 0 0 ) brick')))
t:check(e1 and e1.code == Err.CORRUPT, "truncated face: " .. tostring(e1))
local _, e2 = MapFmt.decode(Bytes.reader(buffer.fromstring('{ "classname" "worldspawn" { brushDef3 { } } }')))
t:check(e2 and e2.code == Err.UNSUPPORTED, "Doom 3 brushDef3: unsupported")
local _, e3 = MapFmt.encode(Types.Scene.new())
t:check(e3 and e3.code == Err.ARG, "encode without entities")
local bad = assert(MapFmt.decode(Bytes.reader(buffer.fromstring(Fx.quake.text)))) :: any
bad.nodes[2].extras.keys.message = 'a "quoted" value'
local _, e4 = MapFmt.encode(bad)
t:check(e4 and e4.code == Err.ARG, "quotes in a value")
end
t:fuzz("decode", function(b: buffer)
return MapFmt.decode(Bytes.reader(b), { hull = true, merge = true })
end, { buffer.fromstring(Fx.quake.text), buffer.fromstring(Fx.quake3.text), buffer.fromstring(Fx.valve.text) }, { mutations = 60, garbage = 20 })
t:done()
+172
View File
@@ -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)