From 52d2d7ebf9af46c5204bba5a5e907eb9f00b2463 Mon Sep 17 00:00:00 2001 From: 4DBug Date: Sun, 1 Nov 2026 18:53:15 -0600 Subject: [PATCH] model/vbsp: Source BSP 19-21 (L4D2 header, LZMA lumps): faces, displacements, static props v4-v13, brush entities, lights, entities, the pak lump as an Archive; KeyValues bench --- README.md | 3 +- docs/FORMATS.md | 1 + docs/guide/scene.md | 28 +- src/Rosetta/Registry.luau | 12 + src/Rosetta/model/vbsp/Faces.luau | 318 +++++++++++++++++++++ src/Rosetta/model/vbsp/Props.luau | 90 ++++++ src/Rosetta/model/vbsp/init.luau | 444 ++++++++++++++++++++++++++++++ tests/model/vbsp.luau | 221 +++++++++++++++ tools/bench.luau | 20 ++ tools/fixtures/docs_source.py | 19 ++ tools/fixtures/vbsp.py | 305 ++++++++++++++++++++ 11 files changed, 1459 insertions(+), 2 deletions(-) create mode 100644 src/Rosetta/model/vbsp/Faces.luau create mode 100644 src/Rosetta/model/vbsp/Props.luau create mode 100644 src/Rosetta/model/vbsp/init.luau create mode 100644 tests/model/vbsp.luau create mode 100644 tools/fixtures/docs_source.py create mode 100644 tools/fixtures/vbsp.py diff --git a/README.md b/README.md index 47b84c2..20f006f 100644 --- a/README.md +++ b/README.md @@ -44,7 +44,7 @@ print(F.detect(webp), #F.formats()) -- "webp", the format list ## Formats -175 formats. Generated from the format contracts by `tools/gen_registry.py`; [docs/FORMATS.md](docs/FORMATS.md) +176 formats. Generated from the format contracts by `tools/gen_registry.py`; [docs/FORMATS.md](docs/FORMATS.md) adds each format's capabilities. | Category | Format | Extensions | Read | Write | @@ -134,6 +134,7 @@ adds each format's capabilities. | 3D models | smd | .smd | yes | yes | | 3D models | stl | .stl | yes | yes | | 3D models | usda | .usda .usd .usdz | yes | yes | +| 3D models | vbsp | .bsp | yes | - | | 3D models | vox | .vox | yes | yes | | 3D models | vrml | .wrl .wrz .vrml | yes | yes | | 3D models | x | .x | yes | - | diff --git a/docs/FORMATS.md b/docs/FORMATS.md index feebd7e..56153f5 100644 --- a/docs/FORMATS.md +++ b/docs/FORMATS.md @@ -90,6 +90,7 @@ is tested under both runtimes (luau `--codegen -O2` and LuaJIT through the build | model | smd | .smd | yes | yes | skins: true, animation: true | `tests/model/smd.luau` | | model | stl | .stl | yes | yes | ascii: true, binary: true, colors: true, indexed: false | `tests/model/stl.luau` | | model | usda | .usda .usd .usdz | yes | yes | materials: true, animation: true, cameras: true, lights: true, polygons: true, vertexColors: true, usdz: "read", usdc: false | `tests/model/usda.luau` | +| model | vbsp | .bsp | yes | - | versions: 19, 20, 21, displacements: true, staticProps: true, pak: true | `tests/model/vbsp.luau` | | model | vox | .vox | yes | yes | voxels: true, sceneGraph: true, materials: true | `tests/model/vox.luau` | | model | vrml | .wrl .wrz .vrml | yes | yes | materials: true, polygons: true, animation: true, cameras: true, lights: true, lines: true, points: true | `tests/model/vrml.luau` | | model | x | .x | yes | - | text: true, binary: true, compressed: true, materials: true, skins: true, animation: true, polygons: true, vertexColors: true | `tests/model/x.luau` | diff --git a/docs/guide/scene.md b/docs/guide/scene.md index 40c3d7b..f8ab0ae 100644 --- a/docs/guide/scene.md +++ b/docs/guide/scene.md @@ -470,6 +470,7 @@ Game model formats load as Scenes too, with what games need: skins (joints + inv | MD5 (Doom 3 `.md5mesh` / `.md5anim`) | skeleton, weighted meshes, shaders as URIs | the `.md5anim` files named in `anims` | | SMD (Valve, read + write) | skeleton, weight links, a primitive per material | the skeleton frames | | BSP (Quake 1 / 2 / 3, Half-Life) | each model a mesh, a primitive per texture (and Quake III lightmap); entities in `meta.entities` | - | +| VBSP (Source 19 / 20 / 21) | each model a mesh, a primitive per material, displacements; static props as nodes; lights; entities; the pak lump | - | ```luau local tank = assert(F.model.load(md2Bytes)) @@ -507,6 +508,31 @@ local again = assert(F.save(barney, nil, { format = "smd" })) -- SMD writes ba assert(F.model.load(again).skins[1]) ``` +### Source maps (VBSP) + +Compiled Source maps (`.bsp` with the `VBSP` magic: HL2, TF2, Portal, L4D2, CS:GO) load as one mesh per brush model +(`world`, `*1`, ...) with a primitive per material; brush entities place their model by `origin` / `angles`. +Displacements are tessellated (their blend alpha is the `_BLEND` attribute), tool faces (nodraw, skip, hint, sky) are +left out unless `tools = true`. Static props are nodes with `extras.model` (the `.mdl` path) and +`extras.vbsp` (skin, solid, fade, ...); `light`, `light_spot` and `light_environment` become lights. Entities are +`meta.entities` (KeyValues objects: a repeated output is an array), the pak lump `meta.pak` (an Archive), and a +material's texture is `materials/.vtf`, embedded when the pak has it. LZMA-compressed lumps and the L4D2 lump +header are read; lightmaps and visibility are not. + +```luau +local room = assert(F.model.load(vbspBytes, { name = "room.bsp" })) +assert(room.meta.source.format == "vbsp" and room.meta.source.version == 21) +local props = {} +for _, n in room.nodes do + if n.extras and n.extras.model then + table.insert(props, n.extras.model) + end +end +assert(props[1] == "models/props_junk/wood_crate001a.mdl") +assert(room.meta.entities[1].classname == "worldspawn") +assert(room.meta.pak:read("materials/custom/note.txt")) +``` + ## Blitz3D (B3D) `.b3d` files (Blitz3D, also written by many old game tools) load read-only. The node tree keeps its names and TRS; @@ -744,7 +770,7 @@ assert(back.meshes[1].primitives[1].indices.count == 3) | VRML97 (WRL / WRZ) | yes | yes | primitives, PROTO, Inline, ROUTE animations, cameras, lights | | X3D (XML / classic) | yes | yes | the VRML reader plus the X3D triangle / quad / line sets; no binary `.x3db` | | STEP | via the CAD plug-in | | see [cad.md](cad.md) | -| MD2, MD3, MDL, MD5, BSP | yes | - | game models and maps: see "Game models" above | +| MD2, MD3, MDL, MD5, BSP, VBSP | yes | - | game models and maps: see "Game models" above | | SMD | yes | yes | Valve studiomdl data | | Roblox `.mesh` (robloxmesh) | yes | yes | see [roblox.md](roblox.md) | | Roblox `.rbxm` / `.rbxl`, `.rbxmx` / `.rbxlx` | as an `RbxTree` | yes | instance trees with typed properties: see [roblox.md](roblox.md) | diff --git a/src/Rosetta/Registry.luau b/src/Rosetta/Registry.luau index 85a34f0..72ffe02 100644 --- a/src/Rosetta/Registry.luau +++ b/src/Rosetta/Registry.luau @@ -1034,6 +1034,18 @@ local list: { Entry } = { return require("@rosetta/model/usda") end, }, + { + name = "vbsp", + category = "model", + path = "model/vbsp", + extensions = { "bsp" }, + mime = { "model/x-vbsp" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/compress/Lzma", "codecs/text/KeyValues", "codecs/model/Mat4", "containers/Zip", "containers/Archive" }, + caps = { decode = true, encode = false, versions = { 19, 20, 21 }, displacements = true, staticProps = true, pak = true }, + load = function() + return require("@rosetta/model/vbsp") + end, + }, { name = "vox", category = "model", diff --git a/src/Rosetta/model/vbsp/Faces.luau b/src/Rosetta/model/vbsp/Faces.luau new file mode 100644 index 0000000..cb9b937 --- /dev/null +++ b/src/Rosetta/model/vbsp/Faces.luau @@ -0,0 +1,318 @@ +--!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 tessellate as CCoreDispInfo:: +-- GenerateDispSurf (rows along corner 0 -> 1, columns 0 -> 3, corner 0 nearest startPosition) with the alternating +-- triangle pattern of the SDK's disp tesselation; their normals come from the grid. +local Types = require("@rosetta/Types") + +local Faces = {} + +local Scene = Types.Scene +local readi32, readu16, readi16, readf32, readu8 = buffer.readi32, buffer.readu16, buffer.readi16, buffer.readf32, buffer.readu8 +local writef32, writeu32 = buffer.writef32, buffer.writeu32 +local sqrt = math.sqrt + +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 cross(ax: number, ay: number, az: number, bx: number, by: number, bz: number): (number, number, number) + return ay * bz - az * by, az * bx - ax * bz, ax * by - ay * bx +end + +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 + +-- the 2^power x 2^power quads in the SDK's alternating diagonal pattern +local function dispTriangles(n: number, flip: boolean, base: number, idx: { number }) + for i = 0, n - 2 do + for j = 0, n - 2 do + local a = base + i * n + j + local b, c, d = a + n, a + n + 1, a + 1 + local tris: { number } + if (i + j) % 2 == 0 then + tris = { a, b, d, b, c, d } + else + tris = { a, b, c, a, c, d } + end + for t = 0, 1 do + local p, q, r = tris[t * 3 + 1], tris[t * 3 + 2], tris[t * 3 + 3] + if flip then + q, r = r, q + end + idx[#idx + 1], idx[#idx + 2], idx[#idx + 3] = p, q, r + end + end + end +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 sx, sy, sz = readf32(b, o), readf32(b, o + 4), readf32(b, o + 8) + local vstart, power = readi32(b, o + 12), readi32(b, o + 20) + if power < 1 or power > 4 then + return "displacement power " .. power + end + if #poly ~= 12 then + return nil -- not a quad: the base face is kept + 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 + local best, bestD = 0, math.huge + for k = 0, 3 do + local dx, dy, dz = poly[k * 3 + 1] - sx, poly[k * 3 + 2] - sy, poly[k * 3 + 3] - sz + local dd = dx * dx + dy * dy + dz * dz + if dd < bestD then + best, bestD = k, dd + end + end + local c: { number } = table.create(12) :: any + for k = 0, 3 do + local s = ((best + k) % 4) * 3 + c[k * 3 + 1], c[k * 3 + 2], c[k * 3 + 3] = poly[s + 1], poly[s + 2], poly[s + 3] + end + local P: { number } = table.create(n * n * 3) :: any + local base = #g.pos // 3 + local blend = g.blend or {} + g.blend = blend + for i = 0, n - 1 do + local t = i / (n - 1) + local ax, ay, az = c[1] + (c[4] - c[1]) * t, c[2] + (c[5] - c[2]) * t, c[3] + (c[6] - c[3]) * t + local bx, by, bz = c[10] + (c[7] - c[10]) * t, c[11] + (c[8] - c[11]) * t, c[12] + (c[9] - c[12]) * t + for j = 0, n - 1 do + local s = j / (n - 1) + local x, y, z = ax + (bx - ax) * s, ay + (by - ay) * s, az + (bz - az) * s + local vo = dv.at + (vstart + i * n + j) * 20 + local dist = readf32(dv.buf, vo + 12) + local k = (i * n + j) * 3 + P[k + 1] = x + readf32(dv.buf, vo) * dist + P[k + 2] = y + readf32(dv.buf, vo + 4) * dist + P[k + 3] = z + readf32(dv.buf, vo + 8) * dist + local u = (x * tex[1] + y * tex[2] + z * tex[3] + tex[4]) / tex[9] + local v = (x * tex[5] + y * tex[6] + z * tex[7] + tex[8]) / tex[10] + emit(g, P[k + 1], P[k + 2], P[k + 3], 0, 0, 0, u, v) + blend[base + i * n + j + 1] = math.clamp(readf32(dv.buf, vo + 16) / 255, 0, 1) + end + end + -- grid normals by central differences, facing the base face's side + local ux, uy, uz = cross(c[4] - c[1], c[5] - c[2], c[6] - c[3], c[10] - c[1], c[11] - c[2], c[12] - c[3]) + local sign = if ux * nx + uy * ny + uz * nz >= 0 then 1 else -1 + local nrm = g.nrm + for i = 0, n - 1 do + local i0, i1 = math.max(i - 1, 0), math.min(i + 1, n - 1) + for j = 0, n - 1 do + local j0, j1 = math.max(j - 1, 0), math.min(j + 1, n - 1) + local a, b2 = (i1 * n + j) * 3, (i0 * n + j) * 3 + local e, f = (i * n + j1) * 3, (i * n + j0) * 3 + local x, y, z = cross(P[a + 1] - P[b2 + 1], P[a + 2] - P[b2 + 2], P[a + 3] - P[b2 + 3], P[e + 1] - P[f + 1], P[e + 2] - P[f + 2], P[e + 3] - P[f + 3]) + local l = sqrt(x * x + y * y + z * z) + if l < 1e-12 then + x, y, z, l = nx, ny, nz, sign + end + local k = (base + i * n + j) * 3 + nrm[k + 1], nrm[k + 2], nrm[k + 3] = x * sign / l, y * sign / l, z * sign / l + end + end + -- triangle (0, n, 1) winds along rows x columns: flip it when that does not face the face normal + dispTriangles(n, sign < 0, base, g.idx) + 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 + if grp.blend then + for k = before // 3 + 1, #grp.pos // 3 do + grp.blend[k] = 0 + end + 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 nv = #g.pos // 3 + local pb, nb, ub = buffer.create(nv * 12), buffer.create(nv * 12), buffer.create(nv * 8) + for k = 1, nv * 3 do + writef32(pb, (k - 1) * 4, g.pos[k]) + writef32(nb, (k - 1) * 4, g.nrm[k]) + end + for k = 1, nv * 2 do + writef32(ub, (k - 1) * 4, g.uv[k]) + end + local ni = #g.idx + local ib = buffer.create(ni * 4) + for k = 1, ni do + writeu32(ib, (k - 1) * 4, g.idx[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 g.blend then + local bb = buffer.create(nv * 4) + for k = 1, nv do + writef32(bb, (k - 1) * 4, g.blend[k] or 0) + end + attrs._BLEND = Scene.accessor(bb, "f32", 1, nv) + end + return { + attributes = attrs, + indices = Scene.accessor(ib, "u32", 1, ni), + mode = "triangles", + material = material, + } +end + +return Faces diff --git a/src/Rosetta/model/vbsp/Props.luau b/src/Rosetta/model/vbsp/Props.luau new file mode 100644 index 0000000..3226c9d --- /dev/null +++ b/src/Rosetta/model/vbsp/Props.luau @@ -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 diff --git a/src/Rosetta/model/vbsp/init.luau b/src/Rosetta/model/vbsp/init.luau new file mode 100644 index 0000000..cc6133b --- /dev/null +++ b/src/Rosetta/model/vbsp/init.luau @@ -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", "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/.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 diff --git a/tests/model/vbsp.luau b/tests/model/vbsp.luau new file mode 100644 index 0000000..d0ad217 --- /dev/null +++ b/tests/model/vbsp.luau @@ -0,0 +1,221 @@ +-- model/vbsp tests: maps written by tools/fixtures/vbsp.py and saved by srctools (v19 / v20 / v21, L4D2 header, LZMA +-- lumps, static props v4 .. v11) against what srctools reads back: face polygons and texture projections per +-- (model, material), the displacement grid, static props, entities, the pak lump; errors and the fuzz pass. +local T = require("@tests/T") +local Vbsp = require("@rosetta/model/vbsp") +local Bytes = require("@rosetta/core/Bytes") +local Err = require("@rosetta/core/Err") +local Types = require("@rosetta/Types") +local Mat4 = require("@rosetta/codecs/model/Mat4") +local Fx = require("@tests/gen/vbsp") + +local t = T.suite("vbsp") +t:eq(Vbsp.name, "vbsp", "name") +t:check(Vbsp.caps.decode and not Vbsp.caps.encode, "caps") + +local function f2(x: number): string + local s = string.format("%.2f", x) + return if s == "-0.00" then "0.00" else s +end + +local function lines(prim: Types.Primitive): (string, number) + local P, U = prim.attributes.POSITION, prim.attributes.TEXCOORD_0 + local out = table.create(P.count) + for i = 0, P.count - 1 do + out[i + 1] = table.concat({ + f2(buffer.readf32(P.data, i * 12)), f2(buffer.readf32(P.data, i * 12 + 4)), f2(buffer.readf32(P.data, i * 12 + 8)), + f2(buffer.readf32(U.data, i * 8)), f2(buffer.readf32(U.data, i * 8 + 4)), + }, " ") + end + table.sort(out) + return table.concat(out, "\n"), (prim.indices :: Types.Accessor).count // 3 +end + +local function fixLines(s: string): string + local out = {} + for l in string.gmatch(s, "[^\n]+") do + table.insert(out, (string.gsub(l, "%-0%.00", "0.00"))) + end + table.sort(out) + return table.concat(out, "\n") +end + +-- every triangle faces its vertices' normals (front faces are counter-clockwise) +local function facing(prim: Types.Primitive): boolean + local P, N, I = prim.attributes.POSITION, prim.attributes.NORMAL, prim.indices :: Types.Accessor + for k = 0, I.count // 3 - 1 do + local a, b, c = buffer.readu32(I.data, k * 12), buffer.readu32(I.data, k * 12 + 4), buffer.readu32(I.data, k * 12 + 8) + local function p(i: number, j: number): number + return buffer.readf32(P.data, i * 12 + j * 4) + end + local ux, uy, uz = p(b, 0) - p(a, 0), p(b, 1) - p(a, 1), p(b, 2) - p(a, 2) + local vx, vy, vz = p(c, 0) - p(a, 0), p(c, 1) - p(a, 1), p(c, 2) - p(a, 2) + local nx, ny, nz = uy * vz - uz * vy, uz * vx - ux * vz, ux * vy - uy * vx + local d = nx * buffer.readf32(N.data, a * 12) + ny * buffer.readf32(N.data, a * 12 + 4) + nz * buffer.readf32(N.data, a * 12 + 8) + if d <= 0 then + return false + end + end + return true +end + +-- Source AngleVectors(pitch, yaw, roll): forward, left (= -right), up +local function basis(p: number, y: number, r: number): { number } + local sp, cp = math.sin(math.rad(p)), math.cos(math.rad(p)) + local sy, cy = math.sin(math.rad(y)), math.cos(math.rad(y)) + local sr, cr = math.sin(math.rad(r)), math.cos(math.rad(r)) + return { + cp * cy, cp * sy, -sp, + sr * sp * cy - cr * sy, sr * sp * sy + cr * cy, sr * cp, + cr * sp * cy + sr * sy, cr * sp * sy - sr * cy, cr * cp, + } +end + +local first: Types.Scene? = nil +for _, c in Fx.cases do + local scene, err = Vbsp.decode(Bytes.reader(buffer.fromstring(c.data))) + t:check(scene ~= nil, c.name .. ": " .. tostring(err)) + if not scene then + continue + end + first = first or scene + local src = scene.meta.source :: any + t:eq(src.version, c.version, c.name .. ": version") + t:eq(src.variant == "l4d2", c.l4d2, c.name .. ": L4D2 header") + t:eq(src.compressed, c.compressed, c.name .. ": LZMA lumps") + t:eq(src.staticPropVersion, c.spversion, c.name .. ": static prop version") + -- faces + local byKey: { [string]: Types.Primitive } = {} + for _, n in scene.nodes do + if n.mesh then + local model = (n.extras :: any).vbsp.model + for _, prim in scene.meshes[n.mesh].primitives do + byKey[model .. "|" .. (scene.materials[prim.material :: number].name :: string)] = prim + end + end + end + local ngroups = 0 + for _ in byKey do + ngroups += 1 + end + t:eq(ngroups, #c.groups, c.name .. ": one primitive per (model, material), nodraw skipped") + for _, g in c.groups do + local prim = byKey[g.model .. "|" .. g.material] + t:check(prim ~= nil, c.name .. ": group " .. g.model .. " " .. g.material) + if prim then + local got, tris = lines(prim) + t:eq(tris, g.tris, c.name .. ": " .. g.material .. " triangles") + t:eq(got, fixLines(g.verts), c.name .. ": " .. g.material .. " positions and UVs as srctools") + t:check(facing(prim), c.name .. ": " .. g.material .. " counter-clockwise fronts") + if string.find(g.material, "BLEND", 1, true) then + t:check(prim.attributes._BLEND ~= nil, c.name .. ": displacement alpha") + end + end + end + -- static props + local props = {} + for _, n in scene.nodes do + if n.extras and (n.extras :: any).model then + table.insert(props, n) + end + end + t:eq(#props, #c.props, c.name .. ": static props") + for i, want in c.props do + local n = props[i] + if n then + t:eq((n.extras :: any).model, want.model, c.name .. ": prop " .. i .. " model") + t:eq((n.extras :: any).vbsp.skin, want.skin, c.name .. ": prop " .. i .. " skin") + local tr = n.translation :: { number } + t:check(math.abs(tr[1] - want.origin[1]) + math.abs(tr[2] - want.origin[2]) + math.abs(tr[3] - want.origin[3]) < 1e-4, c.name .. ": prop " .. i .. " origin") + local m = Mat4.fromQuat(n.rotation :: { number }) + local bv = basis(want.angles[1], want.angles[2], want.angles[3]) + local d = 0 + for col = 0, 2 do + for row = 0, 2 do + d = math.max(d, math.abs(m[col * 4 + row + 1] - bv[col * 3 + row + 1])) + end + end + t:check(d < 1e-5, c.name .. ": prop " .. i .. " rotation is AngleVectors") + end + end + -- entities + local ents = scene.meta.entities :: { any } + t:eq(#ents, c.entities, c.name .. ": entities") + local outputs, classes = 0, {} + for _, e in ents do + table.insert(classes, e.classname) + if type(e.OnTrigger) == "table" then + outputs += #e.OnTrigger + elseif e.OnTrigger then + outputs += 1 + end + end + table.sort(classes) + t:eq(table.concat(classes, ","), table.concat(c.classnames, ","), c.name .. ": classnames") + t:eq(outputs, c.outputs, c.name .. ": repeated outputs") + -- pak + local pak = scene.meta.pak + t:check(pak ~= nil and pak.kind == "archive", c.name .. ": pak archive") + if pak then + local names = {} + for _, e in pak:list() do + table.insert(names, e.name) + end + table.sort(names) + t:eq(table.concat(names, ","), table.concat(c.pak, ","), c.name .. ": pak names") + t:eq(buffer.tostring(pak:read("materials/custom/note.txt") :: buffer), "hello from the pak lump\n", c.name .. ": pak read") + end +end + +if first then + local s = first :: Types.Scene + t:eq(s.meta.up, "z", "z up") + local door, light + for _, n in s.nodes do + if n.name == "door" then + door = n + end + if n.light then + light = n + end + end + t:check(door and door.mesh and door.translation and door.translation[3] == 64, "func_brush placed at its origin") + t:check(light and s.lights[light.light].type == "point" and math.abs(s.lights[light.light].intensity - 300) < 1e-9, "light entity") + local disp = nil + for _, m in s.meshes do + for _, p in m.primitives do + if p.attributes._BLEND then + disp = p + end + end + end + t:check(disp ~= nil and disp.attributes.POSITION.count == 81, "power 3: 9 x 9 grid") + local all = Vbsp.decode(Bytes.reader(buffer.fromstring(Fx.cases[1].data)), { tools = true }) :: Types.Scene + t:check(#all.materials == #s.materials + 1, "tools = true keeps the nodraw face") +end + +do + local plain = buffer.fromstring(Fx.plain) + t:eq(Vbsp.sniff(Bytes.reader(plain)), 1, "sniff") + t:eq(Vbsp.sniff(Bytes.reader(buffer.fromstring("IBSP" .. string.rep("\0", 2000)))), 0, "not Quake") + local bad = buffer.fromstring(Fx.plain) + buffer.writei32(bad, 4, 42) + local _, e1 = Vbsp.decode(Bytes.reader(bad)) + t:eq(e1 and e1.code, Err.UNSUPPORTED, "version 42") + local _, e2 = Vbsp.decode(Bytes.reader(buffer.fromstring(string.sub(Fx.plain, 1, 600)))) + t:eq(e2 and e2.code, Err.TRUNCATED, "short header") + local cut = buffer.fromstring(string.sub(Fx.plain, 1, 3000)) + local _, e3 = Vbsp.decode(Bytes.reader(cut)) + t:eq(e3 and e3.code, Err.TRUNCATED, "lumps past the end") +end + +local samples = {} +for i, c in Fx.cases do + if i <= 4 then + table.insert(samples, c.data) + end +end +t:fuzz("decode", function(b: buffer) + return Vbsp.decode(Bytes.reader(b)) +end, samples, { keepHeader = 8 }) +t:done() diff --git a/tools/bench.luau b/tools/bench.luau index c44889a..fa5e0a2 100644 --- a/tools/bench.luau +++ b/tools/bench.luau @@ -219,6 +219,26 @@ do end) end +-- ws-source: KeyValues text (a 1 MB file of nested blocks) and an entity lump +do + local KeyValues = require("@rosetta/codecs/text/KeyValues") + local parts = { '"root"\n{\n' } + local ents = {} + for i = 1, 6000 do + table.insert(parts, string.format('\t"block%d"\n\t{\n\t\t"name"\t"item %d"\n\t\t"origin"\t"%d 0 64"\n\t\t"path"\t"models/props/x\\\\y.mdl"\n\t}\n', i, i, i)) + table.insert(ents, string.format('{\n"origin" "%d 0 64"\n"classname" "prop_dynamic"\n"OnTrigger" "a,b,,0,-1"\n}\n', i)) + end + table.insert(parts, "}\n") + local text, lump = table.concat(parts), table.concat(ents) + assert(KeyValues.parse(text)) + bench("keyvalues parse", 5, #text, function() + KeyValues.parse(text) + end) + bench("keyvalues entity lump", 5, #lump, function() + KeyValues.entities(lump) + end) +end + -- ws-arch codecs: zstd, brotli, bzip2, xz / lzma do local Zstd = require("@rosetta/codecs/compress/Zstd") diff --git a/tools/fixtures/docs_source.py b/tools/fixtures/docs_source.py new file mode 100644 index 0000000..2207781 --- /dev/null +++ b/tools/fixtures/docs_source.py @@ -0,0 +1,19 @@ +# Docs inputs for the Source engine sections of the scene page (tools/fixtures.py; tools/docs_check.py explains the +# inputs): the CS:GO-style VBSP of tools/fixtures/vbsp.py (srctools-saved, static props v11). +# tests/gen/docs_source.luau { files = { [name] = bytes }, vars = { vbspBytes = "room.bsp", ... } } +import importlib.util, json, os + +INPUTS = ["tools/docs_check.py", "tools/fixtures/vbsp.py"] + + +def mod(ctx, name): + spec = importlib.util.spec_from_file_location("fx_" + name, os.path.join(ctx.root, "tools", name + ".py") if name == "docs_check" else os.path.join(ctx.root, "tools", "fixtures", name + ".py")) + m = importlib.util.module_from_spec(spec) + spec.loader.exec_module(m) + return m + + +def generate(ctx): + res = json.loads(ctx.python(["srctools"], mod(ctx, "vbsp").CODE)) + files = {"room.bsp": next(bytes.fromhex(c["data"]) for c in res["cases"] if c["name"] == "csgo")} + mod(ctx, "docs_check").emit_inputs(ctx, files, {"vbspBytes": "room.bsp"}) diff --git a/tools/fixtures/vbsp.py b/tools/fixtures/vbsp.py new file mode 100644 index 0000000..cedbc27 --- /dev/null +++ b/tools/fixtures/vbsp.py @@ -0,0 +1,305 @@ +# model/vbsp fixtures: a small Source map (a room of brush faces, a non-quad ceiling, a nodraw face, a power-3 +# displacement floor, a func_brush model, entities with repeated outputs, a pak lump) written here from the SDK's +# bspfile.h layouts, then loaded and saved by srctools (BSP.save: static props in game lump versions 4 .. 11, LZMA +# compressed lumps, the L4D2 lump header, a v19 header, a srctools-written entity lump). What srctools reads back from +# each saved file is the reference: face polygons + texinfo projections, static props, entities, pak file names; the +# displacement grid is tessellated here as CCoreDispInfo::GenerateDispSurf does. +# tests/gen/vbsp.luau { cases = { { name, data, version, l4d2?, compressed?, props, entities, pak, groups } } } +# groups: one per (model, material): { model, material, tris, verts = sorted "x y z u v" lines (%.2f) }. +import json + +CODE = r''' +import io, json, math, os, struct, sys, tempfile, zipfile +import srctools.bsp as B +from srctools import Vec, Angle +_out, sys.stdout = sys.stdout, sys.stderr # BSP.save prints + +SURF_NODRAW = 0x80 + +def build(): + texdata = [("BRICK/BRICKWALL001A", 512, 512), ("TOOLS/TOOLSNODRAW", 64, 64), ("NATURE/BLENDGRASSDIRT", 256, 256)] + texinfo = [ # s xyz shift, t xyz shift, flags, texdata + ((0.25, 0, 0, 16), (0, 0, -0.25, 8), 0, 0), + ((0, 0.25, 0, 0), (0, 0, -0.25, 0), 0, 0), + ((0.25, 0, 0, 0), (0, -0.25, 0, 0), 0, 0), + ((0.25, 0, 0, 0), (0, 0.25, 0, 0), SURF_NODRAW, 1), + ((0.125, 0, 0, 0), (0, -0.125, 0, 32), 0, 2), + ] + verts, vindex = [], {} + def v(p): + p = tuple(float(x) for x in p) + if p not in vindex: + vindex[p] = len(verts) + verts.append(p) + return vindex[p] + edges, eindex, surfedges = [(0, 0)], {}, [] + def poly_edges(poly): + first = len(surfedges) + ids = [v(p) for p in poly] + for k in range(len(ids)): + a, b = ids[k], ids[(k + 1) % len(ids)] + if (b, a) in eindex: + surfedges.append(-eindex[(b, a)]) + else: + if (a, b) not in eindex: + eindex[(a, b)] = len(edges) + edges.append((a, b)) + surfedges.append(eindex[(a, b)]) + return first, len(ids) + planes = [] + def plane(n, d): + planes.append((n, d)) + return len(planes) - 1 + def newell(poly): + nx = ny = nz = 0.0 + for k in range(len(poly)): + x1, y1, z1 = poly[k]; x2, y2, z2 = poly[(k + 1) % len(poly)] + nx += (y1 - y2) * (z1 + z2); ny += (z1 - z2) * (x1 + x2); nz += (x1 - x2) * (y1 + y2) + l = math.sqrt(nx * nx + ny * ny + nz * nz) + return (nx / l, ny / l, nz / l) + faces = [] + def face(poly, ti, disp=-1, flip_side=False): + # Source winding: clockwise seen from the front, so the front normal is minus Newell's + n = tuple(-c for c in newell(poly)) + d = sum(a * b for a, b in zip(n, poly[0])) + if flip_side: + pn, side = plane(tuple(-c for c in n), -d), 1 + else: + pn, side = plane(n, d), 0 + fe, ne = poly_edges(poly) + faces.append(dict(plane=pn, side=side, firstedge=fe, numedges=ne, texinfo=ti, disp=disp)) + return len(faces) - 1 + S, H = 256.0, 256.0 + # inward-facing room walls: clockwise seen from inside + face([(-S, -S, 0), (-S, -S, H), (S, -S, H), (S, -S, 0)], 0) # south wall, faces +y + face([(S, S, 0), (S, S, H), (-S, S, H), (-S, S, 0)], 0, flip_side=True) # north wall, faces -y (plane side 1) + face([(-S, S, 0), (-S, S, H), (-S, -S, H), (-S, -S, 0)], 1) # west, faces +x + face([(S, -S, 0), (S, -S, H), (S, S, H), (S, S, 0)], 1) # east, faces -x + # an octagonal ceiling facing down + oc = [] + for k in range(8): + a = -2 * math.pi * k / 8 + oc.append((round(S * math.cos(a), 3), round(S * math.sin(a), 3), H)) + face(list(reversed(oc)), 2) + face([(-S, -S, H + 8), (S, -S, H + 8), (S, S, H + 8), (-S, S, H + 8)], 3) # nodraw + # displacement floor facing up (clockwise seen from above), start position at its second corner + floor = [(-S, -S, 0), (-S, S, 0), (S, S, 0), (S, -S, 0)] + fdisp = face(floor, 4, disp=0) + world_faces = len(faces) + # func_brush: a 32-unit cube around its own origin, outward faces + c = 16.0 + cube = [ + [(-c, -c, c), (-c, c, c), (c, c, c), (c, -c, c)], + [(-c, -c, -c), (c, -c, -c), (c, c, -c), (-c, c, -c)], + [(-c, -c, -c), (-c, -c, c), (c, -c, c), (c, -c, -c)], + [(c, c, -c), (c, c, c), (-c, c, c), (-c, c, -c)], + [(-c, c, -c), (-c, c, c), (-c, -c, c), (-c, -c, -c)], + [(c, -c, -c), (c, -c, c), (c, c, c), (c, c, -c)], + ] + for p in cube: + face(p, 0) + models = [((-S, -S, 0), (S, S, H + 8), (0, 0, 0), 0, world_faces), ((-c, -c, -c), (c, c, c), (0, 0, 0), world_faces, len(faces) - world_faces)] + power = 3 + n = 2 ** power + 1 + dispverts = [] + for i in range(n): + for j in range(n): + dist = 24 * math.sin(i * 0.7) * math.cos(j * 0.5) + 8 + dispverts.append(((0.0, 0.0, 1.0) if dist >= 0 else (0.0, 0.0, -1.0), abs(dist), (i * 31 + j * 7) % 256)) + dispinfo = dict(start=floor[1], power=power, face=fdisp) + ents = ( + '{\n"world_maxs" "256 256 264"\n"world_mins" "-256 -256 0"\n"skyname" "sky_day01_01"\n"mapversion" "7"\n"classname" "worldspawn"\n}\n' + '{\n"origin" "0 0 64"\n"model" "*1"\n"targetname" "door"\n"classname" "func_brush"\n}\n' + '{\n"origin" "-128 0 32"\n"angles" "0 90 0"\n"classname" "info_player_start"\n}\n' + '{\n"origin" "0 0 200"\n"_light" "255 240 200 300"\n"classname" "light"\n}\n' + '{\n"targetname" "relay"\n"OnTrigger" "door,Enable,,0,-1"\n"OnTrigger" "door,Disable,,5,-1"\n"classname" "logic_relay"\n}\n' + ) + pak = io.BytesIO() + with zipfile.ZipFile(pak, "w", zipfile.ZIP_STORED) as z: + z.writestr("materials/maps/test/cubemapdefault.vtf", b"VTF\0" + bytes(60)) + z.writestr("materials/custom/note.txt", b"hello from the pak lump\n") + return dict(texdata=texdata, texinfo=texinfo, verts=verts, edges=edges, surfedges=surfedges, planes=planes, + faces=faces, models=models, dispverts=dispverts, dispinfo=dispinfo, ents=ents, pak=pak.getvalue()) + +def write(m, version=20): + lumps = {} + lumps[0] = m["ents"].encode() + b"\0" + lumps[1] = b"".join(struct.pack("<3ffi", *n, d, 0) for n, d in m["planes"]) + names = b"" + table = [] + for name, w, h in m["texdata"]: + table.append(len(names)) + names += name.encode() + b"\0" + lumps[43] = names + lumps[44] = b"".join(struct.pack("= 0 else b]) + start = min(range(4), key=lambda k: sum((corners[k][i] - di["start"][i]) ** 2 for i in range(3))) + p = corners[start:] + corners[:start] + n = 2 ** di["power"] + 1 + out = [] + lerp = lambda a, b, t: tuple(a[i] + (b[i] - a[i]) * t for i in range(3)) + for i in range(n): + e0 = lerp(p[0], p[1], i / (n - 1)) + e1 = lerp(p[3], p[2], i / (n - 1)) + for j in range(n): + base = lerp(e0, e1, j / (n - 1)) + vec, dist, alpha = m["dispverts"][i * n + j] + dist = struct.unpack("= 0: + pw = 2 ** m["dispinfo"]["power"] + g["tris"] += 2 * pw * pw + for base, pos in disp: + g["verts"].append("%.2f %.2f %.2f %.2f %.2f" % (*pos, *uv(base))) + else: + poly = [e.a for e in f.edges] + g["tris"] += len(poly) - 2 + for q in poly: + g["verts"].append("%.2f %.2f %.2f %.2f %.2f" % (q.x, q.y, q.z, *uv((q.x, q.y, q.z)))) + for g in groups.values(): + g["verts"] = "\n".join(sorted(g["verts"])) + props = [{"model": sp.model, "origin": list(sp.origin), "angles": [sp.angles.pitch, sp.angles.yaw, sp.angles.roll], + "skin": sp.skin, "scale": sp.scaling if isinstance(sp.scaling, float) else sp.scaling.x} for sp in bsp.props] + ents = [bsp.ents.spawn] + list(bsp.ents.entities) + outputs = sum(len(e.outputs) for e in ents) + pak = sorted(bsp.pakfile.namelist()) + return {"groups": sorted(groups.values(), key=lambda g: (g["model"], g["material"])), "props": props, + "entities": len(ents), "outputs": outputs, "classnames": sorted(e["classname"] for e in ents), "pak": pak, + "spversion": bsp.static_prop_version.version} + +m = build() +base = write(m) +cases = [] +V = B.StaticPropVersion +for name, kw in [ + ("v20", dict(sp=V.V6)), + ("v19", dict(version=19, sp=V.V4)), + ("v20_v5", dict(sp=V.V5)), + ("v20_lzma", dict(sp=V.V10, compress=True)), + ("tf2_v7", dict(sp=V.V7)), + ("l4d2", dict(version=B.VERSIONS.L4D2, sp=V.V9, l4d2=True)), + ("csgo", dict(version=21, sp=V.V11)), + ("csgo_lzma", dict(version=21, sp=V.V11, compress=True)), + ("l4d_v8", dict(version=20, sp=V.V8)), + ("srctools_ents", dict(sp=V.V5, rewrite_ents=True)), +]: + data = variant(base, name, **kw) + ref = reference(data, m) + ref.update({"name": name, "data": data.hex(), "version": struct.unpack_from("