merge ws/sourcemdl: Source MDL v44-49 (+vvd/vtx/phy/ani, flexes, animations), VMT materials, codecs/model/SourceAnim

This commit is contained in:
4DBug committed 2026-11-01 19:25:04 -06:00
commit c19a68dfae
33 files changed
+14429 -1224

No files matched your search

+219
View File
@@ -0,0 +1,219 @@
--!strict
--!native
-- codecs/model/SourceAnim: studio model animation data: the run-length coded mstudioanimvalue_t shorts (GoldSrc and
-- Source), Source mstudioanim_t bone records with Quaternion48 / Quaternion64 / Vector48, from the Source SDK 2013
-- studio.h / bone_setup.cpp layouts and SourceIO (MIT) notes; no code taken.
local Half = require("@rosetta/codecs/image/Half")
local SourceAnim = {}
local readu8, readi16, readu16, readu32 = buffer.readu8, buffer.readi16, buffer.readu16, buffer.readu32
local sqrt, sin, cos = math.sqrt, math.sin, math.cos
local HALF = Half.TABLE
export type Bone = {
pos: { number },
quat: { number },
rot: { number }, -- radian euler x, y, z
posScale: { number },
rotScale: { number },
}
export type Track = { pos: { number }, rot: { number } } -- frames * 3 / frames * 4 (quaternion x, y, z, w)
-- ExtractAnimValue: frame k of a run list ({ valid, total } then valid shorts); a frame past valid repeats
-- value[valid] (with valid = 0 that is the run header itself, as the engine reads it)
function SourceAnim.value(b: buffer, at: number, limit: number, k: number): number?
local p = at
for _ = 1, 65536 do
if p + 2 > limit then
return nil
end
local valid, total = readu8(b, p), readu8(b, p + 1)
if total == 0 then
return nil
end
if total > k then
local idx = if valid > k then k + 1 else valid
if p + idx * 2 + 2 > limit then
return nil
end
return readi16(b, p + idx * 2)
end
k -= total
p += (valid + 1) * 2
end
return nil
end
function SourceAnim.values(b: buffer, at: number, limit: number, count: number): { number }?
local out = table.create(count, 0)
local p, f = at, 0
while f < count do
if p + 2 > limit then
return nil
end
local valid, total = readu8(b, p), readu8(b, p + 1)
if total == 0 or p + 2 + valid * 2 > limit then
return nil
end
local n = math.min(total, count - f)
for i = 0, n - 1 do
local idx = if i < valid then i + 1 else valid
out[f + i + 1] = readi16(b, p + idx * 2)
end
f += n
p += (valid + 1) * 2
end
return out
end
-- Quaternion48: x, y u16 (bias 32768), z 15 bits (bias 16384), w sign bit
function SourceAnim.quat48(b: buffer, o: number): (number, number, number, number)
local x = (readu16(b, o) - 32768) / 32768
local y = (readu16(b, o + 2) - 32768) / 32768
local zw = readu16(b, o + 4)
local z = (zw % 32768 - 16384) / 16384
local w = sqrt(math.max(0, 1 - x * x - y * y - z * z))
return x, y, z, if zw >= 32768 then -w else w
end
-- Quaternion64: x, y, z 21 bits each (bias 1048576, scale 1 / 1048576.5), w sign bit 63
function SourceAnim.quat64(b: buffer, o: number): (number, number, number, number)
local lo, hi = readu32(b, o), readu32(b, o + 4)
local xs = lo % 2097152
local ys = (hi % 1024) * 2048 + (lo - xs) / 2097152
local zs = math.floor(hi / 1024) % 2097152
local x, y, z = (xs - 1048576) / 1048576.5, (ys - 1048576) / 1048576.5, (zs - 1048576) / 1048576.5
local w = sqrt(math.max(0, 1 - x * x - y * y - z * z))
return x, y, z, if hi >= 0x80000000 then -w else w
end
function SourceAnim.vec48(b: buffer, o: number): (number, number, number)
return HALF[readu16(b, o)], HALF[readu16(b, o + 2)], HALF[readu16(b, o + 4)]
end
-- AngleQuaternion (RadianEuler: x roll, y pitch, z yaw)
function SourceAnim.angles(x: number, y: number, z: number): (number, number, number, number)
local sy, cy = sin(z / 2), cos(z / 2)
local sp, cp = sin(y / 2), cos(y / 2)
local sr, cr = sin(x / 2), cos(x / 2)
return sr * cp * cy - cr * sp * sy, cr * sp * cy + sr * cp * sy, cr * cp * sy - sr * sp * cy, cr * cp * cy + sr * sp * sy
end
local RAWPOS, RAWROT, ANIMPOS, ANIMROT, DELTA, RAWROT2 = 0x01, 0x02, 0x04, 0x08, 0x10, 0x20
local function channels(b: buffer, vp: number, limit: number, frames: number, scale: { number }): ({ { number }? }?)
if vp + 6 > limit then
return nil
end
local out: { { number }? } = {}
for k = 0, 2 do
local off = readi16(b, vp + k * 2)
if off > 0 then
local v = SourceAnim.values(b, vp + off, limit, frames)
if not v then
return nil
end
local s = scale[k + 1]
for i = 1, frames do
v[i] *= s
end
out[k + 1] = v
end
end
return out
end
-- mstudioanim_t chain at `at` (bone u8, flags u8, next i16, data): `frames` frames of every bone it lists, as the
-- engine's CalcBoneQuaternion / CalcBonePosition (delta records add nothing of the bone's rest pose)
function SourceAnim.decode(b: buffer, at: number, limit: number, bones: { Bone }, frames: number): ({ [number]: Track }?, string?)
local out: { [number]: Track } = {}
local p = at
for _ = 1, #bones + 1 do
if p + 4 > limit then
return nil, "truncated animation"
end
local bone, flags, nxt = readu8(b, p), readu8(b, p + 1), readi16(b, p + 2)
if bone == 255 then
break
end
local bn = bones[bone + 1]
if not bn then
return nil, "animation bone out of range"
end
local delta = bit32.band(flags, DELTA) ~= 0
local d = p + 4
local rot = table.create(frames * 4, 0)
if bit32.band(flags, RAWROT) ~= 0 then
if d + 6 > limit then
return nil, "truncated animation"
end
local x, y, z, w = SourceAnim.quat48(b, d)
for f = 0, frames - 1 do
rot[f * 4 + 1], rot[f * 4 + 2], rot[f * 4 + 3], rot[f * 4 + 4] = x, y, z, w
end
d += 6
elseif bit32.band(flags, RAWROT2) ~= 0 then
if d + 8 > limit then
return nil, "truncated animation"
end
local x, y, z, w = SourceAnim.quat64(b, d)
for f = 0, frames - 1 do
rot[f * 4 + 1], rot[f * 4 + 2], rot[f * 4 + 3], rot[f * 4 + 4] = x, y, z, w
end
d += 8
elseif bit32.band(flags, ANIMROT) ~= 0 then
local ch = channels(b, d, limit, frames, bn.rotScale)
if not ch then
return nil, "bad rotation values"
end
local bx, by, bz = if delta then 0 else bn.rot[1], if delta then 0 else bn.rot[2], if delta then 0 else bn.rot[3]
local cx, cy, cz = ch[1], ch[2], ch[3]
for f = 0, frames - 1 do
local x, y, z, w = SourceAnim.angles(bx + (if cx then cx[f + 1] else 0), by + (if cy then cy[f + 1] else 0), bz + (if cz then cz[f + 1] else 0))
rot[f * 4 + 1], rot[f * 4 + 2], rot[f * 4 + 3], rot[f * 4 + 4] = x, y, z, w
end
d += 6
else
local q = if delta then { 0, 0, 0, 1 } else bn.quat
for f = 0, frames - 1 do
rot[f * 4 + 1], rot[f * 4 + 2], rot[f * 4 + 3], rot[f * 4 + 4] = q[1], q[2], q[3], q[4]
end
end
local pos = table.create(frames * 3, 0)
if bit32.band(flags, RAWPOS) ~= 0 then
if d + 6 > limit then
return nil, "truncated animation"
end
local x, y, z = SourceAnim.vec48(b, d)
for f = 0, frames - 1 do
pos[f * 3 + 1], pos[f * 3 + 2], pos[f * 3 + 3] = x, y, z
end
elseif bit32.band(flags, ANIMPOS) ~= 0 then
local ch = channels(b, d, limit, frames, bn.posScale)
if not ch then
return nil, "bad position values"
end
local bx, by, bz = if delta then 0 else bn.pos[1], if delta then 0 else bn.pos[2], if delta then 0 else bn.pos[3]
local cx, cy, cz = ch[1], ch[2], ch[3]
for f = 0, frames - 1 do
pos[f * 3 + 1] = bx + (if cx then cx[f + 1] else 0)
pos[f * 3 + 2] = by + (if cy then cy[f + 1] else 0)
pos[f * 3 + 3] = bz + (if cz then cz[f + 1] else 0)
end
elseif not delta then
for f = 0, frames - 1 do
pos[f * 3 + 1], pos[f * 3 + 2], pos[f * 3 + 3] = bn.pos[1], bn.pos[2], bn.pos[3]
end
end
out[bone + 1] = { pos = pos, rot = rot }
if nxt <= 0 then
break
end
p += nxt
end
return out, nil
end
return SourceAnim
@@ -0,0 +1,303 @@
--!strict
-- codecs/text/KeyValues/Binary: binary KeyValues (KeyValues::ReadAsBinary; Steam shortcuts.vdf / appinfo values).
-- Types: 0 block, 1 string, 2 int32, 3 float32, 4 pointer, 5 wide string (UTF-16LE), 6 color, 7 uint64, 8 end,
-- 10 int64, 11 end (alternative). 64-bit values are numbers below 2^53, decimal strings above.
local Err = require("@rosetta/core/Err")
local Text = require("@rosetta/codecs/text/Text")
local Binary = {}
export type Pair = {
key: string,
value: any, -- string | number | Block
cond: string?, -- text: the [$CONDITION] kept when not evaluated
type: string?, -- binary: "int32" | "float32" | "pointer" | "wstring" | "color" | "uint64" | "int64" (nil: string / block)
}
export type Block = { Pair }
local readu8, readu32, readi32, readf32 = buffer.readu8, buffer.readu32, buffer.readi32, buffer.readf32
local TYPES: { [number]: string } = { [2] = "int32", [3] = "float32", [4] = "pointer", [5] = "wstring", [6] = "color", [7] = "uint64", [10] = "int64" }
local CODES: { [string]: number } = { int32 = 2, float32 = 3, pointer = 4, wstring = 5, color = 6, uint64 = 7, int64 = 10 }
-- (hi, lo) u32 halves -> number below 2^53, else the decimal digits
local function u64text(hi: number, lo: number): number | string
if hi < 2 ^ 21 then
return hi * 4294967296 + lo
end
local digits: { string } = {}
-- base 10^6 long division over 16-bit limbs
local limbs = { hi // 65536, hi % 65536, lo // 65536, lo % 65536 }
while limbs[1] + limbs[2] + limbs[3] + limbs[4] > 0 do
local rem = 0
for i = 1, 4 do
local cur = rem * 65536 + limbs[i]
limbs[i] = cur // 1000000
rem = cur % 1000000
end
table.insert(digits, 1, string.format("%06d", rem))
end
local s = string.gsub(table.concat(digits), "^0+", "")
return if s == "" then 0 else s
end
-- number or decimal string -> (hi, lo), two's complement for negatives
local function u64parts(v: any): (number?, number?)
if type(v) == "number" then
if v ~= v or math.abs(v) >= 2 ^ 63 then
return nil, nil
end
v = math.floor(v)
local m = math.abs(v)
local hi = m // 4294967296
local lo = m - hi * 4294967296
if v < 0 then
return (4294967295 - hi + (if lo == 0 then 1 else 0)) % 4294967296, (4294967296 - lo) % 4294967296
end
return hi, lo
elseif type(v) == "string" then
local neg, digits = string.match(v, "^(%-?)(%d+)$")
if not digits or #digits > 20 then
return nil, nil
end
local limbs = { 0, 0, 0, 0 } -- 16-bit, most significant first
for i = 1, #digits do
local carry = tonumber(string.sub(digits, i, i)) :: number
for k = 4, 1, -1 do
local cur = limbs[k] * 10 + carry
limbs[k] = cur % 65536
carry = cur // 65536
end
if carry > 0 then
return nil, nil
end
end
if neg == "-" then
local carry = 1
for k = 4, 1, -1 do
local cur = (65535 - limbs[k]) + carry
limbs[k] = cur % 65536
carry = cur // 65536
end
end
return limbs[1] * 65536 + limbs[2], limbs[3] * 65536 + limbs[4]
end
return nil, nil
end
function Binary.read(buf: buffer | string, offset: number?, length: number?, opts: { maxDepth: number? }?): (Block?, Err.Err?)
local b: buffer = if type(buf) == "string" then buffer.fromstring(buf) else buf
if type(b) ~= "buffer" then
return nil, Err.new(Err.ARG, "KeyValues.readBinary: expected a buffer")
end
local o = offset or 0
local e = o + (length or (buffer.len(b) - o))
if o < 0 or e > buffer.len(b) or e < o then
return nil, Err.new(Err.ARG, "KeyValues.readBinary: range out of the buffer")
end
local maxDepth = opts and opts.maxDepth or 256
local p = o
local function cstr(): string?
local q = p
while q < e and readu8(b, q) ~= 0 do
q += 1
end
if q >= e then
return nil
end
local s = buffer.readstring(b, p, q - p)
p = q + 1
return s
end
local root: Block = {}
local stack: { Block } = { root }
while true do
if p >= e then
if #stack > 1 then
return nil, Err.new(Err.TRUNCATED, "unclosed block", p - o)
end
break
end
local t = readu8(b, p)
p += 1
if t == 8 or t == 11 then
if #stack == 1 then
break
end
table.remove(stack)
else
local cur = stack[#stack]
local key = cstr()
if not key then
return nil, Err.new(Err.TRUNCATED, "key", p - o)
end
if t == 0 then
if #stack >= maxDepth then
return nil, Err.new(Err.LIMIT, "nesting deeper than maxDepth", p - o)
end
local sub: Block = {}
table.insert(cur, { key = key, value = sub })
table.insert(stack, sub)
elseif t == 1 then
local v = cstr()
if not v then
return nil, Err.new(Err.TRUNCATED, "string value", p - o)
end
table.insert(cur, { key = key, value = v })
elseif t == 5 then
local q = p
while q + 1 < e and buffer.readu16(b, q) ~= 0 do
q += 2
end
if q + 1 >= e then
return nil, Err.new(Err.TRUNCATED, "wide string value", p - o)
end
table.insert(cur, { key = key, value = Text.utf16(b, p, q - p), type = "wstring" })
p = q + 2
elseif t == 2 or t == 3 or t == 4 or t == 6 then
if p + 4 > e then
return nil, Err.new(Err.TRUNCATED, "value", p - o)
end
local v = if t == 2 then readi32(b, p) elseif t == 3 then readf32(b, p) else readu32(b, p)
table.insert(cur, { key = key, value = v, type = TYPES[t] })
p += 4
elseif t == 7 or t == 10 then
if p + 8 > e then
return nil, Err.new(Err.TRUNCATED, "value", p - o)
end
local lo, hi = readu32(b, p), readu32(b, p + 4)
local v: number | string
if t == 10 and hi >= 2 ^ 31 then
-- negative: magnitude of the two's complement
local nlo = (4294967296 - lo) % 4294967296
local nhi = 4294967295 - hi + (if lo == 0 then 1 else 0)
local m = u64text(nhi, nlo)
v = if type(m) == "number" then -m else "-" .. m
else
v = u64text(hi, lo)
end
table.insert(cur, { key = key, value = v, type = TYPES[t] })
p += 8
else
return nil, Err.new(Err.CORRUPT, "unknown value type " .. t, p - o - 1)
end
end
end
return root, nil
end
local function utf16(s: string): string
local out: { string } = {}
for _, c in utf8.codes(s) do
if c >= 0x10000 then
local v = c - 0x10000
local hs = 0xD800 + v // 1024
table.insert(out, string.char(hs % 256, hs // 256))
local lo = 0xDC00 + v % 1024
table.insert(out, string.char(lo % 256, lo // 256))
else
table.insert(out, string.char(c % 256, c // 256))
end
end
return table.concat(out)
end
local function writeBlock(blk: Block, out: { string }, depth: number): string?
if depth > 256 then
return "nesting deeper than 256"
end
for _, pr in blk do
if type(pr) ~= "table" or type(pr.key) ~= "string" or string.find(pr.key, "%z") then
return "a pair needs a string key without NUL"
end
local v: any = pr.value
local k = pr.key .. "\0"
if type(v) == "table" then
table.insert(out, "\0" .. k)
local err = writeBlock(v, out, depth + 1)
if err then
return err
end
table.insert(out, "\8")
else
local code = if pr.type then CODES[pr.type] else (if type(v) == "number" then (if v % 1 == 0 and v >= -2 ^ 31 and v < 2 ^ 31 then 2 else 3) else 1)
if not code then
return "unknown value type " .. tostring(pr.type)
end
local w = buffer.create(8)
if code == 1 then
if type(v) ~= "string" or string.find(v, "%z") then
return "string value expected for key " .. pr.key
end
table.insert(out, "\1" .. k .. v .. "\0")
elseif code == 5 then
if type(v) ~= "string" or not utf8.len(v) then
return "UTF-8 string value expected for key " .. pr.key
end
table.insert(out, "\5" .. k .. utf16(v) .. "\0\0")
elseif code == 7 or code == 10 then
local hi, lo = u64parts(v)
if not hi then
return "64-bit value expected for key " .. pr.key
end
buffer.writeu32(w, 0, lo :: number)
buffer.writeu32(w, 4, hi :: number)
table.insert(out, string.char(code) .. k .. buffer.readstring(w, 0, 8))
else
if type(v) ~= "number" then
return "number value expected for key " .. pr.key
end
if code == 3 then
buffer.writef32(w, 0, v)
elseif code == 2 then
if v % 1 ~= 0 or v < -2 ^ 31 or v >= 2 ^ 31 then
return "int32 out of range for key " .. pr.key
end
buffer.writei32(w, 0, v)
else
if v % 1 ~= 0 or v < 0 or v >= 2 ^ 32 then
return "u32 out of range for key " .. pr.key
end
buffer.writeu32(w, 0, v)
end
table.insert(out, string.char(code) .. k .. buffer.readstring(w, 0, 4))
end
end
end
return nil
end
function Binary.write(blk: Block): (buffer?, Err.Err?)
if type(blk) ~= "table" then
return nil, Err.new(Err.ARG, "KeyValues.writeBinary: expected a pair list")
end
local out: { string } = {}
local err = writeBlock(blk, out, 0)
if err then
return nil, Err.new(Err.ARG, err)
end
table.insert(out, "\8")
return buffer.fromstring(table.concat(out)), nil
end
-- a type byte 0 / 1 / 2 then a printable NUL-terminated key
function Binary.sniff(b: buffer, o: number, n: number): boolean
if n < 3 then
return false
end
local t = readu8(b, o)
if t ~= 0 and t ~= 1 and t ~= 2 then
return false
end
for i = 1, math.min(n - 1, 64) do
local c = readu8(b, o + i)
if c == 0 then
return i > 1
elseif c < 32 then
return false
end
end
return false
end
return Binary
+555
View File
@@ -0,0 +1,555 @@
--!strict
-- codecs/text/KeyValues: Valve KeyValues text (tier1/KeyValues.cpp of the Source SDK 2013, srctools' reading of it)
-- and binary KeyValues (Steam appinfo / shortcuts.vdf). Pair lists keep order, duplicates and [$CONDITION]s;
-- #include / #base go through opts.resolve; the BSP entity lump ({ ... } blocks without keys) too.
local Err = require("@rosetta/core/Err")
local Types = require("@rosetta/Types")
local Binary = require("@rosetta/codecs/text/KeyValues/Binary")
local KeyValues = {}
export type Pair = Binary.Pair
export type Block = Binary.Block
export type ParseOptions = {
escapes: boolean?, -- \n \t \\ \" ... in quoted strings, default true
-- [$X] conditions: the flags that are true (case-insensitive names, without $); default { WIN32 = true }, the
-- other SDK names (X360, PS3, GAMECONSOLE, OSX, LINUX, POSIX, WINDOWS, DECK) false; false keeps every pair with
-- its cond
defines: ({ [string]: boolean } | false)?,
resolve: ((name: string) -> (buffer | string)?)?, -- #include / #base files
maxDepth: number?, -- default 256
}
export type WriteOptions = {
escapes: boolean?, -- default true
indent: string?, -- default "\t"
}
export type ObjectOptions = {
duplicates: ("array" | "last" | "first")?, -- default "array": a repeated key's values become an array
}
local DEFAULT_DEFINES: { [string]: boolean } = { win32 = true }
local ESCAPE: { [string]: string } = { n = "\n", t = "\t", v = "\v", b = "\b", r = "\r", f = "\f", a = "\a", ["\\"] = "\\", ["?"] = "?", ["'"] = "'", ['"'] = '"' }
type Lexer = { s: string, i: number, n: number, escapes: boolean }
-- kind: "s" string, "{", "}", "[" condition (its text), nil at the end; err on an unterminated string
local function token(lx: Lexer): (string?, string?, number, string?)
local s, n = lx.s, lx.n
local i = lx.i
while true do
local a = string.find(s, "[^ \t\r\n\f\v]", i)
if not a then
lx.i = n + 1
return nil, nil, n, nil
end
i = a
if string.sub(s, i, i + 1) == "//" then
local e = string.find(s, "\n", i, true)
if not e then
lx.i = n + 1
return nil, nil, n, nil
end
i = e + 1
else
break
end
end
local c = string.sub(s, i, i)
if c == "{" or c == "}" then
lx.i = i + 1
return c, nil, i - 1, nil
elseif c == '"' then
local start = i
i += 1
if not lx.escapes then
local e = string.find(s, '"', i, true)
if not e then
lx.i = n + 1
return nil, nil, start - 1, "unterminated string"
end
lx.i = e + 1
return "s", string.sub(s, i, e - 1), start - 1, nil
end
local parts: { string } = {}
while true do
local e = string.find(s, '["\\]', i)
if not e then
lx.i = n + 1
return nil, nil, start - 1, "unterminated string"
end
table.insert(parts, string.sub(s, i, e - 1))
if string.sub(s, e, e) == '"' then
lx.i = e + 1
return "s", table.concat(parts), start - 1, nil
end
local x = string.sub(s, e + 1, e + 1)
local r = ESCAPE[x]
if r then
table.insert(parts, r)
i = e + 2
else
table.insert(parts, "\\")
i = e + 1
end
end
elseif c == "[" then
local e = string.find(s, "]", i, true)
local sp = string.find(s, "[\r\n]", i)
if e and (not sp or sp > e) then
lx.i = e + 1
return "[", string.sub(s, i + 1, e - 1), i - 1, nil
end
end
local e = string.find(s, '[ \t\r\n\f\v"{}]', i)
local stop = if e then e - 1 else n
lx.i = stop + 1
return "s", string.sub(s, i, stop), i - 1, nil
end
-- "$A || !$B && $C": || of && terms; a term is [!]$NAME (KeyValues::EvaluateConditional)
function KeyValues.condition(cond: string, defines: { [string]: boolean }?): boolean
local d = defines or DEFAULT_DEFINES
local function flag(name: string): boolean
local l = string.lower(name)
for k, v in d do
if string.lower(k) == l then
return v == true
end
end
return false
end
local any = false
for alt in string.gmatch(cond .. "||", "(.-)||") do
local all = true
for term in string.gmatch(alt .. "&&", "(.-)&&") do
local neg, name = string.match(term, "^%s*(!?)%s*%$?([%w_]*)%s*$")
if not name then
all = false
else
local v = flag(name :: string)
if neg == "!" then
v = not v
end
all = all and v
end
end
any = any or all
end
return any
end
local function keyEq(a: string, b: string): boolean
return a == b or string.lower(a) == string.lower(b)
end
local function parseText(text: string, opts: ParseOptions?, depth0: number): (Block?, Err.Err?)
local o: ParseOptions = opts or {}
local lx: Lexer = { s = text, i = 1, n = #text, escapes = o.escapes ~= false }
if string.sub(text, 1, 3) == "\239\187\191" then
lx.i = 4
end
local defines: { [string]: boolean }? = nil
local evaluate = o.defines ~= false
if type(o.defines) == "table" then
defines = o.defines
end
local maxDepth = o.maxDepth or 256
local root: Block = {}
local stack: { Block } = { root }
local skipping = 0 -- depth inside a block whose condition failed
local canReplace = false
local includes: { { kind: string, name: string } } = {}
while true do
local kind, v, at, terr = token(lx)
if terr then
return nil, Err.new(Err.TRUNCATED, terr, at)
end
if kind == nil then
if #stack > 1 or skipping > 0 then
return nil, Err.new(Err.TRUNCATED, "unclosed block", at)
end
break
end
local cur = stack[#stack]
if kind == "}" then
if skipping > 0 then
skipping -= 1
elseif #stack == 1 then
return nil, Err.new(Err.CORRUPT, "unbalanced '}'", at)
else
table.remove(stack)
end
canReplace = false
elseif kind ~= "s" then
return nil, Err.new(Err.CORRUPT, if kind == "{" then "block without a key" else "condition without a key", at)
else
local key = v :: string
local k2, v2, at2, terr2 = token(lx)
if terr2 then
return nil, Err.new(Err.TRUNCATED, terr2, at2)
end
local cond: string? = nil
if k2 == "[" then
cond = v2
k2, v2, at2, terr2 = token(lx)
if terr2 then
return nil, Err.new(Err.TRUNCATED, terr2, at2)
end
if k2 ~= "{" then
return nil, Err.new(Err.CORRUPT, "a condition after a key needs a block", at2)
end
end
if k2 == "{" then
if #stack + skipping > maxDepth then
return nil, Err.new(Err.LIMIT, "nesting deeper than maxDepth", at2)
end
local pass = skipping == 0 and (cond == nil or not evaluate or KeyValues.condition(cond :: string, defines))
if not pass then
skipping += 1
else
local pair: Pair = { key = key, value = {}, cond = if evaluate then nil else cond }
local last = cur[#cur]
if cond and evaluate and canReplace and last and type(last.value) == "table" and last.key == key then
cur[#cur] = pair
else
table.insert(cur, pair)
end
table.insert(stack, pair.value :: Block)
end
canReplace = false
elseif k2 == "s" then
local value = v2 :: string
-- a condition after a value: only on the same line
local save = lx.i
local k3, v3 = token(lx)
local c3: string? = nil
if k3 == "[" and not string.find(string.sub(text, save, lx.i - 1), "\n", 1, true) then
c3 = v3
else
lx.i = save
end
if skipping == 0 then
local pass = c3 == nil or not evaluate or KeyValues.condition(c3 :: string, defines)
if pass then
local pair: Pair = { key = key, value = value, cond = if evaluate then nil else c3 }
local last = cur[#cur]
if c3 and evaluate and canReplace and last and type(last.value) == "string" and last.key == key then
cur[#cur] = pair
canReplace = false
else
table.insert(cur, pair)
canReplace = c3 == nil
end
if #stack == 1 and (key == "#include" or key == "#base") and o.resolve then
table.remove(cur)
table.insert(includes, { kind = key, name = value })
end
end
end
elseif k2 == nil then
return nil, Err.new(Err.TRUNCATED, "key without a value", at)
else
return nil, Err.new(Err.CORRUPT, "unexpected '" .. tostring(k2) .. "' after a key", at2)
end
end
end
if #includes > 0 then
if depth0 >= 16 then
return nil, Err.new(Err.LIMIT, "#include / #base nested more than 16 deep")
end
local resolve = o.resolve :: (string) -> (buffer | string)?
for _, inc in includes do
local ok, data = pcall(resolve, inc.name)
if not ok or data == nil then
return nil, Err.new(Err.IO, inc.kind .. ' "' .. inc.name .. '" not found')
end
local s = if type(data) == "buffer" then buffer.tostring(data) else tostring(data)
local sub, err = parseText(s, o, depth0 + 1)
if not sub then
return nil, Err.new((err :: Err.Err).code, inc.name .. ": " .. (err :: Err.Err).message)
end
if inc.kind == "#include" then
for _, p in sub do
table.insert(root, p)
end
else
KeyValues.merge(root, sub)
end
end
end
return root, nil
end
function KeyValues.parse(text: string | buffer, opts: ParseOptions?): (Block?, Err.Err?)
local s = if type(text) == "buffer" then buffer.tostring(text) else text
if type(s) ~= "string" then
return nil, Err.new(Err.ARG, "KeyValues.parse: expected a string or a buffer")
end
return parseText(s, opts, 0)
end
-- #base: keys of base missing from into are added; blocks present in both merge recursively (RecursiveMergeKeyValues)
function KeyValues.merge(into: Block, base: Block)
for _, bp in base do
local found: Pair? = nil
for _, p in into do
if keyEq(p.key, bp.key) then
found = p
break
end
end
if not found then
table.insert(into, KeyValues.copy({ bp })[1])
elseif type(found.value) == "table" and type(bp.value) == "table" then
KeyValues.merge(found.value :: Block, bp.value :: Block)
end
end
end
function KeyValues.copy(b: Block): Block
local out: Block = table.create(#b) :: any
for i, p in b do
local v: any = p.value
out[i] = { key = p.key, value = if type(v) == "table" then KeyValues.copy(v) else v, cond = p.cond, type = p.type }
end
return out
end
-- the first pair with this key (case-insensitive, as KeyValues::FindKey); "a/b/c" walks blocks
function KeyValues.find(b: Block, path: string): Pair?
local cur: Block? = b
local found: Pair? = nil
for part in string.gmatch(path, "[^/]+") do
if not cur then
return nil
end
found = nil
for _, p in cur do
if keyEq(p.key, part) then
found = p
break
end
end
if not found then
return nil
end
cur = if type(found.value) == "table" then found.value :: Block else nil
end
return found
end
function KeyValues.get(b: Block, path: string): any
local p = KeyValues.find(b, path)
return p and p.value
end
function KeyValues.all(b: Block, key: string): { Pair }
local out: { Pair } = {}
for _, p in b do
if keyEq(p.key, key) then
table.insert(out, p)
end
end
return out
end
local function quote(s: string, escapes: boolean): string
if escapes then
s = string.gsub(s, '[\\"\n\t\r]', { ["\\"] = "\\\\", ['"'] = '\\"', ["\n"] = "\\n", ["\t"] = "\\t", ["\r"] = "\\r" })
end
return '"' .. s .. '"'
end
local function writeBlock(b: Block, out: { string }, indent: string, level: number, escapes: boolean, depth: number): string?
if depth > 256 then
return "nesting deeper than 256"
end
local pad = string.rep(indent, level)
for _, p in b do
if type(p) ~= "table" or type(p.key) ~= "string" then
return "a pair needs a string key"
end
local v: any = p.value
local cond = if type(p.cond) == "string" then " [" .. p.cond .. "]" else ""
if type(v) == "table" then
table.insert(out, pad .. quote(p.key, escapes) .. cond .. "\n" .. pad .. "{\n")
local err = writeBlock(v, out, indent, level + 1, escapes, depth + 1)
if err then
return err
end
table.insert(out, pad .. "}\n")
elseif type(v) == "string" or type(v) == "number" or type(v) == "boolean" then
local s = if type(v) == "boolean" then (if v then "1" else "0") else tostring(v)
table.insert(out, pad .. quote(p.key, escapes) .. "\t" .. quote(s, escapes) .. cond .. "\n")
else
return "unwritable value for key " .. p.key
end
end
return nil
end
function KeyValues.write(b: Block, opts: WriteOptions?): (string?, Err.Err?)
if type(b) ~= "table" then
return nil, Err.new(Err.ARG, "KeyValues.write: expected a pair list")
end
local out: { string } = {}
local err = writeBlock(b, out, opts and opts.indent or "\t", 0, not (opts and opts.escapes == false), 0)
if err then
return nil, Err.new(Err.ARG, err)
end
return table.concat(out), nil
end
function KeyValues.toObject(b: Block, opts: ObjectOptions?): any
local mode = opts and opts.duplicates or "array"
local o = Types.object()
local multi: { [string]: boolean } = {}
for _, p in b do
local v: any = p.value
if type(v) == "table" then
v = KeyValues.toObject(v, opts)
end
local old = o[p.key]
if old == nil then
Types.set(o, p.key, v)
elseif mode == "last" then
o[p.key] = v
elseif mode == "array" then
if not multi[p.key] then
o[p.key] = { old }
multi[p.key] = true
end
table.insert(o[p.key], v)
end
end
return o
end
local function fromValue(key: string, v: any, out: Block, depth: number): string?
if depth > 256 then
return "nesting deeper than 256"
end
if type(v) == "table" and not Types.isObject(v) and Types.isArray(v, true) then
for _, x in v do
if type(x) == "table" and not Types.isObject(x) and Types.isArray(x, true) then
return "nested array under key " .. key
end
local err = fromValue(key, x, out, depth + 1)
if err then
return err
end
end
return nil
elseif type(v) == "table" then
local sub: Block = {}
local t: { [any]: any } = v :: any
for _, k in Types.keys(t) do
if type(k) ~= "string" and type(k) ~= "number" then
return "unwritable key"
end
local err = fromValue(tostring(k), t[k], sub, depth + 1)
if err then
return err
end
end
table.insert(out, { key = key, value = sub })
return nil
elseif type(v) == "string" or type(v) == "number" or type(v) == "boolean" then
table.insert(out, { key = key, value = if type(v) == "string" then v elseif type(v) == "boolean" then (if v then "1" else "0") else tostring(v) })
return nil
end
return "unwritable value for key " .. key
end
-- a Types.object / plain table -> pairs (arrays repeat their key; booleans become "1" / "0")
function KeyValues.fromObject(v: any): (Block?, Err.Err?)
if type(v) ~= "table" then
return nil, Err.new(Err.ARG, "KeyValues.fromObject: expected a table")
end
local out: Block = {}
for _, k in Types.keys(v) do
if type(k) ~= "string" and type(k) ~= "number" then
return nil, Err.new(Err.ARG, "unwritable key")
end
local err = fromValue(tostring(k), v[k], out, 0)
if err then
return nil, Err.new(Err.ARG, err)
end
end
return out, nil
end
-- pair list or object
function KeyValues.pairs(v: any): (Block?, Err.Err?)
if type(v) == "table" and not Types.isObject(v) and (#v > 0 or next(v) == nil) then
local first = v[1]
if first == nil or (type(first) == "table" and type(first.key) == "string") then
return v, nil
end
end
return KeyValues.fromObject(v)
end
-- BSP entity lump: { "k" "v" ... } blocks, no escapes (CMapEntities / ParseEntity)
function KeyValues.entities(text: string): ({ Block }?, Err.Err?)
text = string.match(text, "^[^%z]*") :: string
local lx: Lexer = { s = text, i = 1, n = #text, escapes = false }
local out: { Block } = {}
local cur: Block? = nil
while true do
local kind, v, at, terr = token(lx)
if terr then
return nil, Err.new(Err.TRUNCATED, terr, at)
end
if kind == nil then
if cur then
return nil, Err.new(Err.TRUNCATED, "unclosed entity", at)
end
return out, nil
elseif kind == "{" then
if cur then
return nil, Err.new(Err.CORRUPT, "'{' inside an entity", at)
end
cur = {}
elseif kind == "}" then
if not cur then
return nil, Err.new(Err.CORRUPT, "unbalanced '}'", at)
end
table.insert(out, cur :: Block)
cur = nil
elseif not cur then
return nil, Err.new(Err.CORRUPT, "key outside an entity", at)
else
local k2, v2, at2, terr2 = token(lx)
if terr2 then
return nil, Err.new(Err.TRUNCATED, terr2, at2)
end
if k2 ~= "s" then
return nil, Err.new(Err.CORRUPT, "entity key without a value", at)
end
table.insert(cur, { key = v :: string, value = v2 :: string })
end
end
end
function KeyValues.writeEntities(list: { Block }): (string?, Err.Err?)
local out: { string } = {}
for _, e in list do
table.insert(out, "{\n")
for _, p in e do
if type(p.value) ~= "string" then
return nil, Err.new(Err.ARG, "entity values are strings")
end
table.insert(out, '"' .. p.key .. '" "' .. (p.value :: string) .. '"\n')
end
table.insert(out, "}\n")
end
return table.concat(out), nil
end
KeyValues.readBinary = Binary.read
KeyValues.writeBinary = Binary.write
KeyValues.isBinary = Binary.sniff
return KeyValues