merge ws/quake

This commit is contained in:
4DBug committed 2026-11-01 20:08:48 -06:00
commit 58df9e8a3a
39 files changed
+10044 -1413

No files matched your search

+61 -1
View File
@@ -170,6 +170,18 @@ local list: { Entry } = {
return require("@rosetta/image/ktx")
end,
},
{
name = "lmp",
category = "image",
path = "image/lmp",
extensions = { "lmp" },
mime = { "image/x-quake-lmp" },
deps = { "core/Err", "core/Bytes", "core/Input", "Types", "codecs/image/Pixels", "codecs/image/Miptex" },
caps = { decode = true, encode = true, alpha = true, depths = { 8 }, variants = { "qpic", "palette", "colormap" } },
load = function()
return require("@rosetta/image/lmp")
end,
},
{
name = "pcx",
category = "image",
@@ -230,6 +242,18 @@ local list: { Entry } = {
return require("@rosetta/image/sgi")
end,
},
{
name = "spr",
category = "image",
path = "image/spr",
extensions = { "spr" },
mime = { "image/x-quake-sprite" },
deps = { "core/Err", "core/Bytes", "core/Input", "Types", "codecs/image/Pixels", "codecs/image/Miptex" },
caps = { decode = true, encode = true, alpha = true, animation = true, variants = { "quake", "halflife", "spr32" } },
load = function()
return require("@rosetta/image/spr")
end,
},
{
name = "sunras",
category = "image",
@@ -765,7 +789,7 @@ local list: { Entry } = {
extensions = { "bsp" },
mime = { "model/x-bsp" },
deps = { "core/Err", "core/Bytes", "core/Input", "Types", "codecs/image/Pixels", "codecs/image/Miptex", "codecs/model/Patch" },
caps = { decode = true, encode = false, variants = { "quake", "halflife", "quake2", "quake3" }, lightmaps = "quake3" },
caps = { decode = true, encode = false, variants = { "quake", "bsp2", "2psb", "halflife", "quake2", "quake3" }, lightmaps = true, collision = true, visibility = true },
load = function()
return require("@rosetta/model/bsp")
end,
@@ -1658,6 +1682,18 @@ local list: { Entry } = {
return require("@rosetta/archive/wad")
end,
},
{
name = "wad2",
category = "archive",
path = "archive/wad2",
extensions = { "wad" },
mime = { "application/x-quake-wad" },
deps = { "core/Err", "core/Bytes", "core/Input", "Types", "containers/Archive", "codecs/image/Pixels", "codecs/image/Miptex" },
caps = { decode = true, encode = true, images = true, variants = { "wad2", "wad3" } },
load = function()
return require("@rosetta/archive/wad2")
end,
},
{
name = "xz",
category = "archive",
@@ -1814,6 +1850,30 @@ local list: { Entry } = {
return require("@rosetta/data/plist")
end,
},
{
name = "q3shader",
category = "data",
path = "data/q3shader",
extensions = { "shader" },
mime = { "text/x-quake3-shader" },
deps = { "core/Err", "core/Bytes" },
caps = { decode = true, encode = true },
load = function()
return require("@rosetta/data/q3shader")
end,
},
{
name = "q3skin",
category = "data",
path = "data/q3skin",
extensions = { "skin" },
mime = { "text/x-quake3-skin" },
deps = { "core/Err", "core/Bytes" },
caps = { decode = true, encode = true },
load = function()
return require("@rosetta/data/q3skin")
end,
},
{
name = "snbt",
category = "data",
+280
View File
@@ -0,0 +1,280 @@
--!strict
-- archive/wad2: Quake WAD2 and Half-Life WAD3 texture / graphics WADs (wad.h of the Quake source, the GoldSrc WAD3
-- layout; no code taken), read and write. Lumps by name (repeats "<name>~<n>"); Wad2.image decodes miptex, qpic,
-- conchars, palette and GoldSrc font lumps through codecs/image/Miptex (Quake 1 needs a palette: the WAD's own
-- "palette" lump, opts.palette or gfx/palette.lmp through files / resolve; else grey). Not supported: compressed lumps.
-- ------------------------------------------------------------------------------------------------ requires
local Err = require("@rosetta/core/Err")
local Bytes = require("@rosetta/core/Bytes")
local Input = require("@rosetta/core/Input")
local Types = require("@rosetta/Types")
local Archive = require("@rosetta/containers/Archive")
local Pixels = require("@rosetta/codecs/image/Pixels")
local Miptex = require("@rosetta/codecs/image/Miptex")
-- ------------------------------------------------------------------------------------------------ contract
local Wad2 = {
name = "wad2",
category = "archive",
extensions = { "wad" },
mime = { "application/x-quake-wad" },
deps = { "core/Err", "core/Bytes", "core/Input", "Types", "containers/Archive", "codecs/image/Pixels", "codecs/image/Miptex" },
caps = { decode = true, encode = true, images = true, variants = { "wad2", "wad3" } },
}
-- ------------------------------------------------------------------------------------------------ types
export type DecodeOptions = { maxEntries: number? } -- default 1e6
export type EncodeOptions = { variant: ("wad2" | "wad3")? } -- default: the source's, else wad3 when a lump is type 0x43
export type ImageOptions = {
palette: (buffer | string)?, -- 768 bytes (Quake 1)
mip: number?, -- miptex level 0..3, default 0
keyed: boolean?, -- index 255 transparent; default: qpics, conchars and '{' textures
resolve: ((uri: string) -> (buffer | string)?)?,
files: { [string]: buffer | string }?,
}
export type AddOptions = {
kind: ("miptex" | "qpic")?, -- default "miptex"
palette: (buffer | string)?, -- 768 bytes; required for WAD2 lumps, made by median cut for WAD3 without it
}
-- ------------------------------------------------------------------------------------------------ constants
local T = Miptex.TYPES
-- ------------------------------------------------------------------------------------------------ sniff
function Wad2.sniff(r: Bytes.Reader): number
if r:remaining() < 12 then
return 0
end
local m = r:peek(4)
return if m == "WAD2" or m == "WAD3" then 0.9 else 0
end
-- ------------------------------------------------------------------------------------------------ decode
local function encode(archive: any, opts: any?): (buffer?, Err.Err?)
return Wad2.encode(archive, opts)
end
function Wad2.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?)
local size = r.limit - r.base
local lumps, msg, magic = Miptex.wad(r.buf, r.base, size, opts and opts.maxEntries)
if not lumps then
return nil, Err.from(msg, 0)
end
local a = Archive.new("wad2", encode)
local seen: { [string]: number } = {}
for _, l in lumps do
if l.compression ~= 0 then
return nil, Err.new(Err.UNSUPPORTED, "compressed lump " .. l.name)
end
local entry = l.name
local k = seen[string.lower(entry)]
if k then
seen[string.lower(entry)] = k + 1
entry = entry .. "~" .. (k + 1)
else
seen[string.lower(entry)] = 1
end
Archive.put(a, { name = entry, size = l.disksize, dir = false, method = "store", type = l.type, lump = l.name, load = Archive.slice(r.buf, r.base + l.offset, l.disksize) })
end
a.meta.source = { format = "wad2", variant = string.lower(magic :: string), lumps = #lumps }
a.meta.wad2 = { buf = r.buf, base = r.base, lumps = lumps, goldsrc = magic == "WAD3" }
return a, nil
end
-- ------------------------------------------------------------------------------------------------ encode
local function guessType(name: string, data: buffer, goldsrc: boolean): number
local n = buffer.len(data)
if string.lower(name) == "palette" and n == 768 then
return T.palette
end
if n >= 40 then
local w, h = buffer.readu32(data, 16), buffer.readu32(data, 20)
if w > 0 and h > 0 and w < 65536 and h < 65536 and buffer.readu32(data, 24) == 40 then
return if goldsrc then 0x43 else T.miptex
end
end
if n >= 8 then
local w, h = buffer.readu32(data, 0), buffer.readu32(data, 4)
if w > 0 and h > 0 and 8 + w * h <= n then
return T.qpic
end
end
return T.miptex
end
function Wad2.encode(archive: any, opts: EncodeOptions?): (buffer?, Err.Err?)
local items, err = Archive.collect(archive)
if not items then
return nil, err
end
local src = type(archive) == "table" and type(archive.meta) == "table" and archive.meta.source
local variant = opts and opts.variant or (if type(src) == "table" and src.format == "wad2" then src.variant else nil)
if not variant then
variant = "wad2"
for _, it in items do
if (it.entry :: any).type == 0x43 then
variant = "wad3"
end
end
end
if variant ~= "wad2" and variant ~= "wad3" then
return nil, Err.new(Err.ARG, "variant must be wad2 or wad3")
end
local list: { { name: string, data: buffer, type: number } } = {}
for _, it in items do
if not it.entry.dir then
local e: any = it.entry
local name = e.lump or string.gsub(string.match(e.name, "([^/\\]*)$") or e.name, "~%d+$", "")
if #name == 0 or #name > 15 then
return nil, Err.new(Err.ARG, "lump name must be 1..15 bytes: " .. e.name)
end
local typ = if type(e.type) == "number" then e.type else guessType(name, it.data, variant == "wad3")
table.insert(list, { name = name, data = it.data, type = typ })
end
end
local w = Bytes.writer()
w:string(if variant == "wad3" then "WAD3" else "WAD2")
w:u32le(#list)
w:u32le(0)
local offs: { number } = {}
for i, l in list do
offs[i] = w:tell()
w:bytes(l.data)
w:fill(0, (4 - buffer.len(l.data) % 4) % 4)
end
local dir = w:tell()
for i, l in list do
w:u32le(offs[i])
w:u32le(buffer.len(l.data))
w:u32le(buffer.len(l.data))
w:u8(l.type)
w:u8(0)
w:u16le(0)
w:string(l.name)
w:fill(0, 16 - #l.name)
end
w:setU32le(8, dir)
return w:finish(), nil
end
-- ------------------------------------------------------------------------------------------------ extras
local function info(a: any): any
return type(a) == "table" and type(a.meta) == "table" and a.meta.wad2 or nil
end
function Wad2.new(variant: ("wad2" | "wad3")?): any
local a = Archive.new("wad2", encode)
a.meta.source = { format = "wad2", variant = variant or "wad2" }
return a
end
function Wad2.lumps(a: any): { Miptex.Lump }?
local w = info(a)
return w and w.lumps
end
-- the WAD's own "palette" lump (gfx.wad) as a 1024-byte rgba8 palette
function Wad2.palette(a: any): buffer?
local w = info(a)
local l = w and Miptex.find(w.lumps, "palette")
if l and l.disksize >= 768 then
return Pixels.palette(w.buf, w.base + l.offset, 256)
end
return nil
end
function Wad2.image(a: any, name: string, opts: ImageOptions?): (Types.Image?, Err.Err?)
local w = info(a)
if not w then
return nil, Err.new(Err.ARG, "expected a decoded WAD2 / WAD3 archive")
end
local l = Miptex.find(w.lumps, tostring(name))
if not l then
return nil, Err.new(Err.ARG, "no lump named " .. tostring(name))
end
local b, at, size = w.buf, w.base + l.offset, l.disksize
local pal: buffer? = nil
if not w.goldsrc then
local raw = if opts and opts.palette then Bytes.toBuffer(opts.palette) else nil
if raw and buffer.len(raw) >= 768 then
pal = Pixels.palette(raw, 0, 256)
else
pal = Wad2.palette(a)
if not pal then
local lmp = Input.sibling(opts, "gfx/palette.lmp")
pal = if lmp and buffer.len(lmp) >= 768 then Pixels.palette(lmp, 0, 256) else nil
end
end
end
local keyed: boolean? = if opts then opts.keyed else nil
local img: Types.Image?, msg: string?
local kind: string
if l.type == T.palette and size >= 768 then
kind = "palette"
local out = Types.Image.new(16, 16)
buffer.copy(out.pixels, 0, Pixels.palette(b, at, 256), 0, 1024)
img = out
elseif string.lower(l.name) == "conchars" and size == 128 * 128 then
-- gfx.wad's console font: raw 128 x 128 pixels, no header, index 0 transparent
kind = "conchars"
local out = Types.Image.new(128, 128)
Pixels.indexed(b, at, 128, 8, out.pixels, 128, 128, true, Pixels.keyed(pal or Pixels.grey(), if keyed == false then -1 else 0))
img = out
elseif l.type == T.qpic then
kind = "qpic"
img, msg = Miptex.qpic(b, at, size, { palette = pal, goldsrc = w.goldsrc, keyed = keyed } :: any)
elseif l.type == T.font and w.goldsrc and size >= 16 + 1024 then
-- GoldSrc qfont_t: width (256), height, rowcount, rowheight, charinfo[256] (u16 offset, u16 width), pixels, palette
kind = "font"
local fw, fh = buffer.readu32(b, at), buffer.readu32(b, at + 4)
local p = 16 + 1024 + fw * fh
if fw == 0 or fh == 0 or fw * fh > 2 ^ 24 or p + 2 > size then
return nil, Err.new(Err.CORRUPT, "bad font lump " .. l.name, l.offset)
end
local n = buffer.readu16(b, at + p)
local fpal = if n > 0 and n <= 256 and p + 2 + n * 3 <= size then Pixels.palette(b, at + p + 2, n) else Pixels.grey()
local out = Types.Image.new(fw, fh)
Pixels.indexed(b, at + 16 + 1024, fw, 8, out.pixels, fw, fh, true, if keyed == false then fpal else Pixels.keyed(fpal, 255))
local glyphs = {}
for c = 0, 255 do
glyphs[c + 1] = { offset = buffer.readu16(b, at + 16 + c * 4), width = buffer.readu16(b, at + 18 + c * 4) }
end
out.meta.font = { rows = buffer.readu32(b, at + 8), rowHeight = buffer.readu32(b, at + 12), glyphs = glyphs }
img = out
else
kind = "miptex"
img, msg = Miptex.decode(b, at, size, { palette = pal, goldsrc = w.goldsrc, mip = if opts then opts.mip else nil, keyed = keyed } :: any)
end
if not img then
return nil, Err.from(msg, l.offset)
end
img.meta.source = { format = "wad2", kind = kind, lump = l.name, type = l.type, palette = w.goldsrc or pal ~= nil }
return img, nil
end
-- adds an rgba8 image as a miptex (sizes multiples of 16) or qpic lump; WAD3 lumps carry their own palette
function Wad2.addImage(a: any, name: string, img: Types.Image, opts: AddOptions?): (boolean, Err.Err?)
if type(img) ~= "table" or img.format ~= "rgba8" then
return false, Err.new(Err.ARG, "expected an rgba8 Image")
end
local src = type(a) == "table" and type(a.meta) == "table" and a.meta.source
local goldsrc = type(src) == "table" and src.variant == "wad3"
local raw = opts and opts.palette and Bytes.toBuffer(opts.palette)
local pal = if raw and buffer.len(raw) >= 768 then Pixels.palette(raw, 0, 256) else nil
local kind = opts and opts.kind or "miptex"
local data, msg
if kind == "qpic" then
data, msg = Miptex.encodeQpic(img, pal, goldsrc)
else
data, msg = Miptex.encode(img, name, pal, goldsrc)
end
if not data then
return false, Err.new(Err.ARG, msg or "cannot encode")
end
Archive.put(a, { name = name, size = buffer.len(data), dir = false, method = "store", lump = name, data = data,
type = if kind == "qpic" then T.qpic elseif goldsrc then 0x43 else T.miptex })
return true, nil
end
return Wad2
+99 -15
View File
@@ -113,30 +113,28 @@ function Miptex.encode(img: Types.Image, name: string, palette: buffer?, goldsrc
if #name > 15 then
return nil, "miptex name over 15 bytes"
end
local colors: { { number } }
if palette then
colors = Pixels.colorList(palette)
elseif goldsrc then
colors = Quantize.palette(img.pixels, w, h, 256)
else
if not palette and not goldsrc then
return nil, "a Quake miptex needs a palette"
end
local keyed = string.sub(name, 1, 1) == "{"
local _, colors = Miptex.indices(img, palette, keyed)
if keyed and not palette then
colors[256] = { 0, 0, 255, 255 } -- GoldSrc '{' textures: index 255 is the (blue) key colour
end
local pal1024 = palette or buffer.create(1024)
if not palette then
for i, c in colors do
buffer.writeu32(pal1024, (i - 1) * 4, 0xFF000000 + c[3] * 65536 + c[2] * 256 + c[1])
end
end
local levels: { buffer } = {}
local px, lw, lh = img.pixels, w, h
for m = 0, 3 do
if m > 0 then
px, lw, lh = halve(px, lw, lh)
end
local idx = Quantize.map(px, lw, lh, colors, { transparentIndex = if keyed then 255 else nil })
if keyed then
for k = 0, lw * lh - 1 do
if readu8(px, k * 4 + 3) < 128 then
buffer.writeu8(idx, k, 255)
end
end
end
levels[m + 1] = idx
local lvl = { kind = "image", width = lw, height = lh, format = "rgba8", pixels = px, loops = 0, meta = {} } :: any
levels[m + 1] = (Miptex.indices(lvl, pal1024, keyed))
end
local total = 40
for _, l in levels do
@@ -211,4 +209,90 @@ function Miptex.find(lumps: { Lump }, name: string): Lump?
return best
end
-- qpic (Quake .lmp / WAD2 type 0x42: u32 width, height, 8-bit pixels; GoldSrc adds u16 count + count * 3 palette bytes)
-- -> rgba8. keyed: index 255 transparent (Quake's Draw_TransPic), default true
function Miptex.qpic(b: buffer, at: number, size: number, opts: DecodeOptions?): (Types.Image?, string?)
if size < 8 or at < 0 or at + 8 > buffer.len(b) then
return nil, "truncated qpic header"
end
local w, h = readu32(b, at), readu32(b, at + 4)
if w == 0 or h == 0 then
return nil, "empty qpic"
end
if w * h > (opts and opts.maxPixels or 2 ^ 24) then
return nil, "limit: qpic " .. w .. " x " .. h
end
if 8 + w * h > size or at + 8 + w * h > buffer.len(b) then
return nil, "truncated qpic pixels"
end
local own: buffer? = nil
if opts and opts.goldsrc then
local p = 8 + w * h
if p + 2 <= size then
local n = buffer.readu16(b, at + p)
if n > 0 and n <= 256 and p + 2 + n * 3 <= size then
own = Pixels.palette(b, at + p + 2, n)
end
end
end
local pal = own or (opts and opts.palette) or Pixels.grey()
local keyed = if opts and opts.keyed ~= nil then opts.keyed else true
if keyed then
pal = Pixels.keyed(pal, 255)
end
local img = Types.Image.new(w, h)
Pixels.indexed(b, at + 8, w, 8, img.pixels, w, h, true, pal)
img.meta.source = { format = "qpic", palette = own ~= nil or (opts ~= nil and opts.palette ~= nil), keyed = keyed or nil }
return img, nil
end
-- palette indices of an rgba8 image (nearest entry; alpha < 128 -> 255 when keyed and the image has any) and the
-- palette used
function Miptex.indices(img: Types.Image, palette: buffer?, keyed: boolean): (buffer, { { number } })
if keyed then
local any = false
for k = 0, img.width * img.height - 1 do
if readu8(img.pixels, k * 4 + 3) < 128 then
any = true
break
end
end
keyed = any
end
local colors = if palette then Pixels.colorList(palette) else Quantize.palette(img.pixels, img.width, img.height, if keyed then 255 else 256)
local idx = Quantize.map(img.pixels, img.width, img.height, colors, { transparentIndex = if keyed and palette then 255 else nil })
if keyed then
for k = 0, img.width * img.height - 1 do
if readu8(img.pixels, k * 4 + 3) < 128 then
buffer.writeu8(idx, k, 255)
end
end
end
return idx, colors
end
-- an rgba8 image -> qpic bytes (goldsrc: with its palette, made by median cut when none is given)
function Miptex.encodeQpic(img: Types.Image, palette: buffer?, goldsrc: boolean?, keyed: boolean?): (buffer?, string?)
if not palette and not goldsrc then
return nil, "a Quake qpic needs a palette"
end
local w, h = img.width, img.height
local idx, colors = Miptex.indices(img, palette, keyed ~= false)
local out = buffer.create(8 + w * h + (if goldsrc then 2 + 768 else 0))
buffer.writeu32(out, 0, w)
buffer.writeu32(out, 4, h)
buffer.copy(out, 8, idx, 0, w * h)
if goldsrc then
local p = 8 + w * h
buffer.writeu16(out, p, 256)
for i = 0, 255 do
local c = colors[i + 1] or { 0, 0, 0 }
buffer.writeu8(out, p + 2 + i * 3, c[1])
buffer.writeu8(out, p + 3 + i * 3, c[2])
buffer.writeu8(out, p + 4 + i * 3, c[3])
end
end
return out, nil
end
return Miptex
+3 -3
View File
@@ -269,13 +269,13 @@ function Pixels.grey(): buffer
return pal
end
-- a copy of a 1024-byte palette with entry index fully transparent (Quake / GoldSrc: index 255 of sprites, qpics and
-- '{' textures)
-- a copy of a 1024-byte palette with entry index transparent (alpha 0, colour kept as Pillow does; Quake / GoldSrc:
-- index 255 of sprites, qpics and '{' textures)
function Pixels.keyed(pal: buffer, index: number): buffer
local out = buffer.create(1024)
buffer.copy(out, 0, pal, 0, math.min(buffer.len(pal), 1024))
if index >= 0 and index < 256 then
writeu32(out, index * 4, 0)
writeu8(out, index * 4 + 3, 0)
end
return out
end
+237
View File
@@ -0,0 +1,237 @@
--!strict
-- data/q3shader: Quake III shader scripts (.shader; the Quake III Arena Shader Manual, tr_shader.c tokenizing: no code
-- taken), read and write. A script is a list of shaders { name, directives, stages }; a directive is its tokens
-- ({ "surfaceparm", "nolightmap" }, one line each), a stage is a list of directives. Keywords keep their case.
-- Comments (// and /* */) are dropped.
-- ------------------------------------------------------------------------------------------------ requires
local Err = require("@rosetta/core/Err")
local Bytes = require("@rosetta/core/Bytes")
-- ------------------------------------------------------------------------------------------------ contract
local Q3Shader = {
name = "q3shader",
category = "data",
extensions = { "shader" },
mime = { "text/x-quake3-shader" },
deps = { "core/Err", "core/Bytes" },
caps = { decode = true, encode = true },
}
-- ------------------------------------------------------------------------------------------------ types
export type Directive = { string }
export type Shader = { name: string, directives: { Directive }, stages: { { Directive } } }
export type EncodeOptions = { indent: string? } -- default "\t"
-- ------------------------------------------------------------------------------------------------ constants
local KEYWORDS = { "surfaceparm", "map", "clampmap", "animmap", "blendfunc", "rgbgen", "alphagen", "tcgen", "tcmod",
"cull", "deformvertexes", "qer_editorimage", "nopicmip", "nomipmaps", "skyparms", "q3map_", "depthwrite", "alphafunc" }
-- ------------------------------------------------------------------------------------------------ sniff
function Q3Shader.sniff(r: Bytes.Reader): number
local head = r:peek(math.min(r:remaining(), 2048))
if #head < 4 or string.find(head, "[%z\1-\8\14-\31]") then
return 0
end
local s = string.gsub(string.gsub(head, "/%*.-%*/", " "), "//[^\n]*", "")
if not string.match(s, "^%s*[^%s{}\"]+%s*{") then
return 0
end
local lower = string.lower(s)
for _, k in KEYWORDS do
if string.find(lower, "%f[%w_]" .. k) then
return 0.7
end
end
return 0.2
end
-- ------------------------------------------------------------------------------------------------ decode
-- the token lines of a script; braces are lines of their own
local function lex(text: string): ({ { string } }?, string?)
local lines: { { string } } = {}
local cur: { string } = {}
local i, n = 1, #text
local function flush()
if #cur > 0 then
table.insert(lines, cur)
cur = {}
end
end
while i <= n do
local c = string.sub(text, i, i)
if c == "\n" then
flush()
i += 1
elseif string.match(c, "%s") then
i += 1
elseif string.sub(text, i, i + 1) == "//" then
local e = string.find(text, "\n", i, true)
i = e or n + 1
elseif string.sub(text, i, i + 1) == "/*" then
local _, e = string.find(text, "*/", i + 2, true)
if not e then
return nil, "unterminated comment"
end
for _ in string.gmatch(string.sub(text, i, e), "\n") do
flush()
end
i = e + 1
elseif c == "{" or c == "}" then
flush()
table.insert(lines, { c })
i += 1
elseif c == '"' then
local e = string.find(text, '"', i + 1, true)
if not e then
return nil, "unterminated string"
end
table.insert(cur, string.sub(text, i + 1, e - 1))
i = e + 1
else
local _, e = string.find(text, "^[^%s{}\"]+", i)
local stop = e :: number
local tok = string.sub(text, i, stop)
local cm = string.find(tok, "//", 1, true)
if cm and cm > 1 then
tok = string.sub(tok, 1, cm - 1)
stop = i + cm - 2
end
table.insert(cur, tok)
i = stop + 1
end
end
flush()
return lines, nil
end
function Q3Shader.decode(r: Bytes.Reader): ({ Shader }?, Err.Err?)
local text = buffer.readstring(r.buf, r.base, r.limit - r.base)
local lines, msg = lex(text)
if not lines then
return nil, Err.new(Err.CORRUPT, msg or "bad script")
end
local out: { Shader } = {}
local k = 1
while k <= #lines do
local l = lines[k]
if #l ~= 1 or l[1] == "{" or l[1] == "}" then
return nil, Err.new(Err.CORRUPT, "expected a shader name, got '" .. table.concat(l, " ") .. "'")
end
local sh: Shader = { name = l[1], directives = {}, stages = {} }
k += 1
if not lines[k] or lines[k][1] ~= "{" then
return nil, Err.new(Err.CORRUPT, "expected '{' after " .. sh.name)
end
k += 1
local stage: { Directive }? = nil
local closed = false
while k <= #lines do
local d = lines[k]
k += 1
if d[1] == "{" then
if stage then
return nil, Err.new(Err.CORRUPT, "nested stage in " .. sh.name)
end
stage = {}
elseif d[1] == "}" then
if stage then
table.insert(sh.stages, stage)
stage = nil
else
closed = true
break
end
elseif stage then
table.insert(stage, d)
else
table.insert(sh.directives, d)
end
end
if not closed then
return nil, Err.new(Err.TRUNCATED, "shader " .. sh.name .. " not closed")
end
table.insert(out, sh)
end
return out, nil
end
-- ------------------------------------------------------------------------------------------------ encode
local function tokens(d: any): (string?, string?)
if type(d) ~= "table" or #d == 0 then
return nil, "a directive is a list of strings"
end
local parts = {}
for _, t in d do
local s = tostring(t)
if s == "" or string.find(s, "[%s{}]") then
if string.find(s, '"', 1, true) or string.find(s, "\n") then
return nil, "token cannot hold quotes or line breaks: " .. s
end
s = '"' .. s .. '"'
end
table.insert(parts, s)
end
return table.concat(parts, " "), nil
end
function Q3Shader.encode(list: { Shader }, opts: EncodeOptions?): (buffer?, Err.Err?)
if type(list) ~= "table" then
return nil, Err.new(Err.ARG, "expected a list of shaders")
end
local ind = opts and opts.indent or "\t"
local out: { string } = {}
for _, sh in list do
if type(sh) ~= "table" or type(sh.name) ~= "string" or sh.name == "" or string.find(sh.name, "[%s{}\"]") then
return nil, Err.new(Err.ARG, "a shader needs a name without spaces")
end
table.insert(out, sh.name)
table.insert(out, "{")
for _, d in sh.directives or {} do
local line, e = tokens(d)
if not line then
return nil, Err.new(Err.ARG, e or "bad directive")
end
table.insert(out, ind .. line)
end
for _, st in sh.stages or {} do
table.insert(out, ind .. "{")
for _, d in st do
local line, e = tokens(d)
if not line then
return nil, Err.new(Err.ARG, e or "bad directive")
end
table.insert(out, ind .. ind .. line)
end
table.insert(out, ind .. "}")
end
table.insert(out, "}")
table.insert(out, "")
end
return buffer.fromstring(table.concat(out, "\n")), nil
end
-- ------------------------------------------------------------------------------------------------ extras
-- the shader named name (case-insensitive, as the game looks them up)
function Q3Shader.find(list: { Shader }, name: string): Shader?
local want = string.lower(name)
for _, sh in list do
if string.lower(sh.name) == want then
return sh
end
end
return nil
end
-- the first directive starting with keyword (case-insensitive) in a shader or stage directive list
function Q3Shader.directive(list: { Directive }, keyword: string): Directive?
local want = string.lower(keyword)
for _, d in list do
if string.lower(d[1] or "") == want then
return d
end
end
return nil
end
return Q3Shader
+94
View File
@@ -0,0 +1,94 @@
--!strict
-- data/q3skin: Quake III model skins (.skin: "surface,shader" lines, "tag_*," for tags; tr_image.c RE_RegisterSkin, no
-- code taken), read and write. Decodes to a list of { surface, shader } in file order (shader "" for tags).
-- ------------------------------------------------------------------------------------------------ requires
local Err = require("@rosetta/core/Err")
local Bytes = require("@rosetta/core/Bytes")
-- ------------------------------------------------------------------------------------------------ contract
local Q3Skin = {
name = "q3skin",
category = "data",
extensions = { "skin" },
mime = { "text/x-quake3-skin" },
deps = { "core/Err", "core/Bytes" },
caps = { decode = true, encode = true },
}
-- ------------------------------------------------------------------------------------------------ types
export type Entry = { surface: string, shader: string }
-- ------------------------------------------------------------------------------------------------ sniff
function Q3Skin.sniff(r: Bytes.Reader): number
local head = r:peek(math.min(r:remaining(), 1024))
if #head < 3 or string.find(head, "[%z\1-\8\14-\31]") then
return 0
end
local lines, good, paths = 0, 0, 0
for line in string.gmatch(head, "[^\r\n]+") do
if not string.match(line, "^%s*$") then
lines += 1
local surface, shader = string.match(line, "^%s*([%w_%-]+)%s*,%s*([^,%s]*)%s*$")
if surface and shader == "" and string.sub(string.lower(surface), 1, 4) == "tag_" then
good += 1
elseif shader and string.find(shader, "/", 1, true) then
good += 1
paths += 1
end
end
end
return if lines > 0 and good == lines and paths > 0 then 0.5 else 0
end
-- ------------------------------------------------------------------------------------------------ decode
function Q3Skin.decode(r: Bytes.Reader): ({ Entry }?, Err.Err?)
local text = buffer.readstring(r.buf, r.base, r.limit - r.base)
local out: { Entry } = {}
local n = 0
for line in string.gmatch(text, "[^\r\n]+") do
n += 1
local s = string.match(line, "^%s*(.-)%s*$") :: string
if s ~= "" and string.sub(s, 1, 2) ~= "//" then
local surface, shader = string.match(s, "^([^,]-)%s*,%s*(.-)$")
if not surface or surface == "" then
return nil, Err.new(Err.CORRUPT, "line " .. n .. ": expected surface,shader")
end
table.insert(out, { surface = surface, shader = shader :: string })
end
end
return out, nil
end
-- ------------------------------------------------------------------------------------------------ encode
function Q3Skin.encode(list: { Entry }): (buffer?, Err.Err?)
if type(list) ~= "table" then
return nil, Err.new(Err.ARG, "expected a list of { surface, shader }")
end
local out: { string } = {}
for _, e in list do
if type(e) ~= "table" or type(e.surface) ~= "string" or e.surface == "" or string.find(e.surface, "[,\r\n]") then
return nil, Err.new(Err.ARG, "a skin entry needs a surface name without commas")
end
local sh = if e.shader == nil then "" else tostring(e.shader)
if string.find(sh, "[,\r\n]") then
return nil, Err.new(Err.ARG, "a shader path cannot hold commas or line breaks")
end
table.insert(out, e.surface .. "," .. sh)
end
table.insert(out, "")
return buffer.fromstring(table.concat(out, "\n")), nil
end
-- the shader of a surface (case-insensitive)
function Q3Skin.shader(list: { Entry }, surface: string): string?
local want = string.lower(surface)
for _, e in list do
if string.lower(e.surface) == want then
return e.shader
end
end
return nil
end
return Q3Skin
+131
View File
@@ -0,0 +1,131 @@
--!strict
-- image/lmp: Quake .lmp lumps (wad.h / draw.c of the Quake source; no code taken), read and write: qpic pictures (u32
-- width, height, 8-bit pixels; index 255 transparent), palette.lmp (768 bytes: a 16 x 16 swatch) and colormap.lmp (64
-- light levels x 256: a 256 x 64 image). Pictures and colormaps need Quake's palette, which is never embedded (GPL):
-- opts.palette or gfx/palette.lmp through files / resolve; else grey (meta.source.palette = false).
-- ------------------------------------------------------------------------------------------------ requires
local Err = require("@rosetta/core/Err")
local Bytes = require("@rosetta/core/Bytes")
local Input = require("@rosetta/core/Input")
local Types = require("@rosetta/Types")
local Pixels = require("@rosetta/codecs/image/Pixels")
local Miptex = require("@rosetta/codecs/image/Miptex")
-- ------------------------------------------------------------------------------------------------ contract
local Lmp = {
name = "lmp",
category = "image",
extensions = { "lmp" },
mime = { "image/x-quake-lmp" },
deps = { "core/Err", "core/Bytes", "core/Input", "Types", "codecs/image/Pixels", "codecs/image/Miptex" },
caps = { decode = true, encode = true, alpha = true, depths = { 8 }, variants = { "qpic", "palette", "colormap" } },
}
-- ------------------------------------------------------------------------------------------------ types
export type DecodeOptions = {
palette: (buffer | string)?, -- 768 bytes
kind: ("qpic" | "palette" | "colormap")?, -- default: from the size
keyed: boolean?, -- qpic index 255 transparent, default true
resolve: ((uri: string) -> (buffer | string)?)?,
files: { [string]: buffer | string }?,
maxPixels: number?, -- default 2^24
}
export type EncodeOptions = {
palette: (buffer | string)?, -- 768 bytes: required for qpics
kind: ("qpic" | "palette")?, -- default "qpic"; "palette" writes a 16 x 16 swatch as 768 bytes
resolve: ((uri: string) -> (buffer | string)?)?,
files: { [string]: buffer | string }?,
}
-- ------------------------------------------------------------------------------------------------ sniff
local function kindOf(r: Bytes.Reader): string?
local n = r:remaining()
if n == 768 then
return "palette"
elseif n == 16385 or n == 16384 then
return "colormap"
end
if n < 9 then
return nil
end
local w, h = buffer.readu32(r.buf, r.pos), buffer.readu32(r.buf, r.pos + 4)
if w > 0 and h > 0 and w <= 4096 and h <= 4096 and 8 + w * h == n then
return "qpic"
end
return nil
end
function Lmp.sniff(r: Bytes.Reader): number
local k = kindOf(r)
return if k == "qpic" then 0.3 elseif k then 0.05 else 0
end
-- ------------------------------------------------------------------------------------------------ decode
local function palette(opts: any?): buffer?
local raw = if opts and opts.palette then Bytes.toBuffer(opts.palette) else Input.sibling(opts, "gfx/palette.lmp")
if raw and buffer.len(raw) >= 768 then
return Pixels.palette(raw, 0, 256)
end
return nil
end
function Lmp.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Image?, Err.Err?)
local kind = opts and opts.kind or kindOf(r)
local b, at, n = r.buf, r.base, r.limit - r.base
if kind == "palette" then
if n < 768 then
return nil, Err.new(Err.TRUNCATED, "palette", 0)
end
local img = Types.Image.new(16, 16)
buffer.copy(img.pixels, 0, Pixels.palette(b, at, 256), 0, 1024)
local list = Pixels.colorList(img.pixels)
img.meta.palette = list
img.meta.source = { format = "lmp", kind = "palette" }
return img, nil
end
local pal = palette(opts)
if kind == "colormap" then
local rows = math.min(64, n // 256)
if rows < 1 then
return nil, Err.new(Err.TRUNCATED, "colormap", 0)
end
local img = Types.Image.new(256, rows)
Pixels.indexed(b, at, 256, 8, img.pixels, 256, rows, true, pal or Pixels.grey())
img.meta.source = { format = "lmp", kind = "colormap", palette = pal ~= nil }
return img, nil
end
if kind ~= "qpic" and n >= 8 then
kind = "qpic"
end
local img, msg = Miptex.qpic(b, at, n, { palette = pal, keyed = opts and opts.keyed, maxPixels = opts and opts.maxPixels })
if not img then
return nil, Err.from(msg, 0)
end
img.meta.source = { format = "lmp", kind = "qpic", palette = pal ~= nil, keyed = (opts == nil or opts.keyed ~= false) or nil }
return img, nil
end
-- ------------------------------------------------------------------------------------------------ encode
function Lmp.encode(img: Types.Image, opts: EncodeOptions?): (buffer?, Err.Err?)
if type(img) ~= "table" or img.format ~= "rgba8" or type(img.pixels) ~= "buffer" then
return nil, Err.new(Err.ARG, "expected an rgba8 Image")
end
if opts and opts.kind == "palette" then
if img.width * img.height < 256 then
return nil, Err.new(Err.ARG, "a palette needs 256 pixels (16 x 16)")
end
return Pixels.paletteBytes(img.pixels, 256), nil
end
local pal = palette(opts)
if not pal then
return nil, Err.new(Err.ARG, "a qpic needs Quake's palette (opts.palette or gfx/palette.lmp; it is not embedded)")
end
local out, msg = Miptex.encodeQpic(img, pal, false, true)
if not out then
return nil, Err.new(Err.ARG, msg or "cannot encode")
end
return out, nil
end
return Lmp
+311
View File
@@ -0,0 +1,311 @@
--!strict
-- image/spr: Quake (IDSP 1), Half-Life (IDSP 2, own palette, texture formats) and DarkPlaces SPR32 (IDSP 32, rgba)
-- sprites, read and write (spritegn.h of the Quake source, the GoldSrc sprite layout; no code taken). Frames and frame
-- groups become Image frames on one canvas around the sprite origin (meta.origin); group intervals give the delays.
-- Quake sprites need Quake's palette (opts.palette or gfx/palette.lmp through files / resolve; never embedded).
-- Not supported: Quake II sprites (IDS2: frames are separate .pcx files).
-- ------------------------------------------------------------------------------------------------ requires
local Err = require("@rosetta/core/Err")
local Bytes = require("@rosetta/core/Bytes")
local Input = require("@rosetta/core/Input")
local Types = require("@rosetta/Types")
local Pixels = require("@rosetta/codecs/image/Pixels")
local Miptex = require("@rosetta/codecs/image/Miptex")
-- ------------------------------------------------------------------------------------------------ contract
local Spr = {
name = "spr",
category = "image",
extensions = { "spr" },
mime = { "image/x-quake-sprite" },
deps = { "core/Err", "core/Bytes", "core/Input", "Types", "codecs/image/Pixels", "codecs/image/Miptex" },
caps = { decode = true, encode = true, alpha = true, animation = true, variants = { "quake", "halflife", "spr32" } },
}
-- ------------------------------------------------------------------------------------------------ types
export type DecodeOptions = {
palette: (buffer | string)?, -- Quake: 768 bytes
resolve: ((uri: string) -> (buffer | string)?)?,
files: { [string]: buffer | string }?,
maxPixels: number?, -- per frame, default 2^24
maxFrames: number?, -- default 4096
}
export type EncodeOptions = {
version: number?, -- 2 (Half-Life, default), 1 (Quake: needs opts.palette) or 32 (rgba)
palette: (buffer | string)?,
type: number?, -- orientation: 0 parallel upright, 1 facing upright, 2 parallel (default), 3 oriented, 4 parallel oriented
texFormat: number?, -- Half-Life: 0 normal, 1 additive, 2 index alpha, 3 alpha test (default: 3 when any pixel is transparent)
delay: number?, -- seconds per frame when the image has none, default 0.1
}
-- ------------------------------------------------------------------------------------------------ constants
local TEX_FORMATS = { [0] = "normal", "additive", "indexalpha", "alphatest" }
-- ------------------------------------------------------------------------------------------------ sniff
function Spr.sniff(r: Bytes.Reader): number
if r:remaining() < 36 or r:peek(4) ~= "IDSP" then
return 0
end
local v = buffer.readi32(r.buf, r.pos + 4)
return if v == 1 or v == 2 or v == 32 then 1 else 0.3
end
-- ------------------------------------------------------------------------------------------------ decode
type Raw = { x: number, y: number, w: number, h: number, at: number, delay: number }
function Spr.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Image?, Err.Err?)
if r:string(4) ~= "IDSP" then
return nil, r.err or Err.new(Err.CORRUPT, "bad magic", 0)
end
local version = r:i32le()
if version ~= 1 and version ~= 2 and version ~= 32 then
return nil, Err.new(Err.UNSUPPORTED, "sprite version " .. tostring(version), 4)
end
local stype = r:i32le()
local texFormat = if version == 2 then r:i32le() else 3
local radius = r:f32le()
local mw, mh, nframes = r:i32le(), r:i32le(), r:i32le()
local beam, sync = r:f32le(), r:i32le()
if r.err then
return nil, r.err
end
local maxFrames = opts and opts.maxFrames or 4096
local maxPixels = opts and opts.maxPixels or 2 ^ 24
if nframes < 1 or nframes > maxFrames then
return nil, Err.new(if nframes < 1 then Err.CORRUPT else Err.LIMIT, "frame count " .. nframes, 24)
end
local pal: buffer
local own = false
if version == 2 then
local n = r:u16le()
if r.err then
return nil, r.err
end
if n < 1 or n > 256 or not r:need(n * 3) then
return nil, r.err or Err.new(Err.CORRUPT, "palette size " .. n, r:tell() - 2)
end
pal = Pixels.palette(r.buf, r.pos, n)
r:skip(n * 3)
own = true
else
local raw = if opts and opts.palette then Bytes.toBuffer(opts.palette) else Input.sibling(opts, "gfx/palette.lmp")
own = raw ~= nil and buffer.len(raw) >= 768
pal = if raw and own then Pixels.palette(raw, 0, 256) else Pixels.grey()
end
local bpp = if version == 32 then 4 else 1
local raws: { Raw } = {}
local groups: { { type: string, count: number } } = {}
local function single(delay: number): Err.Err?
local x, y, w, h = r:i32le(), r:i32le(), r:i32le(), r:i32le()
if r.err then
return r.err
end
if w < 1 or h < 1 then
return Err.new(Err.CORRUPT, "frame size " .. w .. " x " .. h, r:tell() - 8)
end
if w * h > maxPixels then
return Err.new(Err.LIMIT, "frame " .. w .. " x " .. h)
end
if not r:need(w * h * bpp) then
return r.err
end
table.insert(raws, { x = x, y = y, w = w, h = h, at = r.pos, delay = delay })
r:skip(w * h * bpp)
return nil
end
for _ = 1, nframes do
local ft = r:i32le()
if r.err then
return nil, r.err
end
if ft == 0 then
local e = single(0.1)
if e then
return nil, e
end
table.insert(groups, { type = "single", count = 1 })
else
local n = r:i32le()
if r.err then
return nil, r.err
end
if n < 1 or #raws + n > maxFrames then
return nil, Err.new(if n < 1 then Err.CORRUPT else Err.LIMIT, "group of " .. n .. " frames", r:tell() - 4)
end
local ivs = {}
for k = 1, n do
ivs[k] = r:f32le()
end
if r.err then
return nil, r.err
end
for k = 1, n do
-- intervals are cumulative end times (R_GetSpriteFrame)
local e = single(math.max(0, ivs[k] - (if k > 1 then ivs[k - 1] else 0)))
if e then
return nil, e
end
end
table.insert(groups, { type = "group", count = n })
end
end
local minX: number, maxX: number, minY: number, maxY: number = math.huge, -math.huge, math.huge, -math.huge
for _, f in raws do
minX = math.min(minX, f.x)
maxX = math.max(maxX, f.x + f.w)
maxY = math.max(maxY, f.y)
minY = math.min(minY, f.y - f.h)
end
local cw, ch = maxX - minX, maxY - minY
if cw * ch > maxPixels then
return nil, Err.new(Err.LIMIT, "canvas " .. cw .. " x " .. ch)
end
local fpal = pal
if version ~= 2 or texFormat == 3 then
fpal = Pixels.keyed(pal, 255)
end
local b = r.buf
local frames: { any } = {}
for _, f in raws do
local img = Types.Image.new(f.w, f.h)
if version == 32 then
buffer.copy(img.pixels, 0, b, f.at, f.w * f.h * 4)
elseif version == 2 and texFormat == 2 then
-- index alpha: the colour is the last palette entry, the index is the alpha
local c = bit32.band(buffer.readu32(pal, 255 * 4), 0xFFFFFF)
for k = 0, f.w * f.h - 1 do
buffer.writeu32(img.pixels, k * 4, c + buffer.readu8(b, f.at + k) * 0x1000000)
end
else
Pixels.indexed(b, f.at, f.w, 8, img.pixels, f.w, f.h, true, fpal)
end
table.insert(frames, { image = img, delay = f.delay, x = f.x - minX, y = maxY - f.y, dispose = "background", blend = "source" })
end
local out = Types.Image.new(cw, ch)
local f1 = frames[1]
for yy = 0, f1.image.height - 1 do
buffer.copy(out.pixels, ((f1.y + yy) * cw + f1.x) * 4, f1.image.pixels, yy * f1.image.width * 4, f1.image.width * 4)
end
out.frames = if #frames > 1 then frames else nil
out.loops = 0
out.meta.origin = { -minX, maxY }
out.meta.source = {
format = "spr", version = version, type = stype, texFormat = if version == 2 then TEX_FORMATS[texFormat] or texFormat else nil,
radius = radius, width = mw, height = mh, beamLength = beam, sync = sync, groups = groups,
palette = own, origins = (function()
local o = {}
for i, f in raws do
o[i] = { f.x, f.y }
end
return o
end)(),
}
return out, nil
end
-- ------------------------------------------------------------------------------------------------ encode
function Spr.encode(img: Types.Image, opts: EncodeOptions?): (buffer?, Err.Err?)
if type(img) ~= "table" or img.format ~= "rgba8" or type(img.pixels) ~= "buffer" then
return nil, Err.new(Err.ARG, "expected an rgba8 Image")
end
local version = opts and opts.version or 2
if version ~= 1 and version ~= 2 and version ~= 32 then
return nil, Err.new(Err.ARG, "version must be 1, 2 or 32")
end
local list: { { image: Types.Image, x: number, y: number, delay: number } } = {}
if img.frames and #img.frames > 0 then
for _, f in img.frames do
if f.image.format ~= "rgba8" then
return nil, Err.new(Err.ARG, "frames must be rgba8")
end
table.insert(list, { image = f.image, x = f.x, y = f.y, delay = f.delay })
end
else
table.insert(list, { image = img, x = 0, y = 0, delay = opts and opts.delay or 0.1 })
end
local origin = img.meta and img.meta.origin or { img.width // 2, img.height // 2 }
local mw: number, mh: number, alpha = 0, 0, false
for _, f in list do
mw = math.max(mw, f.image.width)
mh = math.max(mh, f.image.height)
local px = f.image.pixels
for k = 0, f.image.width * f.image.height - 1 do
if buffer.readu8(px, k * 4 + 3) < 128 then
alpha = true
break
end
end
end
local pal: buffer? = nil
if version == 1 then
local raw = if opts and opts.palette then Bytes.toBuffer(opts.palette) else nil
if not raw or buffer.len(raw) < 768 then
return nil, Err.new(Err.ARG, "a Quake sprite needs Quake's palette (opts.palette; it is not embedded)")
end
pal = Pixels.palette(raw, 0, 256)
elseif version == 2 then
local raw = if opts and opts.palette then Bytes.toBuffer(opts.palette) else nil
if raw and buffer.len(raw) >= 768 then
pal = Pixels.palette(raw, 0, 256)
else
-- one palette for every frame: the frames side by side
local tw = 0
for _, f in list do
tw += f.image.width
end
local strip = Types.Image.new(tw, mh)
local x0 = 0
for _, f in list do
for yy = 0, f.image.height - 1 do
buffer.copy(strip.pixels, (yy * tw + x0) * 4, f.image.pixels, yy * f.image.width * 4, f.image.width * 4)
end
x0 += f.image.width
end
local _, colors = Miptex.indices(strip, nil, alpha)
local p = buffer.create(1024)
for i, c in colors do
buffer.writeu32(p, (i - 1) * 4, 0xFF000000 + c[3] * 65536 + c[2] * 256 + c[1])
end
if alpha then
buffer.writeu32(p, 255 * 4, 0xFFFF0000) -- the alpha-test key: blue
end
pal = p
end
end
local texFormat = opts and opts.texFormat or (if alpha then 3 else 0)
local w = Bytes.writer()
w:string("IDSP")
w:u32le(version)
w:u32le(opts and opts.type or 2)
if version == 2 then
w:u32le(texFormat)
end
w:f32le(math.sqrt(mw * mw + mh * mh) / 2)
w:u32le(mw)
w:u32le(mh)
w:u32le(#list)
w:f32le(0)
w:u32le(0)
if version == 2 then
w:u16le(256)
w:bytes(Pixels.paletteBytes(pal :: buffer, 256))
end
for _, f in list do
local fw, fh = f.image.width, f.image.height
w:u32le(0)
w:u32le(bit32.band(f.x - origin[1], 0xFFFFFFFF))
w:u32le(bit32.band(origin[2] - f.y, 0xFFFFFFFF))
w:u32le(fw)
w:u32le(fh)
if version == 32 then
w:bytes(f.image.pixels, 0, fw * fh * 4)
else
local idx = Miptex.indices(f.image, pal, alpha and texFormat == 3 or version == 1)
w:bytes(idx, 0, fw * fh)
end
end
return w:finish(), nil
end
return Spr
+64
View File
@@ -0,0 +1,64 @@
--!strict
-- model/bsp/Lightmap: packs face lightmaps (w x h luxels each) into one atlas, shelf by shelf, tallest first, each
-- with a one-luxel border that repeats its edge (bilinear filtering stays inside the face).
local Lightmap = {}
export type Rect = { x: number, y: number, w: number, h: number } -- x, y: the first luxel inside the border
-- nil, message past maxPixels
function Lightmap.pack(sizes: { { number } }, maxPixels: number): (number, number, { Rect }?, string?)
local area, widest = 0, 1
for _, s in sizes do
area += (s[1] + 2) * (s[2] + 2)
widest = math.max(widest, s[1] + 2)
end
local W = 64
while W * W < area * 1.2 and W < 4096 do
W *= 2
end
W = math.max(W, widest)
local order = table.create(#sizes) :: { number }
for i = 1, #sizes do
order[i] = i
end
table.sort(order, function(a: number, b: number): boolean
local ha, hb = sizes[a][2], sizes[b][2]
if ha ~= hb then
return ha > hb
end
return a < b
end)
local out = table.create(#sizes) :: { Rect }
local x, y, rowH = 0, 0, 0
for _, i in order do
local w, h = sizes[i][1] + 2, sizes[i][2] + 2
if x + w > W then
x, y, rowH = 0, y + rowH, 0
end
out[i] = { x = x + 1, y = y + 1, w = sizes[i][1], h = sizes[i][2] }
x += w
rowH = math.max(rowH, h)
end
local H = math.max(1, y + rowH)
if W * H > maxPixels then
return 0, 0, nil, "limit: lightmap atlas " .. W .. " x " .. H
end
return W, H, out, nil
end
-- copies the outermost luxels of a rect into its border (rgba8 pixels, atlas width W)
function Lightmap.border(px: buffer, W: number, r: Rect)
local function copy(dx: number, dy: number, sx: number, sy: number)
buffer.writeu32(px, (dy * W + dx) * 4, buffer.readu32(px, (sy * W + sx) * 4))
end
for yy = r.y, r.y + r.h - 1 do
copy(r.x - 1, yy, r.x, yy)
copy(r.x + r.w, yy, r.x + r.w - 1, yy)
end
for xx = r.x - 1, r.x + r.w do
copy(xx, r.y - 1, xx, r.y)
copy(xx, r.y + r.h, xx, r.y + r.h - 1)
end
end
return Lightmap
@@ -1,15 +1,17 @@
--!strict
-- model/bsp/Brush: Quake 1 (BSP 29), Half-Life (BSP 30) and Quake II (IBSP 38) maps -> Scene, from bspfile.h of the
-- Quake / Quake II source releases (no code taken). Texture coordinates: s = v . s.xyz + s.w, divided by the texture
-- size.
-- model/bsp/Quake: Quake 1 (BSP 29, BSP2, 2PSB), Half-Life (BSP 30) and Quake II (IBSP 38) maps -> Scene, from
-- bspfile.h of the Quake / Quake II source releases and ericw-tools (BSP2 / 2PSB; no code taken). Texture coordinates:
-- s = v . s.xyz + s.w over the texture size; lightmaps (style 0) packed into one atlas as TEXCOORD_1, extents as
-- CalcSurfaceExtents (16 texels per luxel).
local Types = require("@rosetta/Types")
local Pixels = require("@rosetta/codecs/image/Pixels")
local Lightmap = require("@rosetta/model/bsp/Lightmap")
local Miptex = require("@rosetta/codecs/image/Miptex")
local Brush = {}
local Quake = {}
local Scene = Types.Scene
local readi32, readu16, readf32, readu32 = buffer.readi32, buffer.readu16, buffer.readf32, buffer.readu32
local readi32, readu16, readf32, readu32, readu8 = buffer.readi32, buffer.readu16, buffer.readf32, buffer.readu32, buffer.readu8
local writef32, writeu32 = buffer.writef32, buffer.writeu32
export type Lump = { at: number, size: number }
@@ -18,10 +20,12 @@ export type Options = {
wal: ((name: string) -> buffer?)?, -- Quake II: a texture's .wal file (for its size)
maxPixels: number?,
maxVertices: number?,
lit: buffer?, -- Quake 1 coloured light (.lit: "QLIT", version 1, RGB per luxel)
lightmaps: boolean?, -- default true
}
type Tex = { name: string, width: number, height: number, image: Types.Image?, texels: boolean }
type Batch = { tex: number, pos: { number }, nrm: { number }, uv: { number } }
type Batch = { tex: number, pos: { number }, nrm: { number }, uv: { number }, lm: { number } } -- lm: face, s, t per vertex
local function cstr(b: buffer, at: number, n: number): string
return (string.match(buffer.readstring(b, at, n), "^[^%z]*")) :: string
@@ -58,11 +62,14 @@ local function miptex(b: buffer, base: number, l: Lump, hl: boolean, pal: buffer
return out, nil
end
function Brush.decode(b: buffer, base: number, lumps: { [string]: Lump }, variant: string, opts: Options?): (Types.Scene?, string?)
function Quake.decode(b: buffer, base: number, lumps: { [string]: Lump }, variant: string, opts: Options?): (Types.Scene?, string?)
local q2 = variant == "q2"
local big = variant == "bsp2" or variant == "2psb"
local maxPixels = opts and opts.maxPixels or 2 ^ 24
local V, E, SE, Fc, TI, P, M = lumps.vertices, lumps.edges, lumps.surfedges, lumps.faces, lumps.texinfo, lumps.planes, lumps.models
local nV, nE, nSE, nF = V.size // 12, E.size // 4, SE.size // 4, Fc.size // 20
local fSize: number = if big then 28 else 20
local eSize: number = if big then 8 else 4
local nV, nE, nSE, nF = V.size // 12, E.size // eSize, SE.size // 4, Fc.size // fSize
local tiSize = if q2 then 76 else 40
local nTI, nP = TI.size // tiSize, P.size // 20
local mSize = if q2 then 48 else 64
@@ -125,11 +132,28 @@ function Brush.decode(b: buffer, base: number, lumps: { [string]: Lump }, varian
local batches: { [number]: { [number]: Batch } } = {}
local orders: { [number]: { number } } = {}
local skipped = 0
-- lightmaps: record 1 = a white luxel (sky / liquids), 2 = black (unlit faces), then one per lit face
local LT = lumps.lighting
local useLight = LT.size > 0 and not (opts and opts.lightmaps == false)
local rgb = variant == "hl" or q2
local lit = opts and opts.lit
if lit and (buffer.len(lit) < 8 or buffer.readstring(lit, 0, 4) ~= "QLIT" or buffer.readi32(lit, 4) ~= 1) then
lit = nil
end
local lmSizes: { { number } } = { { 1, 1 }, { 1, 1 } }
local lmFaces: { { face: number, ofs: number, smin: number, tmin: number, styles: number } } = { { face = -1, ofs = -1, smin = 0, tmin = 0, styles = 0 }, { face = -1, ofs = -1, smin = 0, tmin = 0, styles = 0 } }
local lumaTotal = 0
for f = 0, nF - 1 do
local fo = base + Fc.at + f * 20
local plane, side, firstEdge, numEdges, texinfo = readu16(b, fo), readu16(b, fo + 2), readi32(b, fo + 4), readu16(b, fo + 8), readu16(b, fo + 10)
local fo = base + Fc.at + f * fSize
local plane = if big then readi32(b, fo) else readu16(b, fo)
local side = if big then readi32(b, fo + 4) else readu16(b, fo + 2)
local firstEdge = if big then readi32(b, fo + 8) else readi32(b, fo + 4)
local numEdges = if big then readi32(b, fo + 12) else readu16(b, fo + 8)
local texinfo = if big then readi32(b, fo + 16) else readu16(b, fo + 10)
local styles = if big then fo + 20 else fo + 12
local lightofs = if big then readi32(b, fo + 24) else readi32(b, fo + 16)
local model = faceModel[f + 1]
if not model or numEdges < 3 or firstEdge < 0 or firstEdge + numEdges > nSE or plane >= nP or texinfo >= nTI then
if not model or numEdges < 3 or plane < 0 or texinfo < 0 or firstEdge < 0 or firstEdge + numEdges > nSE or plane >= nP or texinfo >= nTI then
skipped += 1
continue
end
@@ -142,7 +166,13 @@ function Brush.decode(b: buffer, base: number, lumps: { [string]: Lump }, varian
ok = false
break
end
local v = if se >= 0 then readu16(b, base + E.at + e * 4) else readu16(b, base + E.at + e * 4 + 2)
local eo = base + E.at + e * eSize
local v
if big then
v = if se >= 0 then readu32(b, eo) else readu32(b, eo + 4)
else
v = if se >= 0 then readu16(b, eo) else readu16(b, eo + 2)
end
if v >= nV then
ok = false
break
@@ -186,6 +216,37 @@ function Brush.decode(b: buffer, base: number, lumps: { [string]: Lump }, varian
local tio = base + TI.at + texinfo * tiSize
local sx, sy, sz, so = readf32(b, tio), readf32(b, tio + 4), readf32(b, tio + 8), readf32(b, tio + 12)
local tx, ty, tz, to = readf32(b, tio + 16), readf32(b, tio + 20), readf32(b, tio + 24), readf32(b, tio + 28)
local rec = 2
if useLight then
local tflags = readi32(b, tio + (if q2 then 32 else 36))
local special = if q2 then bit32.band(tflags, 0x8C) ~= 0 else bit32.band(tflags, 1) ~= 0
if special then
rec = 1
elseif lightofs >= 0 then
local smin: number, smax: number, tmin: number, tmax: number = math.huge, -math.huge, math.huge, -math.huge
for k = 0, n - 1 do
local x, y, z = poly[k * 3 + 1], poly[k * 3 + 2], poly[k * 3 + 3]
local sv, tv = x * sx + y * sy + z * sz + so, x * tx + y * ty + z * tz + to
smin, smax = math.min(smin, sv), math.max(smax, sv)
tmin, tmax = math.min(tmin, tv), math.max(tmax, tv)
end
local bs, bt0 = math.floor(smin / 16), math.floor(tmin / 16)
local lw, lh = math.ceil((smax :: number) / 16) - bs + 1, math.ceil((tmax :: number) / 16) - bt0 + 1
local ns = 0
for k = 0, 3 do
if readu8(b, styles + k) ~= 255 then
ns += 1
end
end
local bytes = lw * lh * (if rgb then 3 else 1)
lumaTotal += lw * lh
if ns > 0 and lw > 0 and lh > 0 and lw <= 256 and lh <= 256 and lightofs + bytes <= LT.size and lumaTotal <= maxPixels then
table.insert(lmSizes, { lw, lh })
table.insert(lmFaces, { face = f, ofs = lightofs, smin = bs * 16, tmin = bt0 * 16, styles = ns })
rec = #lmFaces
end
end
end
local ti = texOf[texinfo + 1] or 0
local tex = texs[ti]
local w, h = if tex then tex.width else 1, if tex then tex.height else 1
@@ -193,7 +254,7 @@ function Brush.decode(b: buffer, base: number, lumps: { [string]: Lump }, varian
batches[model] = bm
local bt = bm[ti]
if not bt then
bt = { tex = ti, pos = {}, nrm = {}, uv = {} }
bt = { tex = ti, pos = {}, nrm = {}, uv = {}, lm = {} }
bm[ti] = bt
local ol = orders[model] or {}
orders[model] = ol
@@ -206,21 +267,69 @@ function Brush.decode(b: buffer, base: number, lumps: { [string]: Lump }, varian
local pp, nn, uu = batch.pos, batch.nrm, batch.uv
pp[#pp + 1], pp[#pp + 2], pp[#pp + 3] = x, y, z
nn[#nn + 1], nn[#nn + 2], nn[#nn + 3] = nx, ny, nz
uu[#uu + 1] = (x * sx + y * sy + z * sz + so) / w
uu[#uu + 1] = (x * tx + y * ty + z * tz + to) / h
local sv, tv = x * sx + y * sy + z * sz + so, x * tx + y * ty + z * tz + to
uu[#uu + 1] = sv / w
uu[#uu + 1] = tv / h
local ll = batch.lm
ll[#ll + 1], ll[#ll + 2], ll[#ll + 3] = rec, sv, tv
end
end
end
local atlasW, atlasH, rects = 0, 0, nil :: { Lightmap.Rect }?
local lmTex: number? = nil
local atlas: Types.Image? = nil
if useLight and #lmFaces > 2 then
local W, H, rs, err = Lightmap.pack(lmSizes, maxPixels)
if not rs then
return nil, err
end
atlasW, atlasH, rects = W, H, rs
local img = Types.Image.new(W, H)
local px = img.pixels
local la = base + LT.at
buffer.writeu32(px, (rs[1].y * W + rs[1].x) * 4, 0xFFFFFFFF)
buffer.writeu32(px, (rs[2].y * W + rs[2].x) * 4, 0xFF000000)
local placed = {}
for i = 3, #lmFaces do
local lf, r = lmFaces[i], rs[i]
for yy = 0, r.h - 1 do
for xx = 0, r.w - 1 do
local k = yy * r.w + xx
local cr: number, cg: number, cb: number = 0, 0, 0
if rgb then
local o = la + lf.ofs + k * 3
cr, cg, cb = readu8(b, o), readu8(b, o + 1), readu8(b, o + 2)
elseif lit and 8 + (lf.ofs + k) * 3 + 3 <= buffer.len(lit) then
local o = 8 + (lf.ofs + k) * 3
cr, cg, cb = readu8(lit, o), readu8(lit, o + 1), readu8(lit, o + 2)
else
local v = readu8(b, la + lf.ofs + k)
cr, cg, cb = v, v, v
end
writeu32(px, ((r.y + yy) * W + r.x + xx) * 4, 0xFF000000 + (cb :: number) * 65536 + (cg :: number) * 256 + (cr :: number))
end
end
table.insert(placed, { face = lf.face, x = r.x, y = r.y, w = r.w, h = r.h, styles = lf.styles })
end
for i = 1, #lmFaces do
Lightmap.border(px, W, rs[i])
end
img.meta.source = { format = "bsp", lightmap = "atlas", coloured = rgb or lit ~= nil }
atlas = img
scene.meta.lightmaps = placed
lmTex = #texs + 1
end
for i, t in texs do
local tex: Types.Texture = { name = t.name, image = t.image, uri = if t.image then nil else (if q2 then "textures/" .. t.name .. ".wal" else t.name) }
table.insert(scene.textures, tex)
local mat = Scene.material(t.name)
mat.metallic = 0
local extras: any = { bsp = { texels = if t.texels then true else nil, width = t.width, height = t.height } }
mat.extras = extras
mat.extras = { bsp = { texels = if t.texels then true else nil, width = t.width, height = t.height } } :: any
mat.extras = { bsp = { texels = if t.texels then true else nil, width = t.width, height = t.height, lightmap = lmTex, lightmapTexCoord = if lmTex then 1 else nil } } :: any
table.insert(scene.materials, mat)
end
if atlas then
table.insert(scene.textures, { name = "lightmap", image = atlas })
end
local root: Types.Node = { name = "bsp", children = {} }
table.insert(scene.nodes, root)
scene.roots[1] = 1
@@ -242,8 +351,23 @@ function Brush.decode(b: buffer, base: number, lumps: { [string]: Lump }, varian
for k = 0, nv - 1 do
writeu32(ib, k * 4, k)
end
local attrs: { [string]: Types.Accessor } = { POSITION = Scene.accessor(pb, "f32", 3, nv), NORMAL = Scene.accessor(nb, "f32", 3, nv), TEXCOORD_0 = Scene.accessor(ub, "f32", 2, nv) }
if rects then
local lb = buffer.create(nv * 8)
for k = 0, nv - 1 do
local rec, sv, tv = bt.lm[k * 3 + 1], bt.lm[k * 3 + 2], bt.lm[k * 3 + 3]
local r, lf = rects[rec], lmFaces[rec]
local lu, lv = r.x + 0.5, r.y + 0.5
if rec > 2 then
lu, lv = r.x + (sv - lf.smin) / 16 + 0.5, r.y + (tv - lf.tmin) / 16 + 0.5
end
writef32(lb, k * 8, lu / atlasW)
writef32(lb, k * 8 + 4, lv / atlasH)
end
attrs.TEXCOORD_1 = Scene.accessor(lb, "f32", 2, nv)
end
table.insert(mesh.primitives, {
attributes = { POSITION = Scene.accessor(pb, "f32", 3, nv), NORMAL = Scene.accessor(nb, "f32", 3, nv), TEXCOORD_0 = Scene.accessor(ub, "f32", 2, nv) },
attributes = attrs,
indices = Scene.accessor(ib, "u32", 1, nv),
mode = "triangles" :: any,
material = if ti > 0 then ti else nil,
@@ -258,4 +382,4 @@ function Brush.decode(b: buffer, base: number, lumps: { [string]: Lump }, varian
return scene, nil
end
return Brush
return Quake
+386
View File
@@ -0,0 +1,386 @@
--!strict
-- model/bsp/Tree: the BSP tree, collision hulls and visibility of Quake 1 / BSP2 / 2PSB / Half-Life / Quake II / Quake
-- III maps as tables (bspfile.h layouts; Unofficial Quake 3 Map Specs), plus point queries: the leaf and contents at a
-- point (Quake 1 hulls 0..3 through nodes / clipnodes as SV_HullPointContents; Quake II leaf contents; Quake III the
-- contents of the leaf's brushes) and the potentially visible set of a leaf (run-length zero bytes, as Mod_DecompressVis).
local Tree = {}
local readi32, readu16, readi16, readf32, readu8, readu32 = buffer.readi32, buffer.readu16, buffer.readi16, buffer.readf32, buffer.readu8, buffer.readu32
export type Lump = { at: number, size: number }
export type Plane = { normal: { number }, dist: number, type: number? }
export type Node = { plane: number, children: { number }, mins: { number }, maxs: { number }, firstFace: number?, numFaces: number? } -- children: >= 0 node, < 0 leaf -(child + 1)
export type Leaf = {
contents: number?,
cluster: number?,
area: number?,
visofs: number?,
mins: { number },
maxs: { number },
firstFace: number?,
numFaces: number?,
firstBrush: number?,
numBrushes: number?,
ambient: { number }?,
}
export type ClipNode = { plane: number, children: { number } } -- children: >= 0 clipnode, < 0 contents
export type Model = { mins: { number }, maxs: { number }, origin: { number }?, headnodes: { number }, visleafs: number?, firstFace: number, numFaces: number }
export type Brush = { firstSide: number, numSides: number, contents: number }
export type Side = { plane: number, texinfo: number }
export type Data = {
variant: string,
planes: { Plane },
nodes: { Node },
leaves: { Leaf },
clipnodes: { ClipNode }?,
models: { Model },
brushes: { Brush }?,
brushSides: { Side }?,
leafBrushes: { number }?,
leafFaces: { number }?,
visibility: buffer?, -- the raw lump
numClusters: number?,
clusterBytes: number?, -- Quake III bytes per cluster vector
}
local function v3(b: buffer, o: number, kind: string): { number }
if kind == "f" then
return { readf32(b, o), readf32(b, o + 4), readf32(b, o + 8) }
elseif kind == "i" then
return { readi32(b, o), readi32(b, o + 4), readi32(b, o + 8) }
end
return { readi16(b, o), readi16(b, o + 2), readi16(b, o + 4) }
end
local function slice(b: buffer, base: number, l: Lump): buffer?
if l.size <= 0 then
return nil
end
local out = buffer.create(l.size)
buffer.copy(out, 0, b, base + l.at, l.size)
return out
end
-- nil, message past maxItems
function Tree.read(b: buffer, base: number, lumps: { [string]: Lump }, variant: string, maxItems: number?): (Data?, string?)
local limit = maxItems or 2 ^ 22
local q2, q3 = variant == "q2", variant == "q3"
local bsp2, rmq = variant == "bsp2", variant == "2psb"
local d: Data = { variant = variant, planes = {}, nodes = {}, leaves = {}, models = {} }
local function count(l: Lump?, size: number): number
return if l then l.size // size else 0
end
local P = lumps.planes
local pSize = if q3 then 16 else 20
local np = count(P, pSize)
if np > limit then
return nil, "limit: too many planes"
end
for i = 0, np - 1 do
local o = base + P.at + i * pSize
d.planes[i + 1] = { normal = v3(b, o, "f"), dist = readf32(b, o + 12), type = if q3 then nil else readi32(b, o + 16) }
end
local N = lumps.nodes
local nSize = if q3 then 36 elseif q2 then 28 elseif bsp2 then 44 elseif rmq then 32 else 24
local nn = count(N, nSize)
if nn > limit then
return nil, "limit: too many nodes"
end
for i = 0, nn - 1 do
local o = base + N.at + i * nSize
local node: any
if q3 or q2 or bsp2 or rmq then
local bk = if q3 then "i" elseif bsp2 then "f" else "s"
local bs = if bk == "s" then 6 else 12
node = { plane = readi32(b, o), children = { readi32(b, o + 4), readi32(b, o + 8) }, mins = v3(b, o + 12, bk), maxs = v3(b, o + 12 + bs, bk) }
if not q3 then
local fo = o + 12 + bs * 2
if q2 then
node.firstFace, node.numFaces = readu16(b, fo), readu16(b, fo + 2)
else
node.firstFace, node.numFaces = readu32(b, fo), readu32(b, fo + 4)
end
end
else
local c = {}
for k = 0, 1 do
local p = readu16(b, o + 4 + k * 2)
c[k + 1] = if p < nn then p else -(65535 - p) - 1 -- Quakespasm Mod_LoadNodes_S: leaf 65535 - p
end
node = { plane = readi32(b, o), children = c, mins = v3(b, o + 8, "s"), maxs = v3(b, o + 14, "s"), firstFace = readu16(b, o + 20), numFaces = readu16(b, o + 22) }
end
d.nodes[i + 1] = node
end
local L = lumps.leaves or lumps.leafs
local lSize = if q3 then 48 elseif q2 then 28 elseif bsp2 then 44 elseif rmq then 32 else 28
local nl = count(L, lSize)
if nl > limit then
return nil, "limit: too many leaves"
end
for i = 0, nl - 1 do
local o = base + L.at + i * lSize
local leaf: any
if q3 then
leaf = { cluster = readi32(b, o), area = readi32(b, o + 4), mins = v3(b, o + 8, "i"), maxs = v3(b, o + 20, "i"),
firstFace = readi32(b, o + 32), numFaces = readi32(b, o + 36), firstBrush = readi32(b, o + 40), numBrushes = readi32(b, o + 44) }
elseif q2 then
leaf = { contents = readi32(b, o), cluster = readi16(b, o + 4), area = readi16(b, o + 6), mins = v3(b, o + 8, "s"), maxs = v3(b, o + 14, "s"),
firstFace = readu16(b, o + 20), numFaces = readu16(b, o + 22), firstBrush = readu16(b, o + 24), numBrushes = readu16(b, o + 26) }
else
local bk = if bsp2 then "f" else "s"
local bs = if bsp2 then 12 else 6
local fo = o + 8 + bs * 2
local big = bsp2 or rmq
leaf = { contents = readi32(b, o), visofs = readi32(b, o + 4), mins = v3(b, o + 8, bk), maxs = v3(b, o + 8 + bs, bk),
firstFace = if big then readu32(b, fo) else readu16(b, fo), numFaces = if big then readu32(b, fo + 4) else readu16(b, fo + 2) }
local ao = fo + (if big then 8 else 4)
leaf.ambient = { readu8(b, ao), readu8(b, ao + 1), readu8(b, ao + 2), readu8(b, ao + 3) }
end
d.leaves[i + 1] = leaf
end
if not q2 and not q3 then
local C = lumps.clipnodes
local cSize = if bsp2 or rmq then 12 else 8
local nc = count(C, cSize)
if nc > limit then
return nil, "limit: too many clipnodes"
end
local cl: { ClipNode } = {}
for i = 0, nc - 1 do
local o = base + C.at + i * cSize
local c
if cSize == 12 then
c = { readi32(b, o + 4), readi32(b, o + 8) }
else
c = {}
for k = 0, 1 do
local p = readu16(b, o + 4 + k * 2)
c[k + 1] = if p > nc then p - 65536 else p -- Quakespasm Mod_LoadClipnodes
end
end
cl[i + 1] = { plane = readi32(b, o), children = c }
end
d.clipnodes = cl
end
local M = lumps.models
local mSize = if q3 then 40 elseif q2 then 48 else 64
for i = 0, count(M, mSize) - 1 do
local o = base + M.at + i * mSize
local m: any
if q3 then
m = { mins = v3(b, o, "f"), maxs = v3(b, o + 12, "f"), headnodes = { 0 }, firstFace = readi32(b, o + 24), numFaces = readi32(b, o + 28) }
elseif q2 then
m = { mins = v3(b, o, "f"), maxs = v3(b, o + 12, "f"), origin = v3(b, o + 24, "f"), headnodes = { readi32(b, o + 36) }, firstFace = readi32(b, o + 40), numFaces = readi32(b, o + 44) }
else
m = { mins = v3(b, o, "f"), maxs = v3(b, o + 12, "f"), origin = v3(b, o + 24, "f"),
headnodes = { readi32(b, o + 36), readi32(b, o + 40), readi32(b, o + 44), readi32(b, o + 48) },
visleafs = readi32(b, o + 52), firstFace = readi32(b, o + 56), numFaces = readi32(b, o + 60) }
end
d.models[i + 1] = m
end
if q2 or q3 then
local B, S = lumps.brushes, lumps.brushsides
local nb, ns = count(B, 12), count(S, if q3 then 8 else 4)
if nb > limit or ns > limit then
return nil, "limit: too many brushes"
end
local brushes: { Brush }, sides: { Side } = {}, {}
for i = 0, nb - 1 do
local o = base + B.at + i * 12
brushes[i + 1] = { firstSide = readi32(b, o), numSides = readi32(b, o + 4), contents = readi32(b, o + 8) } -- Quake III: a texture index
end
for i = 0, ns - 1 do
if q3 then
local o = base + S.at + i * 8
sides[i + 1] = { plane = readi32(b, o), texinfo = readi32(b, o + 4) }
else
local o = base + S.at + i * 4
sides[i + 1] = { plane = readu16(b, o), texinfo = readi16(b, o + 2) }
end
end
d.brushes, d.brushSides = brushes, sides
local LB = lumps.leafbrushes
local lbs: { number } = {}
for i = 0, count(LB, if q3 then 4 else 2) - 1 do
lbs[i + 1] = if q3 then readi32(b, base + LB.at + i * 4) else readu16(b, base + LB.at + i * 2)
end
d.leafBrushes = lbs
if q3 then
-- brush contents come from the texture's contents flags
local T = lumps.textures
local nt = count(T, 72)
for _, br in brushes do
local t = br.contents
br.contents = if t >= 0 and t < nt then readi32(b, base + T.at + t * 72 + 68) else 0
end
end
end
local VL = lumps.visibility or lumps.visdata
d.visibility = if VL then slice(b, base, VL) else nil
local vis = d.visibility
if vis and q2 and buffer.len(vis) >= 4 then
d.numClusters = readi32(vis, 0)
elseif vis and q3 and buffer.len(vis) >= 8 then
d.numClusters, d.clusterBytes = readi32(vis, 0), readi32(vis, 4)
end
return d, nil
end
local function side(d: Data, plane: number, x: number, y: number, z: number): number
local p = d.planes[plane + 1]
if not p then
return 0
end
local n = p.normal
return x * n[1] + y * n[2] + z * n[3] - p.dist
end
-- the leaf (0-based) at a point, walking the tree of model (0-based, default 0)
function Tree.leafAt(d: Data, x: number, y: number, z: number, model: number?): number?
local m = d.models[(model or 0) + 1]
local node = if m then m.headnodes[1] else 0
for _ = 1, #d.nodes + 1 do
if node < 0 then
return -node - 1
end
local nd = d.nodes[node + 1]
if not nd then
return nil
end
node = if side(d, nd.plane, x, y, z) >= 0 then nd.children[1] else nd.children[2]
end
return nil
end
-- Quake 1: CONTENTS_* (-1 empty, -2 solid, -3 water, -4 slime, -5 lava, -6 sky) in hull 0..3; Quake II: the leaf's
-- CONTENTS_* bits; Quake III: the contents bits of the brushes holding the point
function Tree.contents(d: Data, x: number, y: number, z: number, hull: number?, model: number?): number?
local h = hull or 0
if (d.variant == "q1" or d.variant == "hl" or d.variant == "bsp2" or d.variant == "2psb") and h > 0 then
local m = d.models[(model or 0) + 1]
local cl = d.clipnodes or {}
local node = if m then m.headnodes[h + 1] or -1 else -1
for _ = 1, #cl + 1 do
if node < 0 then
return node
end
local c = cl[node + 1]
if not c then
return nil
end
node = if side(d, c.plane, x, y, z) >= 0 then c.children[1] else c.children[2]
end
return nil
end
local leaf = Tree.leafAt(d, x, y, z, model)
local lf = leaf and d.leaves[leaf + 1]
if not lf then
return nil
end
if d.variant ~= "q3" then
return lf.contents
end
local out = 0
local lbs: { number }, brushes: { Brush }, sides: { Side } = d.leafBrushes or {}, d.brushes or {}, d.brushSides or {}
local fb: number, nb: number = lf.firstBrush or 0, lf.numBrushes or 0
for k = fb, fb + nb - 1 do
local br = brushes[(lbs[k + 1] or -1) + 1]
if br then
local inside = true
for s = br.firstSide, br.firstSide + br.numSides - 1 do
local sd = sides[s + 1]
if not sd or side(d, sd.plane, x, y, z) > 0 then
inside = false
break
end
end
if inside then
out = bit32.bor(out, br.contents)
end
end
end
return out
end
local function decompress(vis: buffer, at: number, bytes: number, out: { boolean })
local n = buffer.len(vis)
local i = 0
while i < bytes and at < n do
local c = readu8(vis, at)
if c ~= 0 then
for bit = 0, 7 do
if bit32.band(c, bit32.lshift(1, bit)) ~= 0 then
out[i * 8 + bit + 1] = true
end
end
i += 1
at += 1
else
if at + 1 >= n then
break
end
i += readu8(vis, at + 1)
at += 2
end
end
end
-- the leaves (0-based, sorted) potentially visible from a leaf; nil without visibility data (everything visible)
function Tree.pvs(d: Data, leaf: number): { number }?
local lf = d.leaves[leaf + 1]
local vis = d.visibility
if not lf or not vis then
return nil
end
local out: { number } = {}
if d.variant == "q2" or d.variant == "q3" then
local nc = d.numClusters or 0
local c = lf.cluster or -1
if c < 0 or c >= nc then
return out
end
local bits: { boolean } = {}
if d.variant == "q2" then
if 4 + nc * 8 > buffer.len(vis) then
return nil
end
decompress(vis, readi32(vis, 4 + c * 8), (nc + 7) // 8, bits)
else
local sz = d.clusterBytes or 0
local o = 8 + c * sz
for k = 0, sz - 1 do
if o + k < buffer.len(vis) then
local v = readu8(vis, o + k)
for bit = 0, 7 do
if bit32.band(v, bit32.lshift(1, bit)) ~= 0 then
bits[k * 8 + bit + 1] = true
end
end
end
end
end
for i, l in d.leaves do
local cl = l.cluster or -1
if cl >= 0 and bits[cl + 1] then
table.insert(out, i - 1)
end
end
return out
end
-- Quake 1: bit k = leaf k + 1 (leaf 0 is the shared solid leaf), visleafs bits
local visofs = lf.visofs or -1
if leaf == 0 or visofs < 0 then
return out
end
local n = d.models[1] and d.models[1].visleafs or (#d.leaves - 1)
local bits: { boolean } = {}
decompress(vis, visofs, (n + 7) // 8, bits)
for k = 0, n - 1 do
if bits[k + 1] then
table.insert(out, k + 1)
end
end
return out
end
return Tree
+54 -8
View File
@@ -1,15 +1,18 @@
--!strict
-- model/bsp: compiled game maps, read: Quake 1 (BSP 29), Half-Life (BSP 30), Quake II (IBSP 38), Quake III / RTCW
-- (IBSP 46 / 47). Quake textures need the game's palette (gfx/palette.lmp, not redistributable). Map units, z up.
-- Not supported: Source engine VBSP, Quake 1/2 lightmaps, visibility and collision data, writing.
-- model/bsp: compiled game maps, read: Quake 1 (BSP 29, BSP2, 2PSB), Half-Life (BSP 30), Quake II (IBSP 38), Quake III
-- / RTCW (IBSP 46 / 47). Lightmaps (Quake 1 / 2 / Half-Life: one atlas, Quake III: its pages) as TEXCOORD_1; the tree,
-- collision hulls / brushes and visibility in meta.bsp with point queries (Bsp.leafAt / contents / pvs). Quake textures
-- need the game's palette (gfx/palette.lmp, not redistributable). Map units, z up. Not supported: Source engine VBSP,
-- light styles other than the first, BSPX lumps, writing.
-- ------------------------------------------------------------------------------------------------ requires
local Err = require("@rosetta/core/Err")
local Bytes = require("@rosetta/core/Bytes")
local Input = require("@rosetta/core/Input")
local Types = require("@rosetta/Types")
local Brush = require("@rosetta/model/bsp/Brush")
local Quake = require("@rosetta/model/bsp/Quake")
local Quake3 = require("@rosetta/model/bsp/Quake3")
local Tree = require("@rosetta/model/bsp/Tree")
-- ------------------------------------------------------------------------------------------------ contract
local Bsp = {
@@ -18,7 +21,7 @@ local Bsp = {
extensions = { "bsp" },
mime = { "model/x-bsp" },
deps = { "core/Err", "core/Bytes", "core/Input", "Types", "codecs/image/Pixels", "codecs/image/Miptex", "codecs/model/Patch" },
caps = { decode = true, encode = false, variants = { "quake", "halflife", "quake2", "quake3" }, lightmaps = "quake3" },
caps = { decode = true, encode = false, variants = { "quake", "bsp2", "2psb", "halflife", "quake2", "quake3" }, lightmaps = true, collision = true, visibility = true },
}
-- ------------------------------------------------------------------------------------------------ types
@@ -27,6 +30,10 @@ export type DecodeOptions = {
resolve: ((uri: string) -> (buffer | string)?)?,
files: { [string]: buffer | string }?,
patchLevel: number?, -- default 4
lit: (buffer | string)?, -- Quake 1: the map's .lit file (coloured light); also found as "<map>.lit" through files / resolve
lightmaps: boolean?, -- default true
tree: boolean?, -- meta.bsp (tree, hulls, visibility), default true
name: string?, -- the file name (finds the .lit)
maxPixels: number?, -- default 2^24
maxVertices: number?, -- default 2^24
}
@@ -46,6 +53,9 @@ function Bsp.sniff(r: Bytes.Reader): number
end
local m = r:peek(4)
local v = buffer.readi32(r.buf, r.pos + (if m == "IBSP" then 4 else 0))
if m == "BSP2" or m == "2PSB" then
v = 29
end
if m == "IBSP" then
return if v == 38 or v == 46 or v == 47 then 1 else 0.3
end
@@ -88,6 +98,8 @@ function Bsp.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Scene?, Err.E
names, dir, variant = Q2_LUMPS, 8, "q2"
elseif m == "IBSP" and (version == 46 or version == 47) then
names, dir, variant = Q3_LUMPS, 8, "q3"
elseif m == "BSP2" or m == "2PSB" then
names, dir, variant = Q1_LUMPS, 4, string.lower(m)
elseif m ~= "IBSP" and (version == 29 or version == 30) then
names, dir, variant = Q1_LUMPS, 4, if version == 30 then "hl" else "q1"
elseif m == "VBSP" then
@@ -114,13 +126,15 @@ function Bsp.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Scene?, Err.E
if pal and buffer.len(pal) < 768 then
pal = nil
end
scene, msg = Brush.decode(b, base, lumps, variant, {
scene, msg = Quake.decode(b, base, lumps, variant, {
palette = pal,
wal = function(name: string): buffer?
return Input.sibling(opts, "textures/" .. name .. ".wal")
end,
maxPixels = opts and opts.maxPixels,
maxVertices = opts and opts.maxVertices,
lit = if opts and opts.lit then Bytes.toBuffer(opts.lit) else (if opts and opts.name then Input.sibling(opts, (string.gsub(opts.name :: string, "%.[^./\\]*$", "")) .. ".lit") else nil),
lightmaps = opts and opts.lightmaps,
})
end
if not scene then
@@ -132,12 +146,44 @@ function Bsp.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Scene?, Err.E
scene.meta.entities = entities(text)
scene.meta.source = {
format = "bsp",
variant = ({ q1 = "quake", hl = "halflife", q2 = "quake2", q3 = "quake3" } :: { [string]: string })[variant],
variant = ({ q1 = "quake", bsp2 = "quake", ["2psb"] = "quake", hl = "halflife", q2 = "quake2", q3 = "quake3" } :: { [string]: string })[variant],
layout = if variant == "bsp2" then "BSP2" elseif variant == "2psb" then "2PSB" else nil,
version = version,
entities = text,
palette = if variant == "q1" then (opts ~= nil and (opts.palette ~= nil or Input.sibling(opts, "gfx/palette.lmp") ~= nil)) else nil,
palette = if variant == "q1" or variant == "bsp2" or variant == "2psb" then (opts ~= nil and (opts.palette ~= nil or Input.sibling(opts, "gfx/palette.lmp") ~= nil)) else nil,
}
if not (opts and opts.tree == false) then
local tree, terr = Tree.read(b, base, lumps, variant)
if not tree then
return nil, Err.from(terr)
end
scene.meta.bsp = tree
end
return scene, nil
end
-- ------------------------------------------------------------------------------------------------ extras
local function tree(scene: any): Tree.Data?
return type(scene) == "table" and type(scene.meta) == "table" and scene.meta.bsp or nil
end
-- the leaf (0-based) at a point, in the tree of a model (0 = the world)
function Bsp.leafAt(scene: Types.Scene, x: number, y: number, z: number, model: number?): number?
local d = tree(scene)
return if d then Tree.leafAt(d, x, y, z, model) else nil
end
-- the contents at a point: Quake 1 CONTENTS_* (-1 empty, -2 solid, ...; hull 0 point, 1 player, 2 shambler, 3 crouch
-- in Half-Life), Quake II / III contents bits
function Bsp.contents(scene: Types.Scene, x: number, y: number, z: number, hull: number?, model: number?): number?
local d = tree(scene)
return if d then Tree.contents(d, x, y, z, hull, model) else nil
end
-- the leaves (0-based) potentially visible from a leaf; nil when the map has no visibility data
function Bsp.pvs(scene: Types.Scene, leaf: number): { number }?
local d = tree(scene)
return if d then Tree.pvs(d, leaf) else nil
end
return Bsp