ws-game: model/bsp (Quake 1 / Half-Life / Quake II brush maps, Quake III maps with patches and lightmaps, entities); core/Input.sibling (opts.files / opts.resolve lookup shared by mdl / bsp / md5 / vpk; additive)
This commit is contained in:
1 parent
9b2b50fe75
commit
4932fa7148
11 files changed
+1212
-47
No files matched your search
@@ -35,6 +35,7 @@ is tested under both runtimes (luau `--codegen -O2` and LuaJIT through the build
|
||||
| video | mpegts | .ts .m2ts .mts .tsv | yes | - | streaming: true, video: "mpeg1", "h264", audio: true | `tests/video/mpegts.luau` |
|
||||
| video | y4m | .y4m | yes | yes | streaming: true, video: "rawvideo", depths: 8, 10, 12, 16 | `tests/video/y4m.luau` |
|
||||
| model | 3mf | .3mf | yes | yes | materials: true, vertexColors: true, textures: true, units: true | `tests/model/3mf.luau` |
|
||||
| model | bsp | .bsp | yes | - | variants: "quake", "halflife", "quake2", "quake3", lightmaps: "quake3" | `tests/model/bsp.luau` |
|
||||
| model | dae | .dae .zae | yes | yes | materials: true, polygons: true, skins: true, morphTargets: true, animation: true, cameras: true, lights: true, zae: true | `tests/model/dae.luau` |
|
||||
| model | fbx | .fbx | yes | yes | binary: true, ascii: true, materials: true, animation: true, skins: true, morphTargets: true, cameras: true, lights: true, polygons: true | `tests/model/fbx.luau` |
|
||||
| model | gltf | .gltf .glb | yes | yes | binary: true, materials: true, animation: true, skins: true, morphTargets: true, cameras: true, lights: true | `tests/model/gltf.luau` |
|
||||
|
||||
@@ -374,6 +374,18 @@ local list: { Entry } = {
|
||||
return require("@formats/model/3mf")
|
||||
end,
|
||||
},
|
||||
{
|
||||
name = "bsp",
|
||||
category = "model",
|
||||
path = "model/bsp",
|
||||
extensions = { "bsp" },
|
||||
mime = { "model/x-bsp" },
|
||||
deps = { "core/Err", "core/Bytes", "core/Input", "Types", "codecs/image/Pixels" },
|
||||
caps = { decode = true, encode = false, variants = { "quake", "halflife", "quake2", "quake3" }, lightmaps = "quake3" },
|
||||
load = function()
|
||||
return require("@formats/model/bsp")
|
||||
end,
|
||||
},
|
||||
{
|
||||
name = "dae",
|
||||
category = "model",
|
||||
@@ -440,7 +452,7 @@ local list: { Entry } = {
|
||||
path = "model/md5",
|
||||
extensions = { "md5mesh", "md5anim" },
|
||||
mime = { "model/x-md5mesh", "model/x-md5anim" },
|
||||
deps = { "core/Err", "core/Bytes", "core/Sniff", "Types", "codecs/model/Rig" },
|
||||
deps = { "core/Err", "core/Bytes", "core/Input", "core/Sniff", "Types", "codecs/model/Rig" },
|
||||
caps = { decode = true, encode = false, skins = true, animation = true },
|
||||
load = function()
|
||||
return require("@formats/model/md5")
|
||||
@@ -452,7 +464,7 @@ local list: { Entry } = {
|
||||
path = "model/mdl",
|
||||
extensions = { "mdl" },
|
||||
mime = { "model/x-mdl" },
|
||||
deps = { "core/Err", "core/Bytes", "Types", "codecs/image/Pixels", "codecs/model/Mat4", "codecs/model/Rig" },
|
||||
deps = { "core/Err", "core/Bytes", "core/Input", "Types", "codecs/image/Pixels", "codecs/model/Mat4", "codecs/model/Rig" },
|
||||
caps = { decode = true, encode = false, variants = { "quake", "halflife" }, morph = true, skins = true, animation = true },
|
||||
load = function()
|
||||
return require("@formats/model/mdl")
|
||||
@@ -704,7 +716,7 @@ local list: { Entry } = {
|
||||
path = "archive/vpk",
|
||||
extensions = { "vpk" },
|
||||
mime = { "application/x-vpk" },
|
||||
deps = { "core/Err", "core/Bytes", "core/Crc32", "core/Md5", "containers/Archive" },
|
||||
deps = { "core/Err", "core/Bytes", "core/Input", "core/Crc32", "core/Md5", "containers/Archive" },
|
||||
caps = { decode = true, encode = true, versions = { 1, 2 }, multipart = true },
|
||||
load = function()
|
||||
return require("@formats/archive/vpk")
|
||||
|
||||
@@ -12,6 +12,7 @@
|
||||
-- ------------------------------------------------------------------------------------------------ requires
|
||||
local Err = require("@formats/core/Err")
|
||||
local Bytes = require("@formats/core/Bytes")
|
||||
local Input = require("@formats/core/Input")
|
||||
local Crc32 = require("@formats/core/Crc32")
|
||||
local Md5 = require("@formats/core/Md5")
|
||||
local Archive = require("@formats/containers/Archive")
|
||||
@@ -22,7 +23,7 @@ local Vpk = {
|
||||
category = "archive",
|
||||
extensions = { "vpk" },
|
||||
mime = { "application/x-vpk" },
|
||||
deps = { "core/Err", "core/Bytes", "core/Crc32", "core/Md5", "containers/Archive" },
|
||||
deps = { "core/Err", "core/Bytes", "core/Input", "core/Crc32", "core/Md5", "containers/Archive" },
|
||||
caps = { decode = true, encode = true, versions = { 1, 2 }, multipart = true },
|
||||
}
|
||||
|
||||
@@ -68,15 +69,7 @@ local function partLoader(opts: DecodeOptions?): (number) -> (buffer?, Err.Err?)
|
||||
return hit, nil
|
||||
end
|
||||
local name = string.format("%s_%03d.vpk", prefix, index)
|
||||
local data: any = nil
|
||||
if opts and type(opts.files) == "table" then
|
||||
data = opts.files[name]
|
||||
end
|
||||
if data == nil and opts and type(opts.resolve) == "function" then
|
||||
local ok, v = pcall(opts.resolve, name)
|
||||
data = if ok then v else nil
|
||||
end
|
||||
local b = Bytes.toBuffer(data)
|
||||
local b = Input.sibling(opts, name)
|
||||
if not b then
|
||||
return nil, Err.new(Err.UNSUPPORTED, "part file " .. name .. " not available (opts.resolve / opts.files)")
|
||||
end
|
||||
|
||||
@@ -59,4 +59,24 @@ function Input.extension(name: string?): string?
|
||||
return if ext then string.lower(ext) else nil
|
||||
end
|
||||
|
||||
-- sibling(opts, uri) -> buffer | nil: a file the data being decoded refers to (a palette, an animation, an archive
|
||||
-- part, ...): opts.files[uri] (a buffer or a string), else opts.resolve(uri) (errors in it count as not found)
|
||||
function Input.sibling(opts: any?, uri: string): buffer?
|
||||
if type(opts) ~= "table" then
|
||||
return nil
|
||||
end
|
||||
local v: any = nil
|
||||
if type(opts.files) == "table" then
|
||||
v = opts.files[uri]
|
||||
end
|
||||
if v == nil and type(opts.resolve) == "function" then
|
||||
local ok, got = pcall(opts.resolve, uri)
|
||||
v = if ok then got else nil
|
||||
end
|
||||
if type(v) == "string" then
|
||||
return buffer.fromstring(v)
|
||||
end
|
||||
return if type(v) == "buffer" then v else nil
|
||||
end
|
||||
|
||||
return Input
|
||||
@@ -0,0 +1,291 @@
|
||||
--!strict
|
||||
-- model/bsp/Brush: Quake 1 (BSP 29), Half-Life (BSP 30) and Quake II (IBSP 38) maps to a Scene: every face (a convex
|
||||
-- polygon of surface edges) fan-triangulated counter-clockwise about its plane's normal, one primitive per texture
|
||||
-- per model (model 0 = the world, the others = brush entities "*1", "*2", ... as child nodes), TEXCOORD_0 from the
|
||||
-- texture vectors (s = v . s.xyz + s.w, divided by the texture size), NORMAL = the plane normal. Textures: Quake /
|
||||
-- Half-Life embedded mip textures (mip 0) decoded through the palette (Half-Life: each texture's own; Quake: the
|
||||
-- caller's), textures kept in WAD files as URIs; Quake II textures are external .wal files (URIs; their size from
|
||||
-- opts.resolve("textures/<name>.wal") when available, else texture coordinates stay in texels: extras.bsp.texels).
|
||||
-- Written from the Quake specs (bspfile.h of the Quake / Quake II source releases); no code taken.
|
||||
-- Not supported: lightmaps (light offsets are kept per face in extras), visibility / BSP tree / clip hulls.
|
||||
local Types = require("@formats/Types")
|
||||
local Pixels = require("@formats/codecs/image/Pixels")
|
||||
|
||||
local Brush = {}
|
||||
|
||||
local Scene = Types.Scene
|
||||
local readi32, readu16, readf32, readu32 = buffer.readi32, buffer.readu16, buffer.readf32, buffer.readu32
|
||||
local writef32, writeu32 = buffer.writef32, buffer.writeu32
|
||||
|
||||
export type Lump = { at: number, size: number }
|
||||
export type Options = {
|
||||
palette: buffer?,
|
||||
wal: ((name: string) -> buffer?)?, -- Quake II: the .wal file of a texture (for its size)
|
||||
maxPixels: number?,
|
||||
maxVertices: number?,
|
||||
}
|
||||
|
||||
type Tex = { name: string, width: number, height: number, image: Types.Image?, texels: boolean }
|
||||
type Batch = { tex: number, pos: { number }, nrm: { number }, uv: { number } }
|
||||
|
||||
local function cstr(b: buffer, at: number, n: number): string
|
||||
return (string.match(buffer.readstring(b, at, n), "^[^%z]*")) :: string
|
||||
end
|
||||
|
||||
-- miptex lump (Quake / Half-Life) -> textures
|
||||
local function miptex(b: buffer, base: number, l: Lump, hl: boolean, pal: buffer?, maxPixels: number): ({ Tex }?, string?)
|
||||
local out: { Tex } = {}
|
||||
if l.size < 4 then
|
||||
return out, nil
|
||||
end
|
||||
local at = base + l.at
|
||||
local n = readi32(b, at)
|
||||
if n < 0 or n > 65536 or 4 + n * 4 > l.size then
|
||||
return nil, "bad miptex lump"
|
||||
end
|
||||
local gpal = if pal then Pixels.palette(pal, 0, 256) else nil
|
||||
for i = 0, n - 1 do
|
||||
local o = readi32(b, at + 4 + i * 4)
|
||||
if o < 0 or o + 40 > l.size then
|
||||
out[i + 1] = { name = "missing" .. i, width = 64, height = 64, image = nil, texels = false }
|
||||
else
|
||||
local m = at + o
|
||||
local name = cstr(b, m, 16)
|
||||
local w, h, off0 = readu32(b, m + 16), readu32(b, m + 20), readu32(b, m + 24)
|
||||
local t: Tex = { name = name, width = math.max(w, 1), height = math.max(h, 1), image = nil, texels = false }
|
||||
if off0 ~= 0 and w > 0 and h > 0 and w * h <= maxPixels then
|
||||
local px = m + off0
|
||||
local need = w * h
|
||||
local palAt = m + readu32(b, m + 36) + (w // 8) * (h // 8) + 2
|
||||
if o + off0 + need <= l.size then
|
||||
local p = gpal
|
||||
if hl then
|
||||
p = if palAt - at + 768 <= l.size then Pixels.palette(b, palAt, 256) else nil
|
||||
end
|
||||
local img = Types.Image.new(w, h)
|
||||
if p then
|
||||
Pixels.indexed(b, px, w, 8, img.pixels, w, h, true, p)
|
||||
else
|
||||
for k = 0, need - 1 do
|
||||
writeu32(img.pixels, k * 4, 0xFF000000 + buffer.readu8(b, px + k) * 0x10101)
|
||||
end
|
||||
end
|
||||
img.meta.source = { format = "bsp", miptex = name, palette = p ~= nil }
|
||||
t.image = img
|
||||
end
|
||||
end
|
||||
out[i + 1] = t
|
||||
end
|
||||
end
|
||||
return out, nil
|
||||
end
|
||||
|
||||
-- decode(b, base, size, lumps, variant, opts) -> Scene | nil, message
|
||||
-- variant "q1" (29), "hl" (30) or "q2" (38); lumps by name: vertices, edges, surfedges, faces, texinfo, planes,
|
||||
-- models, miptex (q1 / hl)
|
||||
function Brush.decode(b: buffer, base: number, lumps: { [string]: Lump }, variant: string, opts: Options?): (Types.Scene?, string?)
|
||||
local q2 = variant == "q2"
|
||||
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 tiSize = if q2 then 76 else 40
|
||||
local nTI, nP = TI.size // tiSize, P.size // 20
|
||||
local mSize = if q2 then 48 else 64
|
||||
local nM = M.size // mSize
|
||||
if nF > (opts and opts.maxVertices or 2 ^ 24) then
|
||||
return nil, "limit: too many faces"
|
||||
end
|
||||
-- textures
|
||||
local texs: { Tex } = {}
|
||||
local texOf: { number } = {} -- texinfo -> texture index (1-based)
|
||||
if q2 then
|
||||
local byName: { [string]: number } = {}
|
||||
for i = 0, nTI - 1 do
|
||||
local name = cstr(b, base + TI.at + i * 76 + 40, 32)
|
||||
local ti = byName[name]
|
||||
if not ti then
|
||||
local w, h, texels = 1, 1, true
|
||||
local wal = opts and opts.wal and opts.wal(name)
|
||||
if wal and buffer.len(wal) >= 40 then
|
||||
w, h, texels = math.max(1, readu32(wal, 32)), math.max(1, readu32(wal, 36)), false
|
||||
end
|
||||
table.insert(texs, { name = name, width = w, height = h, image = nil, texels = texels })
|
||||
ti = #texs
|
||||
byName[name] = ti
|
||||
end
|
||||
texOf[i + 1] = ti
|
||||
end
|
||||
else
|
||||
local list, err = miptex(b, base, lumps.miptex, variant == "hl", opts and opts.palette, maxPixels)
|
||||
if not list then
|
||||
return nil, err
|
||||
end
|
||||
texs = list
|
||||
for i = 0, nTI - 1 do
|
||||
local mt = readi32(b, base + TI.at + i * 40 + 32)
|
||||
texOf[i + 1] = if mt >= 0 and mt < #texs then mt + 1 else 0
|
||||
end
|
||||
end
|
||||
-- faces of each model
|
||||
local scene = Scene.new()
|
||||
scene.meta.up = "z"
|
||||
local faceModel: { number } = {}
|
||||
local models: { { first: number, count: number, origin: { number } } } = {}
|
||||
for m = 0, nM - 1 do
|
||||
local o = base + M.at + m * mSize
|
||||
local origin = { readf32(b, o + 24), readf32(b, o + 28), readf32(b, o + 32) }
|
||||
local fo = if q2 then 40 else 56
|
||||
local first, count = readi32(b, o + fo), readi32(b, o + fo + 4)
|
||||
table.insert(models, { first = first, count = count, origin = origin })
|
||||
if first >= 0 and count >= 0 and first + count <= nF then
|
||||
for f = first, first + count - 1 do
|
||||
faceModel[f + 1] = faceModel[f + 1] or (m + 1)
|
||||
end
|
||||
end
|
||||
end
|
||||
if #models == 0 then
|
||||
table.insert(models, { first = 0, count = nF, origin = { 0, 0, 0 } })
|
||||
for f = 1, nF do
|
||||
faceModel[f] = 1
|
||||
end
|
||||
end
|
||||
local batches: { [number]: { [number]: Batch } } = {}
|
||||
local orders: { [number]: { number } } = {}
|
||||
local skipped = 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 model = faceModel[f + 1]
|
||||
if not model or numEdges < 3 or firstEdge < 0 or firstEdge + numEdges > nSE or plane >= nP or texinfo >= nTI then
|
||||
skipped += 1
|
||||
continue
|
||||
end
|
||||
-- the polygon
|
||||
local poly: { number } = {}
|
||||
local ok = true
|
||||
for k = 0, numEdges - 1 do
|
||||
local se = readi32(b, base + SE.at + (firstEdge + k) * 4)
|
||||
local e = math.abs(se)
|
||||
if e >= nE then
|
||||
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)
|
||||
if v >= nV then
|
||||
ok = false
|
||||
break
|
||||
end
|
||||
local vo = base + V.at + v * 12
|
||||
table.insert(poly, readf32(b, vo))
|
||||
table.insert(poly, readf32(b, vo + 4))
|
||||
table.insert(poly, readf32(b, vo + 8))
|
||||
end
|
||||
if not ok then
|
||||
skipped += 1
|
||||
continue
|
||||
end
|
||||
local po = base + P.at + plane * 20
|
||||
local nx, ny, nz = readf32(b, po), readf32(b, po + 4), readf32(b, po + 8)
|
||||
if side ~= 0 then
|
||||
nx, ny, nz = -nx, -ny, -nz
|
||||
end
|
||||
-- orient counter-clockwise about the normal (Newell's normal of the polygon as stored)
|
||||
local n = #poly // 3
|
||||
local ax, ay, az = 0, 0, 0
|
||||
for k = 0, n - 1 do
|
||||
local j = (k + 1) % n
|
||||
local x1, y1, z1 = poly[k * 3 + 1], poly[k * 3 + 2], poly[k * 3 + 3]
|
||||
local x2, y2, z2 = poly[j * 3 + 1], poly[j * 3 + 2], poly[j * 3 + 3]
|
||||
ax += (y1 - y2) * (z1 + z2)
|
||||
ay += (z1 - z2) * (x1 + x2)
|
||||
az += (x1 - x2) * (y1 + y2)
|
||||
end
|
||||
local order: { number } = {}
|
||||
if ax * nx + ay * ny + az * nz >= 0 then
|
||||
for k = 0, n - 1 do
|
||||
order[k + 1] = k
|
||||
end
|
||||
else
|
||||
order[1] = 0
|
||||
for k = 1, n - 1 do
|
||||
order[k + 1] = n - k
|
||||
end
|
||||
end
|
||||
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 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
|
||||
local bm = batches[model] or {}
|
||||
batches[model] = bm
|
||||
local bt = bm[ti]
|
||||
if not bt then
|
||||
bt = { tex = ti, pos = {}, nrm = {}, uv = {} }
|
||||
bm[ti] = bt
|
||||
local ol = orders[model] or {}
|
||||
orders[model] = ol
|
||||
table.insert(ol, ti)
|
||||
end
|
||||
local batch: Batch = bt
|
||||
for k = 2, n - 1 do
|
||||
for _, c in { order[1], order[k], order[k + 1] } do
|
||||
local x, y, z = poly[c * 3 + 1], poly[c * 3 + 2], poly[c * 3 + 3]
|
||||
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
|
||||
end
|
||||
end
|
||||
end
|
||||
-- textures, materials
|
||||
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
|
||||
table.insert(scene.materials, mat)
|
||||
end
|
||||
-- meshes and nodes
|
||||
local root: Types.Node = { name = "bsp", children = {} }
|
||||
table.insert(scene.nodes, root)
|
||||
scene.roots[1] = 1
|
||||
for m, mdl in models do
|
||||
local list = orders[m]
|
||||
if list then
|
||||
local mesh: Types.Mesh = { name = if m == 1 then "world" else "*" .. (m - 1), primitives = {} }
|
||||
for _, ti in list do
|
||||
local bt = batches[m][ti]
|
||||
local nv = #bt.pos // 3
|
||||
local pb, nb, ub, ib = buffer.create(nv * 12), buffer.create(nv * 12), buffer.create(nv * 8), buffer.create(nv * 4)
|
||||
for k = 1, nv * 3 do
|
||||
writef32(pb, (k - 1) * 4, bt.pos[k])
|
||||
writef32(nb, (k - 1) * 4, bt.nrm[k])
|
||||
end
|
||||
for k = 1, nv * 2 do
|
||||
writef32(ub, (k - 1) * 4, bt.uv[k])
|
||||
end
|
||||
for k = 0, nv - 1 do
|
||||
writeu32(ib, k * 4, k)
|
||||
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) },
|
||||
indices = Scene.accessor(ib, "u32", 1, nv),
|
||||
mode = "triangles" :: any,
|
||||
material = if ti > 0 then ti else nil,
|
||||
})
|
||||
end
|
||||
table.insert(scene.meshes, mesh)
|
||||
table.insert(scene.nodes, { name = mesh.name, children = {}, mesh = #scene.meshes, extras = { bsp = { model = m - 1, origin = mdl.origin } } })
|
||||
table.insert(root.children, #scene.nodes)
|
||||
end
|
||||
end
|
||||
scene.meta.skippedFaces = skipped
|
||||
return scene, nil
|
||||
end
|
||||
|
||||
return Brush
|
||||
@@ -0,0 +1,261 @@
|
||||
--!strict
|
||||
-- model/bsp/Quake3: Quake III Arena maps (IBSP version 46; Return to Castle Wolfenstein 47 has the same layout) to a
|
||||
-- Scene: polygon and mesh faces (meshvert triangles, reversed to counter-clockwise), biquadratic patches
|
||||
-- tessellated (opts.patchLevel subdivisions per 3x3 control patch, default 4), one primitive per shader and lightmap
|
||||
-- per model (model 0 = the world, the others "*1", ...), POSITION / NORMAL / TEXCOORD_0 (surface) / TEXCOORD_1
|
||||
-- (lightmap) / COLOR_0 (vertex colours, unorm8); shaders as texture URIs; the 128 x 128 RGB lightmaps as
|
||||
-- texture.image (material.extras.bsp.lightmap = its texture index, texCoord 1). Billboards (flares) are skipped.
|
||||
-- Written from the Unofficial Quake 3 Map Specs (Kekoa Proudfoot); no code taken.
|
||||
local Types = require("@formats/Types")
|
||||
|
||||
local Quake3 = {}
|
||||
|
||||
local Scene = Types.Scene
|
||||
local readi32, readf32, readu8 = buffer.readi32, buffer.readf32, buffer.readu8
|
||||
local writef32, writeu32, writeu8 = buffer.writef32, buffer.writeu32, buffer.writeu8
|
||||
|
||||
export type Lump = { at: number, size: number }
|
||||
export type Options = { patchLevel: number?, maxVertices: number? }
|
||||
|
||||
type Batch = { shader: number, lightmap: number, verts: { number } } -- vertex records (indices into the vertex lump, or -1 - k for patch vertices)
|
||||
|
||||
local function cstr(b: buffer, at: number, n: number): string
|
||||
return (string.match(buffer.readstring(b, at, n), "^[^%z]*")) :: string
|
||||
end
|
||||
|
||||
-- decode(b, base, lumps, opts) -> Scene | nil, message
|
||||
function Quake3.decode(b: buffer, base: number, lumps: { [string]: Lump }, opts: Options?): (Types.Scene?, string?)
|
||||
local T, M, VX, MV, F, LM = lumps.textures, lumps.models, lumps.vertexes, lumps.meshverts, lumps.faces, lumps.lightmaps
|
||||
local nT, nM, nV, nMV, nF, nLM = T.size // 72, M.size // 40, VX.size // 44, MV.size // 4, F.size // 104, LM.size // 49152
|
||||
local level = math.clamp(math.floor(opts and opts.patchLevel or 4), 1, 16)
|
||||
local maxV = opts and opts.maxVertices or 2 ^ 24
|
||||
-- patch vertices: 12 floats + 4 colour bytes each, appended as negative ids
|
||||
local extra: { number } = {}
|
||||
local function vertex(i: number): { number }
|
||||
local o = base + VX.at + i * 44
|
||||
local v = table.create(14, 0)
|
||||
for k = 0, 9 do
|
||||
v[k + 1] = readf32(b, o + k * 4)
|
||||
end
|
||||
for k = 0, 3 do
|
||||
v[11 + k] = readu8(b, o + 40 + k)
|
||||
end
|
||||
return v
|
||||
end
|
||||
local function addExtra(v: { number }): number
|
||||
for k = 1, 14 do
|
||||
table.insert(extra, v[k])
|
||||
end
|
||||
return -(#extra // 14)
|
||||
end
|
||||
local faceModel: { number } = {}
|
||||
for m = 0, nM - 1 do
|
||||
local o = base + M.at + m * 40
|
||||
local first, count = readi32(b, o + 24), readi32(b, o + 28)
|
||||
if first >= 0 and count >= 0 and first + count <= nF then
|
||||
for f = first, first + count - 1 do
|
||||
faceModel[f + 1] = faceModel[f + 1] or (m + 1)
|
||||
end
|
||||
end
|
||||
end
|
||||
local batches: { [number]: { [string]: Batch } } = {}
|
||||
local orders: { [number]: { string } } = {}
|
||||
local counts = { polygons = 0, meshes = 0, patches = 0, billboards = 0, skipped = 0 }
|
||||
local total = 0
|
||||
for f = 0, nF - 1 do
|
||||
local o = base + F.at + f * 104
|
||||
local shader, kind, first, n, mv, nmv, lm = readi32(b, o), readi32(b, o + 8), readi32(b, o + 12), readi32(b, o + 16), readi32(b, o + 20), readi32(b, o + 24), readi32(b, o + 28)
|
||||
local model = faceModel[f + 1] or 1
|
||||
local tris: { number } = {}
|
||||
if (kind == 1 or kind == 3) and first >= 0 and n >= 0 and first + n <= nV and mv >= 0 and nmv >= 0 and mv + nmv <= nMV then
|
||||
for k = 0, nmv - 3, 3 do
|
||||
local ok = true
|
||||
local tri = {}
|
||||
for c = 0, 2 do
|
||||
local idx = readi32(b, base + MV.at + (mv + k + c) * 4)
|
||||
if idx < 0 or idx >= n then
|
||||
ok = false
|
||||
end
|
||||
tri[c + 1] = first + idx
|
||||
end
|
||||
if ok then
|
||||
table.insert(tris, tri[3])
|
||||
table.insert(tris, tri[2])
|
||||
table.insert(tris, tri[1])
|
||||
end
|
||||
end
|
||||
counts[if kind == 1 then "polygons" else "meshes"] += 1
|
||||
elseif kind == 2 and first >= 0 and n >= 0 and first + n <= nV then
|
||||
local w, h = readi32(b, o + 96), readi32(b, o + 100)
|
||||
if w >= 3 and h >= 3 and w % 2 == 1 and h % 2 == 1 and w * h == n then
|
||||
counts.patches += 1
|
||||
local L = level
|
||||
for py = 0, (h - 1) // 2 - 1 do
|
||||
for px = 0, (w - 1) // 2 - 1 do
|
||||
-- the 3x3 control points of this sub-patch
|
||||
local ctrl: { { number } } = {}
|
||||
for j = 0, 2 do
|
||||
for i = 0, 2 do
|
||||
ctrl[j * 3 + i + 1] = vertex(first + (py * 2 + j) * w + px * 2 + i)
|
||||
end
|
||||
end
|
||||
local grid: { number } = {}
|
||||
for gy = 0, L do
|
||||
local tv = gy / L
|
||||
for gx = 0, L do
|
||||
local tu = gx / L
|
||||
local bu = { (1 - tu) ^ 2, 2 * tu * (1 - tu), tu * tu }
|
||||
local bv = { (1 - tv) ^ 2, 2 * tv * (1 - tv), tv * tv }
|
||||
local v = table.create(14, 0)
|
||||
for j = 0, 2 do
|
||||
for i = 0, 2 do
|
||||
local wgt = bu[i + 1] * bv[j + 1]
|
||||
local cp = ctrl[j * 3 + i + 1]
|
||||
for k = 1, 14 do
|
||||
v[k] += cp[k] * wgt
|
||||
end
|
||||
end
|
||||
end
|
||||
local l = math.sqrt(v[8] ^ 2 + v[9] ^ 2 + v[10] ^ 2)
|
||||
if l > 0 then
|
||||
v[8], v[9], v[10] = v[8] / l, v[9] / l, v[10] / l
|
||||
end
|
||||
grid[gy * (L + 1) + gx + 1] = addExtra(v)
|
||||
end
|
||||
end
|
||||
for gy = 0, L - 1 do
|
||||
for gx = 0, L - 1 do
|
||||
local a, c2 = grid[gy * (L + 1) + gx + 1], grid[gy * (L + 1) + gx + 2]
|
||||
local d, e = grid[(gy + 1) * (L + 1) + gx + 1], grid[(gy + 1) * (L + 1) + gx + 2]
|
||||
-- counter-clockwise for Quake's clockwise-front control grids
|
||||
for _, v in { a, d, c2, c2, d, e } do
|
||||
table.insert(tris, v)
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
else
|
||||
counts.skipped += 1
|
||||
end
|
||||
elseif kind == 4 then
|
||||
counts.billboards += 1
|
||||
else
|
||||
counts.skipped += 1
|
||||
end
|
||||
total += #tris
|
||||
if total > maxV then
|
||||
return nil, "limit: too many vertices"
|
||||
end
|
||||
if #tris > 0 then
|
||||
local key = shader .. ":" .. lm
|
||||
local bm = batches[model] or {}
|
||||
batches[model] = bm
|
||||
local bt = bm[key]
|
||||
if not bt then
|
||||
bt = { shader = shader, lightmap = lm, verts = {} }
|
||||
bm[key] = bt
|
||||
local ol = orders[model] or {}
|
||||
orders[model] = ol
|
||||
table.insert(ol, key)
|
||||
end
|
||||
for _, v in tris do
|
||||
table.insert(bt.verts, v)
|
||||
end
|
||||
end
|
||||
end
|
||||
local scene = Scene.new()
|
||||
scene.meta.up = "z"
|
||||
-- shaders, lightmaps
|
||||
for i = 0, nT - 1 do
|
||||
local name = cstr(b, base + T.at + i * 72, 64)
|
||||
table.insert(scene.textures, { name = name, uri = name })
|
||||
end
|
||||
local lmTex: { [number]: number } = {}
|
||||
for i = 0, nLM - 1 do
|
||||
local img = Types.Image.new(128, 128)
|
||||
local o = base + LM.at + i * 49152
|
||||
for k = 0, 128 * 128 - 1 do
|
||||
writeu8(img.pixels, k * 4, readu8(b, o + k * 3))
|
||||
writeu8(img.pixels, k * 4 + 1, readu8(b, o + k * 3 + 1))
|
||||
writeu8(img.pixels, k * 4 + 2, readu8(b, o + k * 3 + 2))
|
||||
writeu8(img.pixels, k * 4 + 3, 255)
|
||||
end
|
||||
img.meta.source = { format = "bsp", lightmap = i }
|
||||
table.insert(scene.textures, { name = "lightmap " .. i, image = img })
|
||||
lmTex[i] = #scene.textures
|
||||
end
|
||||
local matOf: { [string]: number } = {}
|
||||
local root: Types.Node = { name = "bsp", children = {} }
|
||||
table.insert(scene.nodes, root)
|
||||
scene.roots[1] = 1
|
||||
local modelCount = math.max(nM, 1)
|
||||
for m = 1, modelCount do
|
||||
local list = orders[m]
|
||||
if list then
|
||||
local mesh: Types.Mesh = { name = if m == 1 then "world" else "*" .. (m - 1), primitives = {} }
|
||||
for _, key in list do
|
||||
local bt = batches[m][key]
|
||||
local nv = #bt.verts
|
||||
local pb, nb, ub, lb, cb, ib = buffer.create(nv * 12), buffer.create(nv * 12), buffer.create(nv * 8), buffer.create(nv * 8), buffer.create(nv * 4), buffer.create(nv * 4)
|
||||
for k, id in bt.verts do
|
||||
local v: { number }
|
||||
if id >= 0 then
|
||||
v = vertex(id)
|
||||
else
|
||||
local e = (-id - 1) * 14
|
||||
v = table.move(extra, e + 1, e + 14, 1, table.create(14, 0)) :: { number }
|
||||
end
|
||||
local o = (k - 1)
|
||||
writef32(pb, o * 12, v[1])
|
||||
writef32(pb, o * 12 + 4, v[2])
|
||||
writef32(pb, o * 12 + 8, v[3])
|
||||
writef32(ub, o * 8, v[4])
|
||||
writef32(ub, o * 8 + 4, v[5])
|
||||
writef32(lb, o * 8, v[6])
|
||||
writef32(lb, o * 8 + 4, v[7])
|
||||
writef32(nb, o * 12, v[8])
|
||||
writef32(nb, o * 12 + 4, v[9])
|
||||
writef32(nb, o * 12 + 8, v[10])
|
||||
for c = 0, 3 do
|
||||
writeu8(cb, o * 4 + c, math.clamp(math.floor(v[11 + c] + 0.5), 0, 255))
|
||||
end
|
||||
writeu32(ib, o * 4, o)
|
||||
end
|
||||
local mi = matOf[key]
|
||||
if not mi then
|
||||
local name = if bt.shader >= 0 and bt.shader < nT then scene.textures[bt.shader + 1].name else "noshader"
|
||||
local mat = Scene.material(name)
|
||||
mat.metallic = 0
|
||||
if bt.shader >= 0 and bt.shader < nT then
|
||||
mat.baseColorTexture = { texture = bt.shader + 1 }
|
||||
end
|
||||
local lt = lmTex[bt.lightmap]
|
||||
mat.extras = { bsp = { lightmap = lt, lightmapTexCoord = if lt then 1 else nil } }
|
||||
table.insert(scene.materials, mat)
|
||||
mi = #scene.materials
|
||||
matOf[key] = mi
|
||||
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),
|
||||
TEXCOORD_1 = Scene.accessor(lb, "f32", 2, nv),
|
||||
COLOR_0 = Scene.accessor(cb, "unorm8", 4, nv),
|
||||
},
|
||||
indices = Scene.accessor(ib, "u32", 1, nv),
|
||||
mode = "triangles" :: any,
|
||||
material = mi,
|
||||
})
|
||||
end
|
||||
table.insert(scene.meshes, mesh)
|
||||
table.insert(scene.nodes, { name = mesh.name, children = {}, mesh = #scene.meshes, extras = { bsp = { model = m - 1 } } })
|
||||
table.insert(root.children, #scene.nodes)
|
||||
end
|
||||
end
|
||||
scene.meta.faces = counts
|
||||
return scene, nil
|
||||
end
|
||||
|
||||
return Quake3
|
||||
@@ -0,0 +1,150 @@
|
||||
--!strict
|
||||
-- model/bsp: compiled game maps read into a Scene: Quake 1 (BSP 29) and Half-Life (BSP 30), Quake II (IBSP 38)
|
||||
-- through model/bsp/Brush, Quake III Arena / RTCW (IBSP 46 / 47) through model/bsp/Quake3. Each model of the map is a
|
||||
-- mesh (model 0 "world", brush entities "*1", "*2", ... as nodes), one primitive per texture (and Quake III
|
||||
-- lightmap). The entities lump is parsed into meta.entities = { { classname = ..., origin = ..., ... } } (strings as
|
||||
-- stored) with the text in meta.source.entities. Quake textures need the game's palette (gfx/palette.lmp, not
|
||||
-- redistributable: never built in): opts.palette, else opts.resolve / opts.files["gfx/palette.lmp"], else grey.
|
||||
-- Quake II .wal sizes come from opts.resolve("textures/<name>.wal") / opts.files. Units are map units, z up.
|
||||
-- Not supported: Source engine VBSP, Quake 1/2 lightmaps, visibility and collision data, writing.
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ requires
|
||||
local Err = require("@formats/core/Err")
|
||||
local Bytes = require("@formats/core/Bytes")
|
||||
local Input = require("@formats/core/Input")
|
||||
local Types = require("@formats/Types")
|
||||
local Brush = require("@formats/model/bsp/Brush")
|
||||
local Quake3 = require("@formats/model/bsp/Quake3")
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ contract
|
||||
local Bsp = {
|
||||
name = "bsp",
|
||||
category = "model",
|
||||
extensions = { "bsp" },
|
||||
mime = { "model/x-bsp" },
|
||||
deps = { "core/Err", "core/Bytes", "core/Input", "Types", "codecs/image/Pixels" },
|
||||
caps = { decode = true, encode = false, variants = { "quake", "halflife", "quake2", "quake3" }, lightmaps = "quake3" },
|
||||
}
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ types
|
||||
export type DecodeOptions = {
|
||||
palette: (buffer | string)?, -- Quake 1: the 768-byte palette
|
||||
resolve: ((uri: string) -> (buffer | string)?)?,
|
||||
files: { [string]: buffer | string }?,
|
||||
patchLevel: number?, -- Quake III patch subdivisions (default 4)
|
||||
maxPixels: number?, -- default 2^24
|
||||
maxVertices: number?, -- default 2^24
|
||||
}
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ constants
|
||||
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",
|
||||
"leaffaces", "leafbrushes", "edges", "surfedges", "models", "brushes", "brushsides", "pop", "areas", "areaportals" }
|
||||
local Q3_LUMPS = { "entities", "textures", "planes", "nodes", "leafs", "leaffaces", "leafbrushes", "models", "brushes",
|
||||
"brushsides", "vertexes", "meshverts", "effects", "faces", "lightmaps", "lightvols", "visdata" }
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ sniff
|
||||
function Bsp.sniff(r: Bytes.Reader): number
|
||||
if r:remaining() < 64 then
|
||||
return 0
|
||||
end
|
||||
local m = r:peek(4)
|
||||
local v = buffer.readi32(r.buf, r.pos + (if m == "IBSP" then 4 else 0))
|
||||
if m == "IBSP" then
|
||||
return if v == 38 or v == 46 or v == 47 then 1 else 0.3
|
||||
end
|
||||
if v == 29 or v == 30 then
|
||||
-- no magic: check that the lump directory fits the file
|
||||
local size = r:remaining()
|
||||
for i = 0, 14 do
|
||||
local o, n = buffer.readi32(r.buf, r.pos + 4 + i * 8), buffer.readi32(r.buf, r.pos + 8 + i * 8)
|
||||
if o < 0 or n < 0 or o + n > size then
|
||||
return 0
|
||||
end
|
||||
end
|
||||
return 0.6
|
||||
end
|
||||
return 0
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ decode
|
||||
-- the entities text -> { { key = value } }
|
||||
local function entities(text: string): { { [string]: string } }
|
||||
local out: { { [string]: string } } = {}
|
||||
for block in string.gmatch(text, "%b{}") do
|
||||
local e: { [string]: string } = {}
|
||||
for k, v in string.gmatch(block, '"([^"]*)"%s*"([^"]*)"') do
|
||||
e[k] = v
|
||||
end
|
||||
table.insert(out, e)
|
||||
end
|
||||
return out
|
||||
end
|
||||
|
||||
function Bsp.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Scene?, Err.Err?)
|
||||
local size = r.limit - r.base
|
||||
if size < 8 then
|
||||
return nil, Err.new(Err.TRUNCATED, "header", 0)
|
||||
end
|
||||
local b, base = r.buf, r.base
|
||||
local m = r:peek(4)
|
||||
local version = buffer.readi32(b, base + (if m == "IBSP" then 4 else 0))
|
||||
local names: { string }, dir: number, variant: string
|
||||
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 ~= "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
|
||||
return nil, Err.new(Err.UNSUPPORTED, "Source engine VBSP maps", 0)
|
||||
else
|
||||
return nil, Err.new(Err.UNSUPPORTED, "BSP version " .. version, 0)
|
||||
end
|
||||
if dir + #names * 8 > size then
|
||||
return nil, Err.new(Err.TRUNCATED, "lump directory", dir)
|
||||
end
|
||||
local lumps: { [string]: { at: number, size: number } } = {}
|
||||
for i, name in names do
|
||||
local o, n = buffer.readi32(b, base + dir + (i - 1) * 8), buffer.readi32(b, base + dir + (i - 1) * 8 + 4)
|
||||
if o < 0 or n < 0 or o + n > size then
|
||||
return nil, Err.new(Err.TRUNCATED, "lump " .. name .. " past the end", dir + (i - 1) * 8)
|
||||
end
|
||||
lumps[name] = { at = o, size = n }
|
||||
end
|
||||
local scene: Types.Scene?, msg: string?
|
||||
if variant == "q3" then
|
||||
scene, msg = Quake3.decode(b, base, lumps, opts :: any)
|
||||
else
|
||||
local pal = if opts and opts.palette then Bytes.toBuffer(opts.palette) else Input.sibling(opts, "gfx/palette.lmp")
|
||||
if pal and buffer.len(pal) < 768 then
|
||||
pal = nil
|
||||
end
|
||||
scene, msg = Brush.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,
|
||||
})
|
||||
end
|
||||
if not scene then
|
||||
return nil, Err.from(msg)
|
||||
end
|
||||
local e = lumps.entities
|
||||
local text = buffer.readstring(b, base + e.at, e.size)
|
||||
text = string.match(text, "^[^%z]*") :: string
|
||||
scene.meta.entities = entities(text)
|
||||
scene.meta.source = {
|
||||
format = "bsp",
|
||||
variant = ({ q1 = "quake", hl = "halflife", q2 = "quake2", q3 = "quake3" } :: { [string]: string })[variant],
|
||||
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,
|
||||
}
|
||||
return scene, nil
|
||||
end
|
||||
|
||||
return Bsp
|
||||
@@ -9,6 +9,7 @@
|
||||
-- ------------------------------------------------------------------------------------------------ requires
|
||||
local Err = require("@formats/core/Err")
|
||||
local Bytes = require("@formats/core/Bytes")
|
||||
local Input = require("@formats/core/Input")
|
||||
local Sniff = require("@formats/core/Sniff")
|
||||
local Types = require("@formats/Types")
|
||||
local Read = require("@formats/model/md5/Read")
|
||||
@@ -19,7 +20,7 @@ local Md5 = {
|
||||
category = "model",
|
||||
extensions = { "md5mesh", "md5anim" },
|
||||
mime = { "model/x-md5mesh", "model/x-md5anim" },
|
||||
deps = { "core/Err", "core/Bytes", "core/Sniff", "Types", "codecs/model/Rig" },
|
||||
deps = { "core/Err", "core/Bytes", "core/Input", "core/Sniff", "Types", "codecs/model/Rig" },
|
||||
caps = { decode = true, encode = false, skins = true, animation = true },
|
||||
}
|
||||
|
||||
@@ -41,21 +42,6 @@ function Md5.sniff(r: Bytes.Reader): number
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ decode
|
||||
local function fetch(opts: DecodeOptions, uri: string): string?
|
||||
local v: any = nil
|
||||
if type(opts.files) == "table" then
|
||||
v = opts.files[uri]
|
||||
end
|
||||
if v == nil and type(opts.resolve) == "function" then
|
||||
local ok, got = pcall(opts.resolve, uri)
|
||||
v = if ok then got else nil
|
||||
end
|
||||
if type(v) == "buffer" then
|
||||
return buffer.tostring(v)
|
||||
end
|
||||
return if type(v) == "string" then v else nil
|
||||
end
|
||||
|
||||
local function stem(name: string): string
|
||||
local base = string.match(name, "([^/\\]+)$") or name
|
||||
return (string.gsub(base, "%.[^.]*$", ""))
|
||||
@@ -76,7 +62,8 @@ function Md5.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Scene?, Err.E
|
||||
end
|
||||
if opts and type(opts.anims) == "table" then
|
||||
for _, name in opts.anims do
|
||||
local src = if type(name) == "string" then fetch(opts, name) else nil
|
||||
local got = if type(name) == "string" then Input.sibling(opts, name) else nil
|
||||
local src = if got then buffer.tostring(got) else nil
|
||||
if not src then
|
||||
if not opts.skipMissing then
|
||||
return nil, Err.new(Err.UNSUPPORTED, "animation " .. tostring(name) .. " not available (opts.resolve / opts.files)")
|
||||
|
||||
@@ -9,6 +9,7 @@
|
||||
-- ------------------------------------------------------------------------------------------------ requires
|
||||
local Err = require("@formats/core/Err")
|
||||
local Bytes = require("@formats/core/Bytes")
|
||||
local Input = require("@formats/core/Input")
|
||||
local Types = require("@formats/Types")
|
||||
local Quake = require("@formats/model/mdl/Quake")
|
||||
local HalfLife = require("@formats/model/mdl/HalfLife")
|
||||
@@ -19,7 +20,7 @@ local Mdl = {
|
||||
category = "model",
|
||||
extensions = { "mdl" },
|
||||
mime = { "model/x-mdl" },
|
||||
deps = { "core/Err", "core/Bytes", "Types", "codecs/image/Pixels", "codecs/model/Mat4", "codecs/model/Rig" },
|
||||
deps = { "core/Err", "core/Bytes", "core/Input", "Types", "codecs/image/Pixels", "codecs/model/Mat4", "codecs/model/Rig" },
|
||||
caps = { decode = true, encode = false, variants = { "quake", "halflife" }, morph = true, skins = true, animation = true },
|
||||
}
|
||||
|
||||
@@ -48,21 +49,6 @@ function Mdl.sniff(r: Bytes.Reader): number
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ decode
|
||||
local function fetch(opts: DecodeOptions?, uri: string): buffer?
|
||||
if not opts then
|
||||
return nil
|
||||
end
|
||||
local v: any = nil
|
||||
if type(opts.files) == "table" then
|
||||
v = opts.files[uri]
|
||||
end
|
||||
if v == nil and type(opts.resolve) == "function" then
|
||||
local ok, got = pcall(opts.resolve, uri)
|
||||
v = if ok then got else nil
|
||||
end
|
||||
return Bytes.toBuffer(v)
|
||||
end
|
||||
|
||||
function Mdl.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Scene?, Err.Err?)
|
||||
local size = r.limit - r.base
|
||||
if size < 8 then
|
||||
@@ -74,7 +60,7 @@ function Mdl.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Scene?, Err.E
|
||||
if version ~= 6 then
|
||||
return nil, Err.new(Err.UNSUPPORTED, "Quake MDL version " .. version, 4)
|
||||
end
|
||||
local pal = if opts and opts.palette then Bytes.toBuffer(opts.palette) else fetch(opts, "gfx/palette.lmp")
|
||||
local pal = if opts and opts.palette then Bytes.toBuffer(opts.palette) else Input.sibling(opts, "gfx/palette.lmp")
|
||||
if pal and buffer.len(pal) < 768 then
|
||||
pal = nil
|
||||
end
|
||||
|
||||
@@ -0,0 +1,226 @@
|
||||
-- model/bsp tests: Quake 1, Half-Life, Quake II and Quake III maps written by tools/fixtures/bsp.py: every model's
|
||||
-- triangles per texture (positions, normals, texture coordinates against the documented rules), counter-clockwise
|
||||
-- about the face normals, embedded textures (Quake through the palette, Half-Life through its own), WAD / .wal
|
||||
-- textures as URIs, entities; Quake III: polygon / mesh faces against assimp's soup (of a .pk3) and the writer,
|
||||
-- lightmaps, vertex colours, a tessellated patch; errors; the fuzz pass.
|
||||
local T = require("@tests/T")
|
||||
local F = require("@formats")
|
||||
local Bsp = require("@formats/model/bsp")
|
||||
local Bytes = require("@formats/core/Bytes")
|
||||
local Crc32 = require("@formats/core/Crc32")
|
||||
local Err = require("@formats/core/Err")
|
||||
local Types = require("@formats/Types")
|
||||
local Soup = require("@tests/model/_soup")
|
||||
local Fx = require("@tests/gen/bsp")
|
||||
|
||||
local t = T.suite("bsp")
|
||||
t:eq(Bsp.name, "bsp", "name")
|
||||
|
||||
local function near(a: { number }, b: { number }, tol: number): boolean
|
||||
if #a ~= #b then
|
||||
return false
|
||||
end
|
||||
for i = 1, #b do
|
||||
if math.abs(a[i] - b[i]) > tol * math.max(1, math.abs(b[i])) then
|
||||
return false
|
||||
end
|
||||
end
|
||||
return true
|
||||
end
|
||||
|
||||
local function meshOf(s: any, model: number): any
|
||||
for _, n in s.nodes do
|
||||
if n.mesh and n.extras and n.extras.bsp and n.extras.bsp.model == model then
|
||||
return s.meshes[n.mesh]
|
||||
end
|
||||
end
|
||||
return nil
|
||||
end
|
||||
|
||||
-- winding: every triangle's geometric normal agrees with its NORMAL
|
||||
local function windingOk(p: any): boolean
|
||||
local pos = Types.Scene.reader(p.attributes.POSITION) :: any
|
||||
local nrm = Types.Scene.reader(p.attributes.NORMAL) :: any
|
||||
local idx = p.indices
|
||||
for k = 0, idx.count - 1, 3 do
|
||||
local a, b, c = buffer.readu32(idx.data, k * 4), buffer.readu32(idx.data, k * 4 + 4), buffer.readu32(idx.data, k * 4 + 8)
|
||||
local ux, uy, uz = pos(b, 0) - pos(a, 0), pos(b, 1) - pos(a, 1), pos(b, 2) - pos(a, 2)
|
||||
local vx, vy, vz = pos(c, 0) - pos(a, 0), pos(c, 1) - pos(a, 1), pos(c, 2) - pos(a, 2)
|
||||
local cx, cy, cz = uy * vz - uz * vy, uz * vx - ux * vz, ux * vy - uy * vx
|
||||
if cx * nrm(a, 0) + cy * nrm(a, 1) + cz * nrm(a, 2) <= 0 then
|
||||
return false
|
||||
end
|
||||
end
|
||||
return true
|
||||
end
|
||||
|
||||
local function brush(label: string, c: any, opts: any)
|
||||
local s, err = Bsp.decode(Bytes.reader(buffer.fromstring(c.data)), opts)
|
||||
t:check(s, label .. ": " .. tostring(err))
|
||||
t:eq(F.detect(c.data), "bsp", label .. ": F.detect")
|
||||
for model, texs in c.models do
|
||||
local mesh = meshOf(s, tonumber(model) :: number)
|
||||
t:check(mesh, label .. ": model " .. model)
|
||||
for tname, want in texs do
|
||||
local prim
|
||||
for _, p in mesh.primitives do
|
||||
if p.material and s.materials[p.material].name == tname then
|
||||
prim = p
|
||||
end
|
||||
end
|
||||
t:check(prim, label .. ": model " .. model .. " texture " .. tname)
|
||||
t:check(near(Soup.list(Soup.positions(prim)), want.pos, 1e-6), label .. ": " .. tname .. " positions")
|
||||
t:check(near(Soup.uvs(prim, 0), want.uv, 1e-5), label .. ": " .. tname .. " texture coordinates")
|
||||
t:check(near(Soup.list(prim.attributes.NORMAL.data), want.nrm, 1e-6), label .. ": " .. tname .. " normals")
|
||||
t:check(windingOk(prim), label .. ": " .. tname .. " counter-clockwise")
|
||||
end
|
||||
end
|
||||
t:eq(#s.meta.entities, 3, label .. ": entities")
|
||||
t:eq(s.meta.entities[2].classname, "info_player_start", label .. ": entity classname")
|
||||
t:eq(s.meta.entities[3].model, "*1", label .. ": brush entity model")
|
||||
return s
|
||||
end
|
||||
|
||||
-- 1. Quake 1, Half-Life
|
||||
do
|
||||
local q1 = brush("q1", Fx.q1, { palette = Fx.q1.palette })
|
||||
t:eq(Crc32.of(q1.textures[1].image.pixels), Fx.q1.textures[1], "q1: embedded texture through the palette")
|
||||
t:eq(q1.textures[2].uri, "+0door", "q1: WAD texture as a URI")
|
||||
t:eq(q1.meta.source.variant, "quake", "q1: variant")
|
||||
local hl = brush("hl", Fx.hl, nil)
|
||||
t:eq(Crc32.of(hl.textures[1].image.pixels), Fx.hl.textures[1], "hl: embedded texture through its own palette")
|
||||
t:eq(hl.meta.source.variant, "halflife", "hl: variant")
|
||||
local grey = Bsp.decode(Bytes.reader(buffer.fromstring(Fx.q1.data))) :: any
|
||||
t:eq(grey.meta.source.palette, false, "q1 without a palette: grey")
|
||||
end
|
||||
|
||||
-- 2. Quake II
|
||||
do
|
||||
local q2 = brush("q2", Fx.q2, { files = { ["textures/brick.wal"] = Fx.q2.wal } })
|
||||
t:eq(q2.textures[1].uri, "textures/brick.wal", "q2: .wal URI")
|
||||
t:eq(q2.materials[1].extras.bsp.width, 16, "q2: size from the .wal")
|
||||
t:eq(q2.materials[2].extras.bsp.texels, true, "q2: texel coordinates without the .wal")
|
||||
end
|
||||
|
||||
-- 3. Quake III
|
||||
do
|
||||
local q = Fx.q3
|
||||
local s, err = Bsp.decode(Bytes.reader(buffer.fromstring(q.data)))
|
||||
t:check(s, "q3: " .. tostring(err))
|
||||
t:eq(F.detect(q.data), "bsp", "q3: F.detect")
|
||||
for model, keys in q.models do
|
||||
local mesh = meshOf(s, tonumber(model) :: number)
|
||||
for key, want in keys do
|
||||
local sh, lm = string.match(key, "^(%-?%d+):(%-?%d+)$")
|
||||
local prim
|
||||
for _, p in mesh.primitives do
|
||||
local mat = s.materials[p.material]
|
||||
local lt = mat.extras.bsp.lightmap
|
||||
local tex = mat.baseColorTexture and mat.baseColorTexture.texture
|
||||
if tex == tonumber(sh) :: number + 1 and ((lt and s.textures[lt].image.meta.source.lightmap) or -1) == tonumber(lm) then
|
||||
prim = p
|
||||
end
|
||||
end
|
||||
t:check(prim, "q3: model " .. model .. " batch " .. key)
|
||||
t:check(near(Soup.list(Soup.positions(prim)), want.pos, 1e-6), "q3: " .. key .. " positions")
|
||||
t:check(near(Soup.uvs(prim, 0), want.uv, 1e-6), "q3: " .. key .. " texture coordinates")
|
||||
t:check(near(Soup.uvs(prim, 1), want.lm, 1e-6), "q3: " .. key .. " lightmap coordinates")
|
||||
local col = {}
|
||||
local cr = Types.Scene.reader(prim.attributes.COLOR_0) :: any
|
||||
for k = 0, prim.indices.count - 1 do
|
||||
local v = buffer.readu32(prim.indices.data, k * 4)
|
||||
for c = 0, 3 do
|
||||
table.insert(col, math.floor(cr(v, c) * 255 + 0.5))
|
||||
end
|
||||
end
|
||||
t:check(near(col, want.col, 0), "q3: " .. key .. " vertex colours")
|
||||
t:check(windingOk(prim), "q3: " .. key .. " counter-clockwise about the normals")
|
||||
end
|
||||
end
|
||||
-- assimp: the polygon / mesh faces
|
||||
local all = {}
|
||||
local apos = q.assimp.pos
|
||||
for _, mesh in s.meshes do
|
||||
for _, p in mesh.primitives do
|
||||
local mat = s.materials[p.material]
|
||||
if mat.name ~= "textures/base/floor" or p.indices.count == 6 then
|
||||
if p.indices.count == 6 then
|
||||
for _, x in Soup.list(Soup.positions(p)) do
|
||||
table.insert(all, x)
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
t:eq(q.assimp.faces, 6, "q3: assimp reads the 3 quads")
|
||||
-- compare triangle sets: every assimp triangle is one of ours (up to corner rotation); assimp keeps the stored
|
||||
-- clockwise order, we reverse it
|
||||
local found = 0
|
||||
for k = 0, #apos // 9 - 1 do
|
||||
local tri = Soup.slice(apos, k * 9 + 1, 9)
|
||||
tri = { tri[7], tri[8], tri[9], tri[4], tri[5], tri[6], tri[1], tri[2], tri[3] }
|
||||
for j = 0, #all // 9 - 1 do
|
||||
if Soup.triangles(Soup.slice(all, j * 9 + 1, 9), tri, 1e-5) then
|
||||
found += 1
|
||||
break
|
||||
end
|
||||
end
|
||||
end
|
||||
t:eq(found, 6, "q3: every assimp triangle matches one of ours")
|
||||
t:eq(#q.lightmaps, 2, "q3: lightmaps")
|
||||
for i, crc in q.lightmaps do
|
||||
local tex
|
||||
for _, tx in s.textures do
|
||||
if tx.image and tx.image.meta.source.lightmap == i - 1 then
|
||||
tex = tx
|
||||
end
|
||||
end
|
||||
t:eq(Crc32.of(tex.image.pixels), crc, "q3: lightmap " .. i)
|
||||
end
|
||||
-- the patch: a flat 32 x 32 square at z = 100, tessellated
|
||||
local area = 0
|
||||
for _, mesh in s.meshes do
|
||||
for _, p in mesh.primitives do
|
||||
local pos = Types.Scene.reader(p.attributes.POSITION) :: any
|
||||
if pos(0, 2) == 100 then
|
||||
t:check(windingOk(p), "q3: patch counter-clockwise")
|
||||
for k = 0, p.indices.count - 1, 3 do
|
||||
local ux, uy = pos(k + 1, 0) - pos(k, 0), pos(k + 1, 1) - pos(k, 1)
|
||||
local vx, vy = pos(k + 2, 0) - pos(k, 0), pos(k + 2, 1) - pos(k, 1)
|
||||
area += (ux * vy - uy * vx) / 2
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
t:check(math.abs(math.abs(area) - q.patchArea) < 1e-3, "q3: patch area " .. area)
|
||||
t:eq(s.meta.faces.patches, 1, "q3: one patch")
|
||||
local lean = Bsp.decode(Bytes.reader(buffer.fromstring(q.data)), { patchLevel = 1 }) :: any
|
||||
t:check(lean ~= nil, "q3: patchLevel 1")
|
||||
end
|
||||
|
||||
-- 4. errors, fuzz
|
||||
do
|
||||
local _, e1 = Bsp.decode(Bytes.reader(buffer.fromstring(string.sub(Fx.q1.data, 1, 100))))
|
||||
t:check(e1 and e1.code == Err.TRUNCATED, "truncated: " .. tostring(e1))
|
||||
local _, e2 = Bsp.decode(Bytes.reader(buffer.fromstring("VBSP" .. string.rep("\0", 100))))
|
||||
t:check(e2 and e2.code == Err.UNSUPPORTED, "VBSP")
|
||||
end
|
||||
t:fuzz("decode", function(b: buffer)
|
||||
return Bsp.decode(Bytes.reader(b), { palette = Fx.q1.palette })
|
||||
end, { Fx.q1.data, Fx.hl.data, Fx.q2.data }, { mutations = 80 })
|
||||
do
|
||||
local rand = T.rng(13)
|
||||
local threw = 0
|
||||
local q = Fx.q3.data
|
||||
for _ = 1, 60 do
|
||||
local b = buffer.fromstring(q)
|
||||
for _ = 1, 1 + rand(10) do
|
||||
buffer.writeu8(b, 8 + 17 * 8 + rand(#q - 8 - 17 * 8 - 98304), rand(256))
|
||||
end
|
||||
if not pcall(Bsp.decode, Bytes.reader(b)) then
|
||||
threw += 1
|
||||
end
|
||||
end
|
||||
t:eq(threw, 0, "q3: mutated lumps never throw")
|
||||
end
|
||||
t:done()
|
||||
@@ -0,0 +1,238 @@
|
||||
# BSP fixtures (tools/fixtures.py): maps written here from the bspfile.h layouts of the Quake / Quake II source
|
||||
# releases and the Unofficial Quake 3 Map Specs: two boxes (the world and a brush entity "*1"), faces stored
|
||||
# clockwise as the games do (some with side = 1 on a flipped plane), texture vectors, entities.
|
||||
# q1 / hl: miptex lump with one embedded texture (Half-Life: with its palette) and one kept in a WAD (offsets 0);
|
||||
# q2: texture names (.wal sizes through opts.files);
|
||||
# q3: polygon, mesh and patch faces, two lightmaps, vertex colours; plus a .pk3 (zip) of it for assimp.
|
||||
# References: the expected triangles per model and texture (positions, normals, texture coordinates, computed here
|
||||
# with the documented rules), texture CRCs, entities; assimp's soup of the Quake III map.
|
||||
# tests/gen/bsp.luau { q1 = { data, palette, models = { [model] = { [texture] = { pos, uv, nrm } } }, textures,
|
||||
# entities }, hl = ..., q2 = { ..., wal }, q3 = { ..., lightmaps, patchArea, assimp } }
|
||||
import importlib.util, io, math, os, struct, zipfile, zlib
|
||||
|
||||
INPUTS = ["tools/fixtures/_quake_ref.py"]
|
||||
|
||||
|
||||
def ref(ctx):
|
||||
spec = importlib.util.spec_from_file_location("_quake_ref", os.path.join(ctx.root, "tools", "fixtures", "_quake_ref.py"))
|
||||
m = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(m)
|
||||
return m
|
||||
|
||||
|
||||
def f32(x):
|
||||
return struct.unpack("<f", struct.pack("<f", x))[0]
|
||||
|
||||
|
||||
ENTS = b'{\n"classname" "worldspawn"\n"message" "fixture map"\n}\n{\n"classname" "info_player_start"\n"origin" "16 16 24"\n}\n{\n"classname" "func_door"\n"model" "*1"\n}\n\0'
|
||||
|
||||
|
||||
def box(lo, hi):
|
||||
# 6 quads, each clockwise seen from outside (the games' winding), with the outward normal
|
||||
(x0, y0, z0), (x1, y1, z1) = lo, hi
|
||||
return [
|
||||
([(x0, y0, z1), (x0, y1, z1), (x1, y1, z1), (x1, y0, z1)], (0, 0, 1)),
|
||||
([(x0, y0, z0), (x1, y0, z0), (x1, y1, z0), (x0, y1, z0)], (0, 0, -1)),
|
||||
([(x1, y0, z0), (x1, y0, z1), (x1, y1, z1), (x1, y1, z0)], (1, 0, 0)),
|
||||
([(x0, y0, z0), (x0, y1, z0), (x0, y1, z1), (x0, y0, z1)], (-1, 0, 0)),
|
||||
([(x0, y1, z0), (x1, y1, z0), (x1, y1, z1), (x0, y1, z1)], (0, 1, 0)),
|
||||
([(x0, y0, z0), (x0, y0, z1), (x1, y0, z1), (x1, y0, z0)], (0, -1, 0)),
|
||||
]
|
||||
|
||||
|
||||
def ccw_fan(poly, n):
|
||||
# the decoder's rule: counter-clockwise about the face normal (Newell), fan from the first vertex
|
||||
ax = ay = az = 0.0
|
||||
k = len(poly)
|
||||
for i in range(k):
|
||||
(x1, y1, z1), (x2, y2, z2) = poly[i], poly[(i + 1) % k]
|
||||
ax += (y1 - y2) * (z1 + z2)
|
||||
ay += (z1 - z2) * (x1 + x2)
|
||||
az += (x1 - x2) * (y1 + y2)
|
||||
order = list(range(k)) if ax * n[0] + ay * n[1] + az * n[2] >= 0 else [0] + [k - i for i in range(1, k)]
|
||||
out = []
|
||||
for i in range(1, k - 1):
|
||||
out += [order[0], order[i], order[i + 1]]
|
||||
return out
|
||||
|
||||
|
||||
def brush_map(rng, variant, pal):
|
||||
q2 = variant == "q2"
|
||||
faces = [(f, 0) for f in box((-64, -64, 0), (64, 64, 128))] + [(f, 1) for f in box((-8, -8, 8), (8, 8, 40))]
|
||||
verts, edges, surfedges, planes, texinfo, flist = [], [(0, 0)], [], [], [], []
|
||||
vindex = {}
|
||||
|
||||
def vid(p):
|
||||
p = tuple(f32(c) for c in p)
|
||||
if p not in vindex:
|
||||
vindex[p] = len(verts)
|
||||
verts.append(p)
|
||||
return vindex[p]
|
||||
texnames = ["brick", "door"] if q2 else ["brick", "+0door"]
|
||||
sizes = [(16, 8), (8, 8)]
|
||||
tis = []
|
||||
for t in range(2):
|
||||
s = [f32(rng.uniform(-1, 1)) for _ in range(3)] + [f32(rng.uniform(-8, 8))]
|
||||
tt = [f32(rng.uniform(-1, 1)) for _ in range(3)] + [f32(rng.uniform(-8, 8))]
|
||||
tis.append((s, tt))
|
||||
texinfo.append((s, tt, t))
|
||||
models = {}
|
||||
for i, ((poly, n), model) in enumerate(faces):
|
||||
tex = model
|
||||
side = i % 3 == 2
|
||||
pn = tuple(-c for c in n) if side else n
|
||||
planes.append((pn, 0.0))
|
||||
first = len(surfedges)
|
||||
ids = [vid(p) for p in poly]
|
||||
for k in range(len(ids)):
|
||||
a, b = ids[k], ids[(k + 1) % len(ids)]
|
||||
if k % 2 == 0:
|
||||
edges.append((a, b))
|
||||
surfedges.append(len(edges) - 1)
|
||||
else:
|
||||
edges.append((b, a))
|
||||
surfedges.append(-(len(edges) - 1))
|
||||
flist.append((len(planes) - 1, 1 if side else 0, first, len(ids), tex))
|
||||
# expected triangles
|
||||
fp = [tuple(f32(c) for c in p) for p in poly]
|
||||
s, tt = tis[tex]
|
||||
w, h = (sizes[tex] if variant != "q2" else (sizes[tex] if tex == 0 else (1, 1)))
|
||||
e = models.setdefault(model, {}).setdefault(texnames[tex], {"pos": [], "uv": [], "nrm": []})
|
||||
for c in ccw_fan(fp, n):
|
||||
x, y, z = fp[c]
|
||||
e["pos"] += [x, y, z]
|
||||
e["nrm"] += list(n)
|
||||
e["uv"] += [(x * s[0] + y * s[1] + z * s[2] + s[3]) / w, (x * tt[0] + y * tt[1] + z * tt[2] + tt[3]) / h]
|
||||
# lumps
|
||||
L = {}
|
||||
L["entities"] = ENTS
|
||||
L["planes"] = b"".join(struct.pack("<4fi", *n, d, 0) for n, d in planes)
|
||||
L["vertices"] = b"".join(struct.pack("<3f", *v) for v in verts)
|
||||
L["edges"] = b"".join(struct.pack("<2H", *e) for e in edges)
|
||||
L["surfedges"] = b"".join(struct.pack("<i", s) for s in surfedges)
|
||||
L["faces"] = b"".join(struct.pack("<HHiHH4Bi", p, sd, fe, ne, ti, 0, 255, 255, 255, -1) for p, sd, fe, ne, ti in flist)
|
||||
if q2:
|
||||
L["texinfo"] = b"".join(struct.pack("<8fii32si", *s, *t, 0, 0, texnames[k].encode(), -1) for s, t, k in texinfo)
|
||||
L["models"] = b"".join(struct.pack("<9fiii", *([0.0] * 9), 0, first, 6) for first in (0, 6))
|
||||
else:
|
||||
L["texinfo"] = b"".join(struct.pack("<8fii", *s, *t, k, 0) for s, t, k in texinfo)
|
||||
L["models"] = b"".join(struct.pack("<9f4iiii", *([0.0] * 9), 0, 0, 0, 0, 0, first, 6) for first in (0, 6))
|
||||
# miptex: texture 0 embedded (+ palette for HL), texture 1 in a WAD
|
||||
mips, crcs = [], []
|
||||
w, h = sizes[0]
|
||||
pix = bytes(rng.randrange(256) for _ in range(w * h))
|
||||
mip = struct.pack("<16sII", texnames[0].encode(), w, h)
|
||||
o0 = 40
|
||||
o1 = o0 + w * h
|
||||
o2 = o1 + w * h // 4
|
||||
o3 = o2 + w * h // 16
|
||||
mip += struct.pack("<4I", o0, o1, o2, o3) + pix + bytes(w * h // 4 + w * h // 16 + w * h // 64)
|
||||
hp = bytes(rng.randrange(256) for _ in range(768))
|
||||
if variant == "hl":
|
||||
mip += struct.pack("<H", 256) + hp + b"\0\0"
|
||||
usepal = hp if variant == "hl" else pal
|
||||
crcs.append(zlib.crc32(b"".join(usepal[i * 3:i * 3 + 3] + b"\xff" for i in pix)))
|
||||
mip2 = struct.pack("<16sII4I", texnames[1].encode(), 8, 8, 0, 0, 0, 0)
|
||||
lump = struct.pack("<ii", 2, 12) + struct.pack("<i", 12 + len(mip)) + mip + mip2
|
||||
L["miptex"] = lump
|
||||
mips = crcs
|
||||
names = (["entities", "planes", "vertices", "visibility", "nodes", "texinfo", "faces", "lighting", "leaves",
|
||||
"leaffaces", "leafbrushes", "edges", "surfedges", "models", "brushes", "brushsides", "pop", "areas", "areaportals"]
|
||||
if q2 else ["entities", "planes", "miptex", "vertices", "visibility", "nodes", "texinfo", "faces", "lighting",
|
||||
"clipnodes", "leaves", "marksurfaces", "edges", "surfedges", "models"])
|
||||
head = (b"IBSP" + struct.pack("<i", 38)) if q2 else struct.pack("<i", 30 if variant == "hl" else 29)
|
||||
off = len(head) + 8 * len(names)
|
||||
body, dirs = b"", []
|
||||
for n in names:
|
||||
d = L.get(n, b"")
|
||||
dirs.append((off + len(body), len(d)))
|
||||
body += d + b"\0" * ((4 - len(d) % 4) % 4)
|
||||
data = head + b"".join(struct.pack("<ii", *d) for d in dirs) + body
|
||||
out = {"data": data, "models": {str(k): v for k, v in models.items()}, "names": texnames}
|
||||
if not q2:
|
||||
out["textures"] = mips
|
||||
else:
|
||||
out["wal"] = struct.pack("<32sII", b"brick", 16, 8) + bytes(24)
|
||||
return out
|
||||
|
||||
|
||||
def q3_map(rng):
|
||||
verts, meshverts, faces = [], [], []
|
||||
expect = {}
|
||||
def v(p, uv, lm, n, col):
|
||||
verts.append((p, uv, lm, n, col))
|
||||
return len(verts) - 1
|
||||
# 2 polygon quads (shader 0, lightmap 0 / 1), one mesh triangle pair (shader 1), model 1 gets the last
|
||||
quads = [([(0, 0, 0), (64, 0, 0), (64, 64, 0), (0, 64, 0)], 0, 0, 0), ([(0, 0, 64), (0, 64, 64), (64, 64, 64), (64, 0, 64)], 0, 1, 0),
|
||||
([(8, 8, 8), (8, 8, 24), (24, 8, 24), (24, 8, 8)], 1, 0, 1)]
|
||||
for poly, sh, lm, model in quads:
|
||||
first = len(verts)
|
||||
# the stored order is clockwise seen from the front (Quake III's culling): the normal is minus Newell's
|
||||
(ax, ay, az), (bx, by, bz), (cx, cy, cz) = poly[0], poly[1], poly[2]
|
||||
u, w = (bx - ax, by - ay, bz - az), (cx - ax, cy - ay, cz - az)
|
||||
cr = (u[1] * w[2] - u[2] * w[1], u[2] * w[0] - u[0] * w[2], u[0] * w[1] - u[1] * w[0])
|
||||
ln = math.sqrt(sum(c * c for c in cr))
|
||||
nrm = tuple(f32(-c / ln) for c in cr)
|
||||
for p in poly:
|
||||
v(tuple(f32(c) for c in p), (f32(rng.random()), f32(rng.random())), (f32(rng.random()), f32(rng.random())), nrm, tuple(rng.randrange(256) for _ in range(4)))
|
||||
mv = len(meshverts)
|
||||
meshverts += [0, 1, 2, 0, 2, 3]
|
||||
faces.append((sh, 1 if model == 0 else 3, first, 4, mv, 6, lm))
|
||||
e = expect.setdefault(str(model), {}).setdefault("%d:%d" % (sh, lm), {"pos": [], "uv": [], "lm": [], "col": []})
|
||||
for tri in ((0, 1, 2), (0, 2, 3)):
|
||||
for c in reversed(tri):
|
||||
p, uv, lmuv, n, col = verts[first + c]
|
||||
e["pos"] += list(p)
|
||||
e["uv"] += list(uv)
|
||||
e["lm"] += list(lmuv)
|
||||
e["col"] += list(col)
|
||||
# a flat 3x3 patch over [0, 32] x [0, 32] at z = 100, facing down (clockwise from below: rows along +y)
|
||||
first = len(verts)
|
||||
for j in range(3):
|
||||
for i in range(3):
|
||||
v((f32(i * 16.0), f32(j * 16.0), f32(100.0)), (i / 2, j / 2), (0.0, 0.0), (0.0, 0.0, -1.0), (255, 255, 255, 255))
|
||||
faces.append((1, 2, first, 9, 0, 0, -1, 3, 3))
|
||||
shaders = [b"textures/base/wall", b"textures/base/floor"]
|
||||
L = {}
|
||||
L["entities"] = ENTS
|
||||
L["textures"] = b"".join(struct.pack("<64sii", s, 0, 1) for s in shaders)
|
||||
L["planes"] = struct.pack("<4f", 0, 0, 1, 0)
|
||||
L["models"] = struct.pack("<6fiiii", *([0.0] * 6), 0, 2, 0, 0) + struct.pack("<6fiiii", *([0.0] * 6), 2, 2, 0, 0)
|
||||
# reorder: model 0 = faces 0, 1 (quads of model 0) ... the patch is face 3 (model 1 range is 2..3)
|
||||
L["vertexes"] = b"".join(struct.pack("<10f4B", *p, *uv, *lm, *n, *c) for p, uv, lm, n, c in verts)
|
||||
L["meshverts"] = b"".join(struct.pack("<i", m) for m in meshverts)
|
||||
fb = b""
|
||||
for f in faces:
|
||||
sh, kind, first, n, mv, nmv, lm = f[:7]
|
||||
w, h = (f[7], f[8]) if len(f) > 7 else (0, 0)
|
||||
fb += struct.pack("<8i2i2i3f6f3f2i", sh, -1, kind, first, n, mv, nmv, lm, 0, 0, 0, 0, *([0.0] * 12), w, h)
|
||||
L["faces"] = fb
|
||||
lms = [bytes(rng.randrange(256) for _ in range(128 * 128 * 3)) for _ in range(2)]
|
||||
L["lightmaps"] = b"".join(lms)
|
||||
names = ["entities", "textures", "planes", "nodes", "leafs", "leaffaces", "leafbrushes", "models", "brushes",
|
||||
"brushsides", "vertexes", "meshverts", "effects", "faces", "lightmaps", "lightvols", "visdata"]
|
||||
off = 8 + 8 * len(names)
|
||||
body, dirs = b"", []
|
||||
for n in names:
|
||||
d = L.get(n, b"")
|
||||
dirs.append((off + len(body), len(d)))
|
||||
body += d + b"\0" * ((4 - len(d) % 4) % 4)
|
||||
data = b"IBSP" + struct.pack("<i", 46) + b"".join(struct.pack("<ii", *d) for d in dirs) + body
|
||||
lmcrc = [zlib.crc32(b"".join(l[k * 3:k * 3 + 3] + b"\xff" for k in range(128 * 128))) for l in lms]
|
||||
return {"data": data, "models": expect, "lightmaps": lmcrc, "patchArea": 32.0 * 32.0, "shaders": [s.decode() for s in shaders]}
|
||||
|
||||
|
||||
def generate(ctx):
|
||||
rng = ctx.rng(101)
|
||||
R = ref(ctx)
|
||||
pal = bytes(rng.randrange(256) for _ in range(768))
|
||||
q1 = brush_map(rng, "q1", pal)
|
||||
q1["palette"] = pal
|
||||
hl = brush_map(rng, "hl", pal)
|
||||
q2 = brush_map(rng, "q2", pal)
|
||||
q3 = q3_map(rng)
|
||||
zbuf = io.BytesIO()
|
||||
with zipfile.ZipFile(zbuf, "w") as z:
|
||||
z.writestr("maps/test.bsp", q3["data"])
|
||||
q3["assimp"] = R.assimp_soup(ctx, zbuf.getvalue(), "pk3")
|
||||
ctx.emit("bsp", {"q1": q1, "hl": hl, "q2": q2, "q3": q3})
|
||||
Reference in new issue
Block a user