merge ws/sourcemdl: Source MDL v44-49 (+vvd/vtx/phy/ani, flexes, animations), VMT materials, codecs/model/SourceAnim
This commit is contained in:
commit
c19a68dfae
33 files changed
+14429
-1224
No files matched your search
@@ -896,7 +896,7 @@ local list: { Entry } = {
|
||||
path = "model/mdl",
|
||||
extensions = { "mdl" },
|
||||
mime = { "model/x-mdl" },
|
||||
deps = { "core/Err", "core/Bytes", "core/Input", "Types", "codecs/image/Pixels", "codecs/model/Mat4", "codecs/model/Rig" },
|
||||
deps = { "core/Err", "core/Bytes", "core/Input", "Types", "codecs/image/Pixels", "codecs/model/Mat4", "codecs/model/Rig", "codecs/model/SourceAnim" },
|
||||
caps = { decode = true, encode = false, variants = { "quake", "halflife" }, morph = true, skins = true, animation = true },
|
||||
load = function()
|
||||
return require("@rosetta/model/mdl")
|
||||
@@ -1034,6 +1034,18 @@ local list: { Entry } = {
|
||||
return require("@rosetta/model/smd")
|
||||
end,
|
||||
},
|
||||
{
|
||||
name = "sourcemdl",
|
||||
category = "model",
|
||||
path = "model/sourcemdl",
|
||||
extensions = { "mdl" },
|
||||
mime = { "model/x-source-mdl" },
|
||||
deps = { "core/Err", "core/Bytes", "core/Input", "Types", "codecs/image/Half", "codecs/model/Mat4", "codecs/model/Rig", "codecs/model/SourceAnim", "codecs/text/KeyValues" },
|
||||
caps = { decode = true, encode = false, skins = true, morph = true, animation = true, lods = true },
|
||||
load = function()
|
||||
return require("@rosetta/model/sourcemdl")
|
||||
end,
|
||||
},
|
||||
{
|
||||
name = "stl",
|
||||
category = "model",
|
||||
@@ -1730,6 +1742,18 @@ local list: { Entry } = {
|
||||
return require("@rosetta/data/toml")
|
||||
end,
|
||||
},
|
||||
{
|
||||
name = "vdf",
|
||||
category = "data",
|
||||
path = "data/vdf",
|
||||
extensions = { "vdf", "acf", "res", "kv" },
|
||||
mime = { "text/x-vdf" },
|
||||
deps = { "core/Err", "core/Bytes", "core/Sniff", "codecs/text/KeyValues" },
|
||||
caps = { decode = true, encode = true, ordered = true, binary = true },
|
||||
load = function()
|
||||
return require("@rosetta/data/vdf")
|
||||
end,
|
||||
},
|
||||
{
|
||||
name = "xml",
|
||||
category = "data",
|
||||
|
||||
@@ -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
|
||||
@@ -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
|
||||
@@ -0,0 +1,99 @@
|
||||
--!strict
|
||||
-- data/vdf: Valve KeyValues files (.vdf, .acf, .res, ...) as data over codecs/text/KeyValues, read and written; binary
|
||||
-- KeyValues (shortcuts.vdf) too. Values are ordered objects, a repeated key's values an array (opts.duplicates);
|
||||
-- opts.pairs gives the pair list with conditions and binary types. Not supported: appinfo.vdf / packageinfo.vdf headers.
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ requires
|
||||
local Err = require("@rosetta/core/Err")
|
||||
local Bytes = require("@rosetta/core/Bytes")
|
||||
local Sniff = require("@rosetta/core/Sniff")
|
||||
local KeyValues = require("@rosetta/codecs/text/KeyValues")
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ contract
|
||||
local Vdf = {
|
||||
name = "vdf",
|
||||
category = "data",
|
||||
extensions = { "vdf", "acf", "res", "kv" },
|
||||
mime = { "text/x-vdf" },
|
||||
deps = { "core/Err", "core/Bytes", "core/Sniff", "codecs/text/KeyValues" },
|
||||
caps = { decode = true, encode = true, ordered = true, binary = true },
|
||||
}
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ types
|
||||
export type DecodeOptions = {
|
||||
pairs: boolean?, -- the KeyValues pair list instead of an object
|
||||
duplicates: ("array" | "last" | "first")?, -- default "array"
|
||||
escapes: boolean?, -- default true
|
||||
defines: ({ [string]: boolean } | false)?, -- [$X] conditions (codecs/text/KeyValues), default PC
|
||||
resolve: ((name: string) -> (buffer | string)?)?, -- #include / #base
|
||||
binary: boolean?, -- force binary (default: sniffed)
|
||||
}
|
||||
export type EncodeOptions = {
|
||||
binary: boolean?, -- default false
|
||||
escapes: boolean?, -- default true
|
||||
indent: string?, -- default "\t"
|
||||
}
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ sniff
|
||||
function Vdf.sniff(r: Bytes.Reader): number
|
||||
local n = r:remaining()
|
||||
if KeyValues.isBinary(r.buf, r.pos, n) then
|
||||
return 0.3
|
||||
end
|
||||
local head = Sniff.text(r, 256, true)
|
||||
if string.find(head, "%z") then
|
||||
return 0
|
||||
end
|
||||
head = string.gsub(head, "^//[^\n]*\n%s*", "")
|
||||
if string.match(head, '^"[^"\n]+"%s*{') or string.match(head, '^"[^"\n]+"%s*%[[^%]\n]*%]%s*{') then
|
||||
return 0.6
|
||||
end
|
||||
if string.match(head, "^#base%s") or string.match(head, "^#include%s") then
|
||||
return 0.5
|
||||
end
|
||||
if string.match(head, '^[%w_]+%s*\n%s*{%s*\n%s*"') then
|
||||
return 0.3
|
||||
end
|
||||
return 0
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ decode
|
||||
function Vdf.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?)
|
||||
local o: DecodeOptions = opts or {}
|
||||
local n = r.limit - r.base
|
||||
local blk, err
|
||||
if o.binary or (o.binary == nil and KeyValues.isBinary(r.buf, r.base, n)) then
|
||||
blk, err = KeyValues.readBinary(r.buf, r.base, n)
|
||||
else
|
||||
blk, err = KeyValues.parse(buffer.readstring(r.buf, r.base, n), {
|
||||
escapes = o.escapes,
|
||||
defines = o.defines,
|
||||
resolve = o.resolve,
|
||||
})
|
||||
end
|
||||
if not blk then
|
||||
return nil, err
|
||||
end
|
||||
if o.pairs then
|
||||
return blk, nil
|
||||
end
|
||||
return KeyValues.toObject(blk, { duplicates = o.duplicates }), nil
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ encode
|
||||
function Vdf.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?)
|
||||
local blk, err = KeyValues.pairs(value)
|
||||
if not blk then
|
||||
return nil, err
|
||||
end
|
||||
if opts and opts.binary then
|
||||
return KeyValues.writeBinary(blk)
|
||||
end
|
||||
local s, werr = KeyValues.write(blk, { escapes = opts and opts.escapes, indent = opts and opts.indent })
|
||||
if not s then
|
||||
return nil, werr
|
||||
end
|
||||
return buffer.fromstring(s), nil
|
||||
end
|
||||
|
||||
return Vdf
|
||||
@@ -6,6 +6,7 @@ local Types = require("@rosetta/Types")
|
||||
local Mat4 = require("@rosetta/codecs/model/Mat4")
|
||||
local Pixels = require("@rosetta/codecs/image/Pixels")
|
||||
local Rig = require("@rosetta/codecs/model/Rig")
|
||||
local SourceAnim = require("@rosetta/codecs/model/SourceAnim")
|
||||
|
||||
local HalfLife = {}
|
||||
|
||||
@@ -44,31 +45,6 @@ local function textures(b: buffer, base: number, size: number, maxPixels: number
|
||||
return out, names
|
||||
end
|
||||
|
||||
-- bone default + stored value * scale
|
||||
local function animValue(b: buffer, at: number, limit: number, f: number): number?
|
||||
local p = at
|
||||
local k = f
|
||||
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 HalfLife.decode(b: buffer, base: number, size: number, opts: Options?): (Types.Scene?, string?)
|
||||
if size < 244 then
|
||||
return nil, "truncated header"
|
||||
@@ -293,7 +269,7 @@ function HalfLife.decode(b: buffer, base: number, size: number, opts: Options?):
|
||||
local v: { number } = {}
|
||||
for k = 0, 5 do
|
||||
local off = readu16(b, ao + k * 2)
|
||||
local raw = if off ~= 0 then animValue(b, ao + off, limit, f) else nil
|
||||
local raw = if off ~= 0 then SourceAnim.value(b, ao + off, limit, f) else nil
|
||||
v[k + 1] = bn.value[k + 1] + (raw or 0) * bn.scale[k + 1]
|
||||
end
|
||||
table.insert(tr, v[1])
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
--!strict
|
||||
-- model/mdl: Quake 1 ("IDPO" v6, model/mdl/Quake) and GoldSrc ("IDST" v10, model/mdl/HalfLife) models. Quake skins
|
||||
-- need gfx/palette.lmp (not redistributable, never built in; else a grey ramp). Not supported: Source MDL (v44+).
|
||||
-- need gfx/palette.lmp (not redistributable, never built in; else a grey ramp). Source MDL (v44+) is model/sourcemdl.
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ requires
|
||||
local Err = require("@rosetta/core/Err")
|
||||
@@ -16,7 +16,7 @@ local Mdl = {
|
||||
category = "model",
|
||||
extensions = { "mdl" },
|
||||
mime = { "model/x-mdl" },
|
||||
deps = { "core/Err", "core/Bytes", "core/Input", "Types", "codecs/image/Pixels", "codecs/model/Mat4", "codecs/model/Rig" },
|
||||
deps = { "core/Err", "core/Bytes", "core/Input", "Types", "codecs/image/Pixels", "codecs/model/Mat4", "codecs/model/Rig", "codecs/model/SourceAnim" },
|
||||
caps = { decode = true, encode = false, variants = { "quake", "halflife" }, morph = true, skins = true, animation = true },
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,428 @@
|
||||
--!strict
|
||||
-- model/sourcemdl/Build: the parsed MDL / VVD / VTX / PHY into a Scene: bones (poseToBone as inverse bind matrices),
|
||||
-- body part models as meshes (one primitive per studio mesh, LOD 0 indices; LODs 1+ in primitive extras), flexes as
|
||||
-- morph targets, attachments as nodes, animations through codecs/model/SourceAnim. Source front faces wind clockwise.
|
||||
local Types = require("@rosetta/Types")
|
||||
local Mat4 = require("@rosetta/codecs/model/Mat4")
|
||||
local Rig = require("@rosetta/codecs/model/Rig")
|
||||
local SourceAnim = require("@rosetta/codecs/model/SourceAnim")
|
||||
local Mdl = require("@rosetta/model/sourcemdl/Mdl")
|
||||
local Vvd = require("@rosetta/model/sourcemdl/Vvd")
|
||||
local Vtx = require("@rosetta/model/sourcemdl/Vtx")
|
||||
local Phy = require("@rosetta/model/sourcemdl/Phy")
|
||||
|
||||
local Build = {}
|
||||
|
||||
local Scene = Types.Scene
|
||||
local readf32, readu8, readi32, writef32, writeu16, writeu32 = buffer.readf32, buffer.readu8, buffer.readi32, buffer.writef32, buffer.writeu16, buffer.writeu32
|
||||
|
||||
export type Options = {
|
||||
bodies: { number }?, -- 1-based model per body part, default 1
|
||||
lod: number?, -- 1-based LOD for the primitives' indices, default 1
|
||||
animations: boolean?, -- default true
|
||||
maxVertices: number?,
|
||||
maxFrames: number?, -- per animation, default 65536
|
||||
}
|
||||
export type Inputs = { vvd: Vvd.Vertices?, vtx: Vtx.Strips?, phy: Phy.Physics?, ani: buffer?, warnings: { string } }
|
||||
|
||||
local STUDIO_DELTA, STUDIO_FRAMEANIM = 0x04, 0x40
|
||||
|
||||
local function u32s(list: { number }): Types.Accessor
|
||||
local b = buffer.create(#list * 4)
|
||||
for i, v in list do
|
||||
writeu32(b, (i - 1) * 4, v)
|
||||
end
|
||||
return Scene.accessor(b, "u32", 1, #list)
|
||||
end
|
||||
|
||||
local function reversed(tris: { number }, count: number): { number }?
|
||||
local out: { number } = {}
|
||||
for i = 1, #tris - 2, 3 do
|
||||
local a, b, c = tris[i], tris[i + 1], tris[i + 2]
|
||||
if a >= count or b >= count or c >= count then
|
||||
return nil
|
||||
end
|
||||
out[i], out[i + 1], out[i + 2] = c, b, a
|
||||
end
|
||||
return out
|
||||
end
|
||||
|
||||
local function qmul(a: { number }, b: { number }): { number }
|
||||
local ax, ay, az, aw = a[1], a[2], a[3], a[4]
|
||||
local bx, by, bz, bw = b[1], b[2], b[3], b[4]
|
||||
return { aw * bx + ax * bw + ay * bz - az * by, aw * by - ax * bz + ay * bw + az * bx, aw * bz + ax * by - ay * bx + az * bw, aw * bw - ax * bx - ay * by - az * bz }
|
||||
end
|
||||
|
||||
local function primitive(h: Mdl.Header, vvd: Vvd.Vertices, first: number, mesh: Mdl.Mesh, nBones: number): Types.Primitive
|
||||
local n = mesh.vertexCount
|
||||
local pos, nrm, uv = buffer.create(n * 12), buffer.create(n * 12), buffer.create(n * 8)
|
||||
local jb, wb = buffer.create(n * 8), buffer.create(n * 16)
|
||||
local src = vvd.data
|
||||
for i = 0, n - 1 do
|
||||
local o = (first + i) * 48
|
||||
local cnt = readu8(src, o + 15)
|
||||
for k = 0, 2 do
|
||||
if k < cnt then
|
||||
writef32(wb, i * 16 + k * 4, readf32(src, o + k * 4))
|
||||
writeu16(jb, i * 8 + k * 2, math.min(readu8(src, o + 12 + k), math.max(nBones - 1, 0)))
|
||||
end
|
||||
end
|
||||
for k = 0, 2 do
|
||||
writef32(pos, i * 12 + k * 4, readf32(src, o + 16 + k * 4))
|
||||
writef32(nrm, i * 12 + k * 4, readf32(src, o + 28 + k * 4))
|
||||
end
|
||||
writef32(uv, i * 8, readf32(src, o + 40))
|
||||
writef32(uv, i * 8 + 4, readf32(src, o + 44))
|
||||
end
|
||||
local attrs: { [string]: Types.Accessor } = {
|
||||
POSITION = Scene.accessor(pos, "f32", 3, n),
|
||||
NORMAL = Scene.accessor(nrm, "f32", 3, n),
|
||||
TEXCOORD_0 = Scene.accessor(uv, "f32", 2, n),
|
||||
}
|
||||
if nBones > 0 then
|
||||
attrs.JOINTS_0 = Scene.accessor(jb, "u16", 4, n)
|
||||
attrs.WEIGHTS_0 = Scene.accessor(wb, "f32", 4, n)
|
||||
end
|
||||
local tan = vvd.tangents
|
||||
if tan then
|
||||
local t = buffer.create(n * 16)
|
||||
buffer.copy(t, 0, tan, first * 16, n * 16)
|
||||
attrs.TANGENT = Scene.accessor(t, "f32", 4, n)
|
||||
end
|
||||
local fam = h.skins[1]
|
||||
local tex = if fam then fam[mesh.material + 1] else mesh.material
|
||||
return {
|
||||
attributes = attrs,
|
||||
mode = "triangles" :: any,
|
||||
material = if tex and tex >= 0 and tex < #h.textures then tex + 1 else nil,
|
||||
extras = { skinRef = mesh.material, materialType = mesh.materialType, materialParam = mesh.materialParam, id = mesh.id },
|
||||
}
|
||||
end
|
||||
|
||||
local function flexTargets(meshes: { Mdl.Mesh }, prims: { Types.Primitive }, names: { string }): { string }?
|
||||
local used: { [number]: boolean } = {}
|
||||
local order: { number } = {}
|
||||
for _, m in meshes do
|
||||
for _, f in m.flexes do
|
||||
for _, d in { f.desc, if f.partner > 0 then f.partner else -1 } do
|
||||
if d >= 0 and not used[d] then
|
||||
used[d] = true
|
||||
table.insert(order, d)
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
if #order == 0 then
|
||||
return nil
|
||||
end
|
||||
table.sort(order)
|
||||
local slot: { [number]: number } = {}
|
||||
for i, d in order do
|
||||
slot[d] = i
|
||||
end
|
||||
for k, m in meshes do
|
||||
local prim = prims[k]
|
||||
local n = m.vertexCount
|
||||
local targets: { { [string]: Types.Accessor } } = {}
|
||||
for i = 1, #order do
|
||||
targets[i] = { POSITION = Scene.accessor(nil, "f32", 3, n), NORMAL = Scene.accessor(nil, "f32", 3, n) }
|
||||
end
|
||||
for _, f in m.flexes do
|
||||
local stereo = f.partner > 0
|
||||
for _, d in f.deltas do
|
||||
local v = d[1]
|
||||
if v < n then
|
||||
for side = 0, if stereo then 1 else 0 do
|
||||
local w = if not stereo then 1 elseif side == 0 then d[8] else 1 - d[8]
|
||||
local t = targets[slot[if side == 0 then f.desc else f.partner]]
|
||||
if t and w ~= 0 then
|
||||
local pb, nb = t.POSITION.data, t.NORMAL.data
|
||||
for c = 0, 2 do
|
||||
writef32(pb, v * 12 + c * 4, readf32(pb, v * 12 + c * 4) + d[2 + c] * w)
|
||||
writef32(nb, v * 12 + c * 4, readf32(nb, v * 12 + c * 4) + d[5 + c] * w)
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
prim.targets = targets
|
||||
end
|
||||
local out = {}
|
||||
for i, d in order do
|
||||
out[i] = names[d + 1] or ("flex" .. d)
|
||||
end
|
||||
return out
|
||||
end
|
||||
|
||||
local function animate(scene: Types.Scene, h: Mdl.Header, b: buffer, base: number, size: number, inp: Inputs, jointNodes: { number }, opts: Options?)
|
||||
local bones: { SourceAnim.Bone } = h.bones :: any
|
||||
local maxFrames = opts and opts.maxFrames or 65536
|
||||
local firstSeq: { [number]: string } = {}
|
||||
for _, s in h.sequences do
|
||||
local a = s.anims[1]
|
||||
if a and a >= 0 and not firstSeq[a + 1] then
|
||||
firstSeq[a + 1] = s.name
|
||||
end
|
||||
end
|
||||
local list = {}
|
||||
for i, a in h.anims do
|
||||
local info: { [string]: any } = { name = a.name, fps = a.fps, frames = a.frames, flags = a.flags, delta = bit32.band(a.flags, STUDIO_DELTA) ~= 0 }
|
||||
list[i] = info
|
||||
local frames = a.frames
|
||||
if bit32.band(a.flags, STUDIO_FRAMEANIM) ~= 0 then
|
||||
info.skipped = "frame animation (v52+)"
|
||||
elseif frames <= 0 or frames > maxFrames then
|
||||
info.skipped = "frame count"
|
||||
elseif #bones == 0 then
|
||||
info.skipped = "no bones"
|
||||
else
|
||||
local function locate(block: number, index: number): (buffer?, number, number)
|
||||
if block == 0 then
|
||||
return b, base + a.at + index, base + size
|
||||
end
|
||||
local ani, blk = inp.ani, h.animBlocks[block + 1]
|
||||
if not ani or not blk then
|
||||
return nil, 0, 0
|
||||
end
|
||||
local lim = math.min(blk[2], buffer.len(ani))
|
||||
return ani, blk[1] + index, lim
|
||||
end
|
||||
local nSections = 0
|
||||
if a.sectionFrames > 0 and a.sectionIndex ~= 0 then
|
||||
nSections = frames // a.sectionFrames + 2
|
||||
local so = a.at + a.sectionIndex
|
||||
if so < 0 or so + nSections * 8 > size then
|
||||
info.skipped = "bad section table"
|
||||
nSections = -1
|
||||
end
|
||||
end
|
||||
local per: { [number]: { frames: number, block: number, index: number } } = {}
|
||||
local where: { { number } } = {}
|
||||
if nSections >= 0 then
|
||||
for f = 0, frames - 1 do
|
||||
local sec, loc = 0, f
|
||||
if nSections > 0 then
|
||||
if frames > a.sectionFrames and f == frames - 1 then
|
||||
sec, loc = frames // a.sectionFrames + 1, 0
|
||||
else
|
||||
sec = f // a.sectionFrames
|
||||
loc = f - sec * a.sectionFrames
|
||||
end
|
||||
end
|
||||
local e = per[sec]
|
||||
if not e then
|
||||
if nSections > 0 then
|
||||
local so = base + a.at + a.sectionIndex + sec * 8
|
||||
e = { frames = 0, block = readi32(b, so), index = readi32(b, so + 4) }
|
||||
else
|
||||
e = { frames = 0, block = a.block, index = a.index }
|
||||
end
|
||||
per[sec] = e
|
||||
end
|
||||
e.frames = math.max(e.frames, loc + 1)
|
||||
where[f + 1] = { sec, loc }
|
||||
end
|
||||
end
|
||||
local decoded: { [number]: { [number]: SourceAnim.Track } } = {}
|
||||
for sec, e in per do
|
||||
local src, at, lim = locate(e.block, e.index)
|
||||
if e.block < 0 or not src then
|
||||
info.skipped = if e.block < 0 then "missing animation block" else "animation block " .. e.block .. " not resolved (" .. h.animBlockName .. ")"
|
||||
break
|
||||
end
|
||||
local tr, err = SourceAnim.decode(src, at, lim, bones, e.frames)
|
||||
if not tr then
|
||||
info.skipped = err
|
||||
break
|
||||
end
|
||||
decoded[sec] = tr
|
||||
end
|
||||
if not info.skipped then
|
||||
local animated: { [number]: boolean } = {}
|
||||
for _, tr in decoded do
|
||||
for j in tr do
|
||||
animated[j] = true
|
||||
end
|
||||
end
|
||||
local fps = if a.fps > 0 then a.fps else 30
|
||||
local times = table.create(frames, 0)
|
||||
local tracks: { [number]: Rig.Track } = {}
|
||||
for j in animated do
|
||||
tracks[j] = { translation = table.create(frames * 3, 0), rotation = table.create(frames * 4, 0) }
|
||||
end
|
||||
local delta = info.delta
|
||||
for f = 0, frames - 1 do
|
||||
times[f + 1] = f / fps
|
||||
local w = where[f + 1]
|
||||
local tr = decoded[w[1]]
|
||||
for j, out in tracks do
|
||||
local bn = bones[j]
|
||||
local t = tr[j]
|
||||
local tt, rr = out.translation :: { number }, out.rotation :: { number }
|
||||
local px, py, pz, q
|
||||
if t then
|
||||
px, py, pz = t.pos[w[2] * 3 + 1], t.pos[w[2] * 3 + 2], t.pos[w[2] * 3 + 3]
|
||||
q = { t.rot[w[2] * 4 + 1], t.rot[w[2] * 4 + 2], t.rot[w[2] * 4 + 3], t.rot[w[2] * 4 + 4] }
|
||||
else
|
||||
px, py, pz, q = if delta then 0 else bn.pos[1], if delta then 0 else bn.pos[2], if delta then 0 else bn.pos[3], if delta then { 0, 0, 0, 1 } else bn.quat
|
||||
end
|
||||
if delta then
|
||||
px, py, pz = bn.pos[1] + px, bn.pos[2] + py, bn.pos[3] + pz
|
||||
q = qmul(bn.quat, q)
|
||||
end
|
||||
tt[f * 3 + 1], tt[f * 3 + 2], tt[f * 3 + 3] = px, py, pz
|
||||
for c = 1, 4 do
|
||||
rr[f * 4 + c] = q[c]
|
||||
end
|
||||
end
|
||||
end
|
||||
info.animation = Rig.animation(scene, firstSeq[i] or a.name, jointNodes, times, tracks, "LINEAR")
|
||||
end
|
||||
end
|
||||
end
|
||||
return list
|
||||
end
|
||||
|
||||
function Build.scene(h: Mdl.Header, b: buffer, base: number, size: number, inp: Inputs, opts: Options?): (Types.Scene?, string?)
|
||||
local scene = Scene.new()
|
||||
scene.meta.up = "z"
|
||||
local root: Types.Node = { name = h.name, children = {} }
|
||||
table.insert(scene.nodes, root)
|
||||
scene.roots[1] = 1
|
||||
local joints: { Rig.Joint } = {}
|
||||
for i, bn in h.bones do
|
||||
joints[i] = { name = bn.name, parent = bn.parent + 1, translation = table.clone(bn.pos), rotation = table.clone(bn.quat) }
|
||||
end
|
||||
local nBones = #h.bones
|
||||
local jointNodes, skinIndex = {}, nil
|
||||
if nBones > 0 then
|
||||
local nodes, si = Rig.skeleton(scene, joints, "local", 1)
|
||||
jointNodes, skinIndex = nodes, si
|
||||
local ibm = (scene.skins[si].inverseBindMatrices :: Types.Accessor).data
|
||||
for i, bn in h.bones do
|
||||
local m = Mat4.fromRows(bn.poseToBone)
|
||||
for k = 1, 16 do
|
||||
writef32(ibm, ((i - 1) * 16 + k - 1) * 4, m[k])
|
||||
end
|
||||
local ex: { [string]: any } = { bone = i - 1, flags = bn.flags, surfaceProp = bn.surfaceProp, contents = bn.contents, physicsBone = bn.physicsBone }
|
||||
if bn.procedural then
|
||||
ex.procedural = bn.procedural
|
||||
end
|
||||
scene.nodes[nodes[i]].extras = ex
|
||||
end
|
||||
end
|
||||
for _, t in h.textures do
|
||||
local mat = Scene.material(t.name)
|
||||
mat.metallic = 0
|
||||
table.insert(scene.materials, mat)
|
||||
end
|
||||
local vvd, vtx = inp.vvd, inp.vtx
|
||||
local lodPick = math.max(1, opts and opts.lod or 1)
|
||||
local bodyInfo = {}
|
||||
for p, part in h.bodyParts do
|
||||
local pick = (opts and opts.bodies and opts.bodies[p]) or 1
|
||||
local info = { name = part.name, base = part.base, models = {}, selected = pick }
|
||||
bodyInfo[p] = info
|
||||
for m, model in part.models do
|
||||
local minfo: { [string]: any } = { name = model.name, vertices = model.vertexCount, eyeballs = model.eyeballs }
|
||||
info.models[m] = minfo
|
||||
local vlods = vtx and vtx.parts[p] and vtx.parts[p][m]
|
||||
if #model.meshes > 0 and vvd and vlods and #vlods > 0 then
|
||||
local first = model.vertexIndex // 48
|
||||
if first + model.vertexCount > vvd.count then
|
||||
return nil, "model " .. model.name .. ": vertices outside the vvd"
|
||||
end
|
||||
local mesh: Types.Mesh = { name = model.name, primitives = {}, extras = { bodyPart = part.name, lods = #vlods } }
|
||||
for k, sm in model.meshes do
|
||||
local prim = primitive(h, vvd, first + sm.vertexOffset, sm, nBones)
|
||||
local lods = {}
|
||||
for l, lod in vlods do
|
||||
local vm = lod.meshes[k]
|
||||
local idx = if vm then reversed(vm.indices, sm.vertexCount) else {}
|
||||
if not idx then
|
||||
return nil, "vtx index outside mesh " .. (k - 1) .. " of " .. model.name
|
||||
end
|
||||
lods[l] = { indices = u32s(idx), switchPoint = lod.switchPoint }
|
||||
end
|
||||
local use = lods[math.min(lodPick, #lods)]
|
||||
prim.indices = use.indices
|
||||
local ex = prim.extras :: { [string]: any }
|
||||
ex.lods = lods
|
||||
table.insert(mesh.primitives, prim)
|
||||
end
|
||||
local names = flexTargets(model.meshes, mesh.primitives, h.flexDescs)
|
||||
if names then
|
||||
mesh.weights = table.create(#names, 0)
|
||||
local mex = mesh.extras :: { [string]: any }
|
||||
mex.targetNames = names
|
||||
end
|
||||
table.insert(scene.meshes, mesh)
|
||||
minfo.mesh = #scene.meshes
|
||||
if m == pick then
|
||||
table.insert(scene.nodes, { name = part.name, children = {}, mesh = #scene.meshes, skin = skinIndex })
|
||||
table.insert(root.children, #scene.nodes)
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
local attachments = {}
|
||||
for i, a in h.attachments do
|
||||
local t, r, s = Mat4.decompose(Mat4.fromRows(a.matrix))
|
||||
local node: Types.Node = { name = a.name, children = {}, translation = t, rotation = r, scale = if math.abs(s[1] - 1) + math.abs(s[2] - 1) + math.abs(s[3] - 1) > 1e-5 then s else nil, extras = { attachment = i - 1, flags = a.flags } }
|
||||
table.insert(scene.nodes, node)
|
||||
local parent = jointNodes[a.bone + 1]
|
||||
table.insert(scene.nodes[parent or 1].children, #scene.nodes)
|
||||
attachments[i] = { name = a.name, bone = a.bone, flags = a.flags, node = #scene.nodes }
|
||||
end
|
||||
local anims = if opts and opts.animations == false then {} else animate(scene, h, b, base, size, inp, jointNodes, opts)
|
||||
local skins = {}
|
||||
for f, fam in h.skins do
|
||||
local list = {}
|
||||
for r, t in fam do
|
||||
list[r] = t + 1
|
||||
end
|
||||
skins[f] = list
|
||||
end
|
||||
local phy = inp.phy
|
||||
scene.meta.source = {
|
||||
format = "sourcemdl",
|
||||
version = h.version,
|
||||
checksum = h.checksum,
|
||||
name = h.name,
|
||||
flags = h.flags,
|
||||
eye = h.eye,
|
||||
illum = h.illum,
|
||||
hull = { h.hullMin, h.hullMax },
|
||||
view = { h.viewMin, h.viewMax },
|
||||
mass = h.mass,
|
||||
contents = h.contents,
|
||||
surfaceProp = h.surfaceProp,
|
||||
keyValues = h.keyValues,
|
||||
cdmaterials = h.cdmaterials,
|
||||
textures = h.textures,
|
||||
skins = skins,
|
||||
bodyParts = bodyInfo,
|
||||
attachments = attachments,
|
||||
hitboxSets = h.hitboxSets,
|
||||
boneControllers = h.controllers,
|
||||
sequences = h.sequences,
|
||||
animations = anims,
|
||||
poseParameters = h.poseParameters,
|
||||
flexDescs = h.flexDescs,
|
||||
flexControllers = h.flexControllers,
|
||||
flexRules = h.flexRules,
|
||||
includeModels = h.includeModels,
|
||||
animBlockName = h.animBlockName,
|
||||
nodes = h.nodes,
|
||||
rootLod = h.rootLod,
|
||||
lods = if vtx then vtx.lods else 0,
|
||||
lodVertices = if vvd then vvd.lodCounts else nil,
|
||||
lodReplacements = if vtx then vtx.replacements else nil,
|
||||
physics = phy,
|
||||
warnings = inp.warnings,
|
||||
}
|
||||
return scene, nil
|
||||
end
|
||||
|
||||
return Build
|
||||
@@ -0,0 +1,159 @@
|
||||
--!strict
|
||||
-- model/sourcemdl/Material: the MDL's texture names through $cdmaterials to materials/<dir><name>.vmt (the engine's
|
||||
-- search order, then the bare name), parsed with codecs/text/KeyValues; "patch" materials (include + insert /
|
||||
-- replace) applied. $basetexture / $bumpmap ($normalmap) become .vtf texture references for F.model.loadTextures;
|
||||
-- $translucent / $alphatest / $nocull / $color map to the PBR fields, every parameter is kept in extras.vmt.
|
||||
local Types = require("@rosetta/Types")
|
||||
local Input = require("@rosetta/core/Input")
|
||||
local KeyValues = require("@rosetta/codecs/text/KeyValues")
|
||||
|
||||
local Material = {}
|
||||
|
||||
local function dir(s: string): string
|
||||
local d: string = string.gsub(string.gsub(s, "\\", "/"), "^/+", "")
|
||||
return if d ~= "" and string.sub(d, -1) ~= "/" then d .. "/" else d
|
||||
end
|
||||
|
||||
local function path(s: string): string
|
||||
local p = string.gsub(string.gsub(s, "\\", "/"), "^/+", "")
|
||||
return (string.gsub(p, "%.[vV][mMtT][tTfF]$", ""))
|
||||
end
|
||||
|
||||
local function load(opts: any, uri: string): (string, KeyValues.Block?)
|
||||
local b = Input.sibling(opts, uri) or Input.sibling(opts, string.lower(uri))
|
||||
if not b then
|
||||
return uri, nil
|
||||
end
|
||||
local kv = KeyValues.parse(b, { escapes = false, resolve = function(name: string): (buffer | string)?
|
||||
return Input.sibling(opts, name)
|
||||
end })
|
||||
return uri, kv
|
||||
end
|
||||
|
||||
-- { shader, params (lower-case keys) } of a parsed .vmt, patch includes applied (depth 8)
|
||||
local function flatten(opts: any, kv: KeyValues.Block, depth: number): (string?, { [string]: any })
|
||||
local first = kv[1]
|
||||
if not first or type(first.value) ~= "table" then
|
||||
return nil, {}
|
||||
end
|
||||
local shader, body = first.key, first.value :: KeyValues.Block
|
||||
local params: { [string]: any } = {}
|
||||
if string.lower(shader) == "patch" and depth < 8 then
|
||||
local inc = KeyValues.get(body, "include")
|
||||
local base: KeyValues.Block? = nil
|
||||
if type(inc) == "string" then
|
||||
local _, b = load(opts, path(inc) .. ".vmt")
|
||||
base = b
|
||||
end
|
||||
if base then
|
||||
shader, params = flatten(opts, base, depth + 1)
|
||||
end
|
||||
for _, p in body do
|
||||
local k = string.lower(p.key)
|
||||
if (k == "insert" or k == "replace") and type(p.value) == "table" then
|
||||
for _, q in p.value :: KeyValues.Block do
|
||||
local qk = string.lower(q.key)
|
||||
if k == "insert" or params[qk] ~= nil then
|
||||
params[qk] = if q.value == "" then nil else q.value
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
return shader, params
|
||||
end
|
||||
for _, p in body do
|
||||
params[string.lower(p.key)] = p.value
|
||||
end
|
||||
return shader, params
|
||||
end
|
||||
|
||||
local function num(v: any): number?
|
||||
return if type(v) == "number" then v elseif type(v) == "string" then tonumber(v) else nil
|
||||
end
|
||||
|
||||
local function color(v: any): { number }?
|
||||
if type(v) ~= "string" then
|
||||
return nil
|
||||
end
|
||||
local r, g, b = string.match(v, "^%s*[%[{]%s*([%d.eE+-]+)%s+([%d.eE+-]+)%s+([%d.eE+-]+)")
|
||||
if not r then
|
||||
return nil
|
||||
end
|
||||
local scale = if string.match(v, "^%s*{") then 1 / 255 else 1
|
||||
return { (tonumber(r) :: number) * scale, (tonumber(g) :: number) * scale, (tonumber(b) :: number) * scale }
|
||||
end
|
||||
|
||||
function Material.apply(scene: Types.Scene, textures: { any }, cdmaterials: { string }, opts: any?, warnings: { string })
|
||||
if type(opts) ~= "table" or (opts.files == nil and opts.resolve == nil) then
|
||||
return
|
||||
end
|
||||
local dirs: { string } = {}
|
||||
for _, d in cdmaterials do
|
||||
local nd = dir(d)
|
||||
if not table.find(dirs, nd) then
|
||||
table.insert(dirs, nd)
|
||||
end
|
||||
end
|
||||
if not table.find(dirs, "") then
|
||||
table.insert(dirs, "")
|
||||
end
|
||||
local texIndex: { [string]: number } = {}
|
||||
local function texture(v: any): number?
|
||||
if type(v) ~= "string" or v == "" then
|
||||
return nil
|
||||
end
|
||||
local uri = "materials/" .. path(v) .. ".vtf"
|
||||
local i = texIndex[string.lower(uri)]
|
||||
if not i then
|
||||
table.insert(scene.textures, { name = path(v), uri = uri, mime = "image/x-vtf" })
|
||||
i = #scene.textures
|
||||
texIndex[string.lower(uri)] = i
|
||||
end
|
||||
return i
|
||||
end
|
||||
for i, t in textures do
|
||||
local mat = scene.materials[i]
|
||||
local name = path(t.name)
|
||||
local found, kv = nil, nil
|
||||
for _, d in dirs do
|
||||
local uri, b = load(opts, "materials/" .. d .. name .. ".vmt")
|
||||
if b then
|
||||
found, kv = uri, b
|
||||
break
|
||||
end
|
||||
end
|
||||
if not kv then
|
||||
table.insert(warnings, "material " .. t.name .. ": no .vmt")
|
||||
continue
|
||||
end
|
||||
local shader, p = flatten(opts, kv, 0)
|
||||
local ex: { [string]: any } = mat.extras or {}
|
||||
mat.extras = ex
|
||||
ex.vmt = { path = found, shader = shader, params = p }
|
||||
local base = texture(p["$basetexture"])
|
||||
if base then
|
||||
mat.baseColorTexture = { texture = base }
|
||||
end
|
||||
local bump = texture(p["$bumpmap"] or p["$normalmap"])
|
||||
if bump then
|
||||
mat.normalTexture = { texture = bump }
|
||||
end
|
||||
local c = color(p["$color2"]) or color(p["$color"])
|
||||
if c then
|
||||
mat.baseColor = { c[1], c[2], c[3], num(p["$alpha"]) or 1 }
|
||||
elseif num(p["$alpha"]) then
|
||||
mat.baseColor[4] = num(p["$alpha"]) :: number
|
||||
end
|
||||
if num(p["$translucent"]) == 1 then
|
||||
mat.alphaMode = "blend"
|
||||
elseif num(p["$alphatest"]) == 1 then
|
||||
mat.alphaMode = "mask"
|
||||
mat.alphaCutoff = num(p["$alphatestreference"]) or 0.5
|
||||
end
|
||||
if num(p["$nocull"]) == 1 then
|
||||
mat.doubleSided = true
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
return Material
|
||||
@@ -0,0 +1,525 @@
|
||||
--!strict
|
||||
-- model/sourcemdl/Mdl: the studiohdr_t tables of Source MDL v44-49 (Source SDK 2013 public/studio.h layouts, SourceIO
|
||||
-- (MIT) and srctools (MIT) notes; no code taken). Geometry lives in the .vvd / .vtx files.
|
||||
local Half = require("@rosetta/codecs/image/Half")
|
||||
|
||||
local Mdl = {}
|
||||
|
||||
local readi32, readu32, readi16, readu16, readu8, readf32 = buffer.readi32, buffer.readu32, buffer.readi16, buffer.readu16, buffer.readu8, buffer.readf32
|
||||
local HALF = Half.TABLE
|
||||
|
||||
export type Bone = {
|
||||
name: string,
|
||||
parent: number, -- 0-based, -1 = none
|
||||
pos: { number },
|
||||
quat: { number },
|
||||
rot: { number },
|
||||
posScale: { number },
|
||||
rotScale: { number },
|
||||
poseToBone: { number }, -- 3x4 rows
|
||||
flags: number,
|
||||
contents: number,
|
||||
surfaceProp: string,
|
||||
physicsBone: number,
|
||||
controllers: { number },
|
||||
procedural: { [string]: any }?,
|
||||
}
|
||||
export type Flex = {
|
||||
desc: number, -- 0-based flexdesc
|
||||
partner: number,
|
||||
targets: { number },
|
||||
kind: number, -- 0 normal, 1 wrinkle
|
||||
deltas: { { number } }, -- { index (mesh vertex), dx, dy, dz, nx, ny, nz, side, speed, wrinkle }
|
||||
}
|
||||
export type Mesh = { material: number, vertexOffset: number, vertexCount: number, materialType: number, materialParam: number, id: number, center: { number }, flexes: { Flex }, lodVertices: { number } }
|
||||
export type Model = { name: string, kind: number, radius: number, vertexIndex: number, vertexCount: number, tangentIndex: number, meshes: { Mesh }, eyeballs: number }
|
||||
export type BodyPart = { name: string, base: number, models: { Model } }
|
||||
export type AnimDesc = { name: string, fps: number, flags: number, frames: number, block: number, index: number, sectionIndex: number, sectionFrames: number, at: number, movements: number, ikRules: number }
|
||||
export type Header = {
|
||||
version: number,
|
||||
checksum: number,
|
||||
name: string,
|
||||
length: number,
|
||||
eye: { number },
|
||||
illum: { number },
|
||||
hullMin: { number },
|
||||
hullMax: { number },
|
||||
viewMin: { number },
|
||||
viewMax: { number },
|
||||
flags: number,
|
||||
bones: { Bone },
|
||||
controllers: { any },
|
||||
hitboxSets: { any },
|
||||
anims: { AnimDesc },
|
||||
sequences: { any },
|
||||
textures: { { name: string, flags: number } },
|
||||
cdmaterials: { string },
|
||||
skins: { { number } }, -- families of 0-based texture indices per skin reference
|
||||
skinRefs: number,
|
||||
bodyParts: { BodyPart },
|
||||
attachments: { any },
|
||||
flexDescs: { string },
|
||||
flexControllers: { any },
|
||||
flexRules: { any },
|
||||
poseParameters: { any },
|
||||
includeModels: { any },
|
||||
surfaceProp: string,
|
||||
keyValues: string,
|
||||
mass: number,
|
||||
contents: number,
|
||||
animBlockName: string,
|
||||
animBlocks: { { number } }, -- { datastart, dataend }
|
||||
vertAnimScale: number,
|
||||
rootLod: number,
|
||||
allowedRootLods: number,
|
||||
ikChains: number,
|
||||
nodes: { string },
|
||||
}
|
||||
|
||||
local PROCEDURAL = { "axisinterp", "quatinterp", "aimatbone", "aimatattach", "jiggle" }
|
||||
local JIGGLE = {
|
||||
"length", "tipMass", "yawStiffness", "yawDamping", "pitchStiffness", "pitchDamping", "alongStiffness", "alongDamping",
|
||||
"angleLimit", "minYaw", "maxYaw", "yawFriction", "yawBounce", "minPitch", "maxPitch", "pitchFriction", "pitchBounce",
|
||||
"baseMass", "baseStiffness", "baseDamping", "baseMinLeft", "baseMaxLeft", "baseLeftFriction", "baseMinUp", "baseMaxUp",
|
||||
"baseUpFriction", "baseMinForward", "baseMaxForward", "baseForwardFriction",
|
||||
}
|
||||
|
||||
function Mdl.parse(b: buffer, base: number, size: number, opts: { maxVertices: number? }?): (Header?, string?)
|
||||
if size < 408 then
|
||||
return nil, "truncated header"
|
||||
end
|
||||
local function i32(o: number): number
|
||||
return readi32(b, base + o)
|
||||
end
|
||||
local function inside(o: number, n: number): boolean
|
||||
return o >= 0 and n >= 0 and o + n <= size
|
||||
end
|
||||
local function table_(count: number, at: number, stride: number, max: number, what: string): string?
|
||||
if count < 0 or count > max or (count > 0 and not inside(at, count * stride)) then
|
||||
return "bad " .. what .. " table"
|
||||
end
|
||||
return nil
|
||||
end
|
||||
local function str(o: number): string
|
||||
if o < 0 or o >= size then
|
||||
return ""
|
||||
end
|
||||
local n = math.min(size - o, 4096)
|
||||
return (string.match(buffer.readstring(b, base + o, n), "^[^%z]*")) :: string
|
||||
end
|
||||
local function vec(o: number, n: number?): { number }
|
||||
local v = {}
|
||||
for k = 0, (n or 3) - 1 do
|
||||
v[k + 1] = readf32(b, base + o + k * 4)
|
||||
end
|
||||
return v
|
||||
end
|
||||
local h: any = {
|
||||
version = i32(4),
|
||||
checksum = readu32(b, base + 8),
|
||||
name = (string.match(buffer.readstring(b, base + 12, 64), "^[^%z]*")) :: string,
|
||||
length = i32(76),
|
||||
eye = vec(80),
|
||||
illum = vec(92),
|
||||
hullMin = vec(104),
|
||||
hullMax = vec(116),
|
||||
viewMin = vec(128),
|
||||
viewMax = vec(140),
|
||||
flags = readu32(b, base + 152),
|
||||
mass = readf32(b, base + 328),
|
||||
contents = i32(332),
|
||||
rootLod = readu8(b, base + 377),
|
||||
allowedRootLods = readu8(b, base + 378),
|
||||
vertAnimScale = readf32(b, base + 392),
|
||||
ikChains = i32(284),
|
||||
}
|
||||
local hdr2 = i32(400)
|
||||
if hdr2 > 0 and inside(hdr2, 24) then
|
||||
local long = readi32(b, base + hdr2 + 20)
|
||||
if long > 0 then
|
||||
local s = str(hdr2 + long)
|
||||
if s ~= "" then
|
||||
h.name = s
|
||||
end
|
||||
end
|
||||
end
|
||||
local nBones, oBones = i32(156), i32(160)
|
||||
local e = table_(nBones, oBones, 216, 4096, "bone")
|
||||
if e then
|
||||
return nil, e
|
||||
end
|
||||
h.bones = {}
|
||||
for i = 0, nBones - 1 do
|
||||
local o = oBones + i * 216
|
||||
local bone: Bone = {
|
||||
name = str(o + i32(o)),
|
||||
parent = i32(o + 4),
|
||||
controllers = {},
|
||||
pos = vec(o + 32),
|
||||
quat = vec(o + 44, 4),
|
||||
rot = vec(o + 60),
|
||||
posScale = vec(o + 72),
|
||||
rotScale = vec(o + 84),
|
||||
poseToBone = vec(o + 96, 12),
|
||||
flags = readu32(b, base + o + 160),
|
||||
physicsBone = i32(o + 172),
|
||||
surfaceProp = str(o + i32(o + 176)),
|
||||
contents = i32(o + 180),
|
||||
}
|
||||
for k = 0, 5 do
|
||||
bone.controllers[k + 1] = i32(o + 8 + k * 4)
|
||||
end
|
||||
if bone.parent < -1 or bone.parent >= i then
|
||||
return nil, "bone " .. i .. ": bad parent"
|
||||
end
|
||||
local ptype, pidx = i32(o + 164), i32(o + 168)
|
||||
if ptype > 0 and pidx ~= 0 then
|
||||
local po = o + pidx
|
||||
local rule: { [string]: any } = { type = PROCEDURAL[ptype] or ptype }
|
||||
if ptype == 1 and inside(po, 176) then
|
||||
rule.control = i32(po)
|
||||
rule.axis = i32(po + 4)
|
||||
rule.pos, rule.quat = {}, {}
|
||||
for k = 0, 5 do
|
||||
rule.pos[k + 1] = vec(po + 8 + k * 12)
|
||||
rule.quat[k + 1] = vec(po + 80 + k * 16, 4)
|
||||
end
|
||||
elseif ptype == 2 and inside(po, 12) then
|
||||
rule.control = i32(po)
|
||||
local n, t = i32(po + 4), i32(po + 8)
|
||||
rule.triggers = {}
|
||||
if n > 0 and n <= 256 and inside(po + t, n * 48) then
|
||||
for k = 0, n - 1 do
|
||||
local to = po + t + k * 48
|
||||
rule.triggers[k + 1] = { invTolerance = readf32(b, base + to), trigger = vec(to + 4, 4), pos = vec(to + 20), quat = vec(to + 32, 4) }
|
||||
end
|
||||
end
|
||||
elseif (ptype == 3 or ptype == 4) and inside(po, 44) then
|
||||
rule.parent = i32(po)
|
||||
rule.aim = i32(po + 4)
|
||||
rule.aimVector = vec(po + 8)
|
||||
rule.upVector = vec(po + 20)
|
||||
rule.basePos = vec(po + 32)
|
||||
elseif ptype == 5 and inside(po, 120) then
|
||||
rule.flags = i32(po)
|
||||
for k, key in JIGGLE do
|
||||
rule[key] = readf32(b, base + po + k * 4)
|
||||
end
|
||||
end
|
||||
bone.procedural = rule
|
||||
end
|
||||
h.bones[i + 1] = bone
|
||||
end
|
||||
local nCtl, oCtl = i32(164), i32(168)
|
||||
e = table_(nCtl, oCtl, 56, 4096, "bone controller")
|
||||
if e then
|
||||
return nil, e
|
||||
end
|
||||
h.controllers = {}
|
||||
for i = 0, nCtl - 1 do
|
||||
local o = oCtl + i * 56
|
||||
h.controllers[i + 1] = { bone = i32(o), type = i32(o + 4), start = readf32(b, base + o + 8), ["end"] = readf32(b, base + o + 12), rest = i32(o + 16), input = i32(o + 20) }
|
||||
end
|
||||
local nSets, oSets = i32(172), i32(176)
|
||||
e = table_(nSets, oSets, 12, 256, "hitbox set")
|
||||
if e then
|
||||
return nil, e
|
||||
end
|
||||
h.hitboxSets = {}
|
||||
for i = 0, nSets - 1 do
|
||||
local o = oSets + i * 12
|
||||
local n, at = i32(o + 4), i32(o + 8)
|
||||
local set = { name = str(o + i32(o)), boxes = {} }
|
||||
if n > 0 and n <= 65536 and inside(o + at, n * 68) then
|
||||
for k = 0, n - 1 do
|
||||
local bo = o + at + k * 68
|
||||
local nameOff = i32(bo + 32)
|
||||
table.insert(set.boxes, { bone = i32(bo), group = i32(bo + 4), min = vec(bo + 8), max = vec(bo + 20), name = if nameOff ~= 0 then str(bo + nameOff) else "" })
|
||||
end
|
||||
end
|
||||
h.hitboxSets[i + 1] = set
|
||||
end
|
||||
local nAnim, oAnim = i32(180), i32(184)
|
||||
e = table_(nAnim, oAnim, 100, 65536, "animation")
|
||||
if e then
|
||||
return nil, e
|
||||
end
|
||||
h.anims = {}
|
||||
for i = 0, nAnim - 1 do
|
||||
local o = oAnim + i * 100
|
||||
h.anims[i + 1] = {
|
||||
at = o,
|
||||
name = str(o + i32(o + 4)),
|
||||
fps = readf32(b, base + o + 8),
|
||||
flags = i32(o + 12),
|
||||
frames = i32(o + 16),
|
||||
movements = i32(o + 20),
|
||||
block = i32(o + 52),
|
||||
index = i32(o + 56),
|
||||
ikRules = i32(o + 60),
|
||||
sectionIndex = i32(o + 80),
|
||||
sectionFrames = i32(o + 84),
|
||||
}
|
||||
end
|
||||
local nSeq, oSeq = i32(188), i32(192)
|
||||
e = table_(nSeq, oSeq, 212, 65536, "sequence")
|
||||
if e then
|
||||
return nil, e
|
||||
end
|
||||
h.sequences = {}
|
||||
for i = 0, nSeq - 1 do
|
||||
local o = oSeq + i * 212
|
||||
local g0, g1 = i32(o + 68), i32(o + 72)
|
||||
local anims = {}
|
||||
local ai = i32(o + 60)
|
||||
if g0 > 0 and g1 > 0 and g0 * g1 <= 4096 and inside(o + ai, g0 * g1 * 2) then
|
||||
for k = 0, g0 * g1 - 1 do
|
||||
anims[k + 1] = readi16(b, base + o + ai + k * 2)
|
||||
end
|
||||
end
|
||||
local events = {}
|
||||
local ne, eo = i32(o + 24), i32(o + 28)
|
||||
if ne > 0 and ne <= 4096 and inside(o + eo, ne * 80) then
|
||||
for k = 0, ne - 1 do
|
||||
local ev = o + eo + k * 80
|
||||
local nameOff = i32(ev + 76)
|
||||
table.insert(events, {
|
||||
cycle = readf32(b, base + ev),
|
||||
event = i32(ev + 4),
|
||||
type = i32(ev + 8),
|
||||
options = (string.match(buffer.readstring(b, base + ev + 12, 64), "^[^%z]*")) :: string,
|
||||
name = if nameOff ~= 0 then str(ev + nameOff) else "",
|
||||
})
|
||||
end
|
||||
end
|
||||
local kvSize = i32(o + 176)
|
||||
h.sequences[i + 1] = {
|
||||
name = str(o + i32(o + 4)),
|
||||
activity = str(o + i32(o + 8)),
|
||||
flags = i32(o + 12),
|
||||
activityId = i32(o + 16),
|
||||
weight = i32(o + 20),
|
||||
events = events,
|
||||
bboxMin = vec(o + 32),
|
||||
bboxMax = vec(o + 44),
|
||||
blends = i32(o + 56),
|
||||
groupSize = { g0, g1 },
|
||||
anims = anims,
|
||||
paramIndex = { i32(o + 76), i32(o + 80) },
|
||||
paramStart = vec(o + 84, 2),
|
||||
paramEnd = vec(o + 92, 2),
|
||||
fadeIn = readf32(b, base + o + 104),
|
||||
fadeOut = readf32(b, base + o + 108),
|
||||
nextSequence = i32(o + 136),
|
||||
keyValues = if kvSize > 0 then str(o + i32(o + 172)) else "",
|
||||
}
|
||||
end
|
||||
local nTex, oTex = i32(204), i32(208)
|
||||
e = table_(nTex, oTex, 64, 65536, "texture")
|
||||
if e then
|
||||
return nil, e
|
||||
end
|
||||
h.textures = {}
|
||||
for i = 0, nTex - 1 do
|
||||
local o = oTex + i * 64
|
||||
h.textures[i + 1] = { name = str(o + i32(o)), flags = i32(o + 4) }
|
||||
end
|
||||
local nCd, oCd = i32(212), i32(216)
|
||||
e = table_(nCd, oCd, 4, 4096, "cdmaterials")
|
||||
if e then
|
||||
return nil, e
|
||||
end
|
||||
h.cdmaterials = {}
|
||||
for i = 0, nCd - 1 do
|
||||
h.cdmaterials[i + 1] = str(i32(oCd + i * 4))
|
||||
end
|
||||
local nRef, nFam, oSkin = i32(220), i32(224), i32(228)
|
||||
if nRef < 0 or nFam < 0 or nRef * nFam > 1048576 or (nRef * nFam > 0 and not inside(oSkin, nRef * nFam * 2)) then
|
||||
return nil, "bad skin table"
|
||||
end
|
||||
h.skins, h.skinRefs = {}, nRef
|
||||
for f = 0, nFam - 1 do
|
||||
local fam = {}
|
||||
for r = 0, nRef - 1 do
|
||||
fam[r + 1] = readi16(b, base + oSkin + (f * nRef + r) * 2)
|
||||
end
|
||||
h.skins[f + 1] = fam
|
||||
end
|
||||
local nParts, oParts = i32(232), i32(236)
|
||||
e = table_(nParts, oParts, 16, 4096, "body part")
|
||||
if e then
|
||||
return nil, e
|
||||
end
|
||||
local maxVerts = opts and opts.maxVertices or 2 ^ 24
|
||||
local totalFlex = 0
|
||||
h.bodyParts = {}
|
||||
for p = 0, nParts - 1 do
|
||||
local po = oParts + p * 16
|
||||
local nModels, oModels = i32(po + 4), i32(po + 12)
|
||||
local part: BodyPart = { name = str(po + i32(po)), base = i32(po + 8), models = {} }
|
||||
if nModels < 0 or nModels > 4096 or (nModels > 0 and not inside(po + oModels, nModels * 148)) then
|
||||
return nil, "body part " .. p .. ": bad model table"
|
||||
end
|
||||
for m = 0, nModels - 1 do
|
||||
local mo = po + oModels + m * 148
|
||||
local nMesh, oMesh = i32(mo + 72), i32(mo + 76)
|
||||
local model: Model = {
|
||||
name = (string.match(buffer.readstring(b, base + mo, 64), "^[^%z]*")) :: string,
|
||||
kind = i32(mo + 64),
|
||||
radius = readf32(b, base + mo + 68),
|
||||
vertexCount = i32(mo + 80),
|
||||
vertexIndex = i32(mo + 84),
|
||||
tangentIndex = i32(mo + 88),
|
||||
eyeballs = i32(mo + 100),
|
||||
meshes = {},
|
||||
}
|
||||
if nMesh < 0 or nMesh > 4096 or (nMesh > 0 and not inside(mo + oMesh, nMesh * 116)) or model.vertexCount < 0 or model.vertexCount > maxVerts or model.vertexIndex < 0 then
|
||||
return nil, "model " .. model.name .. ": bad mesh table"
|
||||
end
|
||||
for k = 0, nMesh - 1 do
|
||||
local me = mo + oMesh + k * 116
|
||||
local mesh: Mesh = {
|
||||
material = i32(me),
|
||||
vertexCount = i32(me + 8),
|
||||
vertexOffset = i32(me + 12),
|
||||
materialType = i32(me + 24),
|
||||
materialParam = i32(me + 28),
|
||||
id = i32(me + 32),
|
||||
center = vec(me + 36),
|
||||
flexes = {},
|
||||
lodVertices = {},
|
||||
}
|
||||
for l = 0, 7 do
|
||||
mesh.lodVertices[l + 1] = i32(me + 52 + l * 4)
|
||||
end
|
||||
if mesh.vertexCount < 0 or mesh.vertexOffset < 0 or mesh.vertexOffset + mesh.vertexCount > model.vertexCount then
|
||||
return nil, "mesh " .. k .. ": vertex range outside its model"
|
||||
end
|
||||
local nFlex, oFlex = i32(me + 16), i32(me + 20)
|
||||
if nFlex < 0 or nFlex > 4096 or (nFlex > 0 and not inside(me + oFlex, nFlex * 60)) then
|
||||
return nil, "mesh " .. k .. ": bad flex table"
|
||||
end
|
||||
for f = 0, nFlex - 1 do
|
||||
local fo = me + oFlex + f * 60
|
||||
local nv, vo = i32(fo + 20), i32(fo + 24)
|
||||
local kind = readu8(b, base + fo + 32)
|
||||
local stride = if kind == 1 then 18 else 16
|
||||
totalFlex += math.max(nv, 0)
|
||||
if nv < 0 or totalFlex > maxVerts or (nv > 0 and not inside(fo + vo, nv * stride)) then
|
||||
return nil, "flex " .. f .. ": bad vertex animation table"
|
||||
end
|
||||
local flex: Flex = { desc = i32(fo), targets = vec(fo + 4, 4), partner = i32(fo + 28), kind = kind, deltas = {} }
|
||||
local fixed = bit32.band(h.flags, 0x200000) ~= 0
|
||||
local scale = h.vertAnimScale
|
||||
for v = 0, nv - 1 do
|
||||
local a = base + fo + vo + v * stride
|
||||
local d = { readu16(b, a) }
|
||||
for c = 0, 5 do
|
||||
d[c + 2] = if fixed then readi16(b, a + 4 + c * 2) * scale else HALF[readu16(b, a + 4 + c * 2)]
|
||||
end
|
||||
d[8] = readu8(b, a + 3) / 255
|
||||
d[9] = readu8(b, a + 2) / 255
|
||||
d[10] = if kind == 1 then readi16(b, a + 16) / 32767 else 0
|
||||
flex.deltas[v + 1] = d
|
||||
end
|
||||
table.insert(mesh.flexes, flex)
|
||||
end
|
||||
table.insert(model.meshes, mesh)
|
||||
end
|
||||
table.insert(part.models, model)
|
||||
end
|
||||
h.bodyParts[p + 1] = part
|
||||
end
|
||||
local nAtt, oAtt = i32(240), i32(244)
|
||||
e = table_(nAtt, oAtt, 92, 4096, "attachment")
|
||||
if e then
|
||||
return nil, e
|
||||
end
|
||||
h.attachments = {}
|
||||
for i = 0, nAtt - 1 do
|
||||
local o = oAtt + i * 92
|
||||
h.attachments[i + 1] = { name = str(o + i32(o)), flags = i32(o + 4), bone = i32(o + 8), matrix = vec(o + 12, 12) }
|
||||
end
|
||||
local nNodes, oNodeNames = i32(248), i32(256)
|
||||
h.nodes = {}
|
||||
if nNodes > 0 and nNodes <= 1024 and inside(oNodeNames, nNodes * 4) then
|
||||
for i = 0, nNodes - 1 do
|
||||
h.nodes[i + 1] = str(i32(oNodeNames + i * 4))
|
||||
end
|
||||
end
|
||||
local nDesc, oDesc = i32(260), i32(264)
|
||||
e = table_(nDesc, oDesc, 4, 65536, "flex description")
|
||||
if e then
|
||||
return nil, e
|
||||
end
|
||||
h.flexDescs = {}
|
||||
for i = 0, nDesc - 1 do
|
||||
local o = oDesc + i * 4
|
||||
h.flexDescs[i + 1] = str(o + i32(o))
|
||||
end
|
||||
local nFc, oFc = i32(268), i32(272)
|
||||
e = table_(nFc, oFc, 20, 65536, "flex controller")
|
||||
if e then
|
||||
return nil, e
|
||||
end
|
||||
h.flexControllers = {}
|
||||
for i = 0, nFc - 1 do
|
||||
local o = oFc + i * 20
|
||||
h.flexControllers[i + 1] = { type = str(o + i32(o)), name = str(o + i32(o + 4)), localToGlobal = i32(o + 8), min = readf32(b, base + o + 12), max = readf32(b, base + o + 16) }
|
||||
end
|
||||
local nRule, oRule = i32(276), i32(280)
|
||||
e = table_(nRule, oRule, 12, 65536, "flex rule")
|
||||
if e then
|
||||
return nil, e
|
||||
end
|
||||
h.flexRules = {}
|
||||
for i = 0, nRule - 1 do
|
||||
local o = oRule + i * 12
|
||||
local n, at = i32(o + 4), i32(o + 8)
|
||||
local ops = {}
|
||||
if n > 0 and n <= 65536 and inside(o + at, n * 8) then
|
||||
for k = 0, n - 1 do
|
||||
local oo = o + at + k * 8
|
||||
local op = i32(oo)
|
||||
ops[k + 1] = { op = op, value = if op == 1 then readf32(b, base + oo + 4) else i32(oo + 4) }
|
||||
end
|
||||
end
|
||||
h.flexRules[i + 1] = { flex = i32(o), ops = ops }
|
||||
end
|
||||
local nPose, oPose = i32(300), i32(304)
|
||||
e = table_(nPose, oPose, 20, 4096, "pose parameter")
|
||||
if e then
|
||||
return nil, e
|
||||
end
|
||||
h.poseParameters = {}
|
||||
for i = 0, nPose - 1 do
|
||||
local o = oPose + i * 20
|
||||
h.poseParameters[i + 1] = { name = str(o + i32(o)), flags = i32(o + 4), start = readf32(b, base + o + 8), ["end"] = readf32(b, base + o + 12), loop = readf32(b, base + o + 16) }
|
||||
end
|
||||
h.surfaceProp = str(i32(308))
|
||||
local kvAt, kvSize = i32(312), i32(316)
|
||||
h.keyValues = if kvSize > 0 and inside(kvAt, 1) then string.sub(str(kvAt), 1, kvSize) else ""
|
||||
local nInc, oInc = i32(336), i32(340)
|
||||
e = table_(nInc, oInc, 8, 4096, "include model")
|
||||
if e then
|
||||
return nil, e
|
||||
end
|
||||
h.includeModels = {}
|
||||
for i = 0, nInc - 1 do
|
||||
local o = oInc + i * 8
|
||||
local l, f = i32(o), i32(o + 4)
|
||||
h.includeModels[i + 1] = { label = if l ~= 0 then str(o + l) else "", file = if f ~= 0 then str(o + f) else "" }
|
||||
end
|
||||
local nameAt = i32(348)
|
||||
h.animBlockName = if nameAt > 0 then str(nameAt) else ""
|
||||
local nBlk, oBlk = i32(352), i32(356)
|
||||
h.animBlocks = {}
|
||||
if nBlk > 0 and nBlk <= 65536 and inside(oBlk, nBlk * 8) then
|
||||
for i = 0, nBlk - 1 do
|
||||
h.animBlocks[i + 1] = { i32(oBlk + i * 8), i32(oBlk + i * 8 + 4) }
|
||||
end
|
||||
end
|
||||
return h :: Header, nil
|
||||
end
|
||||
|
||||
return Mdl
|
||||
@@ -0,0 +1,121 @@
|
||||
--!strict
|
||||
-- model/sourcemdl/Phy: ".phy" collision models (phyheader_t; "VPHY" or legacy IVP compact surfaces: the ledge tree's
|
||||
-- leaf convex hulls; the trailing KeyValues text), from Source SDK 2013 public/phyfile.h, the IVP compact surface
|
||||
-- layout (ivp_compact_surface.hxx, ivp_compact_ledge.hxx) and SourceIO (MIT) notes; no code taken.
|
||||
local Phy = {}
|
||||
|
||||
local readi32, readu32, readu16, readi16, readf32 = buffer.readi32, buffer.readu32, buffer.readu16, buffer.readi16, buffer.readf32
|
||||
|
||||
export type Hull = { positions: { number }, indices: { number }, bone: number }
|
||||
export type Solid = { hulls: { Hull }, version: number?, kind: number? }
|
||||
export type Physics = { checksum: number, solids: { Solid }, text: string }
|
||||
|
||||
local METERS = 1 / 0.0254
|
||||
|
||||
local function surface(b: buffer, at: number, limit: number, out: Solid, budget: { number }): string?
|
||||
if at + 48 > limit then
|
||||
return "truncated collision surface"
|
||||
end
|
||||
local root = readi32(b, at + 32)
|
||||
local seen = 0
|
||||
local function ledge(lo: number): string?
|
||||
if lo + 16 > limit then
|
||||
return "truncated ledge"
|
||||
end
|
||||
local pts, client, nTri = readi32(b, lo), readi32(b, lo + 4), readi16(b, lo + 12)
|
||||
if nTri < 0 or lo + 16 + nTri * 16 > limit then
|
||||
return "bad ledge"
|
||||
end
|
||||
budget[1] -= nTri
|
||||
if budget[1] < 0 then
|
||||
return "limit: too many collision triangles"
|
||||
end
|
||||
local map: { [number]: number } = {}
|
||||
local hull: Hull = { positions = {}, indices = {}, bone = client }
|
||||
for t = 0, nTri - 1 do
|
||||
local to = lo + 16 + t * 16
|
||||
for e = 0, 2 do
|
||||
local id = readu16(b, to + 4 + e * 4)
|
||||
local v = map[id]
|
||||
if not v then
|
||||
local po = lo + pts + id * 16
|
||||
if po < 0 or po + 12 > limit then
|
||||
return "collision vertex out of range"
|
||||
end
|
||||
local x, y, z = readf32(b, po), readf32(b, po + 4), readf32(b, po + 8)
|
||||
table.insert(hull.positions, x * METERS)
|
||||
table.insert(hull.positions, z * METERS)
|
||||
table.insert(hull.positions, -y * METERS)
|
||||
v = #hull.positions // 3 - 1
|
||||
map[id] = v
|
||||
end
|
||||
table.insert(hull.indices, v)
|
||||
end
|
||||
end
|
||||
table.insert(out.hulls, hull)
|
||||
return nil
|
||||
end
|
||||
local function node(no: number, depth: number): string?
|
||||
seen += 1
|
||||
if depth > 64 or seen > 65536 or no + 28 > limit or no < at then
|
||||
return "bad ledge tree"
|
||||
end
|
||||
local right, led = readi32(b, no), readi32(b, no + 4)
|
||||
if right == 0 then
|
||||
if led == 0 then
|
||||
return nil
|
||||
end
|
||||
return ledge(no + led)
|
||||
end
|
||||
local e = node(no + 28, depth + 1)
|
||||
if e then
|
||||
return e
|
||||
end
|
||||
return node(no + right, depth + 1)
|
||||
end
|
||||
if root <= 0 then
|
||||
return "bad ledge tree root"
|
||||
end
|
||||
return node(at + root, 0)
|
||||
end
|
||||
|
||||
function Phy.parse(b: buffer, maxTriangles: number?): (Physics?, string?)
|
||||
local size = buffer.len(b)
|
||||
if size < 16 then
|
||||
return nil, "truncated phy header"
|
||||
end
|
||||
local hsize, nSolids = readi32(b, 0), readi32(b, 8)
|
||||
if hsize < 16 or hsize > size or nSolids < 0 or nSolids > 1024 then
|
||||
return nil, "bad phy header"
|
||||
end
|
||||
local out: Physics = { checksum = readu32(b, 12), solids = {}, text = "" }
|
||||
local budget = { maxTriangles or 2 ^ 22 }
|
||||
local p = hsize
|
||||
for _ = 1, nSolids do
|
||||
if p + 4 > size then
|
||||
return nil, "truncated phy solid"
|
||||
end
|
||||
local n = readi32(b, p)
|
||||
if n < 0 or p + 4 + n > size then
|
||||
return nil, "truncated phy solid"
|
||||
end
|
||||
local s: Solid = { hulls = {} }
|
||||
local at = p + 4
|
||||
if n >= 28 and buffer.readstring(b, at, 4) == "VPHY" then
|
||||
s.version, s.kind = readu16(b, at + 4), readu16(b, at + 6)
|
||||
at += 28
|
||||
end
|
||||
local e = surface(b, at, p + 4 + n, s, budget)
|
||||
if e then
|
||||
return nil, e
|
||||
end
|
||||
table.insert(out.solids, s)
|
||||
p += 4 + n
|
||||
end
|
||||
if p < size then
|
||||
out.text = (string.match(buffer.readstring(b, p, size - p), "^[^%z]*")) :: string
|
||||
end
|
||||
return out, nil
|
||||
end
|
||||
|
||||
return Phy
|
||||
@@ -0,0 +1,180 @@
|
||||
--!strict
|
||||
-- model/sourcemdl/Vtx: ".vtx" optimized strips (version 7: body part / model / LOD / mesh / strip group / strip
|
||||
-- headers, 9-byte vertices, u16 indices; the 33 / 35-byte strip group / strip headers of later branches too), from
|
||||
-- Source SDK 2013 public/optimize.h.
|
||||
local Vtx = {}
|
||||
|
||||
local readi32, readu16, readu8, readi16, readf32 = buffer.readi32, buffer.readu16, buffer.readu8, buffer.readi16, buffer.readf32
|
||||
|
||||
export type Mesh = { flags: number, indices: { number } } -- triangles of mesh-relative vertex ids, file winding
|
||||
export type Lod = { switchPoint: number, meshes: { Mesh } }
|
||||
export type Strips = {
|
||||
checksum: number,
|
||||
lods: number,
|
||||
parts: { { { Lod } } }, -- parts[p][m][lod]
|
||||
replacements: { { { material: number, name: string } } }, -- per LOD
|
||||
maxBonesPerStrip: number,
|
||||
extended: boolean,
|
||||
}
|
||||
|
||||
local function walk(b: buffer, ext: boolean, maxIndices: number): (Strips?, string?)
|
||||
local size = buffer.len(b)
|
||||
local sgStride, stStride = if ext then 33 else 25, if ext then 35 else 27
|
||||
local function inside(o: number, n: number): boolean
|
||||
return o >= 0 and n >= 0 and o + n <= size
|
||||
end
|
||||
local nParts, oParts = readi32(b, 28), readi32(b, 32)
|
||||
if nParts < 0 or nParts > 4096 or not inside(oParts, nParts * 8) then
|
||||
return nil, "bad vtx body part table"
|
||||
end
|
||||
local total = 0
|
||||
local parts = {}
|
||||
for p = 0, nParts - 1 do
|
||||
local po = oParts + p * 8
|
||||
local nModels, oModels = readi32(b, po), readi32(b, po + 4)
|
||||
if nModels < 0 or nModels > 4096 or not inside(po + oModels, nModels * 8) then
|
||||
return nil, "bad vtx model table"
|
||||
end
|
||||
local models = {}
|
||||
for m = 0, nModels - 1 do
|
||||
local mo = po + oModels + m * 8
|
||||
local nLods, oLods = readi32(b, mo), readi32(b, mo + 4)
|
||||
if nLods < 0 or nLods > 8 or not inside(mo + oLods, nLods * 12) then
|
||||
return nil, "bad vtx lod table"
|
||||
end
|
||||
local lods = {}
|
||||
for l = 0, nLods - 1 do
|
||||
local lo = mo + oLods + l * 12
|
||||
local nMesh, oMesh = readi32(b, lo), readi32(b, lo + 4)
|
||||
if nMesh < 0 or nMesh > 4096 or not inside(lo + oMesh, nMesh * 9) then
|
||||
return nil, "bad vtx mesh table"
|
||||
end
|
||||
local meshes = {}
|
||||
for k = 0, nMesh - 1 do
|
||||
local me = lo + oMesh + k * 9
|
||||
local nGroups, oGroups = readi32(b, me), readi32(b, me + 4)
|
||||
if nGroups < 0 or nGroups > 4096 or not inside(me + oGroups, nGroups * sgStride) then
|
||||
return nil, "bad vtx strip group table"
|
||||
end
|
||||
local tris: { number } = {}
|
||||
for g = 0, nGroups - 1 do
|
||||
local go = me + oGroups + g * sgStride
|
||||
local nv, ov, ni, oi = readi32(b, go), readi32(b, go + 4), readi32(b, go + 8), readi32(b, go + 12)
|
||||
local ns, os = readi32(b, go + 16), readi32(b, go + 20)
|
||||
if not inside(go + ov, nv * 9) or not inside(go + oi, ni * 2) or ns < 0 or ns > 65536 or not inside(go + os, ns * stStride) then
|
||||
return nil, "bad vtx strip group"
|
||||
end
|
||||
total += ni
|
||||
if total > maxIndices then
|
||||
return nil, "limit: too many indices"
|
||||
end
|
||||
local vbase, ibase = go + ov, go + oi
|
||||
local function vid(i: number): number?
|
||||
if i < 0 or i >= ni then
|
||||
return nil
|
||||
end
|
||||
local v = readu16(b, ibase + i * 2)
|
||||
if v >= nv then
|
||||
return nil
|
||||
end
|
||||
return readu16(b, vbase + v * 9 + 4)
|
||||
end
|
||||
local function strip(first: number, count: number, list: boolean): boolean
|
||||
if list then
|
||||
for i = first, first + count - 3, 3 do
|
||||
local a, c, d = vid(i), vid(i + 1), vid(i + 2)
|
||||
if not a or not c or not d then
|
||||
return false
|
||||
end
|
||||
table.insert(tris, a)
|
||||
table.insert(tris, c)
|
||||
table.insert(tris, d)
|
||||
end
|
||||
else
|
||||
for i = first, first + count - 3 do
|
||||
local a, c, d = vid(i), vid(i + 1), vid(i + 2)
|
||||
if not a or not c or not d then
|
||||
return false
|
||||
end
|
||||
if a ~= c and c ~= d and a ~= d then
|
||||
if (i - first) % 2 == 0 then
|
||||
table.insert(tris, a)
|
||||
table.insert(tris, c)
|
||||
table.insert(tris, d)
|
||||
else
|
||||
table.insert(tris, c)
|
||||
table.insert(tris, a)
|
||||
table.insert(tris, d)
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
return true
|
||||
end
|
||||
if ns == 0 then
|
||||
if not strip(0, ni, true) then
|
||||
return nil, "bad vtx index"
|
||||
end
|
||||
end
|
||||
for s = 0, ns - 1 do
|
||||
local so = go + os + s * stStride
|
||||
local sni, sio = readi32(b, so), readi32(b, so + 4)
|
||||
local flags = readu8(b, so + 18)
|
||||
if sni < 0 or sio < 0 or sio + sni > ni then
|
||||
return nil, "bad vtx strip"
|
||||
end
|
||||
if not strip(sio, sni, bit32.band(flags, 2) == 0) then
|
||||
return nil, "bad vtx index"
|
||||
end
|
||||
end
|
||||
end
|
||||
meshes[k + 1] = { flags = readu8(b, me + 8), indices = tris }
|
||||
end
|
||||
lods[l + 1] = { switchPoint = readf32(b, lo + 8), meshes = meshes }
|
||||
end
|
||||
models[m + 1] = lods
|
||||
end
|
||||
parts[p + 1] = models
|
||||
end
|
||||
local nLods = readi32(b, 20)
|
||||
local reps = {}
|
||||
local oRep = readi32(b, 24)
|
||||
if nLods > 0 and nLods <= 8 and inside(oRep, nLods * 8) then
|
||||
for l = 0, nLods - 1 do
|
||||
local ro = oRep + l * 8
|
||||
local n, at = readi32(b, ro), readi32(b, ro + 4)
|
||||
local list = {}
|
||||
if n > 0 and n <= 4096 and inside(ro + at, n * 6) then
|
||||
for k = 0, n - 1 do
|
||||
local eo = ro + at + k * 6
|
||||
local no = eo + readi32(b, eo + 2)
|
||||
local name = if no >= 0 and no < size then (string.match(buffer.readstring(b, no, math.min(size - no, 1024)), "^[^%z]*")) :: string else ""
|
||||
list[k + 1] = { material = readi16(b, eo), name = name }
|
||||
end
|
||||
end
|
||||
reps[l + 1] = list
|
||||
end
|
||||
end
|
||||
return { checksum = readi32(b, 16), lods = nLods, parts = parts, replacements = reps, maxBonesPerStrip = readu16(b, 8), extended = ext }, nil
|
||||
end
|
||||
|
||||
function Vtx.parse(b: buffer, maxIndices: number?): (Strips?, string?)
|
||||
if buffer.len(b) < 36 then
|
||||
return nil, "truncated vtx header"
|
||||
end
|
||||
local version = readi32(b, 0)
|
||||
if version ~= 7 then
|
||||
return nil, "unsupported: vtx version " .. version
|
||||
end
|
||||
local s, err = walk(b, false, maxIndices or 2 ^ 26)
|
||||
if s then
|
||||
return s, nil
|
||||
end
|
||||
local s2 = walk(b, true, maxIndices or 2 ^ 26)
|
||||
if s2 then
|
||||
return s2, nil
|
||||
end
|
||||
return nil, err
|
||||
end
|
||||
|
||||
return Vtx
|
||||
@@ -0,0 +1,92 @@
|
||||
--!strict
|
||||
-- model/sourcemdl/Vvd: ".vvd" vertex data ("IDSV" v4: 48-byte mstudiovertex_t records, 16-byte tangents, the LOD
|
||||
-- fixup table), from Source SDK 2013 public/studio.h (vertexFileHeader_t) and Studio_LoadVertexes.
|
||||
local Vvd = {}
|
||||
|
||||
local readi32, readu32 = buffer.readi32, buffer.readu32
|
||||
|
||||
export type Vertices = {
|
||||
checksum: number,
|
||||
lods: number,
|
||||
lodCounts: { number },
|
||||
count: number,
|
||||
data: buffer, -- count * 48: weight f32[3], bone u8[3], numbones u8, position f32[3], normal f32[3], uv f32[2]
|
||||
tangents: buffer?, -- count * 16: x, y, z, w
|
||||
fixups: number,
|
||||
}
|
||||
|
||||
-- the vertices of LOD `lod` and above, in fixup order (lod 0: every vertex, the layout the MDL meshes index)
|
||||
function Vvd.parse(b: buffer, lod: number?, maxVertices: number?): (Vertices?, string?)
|
||||
local size = buffer.len(b)
|
||||
if size < 64 then
|
||||
return nil, "truncated vvd header"
|
||||
end
|
||||
if buffer.readstring(b, 0, 4) ~= "IDSV" then
|
||||
return nil, "not a vvd file"
|
||||
end
|
||||
local version = readi32(b, 4)
|
||||
if version ~= 4 then
|
||||
return nil, "unsupported: vvd version " .. version
|
||||
end
|
||||
local nLods = readi32(b, 12)
|
||||
local counts = {}
|
||||
for i = 0, 7 do
|
||||
counts[i + 1] = readi32(b, 16 + i * 4)
|
||||
end
|
||||
local nFix, oFix, oVert, oTan = readi32(b, 48), readi32(b, 52), readi32(b, 56), readi32(b, 60)
|
||||
local total = counts[1]
|
||||
if nLods < 1 or nLods > 8 or total < 0 or total > (maxVertices or 2 ^ 24) then
|
||||
return nil, "bad vvd vertex counts"
|
||||
end
|
||||
if oVert < 64 or oVert + total * 48 > size then
|
||||
return nil, "truncated vvd vertex data"
|
||||
end
|
||||
local hasTan = oTan > 0 and oTan + total * 16 <= size
|
||||
local want = math.clamp(lod or 0, 0, nLods - 1)
|
||||
local out: Vertices = { checksum = readu32(b, 8), lods = nLods, lodCounts = counts, count = 0, data = buffer.create(0), fixups = nFix }
|
||||
if nFix <= 0 then
|
||||
out.count = total
|
||||
out.data = buffer.create(total * 48)
|
||||
buffer.copy(out.data, 0, b, oVert, total * 48)
|
||||
if hasTan then
|
||||
local t = buffer.create(total * 16)
|
||||
buffer.copy(t, 0, b, oTan, total * 16)
|
||||
out.tangents = t
|
||||
end
|
||||
return out, nil
|
||||
end
|
||||
if nFix > 65536 or oFix < 0 or oFix + nFix * 12 > size then
|
||||
return nil, "bad vvd fixup table"
|
||||
end
|
||||
local n = 0
|
||||
for i = 0, nFix - 1 do
|
||||
local fl, first, cnt = readi32(b, oFix + i * 12), readi32(b, oFix + i * 12 + 4), readi32(b, oFix + i * 12 + 8)
|
||||
if first < 0 or cnt < 0 or first + cnt > total then
|
||||
return nil, "vvd fixup " .. i .. " out of range"
|
||||
end
|
||||
if fl >= want then
|
||||
n += cnt
|
||||
end
|
||||
end
|
||||
if n > total * 8 then
|
||||
return nil, "bad vvd fixup table"
|
||||
end
|
||||
out.count = n
|
||||
out.data = buffer.create(n * 48)
|
||||
local tan = if hasTan then buffer.create(n * 16) else nil
|
||||
local at = 0
|
||||
for i = 0, nFix - 1 do
|
||||
local fl, first, cnt = readi32(b, oFix + i * 12), readi32(b, oFix + i * 12 + 4), readi32(b, oFix + i * 12 + 8)
|
||||
if fl >= want then
|
||||
buffer.copy(out.data, at * 48, b, oVert + first * 48, cnt * 48)
|
||||
if tan then
|
||||
buffer.copy(tan, at * 16, b, oTan + first * 16, cnt * 16)
|
||||
end
|
||||
at += cnt
|
||||
end
|
||||
end
|
||||
out.tangents = tan
|
||||
return out, nil
|
||||
end
|
||||
|
||||
return Vvd
|
||||
@@ -0,0 +1,169 @@
|
||||
--!strict
|
||||
-- model/sourcemdl: Source engine studio models ("IDST" v44-49) with .vvd / .vtx (.dx90 / .dx80 / .sw) and optional .phy /
|
||||
-- .ani / .vmt through opts.resolve / opts.files; Source SDK 2013 studio.h / optimize.h layouts, checked with srctools.
|
||||
-- Not supported: v52+ frame animations, IK rules, movement, eyeball shading, $includemodel animations.
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ 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 Mdl = require("@rosetta/model/sourcemdl/Mdl")
|
||||
local Vvd = require("@rosetta/model/sourcemdl/Vvd")
|
||||
local Vtx = require("@rosetta/model/sourcemdl/Vtx")
|
||||
local Phy = require("@rosetta/model/sourcemdl/Phy")
|
||||
local Build = require("@rosetta/model/sourcemdl/Build")
|
||||
local Material = require("@rosetta/model/sourcemdl/Material")
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ contract
|
||||
local SourceMdl = {
|
||||
name = "sourcemdl",
|
||||
category = "model",
|
||||
extensions = { "mdl" },
|
||||
mime = { "model/x-source-mdl" },
|
||||
deps = { "core/Err", "core/Bytes", "core/Input", "Types", "codecs/image/Half", "codecs/model/Mat4", "codecs/model/Rig", "codecs/model/SourceAnim", "codecs/text/KeyValues" },
|
||||
caps = { decode = true, encode = false, skins = true, morph = true, animation = true, lods = true },
|
||||
}
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ types
|
||||
export type DecodeOptions = {
|
||||
resolve: ((uri: string) -> (buffer | string)?)?,
|
||||
files: { [string]: buffer | string }?,
|
||||
name: string?, -- the .mdl file name: its stem names the sibling files (default: the stem of the header name)
|
||||
vvd: (buffer | string)?,
|
||||
vtx: (buffer | string)?,
|
||||
phy: (buffer | string)?,
|
||||
ani: (buffer | string)?,
|
||||
bodies: { number }?, -- 1-based model per body part, default 1
|
||||
lod: number?, -- 1-based LOD for the primitive indices, default 1
|
||||
animations: boolean?, -- default true
|
||||
physics: boolean?, -- default true: read the .phy
|
||||
materials: boolean?, -- default true: resolve materials/<cdmaterials><texture>.vmt
|
||||
maxVertices: number?, -- default 2^24
|
||||
maxFrames: number?, -- per animation, default 65536
|
||||
}
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ constants
|
||||
local VTX = { "dx90.vtx", "dx80.vtx", "sw.vtx", "vtx" }
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ sniff
|
||||
function SourceMdl.sniff(r: Bytes.Reader): number
|
||||
if r.limit - r.base < 8 or r:peek(4) ~= "IDST" then
|
||||
return 0
|
||||
end
|
||||
local v = buffer.readi32(r.buf, r.base + 4)
|
||||
return if v >= 44 and v <= 49 then 1 else 0
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ decode
|
||||
local function stems(opts: DecodeOptions?, header: string): { string }
|
||||
local out: { string } = {}
|
||||
local function add(s: string?)
|
||||
if s and s ~= "" and not table.find(out, s) then
|
||||
table.insert(out, s)
|
||||
end
|
||||
end
|
||||
local n = opts and opts.name
|
||||
if type(n) == "string" then
|
||||
add((string.gsub(string.match(n, "([^/\\]+)$") or n, "%.[mM][dD][lL]$", "")))
|
||||
end
|
||||
local h = string.gsub(header, "\\", "/")
|
||||
add((string.gsub(string.match(h, "([^/]+)$") or h, "%.[mM][dD][lL]$", "")))
|
||||
add("models/" .. (string.gsub(h, "%.[mM][dD][lL]$", "")))
|
||||
return out
|
||||
end
|
||||
|
||||
local function sibling(opts: DecodeOptions?, direct: (buffer | string)?, names: { string }, exts: { string }): (buffer?, string?)
|
||||
if direct then
|
||||
return Bytes.toBuffer(direct), nil
|
||||
end
|
||||
for _, s in names do
|
||||
for _, e in exts do
|
||||
local uri = s .. "." .. e
|
||||
local b = Input.sibling(opts, uri)
|
||||
if b then
|
||||
return b, uri
|
||||
end
|
||||
end
|
||||
end
|
||||
return nil, nil
|
||||
end
|
||||
|
||||
function SourceMdl.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Scene?, Err.Err?)
|
||||
local size = r.limit - r.base
|
||||
if size < 8 then
|
||||
return nil, Err.new(Err.TRUNCATED, "header", 0)
|
||||
end
|
||||
if r:peek(4) ~= "IDST" then
|
||||
return nil, Err.new(Err.CORRUPT, "bad magic", 0)
|
||||
end
|
||||
local version = buffer.readi32(r.buf, r.base + 4)
|
||||
if version < 44 or version > 49 then
|
||||
return nil, Err.new(Err.UNSUPPORTED, "studio model version " .. version, 4)
|
||||
end
|
||||
local h, perr = Mdl.parse(r.buf, r.base, size, opts)
|
||||
if not h then
|
||||
return nil, Err.from(perr)
|
||||
end
|
||||
local warnings: { string } = {}
|
||||
local names = stems(opts, h.name)
|
||||
local inp: Build.Inputs = { warnings = warnings }
|
||||
local maxV = opts and opts.maxVertices or 2 ^ 24
|
||||
local vvdBuf = sibling(opts, opts and opts.vvd, names, { "vvd" })
|
||||
if vvdBuf then
|
||||
local v, e = Vvd.parse(vvdBuf, 0, maxV)
|
||||
if not v then
|
||||
return nil, Err.from("vvd: " .. tostring(e))
|
||||
end
|
||||
if v.checksum ~= h.checksum then
|
||||
table.insert(warnings, "vvd checksum differs from the mdl")
|
||||
end
|
||||
inp.vvd = v
|
||||
else
|
||||
table.insert(warnings, "no .vvd: no geometry")
|
||||
end
|
||||
local vtxBuf, vtxName = sibling(opts, opts and opts.vtx, names, VTX)
|
||||
if vtxBuf then
|
||||
local s, e = Vtx.parse(vtxBuf, maxV * 8)
|
||||
if not s then
|
||||
return nil, Err.from("vtx: " .. tostring(e))
|
||||
end
|
||||
if bit32.band(s.checksum, 0xFFFFFFFF) ~= h.checksum then
|
||||
table.insert(warnings, "vtx checksum differs from the mdl")
|
||||
end
|
||||
inp.vtx = s
|
||||
else
|
||||
table.insert(warnings, "no .vtx: no geometry")
|
||||
end
|
||||
if not (opts and opts.physics == false) then
|
||||
local phyBuf = sibling(opts, opts and opts.phy, names, { "phy" })
|
||||
if phyBuf then
|
||||
local p, e = Phy.parse(phyBuf)
|
||||
if p then
|
||||
inp.phy = p
|
||||
else
|
||||
table.insert(warnings, "phy: " .. tostring(e))
|
||||
end
|
||||
end
|
||||
end
|
||||
if #h.animBlocks > 1 and not (opts and opts.animations == false) then
|
||||
local ani: buffer? = if opts and opts.ani then Bytes.toBuffer(opts.ani) else nil
|
||||
local an = string.gsub(h.animBlockName, "\\", "/")
|
||||
if not ani and an ~= "" then
|
||||
ani = Input.sibling(opts, an) or Input.sibling(opts, string.match(an, "([^/]+)$") or an)
|
||||
end
|
||||
inp.ani = ani
|
||||
end
|
||||
local scene, berr = Build.scene(h, r.buf, r.base, size, inp, opts)
|
||||
if not scene then
|
||||
return nil, Err.from(berr)
|
||||
end
|
||||
if not (opts and opts.materials == false) then
|
||||
Material.apply(scene, h.textures, h.cdmaterials, opts, warnings)
|
||||
end
|
||||
local src = scene.meta.source :: { [string]: any }
|
||||
src.vtx = vtxName
|
||||
return scene, nil
|
||||
end
|
||||
|
||||
return SourceMdl
|
||||
Reference in new issue
Block a user