model/bsp: BSP2 / 2PSB, Quake 1 / 2 / Half-Life lightmap atlas (TEXCOORD_1, .lit), tree / hulls / visibility in meta.bsp

Bsp.leafAt / contents / pvs point queries; tested on ericw-tools qbsp + vis output in all three Quake 1 layouts.
This commit is contained in:
4DBug committed 2026-11-01 19:03:55 -06:00
1 parent 2704653a3e
commit 67e116a6c6
13 files changed
+2556 -375

No files matched your search

+1 -1
View File
@@ -741,7 +741,7 @@ local list: { Entry } = {
extensions = { "bsp" },
mime = { "model/x-bsp" },
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" },
caps = { decode = true, encode = false, variants = { "quake", "bsp2", "2psb", "halflife", "quake2", "quake3" }, lightmaps = true, collision = true, visibility = true },
load = function()
return require("@rosetta/model/bsp")
end,
+64
View File
@@ -0,0 +1,64 @@
--!strict
-- model/bsp/Lightmap: packs face lightmaps (w x h luxels each) into one atlas, shelf by shelf, tallest first, each
-- with a one-luxel border that repeats its edge (bilinear filtering stays inside the face).
local Lightmap = {}
export type Rect = { x: number, y: number, w: number, h: number } -- x, y: the first luxel inside the border
-- nil, message past maxPixels
function Lightmap.pack(sizes: { { number } }, maxPixels: number): (number, number, { Rect }?, string?)
local area, widest = 0, 1
for _, s in sizes do
area += (s[1] + 2) * (s[2] + 2)
widest = math.max(widest, s[1] + 2)
end
local W = 64
while W * W < area * 1.2 and W < 4096 do
W *= 2
end
W = math.max(W, widest)
local order = table.create(#sizes) :: { number }
for i = 1, #sizes do
order[i] = i
end
table.sort(order, function(a: number, b: number): boolean
local ha, hb = sizes[a][2], sizes[b][2]
if ha ~= hb then
return ha > hb
end
return a < b
end)
local out = table.create(#sizes) :: { Rect }
local x, y, rowH = 0, 0, 0
for _, i in order do
local w, h = sizes[i][1] + 2, sizes[i][2] + 2
if x + w > W then
x, y, rowH = 0, y + rowH, 0
end
out[i] = { x = x + 1, y = y + 1, w = sizes[i][1], h = sizes[i][2] }
x += w
rowH = math.max(rowH, h)
end
local H = math.max(1, y + rowH)
if W * H > maxPixels then
return 0, 0, nil, "limit: lightmap atlas " .. W .. " x " .. H
end
return W, H, out, nil
end
-- copies the outermost luxels of a rect into its border (rgba8 pixels, atlas width W)
function Lightmap.border(px: buffer, W: number, r: Rect)
local function copy(dx: number, dy: number, sx: number, sy: number)
buffer.writeu32(px, (dy * W + dx) * 4, buffer.readu32(px, (sy * W + sx) * 4))
end
for yy = r.y, r.y + r.h - 1 do
copy(r.x - 1, yy, r.x, yy)
copy(r.x + r.w, yy, r.x + r.w - 1, yy)
end
for xx = r.x - 1, r.x + r.w do
copy(xx, r.y - 1, xx, r.y)
copy(xx, r.y + r.h, xx, r.y + r.h - 1)
end
end
return Lightmap
@@ -1,15 +1,17 @@
--!strict
-- model/bsp/Brush: Quake 1 (BSP 29), Half-Life (BSP 30) and Quake II (IBSP 38) maps -> Scene, from bspfile.h of the
-- Quake / Quake II source releases (no code taken). Texture coordinates: s = v . s.xyz + s.w, divided by the texture
-- size.
-- model/bsp/Quake: Quake 1 (BSP 29, BSP2, 2PSB), Half-Life (BSP 30) and Quake II (IBSP 38) maps -> Scene, from
-- bspfile.h of the Quake / Quake II source releases and ericw-tools (BSP2 / 2PSB; no code taken). Texture coordinates:
-- s = v . s.xyz + s.w over the texture size; lightmaps (style 0) packed into one atlas as TEXCOORD_1, extents as
-- CalcSurfaceExtents (16 texels per luxel).
local Types = require("@rosetta/Types")
local Pixels = require("@rosetta/codecs/image/Pixels")
local Lightmap = require("@rosetta/model/bsp/Lightmap")
local Miptex = require("@rosetta/codecs/image/Miptex")
local Brush = {}
local Quake = {}
local Scene = Types.Scene
local readi32, readu16, readf32, readu32 = buffer.readi32, buffer.readu16, buffer.readf32, buffer.readu32
local readi32, readu16, readf32, readu32, readu8 = buffer.readi32, buffer.readu16, buffer.readf32, buffer.readu32, buffer.readu8
local writef32, writeu32 = buffer.writef32, buffer.writeu32
export type Lump = { at: number, size: number }
@@ -18,10 +20,12 @@ export type Options = {
wal: ((name: string) -> buffer?)?, -- Quake II: a texture's .wal file (for its size)
maxPixels: number?,
maxVertices: number?,
lit: buffer?, -- Quake 1 coloured light (.lit: "QLIT", version 1, RGB per luxel)
lightmaps: boolean?, -- default true
}
type Tex = { name: string, width: number, height: number, image: Types.Image?, texels: boolean }
type Batch = { tex: number, pos: { number }, nrm: { number }, uv: { number } }
type Batch = { tex: number, pos: { number }, nrm: { number }, uv: { number }, lm: { number } } -- lm: face, s, t per vertex
local function cstr(b: buffer, at: number, n: number): string
return (string.match(buffer.readstring(b, at, n), "^[^%z]*")) :: string
@@ -58,11 +62,14 @@ local function miptex(b: buffer, base: number, l: Lump, hl: boolean, pal: buffer
return out, nil
end
function Brush.decode(b: buffer, base: number, lumps: { [string]: Lump }, variant: string, opts: Options?): (Types.Scene?, string?)
function Quake.decode(b: buffer, base: number, lumps: { [string]: Lump }, variant: string, opts: Options?): (Types.Scene?, string?)
local q2 = variant == "q2"
local big = variant == "bsp2" or variant == "2psb"
local maxPixels = opts and opts.maxPixels or 2 ^ 24
local V, E, SE, Fc, TI, P, M = lumps.vertices, lumps.edges, lumps.surfedges, lumps.faces, lumps.texinfo, lumps.planes, lumps.models
local nV, nE, nSE, nF = V.size // 12, E.size // 4, SE.size // 4, Fc.size // 20
local fSize: number = if big then 28 else 20
local eSize: number = if big then 8 else 4
local nV, nE, nSE, nF = V.size // 12, E.size // eSize, SE.size // 4, Fc.size // fSize
local tiSize = if q2 then 76 else 40
local nTI, nP = TI.size // tiSize, P.size // 20
local mSize = if q2 then 48 else 64
@@ -125,11 +132,28 @@ function Brush.decode(b: buffer, base: number, lumps: { [string]: Lump }, varian
local batches: { [number]: { [number]: Batch } } = {}
local orders: { [number]: { number } } = {}
local skipped = 0
-- lightmaps: record 1 = a white luxel (sky / liquids), 2 = black (unlit faces), then one per lit face
local LT = lumps.lighting
local useLight = LT.size > 0 and not (opts and opts.lightmaps == false)
local rgb = variant == "hl" or q2
local lit = opts and opts.lit
if lit and (buffer.len(lit) < 8 or buffer.readstring(lit, 0, 4) ~= "QLIT" or buffer.readi32(lit, 4) ~= 1) then
lit = nil
end
local lmSizes: { { number } } = { { 1, 1 }, { 1, 1 } }
local lmFaces: { { face: number, ofs: number, smin: number, tmin: number, styles: number } } = { { face = -1, ofs = -1, smin = 0, tmin = 0, styles = 0 }, { face = -1, ofs = -1, smin = 0, tmin = 0, styles = 0 } }
local lumaTotal = 0
for f = 0, nF - 1 do
local fo = base + Fc.at + f * 20
local plane, side, firstEdge, numEdges, texinfo = readu16(b, fo), readu16(b, fo + 2), readi32(b, fo + 4), readu16(b, fo + 8), readu16(b, fo + 10)
local fo = base + Fc.at + f * fSize
local plane = if big then readi32(b, fo) else readu16(b, fo)
local side = if big then readi32(b, fo + 4) else readu16(b, fo + 2)
local firstEdge = if big then readi32(b, fo + 8) else readi32(b, fo + 4)
local numEdges = if big then readi32(b, fo + 12) else readu16(b, fo + 8)
local texinfo = if big then readi32(b, fo + 16) else readu16(b, fo + 10)
local styles = if big then fo + 20 else fo + 12
local lightofs = if big then readi32(b, fo + 24) else readi32(b, fo + 16)
local model = faceModel[f + 1]
if not model or numEdges < 3 or firstEdge < 0 or firstEdge + numEdges > nSE or plane >= nP or texinfo >= nTI then
if not model or numEdges < 3 or plane < 0 or texinfo < 0 or firstEdge < 0 or firstEdge + numEdges > nSE or plane >= nP or texinfo >= nTI then
skipped += 1
continue
end
@@ -142,7 +166,13 @@ function Brush.decode(b: buffer, base: number, lumps: { [string]: Lump }, varian
ok = false
break
end
local v = if se >= 0 then readu16(b, base + E.at + e * 4) else readu16(b, base + E.at + e * 4 + 2)
local eo = base + E.at + e * eSize
local v
if big then
v = if se >= 0 then readu32(b, eo) else readu32(b, eo + 4)
else
v = if se >= 0 then readu16(b, eo) else readu16(b, eo + 2)
end
if v >= nV then
ok = false
break
@@ -186,6 +216,37 @@ function Brush.decode(b: buffer, base: number, lumps: { [string]: Lump }, varian
local tio = base + TI.at + texinfo * tiSize
local sx, sy, sz, so = readf32(b, tio), readf32(b, tio + 4), readf32(b, tio + 8), readf32(b, tio + 12)
local tx, ty, tz, to = readf32(b, tio + 16), readf32(b, tio + 20), readf32(b, tio + 24), readf32(b, tio + 28)
local rec = 2
if useLight then
local tflags = readi32(b, tio + (if q2 then 32 else 36))
local special = if q2 then bit32.band(tflags, 0x8C) ~= 0 else bit32.band(tflags, 1) ~= 0
if special then
rec = 1
elseif lightofs >= 0 then
local smin: number, smax: number, tmin: number, tmax: number = math.huge, -math.huge, math.huge, -math.huge
for k = 0, n - 1 do
local x, y, z = poly[k * 3 + 1], poly[k * 3 + 2], poly[k * 3 + 3]
local sv, tv = x * sx + y * sy + z * sz + so, x * tx + y * ty + z * tz + to
smin, smax = math.min(smin, sv), math.max(smax, sv)
tmin, tmax = math.min(tmin, tv), math.max(tmax, tv)
end
local bs, bt0 = math.floor(smin / 16), math.floor(tmin / 16)
local lw, lh = math.ceil((smax :: number) / 16) - bs + 1, math.ceil((tmax :: number) / 16) - bt0 + 1
local ns = 0
for k = 0, 3 do
if readu8(b, styles + k) ~= 255 then
ns += 1
end
end
local bytes = lw * lh * (if rgb then 3 else 1)
lumaTotal += lw * lh
if ns > 0 and lw > 0 and lh > 0 and lw <= 256 and lh <= 256 and lightofs + bytes <= LT.size and lumaTotal <= maxPixels then
table.insert(lmSizes, { lw, lh })
table.insert(lmFaces, { face = f, ofs = lightofs, smin = bs * 16, tmin = bt0 * 16, styles = ns })
rec = #lmFaces
end
end
end
local ti = texOf[texinfo + 1] or 0
local tex = texs[ti]
local w, h = if tex then tex.width else 1, if tex then tex.height else 1
@@ -193,7 +254,7 @@ function Brush.decode(b: buffer, base: number, lumps: { [string]: Lump }, varian
batches[model] = bm
local bt = bm[ti]
if not bt then
bt = { tex = ti, pos = {}, nrm = {}, uv = {} }
bt = { tex = ti, pos = {}, nrm = {}, uv = {}, lm = {} }
bm[ti] = bt
local ol = orders[model] or {}
orders[model] = ol
@@ -206,21 +267,69 @@ function Brush.decode(b: buffer, base: number, lumps: { [string]: Lump }, varian
local pp, nn, uu = batch.pos, batch.nrm, batch.uv
pp[#pp + 1], pp[#pp + 2], pp[#pp + 3] = x, y, z
nn[#nn + 1], nn[#nn + 2], nn[#nn + 3] = nx, ny, nz
uu[#uu + 1] = (x * sx + y * sy + z * sz + so) / w
uu[#uu + 1] = (x * tx + y * ty + z * tz + to) / h
local sv, tv = x * sx + y * sy + z * sz + so, x * tx + y * ty + z * tz + to
uu[#uu + 1] = sv / w
uu[#uu + 1] = tv / h
local ll = batch.lm
ll[#ll + 1], ll[#ll + 2], ll[#ll + 3] = rec, sv, tv
end
end
end
local atlasW, atlasH, rects = 0, 0, nil :: { Lightmap.Rect }?
local lmTex: number? = nil
local atlas: Types.Image? = nil
if useLight and #lmFaces > 2 then
local W, H, rs, err = Lightmap.pack(lmSizes, maxPixels)
if not rs then
return nil, err
end
atlasW, atlasH, rects = W, H, rs
local img = Types.Image.new(W, H)
local px = img.pixels
local la = base + LT.at
buffer.writeu32(px, (rs[1].y * W + rs[1].x) * 4, 0xFFFFFFFF)
buffer.writeu32(px, (rs[2].y * W + rs[2].x) * 4, 0xFF000000)
local placed = {}
for i = 3, #lmFaces do
local lf, r = lmFaces[i], rs[i]
for yy = 0, r.h - 1 do
for xx = 0, r.w - 1 do
local k = yy * r.w + xx
local cr: number, cg: number, cb: number = 0, 0, 0
if rgb then
local o = la + lf.ofs + k * 3
cr, cg, cb = readu8(b, o), readu8(b, o + 1), readu8(b, o + 2)
elseif lit and 8 + (lf.ofs + k) * 3 + 3 <= buffer.len(lit) then
local o = 8 + (lf.ofs + k) * 3
cr, cg, cb = readu8(lit, o), readu8(lit, o + 1), readu8(lit, o + 2)
else
local v = readu8(b, la + lf.ofs + k)
cr, cg, cb = v, v, v
end
writeu32(px, ((r.y + yy) * W + r.x + xx) * 4, 0xFF000000 + (cb :: number) * 65536 + (cg :: number) * 256 + (cr :: number))
end
end
table.insert(placed, { face = lf.face, x = r.x, y = r.y, w = r.w, h = r.h, styles = lf.styles })
end
for i = 1, #lmFaces do
Lightmap.border(px, W, rs[i])
end
img.meta.source = { format = "bsp", lightmap = "atlas", coloured = rgb or lit ~= nil }
atlas = img
scene.meta.lightmaps = placed
lmTex = #texs + 1
end
for i, t in texs do
local tex: Types.Texture = { name = t.name, image = t.image, uri = if t.image then nil else (if q2 then "textures/" .. t.name .. ".wal" else t.name) }
table.insert(scene.textures, tex)
local mat = Scene.material(t.name)
mat.metallic = 0
local extras: any = { bsp = { texels = if t.texels then true else nil, width = t.width, height = t.height } }
mat.extras = extras
mat.extras = { bsp = { texels = if t.texels then true else nil, width = t.width, height = t.height } } :: any
mat.extras = { bsp = { texels = if t.texels then true else nil, width = t.width, height = t.height, lightmap = lmTex, lightmapTexCoord = if lmTex then 1 else nil } } :: any
table.insert(scene.materials, mat)
end
if atlas then
table.insert(scene.textures, { name = "lightmap", image = atlas })
end
local root: Types.Node = { name = "bsp", children = {} }
table.insert(scene.nodes, root)
scene.roots[1] = 1
@@ -242,8 +351,23 @@ function Brush.decode(b: buffer, base: number, lumps: { [string]: Lump }, varian
for k = 0, nv - 1 do
writeu32(ib, k * 4, k)
end
local attrs: { [string]: Types.Accessor } = { POSITION = Scene.accessor(pb, "f32", 3, nv), NORMAL = Scene.accessor(nb, "f32", 3, nv), TEXCOORD_0 = Scene.accessor(ub, "f32", 2, nv) }
if rects then
local lb = buffer.create(nv * 8)
for k = 0, nv - 1 do
local rec, sv, tv = bt.lm[k * 3 + 1], bt.lm[k * 3 + 2], bt.lm[k * 3 + 3]
local r, lf = rects[rec], lmFaces[rec]
local lu, lv = r.x + 0.5, r.y + 0.5
if rec > 2 then
lu, lv = r.x + (sv - lf.smin) / 16 + 0.5, r.y + (tv - lf.tmin) / 16 + 0.5
end
writef32(lb, k * 8, lu / atlasW)
writef32(lb, k * 8 + 4, lv / atlasH)
end
attrs.TEXCOORD_1 = Scene.accessor(lb, "f32", 2, nv)
end
table.insert(mesh.primitives, {
attributes = { POSITION = Scene.accessor(pb, "f32", 3, nv), NORMAL = Scene.accessor(nb, "f32", 3, nv), TEXCOORD_0 = Scene.accessor(ub, "f32", 2, nv) },
attributes = attrs,
indices = Scene.accessor(ib, "u32", 1, nv),
mode = "triangles" :: any,
material = if ti > 0 then ti else nil,
@@ -258,4 +382,4 @@ function Brush.decode(b: buffer, base: number, lumps: { [string]: Lump }, varian
return scene, nil
end
return Brush
return Quake
+386
View File
@@ -0,0 +1,386 @@
--!strict
-- model/bsp/Tree: the BSP tree, collision hulls and visibility of Quake 1 / BSP2 / 2PSB / Half-Life / Quake II / Quake
-- III maps as tables (bspfile.h layouts; Unofficial Quake 3 Map Specs), plus point queries: the leaf and contents at a
-- point (Quake 1 hulls 0..3 through nodes / clipnodes as SV_HullPointContents; Quake II leaf contents; Quake III the
-- contents of the leaf's brushes) and the potentially visible set of a leaf (run-length zero bytes, as Mod_DecompressVis).
local Tree = {}
local readi32, readu16, readi16, readf32, readu8, readu32 = buffer.readi32, buffer.readu16, buffer.readi16, buffer.readf32, buffer.readu8, buffer.readu32
export type Lump = { at: number, size: number }
export type Plane = { normal: { number }, dist: number, type: number? }
export type Node = { plane: number, children: { number }, mins: { number }, maxs: { number }, firstFace: number?, numFaces: number? } -- children: >= 0 node, < 0 leaf -(child + 1)
export type Leaf = {
contents: number?,
cluster: number?,
area: number?,
visofs: number?,
mins: { number },
maxs: { number },
firstFace: number?,
numFaces: number?,
firstBrush: number?,
numBrushes: number?,
ambient: { number }?,
}
export type ClipNode = { plane: number, children: { number } } -- children: >= 0 clipnode, < 0 contents
export type Model = { mins: { number }, maxs: { number }, origin: { number }?, headnodes: { number }, visleafs: number?, firstFace: number, numFaces: number }
export type Brush = { firstSide: number, numSides: number, contents: number }
export type Side = { plane: number, texinfo: number }
export type Data = {
variant: string,
planes: { Plane },
nodes: { Node },
leaves: { Leaf },
clipnodes: { ClipNode }?,
models: { Model },
brushes: { Brush }?,
brushSides: { Side }?,
leafBrushes: { number }?,
leafFaces: { number }?,
visibility: buffer?, -- the raw lump
numClusters: number?,
clusterBytes: number?, -- Quake III bytes per cluster vector
}
local function v3(b: buffer, o: number, kind: string): { number }
if kind == "f" then
return { readf32(b, o), readf32(b, o + 4), readf32(b, o + 8) }
elseif kind == "i" then
return { readi32(b, o), readi32(b, o + 4), readi32(b, o + 8) }
end
return { readi16(b, o), readi16(b, o + 2), readi16(b, o + 4) }
end
local function slice(b: buffer, base: number, l: Lump): buffer?
if l.size <= 0 then
return nil
end
local out = buffer.create(l.size)
buffer.copy(out, 0, b, base + l.at, l.size)
return out
end
-- nil, message past maxItems
function Tree.read(b: buffer, base: number, lumps: { [string]: Lump }, variant: string, maxItems: number?): (Data?, string?)
local limit = maxItems or 2 ^ 22
local q2, q3 = variant == "q2", variant == "q3"
local bsp2, rmq = variant == "bsp2", variant == "2psb"
local d: Data = { variant = variant, planes = {}, nodes = {}, leaves = {}, models = {} }
local function count(l: Lump?, size: number): number
return if l then l.size // size else 0
end
local P = lumps.planes
local pSize = if q3 then 16 else 20
local np = count(P, pSize)
if np > limit then
return nil, "limit: too many planes"
end
for i = 0, np - 1 do
local o = base + P.at + i * pSize
d.planes[i + 1] = { normal = v3(b, o, "f"), dist = readf32(b, o + 12), type = if q3 then nil else readi32(b, o + 16) }
end
local N = lumps.nodes
local nSize = if q3 then 36 elseif q2 then 28 elseif bsp2 then 44 elseif rmq then 32 else 24
local nn = count(N, nSize)
if nn > limit then
return nil, "limit: too many nodes"
end
for i = 0, nn - 1 do
local o = base + N.at + i * nSize
local node: any
if q3 or q2 or bsp2 or rmq then
local bk = if q3 then "i" elseif bsp2 then "f" else "s"
local bs = if bk == "s" then 6 else 12
node = { plane = readi32(b, o), children = { readi32(b, o + 4), readi32(b, o + 8) }, mins = v3(b, o + 12, bk), maxs = v3(b, o + 12 + bs, bk) }
if not q3 then
local fo = o + 12 + bs * 2
if q2 then
node.firstFace, node.numFaces = readu16(b, fo), readu16(b, fo + 2)
else
node.firstFace, node.numFaces = readu32(b, fo), readu32(b, fo + 4)
end
end
else
local c = {}
for k = 0, 1 do
local p = readu16(b, o + 4 + k * 2)
c[k + 1] = if p < nn then p else -(65535 - p) - 1 -- Quakespasm Mod_LoadNodes_S: leaf 65535 - p
end
node = { plane = readi32(b, o), children = c, mins = v3(b, o + 8, "s"), maxs = v3(b, o + 14, "s"), firstFace = readu16(b, o + 20), numFaces = readu16(b, o + 22) }
end
d.nodes[i + 1] = node
end
local L = lumps.leaves or lumps.leafs
local lSize = if q3 then 48 elseif q2 then 28 elseif bsp2 then 44 elseif rmq then 32 else 28
local nl = count(L, lSize)
if nl > limit then
return nil, "limit: too many leaves"
end
for i = 0, nl - 1 do
local o = base + L.at + i * lSize
local leaf: any
if q3 then
leaf = { cluster = readi32(b, o), area = readi32(b, o + 4), mins = v3(b, o + 8, "i"), maxs = v3(b, o + 20, "i"),
firstFace = readi32(b, o + 32), numFaces = readi32(b, o + 36), firstBrush = readi32(b, o + 40), numBrushes = readi32(b, o + 44) }
elseif q2 then
leaf = { contents = readi32(b, o), cluster = readi16(b, o + 4), area = readi16(b, o + 6), mins = v3(b, o + 8, "s"), maxs = v3(b, o + 14, "s"),
firstFace = readu16(b, o + 20), numFaces = readu16(b, o + 22), firstBrush = readu16(b, o + 24), numBrushes = readu16(b, o + 26) }
else
local bk = if bsp2 then "f" else "s"
local bs = if bsp2 then 12 else 6
local fo = o + 8 + bs * 2
local big = bsp2 or rmq
leaf = { contents = readi32(b, o), visofs = readi32(b, o + 4), mins = v3(b, o + 8, bk), maxs = v3(b, o + 8 + bs, bk),
firstFace = if big then readu32(b, fo) else readu16(b, fo), numFaces = if big then readu32(b, fo + 4) else readu16(b, fo + 2) }
local ao = fo + (if big then 8 else 4)
leaf.ambient = { readu8(b, ao), readu8(b, ao + 1), readu8(b, ao + 2), readu8(b, ao + 3) }
end
d.leaves[i + 1] = leaf
end
if not q2 and not q3 then
local C = lumps.clipnodes
local cSize = if bsp2 or rmq then 12 else 8
local nc = count(C, cSize)
if nc > limit then
return nil, "limit: too many clipnodes"
end
local cl: { ClipNode } = {}
for i = 0, nc - 1 do
local o = base + C.at + i * cSize
local c
if cSize == 12 then
c = { readi32(b, o + 4), readi32(b, o + 8) }
else
c = {}
for k = 0, 1 do
local p = readu16(b, o + 4 + k * 2)
c[k + 1] = if p > nc then p - 65536 else p -- Quakespasm Mod_LoadClipnodes
end
end
cl[i + 1] = { plane = readi32(b, o), children = c }
end
d.clipnodes = cl
end
local M = lumps.models
local mSize = if q3 then 40 elseif q2 then 48 else 64
for i = 0, count(M, mSize) - 1 do
local o = base + M.at + i * mSize
local m: any
if q3 then
m = { mins = v3(b, o, "f"), maxs = v3(b, o + 12, "f"), headnodes = { 0 }, firstFace = readi32(b, o + 24), numFaces = readi32(b, o + 28) }
elseif q2 then
m = { mins = v3(b, o, "f"), maxs = v3(b, o + 12, "f"), origin = v3(b, o + 24, "f"), headnodes = { readi32(b, o + 36) }, firstFace = readi32(b, o + 40), numFaces = readi32(b, o + 44) }
else
m = { mins = v3(b, o, "f"), maxs = v3(b, o + 12, "f"), origin = v3(b, o + 24, "f"),
headnodes = { readi32(b, o + 36), readi32(b, o + 40), readi32(b, o + 44), readi32(b, o + 48) },
visleafs = readi32(b, o + 52), firstFace = readi32(b, o + 56), numFaces = readi32(b, o + 60) }
end
d.models[i + 1] = m
end
if q2 or q3 then
local B, S = lumps.brushes, lumps.brushsides
local nb, ns = count(B, 12), count(S, if q3 then 8 else 4)
if nb > limit or ns > limit then
return nil, "limit: too many brushes"
end
local brushes: { Brush }, sides: { Side } = {}, {}
for i = 0, nb - 1 do
local o = base + B.at + i * 12
brushes[i + 1] = { firstSide = readi32(b, o), numSides = readi32(b, o + 4), contents = readi32(b, o + 8) } -- Quake III: a texture index
end
for i = 0, ns - 1 do
if q3 then
local o = base + S.at + i * 8
sides[i + 1] = { plane = readi32(b, o), texinfo = readi32(b, o + 4) }
else
local o = base + S.at + i * 4
sides[i + 1] = { plane = readu16(b, o), texinfo = readi16(b, o + 2) }
end
end
d.brushes, d.brushSides = brushes, sides
local LB = lumps.leafbrushes
local lbs: { number } = {}
for i = 0, count(LB, if q3 then 4 else 2) - 1 do
lbs[i + 1] = if q3 then readi32(b, base + LB.at + i * 4) else readu16(b, base + LB.at + i * 2)
end
d.leafBrushes = lbs
if q3 then
-- brush contents come from the texture's contents flags
local T = lumps.textures
local nt = count(T, 72)
for _, br in brushes do
local t = br.contents
br.contents = if t >= 0 and t < nt then readi32(b, base + T.at + t * 72 + 68) else 0
end
end
end
local VL = lumps.visibility or lumps.visdata
d.visibility = if VL then slice(b, base, VL) else nil
local vis = d.visibility
if vis and q2 and buffer.len(vis) >= 4 then
d.numClusters = readi32(vis, 0)
elseif vis and q3 and buffer.len(vis) >= 8 then
d.numClusters, d.clusterBytes = readi32(vis, 0), readi32(vis, 4)
end
return d, nil
end
local function side(d: Data, plane: number, x: number, y: number, z: number): number
local p = d.planes[plane + 1]
if not p then
return 0
end
local n = p.normal
return x * n[1] + y * n[2] + z * n[3] - p.dist
end
-- the leaf (0-based) at a point, walking the tree of model (0-based, default 0)
function Tree.leafAt(d: Data, x: number, y: number, z: number, model: number?): number?
local m = d.models[(model or 0) + 1]
local node = if m then m.headnodes[1] else 0
for _ = 1, #d.nodes + 1 do
if node < 0 then
return -node - 1
end
local nd = d.nodes[node + 1]
if not nd then
return nil
end
node = if side(d, nd.plane, x, y, z) >= 0 then nd.children[1] else nd.children[2]
end
return nil
end
-- Quake 1: CONTENTS_* (-1 empty, -2 solid, -3 water, -4 slime, -5 lava, -6 sky) in hull 0..3; Quake II: the leaf's
-- CONTENTS_* bits; Quake III: the contents bits of the brushes holding the point
function Tree.contents(d: Data, x: number, y: number, z: number, hull: number?, model: number?): number?
local h = hull or 0
if (d.variant == "q1" or d.variant == "hl" or d.variant == "bsp2" or d.variant == "2psb") and h > 0 then
local m = d.models[(model or 0) + 1]
local cl = d.clipnodes or {}
local node = if m then m.headnodes[h + 1] or -1 else -1
for _ = 1, #cl + 1 do
if node < 0 then
return node
end
local c = cl[node + 1]
if not c then
return nil
end
node = if side(d, c.plane, x, y, z) >= 0 then c.children[1] else c.children[2]
end
return nil
end
local leaf = Tree.leafAt(d, x, y, z, model)
local lf = leaf and d.leaves[leaf + 1]
if not lf then
return nil
end
if d.variant ~= "q3" then
return lf.contents
end
local out = 0
local lbs: { number }, brushes: { Brush }, sides: { Side } = d.leafBrushes or {}, d.brushes or {}, d.brushSides or {}
local fb: number, nb: number = lf.firstBrush or 0, lf.numBrushes or 0
for k = fb, fb + nb - 1 do
local br = brushes[(lbs[k + 1] or -1) + 1]
if br then
local inside = true
for s = br.firstSide, br.firstSide + br.numSides - 1 do
local sd = sides[s + 1]
if not sd or side(d, sd.plane, x, y, z) > 0 then
inside = false
break
end
end
if inside then
out = bit32.bor(out, br.contents)
end
end
end
return out
end
local function decompress(vis: buffer, at: number, bytes: number, out: { boolean })
local n = buffer.len(vis)
local i = 0
while i < bytes and at < n do
local c = readu8(vis, at)
if c ~= 0 then
for bit = 0, 7 do
if bit32.band(c, bit32.lshift(1, bit)) ~= 0 then
out[i * 8 + bit + 1] = true
end
end
i += 1
at += 1
else
if at + 1 >= n then
break
end
i += readu8(vis, at + 1)
at += 2
end
end
end
-- the leaves (0-based, sorted) potentially visible from a leaf; nil without visibility data (everything visible)
function Tree.pvs(d: Data, leaf: number): { number }?
local lf = d.leaves[leaf + 1]
local vis = d.visibility
if not lf or not vis then
return nil
end
local out: { number } = {}
if d.variant == "q2" or d.variant == "q3" then
local nc = d.numClusters or 0
local c = lf.cluster or -1
if c < 0 or c >= nc then
return out
end
local bits: { boolean } = {}
if d.variant == "q2" then
if 4 + nc * 8 > buffer.len(vis) then
return nil
end
decompress(vis, readi32(vis, 4 + c * 8), (nc + 7) // 8, bits)
else
local sz = d.clusterBytes or 0
local o = 8 + c * sz
for k = 0, sz - 1 do
if o + k < buffer.len(vis) then
local v = readu8(vis, o + k)
for bit = 0, 7 do
if bit32.band(v, bit32.lshift(1, bit)) ~= 0 then
bits[k * 8 + bit + 1] = true
end
end
end
end
end
for i, l in d.leaves do
local cl = l.cluster or -1
if cl >= 0 and bits[cl + 1] then
table.insert(out, i - 1)
end
end
return out
end
-- Quake 1: bit k = leaf k + 1 (leaf 0 is the shared solid leaf), visleafs bits
local visofs = lf.visofs or -1
if leaf == 0 or visofs < 0 then
return out
end
local n = d.models[1] and d.models[1].visleafs or (#d.leaves - 1)
local bits: { boolean } = {}
decompress(vis, visofs, (n + 7) // 8, bits)
for k = 0, n - 1 do
if bits[k + 1] then
table.insert(out, k + 1)
end
end
return out
end
return Tree
+54 -8
View File
@@ -1,15 +1,18 @@
--!strict
-- model/bsp: compiled game maps, read: Quake 1 (BSP 29), Half-Life (BSP 30), Quake II (IBSP 38), Quake III / RTCW
-- (IBSP 46 / 47). Quake textures need the game's palette (gfx/palette.lmp, not redistributable). Map units, z up.
-- Not supported: Source engine VBSP, Quake 1/2 lightmaps, visibility and collision data, writing.
-- model/bsp: compiled game maps, read: Quake 1 (BSP 29, BSP2, 2PSB), Half-Life (BSP 30), Quake II (IBSP 38), Quake III
-- / RTCW (IBSP 46 / 47). Lightmaps (Quake 1 / 2 / Half-Life: one atlas, Quake III: its pages) as TEXCOORD_1; the tree,
-- collision hulls / brushes and visibility in meta.bsp with point queries (Bsp.leafAt / contents / pvs). Quake textures
-- need the game's palette (gfx/palette.lmp, not redistributable). Map units, z up. Not supported: Source engine VBSP,
-- light styles other than the first, BSPX lumps, writing.
-- ------------------------------------------------------------------------------------------------ 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 Brush = require("@rosetta/model/bsp/Brush")
local Quake = require("@rosetta/model/bsp/Quake")
local Quake3 = require("@rosetta/model/bsp/Quake3")
local Tree = require("@rosetta/model/bsp/Tree")
-- ------------------------------------------------------------------------------------------------ contract
local Bsp = {
@@ -18,7 +21,7 @@ local Bsp = {
extensions = { "bsp" },
mime = { "model/x-bsp" },
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" },
caps = { decode = true, encode = false, variants = { "quake", "bsp2", "2psb", "halflife", "quake2", "quake3" }, lightmaps = true, collision = true, visibility = true },
}
-- ------------------------------------------------------------------------------------------------ types
@@ -27,6 +30,10 @@ export type DecodeOptions = {
resolve: ((uri: string) -> (buffer | string)?)?,
files: { [string]: buffer | string }?,
patchLevel: number?, -- default 4
lit: (buffer | string)?, -- Quake 1: the map's .lit file (coloured light); also found as "<map>.lit" through files / resolve
lightmaps: boolean?, -- default true
tree: boolean?, -- meta.bsp (tree, hulls, visibility), default true
name: string?, -- the file name (finds the .lit)
maxPixels: number?, -- default 2^24
maxVertices: number?, -- default 2^24
}
@@ -46,6 +53,9 @@ function Bsp.sniff(r: Bytes.Reader): number
end
local m = r:peek(4)
local v = buffer.readi32(r.buf, r.pos + (if m == "IBSP" then 4 else 0))
if m == "BSP2" or m == "2PSB" then
v = 29
end
if m == "IBSP" then
return if v == 38 or v == 46 or v == 47 then 1 else 0.3
end
@@ -88,6 +98,8 @@ function Bsp.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Scene?, Err.E
names, dir, variant = Q2_LUMPS, 8, "q2"
elseif m == "IBSP" and (version == 46 or version == 47) then
names, dir, variant = Q3_LUMPS, 8, "q3"
elseif m == "BSP2" or m == "2PSB" then
names, dir, variant = Q1_LUMPS, 4, string.lower(m)
elseif m ~= "IBSP" and (version == 29 or version == 30) then
names, dir, variant = Q1_LUMPS, 4, if version == 30 then "hl" else "q1"
elseif m == "VBSP" then
@@ -114,13 +126,15 @@ function Bsp.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Scene?, Err.E
if pal and buffer.len(pal) < 768 then
pal = nil
end
scene, msg = Brush.decode(b, base, lumps, variant, {
scene, msg = Quake.decode(b, base, lumps, variant, {
palette = pal,
wal = function(name: string): buffer?
return Input.sibling(opts, "textures/" .. name .. ".wal")
end,
maxPixels = opts and opts.maxPixels,
maxVertices = opts and opts.maxVertices,
lit = if opts and opts.lit then Bytes.toBuffer(opts.lit) else (if opts and opts.name then Input.sibling(opts, (string.gsub(opts.name :: string, "%.[^./\\]*$", "")) .. ".lit") else nil),
lightmaps = opts and opts.lightmaps,
})
end
if not scene then
@@ -132,12 +146,44 @@ function Bsp.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Scene?, Err.E
scene.meta.entities = entities(text)
scene.meta.source = {
format = "bsp",
variant = ({ q1 = "quake", hl = "halflife", q2 = "quake2", q3 = "quake3" } :: { [string]: string })[variant],
variant = ({ q1 = "quake", bsp2 = "quake", ["2psb"] = "quake", hl = "halflife", q2 = "quake2", q3 = "quake3" } :: { [string]: string })[variant],
layout = if variant == "bsp2" then "BSP2" elseif variant == "2psb" then "2PSB" else nil,
version = version,
entities = text,
palette = if variant == "q1" then (opts ~= nil and (opts.palette ~= nil or Input.sibling(opts, "gfx/palette.lmp") ~= nil)) else nil,
palette = if variant == "q1" or variant == "bsp2" or variant == "2psb" then (opts ~= nil and (opts.palette ~= nil or Input.sibling(opts, "gfx/palette.lmp") ~= nil)) else nil,
}
if not (opts and opts.tree == false) then
local tree, terr = Tree.read(b, base, lumps, variant)
if not tree then
return nil, Err.from(terr)
end
scene.meta.bsp = tree
end
return scene, nil
end
-- ------------------------------------------------------------------------------------------------ extras
local function tree(scene: any): Tree.Data?
return type(scene) == "table" and type(scene.meta) == "table" and scene.meta.bsp or nil
end
-- the leaf (0-based) at a point, in the tree of a model (0 = the world)
function Bsp.leafAt(scene: Types.Scene, x: number, y: number, z: number, model: number?): number?
local d = tree(scene)
return if d then Tree.leafAt(d, x, y, z, model) else nil
end
-- the contents at a point: Quake 1 CONTENTS_* (-1 empty, -2 solid, ...; hull 0 point, 1 player, 2 shambler, 3 crouch
-- in Half-Life), Quake II / III contents bits
function Bsp.contents(scene: Types.Scene, x: number, y: number, z: number, hull: number?, model: number?): number?
local d = tree(scene)
return if d then Tree.contents(d, x, y, z, hull, model) else nil
end
-- the leaves (0-based) potentially visible from a leaf; nil when the map has no visibility data
function Bsp.pvs(scene: Types.Scene, leaf: number): { number }?
local d = tree(scene)
return if d then Tree.pvs(d, leaf) else nil
end
return Bsp