merge ws/source: VBSP v19-21, VMF, KeyValues / data/vdf, codecs/model/Displacement (with ws/quake's Brush / Patch / Miptex)

This commit is contained in:
4DBug committed 2026-11-01 19:46:56 -06:00
commit e100366cb8
44 files changed
+18855 -1508

No files matched your search

+9 -24
View File
@@ -4,6 +4,7 @@
-- size.
local Types = require("@rosetta/Types")
local Pixels = require("@rosetta/codecs/image/Pixels")
local Miptex = require("@rosetta/codecs/image/Miptex")
local Brush = {}
@@ -36,34 +37,18 @@ local function miptex(b: buffer, base: number, l: Lump, hl: boolean, pal: buffer
if n < 0 or n > 65536 or 4 + n * 4 > l.size then
return nil, "bad miptex lump"
end
local gpal = if pal then Pixels.palette(pal, 0, 256) else nil
local gpal = if pal and not hl then Pixels.palette(pal, 0, 256) else nil
for i = 0, n - 1 do
local o = readi32(b, at + 4 + i * 4)
if o < 0 or o + 40 > l.size then
local hd = if o >= 0 and o + 40 <= l.size then Miptex.header(b, at + o, l.size - o) else nil
if not hd then
out[i + 1] = { name = "missing" .. i, width = 64, height = 64, image = nil, texels = false }
else
local m = at + o
local name = cstr(b, m, 16)
local w, h, off0 = readu32(b, m + 16), readu32(b, m + 20), readu32(b, m + 24)
local t: Tex = { name = name, width = math.max(w, 1), height = math.max(h, 1), image = nil, texels = false }
if off0 ~= 0 and w > 0 and h > 0 and w * h <= maxPixels then
local px = m + off0
local need = w * h
local palAt = m + readu32(b, m + 36) + (w // 8) * (h // 8) + 2
if o + off0 + need <= l.size then
local p = gpal
if hl then
p = if palAt - at + 768 <= l.size then Pixels.palette(b, palAt, 256) else nil
end
local img = Types.Image.new(w, h)
if p then
Pixels.indexed(b, px, w, 8, img.pixels, w, h, true, p)
else
for k = 0, need - 1 do
writeu32(img.pixels, k * 4, 0xFF000000 + buffer.readu8(b, px + k) * 0x10101)
end
end
img.meta.source = { format = "bsp", miptex = name, palette = p ~= nil }
local t: Tex = { name = hd.name, width = math.max(hd.width, 1), height = math.max(hd.height, 1), image = nil, texels = false }
if hd.offsets[1] ~= 0 and hd.width * hd.height <= maxPixels then
local img = Miptex.decode(b, at + o, l.size - o, { palette = gpal, goldsrc = hl, keyed = false, maxPixels = maxPixels })
if img then
img.meta.source = { format = "bsp", miptex = hd.name, palette = img.meta.source and img.meta.source.palette }
t.image = img
end
end
+19 -46
View File
@@ -1,7 +1,9 @@
--!strict
-- model/bsp/Quake3: Quake III Arena maps (IBSP 46; RTCW 47 has the same layout) -> Scene, from the Unofficial Quake 3
-- Map Specs (Kekoa Proudfoot; no code taken). Lightmaps are 128 x 128 RGB; billboards (flares) are skipped.
-- Map Specs (Kekoa Proudfoot; no code taken). Lightmaps are 128 x 128 RGB; billboards (flares) are skipped; patches
-- through codecs/model/Patch.
local Types = require("@rosetta/Types")
local Patch = require("@rosetta/codecs/model/Patch")
local Quake3 = {}
@@ -81,52 +83,23 @@ function Quake3.decode(b: buffer, base: number, lumps: { [string]: Lump }, opts:
counts[if kind == 1 then "polygons" else "meshes"] += 1
elseif kind == 2 and first >= 0 and n >= 0 and first + n <= nV then
local w, h = readi32(b, o + 96), readi32(b, o + 100)
if w >= 3 and h >= 3 and w % 2 == 1 and h % 2 == 1 and w * h == n then
if Patch.valid(w, h, n) then
counts.patches += 1
local L = level
for py = 0, (h - 1) // 2 - 1 do
for px = 0, (w - 1) // 2 - 1 do
local ctrl: { { number } } = {}
for j = 0, 2 do
for i = 0, 2 do
ctrl[j * 3 + i + 1] = vertex(first + (py * 2 + j) * w + px * 2 + i)
end
end
local grid: { number } = {}
for gy = 0, L do
local tv = gy / L
for gx = 0, L do
local tu = gx / L
local bu = { (1 - tu) ^ 2, 2 * tu * (1 - tu), tu * tu }
local bv = { (1 - tv) ^ 2, 2 * tv * (1 - tv), tv * tv }
local v = table.create(14, 0)
for j = 0, 2 do
for i = 0, 2 do
local wgt = bu[i + 1] * bv[j + 1]
local cp = ctrl[j * 3 + i + 1]
for k = 1, 14 do
v[k] += cp[k] * wgt
end
end
end
local l = math.sqrt(v[8] ^ 2 + v[9] ^ 2 + v[10] ^ 2)
if l > 0 then
v[8], v[9], v[10] = v[8] / l, v[9] / l, v[10] / l
end
grid[gy * (L + 1) + gx + 1] = addExtra(v)
end
end
for gy = 0, L - 1 do
for gx = 0, L - 1 do
local a, c2 = grid[gy * (L + 1) + gx + 1], grid[gy * (L + 1) + gx + 2]
local d, e = grid[(gy + 1) * (L + 1) + gx + 1], grid[(gy + 1) * (L + 1) + gx + 2]
-- Quake's control grids are clockwise-front
for _, v in { a, d, c2, c2, d, e } do
table.insert(tris, v)
end
end
end
end
local ctrl = table.create(n * 14, 0) :: { number }
for k = 0, n - 1 do
table.move(vertex(first + k), 1, 14, k * 14 + 1, ctrl)
end
local pts, gw, gh = Patch.grid(ctrl, w, h, 14, level, level, maxV)
if not pts then
return nil, "limit: too many patch vertices"
end
Patch.normalize(pts, 14, 7)
local ids = table.create(gw * gh) :: { number }
for k = 0, gw * gh - 1 do
ids[k + 1] = addExtra(table.move(pts, k * 14 + 1, k * 14 + 14, 1, table.create(14, 0)) :: { number })
end
for _, v in Patch.triangles(gw, gh) do
table.insert(tris, ids[v + 1])
end
else
counts.skipped += 1
+1 -1
View File
@@ -17,7 +17,7 @@ local Bsp = {
category = "model",
extensions = { "bsp" },
mime = { "model/x-bsp" },
deps = { "core/Err", "core/Bytes", "core/Input", "Types", "codecs/image/Pixels" },
deps = { "core/Err", "core/Bytes", "core/Input", "Types", "codecs/image/Pixels", "codecs/image/Miptex", "codecs/model/Patch" },
caps = { decode = true, encode = false, variants = { "quake", "halflife", "quake2", "quake3" }, lightmaps = "quake3" },
}
+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
+222
View File
@@ -0,0 +1,222 @@
--!strict
-- model/vbsp/Faces: VBSP faces -> primitives, one per (model, texdata), from public/bspfile.h of the Source SDK 2013
-- (dface_t, texinfo_t, dtexdata_t, ddispinfo_t, CDispVert); displacements through codecs/model/Displacement.
local Types = require("@rosetta/Types")
local Displacement = require("@rosetta/codecs/model/Displacement")
local Faces = {}
local readi32, readu16, readi16, readf32, readu8 = buffer.readi32, buffer.readu16, buffer.readi16, buffer.readf32, buffer.readu8
export type Lump = { buf: buffer, at: number, size: number }
export type Input = {
planes: Lump,
vertices: Lump,
edges: Lump,
surfedges: Lump,
faces: Lump,
texinfo: Lump,
texdata: Lump,
models: Lump,
dispinfo: Lump,
dispverts: Lump,
tools: boolean, -- keep nodraw / skip / hint / sky faces
maxVertices: number,
}
export type Group = { model: number, texdata: number, pos: { number }, nrm: { number }, uv: { number }, blend: { number }?, idx: { number } }
-- SURF_SKY2D | SURF_SKY | SURF_NODRAW | SURF_HINT | SURF_SKIP
local TOOL_FLAGS = 0x2 + 0x4 + 0x80 + 0x100 + 0x200
local function emit(g: Group, x: number, y: number, z: number, nx: number, ny: number, nz: number, u: number, v: number): number
local pos, nrm, uv = g.pos, g.nrm, g.uv
local k = #pos
pos[k + 1], pos[k + 2], pos[k + 3] = x, y, z
nrm[k + 1], nrm[k + 2], nrm[k + 3] = nx, ny, nz
local q = #uv
uv[q + 1], uv[q + 2] = u, v
return k // 3
end
local function displacement(I: Input, g: Group, d: number, poly: { number }, nx: number, ny: number, nz: number, tex: { number }): string?
local di = I.dispinfo
if (d + 1) * 176 > di.size then
return "dispinfo index out of range"
end
local o = di.at + d * 176
local b = di.buf
local vstart, power = readi32(b, o + 12), readi32(b, o + 20)
if #poly ~= 12 then
return nil -- not a quad: the base face is kept
end
if power < 1 or power > 4 then
return "displacement power " .. power
end
local n = 2 ^ power + 1
local dv = I.dispverts
if vstart < 0 or (vstart + n * n) * 20 > dv.size then
return "displacement vertices out of range"
end
-- CDispVert: vector * dist, then alpha (0 .. 255)
local offsets: { number } = table.create(n * n * 3) :: any
for k = 0, n * n - 1 do
local vo = dv.at + (vstart + k) * 20
local dist = readf32(dv.buf, vo + 12)
offsets[k * 3 + 1] = readf32(dv.buf, vo) * dist
offsets[k * 3 + 2] = readf32(dv.buf, vo + 4) * dist
offsets[k * 3 + 3] = readf32(dv.buf, vo + 8) * dist
end
local surf, err = Displacement.surface(poly, { readf32(b, o), readf32(b, o + 4), readf32(b, o + 8) }, power, offsets, { nx, ny, nz })
if not surf then
return err
end
local base = #g.pos // 3
local blend = g.blend or {}
g.blend = blend
local flat, pos, nrm = surf.flat, surf.pos, surf.nrm
for k = 0, n * n - 1 do
local x, y, z = flat[k * 3 + 1], flat[k * 3 + 2], flat[k * 3 + 3]
emit(g, pos[k * 3 + 1], pos[k * 3 + 2], pos[k * 3 + 3], nrm[k * 3 + 1], nrm[k * 3 + 2], nrm[k * 3 + 3],
(x * tex[1] + y * tex[2] + z * tex[3] + tex[4]) / tex[9], (x * tex[5] + y * tex[6] + z * tex[7] + tex[8]) / tex[10])
blend[base + k + 1] = math.clamp(readf32(dv.buf, dv.at + (vstart + k) * 20 + 16) / 255, 0, 1)
end
local idx = g.idx
for _, v in surf.idx do
idx[#idx + 1] = base + v
end
return nil
end
function Faces.build(I: Input): ({ Group }?, string?, number?)
local V, E, SE, F, TI, TD, P = I.vertices, I.edges, I.surfedges, I.faces, I.texinfo, I.texdata, I.planes
local nV, nE, nSE, nF = V.size // 12, E.size // 4, SE.size // 4, F.size // 56
local nTI, nTD, nP = TI.size // 72, TD.size // 32, P.size // 20
local faceModel: { [number]: number } = {}
local M = I.models
for m = 0, M.size // 48 - 1 do
local o = M.at + m * 48
local first, count = readi32(M.buf, o + 40), readi32(M.buf, o + 44)
if first >= 0 and count > 0 and first + count <= nF then
for f = first, first + count - 1 do
if faceModel[f] == nil then
faceModel[f] = m
end
end
end
end
local groups: { Group } = {}
local byKey: { [number]: Group } = {}
local skipped, verts = 0, 0
local poly: { number } = {}
for f = 0, nF - 1 do
local fo = F.at + f * 56
local fb = F.buf
local plane, side = readu16(fb, fo), readu8(fb, fo + 2)
local firstEdge, numEdges = readi32(fb, fo + 4), readi16(fb, fo + 8)
local ti, disp = readi16(fb, fo + 10), readi16(fb, fo + 12)
local model = faceModel[f] or 0
if numEdges < 3 or firstEdge < 0 or firstEdge + numEdges > nSE or plane >= nP or ti < 0 or ti >= nTI then
skipped += 1
continue
end
local to = TI.at + ti * 72
local flags, td = readi32(TI.buf, to + 64), readi32(TI.buf, to + 68)
if not I.tools and bit32.band(flags, TOOL_FLAGS) ~= 0 then
continue
end
local w, h = 1, 1
if td >= 0 and td < nTD then
w = math.max(readi32(TD.buf, TD.at + td * 32 + 16), 1)
h = math.max(readi32(TD.buf, TD.at + td * 32 + 20), 1)
else
td = -1
end
table.clear(poly)
local ok = true
for k = 0, numEdges - 1 do
local se = readi32(SE.buf, SE.at + (firstEdge + k) * 4)
local e = math.abs(se)
if e >= nE then
ok = false
break
end
local vi = readu16(E.buf, E.at + e * 4 + (if se >= 0 then 0 else 2))
if vi >= nV then
ok = false
break
end
local vo = V.at + vi * 12
poly[k * 3 + 1], poly[k * 3 + 2], poly[k * 3 + 3] = readf32(V.buf, vo), readf32(V.buf, vo + 4), readf32(V.buf, vo + 8)
end
if not ok then
skipped += 1
continue
end
local po = P.at + plane * 20
local nx, ny, nz = readf32(P.buf, po), readf32(P.buf, po + 4), readf32(P.buf, po + 8)
if side ~= 0 then
nx, ny, nz = -nx, -ny, -nz
end
local key = model * 65536 + td + 1
local grp: Group = byKey[key]
if not grp then
grp = { model = model, texdata = td, pos = {}, nrm = {}, uv = {}, blend = nil :: { number }?, idx = {} }
byKey[key] = grp
table.insert(groups, grp)
end
local tex = {
readf32(TI.buf, to), readf32(TI.buf, to + 4), readf32(TI.buf, to + 8), readf32(TI.buf, to + 12),
readf32(TI.buf, to + 16), readf32(TI.buf, to + 20), readf32(TI.buf, to + 24), readf32(TI.buf, to + 28), w, h,
}
local before = #grp.pos
local done = false
if disp >= 0 then
local derr = displacement(I, grp, disp, poly, nx, ny, nz, tex)
if derr then
return nil, derr, fo
end
done = #grp.pos > before
end
if not done then
local n = numEdges
-- Newell's normal against the plane: the stored winding is clockwise from the front
local ax, ay, az = 0, 0, 0
for k = 0, n - 1 do
local a, b = k * 3, ((k + 1) % n) * 3
ax += (poly[a + 2] - poly[b + 2]) * (poly[a + 3] + poly[b + 3])
ay += (poly[a + 3] - poly[b + 3]) * (poly[a + 1] + poly[b + 1])
az += (poly[a + 1] - poly[b + 1]) * (poly[a + 2] + poly[b + 2])
end
local flip = ax * nx + ay * ny + az * nz < 0
local first = -1
for k = 0, n - 1 do
local x, y, z = poly[k * 3 + 1], poly[k * 3 + 2], poly[k * 3 + 3]
local id = emit(grp, x, y, z, nx, ny, nz, (x * tex[1] + y * tex[2] + z * tex[3] + tex[4]) / w, (x * tex[5] + y * tex[6] + z * tex[7] + tex[8]) / h)
if first < 0 then
first = id
end
end
local idx = grp.idx
for k = 1, n - 2 do
local b, c = first + k, first + k + 1
if flip then
b, c = c, b
end
idx[#idx + 1], idx[#idx + 2], idx[#idx + 3] = first, b, c
end
end
verts += (#grp.pos - before) // 3
if verts > I.maxVertices then
return nil, "limit: over maxVertices", fo
end
end
return groups, nil, skipped
end
function Faces.primitive(g: Group, material: number?): Types.Primitive
local prim = Displacement.primitive(g)
prim.material = material
return prim
end
return Faces
+90
View File
@@ -0,0 +1,90 @@
--!strict
-- model/vbsp/Props: the static prop game lump ("sprp", StaticPropLump_t versions 4 .. 13 of public/gamebspfile.h and
-- the variants srctools / BSPSource list). The record size is the lump's remainder over the prop count, so the
-- version only picks the optional fields: forced fade scale (v5+), uniform scale (v11 / v12: last f32), x/y/z scale
-- (v13: last 3 f32), u32 leaf indices (v12+).
local Props = {}
local readi32, readu16, readu8, readf32 = buffer.readi32, buffer.readu16, buffer.readu8, buffer.readf32
export type Prop = {
model: string,
origin: { number },
angles: { number }, -- pitch, yaw, roll (degrees)
scale: { number },
skin: number,
solid: number,
flags: number,
fadeMin: number,
fadeMax: number,
fadeScale: number?,
lightingOrigin: { number },
}
function Props.read(b: buffer, at: number, size: number, version: number, maxProps: number): ({ Prop }?, string?)
local e = at + size
local p = at
if p + 4 > e then
return {}, nil
end
local nd = readi32(b, p)
p += 4
if nd < 0 or p + nd * 128 > e then
return nil, "static prop model names past the end"
end
local names: { string } = table.create(nd) :: any
for i = 0, nd - 1 do
names[i + 1] = string.match(buffer.readstring(b, p + i * 128, 128), "^[^%z]*") :: string
end
p += nd * 128
if p + 4 > e then
return nil, "static prop leaves truncated"
end
local nl = readi32(b, p)
p += 4
local leafSize = if version >= 12 then 4 else 2
if nl < 0 or p + nl * leafSize + 4 > e then
return nil, "static prop leaves past the end"
end
p += nl * leafSize
local np = readi32(b, p)
p += 4
if np < 0 or np > maxProps then
return nil, "limit: " .. np .. " static props"
end
local out: { Prop } = table.create(np) :: any
if np == 0 then
return out, nil
end
local rec = (e - p) // np
if rec < 56 then
return nil, "static prop records shorter than 56 bytes"
end
for i = 0, np - 1 do
local o = p + i * rec
local mi = readu16(b, o + 24)
local scale = { 1, 1, 1 }
if version == 13 and rec >= 88 then
scale = { readf32(b, o + rec - 12), readf32(b, o + rec - 8), readf32(b, o + rec - 4) }
elseif (version == 11 or version == 12) and rec >= 80 then
local s = readf32(b, o + rec - 4)
scale = { s, s, s }
end
out[i + 1] = {
model = names[mi + 1] or "",
origin = { readf32(b, o), readf32(b, o + 4), readf32(b, o + 8) },
angles = { readf32(b, o + 12), readf32(b, o + 16), readf32(b, o + 20) },
scale = scale,
solid = readu8(b, o + 30),
flags = readu8(b, o + 31),
skin = readi32(b, o + 32),
fadeMin = readf32(b, o + 36),
fadeMax = readf32(b, o + 40),
lightingOrigin = { readf32(b, o + 44), readf32(b, o + 48), readf32(b, o + 52) },
fadeScale = if version >= 5 and rec >= 60 then readf32(b, o + 56) else nil,
}
end
return out, nil
end
return Props
+444
View File
@@ -0,0 +1,444 @@
--!strict
-- model/vbsp: compiled Source engine maps (VBSP 19 / 20 / 21: HL2, TF2, L4D2's lump header, Portal 2 / CS:GO), read,
-- from public/bspfile.h and gamebspfile.h of the Source SDK 2013 (no code taken). Supports: brush faces per bmodel and
-- texdata, displacements, static props (game lump v4 .. v13) as nodes with extras.model, brush entities placed by
-- their origin / angles, point / spot / sun lights, entities (meta.entities), Valve LZMA lumps, the pak lump as a
-- nested Archive (meta.pak). Map units (inches), z up. Not supported: lightmaps, visibility, collision, Xbox 360
-- (big-endian) and Titanfall / Apex rBSP, writing.
-- ------------------------------------------------------------------------------------------------ requires
local Err = require("@rosetta/core/Err")
local Bytes = require("@rosetta/core/Bytes")
local Types = require("@rosetta/Types")
local Lzma = require("@rosetta/codecs/compress/Lzma")
local KeyValues = require("@rosetta/codecs/text/KeyValues")
local Mat4 = require("@rosetta/codecs/model/Mat4")
local Zip = require("@rosetta/containers/Zip")
local Archive = require("@rosetta/containers/Archive")
local Faces = require("@rosetta/model/vbsp/Faces")
local Props = require("@rosetta/model/vbsp/Props")
-- ------------------------------------------------------------------------------------------------ contract
local Vbsp = {
name = "vbsp",
category = "model",
extensions = { "bsp" },
mime = { "model/x-vbsp" },
deps = { "core/Err", "core/Bytes", "Types", "codecs/compress/Lzma", "codecs/text/KeyValues", "codecs/model/Mat4", "codecs/model/Displacement", "containers/Zip", "containers/Archive" },
caps = { decode = true, encode = false, versions = { 19, 20, 21 }, displacements = true, staticProps = true, pak = true },
}
-- ------------------------------------------------------------------------------------------------ types
export type DecodeOptions = {
tools: boolean?, -- keep nodraw / skip / hint / sky faces, default false
pak: boolean?, -- meta.pak and textures from it, default true
maxBytes: number?, -- per decompressed lump, default 2^28
maxVertices: number?, -- default 2^24
maxProps: number?, -- default 2^20
}
-- ------------------------------------------------------------------------------------------------ constants
local L = {
ENTITIES = 0, PLANES = 1, TEXDATA = 2, VERTEXES = 3, TEXINFO = 6, FACES = 7, EDGES = 12, SURFEDGES = 13,
MODELS = 14, DISPINFO = 26, DISP_VERTS = 33, GAME_LUMP = 35, PAKFILE = 40, TEXDATA_STRING_DATA = 43,
TEXDATA_STRING_TABLE = 44, FACES_HDR = 58,
}
local HEADER = 8 + 64 * 16 + 4
local SPRP = 0x73707270 -- 'sprp' read as a little-endian i32
-- ------------------------------------------------------------------------------------------------ sniff
function Vbsp.sniff(r: Bytes.Reader): number
if r:remaining() < HEADER or r:peek(4) ~= "VBSP" then
return 0
end
local v = buffer.readi32(r.buf, r.pos + 4)
return if v >= 19 and v <= 21 then 1 else 0.5
end
-- ------------------------------------------------------------------------------------------------ decode
type Lump = Faces.Lump
local function angles(p: number, y: number, r: number): { number }
return Mat4.quat(Mat4.euler(r, p, y, "xyz"))
end
local function qmul(a: { number }, b: { number }): { number }
local ax, ay, az, aw = a[1], a[2], a[3], a[4]
local bx, by, bz, bw = b[1], b[2], b[3], b[4]
return {
aw * bx + ax * bw + ay * bz - az * by,
aw * by - ax * bz + ay * bw + az * bx,
aw * bz + ax * by - ay * bx + az * bw,
aw * bw - ax * bx - ay * by - az * bz,
}
end
local function vec3(s: any): { number }?
if type(s) ~= "string" 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
-- Valve's LZMA lump: "LZMA", u32 actualSize, u32 lzmaSize, 5 property bytes, the raw stream
local function unlzma(b: buffer, at: number, size: number, maxBytes: number): (buffer?, string?)
if size < 17 then
return nil, "truncated LZMA lump header"
end
local actual, packed = buffer.readu32(b, at + 4), buffer.readu32(b, at + 8)
if actual > maxBytes then
return nil, "limit: LZMA lump of " .. actual .. " bytes"
end
if packed > size - 17 then
return nil, "LZMA lump runs past the end"
end
local props = buffer.create(5)
buffer.copy(props, 0, b, at + 12, 5)
local out, err = Lzma.lzma(b, at + 17, packed, props, actual, { maxBytes = maxBytes })
if not out then
return nil, "LZMA lump: " .. tostring(if type(err) == "table" then err.message else err)
end
return out, nil
end
local function isLzma(b: buffer, at: number, size: number): boolean
return size >= 17 and buffer.readstring(b, at, 4) == "LZMA"
end
local function pakArchive(src: buffer, maxBytes: number): (any, Err.Err?)
local zc, err = Zip.open(src)
if not zc then
return nil, err
end
local a = Archive.new("zip")
for _, e in zc:list() do
local entry: any = {
name = e.name,
size = e.size,
compressedSize = e.compressedSize,
method = if e.method == 0 then "stored" elseif e.method == 8 then "deflate" elseif e.method == 14 then "lzma" else tostring(e.method),
mtime = e.mtime,
dir = e.isDir,
}
entry.load = function(): (buffer?, Err.Err?)
if e.method ~= 14 then
return zc:read(e)
end
-- APPNOTE 5.8.8: u8 major, u8 minor, u16 properties size, properties, then the LZMA stream (CS:GO paks)
local zb = zc.buf
for _, s in Zip._starts(zb, e) do
if s + 9 <= buffer.len(zb) then
local psize = buffer.readu16(zb, s + 2)
local start = s + 4 + psize
local n = math.min(e.compressedSize - 4 - psize, buffer.len(zb) - start)
if psize >= 5 and n > 0 and e.size <= maxBytes then
local props = buffer.create(5)
buffer.copy(props, 0, zb, s + 4, 5)
local out = Lzma.lzma(zb, start, n, props, e.size, { maxBytes = maxBytes })
if out then
return out, nil
end
end
end
end
return nil, Err.new(Err.CORRUPT, e.name .. ": bad LZMA entry")
end
Archive.put(a, entry)
end
a.meta.source = { format = "zip", lump = "pakfile" }
return a, nil
end
local function light(scene: Types.Scene, e: any, class: string): (number?, { number }?)
local l = vec3(e._light)
local rgb: { number } = { 1, 1, 1 }
local intensity = 1
if l then
rgb = { l[1] / 255, l[2] / 255, l[3] / 255 }
local m = type(e._light) == "string" and string.match(e._light, "^%s*%S+%s+%S+%s+%S+%s+(%S+)")
intensity = (m and tonumber(m)) or 200
end
local lt: Types.Light = nil :: any
if class == "light" then
lt = { name = nil :: string?, type = "point", color = rgb, intensity = intensity }
elseif class == "light_spot" then
local outer = tonumber(e._cone) or 45
local inner = tonumber(e._inner_cone) or math.min(30, outer)
lt = { name = nil :: string?, type = "spot", color = rgb, intensity = intensity, innerCone = math.rad(math.min(inner, outer)), outerCone = math.rad(outer) }
else
lt = { name = nil :: string?, type = "directional", color = rgb, intensity = intensity }
end
lt.name = if type(e.targetname) == "string" then e.targetname else class
table.insert(scene.lights, lt :: any)
local ang = vec3(e.angles) or { 0, 0, 0 }
if type(e.pitch) == "string" and tonumber(e.pitch) then
ang[1] = -(tonumber(e.pitch) :: number) -- the FGD's angle_negative_pitch
end
-- the light shines along the entity's forward (+x); a glTF light along -z
return #scene.lights, qmul(angles(ang[1], ang[2], ang[3]), Mat4.axisAngle(0, 1, 0, -90))
end
function Vbsp.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Scene?, Err.Err?)
local o: DecodeOptions = opts or {}
local b, base = r.buf, r.base
local size = r.limit - r.base
if size < HEADER then
return nil, Err.new(Err.TRUNCATED, "header", 0)
end
if buffer.readstring(b, base, 4) ~= "VBSP" then
return nil, Err.new(Err.CORRUPT, "not a VBSP file", 0)
end
local version = buffer.readi32(b, base + 4)
if version < 19 or version > 21 then
return nil, Err.new(Err.UNSUPPORTED, "VBSP version " .. version, 4)
end
local maxBytes = o.maxBytes or 2 ^ 28
-- L4D2 swaps lump_t to { version, fileofs, filelen, fourCC }: the first lump's version is 0 where an offset is >= 1036
local l4d2 = version == 21 and buffer.readu32(b, base + 8) == 0 and buffer.readu32(b, base + 12) >= HEADER
local dir: { { at: number, size: number, version: number, fourcc: number } } = {}
for i = 0, 63 do
local p = base + 8 + i * 16
local a, c, d, f = buffer.readi32(b, p), buffer.readi32(b, p + 4), buffer.readi32(b, p + 8), buffer.readi32(b, p + 12)
local at, n, v = a, c, d
if l4d2 then
v, at, n = a, c, d
end
if n < 0 or at < 0 or (n > 0 and at + n > size) then
return nil, Err.new(Err.TRUNCATED, "lump " .. i .. " past the end", p - base)
end
dir[i] = { at = at, size = n, version = v, fourcc = f }
end
local cache: { [number]: Lump } = {}
local compressed = false
local function lump(i: number): (Lump?, string?)
local c = cache[i]
if c then
return c, nil
end
local d = dir[i]
local out: Lump
if d.size > 0 and isLzma(b, base + d.at, d.size) and i ~= L.PAKFILE and i ~= L.GAME_LUMP then
local u, err = unlzma(b, base + d.at, d.size, maxBytes)
if not u then
return nil, "lump " .. i .. ": " .. tostring(err)
end
compressed = true
out = { buf = u, at = 0, size = buffer.len(u) }
else
out = { buf = b, at = base + d.at, size = d.size }
end
cache[i] = out
return out, nil
end
local need: { [string]: Lump } = {}
for name, idx in { planes = L.PLANES, vertices = L.VERTEXES, edges = L.EDGES, surfedges = L.SURFEDGES, faces = L.FACES, texinfo = L.TEXINFO, texdata = L.TEXDATA, models = L.MODELS, dispinfo = L.DISPINFO, dispverts = L.DISP_VERTS, strings = L.TEXDATA_STRING_DATA, table = L.TEXDATA_STRING_TABLE, entities = L.ENTITIES } :: { [string]: number } do
local lp, err = lump(idx)
if not lp then
return nil, Err.from(err)
end
need[name] = lp
end
if need.faces.size == 0 then
local hdr, err = lump(L.FACES_HDR)
if not hdr then
return nil, Err.from(err)
end
need.faces = hdr
end
local groups, ferr, skipped = Faces.build({
planes = need.planes, vertices = need.vertices, edges = need.edges, surfedges = need.surfedges,
faces = need.faces, texinfo = need.texinfo, texdata = need.texdata, models = need.models,
dispinfo = need.dispinfo, dispverts = need.dispverts, tools = o.tools == true,
maxVertices = o.maxVertices or 2 ^ 24,
})
if not groups then
return nil, Err.from(ferr, skipped and skipped - base)
end
local scene = Types.Scene.new()
scene.meta.up = "z"
scene.meta.unit = 0.0254
local pak: any = nil
local pd = dir[L.PAKFILE]
if o.pak ~= false and pd.size > 0 then
local src = buffer.create(pd.size)
buffer.copy(src, 0, b, base + pd.at, pd.size)
pak = pakArchive(src, maxBytes)
scene.meta.pak = pak
end
-- texdata -> material + texture (materials/<name>.vtf, from the pak when it is there)
local TD, ST, SS = need.texdata, need.table, need.strings
local nTD = TD.size // 32
local matOf: { [number]: number } = {}
local function material(td: number): number?
if td < 0 or td >= nTD then
return nil
end
local m = matOf[td]
if m then
return m
end
local to = TD.at + td * 32
local si = buffer.readi32(TD.buf, to + 12)
local name = "texdata" .. td
if si >= 0 and (si + 1) * 4 <= ST.size then
local off = buffer.readi32(ST.buf, ST.at + si * 4)
if off >= 0 and off < SS.size then
name = string.match(buffer.readstring(SS.buf, SS.at + off, math.min(SS.size - off, 256)), "^[^%z]*") :: string
end
end
local path = "materials/" .. string.lower((string.gsub(name, "\\", "/")))
local tex: Types.Texture = { name = name, uri = path .. ".vtf" }
if pak then
local zc = pak :: any
local ok, data = pcall(zc.read, zc, path .. ".vtf")
if ok and type(data) == "buffer" then
tex.data, tex.mime, tex.uri = data, "image/vnd-valve.source.texture", nil
end
end
table.insert(scene.textures, tex)
local mat = Types.Scene.material(name)
mat.metallic = 0
mat.baseColorTexture = { texture = #scene.textures }
mat.extras = {
vbsp = {
vmt = path .. ".vmt",
width = buffer.readi32(TD.buf, to + 16),
height = buffer.readi32(TD.buf, to + 20),
reflectivity = { buffer.readf32(TD.buf, to), buffer.readf32(TD.buf, to + 4), buffer.readf32(TD.buf, to + 8) },
},
}
table.insert(scene.materials, mat)
matOf[td] = #scene.materials
return #scene.materials
end
local root: Types.Node = { name = "vbsp", children = {} }
table.insert(scene.nodes, root)
scene.roots[1] = 1
local modelNode: { [number]: number } = {}
for _, g in groups do
local node = modelNode[g.model]
if not node then
local name = if g.model == 0 then "world" else "*" .. g.model
table.insert(scene.meshes, { name = name, primitives = {} })
table.insert(scene.nodes, { name = name, children = {}, mesh = #scene.meshes, extras = { vbsp = { model = g.model } } })
node = #scene.nodes
modelNode[g.model] = node
table.insert(root.children, node)
end
local mesh = scene.meshes[scene.nodes[node].mesh :: number]
table.insert(mesh.primitives, Faces.primitive(g, material(g.texdata)))
end
-- entities
local E = need.entities
local text = string.match(buffer.readstring(E.buf, E.at, E.size), "^[^%z]*") :: string
local blocks, eerr = KeyValues.entities(text)
if not blocks then
return nil, Err.new((eerr :: Err.Err).code, "entity lump: " .. (eerr :: Err.Err).message, dir[L.ENTITIES].at)
end
local ents: { any } = table.create(#blocks)
for i, blk in blocks do
local e = KeyValues.toObject(blk)
ents[i] = e
local class = if type(e.classname) == "string" then e.classname else ""
local mdl = if type(e.model) == "string" then string.match(e.model, "^%*(%d+)$") else nil
local mi = mdl and tonumber(mdl)
if mi and mi > 0 and modelNode[mi] then
local node = scene.nodes[modelNode[mi]]
node.name = if type(e.targetname) == "string" then e.targetname else class
local org = vec3(e.origin)
if org then
node.translation = org
end
local ang = vec3(e.angles)
if ang then
node.rotation = angles(ang[1], ang[2], ang[3])
end
local x: any = node.extras
x.vbsp.entity = i
elseif class == "light" or class == "light_spot" or class == "light_environment" then
local li, rot = light(scene, e, class)
table.insert(scene.nodes, { name = scene.lights[li :: number].name, children = {}, light = li, translation = vec3(e.origin), rotation = rot, extras = { vbsp = { entity = i } } })
table.insert(root.children, #scene.nodes)
end
end
scene.meta.entities = ents
-- game lumps
local spVersion: number? = nil
local G = dir[L.GAME_LUMP]
if G.size >= 4 then
local ga = base + G.at
local count = buffer.readi32(b, ga)
if count < 0 or 4 + count * 16 > G.size then
return nil, Err.new(Err.CORRUPT, "game lump directory", G.at)
end
for k = 0, count - 1 do
local eo = ga + 4 + k * 16
local id, flags, ver = buffer.readi32(b, eo), buffer.readu16(b, eo + 4), buffer.readu16(b, eo + 6)
local off, len = buffer.readi32(b, eo + 8), buffer.readi32(b, eo + 12)
if id == SPRP then
if off < 0 or len < 0 or off > size then
return nil, Err.new(Err.TRUNCATED, "static prop lump past the end", eo - base)
end
local pb, pat, plen = b, base + off, len
if bit32.band(flags, 1) ~= 0 or isLzma(b, base + off, math.min(size - off, 17)) then
if off + 17 > size then
return nil, Err.new(Err.TRUNCATED, "static prop lump past the end", eo - base)
end
local u, err = unlzma(b, base + off, size - off, maxBytes)
if not u then
return nil, Err.from(err, off)
end
pb, pat, plen = u, 0, buffer.len(u)
compressed = true
elseif off + len > size then
return nil, Err.new(Err.TRUNCATED, "static prop lump past the end", eo - base)
end
local props, perr = Props.read(pb, pat, plen :: number, ver, o.maxProps or 2 ^ 20)
if not props then
return nil, Err.from(perr, off)
end
spVersion = ver
for pi, p in props do
local nm = string.match(p.model, "([^/\\]+)%.%w+$") or p.model
table.insert(scene.nodes, {
name = nm,
children = {},
translation = p.origin,
rotation = angles(p.angles[1], p.angles[2], p.angles[3]),
scale = if p.scale[1] ~= 1 or p.scale[2] ~= 1 or p.scale[3] ~= 1 then p.scale else nil,
extras = {
model = p.model,
vbsp = { staticProp = pi, angles = p.angles, skin = p.skin, solid = p.solid, flags = p.flags, fadeMin = p.fadeMin, fadeMax = p.fadeMax, lightingOrigin = p.lightingOrigin },
},
})
table.insert(root.children, #scene.nodes)
end
end
end
end
scene.meta.skippedFaces = skipped
scene.meta.source = {
format = "vbsp",
version = version,
variant = if l4d2 then "l4d2" else "v" .. version,
mapRevision = buffer.readi32(b, base + HEADER - 4),
compressed = compressed,
staticPropVersion = spVersion,
entities = text,
}
return scene, nil
end
return Vbsp
+422
View File
@@ -0,0 +1,422 @@
--!strict
-- model/vmf/Build: a parsed VMF (KeyValues pairs) -> Scene. Solids through codecs/model/Brush with Valve 220 axes
-- (u = p . axis / scale + shift, in texels), displacement sides through codecs/model/Displacement (a brush with one
-- keeps only its displaced sides, as vbsp does), a mesh per entity with solids, point entities as nodes, cameras.
local Types = require("@rosetta/Types")
local KeyValues = require("@rosetta/codecs/text/KeyValues")
local Brush = require("@rosetta/codecs/model/Brush")
local Displacement = require("@rosetta/codecs/model/Displacement")
local Mat4 = require("@rosetta/codecs/model/Mat4")
local Build = {}
type Block = KeyValues.Block
export type Side = {
id: number?,
points: { number }, -- 9: the plane's three points
material: string,
uaxis: { number }, -- x, y, z, shift, scale
vaxis: { number },
disp: Block?,
}
export type Solid = { id: number?, sides: { Side }, editor: any, entity: number }
export type Options = {
tools: boolean,
size: (name: string) -> (number, number, boolean),
maxPolygons: number?,
}
local function nums(s: any): { number }
local out: { number } = {}
if type(s) ~= "string" then
return out
end
for w in string.gmatch(s, "[^%s%(%)%[%]]+") do
local n = tonumber(w)
if n then
table.insert(out, n)
end
end
return out
end
Build.nums = nums
local function get(b: Block, key: string): any
return KeyValues.get(b, key)
end
local function editor(b: Block): any
local e = KeyValues.find(b, "editor")
return if e and type(e.value) == "table" then KeyValues.toObject(e.value) else nil
end
function Build.solid(b: Block, entity: number): (Solid?, string?)
local sides: { Side } = {}
for _, p in KeyValues.all(b, "side") do
if type(p.value) == "table" then
local sb = p.value :: Block
local pts = nums(get(sb, "plane"))
if #pts ~= 9 then
return nil, "side without a 3-point plane"
end
local u, v = nums(get(sb, "uaxis")), nums(get(sb, "vaxis"))
local d = KeyValues.find(sb, "dispinfo")
table.insert(sides, {
id = tonumber(get(sb, "id")),
points = pts,
material = tostring(get(sb, "material") or ""),
uaxis = if #u >= 5 then u else { 1, 0, 0, 0, 1 },
vaxis = if #v >= 5 then v else { 0, -1, 0, 0, 1 },
disp = if d and type(d.value) == "table" then d.value :: Block else nil,
})
end
end
return { id = tonumber(get(b, "id")), sides = sides, editor = editor(b), entity = entity }, nil
end
function Build.face(s: Side): Brush.Face?
local p = s.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
return { plane = plane, texture = s.material, vecs = Brush.valveVecs(s.uaxis, s.vaxis, s.uaxis[5], s.vaxis[5]) }
end
local function rows(d: Block, name: string, per: number, n: number): { number }?
local blk = KeyValues.get(d, name)
if type(blk) ~= "table" then
return nil
end
local out: { number } = table.create(n * n * per, 0) :: any
for i = 0, n - 1 do
local r = nums(KeyValues.get(blk, "row" .. i))
for k = 1, math.min(#r, n * per) do
out[i * n * per + k] = r[k]
end
end
return out
end
type Acc = { pos: { number }, nrm: { number }, uv: { number }, idx: { number }, blend: { number } }
-- Hammer dispinfo: vertex = flat + normal * distance + offset + elevation * face normal (CMapDisp)
local function displace(s: Side, face: Brush.Face, poly: Brush.Polygon, acc: Acc, w: number, h: number): string?
local d = s.disp :: Block
local power = tonumber(KeyValues.get(d, "power")) or 0
if power < 1 or power > 4 or power % 1 ~= 0 then
return "displacement power " .. tostring(power)
end
local n = 2 ^ power + 1
local start = nums(KeyValues.get(d, "startposition"))
if #start < 3 then
return "displacement without a start position"
end
local normals, dists = rows(d, "normals", 3, n), rows(d, "distances", 1, n)
local offs, alphas = rows(d, "offsets", 3, n), rows(d, "alphas", 1, n)
local elev = tonumber(KeyValues.get(d, "elevation")) or 0
local pn = face.plane
local offsets: { number } = table.create(n * n * 3, 0) :: any
for k = 0, n * n - 1 do
for c = 1, 3 do
local v = elev * pn[c]
if normals and dists then
v += normals[k * 3 + c] * dists[k + 1]
end
if offs then
v += offs[k * 3 + c]
end
offsets[k * 3 + c] = v
end
end
-- Brush polygons wind counter-clockwise from the front; a face's own winding is clockwise
local pts = poly.points
local cw: { number } = {}
for k = #pts // 3 - 1, 0, -1 do
table.insert(cw, pts[k * 3 + 1])
table.insert(cw, pts[k * 3 + 2])
table.insert(cw, pts[k * 3 + 3])
end
local surf, err = Displacement.surface(cw, start, power, offsets, { pn[1], pn[2], pn[3] })
if not surf then
return err
end
local base = #acc.pos // 3
for k = 0, n * n - 1 do
local x, y, z = surf.flat[k * 3 + 1], surf.flat[k * 3 + 2], surf.flat[k * 3 + 3]
for c = 1, 3 do
table.insert(acc.pos, surf.pos[k * 3 + c])
table.insert(acc.nrm, surf.nrm[k * 3 + c])
end
local u, v = Brush.uv(face, x, y, z, w, h)
table.insert(acc.uv, u)
table.insert(acc.uv, v)
table.insert(acc.blend, math.clamp((alphas and alphas[k + 1] or 0) / 255, 0, 1))
end
for _, i in surf.idx do
table.insert(acc.idx, base + i)
end
return nil
end
local function isTool(name: string): boolean
return string.sub(string.lower(name), 1, 6) == "tools/"
end
-- the solids of one entity -> its primitives (material indices by name through matOf)
function Build.mesh(solids: { Solid }, o: Options, matOf: (string) -> number, name: string): (Types.Mesh?, string?)
local brushes: { { Brush.Face } } = {}
local sideOf: { { Side } } = {}
local hasDisp: { boolean } = {}
for _, s in solids do
local faces: { Brush.Face } = {}
local sides: { Side } = {}
local disp = false
for _, sd in s.sides do
local f = Build.face(sd)
if f then
table.insert(faces, f)
table.insert(sides, sd)
disp = disp or sd.disp ~= nil
end
end
if #faces >= 4 then
table.insert(brushes, faces)
table.insert(sideOf, sides)
table.insert(hasDisp, disp)
end
end
local polys, perr = Brush.polygons(brushes, { maxPolygons = o.maxPolygons })
if not polys then
return nil, perr
end
local keep: { Brush.Polygon } = {}
local disps: { [string]: Acc } = {}
local dispOrder: { string } = {}
for _, p in polys do
local sd = sideOf[p.brush][p.face]
if o.tools or not isTool(sd.material) then
if sd.disp then
local acc = disps[sd.material]
if not acc then
acc = { pos = {}, nrm = {}, uv = {}, idx = {}, blend = {} }
disps[sd.material] = acc
table.insert(dispOrder, sd.material)
end
local w, h = o.size(sd.material)
local err = displace(sd, brushes[p.brush][p.face], p, acc :: Acc, w, h)
if err then
return nil, err
end
elseif not hasDisp[p.brush] then
table.insert(keep, p)
end
end
end
local mesh: Types.Mesh = { name = name, primitives = {} }
local function size(n: string): (number, number)
local w, h = o.size(n)
return w, h
end
for _, b in Brush.primitives(keep, brushes, size) do
b.primitive.material = matOf(b.texture)
table.insert(mesh.primitives, b.primitive)
end
for _, m in dispOrder do
local prim = Displacement.primitive(disps[m] :: any)
prim.material = matOf(m)
table.insert(mesh.primitives, prim)
end
return mesh, nil
end
local function quat(p: number, y: number, r: number): { number }
return Mat4.quat(Mat4.euler(r, p, y, "xyz"))
end
-- a camera at position looking at look, z up: glTF cameras look along -z with +y up
local function lookAt(pos: { number }, look: { number }): { number }
local fx, fy, fz = look[1] - pos[1], look[2] - pos[2], look[3] - pos[3]
local l = math.sqrt(fx * fx + fy * fy + fz * fz)
if l < 1e-9 then
return { 0, 0, 0, 1 }
end
fx, fy, fz = fx / l, fy / l, fz / l
local rx, ry, rz = fy, -fx, 0 -- f x (0, 0, 1)
local rl = math.sqrt(rx * rx + ry * ry)
if rl < 1e-9 then
rx, ry, rl = 1, 0, 1
end
rx, ry = rx / rl, ry / rl
local ux, uy, uz = ry * fz - rz * fy, rz * fx - rx * fz, rx * fy - ry * fx -- r x f
return Mat4.quat({ rx, ry, rz, 0, ux, uy, uz, 0, -fx, -fy, -fz, 0, 0, 0, 0, 1 })
end
local function visgroups(b: Block): { any }
local out = {}
for _, p in KeyValues.all(b, "visgroup") do
if type(p.value) == "table" then
local v = p.value :: Block
table.insert(out, {
name = KeyValues.get(v, "name"),
id = tonumber(KeyValues.get(v, "visgroupid")),
color = KeyValues.get(v, "color"),
children = visgroups(v),
})
end
end
return out
end
-- solids of a block, including those inside its hidden { } blocks
local function solidsOf(b: Block, entity: number, out: { Solid }): string?
for _, p in b do
if type(p.value) == "table" then
local k = string.lower(p.key)
if k == "solid" then
local s, err = Build.solid(p.value :: Block, entity)
if not s then
return err
end
table.insert(out, s)
elseif k == "hidden" then
local err = solidsOf(p.value :: Block, entity, out)
if err then
return err
end
end
end
end
return nil
end
function Build.scene(doc: Block, o: Options): (Types.Scene?, string?)
local scene = Types.Scene.new()
scene.meta.up = "z"
scene.meta.unit = 0.0254
local mats: { [string]: number } = {}
local function matOf(name: string): number
local m = mats[name]
if m then
return m
end
local w, h, known = o.size(name)
local path = "materials/" .. string.lower((string.gsub(name, "\\", "/")))
table.insert(scene.textures, { name = name, uri = path .. ".vtf" })
local mat = Types.Scene.material(name)
mat.metallic = 0
mat.baseColorTexture = { texture = #scene.textures }
mat.extras = { vmf = { vmt = path .. ".vmt", width = w, height = h, sizeKnown = known } }
table.insert(scene.materials, mat)
mats[name] = #scene.materials
return #scene.materials
end
local root: Types.Node = { name = "vmf", children = {} }
table.insert(scene.nodes, root)
scene.roots[1] = 1
local ents: { any } = {}
local solidsMeta: { any } = {}
local groups: { any } = {}
-- world and entities, hidden ones included
local blocks: { { key: string, block: Block } } = {}
for _, p in doc do
if type(p.value) == "table" then
local k = string.lower(p.key)
if k == "world" or k == "entity" then
table.insert(blocks, { key = k, block = p.value :: Block })
elseif k == "hidden" then
for _, q in KeyValues.all(p.value :: Block, "entity") do
if type(q.value) == "table" then
table.insert(blocks, { key = "entity", block = q.value :: Block })
end
end
end
end
end
for _, item in blocks do
local b = item.block
local keys: Block = {}
local conns: any = nil
for _, p in b do
if type(p.value) == "string" then
table.insert(keys, p)
elseif string.lower(p.key) == "connections" then
conns = KeyValues.toObject(p.value :: Block)
elseif item.key == "world" and string.lower(p.key) == "group" then
local g = p.value :: Block
table.insert(groups, { id = tonumber(KeyValues.get(g, "id")), editor = editor(g) })
end
end
local e = KeyValues.toObject(keys)
if conns then
e.connections = conns
end
table.insert(ents, e)
local ei = #ents
local solids: { Solid } = {}
local serr = solidsOf(b, ei, solids)
if serr then
return nil, serr
end
local class = if type(e.classname) == "string" then e.classname else item.key
local name = if item.key == "world" then "world" elseif type(e.targetname) == "string" then e.targetname else class
local node: Types.Node = { name = name, children = {}, extras = { vmf = { entity = ei, id = tonumber(e.id), classname = class, editor = editor(b) } } }
if #solids > 0 then
local mesh, merr = Build.mesh(solids, o, matOf, name)
if not mesh then
return nil, merr
end
if #mesh.primitives > 0 then
table.insert(scene.meshes, mesh)
node.mesh = #scene.meshes
end
for _, s in solids do
table.insert(solidsMeta, { id = s.id, entity = ei, sides = #s.sides, editor = s.editor })
end
else
local org = nums(e.origin)
if #org >= 3 then
node.translation = { org[1], org[2], org[3] }
end
local ang = nums(e.angles)
if #ang >= 3 then
node.rotation = quat(ang[1], ang[2], ang[3])
end
if type(e.model) == "string" and string.find(string.lower(e.model), "%.mdl$") then
(node.extras :: any).model = e.model
end
end
if node.mesh or item.key ~= "world" then
table.insert(scene.nodes, node)
table.insert(root.children, #scene.nodes)
end
end
-- cameras
local cams = KeyValues.get(doc, "cameras")
local camMeta: any = nil
if type(cams) == "table" then
camMeta = { active = tonumber(KeyValues.get(cams, "activecamera")), list = {} }
for _, p in KeyValues.all(cams, "camera") do
if type(p.value) == "table" then
local pos, look = nums(KeyValues.get(p.value, "position")), nums(KeyValues.get(p.value, "look"))
if #pos >= 3 and #look >= 3 then
local cam: Types.Camera = { name = "camera" .. #scene.cameras, type = "perspective", yfov = math.rad(60), znear = 4 }
table.insert(scene.cameras, cam)
table.insert(scene.nodes, { name = "camera" .. (#scene.cameras - 1), children = {}, camera = #scene.cameras, translation = { pos[1], pos[2], pos[3] }, rotation = lookAt(pos, look) })
table.insert(root.children, #scene.nodes)
table.insert(camMeta.list, { position = { pos[1], pos[2], pos[3] }, look = { look[1], look[2], look[3] } })
end
end
end
end
local vg = KeyValues.get(doc, "visgroups")
scene.meta.entities = ents
scene.meta.solids = solidsMeta
scene.meta.groups = groups
scene.meta.visgroups = if type(vg) == "table" then visgroups(vg) else {}
scene.meta.cameras = camMeta
return scene, nil
end
return Build
+323
View File
@@ -0,0 +1,323 @@
--!strict
-- model/vmf: Valve Hammer map sources (.vmf, KeyValues text), read and written. Solids through codecs/model/Brush
-- (Valve 220 axes), displacements (normals, distances, offsets, elevation, alphas) through codecs/model/Displacement,
-- a mesh per entity with solids, point entities as nodes (extras.model for .mdl), cameras, groups and visgroups in
-- meta; meta.vmf keeps the parsed document, which encode writes back in Hammer's layout. Texture sizes from
-- opts.textureSizes, materials/<name>.vtf through resolve + decodeImage, else 512 x 512. Not supported: instances
-- (func_instance is a node), compiling (model/vbsp reads the result), smoothing groups.
-- ------------------------------------------------------------------------------------------------ requires
local Err = require("@rosetta/core/Err")
local Bytes = require("@rosetta/core/Bytes")
local Input = require("@rosetta/core/Input")
local Sniff = require("@rosetta/core/Sniff")
local Types = require("@rosetta/Types")
local KeyValues = require("@rosetta/codecs/text/KeyValues")
local Build = require("@rosetta/model/vmf/Build")
-- ------------------------------------------------------------------------------------------------ contract
local Vmf = {
name = "vmf",
category = "model",
extensions = { "vmf", "vmx" },
mime = { "model/x-vmf" },
deps = { "core/Err", "core/Bytes", "core/Input", "core/Sniff", "Types", "codecs/text/KeyValues", "codecs/model/Brush", "codecs/model/Displacement", "codecs/model/Mat4" },
caps = { decode = true, encode = true, displacements = true, roundTrip = true },
}
-- ------------------------------------------------------------------------------------------------ types
export type DecodeOptions = {
tools: boolean?, -- keep tools/* materials (nodraw, clip, trigger, skybox, ...), default false
textureSizes: { [string]: { number } }?, -- material name -> { width, height }
resolve: ((uri: string) -> (buffer | string)?)?,
files: { [string]: buffer | string }?,
decodeImage: ((buf: buffer) -> any)?,
maxPolygons: number?, -- default 2^20
}
export type EncodeOptions = {}
export type SideSpec = {
points: { { number } }, -- three points, clockwise seen from outside (Hammer)
material: string?,
uaxis: { number }?, -- x, y, z, shift, scale; default from the face's dominant axis
vaxis: { number }?,
rotation: number?,
lightmapscale: number?,
}
-- ------------------------------------------------------------------------------------------------ sniff
function Vmf.sniff(r: Bytes.Reader): number
local head = Sniff.text(r, 512, true)
if string.find(head, "%z") then
return 0
end
if string.match(head, "^versioninfo%s*{") or string.match(head, '^"versioninfo"%s*{') then
return 0.9
end
if string.match(head, "^world%s*{") or string.match(head, "^visgroups%s*{") then
return 0.6
end
return 0
end
-- ------------------------------------------------------------------------------------------------ decode
local function sizer(opts: DecodeOptions?): (string) -> (number, number, boolean)
local cache: { [string]: { number } } = {}
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, h, known = 512, 512, false
local given = opts and opts.textureSizes and (opts.textureSizes[name] or opts.textureSizes[string.lower(name)])
if given and type(given[1]) == "number" and type(given[2]) == "number" then
w, h, known = given[1], given[2], true
elseif opts and opts.decodeImage then
local data = Input.sibling(opts, "materials/" .. string.lower(name) .. ".vtf")
if data then
local ok, img = pcall(opts.decodeImage :: any, data)
if ok and type(img) == "table" and type(img.width) == "number" then
w, h, known = img.width, img.height, true
end
end
end
cache[name] = { w, h, if known then 1 else 0 }
return w, h, known
end
end
function Vmf.parse(src: buffer | string): (KeyValues.Block?, Err.Err?)
return KeyValues.parse(src, { escapes = "quotes", defines = false })
end
function Vmf.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Scene?, Err.Err?)
local doc, err = Vmf.parse(buffer.readstring(r.buf, r.base, r.limit - r.base))
if not doc then
return nil, err
end
local scene, msg = Build.scene(doc, {
tools = opts ~= nil and opts.tools == true,
size = sizer(opts),
maxPolygons = opts and opts.maxPolygons,
})
if not scene then
return nil, Err.from(msg)
end
local vi = KeyValues.get(doc, "versioninfo")
local info: any = if type(vi) == "table" then KeyValues.toObject(vi) else {}
scene.meta.vmf = doc
scene.meta.source = {
format = "vmf",
editorVersion = tonumber(info.editorversion),
editorBuild = tonumber(info.editorbuild),
mapVersion = tonumber(info.mapversion),
formatVersion = tonumber(info.formatversion),
prefab = info.prefab == "1",
}
return scene, nil
end
-- every solid of a parsed document as Brush faces (for Brush.polygons), with its entity index (1 = world)
function Vmf.brushes(doc: KeyValues.Block): ({ { id: number?, entity: number, faces: { any }, materials: { string } } }?, Err.Err?)
local out = {}
local entity = 0
local function walk(b: KeyValues.Block): string?
for _, p in b do
if type(p.value) == "table" then
local k = string.lower(p.key)
if k == "solid" then
local s, err = Build.solid(p.value :: KeyValues.Block, entity)
if not s then
return err
end
local faces, mats = {}, {}
for _, sd in s.sides do
local f = Build.face(sd)
if f then
table.insert(faces, f)
table.insert(mats, sd.material)
end
end
table.insert(out, { id = s.id, entity = entity, faces = faces, materials = mats })
elseif k == "hidden" then
local err = walk(p.value :: KeyValues.Block)
if err then
return err
end
end
end
end
return nil
end
for _, p in doc do
local k = string.lower(p.key)
if type(p.value) == "table" and (k == "world" or k == "entity") then
entity += 1
local err = walk(p.value :: KeyValues.Block)
if err then
return nil, Err.new(Err.CORRUPT, err)
end
end
end
return out, nil
end
-- ------------------------------------------------------------------------------------------------ encode
-- Hammer writes dispinfo rows at their block's own indent
local FLAT: { [string]: boolean } = {}
for _, k in { "normals", "distances", "offsets", "offset_normals", "alphas", "triangle_tags", "allowed_verts", "multiblend", "alphablend", "multiblend_color_0", "multiblend_color_1", "multiblend_color_2", "multiblend_color_3" } do
FLAT[k] = true
end
function Vmf.encode(value: any, _opts: EncodeOptions?): (buffer?, Err.Err?)
local doc = value
if type(value) == "table" and value.kind == "scene" then
doc = value.meta and value.meta.vmf
if type(doc) ~= "table" then
return nil, Err.new(Err.ARG, "a Scene needs meta.vmf (a decoded VMF) to be written")
end
end
if type(doc) ~= "table" then
return nil, Err.new(Err.ARG, "expected a Scene from a VMF or a KeyValues document")
end
local s, err = KeyValues.write(doc, { escapes = "quotes", separator = " ", bareBlocks = true, flatBlocks = FLAT })
if not s then
return nil, err
end
return buffer.fromstring(s), nil
end
-- ------------------------------------------------------------------------------------------------ extras
local function fmt(x: number): string
if x == math.floor(x) and math.abs(x) < 2 ^ 53 then
return string.format("%d", x)
end
return (string.gsub(string.format("%.6f", x), "%.?0+$", ""))
end
local function kv(k: string, v: string): KeyValues.Pair
return { key = k, value = v }
end
-- Hammer's default texture axes for a face (the TextureAxisFromPlane rows: floor / ceiling, walls)
local function defaultAxes(points: { { number } }): ({ number }, { number })
local a, b, c = points[1], points[2], points[3]
local ux, uy, uz = a[1] - b[1], a[2] - b[2], a[3] - b[3]
local vx, vy, vz = c[1] - b[1], c[2] - b[2], c[3] - b[3]
local nx, ny, nz = math.abs(uy * vz - uz * vy), math.abs(uz * vx - ux * vz), math.abs(ux * vy - uy * vx)
if nz >= nx and nz >= ny then
return { 1, 0, 0, 0, 0.25 }, { 0, -1, 0, 0, 0.25 }
elseif nx >= ny then
return { 0, 1, 0, 0, 0.25 }, { 0, 0, -1, 0, 0.25 }
end
return { 1, 0, 0, 0, 0.25 }, { 0, 0, -1, 0, 0.25 }
end
local function id(given: number?, default: number): string
return fmt(given or default)
end
function Vmf.side(s: SideSpec, sideId: number?): KeyValues.Pair
local p = s.points
local du, dv = defaultAxes(p)
local u, v = s.uaxis or du, s.vaxis or dv
local function axis(x: { number }): string
return "[" .. fmt(x[1]) .. " " .. fmt(x[2]) .. " " .. fmt(x[3]) .. " " .. fmt(x[4] or 0) .. "] " .. fmt(x[5] or 0.25)
end
local function pt(x: { number }): string
return "(" .. fmt(x[1]) .. " " .. fmt(x[2]) .. " " .. fmt(x[3]) .. ")"
end
return { key = "side", value = {
kv("id", id(sideId, 1)),
kv("plane", pt(p[1]) .. " " .. pt(p[2]) .. " " .. pt(p[3])),
kv("material", s.material or "TOOLS/TOOLSNODRAW"),
kv("uaxis", axis(u)),
kv("vaxis", axis(v)),
kv("rotation", fmt(s.rotation or 0)),
kv("lightmapscale", fmt(s.lightmapscale or 16)),
kv("smoothing_groups", "0"),
} }
end
function Vmf.solid(sides: { SideSpec }, solidId: number?): KeyValues.Pair
local blk: KeyValues.Block = { kv("id", id(solidId, 1)) }
for i, s in sides do
table.insert(blk, Vmf.side(s, i))
end
table.insert(blk, { key = "editor", value = { kv("color", "0 180 0"), kv("visgroupshown", "1"), kv("visgroupautoshown", "1") } })
return { key = "solid", value = blk }
end
-- an axis-aligned box: Hammer's six planes, a material for every side (or per side: top, bottom, west, east, north,
-- south)
function Vmf.box(lo: { number }, hi: { number }, material: string | { string }, solidId: number?): KeyValues.Pair
local x0, y0, z0, x1, y1, z1 = lo[1], lo[2], lo[3], hi[1], hi[2], hi[3]
local function m(i: number): string
return if type(material) == "table" then material[i] or material[1] else material
end
return Vmf.solid({
{ points = { { x0, y1, z1 }, { x1, y1, z1 }, { x1, y0, z1 } }, material = m(1) },
{ points = { { x0, y0, z0 }, { x1, y0, z0 }, { x1, y1, z0 } }, material = m(2) },
{ points = { { x0, y1, z0 }, { x0, y1, z1 }, { x0, y0, z1 } }, material = m(3) },
{ points = { { x1, y0, z0 }, { x1, y0, z1 }, { x1, y1, z1 } }, material = m(4) },
{ points = { { x1, y1, z0 }, { x1, y1, z1 }, { x0, y1, z1 } }, material = m(5) },
{ points = { { x0, y0, z0 }, { x0, y0, z1 }, { x1, y0, z1 } }, material = m(6) },
}, solidId)
end
-- a new document: versioninfo, visgroups, viewsettings, world (worldspawn keys), cameras, cordons
function Vmf.document(worldKeys: { [string]: string }?): KeyValues.Block
local world: KeyValues.Block = { kv("id", "1"), kv("mapversion", "1"), kv("classname", "worldspawn") }
if worldKeys then
local keys = {}
for k in worldKeys do
table.insert(keys, k)
end
table.sort(keys)
for _, k in keys do
table.insert(world, kv(k, worldKeys[k]))
end
end
return {
{ key = "versioninfo", value = { kv("editorversion", "400"), kv("editorbuild", "8864"), kv("mapversion", "1"), kv("formatversion", "100"), kv("prefab", "0") } },
{ key = "visgroups", value = {} },
{ key = "viewsettings", value = { kv("bSnapToGrid", "1"), kv("bShowGrid", "1"), kv("bShowLogicalGrid", "0"), kv("nGridSpacing", "64"), kv("bShow3DGrid", "0") } },
{ key = "world", value = world },
{ key = "cameras", value = { kv("activecamera", "-1") } },
{ key = "cordons", value = { kv("active", "0") } },
}
end
-- an entity block (keys in the given order, then its solids) appended to doc before cameras
function Vmf.entity(doc: KeyValues.Block, keys: { { string } }, solids: { KeyValues.Pair }?): KeyValues.Pair
local count = 1
for _, p in doc do
if string.lower(p.key) == "entity" then
count += 1
end
end
local blk: KeyValues.Block = { kv("id", id(nil, count + 1)) }
for _, k in keys do
table.insert(blk, kv(k[1], k[2]))
end
for _, s in solids or {} do
table.insert(blk, s)
end
local pair = { key = "entity", value = blk }
local at = #doc + 1
for i, p in doc do
if string.lower(p.key) == "cameras" then
at = i
break
end
end
table.insert(doc, at, pair)
return pair
end
-- the world block of a document (solids go in with table.insert(Vmf.world(doc), Vmf.box(...)))
function Vmf.world(doc: KeyValues.Block): KeyValues.Block?
local w = KeyValues.get(doc, "world")
return if type(w) == "table" then w else nil
end
return Vmf