merge ws/game
This commit is contained in:
commit
3cebe7d4e7
72 files changed
+10473
-6
No files matched your search
@@ -26,6 +26,18 @@ local list: { Entry } = {
|
||||
return require("@formats/image/ani")
|
||||
end,
|
||||
},
|
||||
{
|
||||
name = "blp",
|
||||
category = "image",
|
||||
path = "image/blp",
|
||||
extensions = { "blp" },
|
||||
mime = { "image/x-blp" },
|
||||
deps = { "core/Err", "core/Bytes", "Types", "codecs/image/Jpeg", "codecs/image/Bcn" },
|
||||
caps = { decode = true, encode = true, alpha = true, variants = { "blp1", "blp2" }, compressions = { "jpeg", "palette", "dxt1", "dxt3", "dxt5", "bgra" } },
|
||||
load = function()
|
||||
return require("@formats/image/blp")
|
||||
end,
|
||||
},
|
||||
{
|
||||
name = "bmp",
|
||||
category = "image",
|
||||
@@ -242,6 +254,30 @@ local list: { Entry } = {
|
||||
return require("@formats/image/tiff")
|
||||
end,
|
||||
},
|
||||
{
|
||||
name = "tim",
|
||||
category = "image",
|
||||
path = "image/tim",
|
||||
extensions = { "tim" },
|
||||
mime = { "image/x-tim" },
|
||||
deps = { "core/Err", "core/Bytes", "Types" },
|
||||
caps = { decode = true, encode = true, alpha = true, palette = true, depths = { 4, 8, 16, 24 } },
|
||||
load = function()
|
||||
return require("@formats/image/tim")
|
||||
end,
|
||||
},
|
||||
{
|
||||
name = "vtf",
|
||||
category = "image",
|
||||
path = "image/vtf",
|
||||
extensions = { "vtf" },
|
||||
mime = { "image/x-vtf" },
|
||||
deps = { "core/Err", "core/Bytes", "Types", "codecs/image/Bcn", "codecs/image/Texel" },
|
||||
caps = { decode = true, encode = false, alpha = true, animation = true, versions = { "7.0", "7.1", "7.2", "7.3", "7.4", "7.5" } },
|
||||
load = function()
|
||||
return require("@formats/image/vtf")
|
||||
end,
|
||||
},
|
||||
{
|
||||
name = "webp",
|
||||
category = "image",
|
||||
@@ -698,6 +734,18 @@ local list: { Entry } = {
|
||||
return require("@formats/model/b3d")
|
||||
end,
|
||||
},
|
||||
{
|
||||
name = "bsp",
|
||||
category = "model",
|
||||
path = "model/bsp",
|
||||
extensions = { "bsp" },
|
||||
mime = { "model/x-bsp" },
|
||||
deps = { "core/Err", "core/Bytes", "core/Input", "Types", "codecs/image/Pixels" },
|
||||
caps = { decode = true, encode = false, variants = { "quake", "halflife", "quake2", "quake3" }, lightmaps = "quake3" },
|
||||
load = function()
|
||||
return require("@formats/model/bsp")
|
||||
end,
|
||||
},
|
||||
{
|
||||
name = "dae",
|
||||
category = "model",
|
||||
@@ -782,6 +830,54 @@ local list: { Entry } = {
|
||||
return require("@formats/model/mca")
|
||||
end,
|
||||
},
|
||||
{
|
||||
name = "md2",
|
||||
category = "model",
|
||||
path = "model/md2",
|
||||
extensions = { "md2" },
|
||||
mime = { "model/x-md2" },
|
||||
deps = { "core/Err", "core/Bytes", "core/Sniff", "Types", "codecs/model/Rig" },
|
||||
caps = { decode = true, encode = false, morph = true, animation = true },
|
||||
load = function()
|
||||
return require("@formats/model/md2")
|
||||
end,
|
||||
},
|
||||
{
|
||||
name = "md3",
|
||||
category = "model",
|
||||
path = "model/md3",
|
||||
extensions = { "md3" },
|
||||
mime = { "model/x-md3" },
|
||||
deps = { "core/Err", "core/Bytes", "core/Sniff", "Types", "codecs/model/Mat4", "codecs/model/Rig" },
|
||||
caps = { decode = true, encode = false, morph = true, animation = true, tags = true },
|
||||
load = function()
|
||||
return require("@formats/model/md3")
|
||||
end,
|
||||
},
|
||||
{
|
||||
name = "md5",
|
||||
category = "model",
|
||||
path = "model/md5",
|
||||
extensions = { "md5mesh", "md5anim" },
|
||||
mime = { "model/x-md5mesh", "model/x-md5anim" },
|
||||
deps = { "core/Err", "core/Bytes", "core/Input", "core/Sniff", "Types", "codecs/model/Rig" },
|
||||
caps = { decode = true, encode = false, skins = true, animation = true },
|
||||
load = function()
|
||||
return require("@formats/model/md5")
|
||||
end,
|
||||
},
|
||||
{
|
||||
name = "mdl",
|
||||
category = "model",
|
||||
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" },
|
||||
caps = { decode = true, encode = false, variants = { "quake", "halflife" }, morph = true, skins = true, animation = true },
|
||||
load = function()
|
||||
return require("@formats/model/mdl")
|
||||
end,
|
||||
},
|
||||
{
|
||||
name = "ms3d",
|
||||
category = "model",
|
||||
@@ -902,6 +998,18 @@ local list: { Entry } = {
|
||||
return require("@formats/model/schematic")
|
||||
end,
|
||||
},
|
||||
{
|
||||
name = "smd",
|
||||
category = "model",
|
||||
path = "model/smd",
|
||||
extensions = { "smd" },
|
||||
mime = { "model/x-smd", "text/plain" },
|
||||
deps = { "core/Err", "core/Bytes", "core/Sniff", "Types", "codecs/model/Mat4", "codecs/model/MeshFlatten", "codecs/model/Rig" },
|
||||
caps = { decode = true, encode = true, skins = true, animation = true },
|
||||
load = function()
|
||||
return require("@formats/model/smd")
|
||||
end,
|
||||
},
|
||||
{
|
||||
name = "stl",
|
||||
category = "model",
|
||||
@@ -1070,6 +1178,18 @@ local list: { Entry } = {
|
||||
return require("@formats/archive/bz2")
|
||||
end,
|
||||
},
|
||||
{
|
||||
name = "grp",
|
||||
category = "archive",
|
||||
path = "archive/grp",
|
||||
extensions = { "grp" },
|
||||
mime = { "application/x-build-grp" },
|
||||
deps = { "core/Err", "core/Bytes", "core/Sniff", "containers/Archive" },
|
||||
caps = { decode = true, encode = true },
|
||||
load = function()
|
||||
return require("@formats/archive/grp")
|
||||
end,
|
||||
},
|
||||
{
|
||||
name = "gzip",
|
||||
category = "archive",
|
||||
@@ -1082,6 +1202,18 @@ local list: { Entry } = {
|
||||
return require("@formats/archive/gzip")
|
||||
end,
|
||||
},
|
||||
{
|
||||
name = "mpq",
|
||||
category = "archive",
|
||||
path = "archive/mpq",
|
||||
extensions = { "mpq", "w3x", "w3m", "sc2map", "sc2data", "s2ma", "scm", "scx" },
|
||||
mime = { "application/x-mpq" },
|
||||
deps = { "core/Err", "core/Bytes", "containers/Archive", "codecs/compress/Deflate", "codecs/compress/Bzip2", "codecs/compress/Lzma", "codecs/compress/Explode" },
|
||||
caps = { decode = true, encode = false, versions = { 1, 2, 3, 4 }, methods = { "zlib", "implode", "bzip2", "lzma", "sparse" }, encryption = true },
|
||||
load = function()
|
||||
return require("@formats/archive/mpq")
|
||||
end,
|
||||
},
|
||||
{
|
||||
name = "pak",
|
||||
category = "archive",
|
||||
@@ -1106,6 +1238,30 @@ local list: { Entry } = {
|
||||
return require("@formats/archive/tar")
|
||||
end,
|
||||
},
|
||||
{
|
||||
name = "vpk",
|
||||
category = "archive",
|
||||
path = "archive/vpk",
|
||||
extensions = { "vpk" },
|
||||
mime = { "application/x-vpk" },
|
||||
deps = { "core/Err", "core/Bytes", "core/Input", "core/Crc32", "core/Md5", "containers/Archive" },
|
||||
caps = { decode = true, encode = true, versions = { 1, 2 }, multipart = true },
|
||||
load = function()
|
||||
return require("@formats/archive/vpk")
|
||||
end,
|
||||
},
|
||||
{
|
||||
name = "wad",
|
||||
category = "archive",
|
||||
path = "archive/wad",
|
||||
extensions = { "wad" },
|
||||
mime = { "application/x-doom" },
|
||||
deps = { "core/Err", "core/Bytes", "Types", "containers/Archive", "codecs/image/Pixels", "codecs/model/Polygon" },
|
||||
caps = { decode = true, encode = true, images = true, maps = true, variants = { "iwad", "pwad" } },
|
||||
load = function()
|
||||
return require("@formats/archive/wad")
|
||||
end,
|
||||
},
|
||||
{
|
||||
name = "xz",
|
||||
category = "archive",
|
||||
|
||||
@@ -0,0 +1,115 @@
|
||||
--!strict
|
||||
-- archive/grp: Build engine GRP archives (Duke Nukem 3D, Shadow Warrior, Blood: "KenSilverman", a u32 file count,
|
||||
-- 16-byte entries of a 12-byte name and a u32 size, then the files back to back), read into the standard Archive
|
||||
-- (entries read lazily) and written from any Archive value (names upper-cased to 8.3 by the caller's choice: they
|
||||
-- are stored as given, at most 12 bytes). Written from Ken Silverman's GRP description (kenbuild); no code taken.
|
||||
-- Not supported: the "GRP 2" / RFF / SSI variants.
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ requires
|
||||
local Err = require("@formats/core/Err")
|
||||
local Bytes = require("@formats/core/Bytes")
|
||||
local Sniff = require("@formats/core/Sniff")
|
||||
local Archive = require("@formats/containers/Archive")
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ contract
|
||||
local Grp = {
|
||||
name = "grp",
|
||||
category = "archive",
|
||||
extensions = { "grp" },
|
||||
mime = { "application/x-build-grp" },
|
||||
deps = { "core/Err", "core/Bytes", "core/Sniff", "containers/Archive" },
|
||||
caps = { decode = true, encode = true },
|
||||
}
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ types
|
||||
export type DecodeOptions = { maxEntries: number? } -- default 1e6
|
||||
export type EncodeOptions = { upper: boolean? } -- upper-case the names (Build looks them up case-insensitively; default false)
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ constants
|
||||
local MAGIC = "KenSilverman"
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ sniff
|
||||
function Grp.sniff(r: Bytes.Reader): number
|
||||
return Sniff.magic(r, MAGIC)
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ decode
|
||||
local function encode(archive: any, opts: any?): (buffer?, Err.Err?)
|
||||
return Grp.encode(archive, opts)
|
||||
end
|
||||
|
||||
function Grp.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?)
|
||||
if not r:match(MAGIC) then
|
||||
return nil, Err.new(Err.CORRUPT, "bad magic", 0)
|
||||
end
|
||||
local count = r:u32le()
|
||||
if r.err then
|
||||
return nil, r.err
|
||||
end
|
||||
if count > (opts and opts.maxEntries or 1e6) then
|
||||
return nil, Err.new(Err.LIMIT, "too many entries: " .. count)
|
||||
end
|
||||
if count * 16 > r:remaining() then
|
||||
return nil, Err.new(Err.TRUNCATED, "directory past the end", 12)
|
||||
end
|
||||
local a = Archive.new("grp", encode)
|
||||
local at = 16 + count * 16
|
||||
local size = r.limit - r.base
|
||||
for i = 0, count - 1 do
|
||||
local name = r:fixed(12)
|
||||
local n = r:u32le()
|
||||
if at + n > size then
|
||||
return nil, Err.new(Err.TRUNCATED, "entry " .. name .. " past the end", 16 + i * 16)
|
||||
end
|
||||
Archive.put(a, { name = name, size = n, dir = false, method = "store", offset = at, load = Archive.slice(r.buf, r.base + at, n) })
|
||||
at += n
|
||||
end
|
||||
if r.err then
|
||||
return nil, r.err
|
||||
end
|
||||
a.meta.source = { format = "grp", entries = count }
|
||||
return a, nil
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ encode
|
||||
function Grp.encode(archive: any, opts: EncodeOptions?): (buffer?, Err.Err?)
|
||||
local items, err = Archive.collect(archive)
|
||||
if not items then
|
||||
return nil, err
|
||||
end
|
||||
local files: { { name: string, data: buffer } } = {}
|
||||
for _, it in items do
|
||||
if not it.entry.dir then
|
||||
local name = it.entry.name
|
||||
if opts and opts.upper then
|
||||
name = string.upper(name)
|
||||
end
|
||||
if #name > 12 then
|
||||
return nil, Err.new(Err.ARG, "name longer than 12 bytes: " .. name)
|
||||
end
|
||||
table.insert(files, { name = name, data = it.data })
|
||||
end
|
||||
end
|
||||
local w = Bytes.writer()
|
||||
w:string(MAGIC)
|
||||
w:u32le(#files)
|
||||
for _, f in files do
|
||||
w:string(f.name)
|
||||
w:fill(0, 12 - #f.name)
|
||||
w:u32le(buffer.len(f.data))
|
||||
end
|
||||
for _, f in files do
|
||||
w:bytes(f.data)
|
||||
end
|
||||
return w:finish(), nil
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ extras
|
||||
-- new() -> an empty GRP Archive: a:add(name, data); a:write()
|
||||
function Grp.new(): any
|
||||
local a = Archive.new("grp", encode)
|
||||
a.meta.source = { format = "grp" }
|
||||
return a
|
||||
end
|
||||
|
||||
return Grp
|
||||
@@ -0,0 +1,65 @@
|
||||
--!strict
|
||||
--!native
|
||||
-- archive/mpq/Crypt: the MPQ encryption table, the name hash (types 0 = table index, 1 / 2 = name check, 3 = file
|
||||
-- key) and block decryption in place. Written from the MPQ format description (Justin Olbrantz / Jean-Francois
|
||||
-- Roy, "The MoPaQ Archive Format"; StormLib's documentation); no code taken. All arithmetic is mod 2^32 and every
|
||||
-- value handed to bit32 is an integer in 0..2^32 - 1 (both runtimes agree).
|
||||
local readu32, writeu32 = buffer.readu32, buffer.writeu32
|
||||
local bxor, band, bor, lshift, rshift, bnot = bit32.bxor, bit32.band, bit32.bor, bit32.lshift, bit32.rshift, bit32.bnot
|
||||
|
||||
local Crypt = {}
|
||||
|
||||
local TWO32 = 4294967296
|
||||
local TABLE = buffer.create(0x500 * 4)
|
||||
do
|
||||
local seed = 0x00100001
|
||||
for i1 = 0, 255 do
|
||||
local i2 = i1
|
||||
for _ = 0, 4 do
|
||||
seed = (seed * 125 + 3) % 0x2AAAAB
|
||||
local t1 = band(seed, 0xFFFF) * 65536
|
||||
seed = (seed * 125 + 3) % 0x2AAAAB
|
||||
local t2 = band(seed, 0xFFFF)
|
||||
writeu32(TABLE, i2 * 4, t1 + t2)
|
||||
i2 += 0x100
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
-- hash(name, kind) -> u32: ASCII upper case, '/' as '\'
|
||||
function Crypt.hash(name: string, kind: number): number
|
||||
local s1, s2 = 0x7FED7FED, 0xEEEEEEEE
|
||||
local base = kind * 0x100
|
||||
for i = 1, #name do
|
||||
local c = string.byte(name, i)
|
||||
if c >= 97 and c <= 122 then
|
||||
c -= 32
|
||||
elseif c == 47 then
|
||||
c = 92
|
||||
end
|
||||
s1 = bxor(readu32(TABLE, (base + c) * 4), (s1 + s2) % TWO32)
|
||||
s2 = (c + s1 + s2 + lshift(s2, 5) + 3) % TWO32
|
||||
end
|
||||
return s1
|
||||
end
|
||||
|
||||
-- decrypt(buf, at, n, key): n bytes (whole u32s; a trailing partial word is left as is) at buf[at..] in place
|
||||
function Crypt.decrypt(buf: buffer, at: number, n: number, key: number)
|
||||
local s2 = 0xEEEEEEEE
|
||||
local k = key % TWO32
|
||||
for i = 0, n // 4 - 1 do
|
||||
local o = at + i * 4
|
||||
s2 = (s2 + readu32(TABLE, (0x400 + band(k, 0xFF)) * 4)) % TWO32
|
||||
local ch = bxor(readu32(buf, o), (k + s2) % TWO32)
|
||||
k = bor((lshift(bnot(k), 0x15) + 0x11111111) % TWO32, rshift(k, 0x0B))
|
||||
s2 = (ch + s2 + lshift(s2, 5) + 3) % TWO32
|
||||
writeu32(buf, o, ch)
|
||||
end
|
||||
end
|
||||
|
||||
-- base name of an archived path (the file key uses it)
|
||||
function Crypt.baseName(name: string): string
|
||||
return string.match(name, "([^\\/]*)$") or name
|
||||
end
|
||||
|
||||
return Crypt
|
||||
@@ -0,0 +1,419 @@
|
||||
--!strict
|
||||
-- archive/mpq: Blizzard MPQ archives (MoPaQ: Diablo, StarCraft, Warcraft II / III, WoW, StarCraft II), read into the
|
||||
-- standard Archive. Supports: header versions 1-4 with the classic hash and block tables (encrypted, found at offset
|
||||
-- 0, at any 512-byte boundary (prefixed archives / installers) or through the "MPQ\x1B" user data header), the hi-block
|
||||
-- table (files past 4 GB), names from "(listfile)" (plus opts.names), unnamed files as "File00000123.xxx" (block
|
||||
-- index), encrypted files (key from the name, MPQ_FILE_FIX_KEY), sector offset tables, single-unit files, imploded
|
||||
-- files (codecs/compress/Explode), compressed sectors: zlib (codecs/compress/Deflate), PKWARE DCL implode, bzip2
|
||||
-- (codecs/compress/Bzip2), LZMA (codecs/compress/Lzma), sparse, and combinations; deleted and delete-marker blocks
|
||||
-- are skipped. Written from the MPQ format description (Justin Olbrantz / Jean-Francois Roy, "The MoPaQ Archive
|
||||
-- Format", and StormLib's documentation); no code taken.
|
||||
-- Not supported (Err.UNSUPPORTED on read): Huffman and IMA ADPCM sectors (WAVE files), patch files, the HET / BET
|
||||
-- tables of archives without classic tables, encrypted files whose name is unknown, compressed hash / block tables,
|
||||
-- writing.
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ requires
|
||||
local Err = require("@formats/core/Err")
|
||||
local Bytes = require("@formats/core/Bytes")
|
||||
local Archive = require("@formats/containers/Archive")
|
||||
local Deflate = require("@formats/codecs/compress/Deflate")
|
||||
local Bzip2 = require("@formats/codecs/compress/Bzip2")
|
||||
local Lzma = require("@formats/codecs/compress/Lzma")
|
||||
local Explode = require("@formats/codecs/compress/Explode")
|
||||
local Crypt = require("@formats/archive/mpq/Crypt")
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ contract
|
||||
local Mpq = {
|
||||
name = "mpq",
|
||||
category = "archive",
|
||||
extensions = { "mpq", "w3x", "w3m", "sc2map", "sc2data", "s2ma", "scm", "scx" },
|
||||
mime = { "application/x-mpq" },
|
||||
deps = { "core/Err", "core/Bytes", "containers/Archive", "codecs/compress/Deflate", "codecs/compress/Bzip2", "codecs/compress/Lzma", "codecs/compress/Explode" },
|
||||
caps = { decode = true, encode = false, versions = { 1, 2, 3, 4 }, methods = { "zlib", "implode", "bzip2", "lzma", "sparse" }, encryption = true },
|
||||
}
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ types
|
||||
export type DecodeOptions = {
|
||||
names: { string }?, -- extra file names to look up (beside the archive's own "(listfile)")
|
||||
maxEntries: number?, -- default 1e6
|
||||
maxBytes: number?, -- the largest file read (default 2^30)
|
||||
}
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ constants
|
||||
local FLAG_IMPLODE, FLAG_COMPRESS, FLAG_ENCRYPTED, FLAG_FIX_KEY = 0x100, 0x200, 0x10000, 0x20000
|
||||
local FLAG_PATCH, FLAG_SINGLE, FLAG_DELETE, FLAG_CRC, FLAG_EXISTS = 0x100000, 0x1000000, 0x2000000, 0x4000000, 0x80000000
|
||||
local KEY_HASH_TABLE, KEY_BLOCK_TABLE = Crypt.hash("(hash table)", 3), Crypt.hash("(block table)", 3)
|
||||
local TWO32 = 4294967296
|
||||
local band = bit32.band
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ sniff
|
||||
function Mpq.sniff(r: Bytes.Reader): number
|
||||
local m = r:peek(4)
|
||||
if m == "MPQ\x1A" or m == "MPQ\x1B" then
|
||||
return 1
|
||||
end
|
||||
-- a prefixed archive (an installer stub): the header on a 512-byte boundary in the first 64 KB
|
||||
for at = 512, math.min(65536, r:remaining() - 32), 512 do
|
||||
if r:peek(4, at) == "MPQ\x1A" then
|
||||
return 0.6
|
||||
end
|
||||
end
|
||||
return 0
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ decode
|
||||
-- sparse: a big-endian u32 size, then runs: 0x80 | (n - 1) followed by n bytes, or n - 3 meaning n zeros
|
||||
local function unsparse(b: buffer, at: number, n: number, want: number): (buffer?, string?)
|
||||
local out = buffer.create(want)
|
||||
local p, stop, o = at + 4, at + n, 0
|
||||
while p < stop and o < want do
|
||||
local c = buffer.readu8(b, p)
|
||||
p += 1
|
||||
if c >= 0x80 then
|
||||
local k = c - 0x7F
|
||||
if p + k > stop then
|
||||
return nil, "sparse run past the end"
|
||||
end
|
||||
k = math.min(k, want - o)
|
||||
buffer.copy(out, o, b, p, k)
|
||||
p += k
|
||||
o += k
|
||||
else
|
||||
o = math.min(want, o + c + 3)
|
||||
end
|
||||
end
|
||||
return out, nil
|
||||
end
|
||||
|
||||
-- one compressed sector (mask byte first) -> want bytes
|
||||
local function decompress(b: buffer, at: number, n: number, want: number): (buffer?, Err.Err?)
|
||||
if n < 1 then
|
||||
return nil, Err.new(Err.CORRUPT, "empty compressed sector")
|
||||
end
|
||||
local mask = buffer.readu8(b, at)
|
||||
local cur: buffer, cat: number, cn: number = b, at + 1, n - 1
|
||||
if mask == 0x12 then
|
||||
if cn < 14 or buffer.readu8(b, cat) ~= 0 then
|
||||
return nil, Err.new(Err.UNSUPPORTED, "LZMA sector with a filter")
|
||||
end
|
||||
local props = buffer.readstring(b, cat + 1, 5)
|
||||
local out, e = Lzma.lzma(b, cat + 14, cn - 14, props, want, { maxBytes = want })
|
||||
if not out then
|
||||
return nil, e
|
||||
end
|
||||
return out, nil
|
||||
end
|
||||
if band(mask, 0xC1) ~= 0 then
|
||||
return nil, Err.new(Err.UNSUPPORTED, string.format("Huffman / ADPCM sector (mask 0x%02x)", mask))
|
||||
end
|
||||
if band(mask, 0x10) ~= 0 then
|
||||
local out, e = Bzip2.decompress(cur, cat, cn, { maxBytes = want })
|
||||
if not out then
|
||||
return nil, e
|
||||
end
|
||||
cur, cat, cn = out, 0, buffer.len(out)
|
||||
end
|
||||
if band(mask, 0x08) ~= 0 then
|
||||
local out, e = Explode.decompress(cur, cat, cn, want)
|
||||
if not out then
|
||||
return nil, e
|
||||
end
|
||||
cur, cat, cn = out, 0, buffer.len(out)
|
||||
end
|
||||
if band(mask, 0x02) ~= 0 then
|
||||
local out, e = Deflate.zlib(cur, cat, cn)
|
||||
if not out then
|
||||
return nil, e
|
||||
end
|
||||
cur, cat, cn = out, 0, buffer.len(out)
|
||||
end
|
||||
if band(mask, 0x20) ~= 0 then
|
||||
local out, msg = unsparse(cur, cat, cn, want)
|
||||
if not out then
|
||||
return nil, Err.from(msg)
|
||||
end
|
||||
cur, cat, cn = out, 0, buffer.len(out)
|
||||
end
|
||||
if band(mask, 0x3A) ~= mask then
|
||||
return nil, Err.new(Err.UNSUPPORTED, string.format("compression mask 0x%02x", mask))
|
||||
end
|
||||
if cn ~= want then
|
||||
return nil, Err.new(Err.CORRUPT, "sector decompressed to " .. tostring(cn) .. " bytes, expected " .. tostring(want))
|
||||
end
|
||||
if cur == b then
|
||||
local len = cn :: number
|
||||
local copy = buffer.create(len)
|
||||
buffer.copy(copy, 0, b, cat, len)
|
||||
return copy, nil
|
||||
end
|
||||
return cur, nil
|
||||
end
|
||||
|
||||
type Block = { offset: number, csize: number, size: number, flags: number }
|
||||
|
||||
-- read a file's bytes (the archive buffer, the absolute block offset, the file name for the key)
|
||||
local function readFile(b: buffer, limit: number, blk: Block, at: number, name: string?, sectorSize: number, maxBytes: number): (buffer?, Err.Err?)
|
||||
local flags = blk.flags
|
||||
if band(flags, FLAG_PATCH) ~= 0 then
|
||||
return nil, Err.new(Err.UNSUPPORTED, "patch files")
|
||||
end
|
||||
if blk.size > maxBytes then
|
||||
return nil, Err.new(Err.LIMIT, "file of " .. blk.size .. " bytes")
|
||||
end
|
||||
if at + blk.csize > limit then
|
||||
return nil, Err.new(Err.TRUNCATED, "file data past the end")
|
||||
end
|
||||
local encrypted = band(flags, FLAG_ENCRYPTED) ~= 0
|
||||
local key = 0
|
||||
if encrypted then
|
||||
if not name then
|
||||
return nil, Err.new(Err.UNSUPPORTED, "encrypted file without a known name")
|
||||
end
|
||||
key = Crypt.hash(Crypt.baseName(name), 3)
|
||||
if band(flags, FLAG_FIX_KEY) ~= 0 then
|
||||
key = bit32.bxor((key + blk.offset) % TWO32, blk.size % TWO32)
|
||||
end
|
||||
end
|
||||
local compressed = band(flags, FLAG_COMPRESS + FLAG_IMPLODE) ~= 0
|
||||
local imploded = band(flags, FLAG_IMPLODE) ~= 0
|
||||
local function sector(src: buffer, sat: number, sn: number, want: number, k: number): (buffer?, Err.Err?)
|
||||
local raw = buffer.create(sn)
|
||||
buffer.copy(raw, 0, src, sat, sn)
|
||||
if encrypted then
|
||||
Crypt.decrypt(raw, 0, sn, k)
|
||||
end
|
||||
if compressed and sn < want then
|
||||
if imploded then
|
||||
return Explode.decompress(raw, 0, sn, want)
|
||||
end
|
||||
return decompress(raw, 0, sn, want)
|
||||
end
|
||||
if sn ~= want then
|
||||
if sn > want then
|
||||
local cut = buffer.create(want)
|
||||
buffer.copy(cut, 0, raw, 0, want)
|
||||
return cut, nil
|
||||
end
|
||||
return nil, Err.new(Err.CORRUPT, "stored sector of " .. sn .. " bytes, expected " .. want)
|
||||
end
|
||||
return raw, nil
|
||||
end
|
||||
if band(flags, FLAG_SINGLE) ~= 0 then
|
||||
local out, e = sector(b, at, blk.csize, blk.size, key)
|
||||
if out and buffer.len(out) ~= blk.size then
|
||||
return nil, Err.new(Err.CORRUPT, "file size mismatch")
|
||||
end
|
||||
return out, e
|
||||
end
|
||||
local out = buffer.create(blk.size)
|
||||
local nsec = (blk.size + sectorSize - 1) // sectorSize
|
||||
if not compressed then
|
||||
-- stored in sectors (each decrypted with key + its index)
|
||||
for i = 0, nsec - 1 do
|
||||
local want = math.min(sectorSize, blk.size - i * sectorSize)
|
||||
local s, e = sector(b, at + i * sectorSize, want, want, key + i)
|
||||
if not s then
|
||||
return nil, e
|
||||
end
|
||||
buffer.copy(out, i * sectorSize, s, 0, want)
|
||||
end
|
||||
return out, nil
|
||||
end
|
||||
local entries = nsec + 1 + (if band(flags, FLAG_CRC) ~= 0 then 1 else 0)
|
||||
if entries * 4 > blk.csize then
|
||||
return nil, Err.new(Err.CORRUPT, "sector table larger than the file")
|
||||
end
|
||||
local tbl = buffer.create(entries * 4)
|
||||
buffer.copy(tbl, 0, b, at, entries * 4)
|
||||
if encrypted then
|
||||
Crypt.decrypt(tbl, 0, entries * 4, (key - 1) % TWO32)
|
||||
end
|
||||
for i = 0, nsec - 1 do
|
||||
local s0, s1 = buffer.readu32(tbl, i * 4), buffer.readu32(tbl, i * 4 + 4)
|
||||
if s1 < s0 or s1 > blk.csize then
|
||||
return nil, Err.new(Err.CORRUPT, "bad sector offset table")
|
||||
end
|
||||
local want = math.min(sectorSize, blk.size - i * sectorSize)
|
||||
local s, e = sector(b, at + s0, s1 - s0, want, key + i)
|
||||
if not s then
|
||||
return nil, e
|
||||
end
|
||||
if buffer.len(s) ~= want then
|
||||
return nil, Err.new(Err.CORRUPT, "sector " .. i .. " decompressed to " .. buffer.len(s) .. " bytes, expected " .. want)
|
||||
end
|
||||
buffer.copy(out, i * sectorSize, s, 0, want)
|
||||
end
|
||||
return out, nil
|
||||
end
|
||||
|
||||
local function encode(_archive: any, _opts: any?): (buffer?, Err.Err?)
|
||||
return nil, Err.new(Err.UNSUPPORTED, "MPQ archives are read-only")
|
||||
end
|
||||
|
||||
-- the header: its absolute offset in r (0, a 512-byte boundary, or behind "MPQ\x1B") | nil
|
||||
local function findHeader(r: Bytes.Reader): number?
|
||||
local size = r.limit - r.base
|
||||
local p = 0
|
||||
while p + 32 <= size do
|
||||
local m = buffer.readstring(r.buf, r.base + p, 4)
|
||||
if m == "MPQ\x1A" then
|
||||
return p
|
||||
elseif m == "MPQ\x1B" and p + 12 <= size then
|
||||
local at = p + buffer.readu32(r.buf, r.base + p + 8)
|
||||
if at + 32 <= size and buffer.readstring(r.buf, r.base + at, 4) == "MPQ\x1A" then
|
||||
return at
|
||||
end
|
||||
end
|
||||
p += 512
|
||||
end
|
||||
return nil
|
||||
end
|
||||
|
||||
function Mpq.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?)
|
||||
local found = findHeader(r)
|
||||
if not found then
|
||||
return nil, Err.new(if r:remaining() < 32 then Err.TRUNCATED else Err.CORRUPT, "no MPQ header", 0)
|
||||
end
|
||||
local h: number = found
|
||||
local hr = r:sub(h)
|
||||
hr:skip(4)
|
||||
local headerSize, archiveSize = hr:u32le(), hr:u32le()
|
||||
local version, shift = hr:u16le(), hr:u16le()
|
||||
local hashPos, blockPos, hashCount, blockCount = hr:u32le(), hr:u32le(), hr:u32le(), hr:u32le()
|
||||
local hiBlockPos, hashHi, blockHi = 0, 0, 0
|
||||
if version >= 1 and headerSize >= 44 then
|
||||
hiBlockPos = hr:u64le()
|
||||
hashHi, blockHi = hr:u16le(), hr:u16le()
|
||||
end
|
||||
if hr.err then
|
||||
return nil, hr.err
|
||||
end
|
||||
if shift > 20 then
|
||||
return nil, Err.new(Err.CORRUPT, "bad sector size shift " .. shift, h + 14)
|
||||
end
|
||||
local sectorSize = 512 * 2 ^ shift
|
||||
if hashCount == 0 then
|
||||
return nil, Err.new(Err.UNSUPPORTED, "no classic hash table (HET / BET only)")
|
||||
end
|
||||
local maxEntries: number = opts and opts.maxEntries or 1e6
|
||||
if hashCount > maxEntries * 4 or blockCount > maxEntries then
|
||||
return nil, Err.new(Err.LIMIT, "too many entries")
|
||||
end
|
||||
local size = r.limit - r.base
|
||||
local hashAt = h + hashPos + hashHi * TWO32
|
||||
local blockAt = h + blockPos + blockHi * TWO32
|
||||
if hashAt + hashCount * 16 > size or blockAt + blockCount * 16 > size then
|
||||
return nil, Err.new(Err.TRUNCATED, "hash / block table past the end", h + 16)
|
||||
end
|
||||
local hashes = buffer.create(hashCount * 16)
|
||||
buffer.copy(hashes, 0, r.buf, r.base + hashAt, hashCount * 16)
|
||||
Crypt.decrypt(hashes, 0, hashCount * 16, KEY_HASH_TABLE)
|
||||
local blocksBuf = buffer.create(blockCount * 16)
|
||||
buffer.copy(blocksBuf, 0, r.buf, r.base + blockAt, blockCount * 16)
|
||||
Crypt.decrypt(blocksBuf, 0, blockCount * 16, KEY_BLOCK_TABLE)
|
||||
local hiAt = if hiBlockPos > 0 then h + hiBlockPos else -1
|
||||
if hiAt >= 0 and hiAt + blockCount * 2 > size then
|
||||
hiAt = -1
|
||||
end
|
||||
local blocks: { Block } = {}
|
||||
for i = 0, blockCount - 1 do
|
||||
local hi = if hiAt >= 0 then buffer.readu16(r.buf, r.base + hiAt + i * 2) else 0
|
||||
blocks[i + 1] = {
|
||||
offset = buffer.readu32(blocksBuf, i * 16) + hi * TWO32,
|
||||
csize = buffer.readu32(blocksBuf, i * 16 + 4),
|
||||
size = buffer.readu32(blocksBuf, i * 16 + 8),
|
||||
flags = buffer.readu32(blocksBuf, i * 16 + 12),
|
||||
}
|
||||
end
|
||||
local maxBytes = opts and opts.maxBytes or 2 ^ 30
|
||||
local mask = hashCount - 1
|
||||
local pow2 = band(hashCount, mask) == 0
|
||||
-- lookup(name) -> block index (1-based) | nil
|
||||
local function lookup(name: string): number?
|
||||
local h0, h1, h2 = Crypt.hash(name, 0), Crypt.hash(name, 1), Crypt.hash(name, 2)
|
||||
local start = if pow2 then band(h0, mask) else h0 % hashCount
|
||||
for k = 0, hashCount - 1 do
|
||||
local o = ((start + k) % hashCount) * 16
|
||||
local bi = buffer.readu32(hashes, o + 12)
|
||||
if bi == 0xFFFFFFFF then
|
||||
return nil
|
||||
end
|
||||
if bi ~= 0xFFFFFFFE and buffer.readu32(hashes, o) == h1 and buffer.readu32(hashes, o + 4) == h2 and bi < blockCount then
|
||||
return bi + 1
|
||||
end
|
||||
end
|
||||
return nil
|
||||
end
|
||||
local function usable(bi: number): boolean
|
||||
local f = blocks[bi].flags
|
||||
return band(f, FLAG_EXISTS) ~= 0 and band(f, FLAG_DELETE) == 0
|
||||
end
|
||||
local function blockData(bi: number, name: string?): (buffer?, Err.Err?)
|
||||
local blk = blocks[bi]
|
||||
return readFile(r.buf, r.limit, blk, r.base + h + blk.offset, name, sectorSize, maxBytes)
|
||||
end
|
||||
-- names: (listfile) and opts.names
|
||||
local names: { string } = {}
|
||||
for _, internal in { "(attributes)", "(signature)", "(user data)" } do
|
||||
table.insert(names, internal)
|
||||
end
|
||||
local lf = lookup("(listfile)")
|
||||
if lf and usable(lf) then
|
||||
table.insert(names, "(listfile)")
|
||||
local data = blockData(lf, "(listfile)")
|
||||
if data then
|
||||
for line in string.gmatch(buffer.tostring(data), "[^\r\n;]+") do
|
||||
local nm = string.match(line, "^%s*(.-)%s*$")
|
||||
if nm and nm ~= "" then
|
||||
table.insert(names, nm)
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
if opts and type(opts.names) == "table" then
|
||||
for _, nm in opts.names do
|
||||
if type(nm) == "string" then
|
||||
table.insert(names, nm)
|
||||
end
|
||||
end
|
||||
end
|
||||
local a = Archive.new("mpq", encode)
|
||||
local named: { [number]: string } = {}
|
||||
local function add(bi: number, name: string?)
|
||||
local blk = blocks[bi]
|
||||
local entryName = name or string.format("File%08d.xxx", bi - 1)
|
||||
Archive.put(a, {
|
||||
name = entryName,
|
||||
size = blk.size,
|
||||
compressedSize = blk.csize,
|
||||
dir = false,
|
||||
method = if band(blk.flags, FLAG_IMPLODE) ~= 0 then "implode" elseif band(blk.flags, FLAG_COMPRESS) ~= 0 then "compress" else "store",
|
||||
encrypted = band(blk.flags, FLAG_ENCRYPTED) ~= 0,
|
||||
flags = blk.flags,
|
||||
block = bi - 1,
|
||||
load = function(): (buffer?, Err.Err?)
|
||||
return blockData(bi, name)
|
||||
end,
|
||||
})
|
||||
end
|
||||
for _, nm in names do
|
||||
local bi = lookup(nm)
|
||||
if bi and usable(bi) and not named[bi] then
|
||||
named[bi] = nm
|
||||
add(bi, nm)
|
||||
end
|
||||
end
|
||||
for bi = 1, blockCount do
|
||||
if not named[bi] and usable(bi) and blocks[bi].size > 0 then
|
||||
add(bi, nil)
|
||||
end
|
||||
end
|
||||
a.meta.source = { format = "mpq", version = version + 1, sectorSize = sectorSize, offset = h, archiveSize = archiveSize, hashTable = hashCount, blockTable = blockCount }
|
||||
return a, nil
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ extras
|
||||
-- hash(name, kind) -> the MPQ name hash (kind 0 = table index, 1 / 2 = name checks, 3 = file key)
|
||||
Mpq.hash = Crypt.hash
|
||||
|
||||
return Mpq
|
||||
@@ -0,0 +1,317 @@
|
||||
--!strict
|
||||
-- archive/vpk: Valve VPK archives (Source / Source 2: version 1 and 2 directory files, "pak01_dir.vpk"), read into the
|
||||
-- standard Archive and written from any Archive value. Reading: the extension / path / name tree, preload bytes
|
||||
-- (stored in the tree) followed by the data, data embedded in the directory file (archive index 0x7fff) or in the
|
||||
-- numbered part files "<name>_NNN.vpk", found through opts.resolve(fileName) / opts.files[fileName] (the name comes
|
||||
-- from opts.name, "x_dir.vpk" -> "x_000.vpk", default "pak01"); each entry's CRC-32 is checked on read; version 2's
|
||||
-- MD5 section is kept in meta. Writing: one self-contained directory file (every entry embedded, no preload),
|
||||
-- version 2 by default with its tree / chunk / file MD5s (version = 1 for the older header). Written from the
|
||||
-- Valve Developer Community VPK file format page; no code taken.
|
||||
-- Not supported: Respawn (Titanfall) VPKs, signature checks, writing multi-part archives.
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ requires
|
||||
local Err = require("@formats/core/Err")
|
||||
local Bytes = require("@formats/core/Bytes")
|
||||
local Input = require("@formats/core/Input")
|
||||
local Crc32 = require("@formats/core/Crc32")
|
||||
local Md5 = require("@formats/core/Md5")
|
||||
local Archive = require("@formats/containers/Archive")
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ contract
|
||||
local Vpk = {
|
||||
name = "vpk",
|
||||
category = "archive",
|
||||
extensions = { "vpk" },
|
||||
mime = { "application/x-vpk" },
|
||||
deps = { "core/Err", "core/Bytes", "core/Input", "core/Crc32", "core/Md5", "containers/Archive" },
|
||||
caps = { decode = true, encode = true, versions = { 1, 2 }, multipart = true },
|
||||
}
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ types
|
||||
export type DecodeOptions = {
|
||||
verify: boolean?, -- check each entry's CRC-32 on read (default true)
|
||||
resolve: ((name: string) -> (buffer | string)?)?, -- the part files ("pak01_000.vpk", ...)
|
||||
files: { [string]: buffer | string }?,
|
||||
name: string?, -- the directory file's name ("pak01_dir.vpk"), for the part file names
|
||||
maxEntries: number?, -- default 1e6
|
||||
}
|
||||
export type EncodeOptions = { version: number? } -- 1 or 2 (default: the source's, else 2)
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ constants
|
||||
local SIGNATURE = 0x55AA1234
|
||||
local EMBEDDED = 0x7FFF
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ sniff
|
||||
function Vpk.sniff(r: Bytes.Reader): number
|
||||
if r:remaining() < 12 or r:peek(4) ~= "\x34\x12\xAA\x55" then
|
||||
return 0
|
||||
end
|
||||
local v = r:peekU8(4)
|
||||
return if v == 1 or v == 2 then 1 else 0.5
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ decode
|
||||
local function encode(archive: any, opts: any?): (buffer?, Err.Err?)
|
||||
return Vpk.encode(archive, opts)
|
||||
end
|
||||
|
||||
-- the part file `index` as a buffer (cached per archive)
|
||||
local function partLoader(opts: DecodeOptions?): (number) -> (buffer?, Err.Err?)
|
||||
local cache: { [number]: buffer } = {}
|
||||
local prefix = "pak01"
|
||||
if opts and type(opts.name) == "string" then
|
||||
local base = string.match(opts.name, "([^/\\]+)$") or opts.name
|
||||
prefix = string.match(base, "^(.*)_dir%.[vV][pP][kK]$") or string.match(base, "^(.*)%.[vV][pP][kK]$") or base
|
||||
end
|
||||
return function(index: number): (buffer?, Err.Err?)
|
||||
local hit = cache[index]
|
||||
if hit then
|
||||
return hit, nil
|
||||
end
|
||||
local name = string.format("%s_%03d.vpk", prefix, index)
|
||||
local b = Input.sibling(opts, name)
|
||||
if not b then
|
||||
return nil, Err.new(Err.UNSUPPORTED, "part file " .. name .. " not available (opts.resolve / opts.files)")
|
||||
end
|
||||
cache[index] = b
|
||||
return b, nil
|
||||
end
|
||||
end
|
||||
|
||||
local function loader(r: Bytes.Reader, e: any, dataBase: number, part: (number) -> (buffer?, Err.Err?), verify: boolean): () -> (buffer?, Err.Err?)
|
||||
return function(): (buffer?, Err.Err?)
|
||||
local src: buffer, at: number
|
||||
if e.archiveIndex == EMBEDDED then
|
||||
src, at = r.buf, r.base + dataBase + e.archiveOffset
|
||||
if dataBase + e.archiveOffset + e.length > r.limit - r.base then
|
||||
return nil, Err.new(Err.TRUNCATED, "entry " .. e.name .. " past the end")
|
||||
end
|
||||
else
|
||||
local b, err = part(e.archiveIndex)
|
||||
if not b then
|
||||
return nil, err
|
||||
end
|
||||
src, at = b, e.archiveOffset
|
||||
if at + e.length > buffer.len(b) then
|
||||
return nil, Err.new(Err.TRUNCATED, "entry " .. e.name .. " past the end of part " .. e.archiveIndex)
|
||||
end
|
||||
end
|
||||
local out = buffer.create(e.preloadLength + e.length)
|
||||
buffer.copy(out, 0, r.buf, e.preloadAt, e.preloadLength)
|
||||
buffer.copy(out, e.preloadLength, src, at, e.length)
|
||||
if verify and Crc32.of(out) ~= e.crc32 then
|
||||
return nil, Err.new(Err.CHECKSUM, "entry " .. e.name .. ": CRC-32 mismatch")
|
||||
end
|
||||
return out, nil
|
||||
end
|
||||
end
|
||||
|
||||
function Vpk.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?)
|
||||
local sig, version, treeSize = r:u32le(), r:u32le(), r:u32le()
|
||||
if r.err then
|
||||
return nil, r.err
|
||||
end
|
||||
if sig ~= SIGNATURE then
|
||||
return nil, Err.new(Err.CORRUPT, "bad signature", 0)
|
||||
end
|
||||
if version ~= 1 and version ~= 2 then
|
||||
return nil, Err.new(Err.UNSUPPORTED, "VPK version " .. version, 4)
|
||||
end
|
||||
local v2: any = nil
|
||||
if version == 2 then
|
||||
v2 = { fileDataSize = r:u32le(), archiveMd5Size = r:u32le(), otherMd5Size = r:u32le(), signatureSize = r:u32le() }
|
||||
if r.err then
|
||||
return nil, r.err
|
||||
end
|
||||
end
|
||||
local headerLen = r:tell() - r.base
|
||||
if headerLen + treeSize > r.limit - r.base then
|
||||
return nil, Err.new(Err.TRUNCATED, "tree past the end", 8)
|
||||
end
|
||||
local t = r:sub(headerLen, treeSize)
|
||||
local a = Archive.new("vpk", encode)
|
||||
local part = partLoader(opts)
|
||||
local verify = not (opts and opts.verify == false)
|
||||
local maxEntries = opts and opts.maxEntries or 1e6
|
||||
local count = 0
|
||||
local parts: { [number]: boolean } = {}
|
||||
local dataBase = headerLen + treeSize
|
||||
while true do
|
||||
local ext = t:cstring()
|
||||
if t.err then
|
||||
return nil, t.err
|
||||
end
|
||||
if ext == "" then
|
||||
break
|
||||
end
|
||||
while true do
|
||||
local path = t:cstring()
|
||||
if t.err then
|
||||
return nil, t.err
|
||||
end
|
||||
if path == "" then
|
||||
break
|
||||
end
|
||||
while true do
|
||||
local name = t:cstring()
|
||||
if t.err then
|
||||
return nil, t.err
|
||||
end
|
||||
if name == "" then
|
||||
break
|
||||
end
|
||||
local e: any = { crc32 = t:u32le(), preloadLength = t:u16le(), archiveIndex = t:u16le(), archiveOffset = t:u32le(), length = t:u32le() }
|
||||
local term = t:u16le()
|
||||
e.preloadAt = t.pos
|
||||
t:skip(e.preloadLength)
|
||||
if t.err then
|
||||
return nil, t.err
|
||||
end
|
||||
if term ~= 0xFFFF then
|
||||
return nil, Err.new(Err.CORRUPT, "bad entry terminator", t:tell() + headerLen)
|
||||
end
|
||||
count += 1
|
||||
if count > maxEntries then
|
||||
return nil, Err.new(Err.LIMIT, "too many entries")
|
||||
end
|
||||
local full = (if path == " " then "" else path .. "/") .. name .. (if ext == " " then "" else "." .. ext)
|
||||
e.name = full
|
||||
if e.archiveIndex ~= EMBEDDED then
|
||||
parts[e.archiveIndex] = true
|
||||
end
|
||||
Archive.put(a, {
|
||||
name = full,
|
||||
size = e.preloadLength + e.length,
|
||||
dir = false,
|
||||
method = "store",
|
||||
crc32 = e.crc32,
|
||||
archiveIndex = if e.archiveIndex == EMBEDDED then nil else e.archiveIndex,
|
||||
preload = e.preloadLength,
|
||||
load = loader(r, e, dataBase, part, verify),
|
||||
})
|
||||
end
|
||||
end
|
||||
end
|
||||
local partList: { number } = {}
|
||||
for k in parts do
|
||||
table.insert(partList, k)
|
||||
end
|
||||
table.sort(partList)
|
||||
a.meta.source = { format = "vpk", version = version, entries = count, parts = partList }
|
||||
if v2 then
|
||||
local md5At = dataBase + v2.fileDataSize
|
||||
if v2.otherMd5Size == 48 and md5At + v2.archiveMd5Size + 48 <= r.limit - r.base then
|
||||
local m = r:sub(md5At + v2.archiveMd5Size, 48)
|
||||
v2.treeMd5, v2.chunkHashesMd5, v2.fileMd5 = m:string(16), m:string(16), m:string(16)
|
||||
end
|
||||
a.meta.source.v2 = v2
|
||||
end
|
||||
return a, nil
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ encode
|
||||
function Vpk.encode(archive: any, opts: EncodeOptions?): (buffer?, Err.Err?)
|
||||
local items, err = Archive.collect(archive)
|
||||
if not items then
|
||||
return nil, err
|
||||
end
|
||||
local src = type(archive) == "table" and type(archive.meta) == "table" and archive.meta.source
|
||||
local version = opts and opts.version or (if type(src) == "table" and src.format == "vpk" then src.version else nil) or 2
|
||||
if version ~= 1 and version ~= 2 then
|
||||
return nil, Err.new(Err.ARG, "version must be 1 or 2")
|
||||
end
|
||||
-- group by extension, then path, keeping first-seen order
|
||||
local exts: { string } = {}
|
||||
local byExt: { [string]: { paths: { string }, byPath: { [string]: { { name: string, data: buffer } } } } } = {}
|
||||
for _, it in items do
|
||||
if not it.entry.dir then
|
||||
local full = string.gsub(it.entry.name, "\\", "/")
|
||||
local dir, file = string.match(full, "^(.*)/([^/]*)$")
|
||||
if not dir then
|
||||
dir, file = " ", full
|
||||
end
|
||||
local stem, ext = string.match(file :: string, "^(.*)%.([^.]*)$")
|
||||
if not stem or stem == "" then
|
||||
stem, ext = file, " "
|
||||
end
|
||||
if stem == "" or dir == "" or string.find(full, "\0", 1, true) then
|
||||
return nil, Err.new(Err.ARG, "bad entry name: " .. it.entry.name)
|
||||
end
|
||||
local g = byExt[ext :: string]
|
||||
if not g then
|
||||
g = { paths = {}, byPath = {} }
|
||||
byExt[ext :: string] = g
|
||||
table.insert(exts, ext :: string)
|
||||
end
|
||||
local l = g.byPath[dir :: string]
|
||||
if not l then
|
||||
l = {}
|
||||
g.byPath[dir :: string] = l
|
||||
table.insert(g.paths, dir :: string)
|
||||
end
|
||||
table.insert(l, { name = stem :: string, data = it.data })
|
||||
end
|
||||
end
|
||||
local tree = Bytes.writer()
|
||||
local data = Bytes.writer()
|
||||
for _, ext in exts do
|
||||
tree:cstring(ext)
|
||||
local g = byExt[ext]
|
||||
for _, path in g.paths do
|
||||
tree:cstring(path)
|
||||
for _, f in g.byPath[path] do
|
||||
tree:cstring(f.name)
|
||||
tree:u32le(Crc32.of(f.data))
|
||||
tree:u16le(0)
|
||||
tree:u16le(EMBEDDED)
|
||||
tree:u32le(data:tell())
|
||||
tree:u32le(buffer.len(f.data))
|
||||
tree:u16le(0xFFFF)
|
||||
data:bytes(f.data)
|
||||
end
|
||||
tree:u8(0)
|
||||
end
|
||||
tree:u8(0)
|
||||
end
|
||||
tree:u8(0)
|
||||
local tb, db = tree:finish(), data:finish()
|
||||
local w = Bytes.writer(buffer.len(tb) + buffer.len(db) + 128)
|
||||
w:u32le(SIGNATURE)
|
||||
w:u32le(version)
|
||||
w:u32le(buffer.len(tb))
|
||||
if version == 2 then
|
||||
w:u32le(buffer.len(db))
|
||||
w:u32le(0)
|
||||
w:u32le(48)
|
||||
w:u32le(0)
|
||||
end
|
||||
w:bytes(tb)
|
||||
w:bytes(db)
|
||||
if version == 2 then
|
||||
local treeMd5 = Md5.new()
|
||||
treeMd5:update(tb)
|
||||
local tmd = treeMd5:digest()
|
||||
local chunkMd5 = Md5.new():digest()
|
||||
local file = Md5.new()
|
||||
local sofar = w:finish()
|
||||
file:update(sofar)
|
||||
file:update(buffer.fromstring(tmd .. chunkMd5))
|
||||
local out = Bytes.writer(buffer.len(sofar) + 48)
|
||||
out:bytes(sofar)
|
||||
out:string(tmd)
|
||||
out:string(chunkMd5)
|
||||
out:string(file:digest())
|
||||
return out:finish(), nil
|
||||
end
|
||||
return w:finish(), nil
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ extras
|
||||
-- new(version?) -> an empty VPK Archive (version 2 by default): a:add(name, data); a:write()
|
||||
function Vpk.new(version: number?): any
|
||||
local a = Archive.new("vpk", encode)
|
||||
a.meta.source = { format = "vpk", version = version or 2 }
|
||||
return a
|
||||
end
|
||||
|
||||
return Vpk
|
||||
@@ -0,0 +1,441 @@
|
||||
--!strict
|
||||
-- archive/wad/Map: a Doom / Heretic / Hexen map (the binary lumps after a map marker: THINGS, LINEDEFS, SIDEDEFS,
|
||||
-- VERTEXES, SECTORS; Hexen format when BEHAVIOR is present) parsed into plain tables (Map.parse) and built into a
|
||||
-- Scene (Map.scene): sector floors and ceilings (sector outlines chained from the linedefs, triangulated with
|
||||
-- codecs/model/Polygon), walls (one-sided middles; lower / upper walls and masked middles of two-sided lines, the
|
||||
-- sky hack between two sky ceilings) with the vanilla texture alignment (x / y offsets, upper / lower unpegged), one
|
||||
-- primitive per flat / wall texture, things as child nodes standing on their sector's floor. Units are map units, z
|
||||
-- up. Written from the Unofficial Doom Specs and the Hexen specs; no code taken. UDMF (TEXTMAP) maps are not
|
||||
-- supported.
|
||||
local Types = require("@formats/Types")
|
||||
local Polygon = require("@formats/codecs/model/Polygon")
|
||||
|
||||
local Map = {}
|
||||
|
||||
local Scene = Types.Scene
|
||||
local readu8, readi16, readu16 = buffer.readu8, buffer.readi16, buffer.readu16
|
||||
local writef32, writeu32 = buffer.writef32, buffer.writeu32
|
||||
|
||||
export type Lump = { buf: buffer, at: number, size: number }
|
||||
export type Thing = { x: number, y: number, z: number?, angle: number, type: number, flags: number, tid: number?, special: number?, args: { number }? }
|
||||
export type Linedef = { v1: number, v2: number, flags: number, special: number, tag: number?, args: { number }?, front: number?, back: number? }
|
||||
export type Sidedef = { xoff: number, yoff: number, upper: string, lower: string, middle: string, sector: number }
|
||||
export type Sector = { floor: number, ceiling: number, floorFlat: string, ceilingFlat: string, light: number, special: number, tag: number }
|
||||
export type MapData = {
|
||||
format: "doom" | "hexen",
|
||||
things: { Thing },
|
||||
linedefs: { Linedef },
|
||||
sidedefs: { Sidedef },
|
||||
vertices: { number }, -- x1, y1, x2, y2, ...
|
||||
sectors: { Sector },
|
||||
}
|
||||
-- texture sizes / images by kind ("flat" | "texture") and name: what the WAD knows
|
||||
export type Textures = {
|
||||
size: (kind: string, name: string) -> (number?, number?),
|
||||
image: ((kind: string, name: string) -> Types.Image?)?,
|
||||
}
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ parse
|
||||
local function name8(b: buffer, at: number): string
|
||||
local s = buffer.readstring(b, at, 8)
|
||||
local z = string.find(s, "\0", 1, true)
|
||||
return string.upper(if z then string.sub(s, 1, z - 1) else s)
|
||||
end
|
||||
|
||||
local function side(v: number): number?
|
||||
return if v == 0xFFFF then nil else v + 1
|
||||
end
|
||||
|
||||
-- parse(lumps, hexen) -> MapData | nil, message: lumps = { THINGS, LINEDEFS, SIDEDEFS, VERTEXES, SECTORS } (Lump)
|
||||
function Map.parse(lumps: { [string]: Lump }, hexen: boolean): (MapData?, string?)
|
||||
for _, k in { "LINEDEFS", "SIDEDEFS", "VERTEXES", "SECTORS" } do
|
||||
if not lumps[k] then
|
||||
return nil, "map has no " .. k
|
||||
end
|
||||
end
|
||||
local m: MapData = { format = if hexen then "hexen" else "doom", things = {}, linedefs = {}, sidedefs = {}, vertices = {}, sectors = {} }
|
||||
local v = lumps.VERTEXES
|
||||
for i = 0, v.size // 4 - 1 do
|
||||
table.insert(m.vertices, readi16(v.buf, v.at + i * 4))
|
||||
table.insert(m.vertices, readi16(v.buf, v.at + i * 4 + 2))
|
||||
end
|
||||
local s = lumps.SECTORS
|
||||
for i = 0, s.size // 26 - 1 do
|
||||
local o = s.at + i * 26
|
||||
table.insert(m.sectors, {
|
||||
floor = readi16(s.buf, o),
|
||||
ceiling = readi16(s.buf, o + 2),
|
||||
floorFlat = name8(s.buf, o + 4),
|
||||
ceilingFlat = name8(s.buf, o + 12),
|
||||
light = readi16(s.buf, o + 20),
|
||||
special = readu16(s.buf, o + 22),
|
||||
tag = readu16(s.buf, o + 24),
|
||||
})
|
||||
end
|
||||
local sd = lumps.SIDEDEFS
|
||||
for i = 0, sd.size // 30 - 1 do
|
||||
local o = sd.at + i * 30
|
||||
table.insert(m.sidedefs, {
|
||||
xoff = readi16(sd.buf, o),
|
||||
yoff = readi16(sd.buf, o + 2),
|
||||
upper = name8(sd.buf, o + 4),
|
||||
lower = name8(sd.buf, o + 12),
|
||||
middle = name8(sd.buf, o + 20),
|
||||
sector = readu16(sd.buf, o + 28) + 1,
|
||||
})
|
||||
end
|
||||
local l = lumps.LINEDEFS
|
||||
local ls = if hexen then 16 else 14
|
||||
for i = 0, l.size // ls - 1 do
|
||||
local o = l.at + i * ls
|
||||
local b = l.buf
|
||||
if hexen then
|
||||
table.insert(m.linedefs, {
|
||||
v1 = readu16(b, o) + 1,
|
||||
v2 = readu16(b, o + 2) + 1,
|
||||
flags = readu16(b, o + 4),
|
||||
special = readu8(b, o + 6),
|
||||
args = { readu8(b, o + 7), readu8(b, o + 8), readu8(b, o + 9), readu8(b, o + 10), readu8(b, o + 11) },
|
||||
front = side(readu16(b, o + 12)),
|
||||
back = side(readu16(b, o + 14)),
|
||||
})
|
||||
else
|
||||
table.insert(m.linedefs, {
|
||||
v1 = readu16(b, o) + 1,
|
||||
v2 = readu16(b, o + 2) + 1,
|
||||
flags = readu16(b, o + 4),
|
||||
special = readu16(b, o + 6),
|
||||
tag = readu16(b, o + 8),
|
||||
front = side(readu16(b, o + 10)),
|
||||
back = side(readu16(b, o + 12)),
|
||||
})
|
||||
end
|
||||
end
|
||||
local t = lumps.THINGS
|
||||
if t then
|
||||
local ts = if hexen then 20 else 10
|
||||
for i = 0, t.size // ts - 1 do
|
||||
local o = t.at + i * ts
|
||||
local b = t.buf
|
||||
if hexen then
|
||||
table.insert(m.things, {
|
||||
tid = readi16(b, o),
|
||||
x = readi16(b, o + 2),
|
||||
y = readi16(b, o + 4),
|
||||
z = readi16(b, o + 6),
|
||||
angle = readi16(b, o + 8),
|
||||
type = readu16(b, o + 10),
|
||||
flags = readu16(b, o + 12),
|
||||
special = readu8(b, o + 14),
|
||||
args = { readu8(b, o + 15), readu8(b, o + 16), readu8(b, o + 17), readu8(b, o + 18), readu8(b, o + 19) },
|
||||
})
|
||||
else
|
||||
table.insert(m.things, {
|
||||
x = readi16(b, o),
|
||||
y = readi16(b, o + 2),
|
||||
angle = readi16(b, o + 4),
|
||||
type = readu16(b, o + 6),
|
||||
flags = readu16(b, o + 8),
|
||||
})
|
||||
end
|
||||
end
|
||||
end
|
||||
return m, nil
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ sector outlines
|
||||
-- loops(m) -> loops[sector] = { { vertex ids } }: each sector's edges (front sides v1 -> v2, back sides v2 -> v1;
|
||||
-- lines with the sector on both sides left out) chained into closed loops, taking the sharpest right turn at forks;
|
||||
-- chains that do not close are dropped
|
||||
local function loops(m: MapData): { [number]: { { number } } }
|
||||
local edges: { [number]: { { number } } } = {}
|
||||
local nv = #m.vertices // 2
|
||||
local function add(sec: number, a: number, b: number)
|
||||
local e = edges[sec] or {}
|
||||
edges[sec] = e
|
||||
table.insert(e, { a, b })
|
||||
end
|
||||
for _, ld in m.linedefs do
|
||||
if ld.v1 >= 1 and ld.v1 <= nv and ld.v2 >= 1 and ld.v2 <= nv and ld.v1 ~= ld.v2 then
|
||||
local fs = ld.front and m.sidedefs[ld.front]
|
||||
local bs = ld.back and m.sidedefs[ld.back]
|
||||
local f = fs and fs.sector
|
||||
local b = bs and bs.sector
|
||||
if f ~= b then
|
||||
if f and m.sectors[f] then
|
||||
add(f, ld.v1, ld.v2)
|
||||
end
|
||||
if b and m.sectors[b] then
|
||||
add(b, ld.v2, ld.v1)
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
local V = m.vertices
|
||||
local out: { [number]: { { number } } } = {}
|
||||
for sec, list in edges do
|
||||
local from: { [number]: { number } } = {}
|
||||
for i, e in list do
|
||||
local l = from[e[1]] or {}
|
||||
from[e[1]] = l
|
||||
table.insert(l, i)
|
||||
end
|
||||
local used: { [number]: boolean } = {}
|
||||
local res: { { number } } = {}
|
||||
for start = 1, #list do
|
||||
if not used[start] then
|
||||
used[start] = true
|
||||
local loop = { list[start][1] }
|
||||
local cur = start
|
||||
local closed = false
|
||||
for _ = 1, #list do
|
||||
local e = list[cur]
|
||||
local at = e[2]
|
||||
if at == loop[1] then
|
||||
closed = true
|
||||
break
|
||||
end
|
||||
table.insert(loop, at)
|
||||
local cands = from[at]
|
||||
local best, bestT = nil :: number?, math.huge
|
||||
if cands then
|
||||
local ix, iy = V[at * 2 - 1] - V[e[1] * 2 - 1], V[at * 2] - V[e[1] * 2]
|
||||
for _, c in cands do
|
||||
if not used[c] then
|
||||
local n2 = list[c][2]
|
||||
local ox, oy = V[n2 * 2 - 1] - V[at * 2 - 1], V[n2 * 2] - V[at * 2]
|
||||
local t = math.atan2(ix * oy - iy * ox, ix * ox + iy * oy)
|
||||
if t < bestT then
|
||||
best, bestT = c, t
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
if not best then
|
||||
break
|
||||
end
|
||||
used[best] = true
|
||||
cur = best
|
||||
end
|
||||
if closed and #loop >= 3 then
|
||||
table.insert(res, loop)
|
||||
end
|
||||
end
|
||||
end
|
||||
out[sec] = res
|
||||
end
|
||||
return out
|
||||
end
|
||||
|
||||
local function insideLoop(V: { number }, loop: { number }, x: number, y: number): boolean
|
||||
local c = false
|
||||
local n = #loop
|
||||
local j = n
|
||||
for i = 1, n do
|
||||
local ax, ay = V[loop[i] * 2 - 1], V[loop[i] * 2]
|
||||
local bx, by = V[loop[j] * 2 - 1], V[loop[j] * 2]
|
||||
if (ay > y) ~= (by > y) and x < (bx - ax) * (y - ay) / (by - ay) + ax then
|
||||
c = not c
|
||||
end
|
||||
j = i
|
||||
end
|
||||
return c
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ scene
|
||||
type Batch = { kind: string, name: string, pos: { number }, nrm: { number }, uv: { number } }
|
||||
|
||||
local LOWER_UNPEGGED, UPPER_UNPEGGED, TWO_SIDED = 16, 8, 4
|
||||
|
||||
-- scene(m, tex, name) -> Scene
|
||||
function Map.scene(m: MapData, tex: Textures, name: string?): Types.Scene
|
||||
local batches: { [string]: Batch } = {}
|
||||
local order: { string } = {}
|
||||
local function batch(kind: string, tname: string): Batch
|
||||
local key = kind .. ":" .. tname
|
||||
local b = batches[key]
|
||||
if not b then
|
||||
b = { kind = kind, name = tname, pos = {}, nrm = {}, uv = {} }
|
||||
batches[key] = b
|
||||
table.insert(order, key)
|
||||
end
|
||||
return b
|
||||
end
|
||||
local function vert(b: Batch, x: number, y: number, z: number, nx: number, ny: number, nz: number, u: number, v: number)
|
||||
local p, n, t = b.pos, b.nrm, b.uv
|
||||
p[#p + 1], p[#p + 2], p[#p + 3] = x, y, z
|
||||
n[#n + 1], n[#n + 2], n[#n + 3] = nx, ny, nz
|
||||
t[#t + 1], t[#t + 2] = u, v
|
||||
end
|
||||
local V = m.vertices
|
||||
local nv = #V // 2
|
||||
-- floors and ceilings
|
||||
local secLoops = loops(m)
|
||||
for sec, ls in secLoops do
|
||||
local s = m.sectors[sec]
|
||||
local flat: { { number } } = {}
|
||||
for li, loop in ls do
|
||||
local f: { number } = {}
|
||||
for _, vi in loop do
|
||||
table.insert(f, V[vi * 2 - 1])
|
||||
table.insert(f, V[vi * 2])
|
||||
end
|
||||
flat[li] = f
|
||||
end
|
||||
local tris = Polygon.triangulate(flat)
|
||||
for pass = 1, 2 do
|
||||
local tname = if pass == 1 then s.floorFlat else s.ceilingFlat
|
||||
local fw, fh = tex.size("flat", tname)
|
||||
local w, h = fw or 64, fh or 64
|
||||
local z = if pass == 1 then s.floor else s.ceiling
|
||||
local b = batch("flat", tname)
|
||||
local nz = if pass == 1 then 1 else -1
|
||||
for k = 1, #tris, 6 do
|
||||
for c = 0, 2 do
|
||||
local cc = if pass == 1 then c else 2 - c
|
||||
local loop = ls[tris[k + cc * 2]]
|
||||
local vi = loop[tris[k + cc * 2 + 1]]
|
||||
local x, y = V[vi * 2 - 1], V[vi * 2]
|
||||
vert(b, x, y, z, 0, 0, nz, x / w, -y / h)
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
-- walls
|
||||
local function quad(tname: string, x1: number, y1: number, x2: number, y2: number, zb: number, zt: number, xoff: number, len: number, texTop: number, yoff: number)
|
||||
if tname == "-" or tname == "" or zt <= zb then
|
||||
return
|
||||
end
|
||||
local tw, th = tex.size("texture", tname)
|
||||
local w, h = tw or 64, th or 128
|
||||
local b = batch("texture", tname)
|
||||
local dx, dy = x2 - x1, y2 - y1
|
||||
local l = math.sqrt(dx * dx + dy * dy)
|
||||
local nx, ny = dy / l, -dx / l
|
||||
local u0, u1 = xoff / w, (xoff + len) / w
|
||||
local vb, vt = (texTop - zb + yoff) / h, (texTop - zt + yoff) / h
|
||||
vert(b, x1, y1, zb, nx, ny, 0, u0, vb)
|
||||
vert(b, x2, y2, zb, nx, ny, 0, u1, vb)
|
||||
vert(b, x2, y2, zt, nx, ny, 0, u1, vt)
|
||||
vert(b, x1, y1, zb, nx, ny, 0, u0, vb)
|
||||
vert(b, x2, y2, zt, nx, ny, 0, u1, vt)
|
||||
vert(b, x1, y1, zt, nx, ny, 0, u0, vt)
|
||||
end
|
||||
for _, ld in m.linedefs do
|
||||
if ld.v1 >= 1 and ld.v1 <= nv and ld.v2 >= 1 and ld.v2 <= nv and ld.v1 ~= ld.v2 then
|
||||
local ax, ay, bx, by = V[ld.v1 * 2 - 1], V[ld.v1 * 2], V[ld.v2 * 2 - 1], V[ld.v2 * 2]
|
||||
local len = math.sqrt((bx - ax) ^ 2 + (by - ay) ^ 2)
|
||||
for sideN = 1, 2 do
|
||||
local sdi = if sideN == 1 then ld.front else ld.back
|
||||
local odi = if sideN == 1 then ld.back else ld.front
|
||||
local sd = sdi and m.sidedefs[sdi]
|
||||
local me = sd and m.sectors[sd.sector]
|
||||
if sd and me then
|
||||
local x1, y1, x2, y2 = ax, ay, bx, by
|
||||
if sideN == 2 then
|
||||
x1, y1, x2, y2 = bx, by, ax, ay
|
||||
end
|
||||
local od = odi and m.sidedefs[odi]
|
||||
local other = od and m.sectors[od.sector]
|
||||
if not other then
|
||||
local th = select(2, tex.size("texture", sd.middle)) or 128
|
||||
local top = if bit32.band(ld.flags, LOWER_UNPEGGED) ~= 0 then me.floor + th else me.ceiling
|
||||
quad(sd.middle, x1, y1, x2, y2, me.floor, me.ceiling, sd.xoff, len, top, sd.yoff)
|
||||
else
|
||||
if other.floor > me.floor then
|
||||
local top = if bit32.band(ld.flags, LOWER_UNPEGGED) ~= 0 then me.ceiling else other.floor
|
||||
quad(sd.lower, x1, y1, x2, y2, me.floor, other.floor, sd.xoff, len, top, sd.yoff)
|
||||
end
|
||||
local sky = string.sub(me.ceilingFlat, 1, 5) == "F_SKY" and string.sub(other.ceilingFlat, 1, 5) == "F_SKY"
|
||||
if other.ceiling < me.ceiling and not sky then
|
||||
local th = select(2, tex.size("texture", sd.upper)) or 128
|
||||
local top = if bit32.band(ld.flags, UPPER_UNPEGGED) ~= 0 then me.ceiling else other.ceiling + th
|
||||
quad(sd.upper, x1, y1, x2, y2, other.ceiling, me.ceiling, sd.xoff, len, top, sd.yoff)
|
||||
end
|
||||
if sd.middle ~= "-" and sd.middle ~= "" and bit32.band(ld.flags, TWO_SIDED) ~= 0 then
|
||||
local th = select(2, tex.size("texture", sd.middle)) or 128
|
||||
local lo, hi = math.max(me.floor, other.floor), math.min(me.ceiling, other.ceiling)
|
||||
local top = if bit32.band(ld.flags, LOWER_UNPEGGED) ~= 0 then lo + th else hi
|
||||
quad(sd.middle, x1, y1, x2, y2, math.max(lo, top + sd.yoff - th), math.min(hi, top + sd.yoff), sd.xoff, len, top, sd.yoff)
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
-- the scene
|
||||
local scene = Scene.new()
|
||||
scene.meta.up = "z"
|
||||
local mesh: Types.Mesh = { name = name, primitives = {} }
|
||||
local texIndex: { [string]: number } = {}
|
||||
for _, key in order do
|
||||
local b = batches[key]
|
||||
local n = #b.pos // 3
|
||||
if n > 0 then
|
||||
local pb, nb, ub, ib = buffer.create(n * 12), buffer.create(n * 12), buffer.create(n * 8), buffer.create(n * 4)
|
||||
for i = 1, n * 3 do
|
||||
writef32(pb, (i - 1) * 4, b.pos[i])
|
||||
writef32(nb, (i - 1) * 4, b.nrm[i])
|
||||
end
|
||||
for i = 1, n * 2 do
|
||||
writef32(ub, (i - 1) * 4, b.uv[i])
|
||||
end
|
||||
for i = 0, n - 1 do
|
||||
writeu32(ib, i * 4, i)
|
||||
end
|
||||
local ti = texIndex[key]
|
||||
if not ti then
|
||||
table.insert(scene.textures, { name = b.name, uri = b.name, image = if tex.image then tex.image(b.kind, b.name) else nil, extras = { wad = { kind = b.kind } } })
|
||||
ti = #scene.textures
|
||||
texIndex[key] = ti
|
||||
end
|
||||
local mat = Scene.material(b.name)
|
||||
mat.metallic = 0
|
||||
mat.baseColorTexture = { texture = ti }
|
||||
mat.extras = { wad = { kind = b.kind } }
|
||||
table.insert(scene.materials, mat)
|
||||
table.insert(mesh.primitives, {
|
||||
attributes = {
|
||||
POSITION = Scene.accessor(pb, "f32", 3, n),
|
||||
NORMAL = Scene.accessor(nb, "f32", 3, n),
|
||||
TEXCOORD_0 = Scene.accessor(ub, "f32", 2, n),
|
||||
},
|
||||
indices = Scene.accessor(ib, "u32", 1, n),
|
||||
mode = "triangles" :: any,
|
||||
material = #scene.materials,
|
||||
extras = { wad = { kind = b.kind, texture = b.name } },
|
||||
})
|
||||
end
|
||||
end
|
||||
table.insert(scene.meshes, mesh)
|
||||
scene.nodes[1] = { name = name, children = {}, mesh = 1 }
|
||||
scene.roots[1] = 1
|
||||
-- things, on the floor of the sector under them
|
||||
for i, th in m.things do
|
||||
local z = th.z or 0
|
||||
for sec, ls in secLoops do
|
||||
local inside = false
|
||||
for _, loop in ls do
|
||||
if insideLoop(V, loop, th.x, th.y) then
|
||||
inside = not inside
|
||||
end
|
||||
end
|
||||
if inside then
|
||||
z += m.sectors[sec].floor
|
||||
break
|
||||
end
|
||||
end
|
||||
local a = math.rad(th.angle) / 2
|
||||
table.insert(scene.nodes, {
|
||||
name = "thing " .. i,
|
||||
children = {},
|
||||
translation = { th.x, th.y, z },
|
||||
rotation = { 0, 0, math.sin(a), math.cos(a) },
|
||||
extras = { thing = { type = th.type, angle = th.angle, flags = th.flags, tid = th.tid, special = th.special, args = th.args } },
|
||||
})
|
||||
table.insert(scene.nodes[1].children, #scene.nodes)
|
||||
end
|
||||
return scene
|
||||
end
|
||||
|
||||
return Map
|
||||
@@ -0,0 +1,109 @@
|
||||
--!strict
|
||||
--!native
|
||||
-- archive/wad/Picture: Doom graphics lumps to rgba8 through a u32 palette (Pixels.palette of PLAYPAL): the column
|
||||
-- "picture" format of patches, sprites and menu graphics (width, height, left / top offsets, column offsets, posts of
|
||||
-- topdelta / length / pad / pixels / pad; DeePsea tall patches: a topdelta not above the previous one is relative)
|
||||
-- and raw flats (64 x 64, 64 x 128, 128 x 128, 256 x 256, Heretic's 64 x 65 / 64 x 200 and any w x 64 strip).
|
||||
-- Transparent picture pixels are 0 (alpha 0). Written from the Unofficial Doom Specs and the Doom source release's
|
||||
-- r_data.c description; no code taken. Never throws: every read is checked against the lump's end.
|
||||
local readu8, readu16, readi16, readu32, writeu32 = buffer.readu8, buffer.readu16, buffer.readi16, buffer.readu32, buffer.writeu32
|
||||
|
||||
local Picture = {}
|
||||
|
||||
-- valid(b, at, n) -> width, height, left, top when the lump looks like a picture (every column offset inside it)
|
||||
function Picture.header(b: buffer, at: number, n: number): (number?, number, number, number)
|
||||
if n < 8 then
|
||||
return nil, 0, 0, 0
|
||||
end
|
||||
local w, h = readu16(b, at), readu16(b, at + 2)
|
||||
if w == 0 or h == 0 or w > 4096 or h > 4096 or 8 + w * 4 > n then
|
||||
return nil, 0, 0, 0
|
||||
end
|
||||
for x = 0, w - 1 do
|
||||
local o = readu32(b, at + 8 + x * 4)
|
||||
if o < 8 + w * 4 or o >= n then
|
||||
return nil, 0, 0, 0
|
||||
end
|
||||
end
|
||||
return w, h, readi16(b, at + 4), readi16(b, at + 6)
|
||||
end
|
||||
|
||||
-- decode(b, at, n, pal, out) -> true | false, message: the picture's pixels into out (w * h * 4 bytes, zeroed)
|
||||
function Picture.decode(b: buffer, at: number, n: number, pal: buffer, out: buffer, w: number, h: number): (boolean, string?)
|
||||
local stop = at + n
|
||||
for x = 0, w - 1 do
|
||||
local p = at + readu32(b, at + 8 + x * 4)
|
||||
local top = -1
|
||||
while true do
|
||||
if p >= stop then
|
||||
return false, "column " .. x .. " runs past the end"
|
||||
end
|
||||
local delta = readu8(b, p)
|
||||
if delta == 255 then
|
||||
break
|
||||
end
|
||||
if p + 3 > stop then
|
||||
return false, "post header past the end"
|
||||
end
|
||||
local len = readu8(b, p + 1)
|
||||
top = if delta <= top then top + delta else delta
|
||||
if p + 4 + len > stop then
|
||||
return false, "post past the end"
|
||||
end
|
||||
local src = p + 3
|
||||
for k = 0, len - 1 do
|
||||
local y = top + k
|
||||
if y < h then
|
||||
writeu32(out, (y * w + x) * 4, readu32(pal, readu8(b, src + k) * 4))
|
||||
end
|
||||
end
|
||||
p += 4 + len
|
||||
end
|
||||
end
|
||||
return true, nil
|
||||
end
|
||||
|
||||
-- flatSize(n) -> width, height of a raw flat of n bytes (nil when no shape fits)
|
||||
function Picture.flatSize(n: number): (number?, number)
|
||||
if n == 4096 then
|
||||
return 64, 64
|
||||
elseif n == 4160 then
|
||||
return 64, 64 -- Heretic / Hexen: 64 x 65, the last row is padding
|
||||
elseif n == 8192 then
|
||||
return 64, 128
|
||||
elseif n == 12800 then
|
||||
return 64, 200 -- Heretic / Hexen scrolling flats
|
||||
end
|
||||
local s = math.floor(math.sqrt(n) + 0.5)
|
||||
if s * s == n and s > 0 then
|
||||
return s, s
|
||||
end
|
||||
if n > 0 and n % 64 == 0 then
|
||||
return 64, n // 64
|
||||
end
|
||||
return nil, 0
|
||||
end
|
||||
|
||||
-- flat(b, at, w, h, pal, out): raw indexes, row by row
|
||||
function Picture.flat(b: buffer, at: number, w: number, h: number, pal: buffer, out: buffer)
|
||||
for i = 0, w * h - 1 do
|
||||
writeu32(out, i * 4, readu32(pal, readu8(b, at + i) * 4))
|
||||
end
|
||||
end
|
||||
|
||||
-- blit(src, sw, sh, dst, dw, dh, ox, oy): the non-transparent pixels of an rgba8 image onto another at (ox, oy),
|
||||
-- clipped (composite wall textures from patches)
|
||||
function Picture.blit(src: buffer, sw: number, sh: number, dst: buffer, dw: number, dh: number, ox: number, oy: number)
|
||||
local x0, x1 = math.max(0, -ox), math.min(sw, dw - ox) - 1
|
||||
for y = math.max(0, -oy), math.min(sh, dh - oy) - 1 do
|
||||
local so, d = y * sw, (y + oy) * dw + ox
|
||||
for x = x0, x1 do
|
||||
local v = readu32(src, (so + x) * 4)
|
||||
if v ~= 0 then
|
||||
writeu32(dst, (d + x) * 4, v)
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
return Picture
|
||||
@@ -0,0 +1,474 @@
|
||||
--!strict
|
||||
-- archive/wad: Doom-engine WAD files (IWAD / PWAD: Doom, Heretic, Hexen, Strife, Freedoom, ...), read into the
|
||||
-- standard Archive and written from any Archive value, plus the lumps as game data:
|
||||
-- Wad.lumps(a) every lump in file order with its namespace (sprites / patches / flats / ...) and map
|
||||
-- Wad.palette(a, i?) PLAYPAL palette i (default 0) as a u32 palette buffer
|
||||
-- Wad.image(a, name) a flat, patch, sprite or graphic (the column picture format) as an rgba8 Image
|
||||
-- (meta.offset = { left, top } for pictures; transparent pixels alpha 0)
|
||||
-- Wad.texture(a, name) a wall texture composed from its patches (TEXTURE1 / TEXTURE2 + PNAMES)
|
||||
-- Wad.maps(a) Wad.mapData(a, name) Wad.map(a, name, opts)
|
||||
-- the maps; their things / linedefs / sidedefs / vertices / sectors as tables; a Scene
|
||||
-- (floors, ceilings and walls per texture, things as nodes: archive/wad/Map)
|
||||
-- Entry names: the lump names, except lumps of a map, named "<map>/<lump>" ("MAP01/THINGS"), and later lumps
|
||||
-- repeating an earlier name, named "<name>~<n>" (n = 2, 3, ...), so every entry is unique; writing strips both again
|
||||
-- (the last path component, without its "~n", upper-cased, at most 8 bytes). Written from the Unofficial Doom
|
||||
-- Specs (Matthew Fell) and the Doom source release's w_wad.c / r_data.c description; no code taken.
|
||||
-- Not supported: UDMF (TEXTMAP) map geometry (its lumps are listed and readable), Strife's TEXTURE format variant,
|
||||
-- big-endian (Jaguar) WADs, compressed Jaguar lumps.
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ requires
|
||||
local Err = require("@formats/core/Err")
|
||||
local Bytes = require("@formats/core/Bytes")
|
||||
local Types = require("@formats/Types")
|
||||
local Archive = require("@formats/containers/Archive")
|
||||
local Pixels = require("@formats/codecs/image/Pixels")
|
||||
local Picture = require("@formats/archive/wad/Picture")
|
||||
local Map = require("@formats/archive/wad/Map")
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ contract
|
||||
local Wad = {
|
||||
name = "wad",
|
||||
category = "archive",
|
||||
extensions = { "wad" },
|
||||
mime = { "application/x-doom" },
|
||||
deps = { "core/Err", "core/Bytes", "Types", "containers/Archive", "codecs/image/Pixels", "codecs/model/Polygon" },
|
||||
caps = { decode = true, encode = true, images = true, maps = true, variants = { "iwad", "pwad" } },
|
||||
}
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ types
|
||||
export type DecodeOptions = { maxEntries: number? } -- default 1e6
|
||||
export type EncodeOptions = { type: ("IWAD" | "PWAD")? } -- default: the source's, else "PWAD"
|
||||
export type Lump = {
|
||||
name: string, -- the lump name as stored (upper case)
|
||||
entry: string, -- the Archive entry name
|
||||
index: number, -- 1-based position in the directory
|
||||
offset: number,
|
||||
size: number,
|
||||
namespace: string?, -- "sprites" | "patches" | "flats" | "colormaps" | "textures" (between *_START / *_END markers)
|
||||
map: string?, -- the map this lump belongs to
|
||||
marker: boolean?, -- a zero-size marker (F_START, MAP01, ...)
|
||||
}
|
||||
export type MapOptions = {
|
||||
textures: boolean?, -- build texture images (flats / composed wall textures) into scene.textures (default true)
|
||||
palette: number?, -- PLAYPAL palette index (default 0)
|
||||
}
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ constants
|
||||
local MAP_LUMPS: { [string]: boolean } = {
|
||||
THINGS = true, LINEDEFS = true, SIDEDEFS = true, VERTEXES = true, SEGS = true, SSECTORS = true, NODES = true,
|
||||
SECTORS = true, REJECT = true, BLOCKMAP = true, BEHAVIOR = true, SCRIPTS = true, LEAFS = true, LIGHTS = true,
|
||||
MACROS = true, GL_VERT = true, GL_SEGS = true, GL_SSECT = true, GL_NODES = true, GL_PVS = true,
|
||||
}
|
||||
-- namespace markers: first letter(s) before _START / _END
|
||||
local NAMESPACES: { [string]: string } = { S = "sprites", SS = "sprites", P = "patches", PP = "patches", P1 = "patches", P2 = "patches",
|
||||
P3 = "patches", F = "flats", FF = "flats", F1 = "flats", F2 = "flats", F3 = "flats", C = "colormaps",
|
||||
TX = "textures", HI = "hires", A = "acs", V = "voices" }
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ sniff
|
||||
function Wad.sniff(r: Bytes.Reader): number
|
||||
if r:remaining() < 12 then
|
||||
return 0
|
||||
end
|
||||
local m = r:peek(4)
|
||||
if m ~= "IWAD" and m ~= "PWAD" then
|
||||
return 0
|
||||
end
|
||||
return 0.9
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ decode
|
||||
local function encode(archive: any, opts: any?): (buffer?, Err.Err?)
|
||||
return Wad.encode(archive, opts)
|
||||
end
|
||||
|
||||
local function nameAt(b: buffer, at: number): string
|
||||
local s = buffer.readstring(b, at, 8)
|
||||
local z = string.find(s, "\0", 1, true)
|
||||
return string.upper(if z then string.sub(s, 1, z - 1) else s)
|
||||
end
|
||||
|
||||
function Wad.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?)
|
||||
local kind = r:string(4)
|
||||
local count, dirOfs = r:i32le(), r:i32le()
|
||||
if r.err then
|
||||
return nil, r.err
|
||||
end
|
||||
if kind ~= "IWAD" and kind ~= "PWAD" then
|
||||
return nil, Err.new(Err.CORRUPT, "bad magic", 0)
|
||||
end
|
||||
local size = r.limit - r.base
|
||||
if count < 0 or dirOfs < 0 then
|
||||
return nil, Err.new(Err.CORRUPT, "negative directory field", 4)
|
||||
end
|
||||
if count > (opts and opts.maxEntries or 1e6) then
|
||||
return nil, Err.new(Err.LIMIT, "too many lumps: " .. count)
|
||||
end
|
||||
if dirOfs + count * 16 > size then
|
||||
return nil, Err.new(Err.TRUNCATED, "directory past the end", 8)
|
||||
end
|
||||
local a = Archive.new("wad", encode)
|
||||
local lumps: { Lump } = {}
|
||||
local seen: { [string]: number } = {}
|
||||
local b = r.buf
|
||||
local ns: string? = nil
|
||||
local map: string? = nil
|
||||
local udmf = false
|
||||
for i = 0, count - 1 do
|
||||
local o = r.base + dirOfs + i * 16
|
||||
local at, n = buffer.readi32(b, o), buffer.readi32(b, o + 4)
|
||||
local name = nameAt(b, o + 8)
|
||||
if n < 0 or at < 0 or (n > 0 and at + n > size) then
|
||||
return nil, Err.new(Err.TRUNCATED, "lump " .. name .. " past the end", dirOfs + i * 16)
|
||||
end
|
||||
-- map membership: a lump followed by THINGS (binary) or TEXTMAP (UDMF) starts a map
|
||||
local nextName = if i + 1 < count then nameAt(b, o + 24) else ""
|
||||
local inMap: string? = nil
|
||||
if map then
|
||||
if udmf then
|
||||
inMap = map
|
||||
if name == "ENDMAP" then
|
||||
map = nil
|
||||
end
|
||||
elseif MAP_LUMPS[name] then
|
||||
inMap = map
|
||||
else
|
||||
map = nil
|
||||
end
|
||||
end
|
||||
local isMapMarker = not inMap and (nextName == "THINGS" or nextName == "TEXTMAP")
|
||||
if isMapMarker then
|
||||
map, udmf = name, nextName == "TEXTMAP"
|
||||
end
|
||||
-- namespaces
|
||||
local marker: boolean = false
|
||||
local pre = string.match(name, "^(%w+)_START$")
|
||||
local post = string.match(name, "^(%w+)_END$")
|
||||
if pre and NAMESPACES[pre] then
|
||||
ns = NAMESPACES[pre]
|
||||
marker = true
|
||||
elseif post and NAMESPACES[post] then
|
||||
ns = if #post > 1 and NAMESPACES[string.sub(post, 1, 1)] == ns and (string.match(post, "%d$")) then ns else nil
|
||||
marker = true
|
||||
end
|
||||
local entry = if inMap then inMap .. "/" .. name else name
|
||||
local k = seen[entry]
|
||||
if k then
|
||||
k += 1
|
||||
seen[entry] = k
|
||||
entry = entry .. "~" .. k
|
||||
else
|
||||
seen[entry] = 1
|
||||
end
|
||||
local lump: Lump = { name = name, entry = entry, index = i + 1, offset = at, size = n, namespace = if marker then nil else ns, map = inMap, marker = (n == 0 and (marker or isMapMarker)) or nil }
|
||||
table.insert(lumps, lump)
|
||||
Archive.put(a, { name = entry, size = n, dir = false, method = "store", lump = name, namespace = lump.namespace, map = inMap, load = Archive.slice(b, r.base + at, n) })
|
||||
end
|
||||
a.meta.source = { format = "wad", type = kind, lumps = count }
|
||||
a.meta.wad = { lumps = lumps, buf = b, base = r.base }
|
||||
return a, nil
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ encode
|
||||
function Wad.encode(archive: any, opts: EncodeOptions?): (buffer?, Err.Err?)
|
||||
local items, err = Archive.collect(archive)
|
||||
if not items then
|
||||
return nil, err
|
||||
end
|
||||
local src = type(archive) == "table" and type(archive.meta) == "table" and archive.meta.source
|
||||
local kind = opts and opts.type or (if type(src) == "table" and src.format == "wad" then src.type else nil) or "PWAD"
|
||||
if kind ~= "IWAD" and kind ~= "PWAD" then
|
||||
return nil, Err.new(Err.ARG, "type must be IWAD or PWAD")
|
||||
end
|
||||
local list: { { name: string, data: buffer } } = {}
|
||||
for _, it in items do
|
||||
if not it.entry.dir then
|
||||
local base = string.match(it.entry.name, "([^/\\]*)$") or it.entry.name
|
||||
base = string.upper((string.gsub(base, "~%d+$", "")))
|
||||
if #base > 8 or #base == 0 then
|
||||
return nil, Err.new(Err.ARG, "lump name must be 1..8 bytes: " .. it.entry.name)
|
||||
end
|
||||
table.insert(list, { name = base, data = it.data })
|
||||
end
|
||||
end
|
||||
local w = Bytes.writer()
|
||||
w:string(kind)
|
||||
w:u32le(#list)
|
||||
w:u32le(0)
|
||||
local offs: { number } = {}
|
||||
for i, l in list do
|
||||
offs[i] = w:tell()
|
||||
w:bytes(l.data)
|
||||
end
|
||||
local dirOfs = w:tell()
|
||||
for i, l in list do
|
||||
w:u32le(offs[i])
|
||||
w:u32le(buffer.len(l.data))
|
||||
w:string(l.name)
|
||||
w:fill(0, 8 - #l.name)
|
||||
end
|
||||
w:setU32le(8, dirOfs)
|
||||
return w:finish(), nil
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ extras
|
||||
local function info(a: any): any
|
||||
return type(a) == "table" and type(a.meta) == "table" and a.meta.wad or nil
|
||||
end
|
||||
|
||||
-- the last lump named name (PWAD order: later lumps override), preferring namespace ns when given
|
||||
local function find(w: any, name: string, ns: string?): Lump?
|
||||
local up = string.upper(name)
|
||||
local best: Lump? = nil
|
||||
for _, l in w.lumps do
|
||||
if l.name == up and not l.map then
|
||||
if ns == nil or l.namespace == ns then
|
||||
best = l
|
||||
elseif not best then
|
||||
best = l
|
||||
end
|
||||
end
|
||||
end
|
||||
if best and ns and best.namespace ~= ns then
|
||||
for _, l in w.lumps do
|
||||
if l.name == up and l.namespace == ns then
|
||||
best = l
|
||||
end
|
||||
end
|
||||
end
|
||||
return best
|
||||
end
|
||||
|
||||
-- new(type?) -> an empty WAD Archive ("PWAD" by default): a:add(name, data); a:write()
|
||||
function Wad.new(kind: ("IWAD" | "PWAD")?): any
|
||||
local a = Archive.new("wad", encode)
|
||||
a.meta.source = { format = "wad", type = kind or "PWAD" }
|
||||
return a
|
||||
end
|
||||
|
||||
-- lumps(a) -> { Lump } in directory order (nil when a is not a decoded WAD)
|
||||
function Wad.lumps(a: any): { Lump }?
|
||||
local w = info(a)
|
||||
return w and w.lumps
|
||||
end
|
||||
|
||||
-- palette(a, index?) -> a 256-entry u32 palette (Pixels layout) from PLAYPAL | nil, Err
|
||||
function Wad.palette(a: any, index: number?): (buffer?, Err.Err?)
|
||||
local w = info(a)
|
||||
if not w then
|
||||
return nil, Err.new(Err.ARG, "expected a decoded WAD archive")
|
||||
end
|
||||
local l = find(w, "PLAYPAL")
|
||||
local i = index or 0
|
||||
if not l or l.size < (i + 1) * 768 then
|
||||
return nil, Err.new(Err.UNSUPPORTED, "no PLAYPAL palette " .. i)
|
||||
end
|
||||
return Pixels.palette(w.buf, w.base + l.offset + i * 768, 256), nil
|
||||
end
|
||||
|
||||
-- image(a, name, opts?) -> an rgba8 Image of a flat (in the flats namespace) or a picture (patch, sprite, graphic)
|
||||
-- | nil, Err. opts.palette: the PLAYPAL index (default 0); opts.kind: "flat" | "picture" to force the decoding.
|
||||
function Wad.image(a: any, name: string, opts: { palette: number?, kind: string? }?): (Types.Image?, Err.Err?)
|
||||
local w = info(a)
|
||||
if not w then
|
||||
return nil, Err.new(Err.ARG, "expected a decoded WAD archive")
|
||||
end
|
||||
local kind = opts and opts.kind
|
||||
local l = find(w, name, if kind == "flat" then "flats" else nil)
|
||||
if not l then
|
||||
return nil, Err.new(Err.ARG, "no lump named " .. tostring(name))
|
||||
end
|
||||
local pal, perr = Wad.palette(a, opts and opts.palette)
|
||||
if not pal then
|
||||
return nil, perr
|
||||
end
|
||||
local at = w.base + l.offset
|
||||
local pw, ph, left, top = Picture.header(w.buf, at, l.size)
|
||||
local asFlat = kind == "flat" or (kind ~= "picture" and (l.namespace == "flats" or not pw))
|
||||
if asFlat then
|
||||
local fw, fh = Picture.flatSize(l.size)
|
||||
if not fw then
|
||||
return nil, Err.new(Err.UNSUPPORTED, "lump " .. l.name .. " is neither a picture nor a flat")
|
||||
end
|
||||
local img = Types.Image.new(fw, fh)
|
||||
Picture.flat(w.buf, at, fw, fh, pal, img.pixels)
|
||||
img.meta.source = { format = "wad", kind = "flat", lump = l.name }
|
||||
return img, nil
|
||||
end
|
||||
if not pw then
|
||||
return nil, Err.new(Err.CORRUPT, "lump " .. l.name .. " is not a valid picture")
|
||||
end
|
||||
local img = Types.Image.new(pw, ph)
|
||||
local ok, msg = Picture.decode(w.buf, at, l.size, pal, img.pixels, pw, ph)
|
||||
if not ok then
|
||||
return nil, Err.from(msg, l.offset)
|
||||
end
|
||||
img.meta.offset = { left, top }
|
||||
img.meta.source = { format = "wad", kind = "picture", lump = l.name, left = left, top = top }
|
||||
return img, nil
|
||||
end
|
||||
|
||||
-- the texture definitions (TEXTURE1 + TEXTURE2 with PNAMES): name -> { width, height, patches = { { x, y, patch } } }
|
||||
local function textureDefs(w: any): { [string]: any }
|
||||
if w.textures then
|
||||
return w.textures
|
||||
end
|
||||
local defs: { [string]: any } = {}
|
||||
w.textures = defs
|
||||
local pn = find(w, "PNAMES")
|
||||
local names: { string } = {}
|
||||
if pn and pn.size >= 4 then
|
||||
local at = w.base + pn.offset
|
||||
local n = math.min(buffer.readi32(w.buf, at), (pn.size - 4) // 8)
|
||||
for i = 0, n - 1 do
|
||||
names[i + 1] = nameAt(w.buf, at + 4 + i * 8)
|
||||
end
|
||||
end
|
||||
for _, tl in { "TEXTURE1", "TEXTURE2" } do
|
||||
local l = find(w, tl)
|
||||
if l and l.size >= 4 then
|
||||
local r = Bytes.reader(w.buf, w.base + l.offset, l.size)
|
||||
local n = r:i32le()
|
||||
if n > 0 and n * 4 <= l.size - 4 then
|
||||
for i = 0, n - 1 do
|
||||
r:seek(4 + i * 4)
|
||||
local o = r:i32le()
|
||||
if o > 0 and o + 22 <= l.size then
|
||||
r:seek(o)
|
||||
local tname = string.upper(r:fixed(8))
|
||||
r:skip(4)
|
||||
local tw, th = r:i16le(), r:i16le()
|
||||
r:skip(4)
|
||||
local pc = r:i16le()
|
||||
local patches = {}
|
||||
for _ = 1, math.max(0, pc) do
|
||||
local px, py, pi = r:i16le(), r:i16le(), r:i16le()
|
||||
r:skip(4)
|
||||
if names[pi + 1] then
|
||||
table.insert(patches, { x = px, y = py, patch = names[pi + 1] })
|
||||
end
|
||||
end
|
||||
if not r.err and tw > 0 and th > 0 and defs[tname] == nil then
|
||||
defs[tname] = { width = tw, height = th, patches = patches }
|
||||
end
|
||||
r.err = nil
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
return defs
|
||||
end
|
||||
|
||||
-- texture(a, name, opts?) -> the composed rgba8 Image of a wall texture | nil, Err (opts.palette)
|
||||
function Wad.texture(a: any, name: string, opts: { palette: number? }?): (Types.Image?, Err.Err?)
|
||||
local w = info(a)
|
||||
if not w then
|
||||
return nil, Err.new(Err.ARG, "expected a decoded WAD archive")
|
||||
end
|
||||
local def = textureDefs(w)[string.upper(name)]
|
||||
if not def then
|
||||
return nil, Err.new(Err.ARG, "no texture named " .. tostring(name))
|
||||
end
|
||||
if def.width * def.height > 4096 * 4096 then
|
||||
return nil, Err.new(Err.LIMIT, "texture too big")
|
||||
end
|
||||
local img = Types.Image.new(def.width, def.height)
|
||||
for _, p in def.patches do
|
||||
local pimg = Wad.image(a, p.patch, { palette = opts and opts.palette, kind = "picture" })
|
||||
if pimg then
|
||||
Picture.blit(pimg.pixels, pimg.width, pimg.height, img.pixels, def.width, def.height, p.x, p.y)
|
||||
end
|
||||
end
|
||||
img.meta.source = { format = "wad", kind = "texture", texture = string.upper(name), patches = #def.patches }
|
||||
return img, nil
|
||||
end
|
||||
|
||||
-- maps(a) -> { map names } in file order
|
||||
function Wad.maps(a: any): { string }
|
||||
local w = info(a)
|
||||
local out: { string } = {}
|
||||
if w then
|
||||
local seen: { [string]: boolean } = {}
|
||||
for _, l in w.lumps do
|
||||
if l.map and not seen[l.map] then
|
||||
seen[l.map] = true
|
||||
table.insert(out, l.map)
|
||||
end
|
||||
end
|
||||
end
|
||||
return out
|
||||
end
|
||||
|
||||
-- mapData(a, name) -> Map.MapData (things, linedefs, sidedefs, vertices, sectors as tables, 1-based references)
|
||||
function Wad.mapData(a: any, name: string): (Map.MapData?, Err.Err?)
|
||||
local w = info(a)
|
||||
if not w then
|
||||
return nil, Err.new(Err.ARG, "expected a decoded WAD archive")
|
||||
end
|
||||
local up = string.upper(name)
|
||||
local lumps: { [string]: Map.Lump } = {}
|
||||
for _, l in w.lumps do
|
||||
if l.map == up and lumps[l.name] == nil then
|
||||
lumps[l.name] = { buf = w.buf, at = w.base + l.offset, size = l.size }
|
||||
end
|
||||
end
|
||||
if not next(lumps) then
|
||||
return nil, Err.new(Err.ARG, "no map named " .. tostring(name))
|
||||
end
|
||||
if lumps.TEXTMAP then
|
||||
return nil, Err.new(Err.UNSUPPORTED, "UDMF (TEXTMAP) maps")
|
||||
end
|
||||
local m, msg = Map.parse(lumps, lumps.BEHAVIOR ~= nil)
|
||||
if not m then
|
||||
return nil, Err.from(msg)
|
||||
end
|
||||
return m, nil
|
||||
end
|
||||
|
||||
-- map(a, name, opts?) -> a Scene of the map (z up, map units): one primitive per flat / wall texture (materials and
|
||||
-- textures named after them; texture.image when opts.textures ~= false and the WAD holds it), things as child nodes
|
||||
-- (extras.thing = { type, angle, flags, ... }); meta.source.map = the MapData
|
||||
function Wad.map(a: any, name: string, opts: MapOptions?): (Types.Scene?, Err.Err?)
|
||||
local m, err = Wad.mapData(a, name)
|
||||
if not m then
|
||||
return nil, err
|
||||
end
|
||||
local w = info(a)
|
||||
local defs = textureDefs(w)
|
||||
local images = not (opts and opts.textures == false)
|
||||
local cache: { [string]: any } = {}
|
||||
local pal = opts and opts.palette
|
||||
local function image(kind: string, tname: string): Types.Image?
|
||||
local key = kind .. ":" .. tname
|
||||
local c = cache[key]
|
||||
if c == nil then
|
||||
local img = if kind == "flat" then Wad.image(a, tname, { kind = "flat", palette = pal }) else Wad.texture(a, tname, { palette = pal })
|
||||
c = img or false
|
||||
cache[key] = c
|
||||
end
|
||||
return if c then c else nil
|
||||
end
|
||||
local tex: Map.Textures = {
|
||||
size = function(kind: string, tname: string): (number?, number?)
|
||||
if kind == "texture" then
|
||||
local d = defs[tname]
|
||||
if d then
|
||||
return d.width, d.height
|
||||
end
|
||||
return nil, nil
|
||||
end
|
||||
local l = find(w, tname, "flats")
|
||||
if l then
|
||||
local fw, fh = Picture.flatSize(l.size)
|
||||
return fw, fh
|
||||
end
|
||||
return nil, nil
|
||||
end,
|
||||
image = if images then image else nil,
|
||||
}
|
||||
local scene = Map.scene(m, tex, string.upper(name))
|
||||
scene.meta.source = { format = "wad", map = string.upper(name), mapFormat = m.format, things = #m.things, linedefs = #m.linedefs, sectors = #m.sectors, vertices = #m.vertices // 2 }
|
||||
return scene, nil
|
||||
end
|
||||
|
||||
return Wad
|
||||
@@ -0,0 +1,204 @@
|
||||
--!strict
|
||||
--!native
|
||||
--!optimize 2
|
||||
-- codecs/compress/Explode: decompressor for the PKWARE Data Compression Library "implode" format (DCL, 1987: MPQ
|
||||
-- archive sectors, old installers, some game data files). A codec (layer 3). Written after the format as documented
|
||||
-- by Mark Adler's blast.c (zlib licence, licenses/blast-LICENSE.txt): the same constant code tables (run-length
|
||||
-- coded Huffman code lengths, length bases / extra bits), the bit order (LSB first, Huffman codes inverted); the
|
||||
-- decoder itself is new code.
|
||||
-- Supports: literal coding off (raw bytes) and on (Huffman coded), 1 / 2 / 4 KB dictionaries, the end code; stops
|
||||
-- early at maxOut bytes (MPQ sectors whose stream has no end code).
|
||||
--
|
||||
-- local out, err = Explode.decompress(buf, offset?, length?, maxOut?) -- buffer | nil, Err
|
||||
--
|
||||
-- Never throws: bad data returns nil, Err (TRUNCATED / CORRUPT / ARG / LIMIT).
|
||||
local Err = require("@formats/core/Err")
|
||||
local Bytes = require("@formats/core/Bytes")
|
||||
|
||||
local readu8, writeu8 = buffer.readu8, buffer.writeu8
|
||||
|
||||
local Explode = {}
|
||||
|
||||
local MAXBITS = 13
|
||||
|
||||
-- blast.c's tables: each byte is (count - 1) << 4 | code length
|
||||
local LITLEN = { 11, 124, 8, 7, 28, 7, 188, 13, 76, 4, 10, 8, 12, 10, 12, 10, 8, 23, 8, 9, 7, 6, 7, 8, 7, 6, 55, 8, 23,
|
||||
24, 12, 11, 7, 9, 11, 12, 6, 7, 22, 5, 7, 24, 6, 11, 9, 6, 7, 22, 7, 11, 38, 7, 9, 8, 25, 11, 8, 11, 9, 12, 8, 12, 5,
|
||||
38, 5, 38, 5, 11, 7, 5, 6, 21, 6, 10, 53, 8, 7, 24, 10, 27, 44, 253, 253, 253, 252, 252, 252, 13, 12, 45, 12, 45, 12,
|
||||
61, 12, 45, 44, 173 }
|
||||
local LENLEN = { 2, 35, 36, 53, 38, 23 }
|
||||
local DISTLEN = { 2, 20, 53, 230, 247, 151, 248 }
|
||||
local BASE = { 3, 2, 4, 5, 6, 7, 8, 9, 10, 12, 16, 24, 40, 72, 136, 264 }
|
||||
local EXTRA = { 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 3, 4, 5, 6, 7, 8 }
|
||||
|
||||
type Code = { count: { number }, symbol: { number } }
|
||||
|
||||
-- canonical code from run-length coded lengths
|
||||
local function construct(rep: { number }): Code
|
||||
local lengths: { number } = {}
|
||||
for _, b in rep do
|
||||
local len = b % 16
|
||||
for _ = 0, b // 16 do
|
||||
table.insert(lengths, len)
|
||||
end
|
||||
end
|
||||
local count = table.create(MAXBITS + 1, 0)
|
||||
for _, l in lengths do
|
||||
count[l + 1] += 1
|
||||
end
|
||||
local offs = table.create(MAXBITS + 2, 0)
|
||||
for l = 1, MAXBITS do
|
||||
offs[l + 2] = offs[l + 1] + count[l + 1]
|
||||
end
|
||||
local symbol = table.create(#lengths, 0)
|
||||
for s, l in lengths do
|
||||
if l ~= 0 then
|
||||
offs[l + 1] += 1
|
||||
symbol[offs[l + 1]] = s - 1
|
||||
end
|
||||
end
|
||||
return { count = count, symbol = symbol }
|
||||
end
|
||||
|
||||
local LIT = construct(LITLEN)
|
||||
local LEN = construct(LENLEN)
|
||||
local DIST = construct(DISTLEN)
|
||||
|
||||
-- decompress(buf, offset?, length?, maxOut?) -> buffer | nil, Err
|
||||
function Explode.decompress(buf: buffer | string, offset: number?, length: number?, maxOut: number?): (buffer?, Err.Err?)
|
||||
local b, o, l, aerr = Bytes.span("Explode.decompress", buf, offset, length)
|
||||
if not b then
|
||||
return nil, aerr
|
||||
end
|
||||
local src: buffer = b
|
||||
local p, stop = o, o + l
|
||||
if l < 2 then
|
||||
return nil, Err.new(Err.TRUNCATED, "implode header", 0)
|
||||
end
|
||||
local lit, dict = readu8(src, p), readu8(src, p + 1)
|
||||
p += 2
|
||||
if lit > 1 then
|
||||
return nil, Err.new(Err.CORRUPT, "bad literal mode " .. lit, 0)
|
||||
end
|
||||
if dict < 4 or dict > 6 then
|
||||
return nil, Err.new(Err.CORRUPT, "bad dictionary size " .. dict, 1)
|
||||
end
|
||||
local limit = maxOut or 2 ^ 30
|
||||
local cap = math.max(64, math.min(limit, l * 8))
|
||||
local out = buffer.create(cap)
|
||||
local n = 0
|
||||
local bitbuf, bitcnt = 0, 0
|
||||
local truncated = false
|
||||
|
||||
local function bits(need: number): number
|
||||
while bitcnt < need do
|
||||
if p >= stop then
|
||||
truncated = true
|
||||
return 0
|
||||
end
|
||||
bitbuf += readu8(src, p) * 2 ^ bitcnt
|
||||
p += 1
|
||||
bitcnt += 8
|
||||
end
|
||||
local v = bitbuf % 2 ^ need
|
||||
bitbuf = (bitbuf - v) / 2 ^ need
|
||||
bitcnt -= need
|
||||
return v
|
||||
end
|
||||
|
||||
local function decode(h: Code): number
|
||||
local code, first, index = 0, 0, 0
|
||||
local count, symbol = h.count, h.symbol
|
||||
for len = 1, MAXBITS do
|
||||
local bit = bits(1)
|
||||
if truncated then
|
||||
return -1
|
||||
end
|
||||
code += 1 - bit
|
||||
local c = count[len + 1]
|
||||
if code < first + c then
|
||||
return symbol[index + code - first + 1]
|
||||
end
|
||||
index += c
|
||||
first = (first + c) * 2
|
||||
code *= 2
|
||||
end
|
||||
return -2
|
||||
end
|
||||
|
||||
while n < limit do
|
||||
local flag = bits(1)
|
||||
if truncated then
|
||||
break
|
||||
end
|
||||
if flag == 1 then
|
||||
local sym = decode(LEN)
|
||||
if sym < 0 then
|
||||
if truncated then
|
||||
break
|
||||
end
|
||||
return nil, Err.new(Err.CORRUPT, "bad length code", p - o)
|
||||
end
|
||||
local len = BASE[sym + 1] + bits(EXTRA[sym + 1])
|
||||
if truncated then
|
||||
break
|
||||
end
|
||||
if len == 519 then
|
||||
break
|
||||
end
|
||||
local shift = if len == 2 then 2 else dict
|
||||
local d = decode(DIST)
|
||||
if d < 0 then
|
||||
if truncated then
|
||||
break
|
||||
end
|
||||
return nil, Err.new(Err.CORRUPT, "bad distance code", p - o)
|
||||
end
|
||||
local dist = d * 2 ^ shift + bits(shift) + 1
|
||||
if truncated then
|
||||
break
|
||||
end
|
||||
if dist > n then
|
||||
return nil, Err.new(Err.CORRUPT, "distance too far back", p - o)
|
||||
end
|
||||
if n + len > limit then
|
||||
len = limit - n
|
||||
end
|
||||
if n + len > cap then
|
||||
cap = math.max(cap * 2, n + len)
|
||||
local grown = buffer.create(cap)
|
||||
buffer.copy(grown, 0, out, 0, n)
|
||||
out = grown
|
||||
end
|
||||
local from = n - dist
|
||||
for k = 0, len - 1 do
|
||||
writeu8(out, n + k, readu8(out, from + k))
|
||||
end
|
||||
n += len
|
||||
else
|
||||
local sym = if lit == 1 then decode(LIT) else bits(8)
|
||||
if truncated then
|
||||
break
|
||||
end
|
||||
if sym < 0 then
|
||||
return nil, Err.new(Err.CORRUPT, "bad literal code", p - o)
|
||||
end
|
||||
if n >= cap then
|
||||
cap *= 2
|
||||
local grown = buffer.create(cap)
|
||||
buffer.copy(grown, 0, out, 0, n)
|
||||
out = grown
|
||||
end
|
||||
writeu8(out, n, sym)
|
||||
n += 1
|
||||
end
|
||||
end
|
||||
if truncated and n < limit and not maxOut then
|
||||
return nil, Err.new(Err.TRUNCATED, "no end code", l)
|
||||
end
|
||||
local res = buffer.create(n)
|
||||
buffer.copy(res, 0, out, 0, n)
|
||||
return res, nil
|
||||
end
|
||||
|
||||
return Explode
|
||||
@@ -31,6 +31,7 @@ Color.RGB = 2
|
||||
Color.CMYK = 3
|
||||
Color.YCCK = 4
|
||||
Color.CMYK_PLAIN = 5 -- CMYK without an Adobe marker: not inverted
|
||||
Color.RAW = 6 -- no conversion: components 1..4 as R, G, B, A (opts.raw: BLP1's BGRA JPEGs, ...)
|
||||
|
||||
export type Comp = {
|
||||
plane: buffer, -- u16 samples, stride per row
|
||||
@@ -177,6 +178,19 @@ function Color.run(P: Params)
|
||||
if nc >= 4 then
|
||||
s3, b3 = fetch(comps[4], y, outW)
|
||||
end
|
||||
if space == 6 then
|
||||
for x = 0, outW - 1 do
|
||||
local i = x * 2
|
||||
local c0, c1, c2 = readu16(s0, b0 + i), readu16(s1, b1 + i), readu16(s2, b2 + i)
|
||||
local c3 = if nc >= 4 then readu16(s3, b3 + i) else maxv
|
||||
if toByte then
|
||||
c0, c1, c2, c3 = readu8(toByte, c0), readu8(toByte, c1), readu8(toByte, c2), readu8(toByte, c3)
|
||||
end
|
||||
writeu32(out, o, c0 + c1 * 256 + c2 * 65536 + c3 * 16777216)
|
||||
o += 4
|
||||
end
|
||||
continue
|
||||
end
|
||||
if space == 1 and not toByte then
|
||||
-- the common case: 8-bit YCbCr
|
||||
for x = 0, outW - 1 do
|
||||
|
||||
@@ -228,6 +228,7 @@ export type State = {
|
||||
icc: buffer?,
|
||||
comments: { string },
|
||||
truncated: boolean,
|
||||
raw: boolean, -- opts.raw: no colour conversion
|
||||
scale: number,
|
||||
avi1: number?, -- the AVI1 APP0 field polarity (0 = progressive, 1 / 2 = interlaced: two fields back to back)
|
||||
endPos: number, -- the byte after the EOI marker (or the end of the data)
|
||||
@@ -259,6 +260,7 @@ function Decode.parse(b: buffer, base: number, n: number, opts: any, headerOnly:
|
||||
icc = nil,
|
||||
comments = {},
|
||||
truncated = false,
|
||||
raw = opts ~= nil and opts.raw == true,
|
||||
scale = scale,
|
||||
avi1 = nil,
|
||||
endPos = n,
|
||||
@@ -644,6 +646,9 @@ function Decode.output(st: State): (number?, any, any, string?)
|
||||
if space == "cmyk" and st.adobe == nil then
|
||||
spaceId = Color.CMYK_PLAIN
|
||||
end
|
||||
if st.raw then
|
||||
spaceId = Color.RAW
|
||||
end
|
||||
local t = yccTables(maxv)
|
||||
local tb = nil
|
||||
if maxv == 4095 then
|
||||
|
||||
@@ -43,6 +43,7 @@ export type DecodeOptions = {
|
||||
native: boolean?, -- grey files decode to gray8 (default false: rgba8)
|
||||
yuv: boolean?, -- 8-bit YCbCr / grey frames decode to yuv420p (default false); see the header for the layouts
|
||||
fields: boolean?, -- two JPEGs back to back are two fields of one frame (default: when the AVI1 segment says so)
|
||||
raw: boolean?, -- no colour conversion: 3 / 4 components as R, G, B (, A) bytes (default false; BLP1 BGRA JPEGs)
|
||||
maxPixels: number?, -- refuse larger images (default 2^26)
|
||||
}
|
||||
export type EncodeOptions = {
|
||||
|
||||
@@ -0,0 +1,248 @@
|
||||
--!strict
|
||||
-- codecs/model/Polygon: 2D polygons with holes to triangles, for formats that store regions as outlines (Doom map
|
||||
-- sectors, ...). Loops are classified by nesting (a loop inside an odd number of other loops is a hole of the
|
||||
-- smallest loop around it), oriented, each hole bridged to its outer loop at a mutually visible vertex, then the
|
||||
-- result is ear-clipped (reflex-vertex test; a polygon that never yields a clean ear clips its least bad corner so
|
||||
-- every input terminates). New in formats-luau, after the classic "ear clipping with hole bridging" method
|
||||
-- (D. Eberly, Triangulation by Ear Clipping); no code taken.
|
||||
--
|
||||
-- local tris = Polygon.triangulate({ { 0, 0, 10, 0, 10, 10, 0, 10 }, { 2, 2, 4, 2, 4, 4, 2, 4 } })
|
||||
-- -- tris = { loop, index, loop, index, loop, index, ... }: three corners per triangle, each a (loop, vertex) pair
|
||||
-- -- (1-based), counter-clockwise
|
||||
--
|
||||
-- Never throws; degenerate loops (fewer than 3 points, zero area) are ignored.
|
||||
local Polygon = {}
|
||||
|
||||
type Pt = { x: number, y: number, loop: number, index: number }
|
||||
|
||||
local function area(pts: { Pt }): number
|
||||
local a = 0
|
||||
local n = #pts
|
||||
for i = 1, n do
|
||||
local p, q = pts[i], pts[i % n + 1]
|
||||
a += p.x * q.y - q.x * p.y
|
||||
end
|
||||
return a / 2
|
||||
end
|
||||
|
||||
local function inside(pts: { Pt }, x: number, y: number): boolean
|
||||
local c = false
|
||||
local n = #pts
|
||||
local j = n
|
||||
for i = 1, n do
|
||||
local a, b = pts[i], pts[j]
|
||||
if (a.y > y) ~= (b.y > y) and x < (b.x - a.x) * (y - a.y) / (b.y - a.y) + a.x then
|
||||
c = not c
|
||||
end
|
||||
j = i
|
||||
end
|
||||
return c
|
||||
end
|
||||
|
||||
local function cross(o: Pt, a: Pt, b: Pt): number
|
||||
return (a.x - o.x) * (b.y - o.y) - (a.y - o.y) * (b.x - o.x)
|
||||
end
|
||||
|
||||
-- segments p1-p2 and q1-q2 cross properly (touching at an endpoint does not count)
|
||||
local function crosses(p1: Pt, p2: Pt, q1: Pt, q2: Pt): boolean
|
||||
if (p1.x == q1.x and p1.y == q1.y) or (p1.x == q2.x and p1.y == q2.y) or (p2.x == q1.x and p2.y == q1.y) or (p2.x == q2.x and p2.y == q2.y) then
|
||||
return false
|
||||
end
|
||||
local d1, d2 = cross(q1, q2, p1), cross(q1, q2, p2)
|
||||
local d3, d4 = cross(p1, p2, q1), cross(p1, p2, q2)
|
||||
return ((d1 > 0 and d2 < 0) or (d1 < 0 and d2 > 0)) and ((d3 > 0 and d4 < 0) or (d3 < 0 and d4 > 0))
|
||||
end
|
||||
|
||||
local function visible(m: Pt, v: Pt, rings: { { Pt } }): boolean
|
||||
for _, r in rings do
|
||||
local n = #r
|
||||
for i = 1, n do
|
||||
if crosses(m, v, r[i], r[i % n + 1]) then
|
||||
return false
|
||||
end
|
||||
end
|
||||
end
|
||||
return true
|
||||
end
|
||||
|
||||
-- splice hole h into ring outer (both oriented: outer counter-clockwise, hole clockwise) at mutually visible
|
||||
-- vertices; others = every ring the bridge must not cross
|
||||
local function bridge(outer: { Pt }, h: { Pt }, others: { { Pt } }): { Pt }
|
||||
local mi = 1
|
||||
for i, p in h do
|
||||
if p.x > h[mi].x then
|
||||
mi = i
|
||||
end
|
||||
end
|
||||
local m = h[mi]
|
||||
local best, bestD = 0, math.huge
|
||||
for pass = 1, 2 do
|
||||
for i, v in outer do
|
||||
if pass == 2 or v.x >= m.x then
|
||||
local d = (v.x - m.x) ^ 2 + (v.y - m.y) ^ 2
|
||||
if d < bestD and visible(m, v, others) then
|
||||
best, bestD = i, d
|
||||
end
|
||||
end
|
||||
end
|
||||
if best > 0 then
|
||||
break
|
||||
end
|
||||
end
|
||||
if best == 0 then
|
||||
best = 1
|
||||
end
|
||||
local out: { Pt } = {}
|
||||
for i = 1, best do
|
||||
table.insert(out, outer[i])
|
||||
end
|
||||
local n = #h
|
||||
for k = 0, n do
|
||||
table.insert(out, h[(mi - 1 + k) % n + 1])
|
||||
end
|
||||
for i = best, #outer do
|
||||
table.insert(out, outer[i])
|
||||
end
|
||||
return out
|
||||
end
|
||||
|
||||
local function inTri(a: Pt, b: Pt, c: Pt, p: Pt): boolean
|
||||
return cross(a, b, p) >= 0 and cross(b, c, p) >= 0 and cross(c, a, p) >= 0
|
||||
end
|
||||
|
||||
-- ear clipping of one counter-clockwise ring
|
||||
local function clip(ring: { Pt }, out: { number })
|
||||
local pts = table.clone(ring)
|
||||
local guard = #pts * #pts + 16
|
||||
while #pts > 3 and guard > 0 do
|
||||
guard -= 1
|
||||
local n = #pts
|
||||
local found, bestI, bestScore = 0, 1, -math.huge
|
||||
for i = 1, n do
|
||||
local a, b, c = pts[(i - 2) % n + 1], pts[i], pts[i % n + 1]
|
||||
local cr = cross(a, b, c)
|
||||
if cr > 0 then
|
||||
local ok = true
|
||||
for k = 1, n do
|
||||
local p = pts[k]
|
||||
if p ~= a and p ~= b and p ~= c and not (p.x == b.x and p.y == b.y) and not (p.x == a.x and p.y == a.y) and not (p.x == c.x and p.y == c.y) and inTri(a, b, c, p) then
|
||||
ok = false
|
||||
break
|
||||
end
|
||||
end
|
||||
if ok then
|
||||
found = i
|
||||
break
|
||||
end
|
||||
end
|
||||
if cr > bestScore then
|
||||
bestI, bestScore = i, cr
|
||||
end
|
||||
end
|
||||
local i = if found > 0 then found else bestI
|
||||
local a, b, c = pts[(i - 2) % n + 1], pts[i], pts[i % n + 1]
|
||||
if cross(a, b, c) ~= 0 then
|
||||
table.insert(out, a.loop)
|
||||
table.insert(out, a.index)
|
||||
table.insert(out, b.loop)
|
||||
table.insert(out, b.index)
|
||||
table.insert(out, c.loop)
|
||||
table.insert(out, c.index)
|
||||
end
|
||||
table.remove(pts, i)
|
||||
end
|
||||
if #pts == 3 and cross(pts[1], pts[2], pts[3]) > 0 then
|
||||
for k = 1, 3 do
|
||||
table.insert(out, pts[k].loop)
|
||||
table.insert(out, pts[k].index)
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
-- triangulate(loops) -> { loop, index, ... }: loops[i] = { x1, y1, x2, y2, ... } (closed implicitly)
|
||||
function Polygon.triangulate(loops: { { number } }): { number }
|
||||
local rings: { { Pt } } = {}
|
||||
local areas: { number } = {}
|
||||
for li, l in loops do
|
||||
local pts: { Pt } = {}
|
||||
for k = 1, #l - 1, 2 do
|
||||
local x, y = l[k], l[k + 1]
|
||||
if type(x) == "number" and type(y) == "number" and x == x and y == y then
|
||||
table.insert(pts, { x = x, y = y, loop = li, index = (k + 1) // 2 })
|
||||
end
|
||||
end
|
||||
local a = if #pts >= 3 then area(pts) else 0
|
||||
if a ~= 0 then
|
||||
table.insert(rings, pts)
|
||||
table.insert(areas, math.abs(a))
|
||||
if a < 0 then -- counter-clockwise for now; holes are flipped below
|
||||
local r: { Pt } = {}
|
||||
for k = #pts, 1, -1 do
|
||||
table.insert(r, pts[k])
|
||||
end
|
||||
rings[#rings] = r
|
||||
end
|
||||
end
|
||||
end
|
||||
-- nesting: the parent of a ring is the smallest ring containing its first point
|
||||
local n = #rings
|
||||
local depth, parent = table.create(n, 0), table.create(n, 0)
|
||||
for i = 1, n do
|
||||
local p = rings[i][1]
|
||||
for j = 1, n do
|
||||
if j ~= i and areas[j] > areas[i] and inside(rings[j], p.x, p.y) then
|
||||
depth[i] += 1
|
||||
if parent[i] == 0 or areas[j] < areas[parent[i]] then
|
||||
parent[i] = j
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
local holes: { [number]: { number } } = {}
|
||||
for i = 1, n do
|
||||
if depth[i] % 2 == 1 and parent[i] > 0 then
|
||||
local list = holes[parent[i]] or {}
|
||||
holes[parent[i]] = list
|
||||
table.insert(list, i)
|
||||
end
|
||||
end
|
||||
local out: { number } = {}
|
||||
for i = 1, n do
|
||||
if depth[i] % 2 == 0 then
|
||||
local ring = rings[i]
|
||||
local hs = holes[i]
|
||||
if hs then
|
||||
table.sort(hs, function(a: number, b: number): boolean
|
||||
local ma, mb = -math.huge, -math.huge
|
||||
for _, p in rings[a] do
|
||||
ma = math.max(ma, p.x)
|
||||
end
|
||||
for _, p in rings[b] do
|
||||
mb = math.max(mb, p.x)
|
||||
end
|
||||
return ma > mb
|
||||
end)
|
||||
local flipped: { { Pt } } = {}
|
||||
for _, h in hs do
|
||||
local r: { Pt } = {}
|
||||
local src = rings[h]
|
||||
for k = #src, 1, -1 do
|
||||
table.insert(r, src[k])
|
||||
end
|
||||
table.insert(flipped, r)
|
||||
end
|
||||
for k, h in flipped do
|
||||
local others: { { Pt } } = { ring }
|
||||
for k2 = k + 1, #flipped do
|
||||
table.insert(others, flipped[k2])
|
||||
end
|
||||
ring = bridge(ring, h, others)
|
||||
end
|
||||
end
|
||||
clip(ring, out)
|
||||
end
|
||||
end
|
||||
return out
|
||||
end
|
||||
|
||||
return Polygon
|
||||
@@ -101,16 +101,58 @@ function Rig.morphAnimation(scene: Types.Scene, node: number, targets: number, r
|
||||
end
|
||||
end
|
||||
|
||||
-- normals(pos, count, indices) -> f32 x3 buffer: smooth vertex normals (area-weighted face normals, normalised) of a
|
||||
-- triangle list (indices: 0-based, three per triangle; out-of-range triangles are skipped). For formats whose stored
|
||||
-- normals cannot be used (Quake's precomputed normal table is not redistributable here).
|
||||
function Rig.normals(pos: buffer, count: number, indices: { number }): buffer
|
||||
local out = buffer.create(count * 12)
|
||||
local acc = table.create(count * 3, 0)
|
||||
for k = 1, #indices - 2, 3 do
|
||||
local a, b, c = indices[k], indices[k + 1], indices[k + 2]
|
||||
if a >= 0 and b >= 0 and c >= 0 and a < count and b < count and c < count then
|
||||
local ax, ay, az = readf32(pos, a * 12), readf32(pos, a * 12 + 4), readf32(pos, a * 12 + 8)
|
||||
local ux, uy, uz = readf32(pos, b * 12) - ax, readf32(pos, b * 12 + 4) - ay, readf32(pos, b * 12 + 8) - az
|
||||
local vx, vy, vz = readf32(pos, c * 12) - ax, readf32(pos, c * 12 + 4) - ay, readf32(pos, c * 12 + 8) - az
|
||||
local nx, ny, nz = uy * vz - uz * vy, uz * vx - ux * vz, ux * vy - uy * vx
|
||||
for _, v in { a, b, c } do
|
||||
acc[v * 3 + 1] += nx
|
||||
acc[v * 3 + 2] += ny
|
||||
acc[v * 3 + 3] += nz
|
||||
end
|
||||
end
|
||||
end
|
||||
for v = 0, count - 1 do
|
||||
local x, y, z = acc[v * 3 + 1], acc[v * 3 + 2], acc[v * 3 + 3]
|
||||
local l = math.sqrt(x * x + y * y + z * z)
|
||||
if l > 0 then
|
||||
x, y, z = x / l, y / l, z / l
|
||||
end
|
||||
writef32(out, v * 12, x)
|
||||
writef32(out, v * 12 + 4, y)
|
||||
writef32(out, v * 12 + 8, z)
|
||||
end
|
||||
return out
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ skeletons
|
||||
local function trs(j: Joint): { number }
|
||||
return Mat4.compose(j.translation, j.rotation, j.scale)
|
||||
end
|
||||
|
||||
-- skeleton(scene, joints, space, root?) -> (joint node indices, skin index): one node per joint (TRS relative to its
|
||||
-- angles(x, y, z) -> quaternion { x, y, z, w } of the Euler angles in radians applied x first, then y, then z
|
||||
-- (R = Rz * Ry * Rx: the Quake / Half-Life "AngleQuaternion" convention of MDL bones and SMD skeletons)
|
||||
function Rig.angles(x: number, y: number, z: number): { number }
|
||||
local sy, cy = math.sin(z / 2), math.cos(z / 2)
|
||||
local sp, cp = math.sin(y / 2), math.cos(y / 2)
|
||||
local sr, cr = math.sin(x / 2), math.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
|
||||
|
||||
-- skeleton(scene, joints, space, root?) -> (joint node indices, skin index, world matrices): one node per joint (TRS relative to its
|
||||
-- parent), parented as listed, roots added to scene.roots (or as children of node `root`); a Skin with the inverse
|
||||
-- bind matrices. space "local": joint TRS are relative to the parent (SMD, MDL); "world": in model space (MD5's
|
||||
-- bind pose), converted to local here. A parent index that does not come earlier makes the joint a root.
|
||||
function Rig.skeleton(scene: Types.Scene, joints: { Joint }, space: "local" | "world", root: number?): ({ number }, number)
|
||||
function Rig.skeleton(scene: Types.Scene, joints: { Joint }, space: "local" | "world", root: number?): ({ number }, number, { { number } })
|
||||
local n = #joints
|
||||
local world: { { number } } = {}
|
||||
local nodes: { number } = {}
|
||||
@@ -152,19 +194,28 @@ function Rig.skeleton(scene: Types.Scene, joints: { Joint }, space: "local" | "w
|
||||
local acc = Scene.accessor(ibm, "f32", 16, n)
|
||||
acc.matrix = true
|
||||
table.insert(scene.skins, { joints = nodes, inverseBindMatrices = acc, skeleton = if n > 0 then nodes[1] else nil })
|
||||
return nodes, #scene.skins
|
||||
return nodes, #scene.skins, world
|
||||
end
|
||||
|
||||
-- influences(lists) -> JOINTS_0 (u16 x4), WEIGHTS_0 (f32 x4): lists[v] = { joint, weight, joint, weight, ... } with
|
||||
-- 0-based joint indices (into the skin's joints); the four largest weights are kept and normalised to sum 1.
|
||||
-- 0-based joint indices (into the skin's joints; a joint listed twice adds up); the four largest weights are kept
|
||||
-- and normalised to sum 1.
|
||||
function Rig.influences(lists: { { number } }): (Types.Accessor, Types.Accessor)
|
||||
local n = #lists
|
||||
local jb, wb = buffer.create(n * 8), buffer.create(n * 16)
|
||||
for v, l in lists do
|
||||
local pairs_: { { number } } = {}
|
||||
local at: { [number]: { number } } = {}
|
||||
for k = 1, #l - 1, 2 do
|
||||
if l[k + 1] > 0 then
|
||||
table.insert(pairs_, { l[k], l[k + 1] })
|
||||
local same = at[l[k]]
|
||||
if same then
|
||||
same[2] += l[k + 1] -- the same joint twice: one influence
|
||||
else
|
||||
local e = { l[k], l[k + 1] }
|
||||
at[l[k]] = e
|
||||
table.insert(pairs_, e)
|
||||
end
|
||||
end
|
||||
end
|
||||
table.sort(pairs_, function(a: { number }, b: { number }): boolean
|
||||
|
||||
@@ -59,4 +59,24 @@ function Input.extension(name: string?): string?
|
||||
return if ext then string.lower(ext) else nil
|
||||
end
|
||||
|
||||
-- sibling(opts, uri) -> buffer | nil: a file the data being decoded refers to (a palette, an animation, an archive
|
||||
-- part, ...): opts.files[uri] (a buffer or a string), else opts.resolve(uri) (errors in it count as not found)
|
||||
function Input.sibling(opts: any?, uri: string): buffer?
|
||||
if type(opts) ~= "table" then
|
||||
return nil
|
||||
end
|
||||
local v: any = nil
|
||||
if type(opts.files) == "table" then
|
||||
v = opts.files[uri]
|
||||
end
|
||||
if v == nil and type(opts.resolve) == "function" then
|
||||
local ok, got = pcall(opts.resolve, uri)
|
||||
v = if ok then got else nil
|
||||
end
|
||||
if type(v) == "string" then
|
||||
return buffer.fromstring(v)
|
||||
end
|
||||
return if type(v) == "buffer" then v else nil
|
||||
end
|
||||
|
||||
return Input
|
||||
@@ -0,0 +1,266 @@
|
||||
--!strict
|
||||
-- image/blp: Blizzard BLP textures (Warcraft III: BLP1; World of Warcraft: BLP2), read, and BLP2 written
|
||||
-- (uncompressed BGRA). Written from the wowdev.wiki BLP page; no code taken.
|
||||
-- Decode, mip 0 (meta.source.mips counts the levels) to rgba8:
|
||||
-- BLP1 JPEG: the shared JPEG header + the mip's data through codecs/image/Jpeg; 4-component files (the usual
|
||||
-- Warcraft III layout) are BGRA without colour conversion, 3-component ones YCbCr -> BGR (R and B swapped back);
|
||||
-- BLP1 palette: 8-bit indexes into a BGRA palette, then an 8-bit alpha plane when alphaBits is 8 (else opaque);
|
||||
-- BLP2 palette: indexes + a 1 / 4 / 8-bit alpha plane (LSB first), DXT1 / DXT3 / DXT5 (codecs/image/Bcn: alpha
|
||||
-- type 0 / 1 / 7), uncompressed BGRA.
|
||||
-- Encode: BLP2 uncompressed BGRA with 8-bit alpha (opts.mips = true adds the box-filtered mip chain).
|
||||
-- Not supported: BLP0 (external .b00 mip files), BLP2 JPEG (never used by the games).
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ requires
|
||||
local Err = require("@formats/core/Err")
|
||||
local Bytes = require("@formats/core/Bytes")
|
||||
local Types = require("@formats/Types")
|
||||
local Jpeg = require("@formats/codecs/image/Jpeg")
|
||||
local Bcn = require("@formats/codecs/image/Bcn")
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ contract
|
||||
local Blp = {
|
||||
name = "blp",
|
||||
category = "image",
|
||||
extensions = { "blp" },
|
||||
mime = { "image/x-blp" },
|
||||
deps = { "core/Err", "core/Bytes", "Types", "codecs/image/Jpeg", "codecs/image/Bcn" },
|
||||
caps = { decode = true, encode = true, alpha = true, variants = { "blp1", "blp2" }, compressions = { "jpeg", "palette", "dxt1", "dxt3", "dxt5", "bgra" } },
|
||||
}
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ types
|
||||
export type DecodeOptions = { maxPixels: number? } -- default 2^26
|
||||
export type EncodeOptions = { mips: boolean? } -- write the mip chain (default false)
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ constants
|
||||
local readu8, readu32, writeu32, writeu8 = buffer.readu8, buffer.readu32, buffer.writeu32, buffer.writeu8
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ sniff
|
||||
function Blp.sniff(r: Bytes.Reader): number
|
||||
local m = r:peek(4)
|
||||
return if m == "BLP1" or m == "BLP2" then 1 elseif m == "BLP0" then 0.8 else 0
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ decode
|
||||
-- BGRA u32 (b at the lowest address) -> RGBA u32 with the given alpha
|
||||
local function swap(v: number, a: number): number
|
||||
local b, g, r = v % 256, (v // 256) % 256, (v // 65536) % 256
|
||||
return r + g * 256 + b * 65536 + a * 16777216
|
||||
end
|
||||
|
||||
-- alpha of pixel i from a packed plane at p of depth bits
|
||||
local function alphaAt(b: buffer, p: number, depth: number, i: number): number
|
||||
if depth == 8 then
|
||||
return readu8(b, p + i)
|
||||
elseif depth == 4 then
|
||||
local v = readu8(b, p + i // 2)
|
||||
local n = if i % 2 == 0 then v % 16 else v // 16
|
||||
return n * 17
|
||||
elseif depth == 1 then
|
||||
local v = readu8(b, p + i // 8)
|
||||
return if bit32.band(v, bit32.lshift(1, i % 8)) ~= 0 then 255 else 0
|
||||
end
|
||||
return 255
|
||||
end
|
||||
|
||||
function Blp.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Image?, Err.Err?)
|
||||
local size = r.limit - r.base
|
||||
local b, base = r.buf, r.base
|
||||
local magic = r:peek(4)
|
||||
if magic == "BLP0" then
|
||||
return nil, Err.new(Err.UNSUPPORTED, "BLP0 (mips in external files)", 0)
|
||||
end
|
||||
if magic ~= "BLP1" and magic ~= "BLP2" then
|
||||
return nil, Err.new(if size < 4 then Err.TRUNCATED else Err.CORRUPT, "bad magic", 0)
|
||||
end
|
||||
local v2 = magic == "BLP2"
|
||||
local headerSize = if v2 then 20 + 128 + 1024 else 28 + 128
|
||||
if size < headerSize then
|
||||
return nil, Err.new(Err.TRUNCATED, "header", 0)
|
||||
end
|
||||
local kind = readu32(b, base + 4) -- BLP1: 0 = JPEG, 1 = palette; BLP2: 1 (0 = JPEG)
|
||||
local compression = if v2 then readu8(b, base + 8) elseif kind == 0 then 0 else 1
|
||||
local alphaDepth = if v2 then readu8(b, base + 9) else readu32(b, base + 8)
|
||||
local alphaType = if v2 then readu8(b, base + 10) else 0
|
||||
local w, h = readu32(b, base + 12), readu32(b, base + 16)
|
||||
local mipsAt = if v2 then 20 else 28
|
||||
if w == 0 or h == 0 or w > 65535 or h > 65535 then
|
||||
return nil, Err.new(Err.CORRUPT, "bad size " .. w .. " x " .. h, 12)
|
||||
end
|
||||
if w * h > (opts and opts.maxPixels or 2 ^ 26) then
|
||||
return nil, Err.new(Err.LIMIT, "image too big")
|
||||
end
|
||||
local offs: { number }, lens: { number } = {}, {}
|
||||
local mips = 0
|
||||
for i = 0, 15 do
|
||||
offs[i + 1] = readu32(b, base + mipsAt + i * 4)
|
||||
lens[i + 1] = readu32(b, base + mipsAt + 64 + i * 4)
|
||||
if offs[i + 1] ~= 0 and lens[i + 1] ~= 0 then
|
||||
mips += 1
|
||||
end
|
||||
end
|
||||
local at, len = offs[1], lens[1]
|
||||
if at + len > size or len == 0 then
|
||||
return nil, Err.new(Err.TRUNCATED, "mip 0 past the end", mipsAt)
|
||||
end
|
||||
local img = Types.Image.new(w, h)
|
||||
local px = img.pixels
|
||||
local n = w * h
|
||||
local src = base + at
|
||||
local name: string
|
||||
if (not v2 and kind == 0) or (v2 and kind == 0) then
|
||||
if v2 then
|
||||
return nil, Err.new(Err.UNSUPPORTED, "BLP2 JPEG")
|
||||
end
|
||||
-- the JPEG header shared by the mips, then the mip's own data
|
||||
if size < headerSize + 4 then
|
||||
return nil, Err.new(Err.TRUNCATED, "JPEG header size", headerSize)
|
||||
end
|
||||
local hs = readu32(b, base + headerSize)
|
||||
if hs > 0x10000 or headerSize + 4 + hs > size then
|
||||
return nil, Err.new(Err.CORRUPT, "bad JPEG header size", headerSize)
|
||||
end
|
||||
local jpg = buffer.create(hs + len)
|
||||
buffer.copy(jpg, 0, b, base + headerSize + 4, hs)
|
||||
buffer.copy(jpg, hs, b, src, len)
|
||||
local info = Jpeg.info(jpg)
|
||||
local four = info ~= nil and (info :: any).components == 4
|
||||
local dec, err = Jpeg.decode(jpg, 0, nil, { raw = four, maxPixels = opts and opts.maxPixels })
|
||||
if not dec then
|
||||
return nil, err
|
||||
end
|
||||
local dw, dh = math.min(dec.width, w), math.min(dec.height, h)
|
||||
for y = 0, dh - 1 do
|
||||
for x = 0, dw - 1 do
|
||||
local v = readu32(dec.pixels, (y * dec.width + x) * 4)
|
||||
local a = if four and alphaDepth > 0 then v // 16777216 else 255
|
||||
writeu32(px, (y * w + x) * 4, swap(v, a))
|
||||
end
|
||||
end
|
||||
name = "jpeg"
|
||||
elseif compression == 1 then
|
||||
local palAt = base + (if v2 then 148 else headerSize)
|
||||
local dataAt = src
|
||||
if not v2 then
|
||||
-- BLP1: the palette follows the header; the mip offsets point past it
|
||||
if headerSize + 1024 > size then
|
||||
return nil, Err.new(Err.TRUNCATED, "palette", headerSize)
|
||||
end
|
||||
end
|
||||
local depth = if v2 then alphaDepth else (if alphaDepth >= 8 then 8 else 0)
|
||||
local need = n + (if depth == 8 then n elseif depth == 4 then (n + 1) // 2 elseif depth == 1 then (n + 7) // 8 else 0)
|
||||
if at + need > size then
|
||||
return nil, Err.new(Err.TRUNCATED, "palette mip past the end", at)
|
||||
end
|
||||
for i = 0, n - 1 do
|
||||
local e = readu32(b, palAt + readu8(b, dataAt + i) * 4)
|
||||
writeu32(px, i * 4, swap(e, if depth > 0 then alphaAt(b, dataAt + n, depth, i) else 255))
|
||||
end
|
||||
name = "palette"
|
||||
elseif compression == 2 then
|
||||
local kindName = if alphaType == 7 then "bc3" elseif alphaType == 1 then "bc2" else "bc1"
|
||||
local want: number = Bcn.size(kindName, w, h) or 0
|
||||
if len < want then
|
||||
return nil, Err.new(Err.TRUNCATED, "DXT mip shorter than " .. want .. " bytes", mipsAt + 64)
|
||||
end
|
||||
local dec, err = Bcn.decode(kindName, b, src, w, h)
|
||||
if not dec then
|
||||
return nil, Err.from(err)
|
||||
end
|
||||
buffer.copy(px, 0, dec, 0, n * 4)
|
||||
if kindName == "bc1" and alphaDepth == 0 then
|
||||
for i = 0, n - 1 do
|
||||
writeu8(px, i * 4 + 3, 255)
|
||||
end
|
||||
end
|
||||
name = ({ bc1 = "dxt1", bc2 = "dxt3", bc3 = "dxt5" } :: { [string]: string })[kindName]
|
||||
elseif compression == 3 then
|
||||
if len < n * 4 then
|
||||
return nil, Err.new(Err.TRUNCATED, "BGRA mip too short", mipsAt + 64)
|
||||
end
|
||||
for i = 0, n - 1 do
|
||||
local v = readu32(b, src + i * 4)
|
||||
writeu32(px, i * 4, swap(v, v // 16777216))
|
||||
end
|
||||
name = "bgra"
|
||||
else
|
||||
return nil, Err.new(Err.UNSUPPORTED, "compression " .. tostring(compression))
|
||||
end
|
||||
img.meta.source = { format = "blp", version = if v2 then 2 else 1, compression = name, alphaDepth = alphaDepth, alphaType = alphaType, mips = mips }
|
||||
return img, nil
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ encode
|
||||
-- halve(px, w, h) -> the next mip (2 x 2 box filter; odd edges repeat)
|
||||
local function halve(px: buffer, w: number, h: number): (buffer, number, number)
|
||||
local nw, nh = math.max(1, w // 2), math.max(1, h // 2)
|
||||
local out = buffer.create(nw * nh * 4)
|
||||
for y = 0, nh - 1 do
|
||||
for x = 0, nw - 1 do
|
||||
for c = 0, 3 do
|
||||
local s = 0
|
||||
for dy = 0, 1 do
|
||||
for dx = 0, 1 do
|
||||
local sx, sy = math.min(x * 2 + dx, w - 1), math.min(y * 2 + dy, h - 1)
|
||||
s += readu8(px, (sy * w + sx) * 4 + c)
|
||||
end
|
||||
end
|
||||
writeu8(out, (y * nw + x) * 4 + c, (s + 2) // 4)
|
||||
end
|
||||
end
|
||||
end
|
||||
return out, nw, nh
|
||||
end
|
||||
|
||||
function Blp.encode(img: Types.Image, opts: EncodeOptions?): (buffer?, Err.Err?)
|
||||
if type(img) ~= "table" or img.format ~= "rgba8" or type(img.pixels) ~= "buffer" then
|
||||
return nil, Err.new(Err.ARG, "expected an rgba8 Image")
|
||||
end
|
||||
local w, h = img.width, img.height
|
||||
if w < 1 or h < 1 or w > 65535 or h > 65535 then
|
||||
return nil, Err.new(Err.ARG, "bad size")
|
||||
end
|
||||
local levels: { buffer } = { img.pixels }
|
||||
local sizes: { { number } } = { { w, h } }
|
||||
if opts and opts.mips then
|
||||
local p, cw, ch = img.pixels, w, h
|
||||
while (cw > 1 or ch > 1) and #levels < 16 do
|
||||
p, cw, ch = halve(p, cw, ch)
|
||||
table.insert(levels, p)
|
||||
table.insert(sizes, { cw, ch })
|
||||
end
|
||||
end
|
||||
local out = Bytes.writer(1172 + w * h * 6)
|
||||
out:string("BLP2")
|
||||
out:u32le(1)
|
||||
out:u8(3) -- uncompressed BGRA
|
||||
out:u8(8) -- alpha depth
|
||||
out:u8(8) -- alpha type
|
||||
out:u8(if #levels > 1 then 1 else 0)
|
||||
out:u32le(w)
|
||||
out:u32le(h)
|
||||
local at = 1172
|
||||
for i = 1, 16 do
|
||||
local l = levels[i]
|
||||
out:u32le(if l then at else 0)
|
||||
if l then
|
||||
at += buffer.len(l)
|
||||
end
|
||||
end
|
||||
for i = 1, 16 do
|
||||
local l = levels[i]
|
||||
out:u32le(if l then buffer.len(l) else 0)
|
||||
end
|
||||
out:fill(0, 1024)
|
||||
for _, l in levels do
|
||||
local p = out:reserve(buffer.len(l))
|
||||
local o = out.buf
|
||||
for i = 0, buffer.len(l) // 4 - 1 do
|
||||
local v = readu32(l, i * 4)
|
||||
writeu32(o, p + i * 4, swap(v, v // 16777216))
|
||||
end
|
||||
out.pos = p + buffer.len(l)
|
||||
end
|
||||
return out:finish(), nil
|
||||
end
|
||||
|
||||
return Blp
|
||||
@@ -0,0 +1,247 @@
|
||||
--!strict
|
||||
-- image/tim: PlayStation TIM images (magic 0x10), read and write. Written from the PSX "File Formats" documentation
|
||||
-- (Sony, TIM: pmode, CLUT and image blocks with their VRAM positions); no code taken.
|
||||
-- Decode: 4-bit and 8-bit CLUT images (opts.clut picks the palette row, default 0), 15-bit direct and 24-bit
|
||||
-- direct, to rgba8: PSX colours are 1-5-5-5 STP-B-G-R, channels expanded as (v << 3) | (v >> 2); the colour 0x0000
|
||||
-- is transparent (alpha 0) as on the hardware, others opaque (the STP bit is kept in meta.source.stp = true when
|
||||
-- any pixel or CLUT entry has it). meta.source = { format, bpp, clut = { x, y, colours, count }?, x, y (VRAM) }.
|
||||
-- Encode: rgba8 to 16-bit direct (default), 24-bit (opts.bpp = 24, alpha dropped) or 4 / 8-bit CLUT when the image
|
||||
-- has at most 16 / 256 PSX colours (opts.bpp = 4 / 8; Err.ARG otherwise); alpha below 128 becomes 0x0000; opaque
|
||||
-- black is written as 0x8000 (STP set) so it stays opaque. Not supported: mixed mode (pmode 4) images.
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ requires
|
||||
local Err = require("@formats/core/Err")
|
||||
local Bytes = require("@formats/core/Bytes")
|
||||
local Types = require("@formats/Types")
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ contract
|
||||
local Tim = {
|
||||
name = "tim",
|
||||
category = "image",
|
||||
extensions = { "tim" },
|
||||
mime = { "image/x-tim" },
|
||||
deps = { "core/Err", "core/Bytes", "Types" },
|
||||
caps = { decode = true, encode = true, alpha = true, palette = true, depths = { 4, 8, 16, 24 } },
|
||||
}
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ types
|
||||
export type DecodeOptions = {
|
||||
clut: number?, -- the CLUT row to use for indexed images (0-based, default 0)
|
||||
maxPixels: number?, -- default 2^26
|
||||
}
|
||||
export type EncodeOptions = {
|
||||
bpp: number?, -- 4, 8, 16 (default) or 24
|
||||
x: number?, -- VRAM position of the image (default 0, 0)
|
||||
y: number?,
|
||||
clutX: number?, -- VRAM position of the CLUT (default 0, 480)
|
||||
clutY: number?,
|
||||
}
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ constants
|
||||
local readu8, readu16, writeu32, writeu16, readu32 = buffer.readu8, buffer.readu16, buffer.writeu32, buffer.writeu16, buffer.readu32
|
||||
local BPP = { [0] = 4, [1] = 8, [2] = 16, [3] = 24 }
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ sniff
|
||||
function Tim.sniff(r: Bytes.Reader): number
|
||||
if r:remaining() < 20 or r:peek(4) ~= "\16\0\0\0" then
|
||||
return 0
|
||||
end
|
||||
local flags = r:peekU8(4)
|
||||
if flags > 0x0F or (flags % 8) > 3 or r:peek(3, 5) ~= "\0\0\0" then
|
||||
return 0
|
||||
end
|
||||
return 0.8
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ decode
|
||||
local function colour(c: number): number
|
||||
if c == 0 then
|
||||
return 0
|
||||
end
|
||||
local r, g, b = c % 32, (c // 32) % 32, (c // 1024) % 32
|
||||
r, g, b = r * 8 + r // 4, g * 8 + g // 4, b * 8 + b // 4
|
||||
return 0xFF000000 + b * 65536 + g * 256 + r
|
||||
end
|
||||
|
||||
function Tim.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Image?, Err.Err?)
|
||||
local magic, flags = r:u32le(), r:u32le()
|
||||
if r.err then
|
||||
return nil, r.err
|
||||
end
|
||||
if magic ~= 0x10 then
|
||||
return nil, Err.new(Err.CORRUPT, "bad magic", 0)
|
||||
end
|
||||
local pmode = flags % 8
|
||||
local bpp = BPP[pmode]
|
||||
if not bpp then
|
||||
return nil, Err.new(Err.UNSUPPORTED, "pmode " .. pmode .. " (mixed / unknown)", 4)
|
||||
end
|
||||
local stp = false
|
||||
local pal: buffer? = nil
|
||||
local clutInfo: any = nil
|
||||
if bit32.band(flags, 8) ~= 0 then
|
||||
local start = r:tell()
|
||||
local bnum, cx, cy, cw, ch = r:u32le(), r:u16le(), r:u16le(), r:u16le(), r:u16le()
|
||||
if r.err then
|
||||
return nil, r.err
|
||||
end
|
||||
if bnum < 12 or cw * ch * 2 > bnum - 12 then
|
||||
return nil, Err.new(Err.CORRUPT, "bad CLUT block", start)
|
||||
end
|
||||
if not r:need(cw * ch * 2) then
|
||||
return nil, r.err
|
||||
end
|
||||
local row = math.clamp(math.floor(opts and opts.clut or 0), 0, math.max(ch - 1, 0))
|
||||
pal = buffer.create(256 * 4)
|
||||
local p = r.pos + row * cw * 2
|
||||
for i = 0, math.min(cw, 256) - 1 do
|
||||
local c = readu16(r.buf, p + i * 2)
|
||||
if c >= 0x8000 then
|
||||
stp = true
|
||||
end
|
||||
writeu32(pal :: buffer, i * 4, if c == 0x8000 then 0xFF000000 else colour(c % 0x8000))
|
||||
end
|
||||
clutInfo = { x = cx, y = cy, colours = cw, count = ch, row = row }
|
||||
r:seek(start + bnum)
|
||||
if r.err then
|
||||
return nil, r.err
|
||||
end
|
||||
elseif bpp <= 8 then
|
||||
return nil, Err.new(Err.CORRUPT, "indexed image without a CLUT", 4)
|
||||
end
|
||||
local start = r:tell()
|
||||
local bnum, ix, iy, iw, ih = r:u32le(), r:u16le(), r:u16le(), r:u16le(), r:u16le()
|
||||
if r.err then
|
||||
return nil, r.err
|
||||
end
|
||||
local w = if bpp == 4 then iw * 4 elseif bpp == 8 then iw * 2 elseif bpp == 16 then iw else (iw * 2) // 3
|
||||
local stride = iw * 2
|
||||
if w * ih > (opts and opts.maxPixels or 2 ^ 26) then
|
||||
return nil, Err.new(Err.LIMIT, "image too big")
|
||||
end
|
||||
if bnum < 12 or stride * ih > bnum - 12 then
|
||||
return nil, Err.new(Err.CORRUPT, "bad image block", start)
|
||||
end
|
||||
if not r:need(stride * ih) then
|
||||
return nil, r.err
|
||||
end
|
||||
local img = Types.Image.new(w, ih)
|
||||
local px, src, at = img.pixels, r.buf, r.pos
|
||||
for y = 0, ih - 1 do
|
||||
local row = at + y * stride
|
||||
local d = y * w * 4
|
||||
if bpp == 4 then
|
||||
for x = 0, w - 1 do
|
||||
local v = readu8(src, row + x // 2)
|
||||
local i = if x % 2 == 0 then v % 16 else v // 16
|
||||
writeu32(px, d + x * 4, readu32(pal :: buffer, i * 4))
|
||||
end
|
||||
elseif bpp == 8 then
|
||||
for x = 0, w - 1 do
|
||||
writeu32(px, d + x * 4, readu32(pal :: buffer, readu8(src, row + x) * 4))
|
||||
end
|
||||
elseif bpp == 16 then
|
||||
for x = 0, w - 1 do
|
||||
local c = readu16(src, row + x * 2)
|
||||
if c >= 0x8000 then
|
||||
stp = true
|
||||
end
|
||||
writeu32(px, d + x * 4, if c == 0x8000 then 0xFF000000 else colour(c % 0x8000))
|
||||
end
|
||||
else
|
||||
for x = 0, w - 1 do
|
||||
local o = row + x * 3
|
||||
writeu32(px, d + x * 4, 0xFF000000 + readu8(src, o + 2) * 65536 + readu8(src, o + 1) * 256 + readu8(src, o))
|
||||
end
|
||||
end
|
||||
end
|
||||
img.meta.source = { format = "tim", bpp = bpp, x = ix, y = iy, clut = clutInfo, stp = stp or nil }
|
||||
return img, nil
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ encode
|
||||
-- rgba8 pixel -> PSX colour
|
||||
local function psx(v: number): number
|
||||
local r, g, b, a = v % 256, (v // 256) % 256, (v // 65536) % 256, v // 16777216
|
||||
if a < 128 then
|
||||
return 0
|
||||
end
|
||||
local c = (b // 8) * 1024 + (g // 8) * 32 + r // 8
|
||||
return if c == 0 then 0x8000 else c
|
||||
end
|
||||
|
||||
function Tim.encode(img: Types.Image, opts: EncodeOptions?): (buffer?, Err.Err?)
|
||||
if type(img) ~= "table" or img.format ~= "rgba8" or type(img.pixels) ~= "buffer" then
|
||||
return nil, Err.new(Err.ARG, "expected an rgba8 Image")
|
||||
end
|
||||
local w, h = img.width, img.height
|
||||
local bpp = opts and opts.bpp or 16
|
||||
local per = ({ [4] = 4, [8] = 2, [16] = 1, [24] = 2 / 3 } :: { [number]: number })[bpp]
|
||||
if not per then
|
||||
return nil, Err.new(Err.ARG, "bpp must be 4, 8, 16 or 24")
|
||||
end
|
||||
local iw = if bpp == 24 then (w * 3 + 1) // 2 else math.ceil(w / per)
|
||||
if iw > 0xFFFF or h > 0xFFFF then
|
||||
return nil, Err.new(Err.ARG, "image too wide for TIM")
|
||||
end
|
||||
local px = img.pixels
|
||||
local out = Bytes.writer(64 + iw * 2 * h)
|
||||
out:u32le(0x10)
|
||||
local colours: { number } = {}
|
||||
local index: { [number]: number } = {}
|
||||
if bpp <= 8 then
|
||||
for i = 0, w * h - 1 do
|
||||
local c = psx(readu32(px, i * 4))
|
||||
if not index[c] then
|
||||
table.insert(colours, c)
|
||||
index[c] = #colours - 1
|
||||
if #colours > (if bpp == 4 then 16 else 256) then
|
||||
return nil, Err.new(Err.ARG, "more than " .. (if bpp == 4 then 16 else 256) .. " colours for a " .. bpp .. "-bit TIM")
|
||||
end
|
||||
end
|
||||
end
|
||||
local n = if bpp == 4 then 16 else 256
|
||||
out:u32le(8 + (if bpp == 4 then 0 else 1))
|
||||
out:u32le(12 + n * 2)
|
||||
out:u16le(opts and opts.clutX or 0)
|
||||
out:u16le(opts and opts.clutY or 480)
|
||||
out:u16le(n)
|
||||
out:u16le(1)
|
||||
for i = 1, n do
|
||||
out:u16le(colours[i] or 0)
|
||||
end
|
||||
else
|
||||
out:u32le(if bpp == 16 then 2 else 3)
|
||||
end
|
||||
out:u32le(12 + iw * 2 * h)
|
||||
out:u16le(opts and opts.x or 0)
|
||||
out:u16le(opts and opts.y or 0)
|
||||
out:u16le(iw)
|
||||
out:u16le(h)
|
||||
local at = out:reserve(iw * 2 * h)
|
||||
local b = out.buf
|
||||
buffer.fill(b, at, 0, iw * 2 * h)
|
||||
for y = 0, h - 1 do
|
||||
local row = at + y * iw * 2
|
||||
for x = 0, w - 1 do
|
||||
local v = readu32(px, (y * w + x) * 4)
|
||||
if bpp == 4 then
|
||||
local i = index[psx(v)]
|
||||
local o = row + x // 2
|
||||
buffer.writeu8(b, o, buffer.readu8(b, o) + (if x % 2 == 0 then i else i * 16))
|
||||
elseif bpp == 8 then
|
||||
buffer.writeu8(b, row + x, index[psx(v)])
|
||||
elseif bpp == 16 then
|
||||
writeu16(b, row + x * 2, psx(v))
|
||||
else
|
||||
buffer.writeu8(b, row + x * 3, v % 256)
|
||||
buffer.writeu8(b, row + x * 3 + 1, (v // 256) % 256)
|
||||
buffer.writeu8(b, row + x * 3 + 2, (v // 65536) % 256)
|
||||
end
|
||||
end
|
||||
end
|
||||
out.pos = at + iw * 2 * h
|
||||
return out:finish(), nil
|
||||
end
|
||||
|
||||
return Tim
|
||||
@@ -0,0 +1,245 @@
|
||||
--!strict
|
||||
-- image/vtf: Valve Texture Format (VTF 7.0 - 7.5: Source engine textures), read. Written from the Valve Developer
|
||||
-- Community "VTF (Valve Texture Format)" page; no code taken.
|
||||
-- Decode: the high-resolution image (located by the 7.3+ resource directory or after the low-resolution thumbnail
|
||||
-- for 7.0 - 7.2), mip 0 of slice 0 and face 0 (opts.mip / opts.face / opts.slice pick others), frame 1 as the Image
|
||||
-- and every frame of an animated texture in img.frames (opts.frames ~= false; delay opts.delay, default 0.1 s), to
|
||||
-- rgba8. Texel formats: RGBA8888, ABGR8888, RGB888, BGR888, RGB565, I8, IA88, A8, RGB888 / BGR888 bluescreen (pure
|
||||
-- blue transparent), ARGB8888, BGRA8888, BGRX8888, BGR565, BGRX5551, BGRA5551, BGRA4444, UV88, UVWQ8888, UVLX8888,
|
||||
-- RGBA16161616 (integers) / RGBA16161616F (halves, clamped), R32F, RGB323232F, RGBA32323232F (all through
|
||||
-- codecs/image/Texel), DXT1 (+ one-bit alpha),
|
||||
-- DXT3, DXT5, ATI1N, ATI2N (ids 35 / 34 since Alien Swarm, 38 / 37 in Source 2013) through codecs/image/Bcn. meta.source = { format, version, flags, frames, faces, depth, mips,
|
||||
-- texel, reflectivity, bumpScale }.
|
||||
-- Not supported: P8 (never implemented by Valve), the newer Strata / Source 2 formats, writing.
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ requires
|
||||
local Err = require("@formats/core/Err")
|
||||
local Bytes = require("@formats/core/Bytes")
|
||||
local Types = require("@formats/Types")
|
||||
local Bcn = require("@formats/codecs/image/Bcn")
|
||||
local Texel = require("@formats/codecs/image/Texel")
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ contract
|
||||
local Vtf = {
|
||||
name = "vtf",
|
||||
category = "image",
|
||||
extensions = { "vtf" },
|
||||
mime = { "image/x-vtf" },
|
||||
deps = { "core/Err", "core/Bytes", "Types", "codecs/image/Bcn", "codecs/image/Texel" },
|
||||
caps = { decode = true, encode = false, alpha = true, animation = true, versions = { "7.0", "7.1", "7.2", "7.3", "7.4", "7.5" } },
|
||||
}
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ types
|
||||
export type DecodeOptions = {
|
||||
mip: number?, -- mip level (0 = full size, default)
|
||||
face: number?, -- cube map face (0-based, default 0)
|
||||
slice: number?, -- volume slice (0-based, default 0)
|
||||
frames: boolean?, -- decode every frame into img.frames (default true)
|
||||
delay: number?, -- frame delay in seconds (default 0.1)
|
||||
maxPixels: number?, -- default 2^26
|
||||
}
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ constants
|
||||
local M = Texel.masked
|
||||
-- format id -> a codecs/image/Texel format (name or bit-mask descriptor) | { texel, bluescreen = true } | a BCn kind
|
||||
local FORMATS: { [number]: any } = {
|
||||
[0] = "rgba8", -- RGBA8888
|
||||
[1] = M(4, 0xFF000000, 0x00FF0000, 0x0000FF00, 0x000000FF), -- ABGR8888
|
||||
[2] = "rgb8", -- RGB888
|
||||
[3] = "bgr8", -- BGR888
|
||||
[4] = "r5g6b5", -- RGB565: red in the low bits (as VTFLib / srctools read it)
|
||||
[5] = "l8", -- I8
|
||||
[6] = "la8", -- IA88
|
||||
[8] = "a8", -- A8
|
||||
[9] = { texel = "rgb8", bluescreen = true }, -- RGB888_BLUESCREEN
|
||||
[10] = { texel = "bgr8", bluescreen = true }, -- BGR888_BLUESCREEN
|
||||
[11] = M(4, 0xFF000000, 0x000000FF, 0x0000FF00, 0x00FF0000), -- ARGB8888: VTFLib's layout (G, B, A, R in memory)
|
||||
[12] = "bgra8", -- BGRA8888
|
||||
[13] = "bc1", -- DXT1
|
||||
[14] = "bc2", -- DXT3
|
||||
[15] = "bc3", -- DXT5
|
||||
[16] = "bgrx8", -- BGRX8888
|
||||
[17] = "b5g6r5", -- BGR565: blue in the low bits
|
||||
[18] = "b5g5r5x1", -- BGRX5551
|
||||
[19] = "b4g4r4a4", -- BGRA4444
|
||||
[20] = "bc1a", -- DXT1_ONEBITALPHA
|
||||
[21] = "b5g5r5a1", -- BGRA5551
|
||||
[22] = "rg8", -- UV88
|
||||
[23] = "rgba8", -- UVWQ8888
|
||||
[24] = "rgba16f", -- RGBA16161616F
|
||||
[25] = "rgba16", -- RGBA16161616
|
||||
[26] = "rgba8", -- UVLX8888
|
||||
[27] = "r32f", -- R32F
|
||||
[28] = "rgb32f", -- RGB323232F
|
||||
[29] = "rgba32f", -- RGBA32323232F
|
||||
[34] = "bc5", -- ATI2N (Alien Swarm and later)
|
||||
[35] = "bc4", -- ATI1N (Alien Swarm and later)
|
||||
[37] = "bc5", -- ATI2N (Source 2013)
|
||||
[38] = "bc4", -- ATI1N (Source 2013)
|
||||
}
|
||||
local BCN: { [string]: boolean } = { bc1 = true, bc1a = true, bc2 = true, bc3 = true, bc4 = true, bc5 = true }
|
||||
local NAMES: { [number]: string } = { [0] = "RGBA8888", "ABGR8888", "RGB888", "BGR888", "RGB565", "I8", "IA88", "P8", "A8", "RGB888_BLUESCREEN",
|
||||
"BGR888_BLUESCREEN", "ARGB8888", "BGRA8888", "DXT1", "DXT3", "DXT5", "BGRX8888", "BGR565", "BGRX5551", "BGRA4444",
|
||||
"DXT1_ONEBITALPHA", "BGRA5551", "UV88", "UVWQ8888", "RGBA16161616F", "RGBA16161616", "UVLX8888", "R32F", "RGB323232F",
|
||||
"RGBA32323232F", "NV_DST16", "NV_DST24", "NV_INTZ", "NV_RAWZ", "ATI2N", "ATI1N", "NV_NULL", "ATI2N", "ATI1N" }
|
||||
local ENVMAP = 0x4000
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ sniff
|
||||
function Vtf.sniff(r: Bytes.Reader): number
|
||||
return if r:peek(4) == "VTF\0" and r:peekU8(4) == 7 then 1 else 0
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ decode
|
||||
-- bytes of one w x h image in format f
|
||||
local function imageSize(f: any, w: number, h: number): number
|
||||
if type(f) == "string" and BCN[f] then
|
||||
return Bcn.size(if f == "bc1a" then "bc1" else f, w, h) or 0
|
||||
end
|
||||
return Texel.size(if type(f) == "table" and f.texel then f.texel else f, w, h) or 0
|
||||
end
|
||||
|
||||
function Vtf.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Image?, Err.Err?)
|
||||
local size = r.limit - r.base
|
||||
local b, base = r.buf, r.base
|
||||
if size < 64 then
|
||||
return nil, Err.new(Err.TRUNCATED, "header", 0)
|
||||
end
|
||||
if buffer.readstring(b, base, 4) ~= "VTF\0" then
|
||||
return nil, Err.new(Err.CORRUPT, "bad magic", 0)
|
||||
end
|
||||
local major, minor = buffer.readu32(b, base + 4), buffer.readu32(b, base + 8)
|
||||
if major ~= 7 or minor > 5 then
|
||||
return nil, Err.new(Err.UNSUPPORTED, "VTF version " .. major .. "." .. minor, 4)
|
||||
end
|
||||
local headerSize = buffer.readu32(b, base + 12)
|
||||
local w, h = buffer.readu16(b, base + 16), buffer.readu16(b, base + 18)
|
||||
local flags = buffer.readu32(b, base + 20)
|
||||
local frames, firstFrame = buffer.readu16(b, base + 24), buffer.readu16(b, base + 26)
|
||||
local refl = { buffer.readf32(b, base + 32), buffer.readf32(b, base + 36), buffer.readf32(b, base + 40) }
|
||||
local bump = buffer.readf32(b, base + 48)
|
||||
local fmtId = buffer.readi32(b, base + 52)
|
||||
local mips = buffer.readu8(b, base + 56)
|
||||
local lowFmt = buffer.readi32(b, base + 57)
|
||||
local lowW, lowH = buffer.readu8(b, base + 61), buffer.readu8(b, base + 62)
|
||||
local depth = if minor >= 2 and size >= 65 then math.max(1, buffer.readu16(b, base + 63)) else 1
|
||||
if w == 0 or h == 0 then
|
||||
return nil, Err.new(Err.CORRUPT, "zero size", 16)
|
||||
end
|
||||
if w * h > (opts and opts.maxPixels or 2 ^ 26) then
|
||||
return nil, Err.new(Err.LIMIT, "image too big")
|
||||
end
|
||||
local f: any = FORMATS[fmtId]
|
||||
if not f then
|
||||
return nil, Err.new(Err.UNSUPPORTED, "texel format " .. (NAMES[fmtId] or tostring(fmtId)), 52)
|
||||
end
|
||||
frames = math.max(1, frames)
|
||||
mips = math.max(1, mips)
|
||||
local faces = 1
|
||||
if bit32.band(flags, ENVMAP) ~= 0 then
|
||||
faces = if minor < 5 and firstFrame ~= 0xFFFF then 7 else 6
|
||||
end
|
||||
-- where the high-resolution data starts
|
||||
local dataAt: number? = nil
|
||||
if minor >= 3 then
|
||||
if size < 80 then
|
||||
return nil, Err.new(Err.TRUNCATED, "resource directory", 68)
|
||||
end
|
||||
local nres = buffer.readu32(b, base + 68)
|
||||
if nres > 32 or 80 + nres * 8 > size then
|
||||
return nil, Err.new(Err.CORRUPT, "bad resource count", 68)
|
||||
end
|
||||
for i = 0, nres - 1 do
|
||||
local o = base + 80 + i * 8
|
||||
if buffer.readu8(b, o) == 0x30 and buffer.readu8(b, o + 1) == 0 and buffer.readu8(b, o + 2) == 0 then
|
||||
dataAt = buffer.readu32(b, o + 4)
|
||||
end
|
||||
end
|
||||
if not dataAt then
|
||||
return nil, Err.new(Err.CORRUPT, "no high-resolution image resource", 80)
|
||||
end
|
||||
else
|
||||
local lf = FORMATS[lowFmt]
|
||||
local lowSize = if lowFmt >= 0 and lowW > 0 and lowH > 0 and lf then imageSize(lf, lowW, lowH) else 0
|
||||
dataAt = headerSize + lowSize
|
||||
end
|
||||
-- the chain: mips smallest first; per mip: frames, faces, slices
|
||||
local mip = math.clamp(math.floor(opts and opts.mip or 0), 0, mips - 1)
|
||||
local face = math.clamp(math.floor(opts and opts.face or 0), 0, faces - 1)
|
||||
local slice = math.clamp(math.floor(opts and opts.slice or 0), 0, depth - 1)
|
||||
local off = dataAt :: number
|
||||
for m = mips - 1, mip + 1, -1 do
|
||||
local mw, mh, md = math.max(1, w // 2 ^ m), math.max(1, h // 2 ^ m), math.max(1, depth // 2 ^ m)
|
||||
off += imageSize(f, mw, mh) * md * faces * frames
|
||||
end
|
||||
local mw, mh, md = math.max(1, w // 2 ^ mip), math.max(1, h // 2 ^ mip), math.max(1, depth // 2 ^ mip)
|
||||
local one = imageSize(f, mw, mh)
|
||||
local function image(frame: number): (Types.Image?, Err.Err?)
|
||||
local at = off + ((frame * faces + face) * md + math.min(slice, md - 1)) * one
|
||||
if at + one > size or at < 0 then
|
||||
return nil, Err.new(Err.TRUNCATED, "image data past the end", at)
|
||||
end
|
||||
local img = Types.Image.new(mw, mh)
|
||||
if type(f) == "string" and BCN[f] then
|
||||
local kind = if f == "bc1a" then "bc1" else f
|
||||
local px, e = Bcn.decode(kind, b, base + at, mw, mh)
|
||||
if not px then
|
||||
return nil, Err.from(e)
|
||||
end
|
||||
buffer.copy(img.pixels, 0, px, 0, mw * mh * 4)
|
||||
if f == "bc1" then
|
||||
-- plain DXT1 carries no alpha: the transparent colour of 3-colour blocks reads as opaque black
|
||||
for i = 0, mw * mh - 1 do
|
||||
buffer.writeu8(img.pixels, i * 4 + 3, 255)
|
||||
end
|
||||
end
|
||||
else
|
||||
local blue = type(f) == "table" and f.bluescreen == true
|
||||
local px, e = Texel.decode(if blue then f.texel else f, b, base + at, mw, mh)
|
||||
if not px then
|
||||
return nil, Err.from(e)
|
||||
end
|
||||
buffer.copy(img.pixels, 0, px, 0, mw * mh * 4)
|
||||
if blue then
|
||||
-- pure blue is the transparent key
|
||||
for i = 0, mw * mh - 1 do
|
||||
if buffer.readu32(img.pixels, i * 4) == 0xFFFF0000 then
|
||||
buffer.writeu32(img.pixels, i * 4, 0)
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
return img, nil
|
||||
end
|
||||
local img, err = image(0)
|
||||
if not img then
|
||||
return nil, err
|
||||
end
|
||||
if frames > 1 and not (opts and opts.frames == false) then
|
||||
local delay = opts and opts.delay or 0.1
|
||||
local list: { Types.Frame } = { { image = img, delay = delay, x = 0, y = 0, dispose = "none", blend = "source" } :: any }
|
||||
for fr = 1, frames - 1 do
|
||||
local fi, ferr = image(fr)
|
||||
if not fi then
|
||||
return nil, ferr
|
||||
end
|
||||
table.insert(list, { image = fi, delay = delay, x = 0, y = 0, dispose = "none", blend = "source" } :: any)
|
||||
end
|
||||
img.frames = list
|
||||
img.loops = 0
|
||||
end
|
||||
img.meta.source = {
|
||||
format = "vtf",
|
||||
version = major .. "." .. minor,
|
||||
flags = flags,
|
||||
frames = frames,
|
||||
faces = faces,
|
||||
depth = depth,
|
||||
mips = mips,
|
||||
texel = NAMES[fmtId],
|
||||
reflectivity = refl,
|
||||
bumpScale = bump,
|
||||
}
|
||||
return img, nil
|
||||
end
|
||||
|
||||
return Vtf
|
||||
@@ -0,0 +1,291 @@
|
||||
--!strict
|
||||
-- model/bsp/Brush: Quake 1 (BSP 29), Half-Life (BSP 30) and Quake II (IBSP 38) maps to a Scene: every face (a convex
|
||||
-- polygon of surface edges) fan-triangulated counter-clockwise about its plane's normal, one primitive per texture
|
||||
-- per model (model 0 = the world, the others = brush entities "*1", "*2", ... as child nodes), TEXCOORD_0 from the
|
||||
-- texture vectors (s = v . s.xyz + s.w, divided by the texture size), NORMAL = the plane normal. Textures: Quake /
|
||||
-- Half-Life embedded mip textures (mip 0) decoded through the palette (Half-Life: each texture's own; Quake: the
|
||||
-- caller's), textures kept in WAD files as URIs; Quake II textures are external .wal files (URIs; their size from
|
||||
-- opts.resolve("textures/<name>.wal") when available, else texture coordinates stay in texels: extras.bsp.texels).
|
||||
-- Written from the Quake specs (bspfile.h of the Quake / Quake II source releases); no code taken.
|
||||
-- Not supported: lightmaps (light offsets are kept per face in extras), visibility / BSP tree / clip hulls.
|
||||
local Types = require("@formats/Types")
|
||||
local Pixels = require("@formats/codecs/image/Pixels")
|
||||
|
||||
local Brush = {}
|
||||
|
||||
local Scene = Types.Scene
|
||||
local readi32, readu16, readf32, readu32 = buffer.readi32, buffer.readu16, buffer.readf32, buffer.readu32
|
||||
local writef32, writeu32 = buffer.writef32, buffer.writeu32
|
||||
|
||||
export type Lump = { at: number, size: number }
|
||||
export type Options = {
|
||||
palette: buffer?,
|
||||
wal: ((name: string) -> buffer?)?, -- Quake II: the .wal file of a texture (for its size)
|
||||
maxPixels: number?,
|
||||
maxVertices: number?,
|
||||
}
|
||||
|
||||
type Tex = { name: string, width: number, height: number, image: Types.Image?, texels: boolean }
|
||||
type Batch = { tex: number, pos: { number }, nrm: { number }, uv: { number } }
|
||||
|
||||
local function cstr(b: buffer, at: number, n: number): string
|
||||
return (string.match(buffer.readstring(b, at, n), "^[^%z]*")) :: string
|
||||
end
|
||||
|
||||
-- miptex lump (Quake / Half-Life) -> textures
|
||||
local function miptex(b: buffer, base: number, l: Lump, hl: boolean, pal: buffer?, maxPixels: number): ({ Tex }?, string?)
|
||||
local out: { Tex } = {}
|
||||
if l.size < 4 then
|
||||
return out, nil
|
||||
end
|
||||
local at = base + l.at
|
||||
local n = readi32(b, at)
|
||||
if n < 0 or n > 65536 or 4 + n * 4 > l.size then
|
||||
return nil, "bad miptex lump"
|
||||
end
|
||||
local gpal = if pal then Pixels.palette(pal, 0, 256) else nil
|
||||
for i = 0, n - 1 do
|
||||
local o = readi32(b, at + 4 + i * 4)
|
||||
if o < 0 or o + 40 > l.size then
|
||||
out[i + 1] = { name = "missing" .. i, width = 64, height = 64, image = nil, texels = false }
|
||||
else
|
||||
local m = at + o
|
||||
local name = cstr(b, m, 16)
|
||||
local w, h, off0 = readu32(b, m + 16), readu32(b, m + 20), readu32(b, m + 24)
|
||||
local t: Tex = { name = name, width = math.max(w, 1), height = math.max(h, 1), image = nil, texels = false }
|
||||
if off0 ~= 0 and w > 0 and h > 0 and w * h <= maxPixels then
|
||||
local px = m + off0
|
||||
local need = w * h
|
||||
local palAt = m + readu32(b, m + 36) + (w // 8) * (h // 8) + 2
|
||||
if o + off0 + need <= l.size then
|
||||
local p = gpal
|
||||
if hl then
|
||||
p = if palAt - at + 768 <= l.size then Pixels.palette(b, palAt, 256) else nil
|
||||
end
|
||||
local img = Types.Image.new(w, h)
|
||||
if p then
|
||||
Pixels.indexed(b, px, w, 8, img.pixels, w, h, true, p)
|
||||
else
|
||||
for k = 0, need - 1 do
|
||||
writeu32(img.pixels, k * 4, 0xFF000000 + buffer.readu8(b, px + k) * 0x10101)
|
||||
end
|
||||
end
|
||||
img.meta.source = { format = "bsp", miptex = name, palette = p ~= nil }
|
||||
t.image = img
|
||||
end
|
||||
end
|
||||
out[i + 1] = t
|
||||
end
|
||||
end
|
||||
return out, nil
|
||||
end
|
||||
|
||||
-- decode(b, base, size, lumps, variant, opts) -> Scene | nil, message
|
||||
-- variant "q1" (29), "hl" (30) or "q2" (38); lumps by name: vertices, edges, surfedges, faces, texinfo, planes,
|
||||
-- models, miptex (q1 / hl)
|
||||
function Brush.decode(b: buffer, base: number, lumps: { [string]: Lump }, variant: string, opts: Options?): (Types.Scene?, string?)
|
||||
local q2 = variant == "q2"
|
||||
local maxPixels = opts and opts.maxPixels or 2 ^ 24
|
||||
local V, E, SE, Fc, TI, P, M = lumps.vertices, lumps.edges, lumps.surfedges, lumps.faces, lumps.texinfo, lumps.planes, lumps.models
|
||||
local nV, nE, nSE, nF = V.size // 12, E.size // 4, SE.size // 4, Fc.size // 20
|
||||
local tiSize = if q2 then 76 else 40
|
||||
local nTI, nP = TI.size // tiSize, P.size // 20
|
||||
local mSize = if q2 then 48 else 64
|
||||
local nM = M.size // mSize
|
||||
if nF > (opts and opts.maxVertices or 2 ^ 24) then
|
||||
return nil, "limit: too many faces"
|
||||
end
|
||||
-- textures
|
||||
local texs: { Tex } = {}
|
||||
local texOf: { number } = {} -- texinfo -> texture index (1-based)
|
||||
if q2 then
|
||||
local byName: { [string]: number } = {}
|
||||
for i = 0, nTI - 1 do
|
||||
local name = cstr(b, base + TI.at + i * 76 + 40, 32)
|
||||
local ti = byName[name]
|
||||
if not ti then
|
||||
local w, h, texels = 1, 1, true
|
||||
local wal = opts and opts.wal and opts.wal(name)
|
||||
if wal and buffer.len(wal) >= 40 then
|
||||
w, h, texels = math.max(1, readu32(wal, 32)), math.max(1, readu32(wal, 36)), false
|
||||
end
|
||||
table.insert(texs, { name = name, width = w, height = h, image = nil, texels = texels })
|
||||
ti = #texs
|
||||
byName[name] = ti
|
||||
end
|
||||
texOf[i + 1] = ti
|
||||
end
|
||||
else
|
||||
local list, err = miptex(b, base, lumps.miptex, variant == "hl", opts and opts.palette, maxPixels)
|
||||
if not list then
|
||||
return nil, err
|
||||
end
|
||||
texs = list
|
||||
for i = 0, nTI - 1 do
|
||||
local mt = readi32(b, base + TI.at + i * 40 + 32)
|
||||
texOf[i + 1] = if mt >= 0 and mt < #texs then mt + 1 else 0
|
||||
end
|
||||
end
|
||||
-- faces of each model
|
||||
local scene = Scene.new()
|
||||
scene.meta.up = "z"
|
||||
local faceModel: { number } = {}
|
||||
local models: { { first: number, count: number, origin: { number } } } = {}
|
||||
for m = 0, nM - 1 do
|
||||
local o = base + M.at + m * mSize
|
||||
local origin = { readf32(b, o + 24), readf32(b, o + 28), readf32(b, o + 32) }
|
||||
local fo = if q2 then 40 else 56
|
||||
local first, count = readi32(b, o + fo), readi32(b, o + fo + 4)
|
||||
table.insert(models, { first = first, count = count, origin = origin })
|
||||
if first >= 0 and count >= 0 and first + count <= nF then
|
||||
for f = first, first + count - 1 do
|
||||
faceModel[f + 1] = faceModel[f + 1] or (m + 1)
|
||||
end
|
||||
end
|
||||
end
|
||||
if #models == 0 then
|
||||
table.insert(models, { first = 0, count = nF, origin = { 0, 0, 0 } })
|
||||
for f = 1, nF do
|
||||
faceModel[f] = 1
|
||||
end
|
||||
end
|
||||
local batches: { [number]: { [number]: Batch } } = {}
|
||||
local orders: { [number]: { number } } = {}
|
||||
local skipped = 0
|
||||
for f = 0, nF - 1 do
|
||||
local fo = base + Fc.at + f * 20
|
||||
local plane, side, firstEdge, numEdges, texinfo = readu16(b, fo), readu16(b, fo + 2), readi32(b, fo + 4), readu16(b, fo + 8), readu16(b, fo + 10)
|
||||
local model = faceModel[f + 1]
|
||||
if not model or numEdges < 3 or firstEdge < 0 or firstEdge + numEdges > nSE or plane >= nP or texinfo >= nTI then
|
||||
skipped += 1
|
||||
continue
|
||||
end
|
||||
-- the polygon
|
||||
local poly: { number } = {}
|
||||
local ok = true
|
||||
for k = 0, numEdges - 1 do
|
||||
local se = readi32(b, base + SE.at + (firstEdge + k) * 4)
|
||||
local e = math.abs(se)
|
||||
if e >= nE then
|
||||
ok = false
|
||||
break
|
||||
end
|
||||
local v = if se >= 0 then readu16(b, base + E.at + e * 4) else readu16(b, base + E.at + e * 4 + 2)
|
||||
if v >= nV then
|
||||
ok = false
|
||||
break
|
||||
end
|
||||
local vo = base + V.at + v * 12
|
||||
table.insert(poly, readf32(b, vo))
|
||||
table.insert(poly, readf32(b, vo + 4))
|
||||
table.insert(poly, readf32(b, vo + 8))
|
||||
end
|
||||
if not ok then
|
||||
skipped += 1
|
||||
continue
|
||||
end
|
||||
local po = base + P.at + plane * 20
|
||||
local nx, ny, nz = readf32(b, po), readf32(b, po + 4), readf32(b, po + 8)
|
||||
if side ~= 0 then
|
||||
nx, ny, nz = -nx, -ny, -nz
|
||||
end
|
||||
-- orient counter-clockwise about the normal (Newell's normal of the polygon as stored)
|
||||
local n = #poly // 3
|
||||
local ax, ay, az = 0, 0, 0
|
||||
for k = 0, n - 1 do
|
||||
local j = (k + 1) % n
|
||||
local x1, y1, z1 = poly[k * 3 + 1], poly[k * 3 + 2], poly[k * 3 + 3]
|
||||
local x2, y2, z2 = poly[j * 3 + 1], poly[j * 3 + 2], poly[j * 3 + 3]
|
||||
ax += (y1 - y2) * (z1 + z2)
|
||||
ay += (z1 - z2) * (x1 + x2)
|
||||
az += (x1 - x2) * (y1 + y2)
|
||||
end
|
||||
local order: { number } = {}
|
||||
if ax * nx + ay * ny + az * nz >= 0 then
|
||||
for k = 0, n - 1 do
|
||||
order[k + 1] = k
|
||||
end
|
||||
else
|
||||
order[1] = 0
|
||||
for k = 1, n - 1 do
|
||||
order[k + 1] = n - k
|
||||
end
|
||||
end
|
||||
local tio = base + TI.at + texinfo * tiSize
|
||||
local sx, sy, sz, so = readf32(b, tio), readf32(b, tio + 4), readf32(b, tio + 8), readf32(b, tio + 12)
|
||||
local tx, ty, tz, to = readf32(b, tio + 16), readf32(b, tio + 20), readf32(b, tio + 24), readf32(b, tio + 28)
|
||||
local ti = texOf[texinfo + 1] or 0
|
||||
local tex = texs[ti]
|
||||
local w, h = if tex then tex.width else 1, if tex then tex.height else 1
|
||||
local bm = batches[model] or {}
|
||||
batches[model] = bm
|
||||
local bt = bm[ti]
|
||||
if not bt then
|
||||
bt = { tex = ti, pos = {}, nrm = {}, uv = {} }
|
||||
bm[ti] = bt
|
||||
local ol = orders[model] or {}
|
||||
orders[model] = ol
|
||||
table.insert(ol, ti)
|
||||
end
|
||||
local batch: Batch = bt
|
||||
for k = 2, n - 1 do
|
||||
for _, c in { order[1], order[k], order[k + 1] } do
|
||||
local x, y, z = poly[c * 3 + 1], poly[c * 3 + 2], poly[c * 3 + 3]
|
||||
local pp, nn, uu = batch.pos, batch.nrm, batch.uv
|
||||
pp[#pp + 1], pp[#pp + 2], pp[#pp + 3] = x, y, z
|
||||
nn[#nn + 1], nn[#nn + 2], nn[#nn + 3] = nx, ny, nz
|
||||
uu[#uu + 1] = (x * sx + y * sy + z * sz + so) / w
|
||||
uu[#uu + 1] = (x * tx + y * ty + z * tz + to) / h
|
||||
end
|
||||
end
|
||||
end
|
||||
-- textures, materials
|
||||
for i, t in texs do
|
||||
local tex: Types.Texture = { name = t.name, image = t.image, uri = if t.image then nil else (if q2 then "textures/" .. t.name .. ".wal" else t.name) }
|
||||
table.insert(scene.textures, tex)
|
||||
local mat = Scene.material(t.name)
|
||||
mat.metallic = 0
|
||||
local extras: any = { bsp = { texels = if t.texels then true else nil, width = t.width, height = t.height } }
|
||||
mat.extras = extras
|
||||
mat.extras = { bsp = { texels = if t.texels then true else nil, width = t.width, height = t.height } } :: any
|
||||
table.insert(scene.materials, mat)
|
||||
end
|
||||
-- meshes and nodes
|
||||
local root: Types.Node = { name = "bsp", children = {} }
|
||||
table.insert(scene.nodes, root)
|
||||
scene.roots[1] = 1
|
||||
for m, mdl in models do
|
||||
local list = orders[m]
|
||||
if list then
|
||||
local mesh: Types.Mesh = { name = if m == 1 then "world" else "*" .. (m - 1), primitives = {} }
|
||||
for _, ti in list do
|
||||
local bt = batches[m][ti]
|
||||
local nv = #bt.pos // 3
|
||||
local pb, nb, ub, ib = buffer.create(nv * 12), buffer.create(nv * 12), buffer.create(nv * 8), buffer.create(nv * 4)
|
||||
for k = 1, nv * 3 do
|
||||
writef32(pb, (k - 1) * 4, bt.pos[k])
|
||||
writef32(nb, (k - 1) * 4, bt.nrm[k])
|
||||
end
|
||||
for k = 1, nv * 2 do
|
||||
writef32(ub, (k - 1) * 4, bt.uv[k])
|
||||
end
|
||||
for k = 0, nv - 1 do
|
||||
writeu32(ib, k * 4, k)
|
||||
end
|
||||
table.insert(mesh.primitives, {
|
||||
attributes = { POSITION = Scene.accessor(pb, "f32", 3, nv), NORMAL = Scene.accessor(nb, "f32", 3, nv), TEXCOORD_0 = Scene.accessor(ub, "f32", 2, nv) },
|
||||
indices = Scene.accessor(ib, "u32", 1, nv),
|
||||
mode = "triangles" :: any,
|
||||
material = if ti > 0 then ti else nil,
|
||||
})
|
||||
end
|
||||
table.insert(scene.meshes, mesh)
|
||||
table.insert(scene.nodes, { name = mesh.name, children = {}, mesh = #scene.meshes, extras = { bsp = { model = m - 1, origin = mdl.origin } } })
|
||||
table.insert(root.children, #scene.nodes)
|
||||
end
|
||||
end
|
||||
scene.meta.skippedFaces = skipped
|
||||
return scene, nil
|
||||
end
|
||||
|
||||
return Brush
|
||||
@@ -0,0 +1,261 @@
|
||||
--!strict
|
||||
-- model/bsp/Quake3: Quake III Arena maps (IBSP version 46; Return to Castle Wolfenstein 47 has the same layout) to a
|
||||
-- Scene: polygon and mesh faces (meshvert triangles, reversed to counter-clockwise), biquadratic patches
|
||||
-- tessellated (opts.patchLevel subdivisions per 3x3 control patch, default 4), one primitive per shader and lightmap
|
||||
-- per model (model 0 = the world, the others "*1", ...), POSITION / NORMAL / TEXCOORD_0 (surface) / TEXCOORD_1
|
||||
-- (lightmap) / COLOR_0 (vertex colours, unorm8); shaders as texture URIs; the 128 x 128 RGB lightmaps as
|
||||
-- texture.image (material.extras.bsp.lightmap = its texture index, texCoord 1). Billboards (flares) are skipped.
|
||||
-- Written from the Unofficial Quake 3 Map Specs (Kekoa Proudfoot); no code taken.
|
||||
local Types = require("@formats/Types")
|
||||
|
||||
local Quake3 = {}
|
||||
|
||||
local Scene = Types.Scene
|
||||
local readi32, readf32, readu8 = buffer.readi32, buffer.readf32, buffer.readu8
|
||||
local writef32, writeu32, writeu8 = buffer.writef32, buffer.writeu32, buffer.writeu8
|
||||
|
||||
export type Lump = { at: number, size: number }
|
||||
export type Options = { patchLevel: number?, maxVertices: number? }
|
||||
|
||||
type Batch = { shader: number, lightmap: number, verts: { number } } -- vertex records (indices into the vertex lump, or -1 - k for patch vertices)
|
||||
|
||||
local function cstr(b: buffer, at: number, n: number): string
|
||||
return (string.match(buffer.readstring(b, at, n), "^[^%z]*")) :: string
|
||||
end
|
||||
|
||||
-- decode(b, base, lumps, opts) -> Scene | nil, message
|
||||
function Quake3.decode(b: buffer, base: number, lumps: { [string]: Lump }, opts: Options?): (Types.Scene?, string?)
|
||||
local T, M, VX, MV, F, LM = lumps.textures, lumps.models, lumps.vertexes, lumps.meshverts, lumps.faces, lumps.lightmaps
|
||||
local nT, nM, nV, nMV, nF, nLM = T.size // 72, M.size // 40, VX.size // 44, MV.size // 4, F.size // 104, LM.size // 49152
|
||||
local level = math.clamp(math.floor(opts and opts.patchLevel or 4), 1, 16)
|
||||
local maxV = opts and opts.maxVertices or 2 ^ 24
|
||||
-- patch vertices: 12 floats + 4 colour bytes each, appended as negative ids
|
||||
local extra: { number } = {}
|
||||
local function vertex(i: number): { number }
|
||||
local o = base + VX.at + i * 44
|
||||
local v = table.create(14, 0)
|
||||
for k = 0, 9 do
|
||||
v[k + 1] = readf32(b, o + k * 4)
|
||||
end
|
||||
for k = 0, 3 do
|
||||
v[11 + k] = readu8(b, o + 40 + k)
|
||||
end
|
||||
return v
|
||||
end
|
||||
local function addExtra(v: { number }): number
|
||||
for k = 1, 14 do
|
||||
table.insert(extra, v[k])
|
||||
end
|
||||
return -(#extra // 14)
|
||||
end
|
||||
local faceModel: { number } = {}
|
||||
for m = 0, nM - 1 do
|
||||
local o = base + M.at + m * 40
|
||||
local first, count = readi32(b, o + 24), readi32(b, o + 28)
|
||||
if first >= 0 and count >= 0 and first + count <= nF then
|
||||
for f = first, first + count - 1 do
|
||||
faceModel[f + 1] = faceModel[f + 1] or (m + 1)
|
||||
end
|
||||
end
|
||||
end
|
||||
local batches: { [number]: { [string]: Batch } } = {}
|
||||
local orders: { [number]: { string } } = {}
|
||||
local counts = { polygons = 0, meshes = 0, patches = 0, billboards = 0, skipped = 0 }
|
||||
local total = 0
|
||||
for f = 0, nF - 1 do
|
||||
local o = base + F.at + f * 104
|
||||
local shader, kind, first, n, mv, nmv, lm = readi32(b, o), readi32(b, o + 8), readi32(b, o + 12), readi32(b, o + 16), readi32(b, o + 20), readi32(b, o + 24), readi32(b, o + 28)
|
||||
local model = faceModel[f + 1] or 1
|
||||
local tris: { number } = {}
|
||||
if (kind == 1 or kind == 3) and first >= 0 and n >= 0 and first + n <= nV and mv >= 0 and nmv >= 0 and mv + nmv <= nMV then
|
||||
for k = 0, nmv - 3, 3 do
|
||||
local ok = true
|
||||
local tri = {}
|
||||
for c = 0, 2 do
|
||||
local idx = readi32(b, base + MV.at + (mv + k + c) * 4)
|
||||
if idx < 0 or idx >= n then
|
||||
ok = false
|
||||
end
|
||||
tri[c + 1] = first + idx
|
||||
end
|
||||
if ok then
|
||||
table.insert(tris, tri[3])
|
||||
table.insert(tris, tri[2])
|
||||
table.insert(tris, tri[1])
|
||||
end
|
||||
end
|
||||
counts[if kind == 1 then "polygons" else "meshes"] += 1
|
||||
elseif kind == 2 and first >= 0 and n >= 0 and first + n <= nV then
|
||||
local w, h = readi32(b, o + 96), readi32(b, o + 100)
|
||||
if w >= 3 and h >= 3 and w % 2 == 1 and h % 2 == 1 and w * h == n then
|
||||
counts.patches += 1
|
||||
local L = level
|
||||
for py = 0, (h - 1) // 2 - 1 do
|
||||
for px = 0, (w - 1) // 2 - 1 do
|
||||
-- the 3x3 control points of this sub-patch
|
||||
local ctrl: { { number } } = {}
|
||||
for j = 0, 2 do
|
||||
for i = 0, 2 do
|
||||
ctrl[j * 3 + i + 1] = vertex(first + (py * 2 + j) * w + px * 2 + i)
|
||||
end
|
||||
end
|
||||
local grid: { number } = {}
|
||||
for gy = 0, L do
|
||||
local tv = gy / L
|
||||
for gx = 0, L do
|
||||
local tu = gx / L
|
||||
local bu = { (1 - tu) ^ 2, 2 * tu * (1 - tu), tu * tu }
|
||||
local bv = { (1 - tv) ^ 2, 2 * tv * (1 - tv), tv * tv }
|
||||
local v = table.create(14, 0)
|
||||
for j = 0, 2 do
|
||||
for i = 0, 2 do
|
||||
local wgt = bu[i + 1] * bv[j + 1]
|
||||
local cp = ctrl[j * 3 + i + 1]
|
||||
for k = 1, 14 do
|
||||
v[k] += cp[k] * wgt
|
||||
end
|
||||
end
|
||||
end
|
||||
local l = math.sqrt(v[8] ^ 2 + v[9] ^ 2 + v[10] ^ 2)
|
||||
if l > 0 then
|
||||
v[8], v[9], v[10] = v[8] / l, v[9] / l, v[10] / l
|
||||
end
|
||||
grid[gy * (L + 1) + gx + 1] = addExtra(v)
|
||||
end
|
||||
end
|
||||
for gy = 0, L - 1 do
|
||||
for gx = 0, L - 1 do
|
||||
local a, c2 = grid[gy * (L + 1) + gx + 1], grid[gy * (L + 1) + gx + 2]
|
||||
local d, e = grid[(gy + 1) * (L + 1) + gx + 1], grid[(gy + 1) * (L + 1) + gx + 2]
|
||||
-- counter-clockwise for Quake's clockwise-front control grids
|
||||
for _, v in { a, d, c2, c2, d, e } do
|
||||
table.insert(tris, v)
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
else
|
||||
counts.skipped += 1
|
||||
end
|
||||
elseif kind == 4 then
|
||||
counts.billboards += 1
|
||||
else
|
||||
counts.skipped += 1
|
||||
end
|
||||
total += #tris
|
||||
if total > maxV then
|
||||
return nil, "limit: too many vertices"
|
||||
end
|
||||
if #tris > 0 then
|
||||
local key = shader .. ":" .. lm
|
||||
local bm = batches[model] or {}
|
||||
batches[model] = bm
|
||||
local bt = bm[key]
|
||||
if not bt then
|
||||
bt = { shader = shader, lightmap = lm, verts = {} }
|
||||
bm[key] = bt
|
||||
local ol = orders[model] or {}
|
||||
orders[model] = ol
|
||||
table.insert(ol, key)
|
||||
end
|
||||
for _, v in tris do
|
||||
table.insert(bt.verts, v)
|
||||
end
|
||||
end
|
||||
end
|
||||
local scene = Scene.new()
|
||||
scene.meta.up = "z"
|
||||
-- shaders, lightmaps
|
||||
for i = 0, nT - 1 do
|
||||
local name = cstr(b, base + T.at + i * 72, 64)
|
||||
table.insert(scene.textures, { name = name, uri = name })
|
||||
end
|
||||
local lmTex: { [number]: number } = {}
|
||||
for i = 0, nLM - 1 do
|
||||
local img = Types.Image.new(128, 128)
|
||||
local o = base + LM.at + i * 49152
|
||||
for k = 0, 128 * 128 - 1 do
|
||||
writeu8(img.pixels, k * 4, readu8(b, o + k * 3))
|
||||
writeu8(img.pixels, k * 4 + 1, readu8(b, o + k * 3 + 1))
|
||||
writeu8(img.pixels, k * 4 + 2, readu8(b, o + k * 3 + 2))
|
||||
writeu8(img.pixels, k * 4 + 3, 255)
|
||||
end
|
||||
img.meta.source = { format = "bsp", lightmap = i }
|
||||
table.insert(scene.textures, { name = "lightmap " .. i, image = img })
|
||||
lmTex[i] = #scene.textures
|
||||
end
|
||||
local matOf: { [string]: number } = {}
|
||||
local root: Types.Node = { name = "bsp", children = {} }
|
||||
table.insert(scene.nodes, root)
|
||||
scene.roots[1] = 1
|
||||
local modelCount = math.max(nM, 1)
|
||||
for m = 1, modelCount do
|
||||
local list = orders[m]
|
||||
if list then
|
||||
local mesh: Types.Mesh = { name = if m == 1 then "world" else "*" .. (m - 1), primitives = {} }
|
||||
for _, key in list do
|
||||
local bt = batches[m][key]
|
||||
local nv = #bt.verts
|
||||
local pb, nb, ub, lb, cb, ib = buffer.create(nv * 12), buffer.create(nv * 12), buffer.create(nv * 8), buffer.create(nv * 8), buffer.create(nv * 4), buffer.create(nv * 4)
|
||||
for k, id in bt.verts do
|
||||
local v: { number }
|
||||
if id >= 0 then
|
||||
v = vertex(id)
|
||||
else
|
||||
local e = (-id - 1) * 14
|
||||
v = table.move(extra, e + 1, e + 14, 1, table.create(14, 0)) :: { number }
|
||||
end
|
||||
local o = (k - 1)
|
||||
writef32(pb, o * 12, v[1])
|
||||
writef32(pb, o * 12 + 4, v[2])
|
||||
writef32(pb, o * 12 + 8, v[3])
|
||||
writef32(ub, o * 8, v[4])
|
||||
writef32(ub, o * 8 + 4, v[5])
|
||||
writef32(lb, o * 8, v[6])
|
||||
writef32(lb, o * 8 + 4, v[7])
|
||||
writef32(nb, o * 12, v[8])
|
||||
writef32(nb, o * 12 + 4, v[9])
|
||||
writef32(nb, o * 12 + 8, v[10])
|
||||
for c = 0, 3 do
|
||||
writeu8(cb, o * 4 + c, math.clamp(math.floor(v[11 + c] + 0.5), 0, 255))
|
||||
end
|
||||
writeu32(ib, o * 4, o)
|
||||
end
|
||||
local mi = matOf[key]
|
||||
if not mi then
|
||||
local name = if bt.shader >= 0 and bt.shader < nT then scene.textures[bt.shader + 1].name else "noshader"
|
||||
local mat = Scene.material(name)
|
||||
mat.metallic = 0
|
||||
if bt.shader >= 0 and bt.shader < nT then
|
||||
mat.baseColorTexture = { texture = bt.shader + 1 }
|
||||
end
|
||||
local lt = lmTex[bt.lightmap]
|
||||
mat.extras = { bsp = { lightmap = lt, lightmapTexCoord = if lt then 1 else nil } }
|
||||
table.insert(scene.materials, mat)
|
||||
mi = #scene.materials
|
||||
matOf[key] = mi
|
||||
end
|
||||
table.insert(mesh.primitives, {
|
||||
attributes = {
|
||||
POSITION = Scene.accessor(pb, "f32", 3, nv),
|
||||
NORMAL = Scene.accessor(nb, "f32", 3, nv),
|
||||
TEXCOORD_0 = Scene.accessor(ub, "f32", 2, nv),
|
||||
TEXCOORD_1 = Scene.accessor(lb, "f32", 2, nv),
|
||||
COLOR_0 = Scene.accessor(cb, "unorm8", 4, nv),
|
||||
},
|
||||
indices = Scene.accessor(ib, "u32", 1, nv),
|
||||
mode = "triangles" :: any,
|
||||
material = mi,
|
||||
})
|
||||
end
|
||||
table.insert(scene.meshes, mesh)
|
||||
table.insert(scene.nodes, { name = mesh.name, children = {}, mesh = #scene.meshes, extras = { bsp = { model = m - 1 } } })
|
||||
table.insert(root.children, #scene.nodes)
|
||||
end
|
||||
end
|
||||
scene.meta.faces = counts
|
||||
return scene, nil
|
||||
end
|
||||
|
||||
return Quake3
|
||||
@@ -0,0 +1,150 @@
|
||||
--!strict
|
||||
-- model/bsp: compiled game maps read into a Scene: Quake 1 (BSP 29) and Half-Life (BSP 30), Quake II (IBSP 38)
|
||||
-- through model/bsp/Brush, Quake III Arena / RTCW (IBSP 46 / 47) through model/bsp/Quake3. Each model of the map is a
|
||||
-- mesh (model 0 "world", brush entities "*1", "*2", ... as nodes), one primitive per texture (and Quake III
|
||||
-- lightmap). The entities lump is parsed into meta.entities = { { classname = ..., origin = ..., ... } } (strings as
|
||||
-- stored) with the text in meta.source.entities. Quake textures need the game's palette (gfx/palette.lmp, not
|
||||
-- redistributable: never built in): opts.palette, else opts.resolve / opts.files["gfx/palette.lmp"], else grey.
|
||||
-- Quake II .wal sizes come from opts.resolve("textures/<name>.wal") / opts.files. Units are map units, z up.
|
||||
-- Not supported: Source engine VBSP, Quake 1/2 lightmaps, visibility and collision data, writing.
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ requires
|
||||
local Err = require("@formats/core/Err")
|
||||
local Bytes = require("@formats/core/Bytes")
|
||||
local Input = require("@formats/core/Input")
|
||||
local Types = require("@formats/Types")
|
||||
local Brush = require("@formats/model/bsp/Brush")
|
||||
local Quake3 = require("@formats/model/bsp/Quake3")
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ contract
|
||||
local Bsp = {
|
||||
name = "bsp",
|
||||
category = "model",
|
||||
extensions = { "bsp" },
|
||||
mime = { "model/x-bsp" },
|
||||
deps = { "core/Err", "core/Bytes", "core/Input", "Types", "codecs/image/Pixels" },
|
||||
caps = { decode = true, encode = false, variants = { "quake", "halflife", "quake2", "quake3" }, lightmaps = "quake3" },
|
||||
}
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ types
|
||||
export type DecodeOptions = {
|
||||
palette: (buffer | string)?, -- Quake 1: the 768-byte palette
|
||||
resolve: ((uri: string) -> (buffer | string)?)?,
|
||||
files: { [string]: buffer | string }?,
|
||||
patchLevel: number?, -- Quake III patch subdivisions (default 4)
|
||||
maxPixels: number?, -- default 2^24
|
||||
maxVertices: number?, -- default 2^24
|
||||
}
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ constants
|
||||
local Q1_LUMPS = { "entities", "planes", "miptex", "vertices", "visibility", "nodes", "texinfo", "faces", "lighting",
|
||||
"clipnodes", "leaves", "marksurfaces", "edges", "surfedges", "models" }
|
||||
local Q2_LUMPS = { "entities", "planes", "vertices", "visibility", "nodes", "texinfo", "faces", "lighting", "leaves",
|
||||
"leaffaces", "leafbrushes", "edges", "surfedges", "models", "brushes", "brushsides", "pop", "areas", "areaportals" }
|
||||
local Q3_LUMPS = { "entities", "textures", "planes", "nodes", "leafs", "leaffaces", "leafbrushes", "models", "brushes",
|
||||
"brushsides", "vertexes", "meshverts", "effects", "faces", "lightmaps", "lightvols", "visdata" }
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ sniff
|
||||
function Bsp.sniff(r: Bytes.Reader): number
|
||||
if r:remaining() < 64 then
|
||||
return 0
|
||||
end
|
||||
local m = r:peek(4)
|
||||
local v = buffer.readi32(r.buf, r.pos + (if m == "IBSP" then 4 else 0))
|
||||
if m == "IBSP" then
|
||||
return if v == 38 or v == 46 or v == 47 then 1 else 0.3
|
||||
end
|
||||
if v == 29 or v == 30 then
|
||||
-- no magic: check that the lump directory fits the file
|
||||
local size = r:remaining()
|
||||
for i = 0, 14 do
|
||||
local o, n = buffer.readi32(r.buf, r.pos + 4 + i * 8), buffer.readi32(r.buf, r.pos + 8 + i * 8)
|
||||
if o < 0 or n < 0 or o + n > size then
|
||||
return 0
|
||||
end
|
||||
end
|
||||
return 0.6
|
||||
end
|
||||
return 0
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ decode
|
||||
-- the entities text -> { { key = value } }
|
||||
local function entities(text: string): { { [string]: string } }
|
||||
local out: { { [string]: string } } = {}
|
||||
for block in string.gmatch(text, "%b{}") do
|
||||
local e: { [string]: string } = {}
|
||||
for k, v in string.gmatch(block, '"([^"]*)"%s*"([^"]*)"') do
|
||||
e[k] = v
|
||||
end
|
||||
table.insert(out, e)
|
||||
end
|
||||
return out
|
||||
end
|
||||
|
||||
function Bsp.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Scene?, Err.Err?)
|
||||
local size = r.limit - r.base
|
||||
if size < 8 then
|
||||
return nil, Err.new(Err.TRUNCATED, "header", 0)
|
||||
end
|
||||
local b, base = r.buf, r.base
|
||||
local m = r:peek(4)
|
||||
local version = buffer.readi32(b, base + (if m == "IBSP" then 4 else 0))
|
||||
local names: { string }, dir: number, variant: string
|
||||
if m == "IBSP" and version == 38 then
|
||||
names, dir, variant = Q2_LUMPS, 8, "q2"
|
||||
elseif m == "IBSP" and (version == 46 or version == 47) then
|
||||
names, dir, variant = Q3_LUMPS, 8, "q3"
|
||||
elseif m ~= "IBSP" and (version == 29 or version == 30) then
|
||||
names, dir, variant = Q1_LUMPS, 4, if version == 30 then "hl" else "q1"
|
||||
elseif m == "VBSP" then
|
||||
return nil, Err.new(Err.UNSUPPORTED, "Source engine VBSP maps", 0)
|
||||
else
|
||||
return nil, Err.new(Err.UNSUPPORTED, "BSP version " .. version, 0)
|
||||
end
|
||||
if dir + #names * 8 > size then
|
||||
return nil, Err.new(Err.TRUNCATED, "lump directory", dir)
|
||||
end
|
||||
local lumps: { [string]: { at: number, size: number } } = {}
|
||||
for i, name in names do
|
||||
local o, n = buffer.readi32(b, base + dir + (i - 1) * 8), buffer.readi32(b, base + dir + (i - 1) * 8 + 4)
|
||||
if o < 0 or n < 0 or o + n > size then
|
||||
return nil, Err.new(Err.TRUNCATED, "lump " .. name .. " past the end", dir + (i - 1) * 8)
|
||||
end
|
||||
lumps[name] = { at = o, size = n }
|
||||
end
|
||||
local scene: Types.Scene?, msg: string?
|
||||
if variant == "q3" then
|
||||
scene, msg = Quake3.decode(b, base, lumps, opts :: any)
|
||||
else
|
||||
local pal = if opts and opts.palette then Bytes.toBuffer(opts.palette) else Input.sibling(opts, "gfx/palette.lmp")
|
||||
if pal and buffer.len(pal) < 768 then
|
||||
pal = nil
|
||||
end
|
||||
scene, msg = Brush.decode(b, base, lumps, variant, {
|
||||
palette = pal,
|
||||
wal = function(name: string): buffer?
|
||||
return Input.sibling(opts, "textures/" .. name .. ".wal")
|
||||
end,
|
||||
maxPixels = opts and opts.maxPixels,
|
||||
maxVertices = opts and opts.maxVertices,
|
||||
})
|
||||
end
|
||||
if not scene then
|
||||
return nil, Err.from(msg)
|
||||
end
|
||||
local e = lumps.entities
|
||||
local text = buffer.readstring(b, base + e.at, e.size)
|
||||
text = string.match(text, "^[^%z]*") :: string
|
||||
scene.meta.entities = entities(text)
|
||||
scene.meta.source = {
|
||||
format = "bsp",
|
||||
variant = ({ q1 = "quake", hl = "halflife", q2 = "quake2", q3 = "quake3" } :: { [string]: string })[variant],
|
||||
version = version,
|
||||
entities = text,
|
||||
palette = if variant == "q1" then (opts ~= nil and (opts.palette ~= nil or Input.sibling(opts, "gfx/palette.lmp") ~= nil)) else nil,
|
||||
}
|
||||
return scene, nil
|
||||
end
|
||||
|
||||
return Bsp
|
||||
@@ -0,0 +1,209 @@
|
||||
--!strict
|
||||
-- model/md2: Quake II MD2 models ("IDP2" version 8), read into a Scene. Written from the MD2 format description in the
|
||||
-- Quake II source release (qfiles.h: dmdl_t) and the "MD2 file format" notes (David Henry); no code taken.
|
||||
-- Decode: one primitive: the triangles (welded on (vertex, texture coordinate) pairs; MD2 front faces are clockwise,
|
||||
-- the indices are reversed to counter-clockwise as glTF wants), POSITION of frame opts.frame (default 1),
|
||||
-- TEXCOORD_0 = s / skinwidth, t / skinheight (top-left origin), NORMAL computed from the geometry (the stored
|
||||
-- indexes into Quake's normal table are kept as meta.source.normalIndexes = false: that table is not
|
||||
-- redistributable here); every frame as a morph target (codecs/model/Rig: weight k = 1 shows frame k) and one
|
||||
-- animation per frame-name group ("run1".."run6" -> "run", 10 frames per second, LINEAR); the skins as texture
|
||||
-- URIs (the first is the material's base colour texture; mesh.extras.skins lists all). Units are Quake units, z up.
|
||||
-- meta.source = { format, frames, frameNames, skinWidth, skinHeight }.
|
||||
-- Not supported: the GL command list (the triangles carry the same geometry), writing.
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ requires
|
||||
local Err = require("@formats/core/Err")
|
||||
local Bytes = require("@formats/core/Bytes")
|
||||
local Sniff = require("@formats/core/Sniff")
|
||||
local Types = require("@formats/Types")
|
||||
local Rig = require("@formats/codecs/model/Rig")
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ contract
|
||||
local Md2 = {
|
||||
name = "md2",
|
||||
category = "model",
|
||||
extensions = { "md2" },
|
||||
mime = { "model/x-md2" },
|
||||
deps = { "core/Err", "core/Bytes", "core/Sniff", "Types", "codecs/model/Rig" },
|
||||
caps = { decode = true, encode = false, morph = true, animation = true },
|
||||
}
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ types
|
||||
export type DecodeOptions = {
|
||||
frame: number?, -- the frame used as the base POSITION (1-based, default 1)
|
||||
morph: boolean?, -- every frame as a morph target + the animations (default true)
|
||||
fps: number?, -- animation frame rate (default 10)
|
||||
maxVertices: number?, -- frames x vertices (default 2^24)
|
||||
}
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ constants
|
||||
local Scene = Types.Scene
|
||||
local readu8, readu16, readi16, readf32, writef32, writeu32 = buffer.readu8, buffer.readu16, buffer.readi16, buffer.readf32, buffer.writef32, buffer.writeu32
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ sniff
|
||||
function Md2.sniff(r: Bytes.Reader): number
|
||||
if r:remaining() < 68 then
|
||||
return 0
|
||||
end
|
||||
return if Sniff.magic(r, "IDP2") == 1 and r:peekU8(4) == 8 then 1 else 0
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ decode
|
||||
-- group frame names by their name without trailing digits, in file order
|
||||
local function groups(names: { string }, fps: number): { Rig.Range }
|
||||
local out: { Rig.Range } = {}
|
||||
for i, n in names do
|
||||
local stem = string.match(n, "^(.-)_?%d*$") or n
|
||||
if stem == "" then
|
||||
stem = n
|
||||
end
|
||||
local last = out[#out]
|
||||
if last and last.name == stem and last.last == i - 1 then
|
||||
last.last = i
|
||||
else
|
||||
table.insert(out, { name = stem, first = i, last = i, fps = fps })
|
||||
end
|
||||
end
|
||||
return out
|
||||
end
|
||||
|
||||
function Md2.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Scene?, Err.Err?)
|
||||
local size = r.limit - r.base
|
||||
if not r:match("IDP2") then
|
||||
return nil, Err.new(if size < 4 then Err.TRUNCATED else Err.CORRUPT, "bad magic", 0)
|
||||
end
|
||||
local h: { number } = {}
|
||||
for i = 1, 16 do
|
||||
h[i] = r:i32le()
|
||||
end
|
||||
if r.err then
|
||||
return nil, r.err
|
||||
end
|
||||
local version, sw, sh, frameSize, nSkins, nXyz, nSt, nTris, _, nFrames, oSkins, oSt, oTris, oFrames = table.unpack(h, 1, 14)
|
||||
if version ~= 8 then
|
||||
return nil, Err.new(Err.UNSUPPORTED, "MD2 version " .. version, 4)
|
||||
end
|
||||
if nSkins < 0 or nXyz <= 0 or nSt < 0 or nTris < 0 or nFrames <= 0 or sw < 0 or sh < 0 then
|
||||
return nil, Err.new(Err.CORRUPT, "bad counts", 8)
|
||||
end
|
||||
if nFrames * nXyz > (opts and opts.maxVertices or 2 ^ 24) then
|
||||
return nil, Err.new(Err.LIMIT, "too many vertices")
|
||||
end
|
||||
local function inside(o: number, n: number): boolean
|
||||
return o >= 0 and n >= 0 and o + n <= size
|
||||
end
|
||||
if not (inside(oSkins, nSkins * 64) and inside(oSt, nSt * 4) and inside(oTris, nTris * 12) and inside(oFrames, nFrames * frameSize)) then
|
||||
return nil, Err.new(Err.TRUNCATED, "a section runs past the end", 44)
|
||||
end
|
||||
if frameSize < 40 + nXyz * 4 then
|
||||
return nil, Err.new(Err.CORRUPT, "frame size too small", 16)
|
||||
end
|
||||
local b, base = r.buf, r.base
|
||||
-- skins
|
||||
local skins: { string } = {}
|
||||
for i = 0, nSkins - 1 do
|
||||
local s = buffer.readstring(b, base + oSkins + i * 64, 64)
|
||||
table.insert(skins, (string.match(s, "^[^%z]*")) :: string)
|
||||
end
|
||||
-- weld (xyz, st) pairs
|
||||
local key: { [number]: number } = {}
|
||||
local vx: { number }, vst: { number } = {}, {}
|
||||
local indices: { number } = {}
|
||||
for t = 0, nTris - 1 do
|
||||
local o = base + oTris + t * 12
|
||||
local corner: { number } = {}
|
||||
for c = 0, 2 do
|
||||
local xi, si = readu16(b, o + c * 2), readu16(b, o + 6 + c * 2)
|
||||
if xi >= nXyz or (nSt > 0 and si >= nSt) then
|
||||
return nil, Err.new(Err.CORRUPT, "triangle " .. t .. " index out of range", oTris + t * 12)
|
||||
end
|
||||
local k = xi * 65536 + si
|
||||
local v = key[k]
|
||||
if not v then
|
||||
table.insert(vx, xi)
|
||||
table.insert(vst, si)
|
||||
v = #vx - 1
|
||||
key[k] = v
|
||||
end
|
||||
corner[c + 1] = v
|
||||
end
|
||||
table.insert(indices, corner[3])
|
||||
table.insert(indices, corner[2])
|
||||
table.insert(indices, corner[1])
|
||||
end
|
||||
local nv = #vx
|
||||
local uv = buffer.create(nv * 8)
|
||||
for i = 1, nv do
|
||||
if nSt > 0 then
|
||||
local o = base + oSt + vst[i] * 4
|
||||
writef32(uv, (i - 1) * 8, readi16(b, o) / math.max(sw, 1))
|
||||
writef32(uv, (i - 1) * 8 + 4, readi16(b, o + 2) / math.max(sh, 1))
|
||||
end
|
||||
end
|
||||
-- frames
|
||||
local frames: { buffer } = {}
|
||||
local normals: { buffer } = {}
|
||||
local names: { string } = {}
|
||||
local morph = not (opts and opts.morph == false)
|
||||
local want = math.clamp(math.floor(opts and opts.frame or 1), 1, nFrames)
|
||||
for f = 1, nFrames do
|
||||
if morph or f == want then
|
||||
local o = base + oFrames + (f - 1) * frameSize
|
||||
local sx, sy, sz = readf32(b, o), readf32(b, o + 4), readf32(b, o + 8)
|
||||
local tx, ty, tz = readf32(b, o + 12), readf32(b, o + 16), readf32(b, o + 20)
|
||||
local pos = buffer.create(nv * 12)
|
||||
for i = 1, nv do
|
||||
local p = o + 40 + vx[i] * 4
|
||||
writef32(pos, (i - 1) * 12, readu8(b, p) * sx + tx)
|
||||
writef32(pos, (i - 1) * 12 + 4, readu8(b, p + 1) * sy + ty)
|
||||
writef32(pos, (i - 1) * 12 + 8, readu8(b, p + 2) * sz + tz)
|
||||
end
|
||||
frames[f] = pos
|
||||
normals[f] = Rig.normals(pos, nv, indices)
|
||||
end
|
||||
local nm = buffer.readstring(b, base + oFrames + (f - 1) * frameSize + 24, 16)
|
||||
names[f] = (string.match(nm, "^[^%z]*")) :: string
|
||||
end
|
||||
local ib = buffer.create(#indices * 4)
|
||||
for i, v in indices do
|
||||
writeu32(ib, (i - 1) * 4, v)
|
||||
end
|
||||
local prim: Types.Primitive = {
|
||||
attributes = {
|
||||
POSITION = Scene.accessor(frames[want], "f32", 3, nv),
|
||||
NORMAL = Scene.accessor(normals[want], "f32", 3, nv),
|
||||
TEXCOORD_0 = Scene.accessor(uv, "f32", 2, nv),
|
||||
},
|
||||
indices = Scene.accessor(ib, "u32", 1, #indices),
|
||||
mode = "triangles",
|
||||
}
|
||||
local scene = Scene.new()
|
||||
scene.meta.up = "z"
|
||||
if #skins > 0 then
|
||||
for _, s in skins do
|
||||
table.insert(scene.textures, { name = s, uri = s })
|
||||
end
|
||||
local mat = Scene.material(skins[1])
|
||||
mat.metallic = 0
|
||||
mat.baseColorTexture = { texture = 1 }
|
||||
table.insert(scene.materials, mat)
|
||||
prim.material = 1
|
||||
end
|
||||
scene.meshes[1] = { primitives = { prim }, extras = { skins = skins } }
|
||||
scene.nodes[1] = { children = {}, mesh = 1 }
|
||||
scene.roots[1] = 1
|
||||
if morph then
|
||||
local fr: { buffer } = {}
|
||||
for f = 1, nFrames do
|
||||
fr[f] = frames[f]
|
||||
end
|
||||
Rig.morph(prim, fr, normals)
|
||||
local w = table.create(nFrames, 0)
|
||||
scene.meshes[1].weights = w
|
||||
Rig.morphAnimation(scene, 1, nFrames, groups(names, opts and opts.fps or 10), "LINEAR")
|
||||
end
|
||||
scene.meta.source = { format = "md2", frames = nFrames, frameNames = names, skinWidth = sw, skinHeight = sh, normalIndexes = false }
|
||||
return scene, nil
|
||||
end
|
||||
|
||||
return Md2
|
||||
@@ -0,0 +1,234 @@
|
||||
--!strict
|
||||
-- model/md3: Quake III Arena MD3 models ("IDP3" version 15), read into a Scene. Written from the MD3 format
|
||||
-- description in the Quake III source release (qfiles.h: md3Header_t, md3Surface_t) and the "MD3 file format"
|
||||
-- notes (PhaethonH); no code taken.
|
||||
-- Decode: one mesh, one primitive per surface (indices reversed to counter-clockwise; POSITION of frame opts.frame
|
||||
-- (default 1) in units of 1/64; NORMAL from the stored latitude / longitude bytes; TEXCOORD_0 as stored, top-left
|
||||
-- origin); every frame as a morph target of each primitive (codecs/model/Rig) and one animation "frames" over all
|
||||
-- of them (opts.fps, default 15); the first shader of each surface as its material's texture URI; tags as child nodes
|
||||
-- (origin + axis of frame 1; their per-frame motion as translation / rotation channels of the same animation).
|
||||
-- Units are Quake units, z up. meta.source = { format, name, frames, frameNames, tags }.
|
||||
-- Not supported: writing.
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ requires
|
||||
local Err = require("@formats/core/Err")
|
||||
local Bytes = require("@formats/core/Bytes")
|
||||
local Sniff = require("@formats/core/Sniff")
|
||||
local Types = require("@formats/Types")
|
||||
local Mat4 = require("@formats/codecs/model/Mat4")
|
||||
local Rig = require("@formats/codecs/model/Rig")
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ contract
|
||||
local Md3 = {
|
||||
name = "md3",
|
||||
category = "model",
|
||||
extensions = { "md3" },
|
||||
mime = { "model/x-md3" },
|
||||
deps = { "core/Err", "core/Bytes", "core/Sniff", "Types", "codecs/model/Mat4", "codecs/model/Rig" },
|
||||
caps = { decode = true, encode = false, morph = true, animation = true, tags = true },
|
||||
}
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ types
|
||||
export type DecodeOptions = {
|
||||
frame: number?, -- the frame used as the base POSITION / NORMAL (1-based, default 1)
|
||||
morph: boolean?, -- every frame as a morph target + the animation (default true)
|
||||
fps: number?, -- animation frame rate (default 15)
|
||||
maxVertices: number?, -- frames x vertices over all surfaces (default 2^24)
|
||||
}
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ constants
|
||||
local Scene = Types.Scene
|
||||
local readi16, readu8, readi32, readf32, writef32, writeu32 = buffer.readi16, buffer.readu8, buffer.readi32, buffer.readf32, buffer.writef32, buffer.writeu32
|
||||
local K = math.pi / 128 -- the engine maps a byte to 2 pi / 256 (tr_surface.c LatLongToNormal)
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ sniff
|
||||
function Md3.sniff(r: Bytes.Reader): number
|
||||
if r:remaining() < 108 then
|
||||
return 0
|
||||
end
|
||||
return if Sniff.magic(r, "IDP3") == 1 and r:peekU8(4) == 15 then 1 else 0
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ decode
|
||||
local function cstr(b: buffer, at: number, n: number): string
|
||||
return (string.match(buffer.readstring(b, at, n), "^[^%z]*")) :: string
|
||||
end
|
||||
|
||||
function Md3.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Scene?, Err.Err?)
|
||||
local size = r.limit - r.base
|
||||
if size < 108 then
|
||||
return nil, Err.new(Err.TRUNCATED, "header", 0)
|
||||
end
|
||||
if not r:match("IDP3") then
|
||||
return nil, Err.new(Err.CORRUPT, "bad magic", 0)
|
||||
end
|
||||
local version = r:i32le()
|
||||
if version ~= 15 then
|
||||
return nil, Err.new(Err.UNSUPPORTED, "MD3 version " .. version, 4)
|
||||
end
|
||||
local b, base = r.buf, r.base
|
||||
local name = cstr(b, base + 8, 64)
|
||||
r:skip(68)
|
||||
local nFrames, nTags, nSurf, _nSkins = r:i32le(), r:i32le(), r:i32le(), r:i32le()
|
||||
local oFrames, oTags, oSurf = r:i32le(), r:i32le(), r:i32le()
|
||||
if r.err then
|
||||
return nil, r.err
|
||||
end
|
||||
if nFrames <= 0 or nTags < 0 or nSurf < 0 or nFrames > 65536 or nTags > 4096 or nSurf > 4096 then
|
||||
return nil, Err.new(Err.CORRUPT, "bad counts", 76)
|
||||
end
|
||||
local function inside(o: number, n: number): boolean
|
||||
return o >= 0 and n >= 0 and o + n <= size
|
||||
end
|
||||
if not inside(oFrames, nFrames * 56) or not inside(oTags, nFrames * nTags * 112) then
|
||||
return nil, Err.new(Err.TRUNCATED, "frames / tags past the end", 88)
|
||||
end
|
||||
local morph = not (opts and opts.morph == false)
|
||||
local want = math.clamp(math.floor(opts and opts.frame or 1), 1, nFrames)
|
||||
local maxV = opts and opts.maxVertices or 2 ^ 24
|
||||
local scene = Scene.new()
|
||||
scene.meta.up = "z"
|
||||
local mesh: Types.Mesh = { name = if name ~= "" then name else nil, primitives = {} }
|
||||
scene.meshes[1] = mesh
|
||||
scene.nodes[1] = { name = mesh.name, children = {}, mesh = 1 }
|
||||
scene.roots[1] = 1
|
||||
local total = 0
|
||||
local so = oSurf
|
||||
for s = 1, nSurf do
|
||||
if not inside(so, 108) or cstr(b, base + so, 4) ~= "IDP3" then
|
||||
return nil, Err.new(Err.CORRUPT, "surface " .. s .. ": bad header", so)
|
||||
end
|
||||
local p = base + so
|
||||
local sname = cstr(b, p + 4, 64)
|
||||
local sFrames, nShaders, nVerts, nTris = readi32(b, p + 72), readi32(b, p + 76), readi32(b, p + 80), readi32(b, p + 84)
|
||||
local oTri, oSh, oSt, oXyz, oEnd = readi32(b, p + 88), readi32(b, p + 92), readi32(b, p + 96), readi32(b, p + 100), readi32(b, p + 104)
|
||||
if sFrames ~= nFrames or nShaders < 0 or nVerts < 0 or nTris < 0 or oEnd <= 0 then
|
||||
return nil, Err.new(Err.CORRUPT, "surface " .. s .. ": bad counts", so + 72)
|
||||
end
|
||||
total += nVerts * nFrames
|
||||
if total > maxV then
|
||||
return nil, Err.new(Err.LIMIT, "too many vertices")
|
||||
end
|
||||
if not (inside(so + oTri, nTris * 12) and inside(so + oSh, nShaders * 68) and inside(so + oSt, nVerts * 8) and inside(so + oXyz, nVerts * nFrames * 8)) then
|
||||
return nil, Err.new(Err.TRUNCATED, "surface " .. s .. " past the end", so)
|
||||
end
|
||||
local ib = buffer.create(nTris * 12)
|
||||
local idx = table.create(nTris * 3, 0) :: { number }
|
||||
for t = 0, nTris - 1 do
|
||||
for c = 0, 2 do
|
||||
local v = readi32(b, p + oTri + t * 12 + c * 4)
|
||||
if v < 0 or v >= nVerts then
|
||||
return nil, Err.new(Err.CORRUPT, "surface " .. s .. ": triangle index out of range", so + oTri + t * 12)
|
||||
end
|
||||
idx[t * 3 + 3 - c] = v
|
||||
end
|
||||
end
|
||||
for i, v in idx do
|
||||
writeu32(ib, (i - 1) * 4, v)
|
||||
end
|
||||
local uv = buffer.create(nVerts * 8)
|
||||
buffer.copy(uv, 0, b, p + oSt, nVerts * 8)
|
||||
local frames: { buffer }, normals: { buffer } = {}, {}
|
||||
for f = 1, nFrames do
|
||||
if morph or f == want then
|
||||
local pos, nrm = buffer.create(nVerts * 12), buffer.create(nVerts * 12)
|
||||
local q = p + oXyz + (f - 1) * nVerts * 8
|
||||
for v = 0, nVerts - 1 do
|
||||
local o = q + v * 8
|
||||
writef32(pos, v * 12, readi16(b, o) / 64)
|
||||
writef32(pos, v * 12 + 4, readi16(b, o + 2) / 64)
|
||||
writef32(pos, v * 12 + 8, readi16(b, o + 4) / 64)
|
||||
local lng, lat = readu8(b, o + 6) * K, readu8(b, o + 7) * K
|
||||
writef32(nrm, v * 12, math.cos(lat) * math.sin(lng))
|
||||
writef32(nrm, v * 12 + 4, math.sin(lat) * math.sin(lng))
|
||||
writef32(nrm, v * 12 + 8, math.cos(lng))
|
||||
end
|
||||
frames[f], normals[f] = pos, nrm
|
||||
end
|
||||
end
|
||||
local prim: Types.Primitive = {
|
||||
attributes = {
|
||||
POSITION = Scene.accessor(frames[want], "f32", 3, nVerts),
|
||||
NORMAL = Scene.accessor(normals[want], "f32", 3, nVerts),
|
||||
TEXCOORD_0 = Scene.accessor(uv, "f32", 2, nVerts),
|
||||
},
|
||||
indices = Scene.accessor(ib, "u32", 1, nTris * 3),
|
||||
mode = "triangles",
|
||||
extras = { md3 = { surface = sname } },
|
||||
}
|
||||
if morph then
|
||||
Rig.morph(prim, frames, normals)
|
||||
end
|
||||
local shaders: { string } = {}
|
||||
for k = 0, nShaders - 1 do
|
||||
table.insert(shaders, cstr(b, p + oSh + k * 68, 64))
|
||||
end
|
||||
local mat = Scene.material(sname)
|
||||
mat.metallic = 0
|
||||
if shaders[1] and shaders[1] ~= "" then
|
||||
table.insert(scene.textures, { name = shaders[1], uri = shaders[1] })
|
||||
mat.baseColorTexture = { texture = #scene.textures }
|
||||
end
|
||||
mat.extras = { md3 = { shaders = shaders } }
|
||||
table.insert(scene.materials, mat)
|
||||
prim.material = #scene.materials
|
||||
table.insert(mesh.primitives, prim)
|
||||
so += oEnd
|
||||
end
|
||||
-- frames and tags
|
||||
local frameNames: { string } = {}
|
||||
for f = 0, nFrames - 1 do
|
||||
frameNames[f + 1] = cstr(b, base + oFrames + f * 56 + 40, 16)
|
||||
end
|
||||
local tagNodes: { number } = {}
|
||||
local tracks: { [number]: Rig.Track } = {}
|
||||
local tagNames: { string } = {}
|
||||
for k = 0, nTags - 1 do
|
||||
local tr: Rig.Track = { translation = {}, rotation = {} }
|
||||
local first: any = nil
|
||||
for f = 0, nFrames - 1 do
|
||||
local o = base + oTags + (f * nTags + k) * 112
|
||||
local t = { readf32(b, o + 64), readf32(b, o + 68), readf32(b, o + 72) }
|
||||
local a: { number } = {}
|
||||
for i = 0, 8 do
|
||||
a[i + 1] = readf32(b, o + 76 + i * 4)
|
||||
end
|
||||
local m = { a[1], a[2], a[3], 0, a[4], a[5], a[6], 0, a[7], a[8], a[9], 0, t[1], t[2], t[3], 1 }
|
||||
local q = Mat4.quat(m)
|
||||
for c = 1, 3 do
|
||||
table.insert(tr.translation :: { number }, t[c])
|
||||
end
|
||||
for c = 1, 4 do
|
||||
table.insert(tr.rotation :: { number }, q[c])
|
||||
end
|
||||
if f == want - 1 then
|
||||
first = { name = cstr(b, o, 64), t = t, q = q }
|
||||
end
|
||||
end
|
||||
table.insert(tagNames, first.name)
|
||||
table.insert(scene.nodes, { name = first.name, children = {}, translation = first.t, rotation = first.q, extras = { md3 = { tag = true } } })
|
||||
table.insert(scene.nodes[1].children, #scene.nodes)
|
||||
tagNodes[k + 1] = #scene.nodes
|
||||
tracks[k + 1] = tr
|
||||
end
|
||||
if morph and nFrames > 1 then
|
||||
scene.meshes[1].weights = table.create(nFrames, 0)
|
||||
local fps = opts and opts.fps or 15
|
||||
Rig.morphAnimation(scene, 1, nFrames, { { name = "frames", first = 1, last = nFrames, fps = fps } }, "LINEAR")
|
||||
if nTags > 0 then
|
||||
local times: { number } = {}
|
||||
for f = 1, nFrames do
|
||||
times[f] = (f - 1) / fps
|
||||
end
|
||||
local ai = Rig.animation(scene, "tags", tagNodes, times, tracks)
|
||||
local tagAnim = table.remove(scene.animations, ai) :: Types.Animation
|
||||
for _, ch in tagAnim.channels do
|
||||
table.insert(scene.animations[1].channels, ch)
|
||||
end
|
||||
end
|
||||
end
|
||||
scene.meta.source = { format = "md3", name = name, frames = nFrames, frameNames = frameNames, tags = tagNames }
|
||||
return scene, nil
|
||||
end
|
||||
|
||||
return Md3
|
||||
@@ -0,0 +1,440 @@
|
||||
--!strict
|
||||
-- model/md5/Read: Doom 3 / Quake 4 MD5 text (MD5Version 10) to Scenes. md5mesh: joints (model-space bind pose:
|
||||
-- position + unit quaternion with w = -sqrt(1 - x² - y² - z²)) -> joint nodes and a Skin, each mesh -> a primitive
|
||||
-- (positions from the weights in the bind pose, normals computed, texture coordinates as stored, triangles reversed
|
||||
-- to counter-clockwise, JOINTS_0 / WEIGHTS_0 from the weights), its shader -> a material / texture URI. md5anim:
|
||||
-- hierarchy + baseframe (parent-relative) + frames of animated components -> translation / rotation channels at
|
||||
-- frameRate, applied to the joint nodes of the same names. Written from the format notes of the Doom 3 modding
|
||||
-- community (modwiki "MD5 (file format)", David Henry's "The MD5 Mesh and Animation Formats"); no code taken.
|
||||
local Types = require("@formats/Types")
|
||||
local Rig = require("@formats/codecs/model/Rig")
|
||||
|
||||
local Read = {}
|
||||
|
||||
local Scene = Types.Scene
|
||||
local writef32, writeu32 = buffer.writef32, buffer.writeu32
|
||||
|
||||
export type Options = { maxVertices: number? }
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ tokens
|
||||
type Lexer = { text: string, pos: number, err: string? }
|
||||
|
||||
local function token(L: Lexer): string?
|
||||
local s = L.text
|
||||
while true do
|
||||
local a = string.find(s, "%S", L.pos)
|
||||
if not a then
|
||||
L.pos = #s + 1
|
||||
return nil
|
||||
end
|
||||
if string.sub(s, a, a + 1) == "//" then
|
||||
local nl = string.find(s, "\n", a, true)
|
||||
L.pos = if nl then nl + 1 else #s + 1
|
||||
else
|
||||
L.pos = a
|
||||
break
|
||||
end
|
||||
end
|
||||
local c = string.sub(s, L.pos, L.pos)
|
||||
if c == '"' then
|
||||
local e = string.find(s, '"', L.pos + 1, true)
|
||||
if not e then
|
||||
L.err = "unterminated string"
|
||||
L.pos = #s + 1
|
||||
return nil
|
||||
end
|
||||
local v = string.sub(s, L.pos + 1, e - 1)
|
||||
L.pos = e + 1
|
||||
return '"' .. v
|
||||
end
|
||||
if c == "(" or c == ")" or c == "{" or c == "}" then
|
||||
L.pos += 1
|
||||
return c
|
||||
end
|
||||
local e = string.find(s, '[%s(){}"]', L.pos) or (#s + 1)
|
||||
local v = string.sub(s, L.pos, e - 1)
|
||||
L.pos = e
|
||||
return v
|
||||
end
|
||||
|
||||
local function num(L: Lexer): number
|
||||
local t = token(L)
|
||||
local v = t and tonumber(t)
|
||||
if not v then
|
||||
L.err = L.err or ("expected a number, got " .. tostring(t))
|
||||
return 0
|
||||
end
|
||||
return v
|
||||
end
|
||||
|
||||
local function str(L: Lexer): string
|
||||
local t = token(L)
|
||||
if not t or string.sub(t, 1, 1) ~= '"' then
|
||||
L.err = L.err or ("expected a string, got " .. tostring(t))
|
||||
return ""
|
||||
end
|
||||
return string.sub(t, 2)
|
||||
end
|
||||
|
||||
local function expect(L: Lexer, want: string)
|
||||
local t = token(L)
|
||||
if t ~= want then
|
||||
L.err = L.err or ("expected " .. want .. ", got " .. tostring(t))
|
||||
end
|
||||
end
|
||||
|
||||
local function vec(L: Lexer, n: number): { number }
|
||||
expect(L, "(")
|
||||
local v = table.create(n, 0)
|
||||
for i = 1, n do
|
||||
v[i] = num(L)
|
||||
end
|
||||
expect(L, ")")
|
||||
return v
|
||||
end
|
||||
|
||||
-- the unit quaternion from its x, y, z (w <= 0, as id's tools store it)
|
||||
local function quat(x: number, y: number, z: number): { number }
|
||||
local t = 1 - x * x - y * y - z * z
|
||||
return { x, y, z, if t < 0 then 0 else -math.sqrt(t) }
|
||||
end
|
||||
|
||||
local function rotate(q: { number }, vx: number, vy: number, vz: number): (number, number, number)
|
||||
local qx, qy, qz, qw = q[1], q[2], q[3], q[4]
|
||||
-- v + 2 w (q x v) + 2 q x (q x v)
|
||||
local tx, ty, tz = 2 * (qy * vz - qz * vy), 2 * (qz * vx - qx * vz), 2 * (qx * vy - qy * vx)
|
||||
return vx + qw * tx + (qy * tz - qz * ty), vy + qw * ty + (qz * tx - qx * tz), vz + qw * tz + (qx * ty - qy * tx)
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ md5mesh
|
||||
type MeshJoint = { name: string, parent: number, pos: { number }, q: { number } }
|
||||
|
||||
-- mesh(text, opts) -> Scene, joint node indices by name | nil, message
|
||||
function Read.mesh(text: string, opts: Options?): (Types.Scene?, any)
|
||||
local L: Lexer = { text = text, pos = 1, err = nil }
|
||||
local joints: { MeshJoint } = {}
|
||||
local scene = Scene.new()
|
||||
scene.meta.up = "z"
|
||||
local root: Types.Node = { name = "md5", children = {} }
|
||||
table.insert(scene.nodes, root)
|
||||
scene.roots[1] = 1
|
||||
local version: number? = nil
|
||||
local mesh: Types.Mesh = { primitives = {} }
|
||||
local maxV = opts and opts.maxVertices or 2 ^ 24
|
||||
local total = 0
|
||||
local skinIndex = 0
|
||||
local nodes: { number } = {}
|
||||
while not L.err do
|
||||
local t = token(L)
|
||||
if not t then
|
||||
break
|
||||
end
|
||||
if t == "MD5Version" then
|
||||
version = num(L)
|
||||
elseif t == "commandline" then
|
||||
str(L)
|
||||
elseif t == "numJoints" or t == "numMeshes" then
|
||||
num(L)
|
||||
elseif t == "joints" then
|
||||
expect(L, "{")
|
||||
while not L.err do
|
||||
local s = token(L)
|
||||
if s == "}" then
|
||||
break
|
||||
end
|
||||
if not s or string.sub(s, 1, 1) ~= '"' then
|
||||
return nil, "bad joint line"
|
||||
end
|
||||
local parent = num(L)
|
||||
local p, q = vec(L, 3), vec(L, 3)
|
||||
table.insert(joints, { name = string.sub(s, 2), parent = parent + 1, pos = p, q = quat(q[1], q[2], q[3]) })
|
||||
end
|
||||
local list: { Rig.Joint } = {}
|
||||
for i, j in joints do
|
||||
list[i] = { name = j.name, parent = j.parent, translation = j.pos, rotation = j.q }
|
||||
end
|
||||
local n, si = Rig.skeleton(scene, list, "world", 1)
|
||||
nodes, skinIndex = n, si
|
||||
elseif t == "mesh" then
|
||||
expect(L, "{")
|
||||
local shader = ""
|
||||
local verts: { { number } } = {} -- s, t, startWeight, countWeight
|
||||
local tris: { number } = {}
|
||||
local weights: { { number } } = {} -- joint, bias, x, y, z
|
||||
while not L.err do
|
||||
local k = token(L)
|
||||
if k == "}" then
|
||||
break
|
||||
elseif k == "shader" then
|
||||
shader = str(L)
|
||||
elseif k == "numverts" or k == "numtris" or k == "numweights" then
|
||||
local n = num(L)
|
||||
total += if k == "numverts" then n else 0
|
||||
if total > maxV then
|
||||
return nil, "limit: too many vertices"
|
||||
end
|
||||
elseif k == "vert" then
|
||||
local i = num(L)
|
||||
local st = vec(L, 2)
|
||||
verts[i + 1] = { st[1], st[2], num(L), num(L) }
|
||||
elseif k == "tri" then
|
||||
num(L)
|
||||
local a, b, c = num(L), num(L), num(L)
|
||||
table.insert(tris, c)
|
||||
table.insert(tris, b)
|
||||
table.insert(tris, a)
|
||||
elseif k == "weight" then
|
||||
local i = num(L)
|
||||
local j, bias = num(L), num(L)
|
||||
local p = vec(L, 3)
|
||||
weights[i + 1] = { j, bias, p[1], p[2], p[3] }
|
||||
else
|
||||
return nil, "unknown mesh keyword " .. tostring(k)
|
||||
end
|
||||
end
|
||||
local nv = #verts
|
||||
local pos, uv = buffer.create(nv * 12), buffer.create(nv * 8)
|
||||
local lists: { { number } } = {}
|
||||
for vi = 1, nv do
|
||||
local v = verts[vi]
|
||||
if not v then
|
||||
return nil, "missing vert " .. (vi - 1)
|
||||
end
|
||||
local x, y, z = 0, 0, 0
|
||||
local l: { number } = {}
|
||||
for w = v[3] + 1, v[3] + v[4] do
|
||||
local wt = weights[w]
|
||||
local j = wt and joints[wt[1] + 1]
|
||||
if not wt or not j then
|
||||
return nil, "vert " .. (vi - 1) .. ": bad weight " .. (w - 1)
|
||||
end
|
||||
local rx, ry, rz = rotate(j.q, wt[3], wt[4], wt[5])
|
||||
x += (j.pos[1] + rx) * wt[2]
|
||||
y += (j.pos[2] + ry) * wt[2]
|
||||
z += (j.pos[3] + rz) * wt[2]
|
||||
table.insert(l, wt[1])
|
||||
table.insert(l, wt[2])
|
||||
end
|
||||
writef32(pos, (vi - 1) * 12, x)
|
||||
writef32(pos, (vi - 1) * 12 + 4, y)
|
||||
writef32(pos, (vi - 1) * 12 + 8, z)
|
||||
writef32(uv, (vi - 1) * 8, v[1])
|
||||
writef32(uv, (vi - 1) * 8 + 4, v[2])
|
||||
lists[vi] = l
|
||||
end
|
||||
for _, ix in tris do
|
||||
if ix < 0 or ix >= nv then
|
||||
return nil, "triangle index out of range"
|
||||
end
|
||||
end
|
||||
local ib = buffer.create(#tris * 4)
|
||||
for i, ix in tris do
|
||||
writeu32(ib, (i - 1) * 4, ix)
|
||||
end
|
||||
local attrs: { [string]: Types.Accessor } = {
|
||||
POSITION = Scene.accessor(pos, "f32", 3, nv),
|
||||
NORMAL = Scene.accessor(Rig.normals(pos, nv, tris), "f32", 3, nv),
|
||||
TEXCOORD_0 = Scene.accessor(uv, "f32", 2, nv),
|
||||
}
|
||||
if #joints > 0 then
|
||||
attrs.JOINTS_0, attrs.WEIGHTS_0 = Rig.influences(lists)
|
||||
end
|
||||
local mat = Scene.material(shader)
|
||||
mat.metallic = 0
|
||||
table.insert(scene.textures, { name = shader, uri = shader })
|
||||
mat.baseColorTexture = { texture = #scene.textures }
|
||||
table.insert(scene.materials, mat)
|
||||
table.insert(mesh.primitives, { attributes = attrs, indices = Scene.accessor(ib, "u32", 1, #tris), mode = "triangles" :: any, material = #scene.materials })
|
||||
else
|
||||
return nil, "unknown keyword " .. t
|
||||
end
|
||||
end
|
||||
if L.err then
|
||||
return nil, L.err
|
||||
end
|
||||
if version ~= 10 then
|
||||
return nil, if version then "unsupported: MD5Version " .. version else "no MD5Version"
|
||||
end
|
||||
if #mesh.primitives > 0 then
|
||||
table.insert(scene.meshes, mesh)
|
||||
table.insert(scene.nodes, { name = "mesh", children = {}, mesh = #scene.meshes, skin = if #joints > 0 then skinIndex else nil })
|
||||
table.insert(root.children, #scene.nodes)
|
||||
end
|
||||
local byName: { [string]: number } = {}
|
||||
for i, j in joints do
|
||||
byName[j.name] = nodes[i]
|
||||
end
|
||||
scene.meta.source = { format = "md5", kind = "mesh", joints = #joints, meshes = #mesh.primitives }
|
||||
return scene, byName
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ md5anim
|
||||
export type Anim = {
|
||||
frameRate: number,
|
||||
frames: number,
|
||||
joints: { { name: string, parent: number } },
|
||||
base: { { number } }, -- per joint: px py pz qx qy qz
|
||||
tracks: { Rig.Track }, -- per joint: translation / rotation keys, one per frame
|
||||
}
|
||||
|
||||
-- anim(text) -> Anim | nil, message
|
||||
function Read.anim(text: string): (Anim?, string?)
|
||||
local L: Lexer = { text = text, pos = 1, err = nil }
|
||||
local a: Anim = { frameRate = 24, frames = 0, joints = {}, base = {}, tracks = {} }
|
||||
local hier: { { number } } = {} -- flags, startIndex
|
||||
local version: number? = nil
|
||||
local nComp = 0
|
||||
local frames: { { number } } = {}
|
||||
while not L.err do
|
||||
local t = token(L)
|
||||
if not t then
|
||||
break
|
||||
end
|
||||
if t == "MD5Version" then
|
||||
version = num(L)
|
||||
elseif t == "commandline" then
|
||||
str(L)
|
||||
elseif t == "numFrames" then
|
||||
a.frames = num(L)
|
||||
elseif t == "numJoints" then
|
||||
num(L)
|
||||
elseif t == "frameRate" then
|
||||
a.frameRate = num(L)
|
||||
elseif t == "numAnimatedComponents" then
|
||||
nComp = num(L)
|
||||
if nComp < 0 or nComp > 2 ^ 20 then
|
||||
return nil, "bad numAnimatedComponents"
|
||||
end
|
||||
elseif t == "hierarchy" then
|
||||
expect(L, "{")
|
||||
while not L.err do
|
||||
local s = token(L)
|
||||
if s == "}" then
|
||||
break
|
||||
end
|
||||
if not s or string.sub(s, 1, 1) ~= '"' then
|
||||
return nil, "bad hierarchy line"
|
||||
end
|
||||
local parent, flags, start = num(L), num(L), num(L)
|
||||
table.insert(a.joints, { name = string.sub(s, 2), parent = parent + 1 })
|
||||
table.insert(hier, { flags, start })
|
||||
end
|
||||
elseif t == "bounds" then
|
||||
expect(L, "{")
|
||||
while not L.err do
|
||||
local s = token(L)
|
||||
if s == "}" or s == nil then
|
||||
break
|
||||
end
|
||||
end
|
||||
elseif t == "baseframe" then
|
||||
expect(L, "{")
|
||||
while not L.err do
|
||||
local s = token(L)
|
||||
if s == "}" then
|
||||
break
|
||||
end
|
||||
if s ~= "(" then
|
||||
return nil, "bad baseframe line"
|
||||
end
|
||||
L.pos -= 1
|
||||
local p, q = vec(L, 3), vec(L, 3)
|
||||
table.insert(a.base, { p[1], p[2], p[3], q[1], q[2], q[3] })
|
||||
end
|
||||
elseif t == "frame" then
|
||||
local fi = num(L)
|
||||
expect(L, "{")
|
||||
local vals = table.create(nComp, 0)
|
||||
for k = 1, nComp do
|
||||
vals[k] = num(L)
|
||||
end
|
||||
expect(L, "}")
|
||||
if fi < 0 or fi > 2 ^ 20 then
|
||||
return nil, "bad frame index"
|
||||
end
|
||||
frames[fi + 1] = vals
|
||||
else
|
||||
return nil, "unknown keyword " .. t
|
||||
end
|
||||
end
|
||||
if L.err then
|
||||
return nil, L.err
|
||||
end
|
||||
if version ~= 10 then
|
||||
return nil, if version then "unsupported: MD5Version " .. version else "no MD5Version"
|
||||
end
|
||||
if #a.base ~= #a.joints then
|
||||
return nil, "baseframe and hierarchy disagree"
|
||||
end
|
||||
for f = 1, a.frames do
|
||||
if not frames[f] then
|
||||
return nil, "missing frame " .. (f - 1)
|
||||
end
|
||||
end
|
||||
for j, h in hier do
|
||||
local tr: { number }, rot: { number } = {}, {}
|
||||
local flags, start = h[1], h[2]
|
||||
for f = 1, a.frames do
|
||||
local v = table.clone(a.base[j])
|
||||
local k = start + 1
|
||||
for bit = 0, 5 do
|
||||
if bit32.band(flags, bit32.lshift(1, bit)) ~= 0 then
|
||||
v[bit + 1] = frames[f][k] or v[bit + 1]
|
||||
k += 1
|
||||
end
|
||||
end
|
||||
table.insert(tr, v[1])
|
||||
table.insert(tr, v[2])
|
||||
table.insert(tr, v[3])
|
||||
local q = quat(v[4], v[5], v[6])
|
||||
for c = 1, 4 do
|
||||
table.insert(rot, q[c])
|
||||
end
|
||||
end
|
||||
a.tracks[j] = { translation = tr, rotation = rot }
|
||||
end
|
||||
return a, nil
|
||||
end
|
||||
|
||||
-- addAnim(scene, nodes by joint name, anim, name) -> channels added
|
||||
function Read.addAnim(scene: Types.Scene, byName: { [string]: number }, a: Anim, name: string): number
|
||||
local nodes: { number } = {}
|
||||
local tracks: { [number]: Rig.Track } = {}
|
||||
for j, jt in a.joints do
|
||||
local nd = byName[jt.name]
|
||||
if nd then
|
||||
table.insert(nodes, nd)
|
||||
tracks[#nodes] = a.tracks[j]
|
||||
end
|
||||
end
|
||||
local times: { number } = {}
|
||||
local rate = if a.frameRate > 0 then a.frameRate else 24
|
||||
for f = 1, a.frames do
|
||||
times[f] = (f - 1) / rate
|
||||
end
|
||||
local ai = Rig.animation(scene, name, nodes, times, tracks, "LINEAR")
|
||||
return #scene.animations[ai].channels
|
||||
end
|
||||
|
||||
-- animScene(a, name) -> a Scene of the animation's skeleton (baseframe pose) with the animation
|
||||
function Read.animScene(a: Anim, name: string): Types.Scene
|
||||
local scene = Scene.new()
|
||||
scene.meta.up = "z"
|
||||
table.insert(scene.nodes, { name = "md5", children = {} })
|
||||
scene.roots[1] = 1
|
||||
local list: { Rig.Joint } = {}
|
||||
for j, jt in a.joints do
|
||||
local b = a.base[j]
|
||||
list[j] = { name = jt.name, parent = jt.parent, translation = { b[1], b[2], b[3] }, rotation = quat(b[4], b[5], b[6]) }
|
||||
end
|
||||
local nodes = Rig.skeleton(scene, list, "local", 1)
|
||||
local byName: { [string]: number } = {}
|
||||
for j, jt in a.joints do
|
||||
byName[jt.name] = nodes[j]
|
||||
end
|
||||
Read.addAnim(scene, byName, a, name)
|
||||
scene.meta.source = { format = "md5", kind = "anim", joints = #a.joints, frames = a.frames, frameRate = a.frameRate }
|
||||
return scene
|
||||
end
|
||||
|
||||
return Read
|
||||
@@ -0,0 +1,83 @@
|
||||
--!strict
|
||||
-- model/md5: Doom 3 / Quake 4 MD5 models (MD5Version 10 text): .md5mesh (skeleton, skin, meshes) and .md5anim
|
||||
-- (skeletal animation), read into a Scene through model/md5/Read. A .md5mesh loads its animations from
|
||||
-- opts.anims = { "idle.md5anim", ... } (each found through opts.files[name] or opts.resolve(name); joints matched by
|
||||
-- name; the animation is named after the file without its extension); a missing one fails with UNSUPPORTED unless
|
||||
-- opts.skipMissing. A .md5anim alone loads as its skeleton (baseframe pose) with the animation. Units are Doom
|
||||
-- units, z up. Not supported: writing, .md5camera.
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ requires
|
||||
local Err = require("@formats/core/Err")
|
||||
local Bytes = require("@formats/core/Bytes")
|
||||
local Input = require("@formats/core/Input")
|
||||
local Sniff = require("@formats/core/Sniff")
|
||||
local Types = require("@formats/Types")
|
||||
local Read = require("@formats/model/md5/Read")
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ contract
|
||||
local Md5 = {
|
||||
name = "md5",
|
||||
category = "model",
|
||||
extensions = { "md5mesh", "md5anim" },
|
||||
mime = { "model/x-md5mesh", "model/x-md5anim" },
|
||||
deps = { "core/Err", "core/Bytes", "core/Input", "core/Sniff", "Types", "codecs/model/Rig" },
|
||||
caps = { decode = true, encode = false, skins = true, animation = true },
|
||||
}
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ types
|
||||
export type DecodeOptions = {
|
||||
anims: { string }?, -- .md5anim files to load with a .md5mesh
|
||||
resolve: ((uri: string) -> (buffer | string)?)?,
|
||||
files: { [string]: buffer | string }?,
|
||||
skipMissing: boolean?, -- ignore animations that cannot be found (default false: UNSUPPORTED)
|
||||
name: string?, -- the file name (names a standalone animation)
|
||||
maxVertices: number?, -- default 2^24
|
||||
}
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ sniff
|
||||
function Md5.sniff(r: Bytes.Reader): number
|
||||
local head = Sniff.text(r, 512, true)
|
||||
head = string.gsub(head, "^//[^\n]*\n%s*", "")
|
||||
return if string.match(head, "^MD5Version%s+%d+") then 1 else 0
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ decode
|
||||
local function stem(name: string): string
|
||||
local base = string.match(name, "([^/\\]+)$") or name
|
||||
return (string.gsub(base, "%.[^.]*$", ""))
|
||||
end
|
||||
|
||||
function Md5.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Scene?, Err.Err?)
|
||||
local text = Sniff.dropBom(r:string(r:remaining()))
|
||||
if string.find(text, "numAnimatedComponents", 1, true) then
|
||||
local a, msg = Read.anim(text)
|
||||
if not a then
|
||||
return nil, Err.from(msg)
|
||||
end
|
||||
return Read.animScene(a, if opts and type(opts.name) == "string" then stem(opts.name) else "animation"), nil
|
||||
end
|
||||
local scene, byName = Read.mesh(text, opts :: any)
|
||||
if not scene then
|
||||
return nil, Err.from(byName)
|
||||
end
|
||||
if opts and type(opts.anims) == "table" then
|
||||
for _, name in opts.anims do
|
||||
local got = if type(name) == "string" then Input.sibling(opts, name) else nil
|
||||
local src = if got then buffer.tostring(got) else nil
|
||||
if not src then
|
||||
if not opts.skipMissing then
|
||||
return nil, Err.new(Err.UNSUPPORTED, "animation " .. tostring(name) .. " not available (opts.resolve / opts.files)")
|
||||
end
|
||||
else
|
||||
local a, msg = Read.anim(Sniff.dropBom(src))
|
||||
if not a then
|
||||
return nil, Err.from("animation " .. name .. ": " .. tostring(msg))
|
||||
end
|
||||
Read.addAnim(scene, byName, a, stem(name))
|
||||
end
|
||||
end
|
||||
end
|
||||
return scene, nil
|
||||
end
|
||||
|
||||
return Md5
|
||||
@@ -0,0 +1,340 @@
|
||||
--!strict
|
||||
-- model/mdl/HalfLife: Half-Life 1 (GoldSrc) studio models ("IDST" version 10) to a Scene. Written from the studio.h
|
||||
-- layout of the Half-Life SDK and the format notes of the HLMV / Crowbar communities; no code taken.
|
||||
-- Bones -> joint nodes and a Skin (bind pose from the bone defaults; Euler angles through Rig.angles), body parts ->
|
||||
-- one mesh per body part (its first model, or opts.bodies[part]), its meshes -> primitives (triangle strips and fans
|
||||
-- unrolled to counter-clockwise triangles; vertices transformed to model space by their bone's bind pose; JOINTS_0 =
|
||||
-- that bone, WEIGHTS_0 = 1), textures (8-bit + their own palette) -> texture.image, the first skin family ->
|
||||
-- materials, sequences of the main file -> animations (frames at the sequence's fps; the first blend only).
|
||||
-- Not supported: sequence groups in other files (those sequences are listed in meta, without channels), bone
|
||||
-- controllers, hitboxes / attachments / events (counted in meta), textures in a separate "<name>t.mdl" (pass it
|
||||
-- as opts.textures = that file's bytes).
|
||||
local Types = require("@formats/Types")
|
||||
local Mat4 = require("@formats/codecs/model/Mat4")
|
||||
local Pixels = require("@formats/codecs/image/Pixels")
|
||||
local Rig = require("@formats/codecs/model/Rig")
|
||||
|
||||
local HalfLife = {}
|
||||
|
||||
local Scene = Types.Scene
|
||||
local readi32, readi16, readu16, readu8, readf32 = buffer.readi32, buffer.readi16, buffer.readu16, buffer.readu8, buffer.readf32
|
||||
local writef32, writeu32, writeu16 = buffer.writef32, buffer.writeu32, buffer.writeu16
|
||||
|
||||
type Bone = { name: string, parent: number, value: { number }, scale: { number } }
|
||||
export type Options = { bodies: { number }?, textures: buffer?, maxPixels: number?, maxVertices: number? }
|
||||
|
||||
local function str(b: buffer, at: number, n: number): string
|
||||
return (string.match(buffer.readstring(b, at, n), "^[^%z]*")) :: string
|
||||
end
|
||||
|
||||
-- the textures of a studio header at base (this file or a separate texture file) -> { Image }, names | nil, message
|
||||
local function textures(b: buffer, base: number, size: number, maxPixels: number): ({ Types.Image }?, { string } | string)
|
||||
local n, at = readi32(b, base + 180), readi32(b, base + 184)
|
||||
if n < 0 or n > 4096 or at < 0 or at + n * 80 > size then
|
||||
return nil, "bad texture table"
|
||||
end
|
||||
local out: { Types.Image } = {}
|
||||
local names: { string } = {}
|
||||
for i = 0, n - 1 do
|
||||
local o = base + at + i * 80
|
||||
local w, h, data = readi32(b, o + 68), readi32(b, o + 72), readi32(b, o + 76)
|
||||
if w <= 0 or h <= 0 or w * h > maxPixels or data < 0 or data + w * h + 768 > size then
|
||||
return nil, "bad texture " .. i
|
||||
end
|
||||
local img = Types.Image.new(w, h)
|
||||
local pal = Pixels.palette(b, base + data + w * h, 256)
|
||||
Pixels.indexed(b, base + data, w, 8, img.pixels, w, h, true, pal)
|
||||
local flags = readi32(b, o + 64)
|
||||
img.meta.source = { format = "mdl", flags = flags }
|
||||
out[i + 1] = img
|
||||
names[i + 1] = str(b, o, 64)
|
||||
end
|
||||
return out, names
|
||||
end
|
||||
|
||||
-- one animation value: bone default + stored value * scale (frame f, 0-based)
|
||||
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
|
||||
|
||||
-- decode(b, base, size, opts) -> Scene | nil, message
|
||||
function HalfLife.decode(b: buffer, base: number, size: number, opts: Options?): (Types.Scene?, string?)
|
||||
if size < 244 then
|
||||
return nil, "truncated header"
|
||||
end
|
||||
local limit = base + size
|
||||
local function hdr(o: number): number
|
||||
return readi32(b, base + o)
|
||||
end
|
||||
local nBones, oBones = hdr(140), hdr(144)
|
||||
local nSeq, oSeq = hdr(164), hdr(168)
|
||||
local nTex = hdr(180)
|
||||
local nSkinRef, nFamilies, oSkins = hdr(192), hdr(196), hdr(200)
|
||||
local nParts, oParts = hdr(204), hdr(208)
|
||||
local function inside(o: number, n: number): boolean
|
||||
return o >= 0 and n >= 0 and o + n <= size
|
||||
end
|
||||
if nBones < 0 or nBones > 256 or not inside(oBones, nBones * 112) then
|
||||
return nil, "bad bone table"
|
||||
end
|
||||
if nSeq < 0 or nSeq > 4096 or not inside(oSeq, nSeq * 176) then
|
||||
return nil, "bad sequence table"
|
||||
end
|
||||
if nParts < 0 or nParts > 256 or not inside(oParts, nParts * 76) then
|
||||
return nil, "bad body part table"
|
||||
end
|
||||
local maxPixels = opts and opts.maxPixels or 2 ^ 24
|
||||
local scene = Scene.new()
|
||||
scene.meta.up = "z"
|
||||
-- bones
|
||||
local bones: { Bone } = {}
|
||||
local joints: { Rig.Joint } = {}
|
||||
for i = 0, nBones - 1 do
|
||||
local o = base + oBones + i * 112
|
||||
local value, scale = {}, {}
|
||||
for k = 0, 5 do
|
||||
value[k + 1] = readf32(b, o + 64 + k * 4)
|
||||
scale[k + 1] = readf32(b, o + 88 + k * 4)
|
||||
end
|
||||
local parent = readi32(b, o + 32)
|
||||
bones[i + 1] = { name = str(b, o, 32), parent = parent + 1, value = value, scale = scale }
|
||||
joints[i + 1] = { name = bones[i + 1].name, parent = parent + 1, translation = { value[1], value[2], value[3] }, rotation = Rig.angles(value[4], value[5], value[6]) }
|
||||
end
|
||||
local root: Types.Node = { name = str(b, base + 8, 64), children = {} }
|
||||
table.insert(scene.nodes, root)
|
||||
scene.roots[1] = 1
|
||||
local jointNodes, skinIndex, world = Rig.skeleton(scene, joints, "local", 1)
|
||||
-- textures and skins
|
||||
local texSrc, texBase, texSize = b, base, size
|
||||
if nTex == 0 and opts and opts.textures then
|
||||
texSrc, texBase, texSize = opts.textures, 0, buffer.len(opts.textures)
|
||||
if texSize < 244 or buffer.readstring(texSrc, 0, 4) ~= "IDST" then
|
||||
return nil, "opts.textures is not a studio texture file"
|
||||
end
|
||||
nSkinRef, nFamilies, oSkins = readi32(texSrc, 192), readi32(texSrc, 196), readi32(texSrc, 200)
|
||||
end
|
||||
local images, texNames = textures(texSrc, texBase, texSize, maxPixels)
|
||||
if not images then
|
||||
return nil, texNames :: string
|
||||
end
|
||||
local names = texNames :: { string }
|
||||
for i, img in images do
|
||||
table.insert(scene.textures, { name = names[i], image = img, uri = names[i] })
|
||||
local mat = Scene.material(names[i])
|
||||
mat.metallic = 0
|
||||
mat.baseColorTexture = { texture = i }
|
||||
table.insert(scene.materials, mat)
|
||||
end
|
||||
local skinMap: { number } = {}
|
||||
if nSkinRef > 0 and nFamilies > 0 and oSkins >= 0 and oSkins + nSkinRef * 2 <= texSize then
|
||||
for r = 0, nSkinRef - 1 do
|
||||
skinMap[r + 1] = readi16(texSrc, texBase + oSkins + r * 2) + 1
|
||||
end
|
||||
end
|
||||
-- body parts
|
||||
local totalVerts = 0
|
||||
for part = 0, nParts - 1 do
|
||||
local po = base + oParts + part * 76
|
||||
local pname = str(b, po, 64)
|
||||
local nModels, oModels = readi32(b, po + 64), readi32(b, po + 72)
|
||||
local pick = (opts and opts.bodies and opts.bodies[part + 1]) or 1
|
||||
if nModels > 0 and pick >= 1 and pick <= nModels and inside(oModels, nModels * 112) then
|
||||
local mo = base + oModels + (pick - 1) * 112
|
||||
local nMesh, oMesh = readi32(b, mo + 72), readi32(b, mo + 76)
|
||||
local nVerts, oVertInfo, oVerts = readi32(b, mo + 80), readi32(b, mo + 84), readi32(b, mo + 88)
|
||||
local nNorms, oNormInfo, oNorms = readi32(b, mo + 92), readi32(b, mo + 96), readi32(b, mo + 100)
|
||||
if nMesh < 0 or nMesh > 4096 or not inside(oMesh, nMesh * 20) or nVerts < 0 or not inside(oVertInfo, nVerts) or not inside(oVerts, nVerts * 12) or nNorms < 0 or not inside(oNormInfo, nNorms) or not inside(oNorms, nNorms * 12) then
|
||||
return nil, "body part " .. pname .. ": bad model tables"
|
||||
end
|
||||
local mesh: Types.Mesh = { name = pname, primitives = {}, extras = { mdl = { model = str(b, mo, 64), models = nModels } } }
|
||||
for m = 0, nMesh - 1 do
|
||||
local me = base + oMesh + m * 20
|
||||
local oTri, skinref = readi32(b, me + 4), readi32(b, me + 8)
|
||||
local tex = skinMap[skinref + 1] or (skinref + 1)
|
||||
local img = images[tex]
|
||||
local tw, th = if img then img.width else 1, if img then img.height else 1
|
||||
-- triangle commands
|
||||
local weld: { [string]: number } = {}
|
||||
local corners: { { number } } = {}
|
||||
local indices: { number } = {}
|
||||
local p = base + oTri
|
||||
if oTri < 0 or oTri >= size then
|
||||
return nil, "bad triangle command offset"
|
||||
end
|
||||
while true do
|
||||
if p + 2 > limit then
|
||||
return nil, "truncated triangle commands"
|
||||
end
|
||||
local n = readi16(b, p)
|
||||
p += 2
|
||||
if n == 0 then
|
||||
break
|
||||
end
|
||||
local fan = n < 0
|
||||
n = math.abs(n)
|
||||
if p + n * 8 > limit then
|
||||
return nil, "truncated triangle commands"
|
||||
end
|
||||
local ids: { number } = {}
|
||||
for k = 0, n - 1 do
|
||||
local o = p + k * 8
|
||||
local vi, ni, s, t = readu16(b, o), readu16(b, o + 2), readi16(b, o + 4), readi16(b, o + 6)
|
||||
if vi >= nVerts or ni >= nNorms then
|
||||
return nil, "triangle command vertex out of range"
|
||||
end
|
||||
local key = vi .. ":" .. ni .. ":" .. s .. ":" .. t
|
||||
local id = weld[key]
|
||||
if not id then
|
||||
table.insert(corners, { vi, ni, s, t })
|
||||
id = #corners - 1
|
||||
weld[key] = id
|
||||
end
|
||||
ids[k + 1] = id
|
||||
end
|
||||
p += n * 8
|
||||
for k = 3, n do
|
||||
local a, c2, c3
|
||||
if fan then
|
||||
a, c2, c3 = ids[1], ids[k - 1], ids[k]
|
||||
elseif k % 2 == 1 then
|
||||
a, c2, c3 = ids[k - 2], ids[k - 1], ids[k]
|
||||
else
|
||||
a, c2, c3 = ids[k - 1], ids[k - 2], ids[k]
|
||||
end
|
||||
-- studio models wind clockwise: reverse
|
||||
table.insert(indices, c3)
|
||||
table.insert(indices, c2)
|
||||
table.insert(indices, a)
|
||||
end
|
||||
end
|
||||
local nv = #corners
|
||||
totalVerts += nv
|
||||
if totalVerts > (opts and opts.maxVertices or 2 ^ 24) then
|
||||
return nil, "limit: too many vertices"
|
||||
end
|
||||
local pos, nrm, uv = buffer.create(nv * 12), buffer.create(nv * 12), buffer.create(nv * 8)
|
||||
local jb, wb = buffer.create(nv * 8), buffer.create(nv * 16)
|
||||
for i, c in corners do
|
||||
local o = (i - 1) * 12
|
||||
local bone = readu8(b, base + oVertInfo + c[1])
|
||||
local nbone = readu8(b, base + oNormInfo + c[2])
|
||||
local vo, no = base + oVerts + c[1] * 12, base + oNorms + c[2] * 12
|
||||
local x, y, z = readf32(b, vo), readf32(b, vo + 4), readf32(b, vo + 8)
|
||||
local m4 = world[bone + 1]
|
||||
if m4 then
|
||||
x, y, z = Mat4.point(m4, x, y, z)
|
||||
end
|
||||
writef32(pos, o, x)
|
||||
writef32(pos, o + 4, y)
|
||||
writef32(pos, o + 8, z)
|
||||
local nx, ny, nz = readf32(b, no), readf32(b, no + 4), readf32(b, no + 8)
|
||||
local n4 = world[nbone + 1]
|
||||
if n4 then
|
||||
nx, ny, nz = n4[1] * nx + n4[5] * ny + n4[9] * nz, n4[2] * nx + n4[6] * ny + n4[10] * nz, n4[3] * nx + n4[7] * ny + n4[11] * nz
|
||||
end
|
||||
writef32(nrm, o, nx)
|
||||
writef32(nrm, o + 4, ny)
|
||||
writef32(nrm, o + 8, nz)
|
||||
writef32(uv, (i - 1) * 8, c[3] / tw)
|
||||
writef32(uv, (i - 1) * 8 + 4, c[4] / th)
|
||||
writeu16(jb, (i - 1) * 8, math.min(bone, math.max(0, nBones - 1)))
|
||||
writef32(wb, (i - 1) * 16, 1)
|
||||
end
|
||||
local ib = buffer.create(#indices * 4)
|
||||
for i, v in indices do
|
||||
writeu32(ib, (i - 1) * 4, v)
|
||||
end
|
||||
local attrs: { [string]: Types.Accessor } = {
|
||||
POSITION = Scene.accessor(pos, "f32", 3, nv),
|
||||
NORMAL = Scene.accessor(nrm, "f32", 3, nv),
|
||||
TEXCOORD_0 = Scene.accessor(uv, "f32", 2, nv),
|
||||
}
|
||||
if nBones > 0 then
|
||||
attrs.JOINTS_0 = Scene.accessor(jb, "u16", 4, nv)
|
||||
attrs.WEIGHTS_0 = Scene.accessor(wb, "f32", 4, nv)
|
||||
end
|
||||
table.insert(mesh.primitives, {
|
||||
attributes = attrs,
|
||||
indices = Scene.accessor(ib, "u32", 1, #indices),
|
||||
mode = "triangles" :: any,
|
||||
material = if img then tex else nil,
|
||||
})
|
||||
end
|
||||
table.insert(scene.meshes, mesh)
|
||||
table.insert(scene.nodes, { name = pname, children = {}, mesh = #scene.meshes, skin = if nBones > 0 then skinIndex else nil })
|
||||
table.insert(root.children, #scene.nodes)
|
||||
end
|
||||
end
|
||||
-- sequences
|
||||
local seqs: { any } = {}
|
||||
for s = 0, nSeq - 1 do
|
||||
local so = base + oSeq + s * 176
|
||||
local label, fps, nFrames = str(b, so, 32), readf32(b, so + 32), readi32(b, so + 56)
|
||||
local nBlends, oAnim, group = readi32(b, so + 120), readi32(b, so + 124), readi32(b, so + 156)
|
||||
table.insert(seqs, { name = label, fps = fps, frames = nFrames, blends = nBlends, group = group })
|
||||
if group == 0 and nFrames > 0 and nFrames <= 65536 and nBones > 0 and inside(oAnim, nBones * 12) then
|
||||
local rate = if fps > 0 then fps else 30
|
||||
local times: { number } = {}
|
||||
for f = 0, nFrames - 1 do
|
||||
times[f + 1] = f / rate
|
||||
end
|
||||
local tracks: { [number]: Rig.Track } = {}
|
||||
for j = 1, nBones do
|
||||
local bn = bones[j]
|
||||
local ao = base + oAnim + (j - 1) * 12
|
||||
local tr, rot = {}, {}
|
||||
for f = 0, nFrames - 1 do
|
||||
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
|
||||
v[k + 1] = bn.value[k + 1] + (raw or 0) * bn.scale[k + 1]
|
||||
end
|
||||
table.insert(tr, v[1])
|
||||
table.insert(tr, v[2])
|
||||
table.insert(tr, v[3])
|
||||
local q = Rig.angles(v[4], v[5], v[6])
|
||||
for k = 1, 4 do
|
||||
table.insert(rot, q[k])
|
||||
end
|
||||
end
|
||||
tracks[j] = { translation = tr, rotation = rot }
|
||||
end
|
||||
Rig.animation(scene, label, jointNodes, times, tracks, "LINEAR")
|
||||
end
|
||||
end
|
||||
scene.meta.source = {
|
||||
format = "mdl",
|
||||
variant = "halflife",
|
||||
name = root.name,
|
||||
bones = nBones,
|
||||
sequences = seqs,
|
||||
textures = #images,
|
||||
skinFamilies = nFamilies,
|
||||
hitboxes = hdr(156),
|
||||
attachments = hdr(212),
|
||||
}
|
||||
return scene, nil
|
||||
end
|
||||
|
||||
return HalfLife
|
||||
@@ -0,0 +1,222 @@
|
||||
--!strict
|
||||
-- model/mdl/Quake: Quake 1 MDL ("IDPO" version 6) to a Scene. Written from the Quake specs (Olivier Montanuy et
|
||||
-- al., "Quake Specs 3.4", section 5) and the modelgen.h layout of the Quake source release; no code taken.
|
||||
-- Skins (single and grouped: the first picture of a group) become texture.image through a 768-byte palette;
|
||||
-- texture coordinates on the seam of back-facing triangles move half a skin width (the vertices are welded per
|
||||
-- side); simple and grouped frames become morph targets with one animation per frame-name group.
|
||||
local Types = require("@formats/Types")
|
||||
local Pixels = require("@formats/codecs/image/Pixels")
|
||||
local Rig = require("@formats/codecs/model/Rig")
|
||||
|
||||
local Quake = {}
|
||||
|
||||
local Scene = Types.Scene
|
||||
local readi32, readf32, readu8, writef32, writeu32 = buffer.readi32, buffer.readf32, buffer.readu8, buffer.writef32, buffer.writeu32
|
||||
|
||||
export type Options = { frame: number?, morph: boolean?, fps: number?, maxVertices: number?, maxPixels: number? }
|
||||
|
||||
local function name16(b: buffer, at: number): string
|
||||
return (string.match(buffer.readstring(b, at, 16), "^[^%z]*")) :: string
|
||||
end
|
||||
|
||||
-- decode(b, base, size, palette, opts) -> Scene | nil, message (offsets relative to base)
|
||||
function Quake.decode(b: buffer, base: number, size: number, palette: buffer?, opts: Options?): (Types.Scene?, string?)
|
||||
if size < 84 then
|
||||
return nil, "truncated header"
|
||||
end
|
||||
local scale = { readf32(b, base + 8), readf32(b, base + 12), readf32(b, base + 16) }
|
||||
local origin = { readf32(b, base + 20), readf32(b, base + 24), readf32(b, base + 28) }
|
||||
local nSkins, sw, sh = readi32(b, base + 48), readi32(b, base + 52), readi32(b, base + 56)
|
||||
local nVerts, nTris, nFrames = readi32(b, base + 60), readi32(b, base + 64), readi32(b, base + 68)
|
||||
if nSkins < 0 or sw < 0 or sh < 0 or nVerts <= 0 or nTris < 0 or nFrames <= 0 or nSkins > 1024 or nFrames > 65536 then
|
||||
return nil, "bad counts"
|
||||
end
|
||||
if sw * sh > (opts and opts.maxPixels or 2 ^ 24) then
|
||||
return nil, "limit: skin too big"
|
||||
end
|
||||
if nFrames * nVerts > (opts and opts.maxVertices or 2 ^ 24) then
|
||||
return nil, "limit: too many vertices"
|
||||
end
|
||||
local p = 84
|
||||
local function need(n: number): boolean
|
||||
return n >= 0 and p + n <= size
|
||||
end
|
||||
-- skins
|
||||
local pal = if palette then Pixels.palette(palette, 0, 256) else nil
|
||||
local skins: { Types.Image } = {}
|
||||
local px = sw * sh
|
||||
for _ = 1, nSkins do
|
||||
if not need(4) then
|
||||
return nil, "truncated skins"
|
||||
end
|
||||
local group = readi32(b, base + p)
|
||||
p += 4
|
||||
local count = 1
|
||||
if group ~= 0 then
|
||||
if not need(4) then
|
||||
return nil, "truncated skin group"
|
||||
end
|
||||
count = readi32(b, base + p)
|
||||
p += 4
|
||||
if count <= 0 or count > 256 or not need(count * 4) then
|
||||
return nil, "bad skin group"
|
||||
end
|
||||
p += count * 4
|
||||
end
|
||||
if not need(count * px) then
|
||||
return nil, "truncated skin pixels"
|
||||
end
|
||||
local img = Types.Image.new(sw, sh)
|
||||
if pal then
|
||||
Pixels.indexed(b, base + p, sw, 8, img.pixels, sw, sh, true, pal)
|
||||
else
|
||||
for i = 0, px - 1 do
|
||||
local v = readu8(b, base + p + i)
|
||||
writeu32(img.pixels, i * 4, 0xFF000000 + v * 0x10101)
|
||||
end
|
||||
end
|
||||
img.meta.source = { format = "mdl", palette = pal ~= nil, frames = count }
|
||||
table.insert(skins, img)
|
||||
p += count * px
|
||||
end
|
||||
-- texture coordinates and triangles
|
||||
if not need(nVerts * 12 + nTris * 16) then
|
||||
return nil, "truncated vertices / triangles"
|
||||
end
|
||||
local stAt = p
|
||||
p += nVerts * 12
|
||||
local weld: { [number]: number } = {}
|
||||
local src: { number }, uvs: { number } = {}, {}
|
||||
local indices: { number } = {}
|
||||
for t = 0, nTris - 1 do
|
||||
local o = base + p + t * 16
|
||||
local front = readi32(b, o) ~= 0
|
||||
local c: { number } = {}
|
||||
for k = 1, 3 do
|
||||
local v = readi32(b, o + k * 4)
|
||||
if v < 0 or v >= nVerts then
|
||||
return nil, "triangle vertex out of range"
|
||||
end
|
||||
local so = base + stAt + v * 12
|
||||
local seam = readi32(b, so) ~= 0 and not front
|
||||
local key = v * 2 + (if seam then 1 else 0)
|
||||
local id = weld[key]
|
||||
if not id then
|
||||
table.insert(src, v)
|
||||
local s = readi32(b, so + 4) + (if seam then sw / 2 else 0)
|
||||
table.insert(uvs, (s + 0.5) / math.max(sw, 1))
|
||||
table.insert(uvs, (readi32(b, so + 8) + 0.5) / math.max(sh, 1))
|
||||
id = #src - 1
|
||||
weld[key] = id
|
||||
end
|
||||
c[k] = id
|
||||
end
|
||||
-- Quake's front faces are clockwise
|
||||
table.insert(indices, c[3])
|
||||
table.insert(indices, c[2])
|
||||
table.insert(indices, c[1])
|
||||
end
|
||||
p += nTris * 16
|
||||
-- frames: simple (type 0) or groups of simple frames
|
||||
local frameAt: { number } = {}
|
||||
local names: { string } = {}
|
||||
local fsize = 24 + nVerts * 4
|
||||
for _ = 1, nFrames do
|
||||
if not need(4) then
|
||||
return nil, "truncated frames"
|
||||
end
|
||||
local kind = readi32(b, base + p)
|
||||
p += 4
|
||||
if kind == 0 then
|
||||
if not need(fsize) then
|
||||
return nil, "truncated frame"
|
||||
end
|
||||
table.insert(frameAt, p + 8)
|
||||
table.insert(names, name16(b, base + p + 8))
|
||||
p += fsize
|
||||
else
|
||||
if not need(12) then
|
||||
return nil, "truncated frame group"
|
||||
end
|
||||
local count = readi32(b, base + p)
|
||||
if count <= 0 or count > 4096 or not need(12 + count * 4 + count * fsize) then
|
||||
return nil, "bad frame group"
|
||||
end
|
||||
p += 12 + count * 4
|
||||
for _ = 1, count do
|
||||
table.insert(frameAt, p + 8)
|
||||
table.insert(names, name16(b, base + p + 8))
|
||||
p += fsize
|
||||
end
|
||||
end
|
||||
end
|
||||
local nv = #src
|
||||
local total = #frameAt
|
||||
local morph = not (opts and opts.morph == false)
|
||||
local want = math.clamp(math.floor(opts and opts.frame or 1), 1, total)
|
||||
local positions: { buffer }, normals: { buffer } = {}, {}
|
||||
for f, at in frameAt do
|
||||
if morph or f == want then
|
||||
local pos = buffer.create(nv * 12)
|
||||
local vo = base + at + 16
|
||||
for i, v in src do
|
||||
for k = 0, 2 do
|
||||
writef32(pos, (i - 1) * 12 + k * 4, readu8(b, vo + v * 4 + k) * scale[k + 1] + origin[k + 1])
|
||||
end
|
||||
end
|
||||
positions[f] = pos
|
||||
normals[f] = Rig.normals(pos, nv, indices)
|
||||
end
|
||||
end
|
||||
local ib = buffer.create(#indices * 4)
|
||||
for i, v in indices do
|
||||
writeu32(ib, (i - 1) * 4, v)
|
||||
end
|
||||
local uvb = buffer.create(nv * 8)
|
||||
for i, v in uvs do
|
||||
writef32(uvb, (i - 1) * 4, v)
|
||||
end
|
||||
local prim: Types.Primitive = {
|
||||
attributes = {
|
||||
POSITION = Scene.accessor(positions[want], "f32", 3, nv),
|
||||
NORMAL = Scene.accessor(normals[want], "f32", 3, nv),
|
||||
TEXCOORD_0 = Scene.accessor(uvb, "f32", 2, nv),
|
||||
},
|
||||
indices = Scene.accessor(ib, "u32", 1, #indices),
|
||||
mode = "triangles",
|
||||
}
|
||||
local scene = Scene.new()
|
||||
scene.meta.up = "z"
|
||||
for i, img in skins do
|
||||
table.insert(scene.textures, { name = "skin " .. i, image = img, sampler = { filter = "nearest" :: any } })
|
||||
end
|
||||
if #skins > 0 then
|
||||
local mat = Scene.material("skin")
|
||||
mat.metallic = 0
|
||||
mat.baseColorTexture = { texture = 1 }
|
||||
scene.materials[1] = mat
|
||||
prim.material = 1
|
||||
end
|
||||
scene.meshes[1] = { primitives = { prim } }
|
||||
scene.nodes[1] = { children = {}, mesh = 1 }
|
||||
scene.roots[1] = 1
|
||||
if morph then
|
||||
Rig.morph(prim, positions, normals)
|
||||
scene.meshes[1].weights = table.create(total, 0)
|
||||
local ranges: { Rig.Range } = {}
|
||||
for i, n in names do
|
||||
local stem = string.match(n, "^(.-)%d*$") or n
|
||||
local last = ranges[#ranges]
|
||||
if last and last.name == stem then
|
||||
last.last = i
|
||||
else
|
||||
table.insert(ranges, { name = if stem ~= "" then stem else n, first = i, last = i, fps = opts and opts.fps or 10 })
|
||||
end
|
||||
end
|
||||
Rig.morphAnimation(scene, 1, total, ranges, "LINEAR")
|
||||
end
|
||||
scene.meta.source = { format = "mdl", variant = "quake", frames = total, frameNames = names, skinWidth = sw, skinHeight = sh, palette = pal ~= nil }
|
||||
return scene, nil
|
||||
end
|
||||
|
||||
return Quake
|
||||
@@ -0,0 +1,84 @@
|
||||
--!strict
|
||||
-- model/mdl: Quake 1 ("IDPO" version 6: model/mdl/Quake) and Half-Life 1 / GoldSrc ("IDST" version 10:
|
||||
-- model/mdl/HalfLife) models, read into a Scene. See the two submodules for what each maps. Quake skins need the
|
||||
-- game's 768-byte palette (gfx/palette.lmp, not redistributable: never built in): opts.palette (a buffer / string),
|
||||
-- else opts.resolve("gfx/palette.lmp") / opts.files["gfx/palette.lmp"], else a grey ramp (meta.source.palette =
|
||||
-- false). Half-Life textures carry their own palettes. Source engine MDL ("IDST" version 44+, with .vvd / .vtx
|
||||
-- files) is UNSUPPORTED.
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ requires
|
||||
local Err = require("@formats/core/Err")
|
||||
local Bytes = require("@formats/core/Bytes")
|
||||
local Input = require("@formats/core/Input")
|
||||
local Types = require("@formats/Types")
|
||||
local Quake = require("@formats/model/mdl/Quake")
|
||||
local HalfLife = require("@formats/model/mdl/HalfLife")
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ contract
|
||||
local Mdl = {
|
||||
name = "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" },
|
||||
caps = { decode = true, encode = false, variants = { "quake", "halflife" }, morph = true, skins = true, animation = true },
|
||||
}
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ types
|
||||
export type DecodeOptions = {
|
||||
palette: (buffer | string)?, -- Quake: the 768-byte palette (default: resolved gfx/palette.lmp, else grey)
|
||||
resolve: ((uri: string) -> (buffer | string)?)?,
|
||||
files: { [string]: buffer | string }?,
|
||||
frame: number?, -- Quake: the frame used as the base POSITION (default 1)
|
||||
morph: boolean?, -- Quake: frames as morph targets + animations (default true)
|
||||
fps: number?, -- Quake: animation frame rate (default 10)
|
||||
bodies: { number }?, -- Half-Life: the model picked for each body part (1-based, default 1)
|
||||
textures: (buffer | string)?, -- Half-Life: the "<name>t.mdl" texture file of a model without textures
|
||||
maxPixels: number?, -- default 2^24
|
||||
maxVertices: number?, -- default 2^24
|
||||
}
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ sniff
|
||||
function Mdl.sniff(r: Bytes.Reader): number
|
||||
local m = r:peek(4)
|
||||
local v = r:peekU8(4)
|
||||
if (m == "IDPO" and v == 6) or (m == "IDST" and v == 10) then
|
||||
return 1
|
||||
end
|
||||
return 0
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ decode
|
||||
function Mdl.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Scene?, Err.Err?)
|
||||
local size = r.limit - r.base
|
||||
if size < 8 then
|
||||
return nil, Err.new(Err.TRUNCATED, "header", 0)
|
||||
end
|
||||
local magic, version = r:peek(4), buffer.readi32(r.buf, r.base + 4)
|
||||
local scene: Types.Scene?, msg: string?
|
||||
if magic == "IDPO" then
|
||||
if version ~= 6 then
|
||||
return nil, Err.new(Err.UNSUPPORTED, "Quake MDL version " .. version, 4)
|
||||
end
|
||||
local pal = if opts and opts.palette then Bytes.toBuffer(opts.palette) else Input.sibling(opts, "gfx/palette.lmp")
|
||||
if pal and buffer.len(pal) < 768 then
|
||||
pal = nil
|
||||
end
|
||||
scene, msg = Quake.decode(r.buf, r.base, size, pal, opts :: any)
|
||||
elseif magic == "IDST" then
|
||||
if version ~= 10 then
|
||||
return nil, Err.new(Err.UNSUPPORTED, "studio model version " .. version .. " (Source engine models need .vvd / .vtx)", 4)
|
||||
end
|
||||
local o: any = opts and table.clone(opts :: any) or {}
|
||||
o.textures = if opts and opts.textures then Bytes.toBuffer(opts.textures) else nil
|
||||
scene, msg = HalfLife.decode(r.buf, r.base, size, o)
|
||||
else
|
||||
return nil, Err.new(Err.CORRUPT, "bad magic", 0)
|
||||
end
|
||||
if not scene then
|
||||
return nil, Err.from(msg)
|
||||
end
|
||||
return scene, nil
|
||||
end
|
||||
|
||||
return Mdl
|
||||
@@ -0,0 +1,275 @@
|
||||
--!strict
|
||||
-- model/smd/Read: Valve SMD text (GoldSrc / Source studiomdl input: version 1) to a Scene. Sections "nodes" (id,
|
||||
-- "name", parent), "skeleton" ("time n" blocks of "bone px py pz rx ry rz", Euler radians, R = Rz Ry Rx; a bone
|
||||
-- missing from a later frame keeps its previous pose), "triangles" (a material line, then three vertex lines "bone px
|
||||
-- py pz nx ny nz u v [links (bone weight)...]": model-space positions, v up), "vertexanimation" (skipped, counted).
|
||||
-- Bones -> joint nodes and a Skin (bind pose = the first skeleton frame), triangles -> one primitive per material
|
||||
-- (welded vertices, counter-clockwise as stored, TEXCOORD_0 v flipped to top-left, JOINTS_0 / WEIGHTS_0: the links,
|
||||
-- the rest of the weight to the parent bone; GoldSrc lines without links: the parent bone), skeleton frames beyond
|
||||
-- the first -> one animation (opts.fps, default 30). An animation SMD (no triangles) is a skeleton + its animation.
|
||||
local Types = require("@formats/Types")
|
||||
local Rig = require("@formats/codecs/model/Rig")
|
||||
|
||||
local Read = {}
|
||||
|
||||
local Scene = Types.Scene
|
||||
local writef32, writeu32 = buffer.writef32, buffer.writeu32
|
||||
|
||||
export type Options = { fps: number?, name: string?, maxVertices: number? }
|
||||
|
||||
type Bone = { id: number, name: string, parent: number }
|
||||
local ZERO: { number } = { 0, 0, 0, 0, 0, 0 }
|
||||
|
||||
-- read(text, opts) -> Scene | nil, message
|
||||
function Read.read(text: string, opts: Options?): (Types.Scene?, string?)
|
||||
local lines: { string } = {}
|
||||
for line in string.gmatch(text, "[^\r\n]*") do
|
||||
table.insert(lines, line)
|
||||
end
|
||||
local i = 1
|
||||
local n = #lines
|
||||
local function nextLine(): string?
|
||||
while i <= n do
|
||||
local l = lines[i]
|
||||
i += 1
|
||||
local s = string.match(l, "^%s*(.-)%s*$") :: string
|
||||
s = string.gsub(s, "%s*//.*$", "") :: string
|
||||
if s ~= "" then
|
||||
return s
|
||||
end
|
||||
end
|
||||
return nil
|
||||
end
|
||||
local bones: { Bone } = {}
|
||||
local byId: { [number]: number } = {} -- SMD bone id -> index into bones (1-based)
|
||||
local frames: { { [number]: { number } } } = {} -- frames[f][bone index] = { px, py, pz, rx, ry, rz }
|
||||
local times: { number } = {}
|
||||
type Batch = { name: string, keys: { [string]: number }, verts: { { number } }, indices: { number } }
|
||||
local batches: { Batch } = {}
|
||||
local byMat: { [string]: Batch } = {}
|
||||
local version: number? = nil
|
||||
local vertexAnimations = 0
|
||||
local maxV = opts and opts.maxVertices or 2 ^ 24
|
||||
local total = 0
|
||||
while true do
|
||||
local l = nextLine()
|
||||
if not l then
|
||||
break
|
||||
end
|
||||
local kw = string.lower(string.match(l, "^(%S+)") or "")
|
||||
if kw == "version" then
|
||||
version = tonumber(string.match(l, "^%S+%s+(%S+)"))
|
||||
elseif kw == "nodes" then
|
||||
while true do
|
||||
local s = nextLine()
|
||||
if not s then
|
||||
return nil, "truncated: nodes without end"
|
||||
end
|
||||
if string.lower(s) == "end" then
|
||||
break
|
||||
end
|
||||
local id, name, parent = string.match(s, '^(%-?%d+)%s+"(.-)"%s+(%-?%d+)')
|
||||
if not id then
|
||||
id, name, parent = string.match(s, "^(%-?%d+)%s+(%S+)%s+(%-?%d+)")
|
||||
end
|
||||
if not id then
|
||||
return nil, "bad node line: " .. s
|
||||
end
|
||||
table.insert(bones, { id = tonumber(id) :: number, name = name :: string, parent = tonumber(parent) :: number })
|
||||
byId[tonumber(id) :: number] = #bones
|
||||
end
|
||||
elseif kw == "skeleton" then
|
||||
local cur: { [number]: { number } }? = nil
|
||||
while true do
|
||||
local s = nextLine()
|
||||
if not s then
|
||||
return nil, "truncated: skeleton without end"
|
||||
end
|
||||
local low = string.lower(s)
|
||||
if low == "end" then
|
||||
break
|
||||
end
|
||||
local tm = string.match(low, "^time%s+(%-?[%d%.]+)")
|
||||
if tm then
|
||||
local prev = frames[#frames]
|
||||
local f: { [number]: { number } } = {}
|
||||
if prev then
|
||||
for k, v in prev do
|
||||
f[k] = v
|
||||
end
|
||||
end
|
||||
table.insert(frames, f)
|
||||
table.insert(times, tonumber(tm) :: number)
|
||||
cur = f
|
||||
else
|
||||
local nums: { number } = {}
|
||||
for tok in string.gmatch(s, "%S+") do
|
||||
table.insert(nums, tonumber(tok) or 0 / 0)
|
||||
end
|
||||
local bi = byId[nums[1]]
|
||||
if not cur or #nums < 7 or not bi then
|
||||
return nil, "bad skeleton line: " .. s
|
||||
end
|
||||
cur[bi] = { nums[2], nums[3], nums[4], nums[5], nums[6], nums[7] }
|
||||
end
|
||||
end
|
||||
elseif kw == "triangles" then
|
||||
while true do
|
||||
local mat = nextLine()
|
||||
if not mat then
|
||||
return nil, "truncated: triangles without end"
|
||||
end
|
||||
if string.lower(mat) == "end" then
|
||||
break
|
||||
end
|
||||
local b = byMat[mat]
|
||||
if not b then
|
||||
b = { name = mat, keys = {}, verts = {}, indices = {} }
|
||||
byMat[mat] = b
|
||||
table.insert(batches, b)
|
||||
end
|
||||
for _ = 1, 3 do
|
||||
local s = nextLine()
|
||||
if not s then
|
||||
return nil, "truncated triangle"
|
||||
end
|
||||
local nums: { number } = {}
|
||||
for tok in string.gmatch(s, "%S+") do
|
||||
local v = tonumber(tok)
|
||||
if not v then
|
||||
return nil, "bad vertex line: " .. s
|
||||
end
|
||||
table.insert(nums, v)
|
||||
end
|
||||
if #nums < 9 then
|
||||
return nil, "short vertex line: " .. s
|
||||
end
|
||||
local id = b.keys[s]
|
||||
if not id then
|
||||
total += 1
|
||||
if total > maxV then
|
||||
return nil, "limit: too many vertices"
|
||||
end
|
||||
table.insert(b.verts, nums)
|
||||
id = #b.verts - 1
|
||||
b.keys[s] = id
|
||||
end
|
||||
table.insert(b.indices, id)
|
||||
end
|
||||
end
|
||||
elseif kw == "vertexanimation" then
|
||||
vertexAnimations += 1
|
||||
while true do
|
||||
local s = nextLine()
|
||||
if not s or string.lower(s) == "end" then
|
||||
break
|
||||
end
|
||||
end
|
||||
else
|
||||
return nil, "unknown section " .. kw
|
||||
end
|
||||
end
|
||||
if version ~= 1 then
|
||||
return nil, if version == nil then "no version line" else "unsupported: SMD version " .. tostring(version)
|
||||
end
|
||||
local scene = Scene.new()
|
||||
scene.meta.up = "z"
|
||||
local root: Types.Node = { name = opts and opts.name or "smd", children = {} }
|
||||
table.insert(scene.nodes, root)
|
||||
scene.roots[1] = 1
|
||||
-- skeleton (bind pose: the first frame)
|
||||
local joints: { Rig.Joint } = {}
|
||||
local bind: { [number]: { number } } = frames[1] or {}
|
||||
for k, bn in bones do
|
||||
local v: { number } = bind[k] or ZERO
|
||||
local parent = if bn.parent >= 0 then byId[bn.parent] or 0 else 0
|
||||
joints[k] = { name = bn.name, parent = parent, translation = { v[1], v[2], v[3] }, rotation = Rig.angles(v[4], v[5], v[6]) }
|
||||
end
|
||||
local jointNodes, skinIndex = Rig.skeleton(scene, joints, "local", 1)
|
||||
-- meshes
|
||||
if #batches > 0 then
|
||||
local mesh: Types.Mesh = { primitives = {} }
|
||||
for _, b in batches do
|
||||
local nv = #b.verts
|
||||
local pos, nrm, uv = buffer.create(nv * 12), buffer.create(nv * 12), buffer.create(nv * 8)
|
||||
local lists: { { number } } = {}
|
||||
for vi, v in b.verts do
|
||||
local o = (vi - 1) * 12
|
||||
writef32(pos, o, v[2])
|
||||
writef32(pos, o + 4, v[3])
|
||||
writef32(pos, o + 8, v[4])
|
||||
writef32(nrm, o, v[5])
|
||||
writef32(nrm, o + 4, v[6])
|
||||
writef32(nrm, o + 8, v[7])
|
||||
writef32(uv, (vi - 1) * 8, v[8])
|
||||
writef32(uv, (vi - 1) * 8 + 4, 1 - v[9])
|
||||
local l: { number } = {}
|
||||
local sum = 0
|
||||
local nl = if #v >= 10 then math.floor(v[10]) else 0
|
||||
for k = 0, nl - 1 do
|
||||
local bi, w = byId[v[11 + k * 2]], v[12 + k * 2]
|
||||
if bi and w then
|
||||
table.insert(l, bi - 1)
|
||||
table.insert(l, w)
|
||||
sum += w
|
||||
end
|
||||
end
|
||||
local parent = byId[v[1]]
|
||||
if parent and sum < 0.999 then
|
||||
table.insert(l, parent - 1)
|
||||
table.insert(l, 1 - sum)
|
||||
end
|
||||
lists[vi] = l
|
||||
end
|
||||
local ib = buffer.create(#b.indices * 4)
|
||||
for k, id in b.indices do
|
||||
writeu32(ib, (k - 1) * 4, id)
|
||||
end
|
||||
local attrs: { [string]: Types.Accessor } = {
|
||||
POSITION = Scene.accessor(pos, "f32", 3, nv),
|
||||
NORMAL = Scene.accessor(nrm, "f32", 3, nv),
|
||||
TEXCOORD_0 = Scene.accessor(uv, "f32", 2, nv),
|
||||
}
|
||||
if #bones > 0 then
|
||||
attrs.JOINTS_0, attrs.WEIGHTS_0 = Rig.influences(lists)
|
||||
end
|
||||
local mat = Scene.material(b.name)
|
||||
mat.metallic = 0
|
||||
table.insert(scene.textures, { name = b.name, uri = b.name })
|
||||
mat.baseColorTexture = { texture = #scene.textures }
|
||||
table.insert(scene.materials, mat)
|
||||
table.insert(mesh.primitives, { attributes = attrs, indices = Scene.accessor(ib, "u32", 1, #b.indices), mode = "triangles" :: any, material = #scene.materials })
|
||||
end
|
||||
table.insert(scene.meshes, mesh)
|
||||
table.insert(scene.nodes, { name = "mesh", children = {}, mesh = #scene.meshes, skin = if #bones > 0 then skinIndex else nil })
|
||||
table.insert(root.children, #scene.nodes)
|
||||
end
|
||||
-- animation
|
||||
if #frames > 1 or (#frames == 1 and #batches == 0) then
|
||||
local fps = opts and opts.fps or 30
|
||||
local t: { number } = {}
|
||||
for k, tm in times do
|
||||
t[k] = (tm - times[1]) / fps
|
||||
end
|
||||
local tracks: { [number]: Rig.Track } = {}
|
||||
for k = 1, #bones do
|
||||
local tr: { number }, rot: { number } = {}, {}
|
||||
for _, f in frames do
|
||||
local v: { number } = f[k] or bind[k] or ZERO
|
||||
table.insert(tr, v[1])
|
||||
table.insert(tr, v[2])
|
||||
table.insert(tr, v[3])
|
||||
local q = Rig.angles(v[4], v[5], v[6])
|
||||
for c = 1, 4 do
|
||||
table.insert(rot, q[c])
|
||||
end
|
||||
end
|
||||
tracks[k] = { translation = tr, rotation = rot }
|
||||
end
|
||||
Rig.animation(scene, opts and opts.name or "animation", jointNodes, t, tracks, "LINEAR")
|
||||
end
|
||||
scene.meta.source = { format = "smd", version = version, bones = #bones, frames = #frames, vertexAnimations = vertexAnimations, kind = if #batches > 0 then "reference" else "animation" }
|
||||
return scene, nil
|
||||
end
|
||||
|
||||
return Read
|
||||
@@ -0,0 +1,250 @@
|
||||
--!strict
|
||||
-- model/smd/Write: a Scene to Valve SMD text (version 1). Bones: the joints of the first skin (parents from the node
|
||||
-- tree: the nearest ancestor that is also a joint), or one "root" bone for a static scene; "skeleton": the bind pose
|
||||
-- (each joint node's TRS: rotation as Euler radians, R = Rz Ry Rx), or, with opts.animation = i, that animation sampled
|
||||
-- at its key times (translation / scale linearly, rotation by normalised linear interpolation); "triangles": every
|
||||
-- triangle of the scene in world space (codecs/model/MeshFlatten), one material line per triangle (the material
|
||||
-- name, else "default"), vertex lines with the Source links (opts.links ~= false; GoldSrc style otherwise: the
|
||||
-- strongest joint as the parent bone only). Animation SMDs (opts.animation set) carry no triangles unless
|
||||
-- opts.triangles is true.
|
||||
local Types = require("@formats/Types")
|
||||
local Mat4 = require("@formats/codecs/model/Mat4")
|
||||
local Flatten = require("@formats/codecs/model/MeshFlatten")
|
||||
|
||||
local Write = {}
|
||||
|
||||
export type Options = { animation: number?, links: boolean?, triangles: boolean? }
|
||||
|
||||
local fmt = string.format
|
||||
|
||||
local function num(v: number): string
|
||||
if v ~= v or v == math.huge or v == -math.huge then
|
||||
return "0"
|
||||
end
|
||||
local s = fmt("%.6f", v)
|
||||
if s == "-0.000000" then
|
||||
return "0.000000"
|
||||
end
|
||||
return s
|
||||
end
|
||||
|
||||
-- quaternion -> x, y, z Euler radians with R = Rz(z) Ry(y) Rx(x)
|
||||
local function angles(q: { number }): (number, number, number)
|
||||
local m = Mat4.fromQuat(q)
|
||||
local r31, r32, r33, r21, r11 = m[3], m[7], m[11], m[2], m[1]
|
||||
local y = math.asin(math.clamp(-r31, -1, 1))
|
||||
local x, z
|
||||
if math.abs(r31) < 0.9999999 then
|
||||
x = math.atan2(r32, r33)
|
||||
z = math.atan2(r21, r11)
|
||||
else
|
||||
x = math.atan2(-m[10], m[6])
|
||||
z = 0
|
||||
end
|
||||
return x, y, z
|
||||
end
|
||||
|
||||
local function lerp(a: { number }, b: { number }, t: number): { number }
|
||||
local out: { number } = {}
|
||||
for i = 1, #a do
|
||||
out[i] = a[i] + (b[i] - a[i]) * t
|
||||
end
|
||||
return out
|
||||
end
|
||||
|
||||
-- the value of channel ch at time tm (nil when the channel has no keys)
|
||||
local function sample(ch: Types.Channel, tm: number): { number }?
|
||||
local input, output = ch.input, ch.output
|
||||
local n = input.count
|
||||
if n == 0 then
|
||||
return nil
|
||||
end
|
||||
local comps = if ch.path == "rotation" then 4 else 3
|
||||
local function key(k: number): { number }
|
||||
local out: { number } = {}
|
||||
for c = 0, comps - 1 do
|
||||
out[c + 1] = buffer.readf32(output.data, (k * comps + c) * 4)
|
||||
end
|
||||
return out
|
||||
end
|
||||
local times = input.data
|
||||
if tm <= buffer.readf32(times, 0) then
|
||||
return key(0)
|
||||
end
|
||||
for k = 1, n - 1 do
|
||||
local t1 = buffer.readf32(times, k * 4)
|
||||
if tm <= t1 then
|
||||
local t0 = buffer.readf32(times, (k - 1) * 4)
|
||||
local f = if ch.interpolation == "STEP" or t1 <= t0 then 0 else (tm - t0) / (t1 - t0)
|
||||
local a, b = key(k - 1), key(k)
|
||||
if comps == 4 then
|
||||
if a[1] * b[1] + a[2] * b[2] + a[3] * b[3] + a[4] * b[4] < 0 then
|
||||
b = { -b[1], -b[2], -b[3], -b[4] }
|
||||
end
|
||||
local q = lerp(a, b, f)
|
||||
local l = math.sqrt(q[1] ^ 2 + q[2] ^ 2 + q[3] ^ 2 + q[4] ^ 2)
|
||||
return if l > 0 then { q[1] / l, q[2] / l, q[3] / l, q[4] / l } else a
|
||||
end
|
||||
return lerp(a, b, f)
|
||||
end
|
||||
end
|
||||
return key(n - 1)
|
||||
end
|
||||
|
||||
-- write(scene, opts) -> text | nil, message
|
||||
function Write.write(scene: Types.Scene, opts: Options?): (string?, string?)
|
||||
if type(scene) ~= "table" or scene.kind ~= "scene" then
|
||||
return nil, "expected a Scene"
|
||||
end
|
||||
local out: { string } = { "version 1", "nodes" }
|
||||
local skin = scene.skins and scene.skins[1]
|
||||
local joints: { number } = if skin then skin.joints else {}
|
||||
local jointOf: { [number]: number } = {} -- node index -> bone id (0-based)
|
||||
for k, nd in joints do
|
||||
jointOf[nd] = k - 1
|
||||
end
|
||||
local parentOf: { [number]: number } = {}
|
||||
for ni, nd in scene.nodes do
|
||||
for _, c in nd.children do
|
||||
parentOf[c] = ni
|
||||
end
|
||||
end
|
||||
if #joints == 0 then
|
||||
table.insert(out, '0 "root" -1')
|
||||
else
|
||||
for k, nd in joints do
|
||||
local p = parentOf[nd]
|
||||
while p and jointOf[p] == nil do
|
||||
p = parentOf[p]
|
||||
end
|
||||
local name = scene.nodes[nd] and scene.nodes[nd].name or ("bone" .. (k - 1))
|
||||
table.insert(out, fmt('%d "%s" %d', k - 1, string.gsub(name, '"', "'"), if p then jointOf[p] else -1))
|
||||
end
|
||||
end
|
||||
table.insert(out, "end")
|
||||
table.insert(out, "skeleton")
|
||||
local function pose(tr: { number }?, rot: { number }?): string
|
||||
local t = tr or { 0, 0, 0 }
|
||||
local x, y, z = angles(rot or { 0, 0, 0, 1 })
|
||||
return table.concat({ num(t[1]), num(t[2]), num(t[3]), num(x), num(y), num(z) }, " ")
|
||||
end
|
||||
local animIndex = opts and opts.animation
|
||||
local anim = animIndex and scene.animations[animIndex]
|
||||
if animIndex and not anim then
|
||||
return nil, "no animation " .. tostring(animIndex)
|
||||
end
|
||||
if anim then
|
||||
local keyset: { [number]: boolean } = {}
|
||||
for _, ch in anim.channels do
|
||||
for k = 0, ch.input.count - 1 do
|
||||
keyset[buffer.readf32(ch.input.data, k * 4)] = true
|
||||
end
|
||||
end
|
||||
local keys: { number } = {}
|
||||
for tm in keyset do
|
||||
table.insert(keys, tm)
|
||||
end
|
||||
table.sort(keys)
|
||||
local byNode: { [number]: { [string]: Types.Channel } } = {}
|
||||
for _, ch in anim.channels do
|
||||
local m = byNode[ch.node] or {}
|
||||
byNode[ch.node] = m
|
||||
m[ch.path] = ch
|
||||
end
|
||||
for f, tm in keys do
|
||||
table.insert(out, "time " .. (f - 1))
|
||||
for k, nd in joints do
|
||||
local node = scene.nodes[nd]
|
||||
local chs: { [string]: Types.Channel } = byNode[nd] or {}
|
||||
local tch, rch = chs.translation, chs.rotation
|
||||
local tr = if tch then sample(tch, tm) else node.translation
|
||||
local rot = if rch then sample(rch, tm) else node.rotation
|
||||
table.insert(out, (k - 1) .. " " .. pose(tr, rot))
|
||||
end
|
||||
end
|
||||
else
|
||||
table.insert(out, "time 0")
|
||||
if #joints == 0 then
|
||||
table.insert(out, "0 " .. pose(nil, nil))
|
||||
else
|
||||
for k, nd in joints do
|
||||
local node = scene.nodes[nd]
|
||||
local tr, rot = node.translation, node.rotation
|
||||
if node.matrix then
|
||||
local t, r = Mat4.decompose(node.matrix)
|
||||
tr, rot = t, r
|
||||
end
|
||||
table.insert(out, (k - 1) .. " " .. pose(tr, rot))
|
||||
end
|
||||
end
|
||||
end
|
||||
table.insert(out, "end")
|
||||
-- triangles
|
||||
if not anim or (opts and opts.triangles) then
|
||||
local m, err = Flatten.merge(scene, function(name: string): boolean
|
||||
return name == "NORMAL" or name == "TEXCOORD_0" or name == "JOINTS_0" or name == "WEIGHTS_0"
|
||||
end, { triangulate = true })
|
||||
if not m then
|
||||
return nil, err
|
||||
end
|
||||
local A = m.attrs
|
||||
local P, N, UV, J, W = A.POSITION, A.NORMAL, A.TEXCOORD_0, A.JOINTS_0, A.WEIGHTS_0
|
||||
local links = not (opts and opts.links == false)
|
||||
local nbones = math.max(1, #joints)
|
||||
if #m.corners > 0 then
|
||||
table.insert(out, "triangles")
|
||||
for _, part in m.parts do
|
||||
local mat = part.prim.material and scene.materials[part.prim.material]
|
||||
local mname = if mat and mat.name and mat.name ~= "" then mat.name else "default"
|
||||
for f = part.firstFace, part.firstFace + part.faceCount - 1 do
|
||||
table.insert(out, mname)
|
||||
for c = 0, 2 do
|
||||
local v = m.corners[f * 3 + c + 1]
|
||||
local px, py, pz = P.values[v * 3 + 1], P.values[v * 3 + 2], P.values[v * 3 + 3]
|
||||
local nx, ny, nz = 0, 0, 1
|
||||
if N then
|
||||
nx, ny, nz = N.values[v * 3 + 1], N.values[v * 3 + 2], N.values[v * 3 + 3]
|
||||
end
|
||||
local u, w = 0, 0
|
||||
if UV then
|
||||
local k = UV.components
|
||||
u, w = UV.values[v * k + 1], UV.values[v * k + 2]
|
||||
end
|
||||
local parent = 0
|
||||
local lk: { string } = {}
|
||||
if J and W and #joints > 0 then
|
||||
local jk, wk = J.components, W.components
|
||||
local best, bestW = 0, -1
|
||||
local count = 0
|
||||
for c2 = 1, math.min(4, jk, wk) do
|
||||
local jw = W.values[v * wk + c2]
|
||||
local jj = math.clamp(math.floor(J.values[v * jk + c2] or 0), 0, nbones - 1)
|
||||
if jw and jw > 0 then
|
||||
count += 1
|
||||
table.insert(lk, fmt("%d %s", jj, num(jw)))
|
||||
if jw > bestW then
|
||||
best, bestW = jj, jw
|
||||
end
|
||||
end
|
||||
end
|
||||
parent = best
|
||||
if count > 0 then
|
||||
table.insert(lk, 1, tostring(count))
|
||||
end
|
||||
end
|
||||
local line = fmt("%d %s %s %s %s %s %s %s %s", parent, num(px), num(py), num(pz), num(nx), num(ny), num(nz), num(u), num(1 - w))
|
||||
if links and #lk > 0 then
|
||||
line ..= " " .. table.concat(lk, " ")
|
||||
end
|
||||
table.insert(out, line)
|
||||
end
|
||||
end
|
||||
end
|
||||
table.insert(out, "end")
|
||||
end
|
||||
end
|
||||
table.insert(out, "")
|
||||
return table.concat(out, "\n"), nil
|
||||
end
|
||||
|
||||
return Write
|
||||
@@ -0,0 +1,69 @@
|
||||
--!strict
|
||||
-- model/smd: Valve SMD (studiomdl data, GoldSrc and Source: "version 1" text), read and write. Written from the
|
||||
-- Valve Developer Community "SMD file format" page; no code taken. Read: model/smd/Read (bones -> joint nodes + a
|
||||
-- Skin, triangles -> a primitive per material with JOINTS_0 / WEIGHTS_0, skeleton frames -> an animation; animation
|
||||
-- SMDs too). Write: model/smd/Write (the first skin's joints or one root bone, the bind pose or opts.animation,
|
||||
-- world-space triangles with Source weight links). Units as stored (inches in Valve's games), z up.
|
||||
-- Not supported: vertex animation (flex) sections (skipped, counted in meta.source.vertexAnimations).
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ requires
|
||||
local Err = require("@formats/core/Err")
|
||||
local Bytes = require("@formats/core/Bytes")
|
||||
local Sniff = require("@formats/core/Sniff")
|
||||
local Types = require("@formats/Types")
|
||||
local Read = require("@formats/model/smd/Read")
|
||||
local Write = require("@formats/model/smd/Write")
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ contract
|
||||
local Smd = {
|
||||
name = "smd",
|
||||
category = "model",
|
||||
extensions = { "smd" },
|
||||
mime = { "model/x-smd", "text/plain" },
|
||||
deps = { "core/Err", "core/Bytes", "core/Sniff", "Types", "codecs/model/Mat4", "codecs/model/MeshFlatten", "codecs/model/Rig" },
|
||||
caps = { decode = true, encode = true, skins = true, animation = true },
|
||||
}
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ types
|
||||
export type DecodeOptions = {
|
||||
fps: number?, -- skeleton frames per second (default 30)
|
||||
name: string?, -- the root node / animation name (the api passes the file name)
|
||||
maxVertices: number?, -- default 2^24
|
||||
}
|
||||
export type EncodeOptions = Write.Options
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ sniff
|
||||
function Smd.sniff(r: Bytes.Reader): number
|
||||
local head = Sniff.text(r, 256, true)
|
||||
head = string.gsub(head, "^//[^\n]*\n%s*", "")
|
||||
if string.match(head, "^version%s+1%s") and string.find(head, "nodes", 1, true) then
|
||||
return 0.9
|
||||
end
|
||||
return 0
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ decode
|
||||
function Smd.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Scene?, Err.Err?)
|
||||
local text = Sniff.dropBom(r:string(r:remaining()))
|
||||
local o: any = opts and table.clone(opts :: any) or {}
|
||||
if type(o.name) == "string" then
|
||||
o.name = string.match(o.name, "([^/\\]+)$") or o.name
|
||||
o.name = string.gsub(o.name, "%.[sS][mM][dD]$", "")
|
||||
end
|
||||
local scene, msg = Read.read(text, o)
|
||||
if not scene then
|
||||
return nil, Err.from(msg)
|
||||
end
|
||||
return scene, nil
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ encode
|
||||
function Smd.encode(scene: Types.Scene, opts: EncodeOptions?): (buffer?, Err.Err?)
|
||||
local text, msg = Write.write(scene, opts)
|
||||
if not text then
|
||||
return nil, Err.new(Err.ARG, tostring(msg))
|
||||
end
|
||||
return buffer.fromstring(text), nil
|
||||
end
|
||||
|
||||
return Smd
|
||||
Reference in new issue
Block a user