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

+656 -32
View File
@@ -2244,7 +2244,7 @@ local list= {
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 __include("model/bsp")
end,
@@ -146126,18 +146126,21 @@ end
return Read
end
__FILES["model/bsp"] = function()
local __compat = __compat local buffer, __iter = __compat.buffer, __compat.__iter --!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.
local __compat = __compat local buffer, type, __iter = __compat.buffer, __compat.type, __compat.__iter --!strict
-- 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 = __include("core/Err")
local Bytes = __include("core/Bytes")
local Input = __include("core/Input")
local Types = __include("Types")
local Brush = __include("model/bsp/Brush")
local Quake = __include("model/bsp/Quake")
local Quake3 = __include("model/bsp/Quake3")
local Tree = __include("model/bsp/Tree")
-- ------------------------------------------------------------------------------------------------ contract
local Bsp = {
@@ -146146,7 +146149,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
-- ------------------------------------------------------------------------------------------------ constants
@@ -146160,6 +146163,10 @@ local Bsp = {
local Q1_LUMPS = { "entities", "planes", "miptex", "vertices", "visibility", "nodes", "texinfo", "faces", "lighting",
"clipnodes", "leaves", "marksurfaces", "edges", "surfedges", "models" }
local Q2_LUMPS = { "entities", "planes", "vertices", "visibility", "nodes", "texinfo", "faces", "lighting", "leaves",
@@ -146174,6 +146181,9 @@ if r:remaining() < 64 then
end
local m = r:peek(4)
local v = buffer.readi32(r.buf, r.pos + (m == "IBSP" and 4 or 0))
if m == "BSP2" or m == "2PSB" then
v = 29
end
if m == "IBSP" then
return (v == 38 or v == 46 or v == 47 )and 1 or 0.3
end
@@ -146216,6 +146226,8 @@ if m == "IBSP" and version == 38 then
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, version == 30 and"hl" or"q1"
elseif m == "VBSP" then
@@ -146242,13 +146254,15 @@ if variant == "q3" then
)})[1] 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)
return Input.sibling(opts, "textures/" .. name .. ".wal")
end,
maxPixels = opts and opts.maxPixels,
maxVertices = opts and opts.maxVertices,
lit = (opts and opts.lit and{(Bytes.toBuffer(opts.lit) )}or{((opts and opts.name and{(Input.sibling(opts, (string.gsub(opts.name , "%.[^./\\]*$", "")) .. ".lit") )}or{nil})[1])})[1],
lightmaps = opts and opts.lightmaps,
})
end
if not scene then
@@ -146260,29 +146274,129 @@ return Input.sibling(opts, "textures/" .. name .. ".wal")
scene.meta.entities = entities(text)
scene.meta.source = {
format = "bsp",
variant = ({ q1 = "quake", hl = "halflife", q2 = "quake2", q3 = "quake3" } )[variant],
variant = ({ q1 = "quake", bsp2 = "quake", ["2psb"] = "quake", hl = "halflife", q2 = "quake2", q3 = "quake3" } )[variant],
layout = variant == "bsp2" and"BSP2" or(variant == "2psb" and"2PSB" or nil),
version = version,
entities = text,
palette = (variant == "q1" and{(opts ~= nil and (opts.palette ~= nil or Input.sibling(opts, "gfx/palette.lmp") ~= nil)) }or{nil})[1],
palette = ((variant == "q1" or variant == "bsp2" or variant == "2psb" )and{(opts ~= nil and (opts.palette ~= nil or Input.sibling(opts, "gfx/palette.lmp") ~= nil)) }or{nil})[1],
}
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)
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, x, y, z, model)
local d = tree(scene)
return (d and{(Tree.leafAt(d, x, y, z, model) )}or{nil
})[1]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, x, y, z, hull, model)
local d = tree(scene)
return (d and{(Tree.contents(d, x, y, z, hull, model) )}or{nil
})[1]end
-- the leaves (0-based) potentially visible from a leaf; nil when the map has no visibility data
function Bsp.pvs(scene, leaf)
local d = tree(scene)
return (d and{(Tree.pvs(d, leaf) )}or{nil
})[1]end
return Bsp
end
__FILES["model/bsp/Brush"] = function()
__FILES["model/bsp/Lightmap"] = function()
local __compat = __compat local buffer, __iter = __compat.buffer, __compat.__iter --!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/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 = {}
-- nil, message past maxPixels
function Lightmap.pack(sizes, maxPixels)
local area, widest = 0, 1
for _, s in __iter(sizes) do
area =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 =W* 2
end
W = math.max(W, widest)
local order = (table.create(#sizes) )
for i = 1, #sizes do
order[i] = i
end
table.sort(order, function(a, b)
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) )
local x, y, rowH = 0, 0, 0
for _, i in __iter(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 =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, W, r)
local function copy(dx, dy, sx, sy)
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
end
__FILES["model/bsp/Quake"] = function()
local __compat = __compat local buffer, bit32, __iter = __compat.buffer, __compat.bit32, __compat.__iter --!strict
-- 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 = __include("Types")
local Pixels = __include("codecs/image/Pixels")
local Lightmap = __include("model/bsp/Lightmap")
local Miptex = __include("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
@@ -146296,6 +146410,8 @@ local writef32, writeu32 = buffer.writef32, buffer.writeu32
local function cstr(b, at, n)
return (string.match(buffer.readstring(b, at, n), "^[^%z]*"))
end
@@ -146331,11 +146447,14 @@ local out= {}
return out, nil
end
function Brush.decode(b, base, lumps, variant, opts)
function Quake.decode(b, base, lumps, variant, opts)
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 = math.floor(V.size / 12), math.floor(E.size / 4), math.floor(SE.size / 4), math.floor(Fc.size / 20
local fSize= big and 28 or 20
local eSize= big and 8 or 4
local nV, nE, nSE, nF = math.floor(V.size / 12), math.floor(E.size / eSize), math.floor(SE.size / 4), math.floor(Fc.size / fSize
) local tiSize = q2 and 76 or 40
local nTI, nP = math.floor(TI.size / tiSize), math.floor(P.size / 20
) local mSize = q2 and 48 or 64
@@ -146398,11 +146517,28 @@ local q2 = variant == "q2"
local batches= {}
local orders= {}
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= { { 1, 1 }, { 1, 1 } }
local lmFaces= { { 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 __DARKLUA_CONTINUE_7=false repeat 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 model = faceModel[f + 1]
if not model or numEdges < 3 or firstEdge < 0 or firstEdge + numEdges > nSE or plane >= nP or texinfo >= nTI then
local __DARKLUA_CONTINUE_7=false repeat local fo = base + Fc.at + f * fSize
local plane = (big and{(readi32(b, fo) )}or{(readu16(b, fo)
)})[1] local side = (big and{(readi32(b, fo + 4) )}or{(readu16(b, fo + 2)
)})[1] local firstEdge = (big and{(readi32(b, fo + 8) )}or{(readi32(b, fo + 4)
)})[1] local numEdges = (big and{(readi32(b, fo + 12) )}or{(readu16(b, fo + 8)
)})[1] local texinfo = (big and{(readi32(b, fo + 16) )}or{(readu16(b, fo + 10)
)})[1] local styles = (big and((fo + 20 ))or((fo + 12
))) local lightofs = (big and{(readi32(b, fo + 24) )}or{(readi32(b, fo + 16)
)})[1] local model = faceModel[f + 1]
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 =skipped+ 1
__DARKLUA_CONTINUE_7=true break
end
@@ -146415,8 +146551,14 @@ __DARKLUA_CONTINUE_7=true break
ok = false
break
end
local v = (se >= 0 and{(readu16(b, base + E.at + e * 4) )}or{(readu16(b, base + E.at + e * 4 + 2)
)})[1] if v >= nV then
local eo = base + E.at + e * eSize
local v
if big then
v = (se >= 0 and{(readu32(b, eo) )}or{(readu32(b, eo + 4)
)})[1] else
v = (se >= 0 and{(readu16(b, eo) )}or{(readu16(b, eo + 2)
)})[1] end
if v >= nV then
ok = false
break
end
@@ -146459,6 +146601,37 @@ __DARKLUA_CONTINUE_7=true break
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 + (q2 and 32 or 36))
local special = (q2 and{(bit32.band(tflags, 0x8C) ~= 0 )}or{(bit32.band(tflags, 1) ~= 0
)})[1] if special then
rec = 1
elseif lightofs >= 0 then
local smin, smax, tmin, tmax= 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 ) / 16) - bs + 1, math.ceil((tmax ) / 16) - bt0 + 1
local ns = 0
for k = 0, 3 do
if readu8(b, styles + k) ~= 255 then
ns =ns+ 1
end
end
local bytes = lw * lh * (rgb and 3 or 1)
lumaTotal =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 = (tex and{tex.width }or{1})[1], (tex and{tex.height }or{1
@@ -146466,7 +146639,7 @@ __DARKLUA_CONTINUE_7=true break
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
@@ -146479,21 +146652,69 @@ __DARKLUA_CONTINUE_7=true break
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
__DARKLUA_CONTINUE_7=true until true if not __DARKLUA_CONTINUE_7 then break end end
local atlasW, atlasH, rects = 0, 0, nil
local lmTex= nil
local atlas= 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, cg, cb= 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 ) * 65536 + (cg ) * 256 + (cr ))
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 __iter(texs) do
local tex= { name = t.name, image = t.image, uri = (t.image and{nil }or{((q2 and(("textures/" .. t.name .. ".wal" ))or(t.name))) })[1]}
table.insert(scene.textures, tex)
local mat = Scene.material(t.name)
mat.metallic = 0
local extras= { bsp = { texels = t.texels and true or nil, width = t.width, height = t.height } }
mat.extras = extras
mat.extras = { bsp = { texels = t.texels and true or nil, width = t.width, height = t.height } }
mat.extras = { bsp = { texels = t.texels and true or nil, width = t.width, height = t.height, lightmap = lmTex, lightmapTexCoord = lmTex and 1 or nil } }
table.insert(scene.materials, mat)
end
if atlas then
table.insert(scene.textures, { name = "lightmap", image = atlas })
end
local root= { name = "bsp", children = {} }
table.insert(scene.nodes, root)
scene.roots[1] = 1
@@ -146515,8 +146736,23 @@ table.insert(scene.materials, mat)
for k = 0, nv - 1 do
writeu32(ib, k * 4, k)
end
local attrs= { 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" ,
material = (ti > 0 and{ti }or{nil})[1],
@@ -146531,7 +146767,7 @@ table.insert(scene.materials, mat)
return scene, nil
end
return Brush
return Quake
end
__FILES["model/bsp/Quake3"] = function()
local __compat = __compat local buffer, __iter = __compat.buffer, __compat.__iter --!strict
@@ -146761,6 +146997,394 @@ end
return Quake3
end
__FILES["model/bsp/Tree"] = function()
local __compat = __compat local buffer, bit32, type, __iter = __compat.buffer, __compat.bit32, __compat.type, __compat.__iter --!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
local function v3(b, o, kind)
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, base, l)
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, base, lumps, variant, maxItems)
local limit = maxItems or 2 ^ 22
local q2, q3 = variant == "q2", variant == "q3"
local bsp2, rmq = variant == "bsp2", variant == "2psb"
local d= { variant = variant, planes = {}, nodes = {}, leaves = {}, models = {} }
local function count(l, size)
return (l and{(math.floor(l.size / size ))}or{0
})[1] end
local P = lumps.planes
local pSize = q3 and 16 or 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 = (q3 and{nil }or{(readi32(b, o + 16) )})[1]}
end
local N = lumps.nodes
local nSize = q3 and 36 or(q2 and 28 or(bsp2 and 44 or(rmq and 32 or 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
if q3 or q2 or bsp2 or rmq then
local bk = q3 and"i" or(bsp2 and"f" or"s"
) local bs = bk == "s" and 6 or 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] = (p < nn and{p }or{(-(65535 - p) - 1 -- Quakespasm Mod_LoadNodes_S: leaf 65535 - p
)})[1] 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 = q3 and 48 or(q2 and 28 or(bsp2 and 44 or(rmq and 32 or 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
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 = bsp2 and"f" or"s"
local bs = bsp2 and 12 or 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 = (big and{(readu32(b, fo) )}or{(readu16(b, fo))})[1], numFaces = (big and{(readu32(b, fo + 4) )}or{(readu16(b, fo + 2) )})[1]}
local ao = fo + (big and 8 or 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 = (bsp2 or rmq )and 12 or 8
local nc = count(C, cSize)
if nc > limit then
return nil, "limit: too many clipnodes"
end
local cl= {}
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] = (p > nc and((p - 65536 ))or(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 = q3 and 40 or(q2 and 48 or 64
) for i = 0, count(M, mSize) - 1 do
local o = base + M.at + i * mSize
local m
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, q3 and 8 or 4)
if nb > limit or ns > limit then
return nil, "limit: too many brushes"
end
local brushes, sides= {}, {}
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= {}
for i = 0, count(LB, q3 and 4 or 2) - 1 do
lbs[i + 1] = (q3 and{(readi32(b, base + LB.at + i * 4) )}or{(readu16(b, base + LB.at + i * 2)
)})[1] 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 __iter(brushes) do
local t = br.contents
br.contents = (t >= 0 and t < nt and{(readi32(b, base + T.at + t * 72 + 68) )}or{0
})[1] end
end
end
local VL = lumps.visibility or lumps.visdata
d.visibility = (VL and{(slice(b, base, VL) )}or{nil
})[1] 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, plane, x, y, z)
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, x, y, z, model)
local m = d.models[(model or 0) + 1]
local node = (m and{m.headnodes[1] }or{0
})[1] 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 = (side(d, nd.plane, x, y, z) >= 0 and{nd.children[1] }or{nd.children[2]
})[1] 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, x, y, z, hull, model)
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 = (m and{m.headnodes[h + 1] or -1 }or{(-1
)})[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 = (side(d, c.plane, x, y, z) >= 0 and{c.children[1] }or{c.children[2]
})[1] 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, brushes, sides= d.leafBrushes or {}, d.brushes or {}, d.brushSides or {}
local fb, nb= 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, at, bytes, out)
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 =i+ 1
at =at+ 1
else
if at + 1 >= n then
break
end
i =i+ readu8(vis, at + 1)
at =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, leaf)
local lf = d.leaves[leaf + 1]
local vis = d.visibility
if not lf or not vis then
return nil
end
local out= {}
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= {}
if d.variant == "q2" then
if 4 + nc * 8 > buffer.len(vis) then
return nil
end
decompress(vis, readi32(vis, 4 + c * 8), math.floor((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 __iter(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= {}
decompress(vis, visofs, math.floor((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
end
__FILES["model/dae"] = function()
local __compat = __compat local buffer, type, __iter = __compat.buffer, __compat.type, __compat.__iter --!strict
-- model/dae: COLLADA 1.4.1 / 1.5.0 (Khronos specifications; .dae XML, .zae zip with manifest.xml). Supports: geometry,