archive/wad2, image/lmp, image/spr, data/q3shader, data/q3skin

WAD2 / WAD3 with miptex / qpic / conchars / font / palette images and addImage; Quake .lmp pictures, palette and
colormap (palette never embedded); Quake / Half-Life / SPR32 sprites with frame groups; Quake III shader scripts and
.skin files. Miptex gains qpic decode / encode and palette mapping; Pixels.keyed keeps the key colour (alpha 0).
This commit is contained in:
4DBug committed 2026-11-01 19:17:00 -06:00
1 parent 67e116a6c6
commit 175ca9e823
23 files changed
+5380 -1143

No files matched your search

+6 -1
View File
@@ -44,7 +44,7 @@ print(F.detect(webp), #F.formats()) -- "webp", the format list
## Formats
<!-- formats:begin -->
175 formats. Generated from the format contracts by `tools/gen_registry.py`; [docs/FORMATS.md](docs/FORMATS.md)
180 formats. Generated from the format contracts by `tools/gen_registry.py`; [docs/FORMATS.md](docs/FORMATS.md)
adds each format's capabilities.
| Category | Format | Extensions | Read | Write |
@@ -61,11 +61,13 @@ adds each format's capabilities.
| Images | ilbm | .iff .ilbm .lbm .pbm | yes | yes |
| Images | jpeg | .jpg .jpeg .jpe .jfif | yes | yes |
| Images | ktx | .ktx2 .ktx | yes | yes |
| Images | lmp | .lmp | yes | yes |
| Images | pcx | .pcx .pcc .dcx | yes | yes |
| Images | png | .png .apng | yes | yes |
| Images | pnm | .pnm .pbm .pgm .ppm .pam .pfm | yes | yes |
| Images | qoi | .qoi | yes | yes |
| Images | sgi | .sgi .rgb .rgba .bw .int .inta | yes | yes |
| Images | spr | .spr | yes | yes |
| Images | sunras | .ras .sun .rs .im1 .im8 .im24 .im32 | yes | yes |
| Images | tga | .tga .icb .vda .vst .tpic | yes | yes |
| Images | tiff | .tif .tiff | yes | yes |
@@ -176,6 +178,7 @@ adds each format's capabilities.
| Archives | uu | .uu .uue .xxe .b64 | yes | yes |
| Archives | vpk | .vpk | yes | yes |
| Archives | wad | .wad | yes | yes |
| Archives | wad2 | .wad | yes | yes |
| Archives | xz | .xz .txz .lzma | yes | - |
| Archives | yenc | .yenc .ync | yes | yes |
| Archives | z | .z .taz .tz | yes | yes |
@@ -189,6 +192,8 @@ adds each format's capabilities.
| Data | msgpack | .msgpack .mpk | yes | yes |
| Data | nbt | .nbt .dat .mcstructure .dat_old | yes | yes |
| Data | plist | .plist | yes | yes |
| Data | q3shader | .shader | yes | yes |
| Data | q3skin | .skin | yes | yes |
| Data | snbt | .snbt | yes | yes |
| Data | toml | .toml | yes | yes |
| Data | xml | .xml .xsd .xsl .xslt .rss .atom .xhtml | yes | yes |
+1221 -18
View File
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
+1221 -18
View File
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
+5
View File
@@ -17,11 +17,13 @@ is tested under both runtimes (luau `--codegen -O2` and LuaJIT through the build
| image | ilbm | .iff .ilbm .lbm .pbm | yes | yes | alpha: true, palette: true, depths: 1, 2, 3, 4, 5, 6, 7, 8, 24, 32 | `tests/image/ilbm.luau` |
| image | jpeg | .jpg .jpeg .jpe .jfif | yes | yes | lossy: true, alpha: false, depths: 8, 12, progressive: true, arithmetic: true | `tests/image/jpeg.luau` |
| image | ktx | .ktx2 .ktx | yes | yes | alpha: true, float: true, mipmaps: true, cubemap: true, compressed: "bc1", "bc2", "bc3", "bc4", "bc5", "bc6h", "bc7", "etc1", "etc2", "eac" | `tests/image/ktx.luau` |
| image | lmp | .lmp | yes | yes | alpha: true, depths: 8, variants: "qpic", "palette", "colormap" | `tests/image/lmp.luau` |
| image | pcx | .pcx .pcc .dcx | yes | yes | alpha: true, palette: true, depths: 1, 2, 4, 8, 24, 32 | `tests/image/pcx.luau` |
| image | png | .png .apng | yes | yes | animation: true, alpha: true, depths: 1, 2, 4, 8, 16 | `tests/image/png.luau` |
| image | pnm | .pnm .pbm .pgm .ppm .pam .pfm | yes | yes | alpha: true, depths: 1, 8, 16, 32, float: true | `tests/image/pnm.luau` |
| image | qoi | .qoi | yes | yes | alpha: true, depths: 8 | `tests/image/qoi.luau` |
| image | sgi | .sgi .rgb .rgba .bw .int .inta | yes | yes | alpha: true, depths: 8, 16 | `tests/image/sgi.luau` |
| image | spr | .spr | yes | yes | alpha: true, animation: true, variants: "quake", "halflife", "spr32" | `tests/image/spr.luau` |
| image | sunras | .ras .sun .rs .im1 .im8 .im24 .im32 | yes | yes | alpha: true, palette: true, depths: 1, 8, 24, 32 | `tests/image/sunras.luau` |
| image | tga | .tga .icb .vda .vst .tpic | yes | yes | alpha: true, palette: true, depths: 8, 15, 16, 24, 32 | `tests/image/tga.luau` |
| image | tiff | .tif .tiff | yes | yes | alpha: true, pages: true, depths: 1, 2, 4, 8, 16, 32, float: true | `tests/image/tiff.luau` |
@@ -132,6 +134,7 @@ is tested under both runtimes (luau `--codegen -O2` and LuaJIT through the build
| archive | uu | .uu .uue .xxe .b64 | yes | yes | variants: "uu", "xx", "base64" | `tests/archive/uu.luau` |
| archive | vpk | .vpk | yes | yes | versions: 1, 2, multipart: true | `tests/archive/vpk.luau` |
| archive | wad | .wad | yes | yes | images: true, maps: true, variants: "iwad", "pwad" | `tests/archive/wad.luau` |
| archive | wad2 | .wad | yes | yes | images: true, variants: "wad2", "wad3" | `tests/archive/wad2.luau` |
| archive | xz | .xz .txz .lzma | yes | - | stream: true, filters: "lzma2", "lzma", "delta", "x86", "powerpc", "arm", "armthumb", "sparc", "arm64" | `tests/archive/xz.luau` |
| archive | yenc | .yenc .ync | yes | yes | multipart: true | `tests/archive/yenc.luau` |
| archive | z | .z .taz .tz | yes | yes | stream: true, bits: 9, 16 | `tests/archive/z.luau` |
@@ -145,6 +148,8 @@ is tested under both runtimes (luau `--codegen -O2` and LuaJIT through the build
| data | msgpack | .msgpack .mpk | yes | yes | binary: true, ordered: true | `tests/data/msgpack.luau` |
| data | nbt | .nbt .dat .mcstructure .dat_old | yes | yes | binary: true, ordered: true, typed: true | `tests/data/nbt.luau` |
| data | plist | .plist | yes | yes | binary: "read", ordered: true | `tests/data/plist.luau` |
| data | q3shader | .shader | yes | yes | | `tests/data/q3shader.luau` |
| data | q3skin | .skin | yes | yes | | `tests/data/q3skin.luau` |
| data | snbt | .snbt | yes | yes | ordered: true, typed: true | `tests/data/snbt.luau` |
| data | toml | .toml | yes | yes | ordered: true, dates: true | `tests/data/toml.luau` |
| data | xml | .xml .xsd .xsl .xslt .rss .atom .xhtml | yes | yes | namespaces: true, streaming: true | `tests/data/xml.luau` |
+60
View File
@@ -158,6 +158,18 @@ local list: { Entry } = {
return require("@rosetta/image/ktx")
end,
},
{
name = "lmp",
category = "image",
path = "image/lmp",
extensions = { "lmp" },
mime = { "image/x-quake-lmp" },
deps = { "core/Err", "core/Bytes", "core/Input", "Types", "codecs/image/Pixels", "codecs/image/Miptex" },
caps = { decode = true, encode = true, alpha = true, depths = { 8 }, variants = { "qpic", "palette", "colormap" } },
load = function()
return require("@rosetta/image/lmp")
end,
},
{
name = "pcx",
category = "image",
@@ -218,6 +230,18 @@ local list: { Entry } = {
return require("@rosetta/image/sgi")
end,
},
{
name = "spr",
category = "image",
path = "image/spr",
extensions = { "spr" },
mime = { "image/x-quake-sprite" },
deps = { "core/Err", "core/Bytes", "core/Input", "Types", "codecs/image/Pixels", "codecs/image/Miptex" },
caps = { decode = true, encode = true, alpha = true, animation = true, variants = { "quake", "halflife", "spr32" } },
load = function()
return require("@rosetta/image/spr")
end,
},
{
name = "sunras",
category = "image",
@@ -1538,6 +1562,18 @@ local list: { Entry } = {
return require("@rosetta/archive/wad")
end,
},
{
name = "wad2",
category = "archive",
path = "archive/wad2",
extensions = { "wad" },
mime = { "application/x-quake-wad" },
deps = { "core/Err", "core/Bytes", "core/Input", "Types", "containers/Archive", "codecs/image/Pixels", "codecs/image/Miptex" },
caps = { decode = true, encode = true, images = true, variants = { "wad2", "wad3" } },
load = function()
return require("@rosetta/archive/wad2")
end,
},
{
name = "xz",
category = "archive",
@@ -1694,6 +1730,30 @@ local list: { Entry } = {
return require("@rosetta/data/plist")
end,
},
{
name = "q3shader",
category = "data",
path = "data/q3shader",
extensions = { "shader" },
mime = { "text/x-quake3-shader" },
deps = { "core/Err", "core/Bytes" },
caps = { decode = true, encode = true },
load = function()
return require("@rosetta/data/q3shader")
end,
},
{
name = "q3skin",
category = "data",
path = "data/q3skin",
extensions = { "skin" },
mime = { "text/x-quake3-skin" },
deps = { "core/Err", "core/Bytes" },
caps = { decode = true, encode = true },
load = function()
return require("@rosetta/data/q3skin")
end,
},
{
name = "snbt",
category = "data",
+280
View File
@@ -0,0 +1,280 @@
--!strict
-- archive/wad2: Quake WAD2 and Half-Life WAD3 texture / graphics WADs (wad.h of the Quake source, the GoldSrc WAD3
-- layout; no code taken), read and write. Lumps by name (repeats "<name>~<n>"); Wad2.image decodes miptex, qpic,
-- conchars, palette and GoldSrc font lumps through codecs/image/Miptex (Quake 1 needs a palette: the WAD's own
-- "palette" lump, opts.palette or gfx/palette.lmp through files / resolve; else grey). Not supported: compressed lumps.
-- ------------------------------------------------------------------------------------------------ requires
local Err = require("@rosetta/core/Err")
local Bytes = require("@rosetta/core/Bytes")
local Input = require("@rosetta/core/Input")
local Types = require("@rosetta/Types")
local Archive = require("@rosetta/containers/Archive")
local Pixels = require("@rosetta/codecs/image/Pixels")
local Miptex = require("@rosetta/codecs/image/Miptex")
-- ------------------------------------------------------------------------------------------------ contract
local Wad2 = {
name = "wad2",
category = "archive",
extensions = { "wad" },
mime = { "application/x-quake-wad" },
deps = { "core/Err", "core/Bytes", "core/Input", "Types", "containers/Archive", "codecs/image/Pixels", "codecs/image/Miptex" },
caps = { decode = true, encode = true, images = true, variants = { "wad2", "wad3" } },
}
-- ------------------------------------------------------------------------------------------------ types
export type DecodeOptions = { maxEntries: number? } -- default 1e6
export type EncodeOptions = { variant: ("wad2" | "wad3")? } -- default: the source's, else wad3 when a lump is type 0x43
export type ImageOptions = {
palette: (buffer | string)?, -- 768 bytes (Quake 1)
mip: number?, -- miptex level 0..3, default 0
keyed: boolean?, -- index 255 transparent; default: qpics, conchars and '{' textures
resolve: ((uri: string) -> (buffer | string)?)?,
files: { [string]: buffer | string }?,
}
export type AddOptions = {
kind: ("miptex" | "qpic")?, -- default "miptex"
palette: (buffer | string)?, -- 768 bytes; required for WAD2 lumps, made by median cut for WAD3 without it
}
-- ------------------------------------------------------------------------------------------------ constants
local T = Miptex.TYPES
-- ------------------------------------------------------------------------------------------------ sniff
function Wad2.sniff(r: Bytes.Reader): number
if r:remaining() < 12 then
return 0
end
local m = r:peek(4)
return if m == "WAD2" or m == "WAD3" then 0.9 else 0
end
-- ------------------------------------------------------------------------------------------------ decode
local function encode(archive: any, opts: any?): (buffer?, Err.Err?)
return Wad2.encode(archive, opts)
end
function Wad2.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?)
local size = r.limit - r.base
local lumps, msg, magic = Miptex.wad(r.buf, r.base, size, opts and opts.maxEntries)
if not lumps then
return nil, Err.from(msg, 0)
end
local a = Archive.new("wad2", encode)
local seen: { [string]: number } = {}
for _, l in lumps do
if l.compression ~= 0 then
return nil, Err.new(Err.UNSUPPORTED, "compressed lump " .. l.name)
end
local entry = l.name
local k = seen[string.lower(entry)]
if k then
seen[string.lower(entry)] = k + 1
entry = entry .. "~" .. (k + 1)
else
seen[string.lower(entry)] = 1
end
Archive.put(a, { name = entry, size = l.disksize, dir = false, method = "store", type = l.type, lump = l.name, load = Archive.slice(r.buf, r.base + l.offset, l.disksize) })
end
a.meta.source = { format = "wad2", variant = string.lower(magic :: string), lumps = #lumps }
a.meta.wad2 = { buf = r.buf, base = r.base, lumps = lumps, goldsrc = magic == "WAD3" }
return a, nil
end
-- ------------------------------------------------------------------------------------------------ encode
local function guessType(name: string, data: buffer, goldsrc: boolean): number
local n = buffer.len(data)
if string.lower(name) == "palette" and n == 768 then
return T.palette
end
if n >= 40 then
local w, h = buffer.readu32(data, 16), buffer.readu32(data, 20)
if w > 0 and h > 0 and w < 65536 and h < 65536 and buffer.readu32(data, 24) == 40 then
return if goldsrc then 0x43 else T.miptex
end
end
if n >= 8 then
local w, h = buffer.readu32(data, 0), buffer.readu32(data, 4)
if w > 0 and h > 0 and 8 + w * h <= n then
return T.qpic
end
end
return T.miptex
end
function Wad2.encode(archive: any, opts: EncodeOptions?): (buffer?, Err.Err?)
local items, err = Archive.collect(archive)
if not items then
return nil, err
end
local src = type(archive) == "table" and type(archive.meta) == "table" and archive.meta.source
local variant = opts and opts.variant or (if type(src) == "table" and src.format == "wad2" then src.variant else nil)
if not variant then
variant = "wad2"
for _, it in items do
if (it.entry :: any).type == 0x43 then
variant = "wad3"
end
end
end
if variant ~= "wad2" and variant ~= "wad3" then
return nil, Err.new(Err.ARG, "variant must be wad2 or wad3")
end
local list: { { name: string, data: buffer, type: number } } = {}
for _, it in items do
if not it.entry.dir then
local e: any = it.entry
local name = e.lump or string.gsub(string.match(e.name, "([^/\\]*)$") or e.name, "~%d+$", "")
if #name == 0 or #name > 15 then
return nil, Err.new(Err.ARG, "lump name must be 1..15 bytes: " .. e.name)
end
local typ = if type(e.type) == "number" then e.type else guessType(name, it.data, variant == "wad3")
table.insert(list, { name = name, data = it.data, type = typ })
end
end
local w = Bytes.writer()
w:string(if variant == "wad3" then "WAD3" else "WAD2")
w:u32le(#list)
w:u32le(0)
local offs: { number } = {}
for i, l in list do
offs[i] = w:tell()
w:bytes(l.data)
w:fill(0, (4 - buffer.len(l.data) % 4) % 4)
end
local dir = w:tell()
for i, l in list do
w:u32le(offs[i])
w:u32le(buffer.len(l.data))
w:u32le(buffer.len(l.data))
w:u8(l.type)
w:u8(0)
w:u16le(0)
w:string(l.name)
w:fill(0, 16 - #l.name)
end
w:setU32le(8, dir)
return w:finish(), nil
end
-- ------------------------------------------------------------------------------------------------ extras
local function info(a: any): any
return type(a) == "table" and type(a.meta) == "table" and a.meta.wad2 or nil
end
function Wad2.new(variant: ("wad2" | "wad3")?): any
local a = Archive.new("wad2", encode)
a.meta.source = { format = "wad2", variant = variant or "wad2" }
return a
end
function Wad2.lumps(a: any): { Miptex.Lump }?
local w = info(a)
return w and w.lumps
end
-- the WAD's own "palette" lump (gfx.wad) as a 1024-byte rgba8 palette
function Wad2.palette(a: any): buffer?
local w = info(a)
local l = w and Miptex.find(w.lumps, "palette")
if l and l.disksize >= 768 then
return Pixels.palette(w.buf, w.base + l.offset, 256)
end
return nil
end
function Wad2.image(a: any, name: string, opts: ImageOptions?): (Types.Image?, Err.Err?)
local w = info(a)
if not w then
return nil, Err.new(Err.ARG, "expected a decoded WAD2 / WAD3 archive")
end
local l = Miptex.find(w.lumps, tostring(name))
if not l then
return nil, Err.new(Err.ARG, "no lump named " .. tostring(name))
end
local b, at, size = w.buf, w.base + l.offset, l.disksize
local pal: buffer? = nil
if not w.goldsrc then
local raw = if opts and opts.palette then Bytes.toBuffer(opts.palette) else nil
if raw and buffer.len(raw) >= 768 then
pal = Pixels.palette(raw, 0, 256)
else
pal = Wad2.palette(a)
if not pal then
local lmp = Input.sibling(opts, "gfx/palette.lmp")
pal = if lmp and buffer.len(lmp) >= 768 then Pixels.palette(lmp, 0, 256) else nil
end
end
end
local keyed: boolean? = if opts then opts.keyed else nil
local img: Types.Image?, msg: string?
local kind: string
if l.type == T.palette and size >= 768 then
kind = "palette"
local out = Types.Image.new(16, 16)
buffer.copy(out.pixels, 0, Pixels.palette(b, at, 256), 0, 1024)
img = out
elseif string.lower(l.name) == "conchars" and size == 128 * 128 then
-- gfx.wad's console font: raw 128 x 128 pixels, no header, index 0 transparent
kind = "conchars"
local out = Types.Image.new(128, 128)
Pixels.indexed(b, at, 128, 8, out.pixels, 128, 128, true, Pixels.keyed(pal or Pixels.grey(), if keyed == false then -1 else 0))
img = out
elseif l.type == T.qpic then
kind = "qpic"
img, msg = Miptex.qpic(b, at, size, { palette = pal, goldsrc = w.goldsrc, keyed = keyed } :: any)
elseif l.type == T.font and w.goldsrc and size >= 16 + 1024 then
-- GoldSrc qfont_t: width (256), height, rowcount, rowheight, charinfo[256] (u16 offset, u16 width), pixels, palette
kind = "font"
local fw, fh = buffer.readu32(b, at), buffer.readu32(b, at + 4)
local p = 16 + 1024 + fw * fh
if fw == 0 or fh == 0 or fw * fh > 2 ^ 24 or p + 2 > size then
return nil, Err.new(Err.CORRUPT, "bad font lump " .. l.name, l.offset)
end
local n = buffer.readu16(b, at + p)
local fpal = if n > 0 and n <= 256 and p + 2 + n * 3 <= size then Pixels.palette(b, at + p + 2, n) else Pixels.grey()
local out = Types.Image.new(fw, fh)
Pixels.indexed(b, at + 16 + 1024, fw, 8, out.pixels, fw, fh, true, if keyed == false then fpal else Pixels.keyed(fpal, 255))
local glyphs = {}
for c = 0, 255 do
glyphs[c + 1] = { offset = buffer.readu16(b, at + 16 + c * 4), width = buffer.readu16(b, at + 18 + c * 4) }
end
out.meta.font = { rows = buffer.readu32(b, at + 8), rowHeight = buffer.readu32(b, at + 12), glyphs = glyphs }
img = out
else
kind = "miptex"
img, msg = Miptex.decode(b, at, size, { palette = pal, goldsrc = w.goldsrc, mip = if opts then opts.mip else nil, keyed = keyed } :: any)
end
if not img then
return nil, Err.from(msg, l.offset)
end
img.meta.source = { format = "wad2", kind = kind, lump = l.name, type = l.type, palette = w.goldsrc or pal ~= nil }
return img, nil
end
-- adds an rgba8 image as a miptex (sizes multiples of 16) or qpic lump; WAD3 lumps carry their own palette
function Wad2.addImage(a: any, name: string, img: Types.Image, opts: AddOptions?): (boolean, Err.Err?)
if type(img) ~= "table" or img.format ~= "rgba8" then
return false, Err.new(Err.ARG, "expected an rgba8 Image")
end
local src = type(a) == "table" and type(a.meta) == "table" and a.meta.source
local goldsrc = type(src) == "table" and src.variant == "wad3"
local raw = opts and opts.palette and Bytes.toBuffer(opts.palette)
local pal = if raw and buffer.len(raw) >= 768 then Pixels.palette(raw, 0, 256) else nil
local kind = opts and opts.kind or "miptex"
local data, msg
if kind == "qpic" then
data, msg = Miptex.encodeQpic(img, pal, goldsrc)
else
data, msg = Miptex.encode(img, name, pal, goldsrc)
end
if not data then
return false, Err.new(Err.ARG, msg or "cannot encode")
end
Archive.put(a, { name = name, size = buffer.len(data), dir = false, method = "store", lump = name, data = data,
type = if kind == "qpic" then T.qpic elseif goldsrc then 0x43 else T.miptex })
return true, nil
end
return Wad2
+99 -15
View File
@@ -113,30 +113,28 @@ function Miptex.encode(img: Types.Image, name: string, palette: buffer?, goldsrc
if #name > 15 then
return nil, "miptex name over 15 bytes"
end
local colors: { { number } }
if palette then
colors = Pixels.colorList(palette)
elseif goldsrc then
colors = Quantize.palette(img.pixels, w, h, 256)
else
if not palette and not goldsrc then
return nil, "a Quake miptex needs a palette"
end
local keyed = string.sub(name, 1, 1) == "{"
local _, colors = Miptex.indices(img, palette, keyed)
if keyed and not palette then
colors[256] = { 0, 0, 255, 255 } -- GoldSrc '{' textures: index 255 is the (blue) key colour
end
local pal1024 = palette or buffer.create(1024)
if not palette then
for i, c in colors do
buffer.writeu32(pal1024, (i - 1) * 4, 0xFF000000 + c[3] * 65536 + c[2] * 256 + c[1])
end
end
local levels: { buffer } = {}
local px, lw, lh = img.pixels, w, h
for m = 0, 3 do
if m > 0 then
px, lw, lh = halve(px, lw, lh)
end
local idx = Quantize.map(px, lw, lh, colors, { transparentIndex = if keyed then 255 else nil })
if keyed then
for k = 0, lw * lh - 1 do
if readu8(px, k * 4 + 3) < 128 then
buffer.writeu8(idx, k, 255)
end
end
end
levels[m + 1] = idx
local lvl = { kind = "image", width = lw, height = lh, format = "rgba8", pixels = px, loops = 0, meta = {} } :: any
levels[m + 1] = (Miptex.indices(lvl, pal1024, keyed))
end
local total = 40
for _, l in levels do
@@ -211,4 +209,90 @@ function Miptex.find(lumps: { Lump }, name: string): Lump?
return best
end
-- qpic (Quake .lmp / WAD2 type 0x42: u32 width, height, 8-bit pixels; GoldSrc adds u16 count + count * 3 palette bytes)
-- -> rgba8. keyed: index 255 transparent (Quake's Draw_TransPic), default true
function Miptex.qpic(b: buffer, at: number, size: number, opts: DecodeOptions?): (Types.Image?, string?)
if size < 8 or at < 0 or at + 8 > buffer.len(b) then
return nil, "truncated qpic header"
end
local w, h = readu32(b, at), readu32(b, at + 4)
if w == 0 or h == 0 then
return nil, "empty qpic"
end
if w * h > (opts and opts.maxPixels or 2 ^ 24) then
return nil, "limit: qpic " .. w .. " x " .. h
end
if 8 + w * h > size or at + 8 + w * h > buffer.len(b) then
return nil, "truncated qpic pixels"
end
local own: buffer? = nil
if opts and opts.goldsrc then
local p = 8 + w * h
if p + 2 <= size then
local n = buffer.readu16(b, at + p)
if n > 0 and n <= 256 and p + 2 + n * 3 <= size then
own = Pixels.palette(b, at + p + 2, n)
end
end
end
local pal = own or (opts and opts.palette) or Pixels.grey()
local keyed = if opts and opts.keyed ~= nil then opts.keyed else true
if keyed then
pal = Pixels.keyed(pal, 255)
end
local img = Types.Image.new(w, h)
Pixels.indexed(b, at + 8, w, 8, img.pixels, w, h, true, pal)
img.meta.source = { format = "qpic", palette = own ~= nil or (opts ~= nil and opts.palette ~= nil), keyed = keyed or nil }
return img, nil
end
-- palette indices of an rgba8 image (nearest entry; alpha < 128 -> 255 when keyed and the image has any) and the
-- palette used
function Miptex.indices(img: Types.Image, palette: buffer?, keyed: boolean): (buffer, { { number } })
if keyed then
local any = false
for k = 0, img.width * img.height - 1 do
if readu8(img.pixels, k * 4 + 3) < 128 then
any = true
break
end
end
keyed = any
end
local colors = if palette then Pixels.colorList(palette) else Quantize.palette(img.pixels, img.width, img.height, if keyed then 255 else 256)
local idx = Quantize.map(img.pixels, img.width, img.height, colors, { transparentIndex = if keyed and palette then 255 else nil })
if keyed then
for k = 0, img.width * img.height - 1 do
if readu8(img.pixels, k * 4 + 3) < 128 then
buffer.writeu8(idx, k, 255)
end
end
end
return idx, colors
end
-- an rgba8 image -> qpic bytes (goldsrc: with its palette, made by median cut when none is given)
function Miptex.encodeQpic(img: Types.Image, palette: buffer?, goldsrc: boolean?, keyed: boolean?): (buffer?, string?)
if not palette and not goldsrc then
return nil, "a Quake qpic needs a palette"
end
local w, h = img.width, img.height
local idx, colors = Miptex.indices(img, palette, keyed ~= false)
local out = buffer.create(8 + w * h + (if goldsrc then 2 + 768 else 0))
buffer.writeu32(out, 0, w)
buffer.writeu32(out, 4, h)
buffer.copy(out, 8, idx, 0, w * h)
if goldsrc then
local p = 8 + w * h
buffer.writeu16(out, p, 256)
for i = 0, 255 do
local c = colors[i + 1] or { 0, 0, 0 }
buffer.writeu8(out, p + 2 + i * 3, c[1])
buffer.writeu8(out, p + 3 + i * 3, c[2])
buffer.writeu8(out, p + 4 + i * 3, c[3])
end
end
return out, nil
end
return Miptex
+3 -3
View File
@@ -269,13 +269,13 @@ function Pixels.grey(): buffer
return pal
end
-- a copy of a 1024-byte palette with entry index fully transparent (Quake / GoldSrc: index 255 of sprites, qpics and
-- '{' textures)
-- a copy of a 1024-byte palette with entry index transparent (alpha 0, colour kept as Pillow does; Quake / GoldSrc:
-- index 255 of sprites, qpics and '{' textures)
function Pixels.keyed(pal: buffer, index: number): buffer
local out = buffer.create(1024)
buffer.copy(out, 0, pal, 0, math.min(buffer.len(pal), 1024))
if index >= 0 and index < 256 then
writeu32(out, index * 4, 0)
writeu8(out, index * 4 + 3, 0)
end
return out
end
+237
View File
@@ -0,0 +1,237 @@
--!strict
-- data/q3shader: Quake III shader scripts (.shader; the Quake III Arena Shader Manual, tr_shader.c tokenizing: no code
-- taken), read and write. A script is a list of shaders { name, directives, stages }; a directive is its tokens
-- ({ "surfaceparm", "nolightmap" }, one line each), a stage is a list of directives. Keywords keep their case.
-- Comments (// and /* */) are dropped.
-- ------------------------------------------------------------------------------------------------ requires
local Err = require("@rosetta/core/Err")
local Bytes = require("@rosetta/core/Bytes")
-- ------------------------------------------------------------------------------------------------ contract
local Q3Shader = {
name = "q3shader",
category = "data",
extensions = { "shader" },
mime = { "text/x-quake3-shader" },
deps = { "core/Err", "core/Bytes" },
caps = { decode = true, encode = true },
}
-- ------------------------------------------------------------------------------------------------ types
export type Directive = { string }
export type Shader = { name: string, directives: { Directive }, stages: { { Directive } } }
export type EncodeOptions = { indent: string? } -- default "\t"
-- ------------------------------------------------------------------------------------------------ constants
local KEYWORDS = { "surfaceparm", "map", "clampmap", "animmap", "blendfunc", "rgbgen", "alphagen", "tcgen", "tcmod",
"cull", "deformvertexes", "qer_editorimage", "nopicmip", "nomipmaps", "skyparms", "q3map_", "depthwrite", "alphafunc" }
-- ------------------------------------------------------------------------------------------------ sniff
function Q3Shader.sniff(r: Bytes.Reader): number
local head = r:peek(math.min(r:remaining(), 2048))
if #head < 4 or string.find(head, "[%z\1-\8\14-\31]") then
return 0
end
local s = string.gsub(string.gsub(head, "/%*.-%*/", " "), "//[^\n]*", "")
if not string.match(s, "^%s*[^%s{}\"]+%s*{") then
return 0
end
local lower = string.lower(s)
for _, k in KEYWORDS do
if string.find(lower, "%f[%w_]" .. k) then
return 0.7
end
end
return 0.2
end
-- ------------------------------------------------------------------------------------------------ decode
-- the token lines of a script; braces are lines of their own
local function lex(text: string): ({ { string } }?, string?)
local lines: { { string } } = {}
local cur: { string } = {}
local i, n = 1, #text
local function flush()
if #cur > 0 then
table.insert(lines, cur)
cur = {}
end
end
while i <= n do
local c = string.sub(text, i, i)
if c == "\n" then
flush()
i += 1
elseif string.match(c, "%s") then
i += 1
elseif string.sub(text, i, i + 1) == "//" then
local e = string.find(text, "\n", i, true)
i = e or n + 1
elseif string.sub(text, i, i + 1) == "/*" then
local _, e = string.find(text, "*/", i + 2, true)
if not e then
return nil, "unterminated comment"
end
for _ in string.gmatch(string.sub(text, i, e), "\n") do
flush()
end
i = e + 1
elseif c == "{" or c == "}" then
flush()
table.insert(lines, { c })
i += 1
elseif c == '"' then
local e = string.find(text, '"', i + 1, true)
if not e then
return nil, "unterminated string"
end
table.insert(cur, string.sub(text, i + 1, e - 1))
i = e + 1
else
local _, e = string.find(text, "^[^%s{}\"]+", i)
local stop = e :: number
local tok = string.sub(text, i, stop)
local cm = string.find(tok, "//", 1, true)
if cm and cm > 1 then
tok = string.sub(tok, 1, cm - 1)
stop = i + cm - 2
end
table.insert(cur, tok)
i = stop + 1
end
end
flush()
return lines, nil
end
function Q3Shader.decode(r: Bytes.Reader): ({ Shader }?, Err.Err?)
local text = buffer.readstring(r.buf, r.base, r.limit - r.base)
local lines, msg = lex(text)
if not lines then
return nil, Err.new(Err.CORRUPT, msg or "bad script")
end
local out: { Shader } = {}
local k = 1
while k <= #lines do
local l = lines[k]
if #l ~= 1 or l[1] == "{" or l[1] == "}" then
return nil, Err.new(Err.CORRUPT, "expected a shader name, got '" .. table.concat(l, " ") .. "'")
end
local sh: Shader = { name = l[1], directives = {}, stages = {} }
k += 1
if not lines[k] or lines[k][1] ~= "{" then
return nil, Err.new(Err.CORRUPT, "expected '{' after " .. sh.name)
end
k += 1
local stage: { Directive }? = nil
local closed = false
while k <= #lines do
local d = lines[k]
k += 1
if d[1] == "{" then
if stage then
return nil, Err.new(Err.CORRUPT, "nested stage in " .. sh.name)
end
stage = {}
elseif d[1] == "}" then
if stage then
table.insert(sh.stages, stage)
stage = nil
else
closed = true
break
end
elseif stage then
table.insert(stage, d)
else
table.insert(sh.directives, d)
end
end
if not closed then
return nil, Err.new(Err.TRUNCATED, "shader " .. sh.name .. " not closed")
end
table.insert(out, sh)
end
return out, nil
end
-- ------------------------------------------------------------------------------------------------ encode
local function tokens(d: any): (string?, string?)
if type(d) ~= "table" or #d == 0 then
return nil, "a directive is a list of strings"
end
local parts = {}
for _, t in d do
local s = tostring(t)
if s == "" or string.find(s, "[%s{}]") then
if string.find(s, '"', 1, true) or string.find(s, "\n") then
return nil, "token cannot hold quotes or line breaks: " .. s
end
s = '"' .. s .. '"'
end
table.insert(parts, s)
end
return table.concat(parts, " "), nil
end
function Q3Shader.encode(list: { Shader }, opts: EncodeOptions?): (buffer?, Err.Err?)
if type(list) ~= "table" then
return nil, Err.new(Err.ARG, "expected a list of shaders")
end
local ind = opts and opts.indent or "\t"
local out: { string } = {}
for _, sh in list do
if type(sh) ~= "table" or type(sh.name) ~= "string" or sh.name == "" or string.find(sh.name, "[%s{}\"]") then
return nil, Err.new(Err.ARG, "a shader needs a name without spaces")
end
table.insert(out, sh.name)
table.insert(out, "{")
for _, d in sh.directives or {} do
local line, e = tokens(d)
if not line then
return nil, Err.new(Err.ARG, e or "bad directive")
end
table.insert(out, ind .. line)
end
for _, st in sh.stages or {} do
table.insert(out, ind .. "{")
for _, d in st do
local line, e = tokens(d)
if not line then
return nil, Err.new(Err.ARG, e or "bad directive")
end
table.insert(out, ind .. ind .. line)
end
table.insert(out, ind .. "}")
end
table.insert(out, "}")
table.insert(out, "")
end
return buffer.fromstring(table.concat(out, "\n")), nil
end
-- ------------------------------------------------------------------------------------------------ extras
-- the shader named name (case-insensitive, as the game looks them up)
function Q3Shader.find(list: { Shader }, name: string): Shader?
local want = string.lower(name)
for _, sh in list do
if string.lower(sh.name) == want then
return sh
end
end
return nil
end
-- the first directive starting with keyword (case-insensitive) in a shader or stage directive list
function Q3Shader.directive(list: { Directive }, keyword: string): Directive?
local want = string.lower(keyword)
for _, d in list do
if string.lower(d[1] or "") == want then
return d
end
end
return nil
end
return Q3Shader
+90
View File
@@ -0,0 +1,90 @@
--!strict
-- data/q3skin: Quake III model skins (.skin: "surface,shader" lines, "tag_*," for tags; tr_image.c RE_RegisterSkin, no
-- code taken), read and write. Decodes to a list of { surface, shader } in file order (shader "" for tags).
-- ------------------------------------------------------------------------------------------------ requires
local Err = require("@rosetta/core/Err")
local Bytes = require("@rosetta/core/Bytes")
-- ------------------------------------------------------------------------------------------------ contract
local Q3Skin = {
name = "q3skin",
category = "data",
extensions = { "skin" },
mime = { "text/x-quake3-skin" },
deps = { "core/Err", "core/Bytes" },
caps = { decode = true, encode = true },
}
-- ------------------------------------------------------------------------------------------------ types
export type Entry = { surface: string, shader: string }
-- ------------------------------------------------------------------------------------------------ sniff
function Q3Skin.sniff(r: Bytes.Reader): number
local head = r:peek(math.min(r:remaining(), 1024))
if #head < 3 or string.find(head, "[%z\1-\8\14-\31]") then
return 0
end
local lines, good = 0, 0
for line in string.gmatch(head, "[^\r\n]+") do
if not string.match(line, "^%s*$") then
lines += 1
if string.match(line, "^%s*[%w_%-]+%s*,%s*[^,%s]*%s*$") then
good += 1
end
end
end
return if lines > 0 and good == lines then 0.5 else 0
end
-- ------------------------------------------------------------------------------------------------ decode
function Q3Skin.decode(r: Bytes.Reader): ({ Entry }?, Err.Err?)
local text = buffer.readstring(r.buf, r.base, r.limit - r.base)
local out: { Entry } = {}
local n = 0
for line in string.gmatch(text, "[^\r\n]+") do
n += 1
local s = string.match(line, "^%s*(.-)%s*$") :: string
if s ~= "" and string.sub(s, 1, 2) ~= "//" then
local surface, shader = string.match(s, "^([^,]-)%s*,%s*(.-)$")
if not surface or surface == "" then
return nil, Err.new(Err.CORRUPT, "line " .. n .. ": expected surface,shader")
end
table.insert(out, { surface = surface, shader = shader :: string })
end
end
return out, nil
end
-- ------------------------------------------------------------------------------------------------ encode
function Q3Skin.encode(list: { Entry }): (buffer?, Err.Err?)
if type(list) ~= "table" then
return nil, Err.new(Err.ARG, "expected a list of { surface, shader }")
end
local out: { string } = {}
for _, e in list do
if type(e) ~= "table" or type(e.surface) ~= "string" or e.surface == "" or string.find(e.surface, "[,\r\n]") then
return nil, Err.new(Err.ARG, "a skin entry needs a surface name without commas")
end
local sh = if e.shader == nil then "" else tostring(e.shader)
if string.find(sh, "[,\r\n]") then
return nil, Err.new(Err.ARG, "a shader path cannot hold commas or line breaks")
end
table.insert(out, e.surface .. "," .. sh)
end
table.insert(out, "")
return buffer.fromstring(table.concat(out, "\n")), nil
end
-- the shader of a surface (case-insensitive)
function Q3Skin.shader(list: { Entry }, surface: string): string?
local want = string.lower(surface)
for _, e in list do
if string.lower(e.surface) == want then
return e.shader
end
end
return nil
end
return Q3Skin
+131
View File
@@ -0,0 +1,131 @@
--!strict
-- image/lmp: Quake .lmp lumps (wad.h / draw.c of the Quake source; no code taken), read and write: qpic pictures (u32
-- width, height, 8-bit pixels; index 255 transparent), palette.lmp (768 bytes: a 16 x 16 swatch) and colormap.lmp (64
-- light levels x 256: a 256 x 64 image). Pictures and colormaps need Quake's palette, which is never embedded (GPL):
-- opts.palette or gfx/palette.lmp through files / resolve; else grey (meta.source.palette = false).
-- ------------------------------------------------------------------------------------------------ requires
local Err = require("@rosetta/core/Err")
local Bytes = require("@rosetta/core/Bytes")
local Input = require("@rosetta/core/Input")
local Types = require("@rosetta/Types")
local Pixels = require("@rosetta/codecs/image/Pixels")
local Miptex = require("@rosetta/codecs/image/Miptex")
-- ------------------------------------------------------------------------------------------------ contract
local Lmp = {
name = "lmp",
category = "image",
extensions = { "lmp" },
mime = { "image/x-quake-lmp" },
deps = { "core/Err", "core/Bytes", "core/Input", "Types", "codecs/image/Pixels", "codecs/image/Miptex" },
caps = { decode = true, encode = true, alpha = true, depths = { 8 }, variants = { "qpic", "palette", "colormap" } },
}
-- ------------------------------------------------------------------------------------------------ types
export type DecodeOptions = {
palette: (buffer | string)?, -- 768 bytes
kind: ("qpic" | "palette" | "colormap")?, -- default: from the size
keyed: boolean?, -- qpic index 255 transparent, default true
resolve: ((uri: string) -> (buffer | string)?)?,
files: { [string]: buffer | string }?,
maxPixels: number?, -- default 2^24
}
export type EncodeOptions = {
palette: (buffer | string)?, -- 768 bytes: required for qpics
kind: ("qpic" | "palette")?, -- default "qpic"; "palette" writes a 16 x 16 swatch as 768 bytes
resolve: ((uri: string) -> (buffer | string)?)?,
files: { [string]: buffer | string }?,
}
-- ------------------------------------------------------------------------------------------------ sniff
local function kindOf(r: Bytes.Reader): string?
local n = r:remaining()
if n == 768 then
return "palette"
elseif n == 16385 or n == 16384 then
return "colormap"
end
if n < 9 then
return nil
end
local w, h = buffer.readu32(r.buf, r.pos), buffer.readu32(r.buf, r.pos + 4)
if w > 0 and h > 0 and w <= 4096 and h <= 4096 and 8 + w * h == n then
return "qpic"
end
return nil
end
function Lmp.sniff(r: Bytes.Reader): number
local k = kindOf(r)
return if k == "qpic" then 0.3 elseif k then 0.05 else 0
end
-- ------------------------------------------------------------------------------------------------ decode
local function palette(opts: any?): buffer?
local raw = if opts and opts.palette then Bytes.toBuffer(opts.palette) else Input.sibling(opts, "gfx/palette.lmp")
if raw and buffer.len(raw) >= 768 then
return Pixels.palette(raw, 0, 256)
end
return nil
end
function Lmp.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Image?, Err.Err?)
local kind = opts and opts.kind or kindOf(r)
local b, at, n = r.buf, r.base, r.limit - r.base
if kind == "palette" then
if n < 768 then
return nil, Err.new(Err.TRUNCATED, "palette", 0)
end
local img = Types.Image.new(16, 16)
buffer.copy(img.pixels, 0, Pixels.palette(b, at, 256), 0, 1024)
local list = Pixels.colorList(img.pixels)
img.meta.palette = list
img.meta.source = { format = "lmp", kind = "palette" }
return img, nil
end
local pal = palette(opts)
if kind == "colormap" then
local rows = math.min(64, n // 256)
if rows < 1 then
return nil, Err.new(Err.TRUNCATED, "colormap", 0)
end
local img = Types.Image.new(256, rows)
Pixels.indexed(b, at, 256, 8, img.pixels, 256, rows, true, pal or Pixels.grey())
img.meta.source = { format = "lmp", kind = "colormap", palette = pal ~= nil }
return img, nil
end
if kind ~= "qpic" and n >= 8 then
kind = "qpic"
end
local img, msg = Miptex.qpic(b, at, n, { palette = pal, keyed = opts and opts.keyed, maxPixels = opts and opts.maxPixels })
if not img then
return nil, Err.from(msg, 0)
end
img.meta.source = { format = "lmp", kind = "qpic", palette = pal ~= nil, keyed = (opts == nil or opts.keyed ~= false) or nil }
return img, nil
end
-- ------------------------------------------------------------------------------------------------ encode
function Lmp.encode(img: Types.Image, opts: EncodeOptions?): (buffer?, Err.Err?)
if type(img) ~= "table" or img.format ~= "rgba8" or type(img.pixels) ~= "buffer" then
return nil, Err.new(Err.ARG, "expected an rgba8 Image")
end
if opts and opts.kind == "palette" then
if img.width * img.height < 256 then
return nil, Err.new(Err.ARG, "a palette needs 256 pixels (16 x 16)")
end
return Pixels.paletteBytes(img.pixels, 256), nil
end
local pal = palette(opts)
if not pal then
return nil, Err.new(Err.ARG, "a qpic needs Quake's palette (opts.palette or gfx/palette.lmp; it is not embedded)")
end
local out, msg = Miptex.encodeQpic(img, pal, false, true)
if not out then
return nil, Err.new(Err.ARG, msg or "cannot encode")
end
return out, nil
end
return Lmp
+311
View File
@@ -0,0 +1,311 @@
--!strict
-- image/spr: Quake (IDSP 1), Half-Life (IDSP 2, own palette, texture formats) and DarkPlaces SPR32 (IDSP 32, rgba)
-- sprites, read and write (spritegn.h of the Quake source, the GoldSrc sprite layout; no code taken). Frames and frame
-- groups become Image frames on one canvas around the sprite origin (meta.origin); group intervals give the delays.
-- Quake sprites need Quake's palette (opts.palette or gfx/palette.lmp through files / resolve; never embedded).
-- Not supported: Quake II sprites (IDS2: frames are separate .pcx files).
-- ------------------------------------------------------------------------------------------------ requires
local Err = require("@rosetta/core/Err")
local Bytes = require("@rosetta/core/Bytes")
local Input = require("@rosetta/core/Input")
local Types = require("@rosetta/Types")
local Pixels = require("@rosetta/codecs/image/Pixels")
local Miptex = require("@rosetta/codecs/image/Miptex")
-- ------------------------------------------------------------------------------------------------ contract
local Spr = {
name = "spr",
category = "image",
extensions = { "spr" },
mime = { "image/x-quake-sprite" },
deps = { "core/Err", "core/Bytes", "core/Input", "Types", "codecs/image/Pixels", "codecs/image/Miptex" },
caps = { decode = true, encode = true, alpha = true, animation = true, variants = { "quake", "halflife", "spr32" } },
}
-- ------------------------------------------------------------------------------------------------ types
export type DecodeOptions = {
palette: (buffer | string)?, -- Quake: 768 bytes
resolve: ((uri: string) -> (buffer | string)?)?,
files: { [string]: buffer | string }?,
maxPixels: number?, -- per frame, default 2^24
maxFrames: number?, -- default 4096
}
export type EncodeOptions = {
version: number?, -- 2 (Half-Life, default), 1 (Quake: needs opts.palette) or 32 (rgba)
palette: (buffer | string)?,
type: number?, -- orientation: 0 parallel upright, 1 facing upright, 2 parallel (default), 3 oriented, 4 parallel oriented
texFormat: number?, -- Half-Life: 0 normal, 1 additive, 2 index alpha, 3 alpha test (default: 3 when any pixel is transparent)
delay: number?, -- seconds per frame when the image has none, default 0.1
}
-- ------------------------------------------------------------------------------------------------ constants
local TEX_FORMATS = { [0] = "normal", "additive", "indexalpha", "alphatest" }
-- ------------------------------------------------------------------------------------------------ sniff
function Spr.sniff(r: Bytes.Reader): number
if r:remaining() < 36 or r:peek(4) ~= "IDSP" then
return 0
end
local v = buffer.readi32(r.buf, r.pos + 4)
return if v == 1 or v == 2 or v == 32 then 1 else 0.3
end
-- ------------------------------------------------------------------------------------------------ decode
type Raw = { x: number, y: number, w: number, h: number, at: number, delay: number }
function Spr.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Image?, Err.Err?)
if r:string(4) ~= "IDSP" then
return nil, r.err or Err.new(Err.CORRUPT, "bad magic", 0)
end
local version = r:i32le()
if version ~= 1 and version ~= 2 and version ~= 32 then
return nil, Err.new(Err.UNSUPPORTED, "sprite version " .. tostring(version), 4)
end
local stype = r:i32le()
local texFormat = if version == 2 then r:i32le() else 3
local radius = r:f32le()
local mw, mh, nframes = r:i32le(), r:i32le(), r:i32le()
local beam, sync = r:f32le(), r:i32le()
if r.err then
return nil, r.err
end
local maxFrames = opts and opts.maxFrames or 4096
local maxPixels = opts and opts.maxPixels or 2 ^ 24
if nframes < 1 or nframes > maxFrames then
return nil, Err.new(if nframes < 1 then Err.CORRUPT else Err.LIMIT, "frame count " .. nframes, 24)
end
local pal: buffer
local own = false
if version == 2 then
local n = r:u16le()
if r.err then
return nil, r.err
end
if n < 1 or n > 256 or not r:need(n * 3) then
return nil, r.err or Err.new(Err.CORRUPT, "palette size " .. n, r:tell() - 2)
end
pal = Pixels.palette(r.buf, r.pos, n)
r:skip(n * 3)
own = true
else
local raw = if opts and opts.palette then Bytes.toBuffer(opts.palette) else Input.sibling(opts, "gfx/palette.lmp")
own = raw ~= nil and buffer.len(raw) >= 768
pal = if raw and own then Pixels.palette(raw, 0, 256) else Pixels.grey()
end
local bpp = if version == 32 then 4 else 1
local raws: { Raw } = {}
local groups: { { type: string, count: number } } = {}
local function single(delay: number): Err.Err?
local x, y, w, h = r:i32le(), r:i32le(), r:i32le(), r:i32le()
if r.err then
return r.err
end
if w < 1 or h < 1 then
return Err.new(Err.CORRUPT, "frame size " .. w .. " x " .. h, r:tell() - 8)
end
if w * h > maxPixels then
return Err.new(Err.LIMIT, "frame " .. w .. " x " .. h)
end
if not r:need(w * h * bpp) then
return r.err
end
table.insert(raws, { x = x, y = y, w = w, h = h, at = r.pos, delay = delay })
r:skip(w * h * bpp)
return nil
end
for _ = 1, nframes do
local ft = r:i32le()
if r.err then
return nil, r.err
end
if ft == 0 then
local e = single(0.1)
if e then
return nil, e
end
table.insert(groups, { type = "single", count = 1 })
else
local n = r:i32le()
if r.err then
return nil, r.err
end
if n < 1 or #raws + n > maxFrames then
return nil, Err.new(if n < 1 then Err.CORRUPT else Err.LIMIT, "group of " .. n .. " frames", r:tell() - 4)
end
local ivs = {}
for k = 1, n do
ivs[k] = r:f32le()
end
if r.err then
return nil, r.err
end
for k = 1, n do
-- intervals are cumulative end times (R_GetSpriteFrame)
local e = single(math.max(0, ivs[k] - (if k > 1 then ivs[k - 1] else 0)))
if e then
return nil, e
end
end
table.insert(groups, { type = "group", count = n })
end
end
local minX: number, maxX: number, minY: number, maxY: number = math.huge, -math.huge, math.huge, -math.huge
for _, f in raws do
minX = math.min(minX, f.x)
maxX = math.max(maxX, f.x + f.w)
maxY = math.max(maxY, f.y)
minY = math.min(minY, f.y - f.h)
end
local cw, ch = maxX - minX, maxY - minY
if cw * ch > maxPixels then
return nil, Err.new(Err.LIMIT, "canvas " .. cw .. " x " .. ch)
end
local fpal = pal
if version ~= 2 or texFormat == 3 then
fpal = Pixels.keyed(pal, 255)
end
local b = r.buf
local frames: { any } = {}
for _, f in raws do
local img = Types.Image.new(f.w, f.h)
if version == 32 then
buffer.copy(img.pixels, 0, b, f.at, f.w * f.h * 4)
elseif version == 2 and texFormat == 2 then
-- index alpha: the colour is the last palette entry, the index is the alpha
local c = bit32.band(buffer.readu32(pal, 255 * 4), 0xFFFFFF)
for k = 0, f.w * f.h - 1 do
buffer.writeu32(img.pixels, k * 4, c + buffer.readu8(b, f.at + k) * 0x1000000)
end
else
Pixels.indexed(b, f.at, f.w, 8, img.pixels, f.w, f.h, true, fpal)
end
table.insert(frames, { image = img, delay = f.delay, x = f.x - minX, y = maxY - f.y, dispose = "background", blend = "source" })
end
local out = Types.Image.new(cw, ch)
local f1 = frames[1]
for yy = 0, f1.image.height - 1 do
buffer.copy(out.pixels, ((f1.y + yy) * cw + f1.x) * 4, f1.image.pixels, yy * f1.image.width * 4, f1.image.width * 4)
end
out.frames = if #frames > 1 then frames else nil
out.loops = 0
out.meta.origin = { -minX, maxY }
out.meta.source = {
format = "spr", version = version, type = stype, texFormat = if version == 2 then TEX_FORMATS[texFormat] or texFormat else nil,
radius = radius, width = mw, height = mh, beamLength = beam, sync = sync, groups = groups,
palette = own, origins = (function()
local o = {}
for i, f in raws do
o[i] = { f.x, f.y }
end
return o
end)(),
}
return out, nil
end
-- ------------------------------------------------------------------------------------------------ encode
function Spr.encode(img: Types.Image, opts: EncodeOptions?): (buffer?, Err.Err?)
if type(img) ~= "table" or img.format ~= "rgba8" or type(img.pixels) ~= "buffer" then
return nil, Err.new(Err.ARG, "expected an rgba8 Image")
end
local version = opts and opts.version or 2
if version ~= 1 and version ~= 2 and version ~= 32 then
return nil, Err.new(Err.ARG, "version must be 1, 2 or 32")
end
local list: { { image: Types.Image, x: number, y: number, delay: number } } = {}
if img.frames and #img.frames > 0 then
for _, f in img.frames do
if f.image.format ~= "rgba8" then
return nil, Err.new(Err.ARG, "frames must be rgba8")
end
table.insert(list, { image = f.image, x = f.x, y = f.y, delay = f.delay })
end
else
table.insert(list, { image = img, x = 0, y = 0, delay = opts and opts.delay or 0.1 })
end
local origin = img.meta and img.meta.origin or { img.width // 2, img.height // 2 }
local mw: number, mh: number, alpha = 0, 0, false
for _, f in list do
mw = math.max(mw, f.image.width)
mh = math.max(mh, f.image.height)
local px = f.image.pixels
for k = 0, f.image.width * f.image.height - 1 do
if buffer.readu8(px, k * 4 + 3) < 128 then
alpha = true
break
end
end
end
local pal: buffer? = nil
if version == 1 then
local raw = if opts and opts.palette then Bytes.toBuffer(opts.palette) else nil
if not raw or buffer.len(raw) < 768 then
return nil, Err.new(Err.ARG, "a Quake sprite needs Quake's palette (opts.palette; it is not embedded)")
end
pal = Pixels.palette(raw, 0, 256)
elseif version == 2 then
local raw = if opts and opts.palette then Bytes.toBuffer(opts.palette) else nil
if raw and buffer.len(raw) >= 768 then
pal = Pixels.palette(raw, 0, 256)
else
-- one palette for every frame: the frames side by side
local tw = 0
for _, f in list do
tw += f.image.width
end
local strip = Types.Image.new(tw, mh)
local x0 = 0
for _, f in list do
for yy = 0, f.image.height - 1 do
buffer.copy(strip.pixels, (yy * tw + x0) * 4, f.image.pixels, yy * f.image.width * 4, f.image.width * 4)
end
x0 += f.image.width
end
local _, colors = Miptex.indices(strip, nil, alpha)
local p = buffer.create(1024)
for i, c in colors do
buffer.writeu32(p, (i - 1) * 4, 0xFF000000 + c[3] * 65536 + c[2] * 256 + c[1])
end
if alpha then
buffer.writeu32(p, 255 * 4, 0xFFFF0000) -- the alpha-test key: blue
end
pal = p
end
end
local texFormat = opts and opts.texFormat or (if alpha then 3 else 0)
local w = Bytes.writer()
w:string("IDSP")
w:u32le(version)
w:u32le(opts and opts.type or 2)
if version == 2 then
w:u32le(texFormat)
end
w:f32le(math.sqrt(mw * mw + mh * mh) / 2)
w:u32le(mw)
w:u32le(mh)
w:u32le(#list)
w:f32le(0)
w:u32le(0)
if version == 2 then
w:u16le(256)
w:bytes(Pixels.paletteBytes(pal :: buffer, 256))
end
for _, f in list do
local fw, fh = f.image.width, f.image.height
w:u32le(0)
w:u32le(bit32.band(f.x - origin[1], 0xFFFFFFFF))
w:u32le(bit32.band(origin[2] - f.y, 0xFFFFFFFF))
w:u32le(fw)
w:u32le(fh)
if version == 32 then
w:bytes(f.image.pixels, 0, fw * fh * 4)
else
local idx = Miptex.indices(f.image, pal, alpha and texFormat == 3 or version == 1)
w:bytes(idx, 0, fw * fh)
end
end
return w:finish(), nil
end
return Spr
+95
View File
@@ -0,0 +1,95 @@
-- archive/wad2 tests: WAD2 / WAD3 lumps, miptex / qpic / conchars / font / palette images against pixels decoded in
-- the fixture, ericw-tools qbsp's copy of a miptex, write round trips, adding images, errors, the fuzz pass.
-- Fixtures: tools/fixtures/wad2.py.
local T = require("@tests/T")
local F = require("@rosetta")
local Wad2 = require("@rosetta/archive/wad2")
local Miptex = require("@rosetta/codecs/image/Miptex")
local Bytes = require("@rosetta/core/Bytes")
local Crc32 = require("@rosetta/core/Crc32")
local Err = require("@rosetta/core/Err")
local Fx = require("@tests/gen/wad2")
local t = T.suite("wad2")
t:eq(Wad2.name, "wad2", "name")
for _, v in { "wad2", "wad3" } do
local c = Fx[v]
t:eq(F.detect(c.data), "wad2", v .. ": F.detect")
local a, err = Wad2.decode(Bytes.reader(buffer.fromstring(c.data)))
t:check(a, v .. ": " .. tostring(err))
t:eq(a.meta.source.variant, v, v .. ": variant")
local names = {}
for _, e in a:list() do
table.insert(names, e.name)
end
t:eq(table.concat(names, ","), table.concat(c.names, ","), v .. ": lump names in order")
for name, want in c.images do
local img, ierr = Wad2.image(a, name)
t:check(img, v .. ": image " .. name .. ": " .. tostring(ierr))
t:eq(img.width .. "x" .. img.height, want.w .. "x" .. want.h, v .. ": " .. name .. " size")
t:eq(Crc32.of(img.pixels), want.crc, v .. ": " .. name .. " pixels")
t:eq(img.meta.source.kind, want.kind, v .. ": " .. name .. " kind")
if want.mip2 then
local m2 = assert(Wad2.image(a, name, { mip = 2 }))
t:eq(Crc32.of(m2.pixels), want.mip2, v .. ": " .. name .. " mip 2")
end
end
-- write: the same lumps back
local out = assert(F.save(a))
local b = assert(Wad2.decode(Bytes.reader(out)))
t:eq(b.meta.source.variant, v, v .. ": variant kept")
for _, e in a:list() do
t:check(buffer.tostring(assert(a:read(e.name))) == buffer.tostring(assert(b:read(e.name))), v .. ": round trip " .. e.name)
t:eq((b:list()[1] :: any).type, (a:list()[1] :: any).type, v .. ": lump types kept")
end
end
do
local a = assert(Wad2.decode(Bytes.reader(buffer.fromstring(Fx.wad2.data))))
t:eq(Wad2.image(a, "palette").width, 16, "palette lump as a 16 x 16 image")
t:check(Wad2.palette(a) ~= nil, "the WAD's palette")
-- an explicit palette wins over the WAD's
local grey = string.rep("\0", 768)
local g = assert(Wad2.image(a, "brick", { palette = grey }))
t:eq(buffer.readu32(g.pixels, 0), 0xFF000000, "explicit palette")
-- qbsp copied brick into the BSP: same pixels
local m = assert(Miptex.decode(buffer.fromstring(Fx.bsp.miptex), 0, #Fx.bsp.miptex, { palette = Wad2.palette(a) }))
t:eq(Crc32.of(m.pixels), Fx.wad2.images.brick.crc, "qbsp's copy of the miptex")
-- adding images: palette colours map back exactly
local brick = assert(Wad2.image(a, "brick"))
local n = Wad2.new("wad2")
t:check(Wad2.addImage(n, "copy", brick, { palette = Fx.wad2.palette }), "addImage miptex")
t:check(Wad2.addImage(n, "pic", brick, { palette = Fx.wad2.palette, kind = "qpic" }), "addImage qpic")
local _, e1 = Wad2.addImage(n, "odd", F.ops.image.new(10, 10), { palette = Fx.wad2.palette })
t:check(e1 and e1.code == Err.ARG, "miptex sizes: multiples of 16")
local _, e2 = Wad2.addImage(n, "nopal", brick)
t:check(e2 and e2.code == Err.ARG, "WAD2 needs a palette")
local nb = assert(Wad2.decode(Bytes.reader(assert(F.save(n)))))
t:eq(Crc32.of(assert(Wad2.image(nb, "copy", { palette = Fx.wad2.palette })).pixels), Fx.wad2.images.brick.crc, "added miptex decodes the same")
t:eq(Crc32.of(assert(Wad2.image(nb, "pic", { palette = Fx.wad2.palette, keyed = false })).pixels), Fx.wad2.images.brick.crc, "added qpic decodes the same")
-- WAD3: its own palette from median cut (at most 256 colours: exact)
local w3 = assert(Wad2.decode(Bytes.reader(buffer.fromstring(Fx.wad3.data))))
local crete = assert(Wad2.image(w3, "crete"))
local n3 = Wad2.new("wad3")
t:check(Wad2.addImage(n3, "CRETE2", crete), "addImage into WAD3")
local d3 = assert(Wad2.decode(Bytes.reader(assert(F.save(n3)))))
t:eq(d3.meta.source.variant, "wad3", "WAD3 written")
t:eq(Crc32.of(assert(Wad2.image(d3, "CRETE2")).pixels), Fx.wad3.images.CRETE.crc, "WAD3 miptex with a made palette")
t:check(assert(Wad2.image(w3, "CONCHARS")).meta.font.glyphs[66].width == 8, "font glyph table")
local _, e3 = Wad2.image(w3, "missing")
t:check(e3 and e3.code == Err.ARG, "missing lump")
local _, e4 = Wad2.decode(Bytes.reader(buffer.fromstring(string.sub(Fx.wad2.data, 1, 20))))
t:check(e4 and e4.code == Err.TRUNCATED, "truncated directory: " .. tostring(e4))
end
t:fuzz("decode", function(b: buffer)
local a = Wad2.decode(Bytes.reader(b))
if a then
for _, e in a:list() do
Wad2.image(a, e.name)
end
end
return a
end, { Fx.wad2.data, Fx.wad3.data }, { mutations = 80 })
t:done()
+57
View File
@@ -0,0 +1,57 @@
-- data/q3shader tests: shader scripts against an independent tokenizer (tools/fixtures/q3shader.py), write round
-- trips, lookups, errors, the fuzz pass.
local T = require("@tests/T")
local F = require("@rosetta")
local Q3Shader = require("@rosetta/data/q3shader")
local Bytes = require("@rosetta/core/Bytes")
local Err = require("@rosetta/core/Err")
local Fx = require("@tests/gen/q3shader")
local t = T.suite("q3shader")
t:eq(Q3Shader.name, "q3shader", "name")
local function dump(v: any): string
if type(v) ~= "table" then
return tostring(v)
end
local parts = {}
if v.name then
table.insert(parts, "name=" .. v.name)
table.insert(parts, "d=" .. dump(v.directives))
table.insert(parts, "s=" .. dump(v.stages))
elseif v.surface then
table.insert(parts, v.surface .. "=" .. v.shader)
else
for _, x in v do
table.insert(parts, dump(x))
end
end
return "{" .. table.concat(parts, "|") .. "}"
end
local samples = {}
for i, c in Fx.scripts do
t:eq(F.detect(c.text), "q3shader", "script " .. i .. ": F.detect")
local list, err = Q3Shader.decode(Bytes.reader(buffer.fromstring(c.text)))
t:check(list, "script " .. i .. ": " .. tostring(err))
t:eq(dump(list), dump(c.shaders), "script " .. i .. ": structure")
local out = assert(Q3Shader.encode(list :: any))
t:eq(dump(Q3Shader.decode(Bytes.reader(out))), dump(c.shaders), "script " .. i .. ": round trip")
table.insert(samples, c.text)
end
do
local list = assert(Q3Shader.decode(Bytes.reader(buffer.fromstring(Fx.scripts[2].text))))
local sky = assert(Q3Shader.find(list, "TEXTURES/SKIES/HELLSKY"))
t:eq(assert(Q3Shader.directive(sky.directives, "skyparms"))[2], "env/hell sky", "quoted token")
t:eq(#sky.stages, 1, "stage on brace lines")
local again = assert(F.data.load(Fx.scripts[1].text))
t:eq(#again, 2, "F.data.load")
local _, e1 = Q3Shader.decode(Bytes.reader(buffer.fromstring("textures/x\n{\n{\nmap a\n")))
t:check(e1 and e1.code == Err.TRUNCATED, "unclosed shader")
local _, e2 = Q3Shader.encode({ { name = "has space", directives = {}, stages = {} } } :: any)
t:check(e2 and e2.code == Err.ARG, "bad name")
end
t:fuzz("decode", function(b: buffer)
return Q3Shader.decode(Bytes.reader(b))
end, samples)
t:done()
+36
View File
@@ -0,0 +1,36 @@
-- data/q3skin tests: Quake III .skin files against tools/fixtures/q3shader.py's parse, write round trips, lookup,
-- errors, the fuzz pass.
local T = require("@tests/T")
local F = require("@rosetta")
local Q3Skin = require("@rosetta/data/q3skin")
local Bytes = require("@rosetta/core/Bytes")
local Err = require("@rosetta/core/Err")
local Fx = require("@tests/gen/q3shader")
local t = T.suite("q3skin")
t:eq(Q3Skin.name, "q3skin", "name")
local function dump(list: any): string
local parts = {}
for _, e in list do
table.insert(parts, e.surface .. "=" .. e.shader)
end
return table.concat(parts, "|")
end
for i, c in Fx.skins do
local list, err = Q3Skin.decode(Bytes.reader(buffer.fromstring(c.text)))
t:check(list, "skin " .. i .. ": " .. tostring(err))
t:eq(dump(list), dump(c.entries), "skin " .. i .. ": entries")
t:eq(dump(Q3Skin.decode(Bytes.reader(assert(Q3Skin.encode(list :: any))))), dump(c.entries), "skin " .. i .. ": round trip")
t:eq(F.detect(c.text, { name = "x.skin" }), "q3skin", "skin " .. i .. ": F.detect")
end
t:eq(Q3Skin.shader(assert(Q3Skin.decode(Bytes.reader(buffer.fromstring(Fx.skins[1].text)))), "H_HEAD"), "models/players/sarge/band.tga", "skin lookup")
local _, e1 = Q3Skin.encode({ { surface = "a,b", shader = "x" } })
t:check(e1 and e1.code == Err.ARG, "comma in a surface name")
local _, e2 = Q3Skin.decode(Bytes.reader(buffer.fromstring("no comma here\n")))
t:check(e2 and e2.code == Err.CORRUPT, "line without a comma")
t:fuzz("decode", function(b: buffer)
return Q3Skin.decode(Bytes.reader(b))
end, { Fx.skins[1].text, Fx.skins[2].text })
t:done()
+48
View File
@@ -0,0 +1,48 @@
-- image/lmp tests: qpic pictures, palette.lmp and colormap.lmp against Pillow (tools/fixtures/lmp.py), the palette
-- through files, the grey fallback, the qpic writer round trip, errors, the fuzz pass.
local T = require("@tests/T")
local F = require("@rosetta")
local Lmp = require("@rosetta/image/lmp")
local Bytes = require("@rosetta/core/Bytes")
local Crc32 = require("@rosetta/core/Crc32")
local Err = require("@rosetta/core/Err")
local Fx = require("@tests/gen/lmp")
local t = T.suite("lmp")
t:eq(Lmp.name, "lmp", "name")
local samples = {}
for _, p in Fx.pics do
local img, err = Lmp.decode(Bytes.reader(buffer.fromstring(p.data)), { palette = Fx.palette })
t:check(img, p.name .. ": " .. tostring(err))
t:eq(img.width .. "x" .. img.height, p.w .. "x" .. p.h, p.name .. ": size")
t:eq(Crc32.of(img.pixels), p.crc, p.name .. ": pixels = Pillow (index 255 transparent)")
local opaque = assert(Lmp.decode(Bytes.reader(buffer.fromstring(p.data)), { files = { ["gfx/palette.lmp"] = Fx.palette }, keyed = false }))
t:eq(Crc32.of(opaque.pixels), p.crcOpaque, p.name .. ": opaque, palette through files")
t:eq(opaque.meta.source.palette, true, p.name .. ": palette found")
-- write back: the palette colours map to the same indices
local out = assert(Lmp.encode(img, { palette = Fx.palette }))
t:check(buffer.tostring(out) == p.data, p.name .. ": writer gives the same bytes")
table.insert(samples, p.data)
end
do
local p = Fx.pics[2]
t:eq(F.detect(p.data, { name = "conback.lmp" }), "lmp", "F.detect by size + extension")
local grey = assert(Lmp.decode(Bytes.reader(buffer.fromstring(p.data))))
t:eq(grey.meta.source.palette, false, "no palette: grey")
local cm = assert(Lmp.decode(Bytes.reader(buffer.fromstring(Fx.colormap.data)), { palette = Fx.palette }))
t:eq(cm.width .. "x" .. cm.height, "256x64", "colormap size")
t:eq(Crc32.of(cm.pixels), Fx.colormap.crc, "colormap = Pillow")
local pal = assert(Lmp.decode(Bytes.reader(buffer.fromstring(Fx.palette))))
t:eq(Crc32.of(pal.pixels), Fx.palcrc, "palette.lmp swatch = Pillow")
t:eq(#pal.meta.palette, 256, "palette entries")
t:check(buffer.tostring(assert(Lmp.encode(pal, { kind = "palette" }))) == Fx.palette, "palette round trip")
local _, e1 = Lmp.encode(grey)
t:check(e1 and e1.code == Err.ARG, "qpic writer needs the palette")
local _, e2 = Lmp.decode(Bytes.reader(buffer.fromstring(string.sub(p.data, 1, 30))), { kind = "qpic" })
t:check(e2 and e2.code == Err.CORRUPT or e2 and e2.code == Err.TRUNCATED, "truncated qpic: " .. tostring(e2))
end
t:fuzz("decode", function(b: buffer)
return Lmp.decode(Bytes.reader(b), { palette = Fx.palette, kind = "qpic" })
end, samples)
t:done()
+67
View File
@@ -0,0 +1,67 @@
-- image/spr tests: Quake / Half-Life (alpha test, index alpha, normal) / SPR32 sprites against the frames written by
-- tools/fixtures/spr.py (pixels, canvas positions from the origins, group delays), the writer round trips (versions 1,
-- 2 and 32), errors, the fuzz pass.
local T = require("@tests/T")
local F = require("@rosetta")
local Spr = require("@rosetta/image/spr")
local Bytes = require("@rosetta/core/Bytes")
local Crc32 = require("@rosetta/core/Crc32")
local Err = require("@rosetta/core/Err")
local Fx = require("@tests/gen/spr")
local t = T.suite("spr")
t:eq(Spr.name, "spr", "name")
local samples = {}
for _, s in Fx.sprites do
t:eq(F.detect(s.data), "spr", s.name .. ": F.detect")
local img, err = Spr.decode(Bytes.reader(buffer.fromstring(s.data)), { palette = Fx.palette })
t:check(img, s.name .. ": " .. tostring(err))
t:eq(img.width .. "x" .. img.height, s.w .. "x" .. s.h, s.name .. ": canvas")
t:eq(img.meta.origin[1] .. " " .. img.meta.origin[2], s.origin[1] .. " " .. s.origin[2], s.name .. ": origin")
local frames = img.frames or { { image = img, x = 0, y = 0, delay = 0.1 } }
t:eq(#frames, #s.frames, s.name .. ": frames")
for i, want in s.frames do
local f = frames[i]
t:eq(f.x .. "," .. f.y .. " " .. f.image.width .. "x" .. f.image.height, want.x .. "," .. want.y .. " " .. want.w .. "x" .. want.h, s.name .. ": frame " .. i .. " placement")
t:eq(Crc32.of(f.image.pixels), want.crc, s.name .. ": frame " .. i .. " pixels")
t:check(math.abs(f.delay - want.delay) < 1e-6, s.name .. ": frame " .. i .. " delay")
end
t:eq(img.meta.source.version, s.version, s.name .. ": version")
-- write in the same version and read back the same frames
local out, eerr = Spr.encode(img, { version = s.version, palette = if s.version == 2 then Fx.hlpalette else Fx.palette, texFormat = s.tex })
t:check(out, s.name .. ": encode " .. tostring(eerr))
local back = assert(Spr.decode(Bytes.reader(out :: buffer), { palette = Fx.palette }))
local bf = back.frames or { { image = back, x = 0, y = 0 } }
local same = #bf == #frames
for i, f in frames do
local g = bf[i]
same = same and g and g.x == f.x and g.y == f.y
if s.version == 32 or s.version == 1 or s.tex == 0 or s.tex == 3 then
same = same and Crc32.of(g.image.pixels) == Crc32.of(f.image.pixels)
end
end
t:check(same, s.name .. ": round trip keeps frames, placement and pixels")
table.insert(samples, s.data)
end
do
local q = Fx.sprites[1]
local img = assert(Spr.decode(Bytes.reader(buffer.fromstring(q.data)), { palette = Fx.palette }))
-- Half-Life from a Quake sprite: a made palette
local hl = assert(Spr.encode(img))
local back = assert(Spr.decode(Bytes.reader(hl)))
t:eq(back.meta.source.version, 2, "default version 2")
t:eq(back.meta.source.texFormat, "alphatest", "transparent pixels: alpha test")
local grey = assert(Spr.decode(Bytes.reader(buffer.fromstring(q.data))))
t:eq(grey.meta.source.palette, false, "Quake sprite without a palette: grey")
local _, e1 = Spr.encode(img, { version = 1 })
t:check(e1 and e1.code == Err.ARG, "version 1 needs a palette")
local _, e2 = Spr.decode(Bytes.reader(buffer.fromstring("IDS2" .. string.rep("\0", 40))))
t:check(e2 and e2.code == Err.CORRUPT, "Quake II sprite: not IDSP")
local _, e3 = Spr.decode(Bytes.reader(buffer.fromstring(string.sub(q.data, 1, 60))), { palette = Fx.palette })
t:check(e3 and e3.code == Err.TRUNCATED, "truncated: " .. tostring(e3))
end
t:fuzz("decode", function(b: buffer)
return Spr.decode(Bytes.reader(b), { palette = Fx.palette })
end, samples)
t:done()
+39
View File
@@ -0,0 +1,39 @@
# image/lmp fixtures (tools/fixtures.py): qpic .lmp pictures, a palette.lmp and a colormap.lmp written from wad.h /
# draw.c; reference rgba from Pillow (a "P" image with the palette, index 255 transparent for qpics). The palette is
# random: Quake's own is GPL and never committed.
# tests/gen/lmp.luau { palette, pics = { { name, data, w, h, crc, crcOpaque } }, colormap = { data, crc }, palcrc }
import json, struct, zlib
CODE = r"""
import json, sys, zlib, io
from PIL import Image
job = json.loads(sys.stdin.read())
out = {}
pal = bytes.fromhex(job["pal"])
for k, (w, h, hexpix, key) in job["imgs"].items():
im = Image.frombytes("P", (w, h), bytes.fromhex(hexpix))
im.putpalette(pal)
if key is not None:
im.info["transparency"] = key
out[k] = zlib.crc32(im.convert("RGBA").tobytes())
print(json.dumps(out))
"""
def generate(ctx):
rng = ctx.rng(31)
pal = bytes(rng.randrange(256) for _ in range(768))
imgs, pics = {}, []
for name, w, h in (("disc", 24, 24), ("conback", 64, 40), ("num_0", 24, 24), ("wide", 3, 1)):
pix = bytes(rng.randrange(256) for _ in range(w * h))
imgs[name] = [w, h, pix.hex(), 255]
imgs[name + "_o"] = [w, h, pix.hex(), None]
pics.append({"name": name, "data": struct.pack("<II", w, h) + pix, "w": w, "h": h})
cmap = bytes(rng.randrange(256) for _ in range(64 * 256)) + b"\0"
imgs["colormap"] = [256, 64, cmap[:16384].hex(), None]
imgs["palette"] = [16, 16, bytes(range(256)).hex(), None]
ref = json.loads(ctx.python(["pillow"], CODE, input=json.dumps({"pal": pal.hex(), "imgs": imgs}).encode()))
for p in pics:
p["crc"] = ref[p["name"]]
p["crcOpaque"] = ref[p["name"] + "_o"]
ctx.emit("lmp", {"palette": pal, "pics": pics, "colormap": {"data": cmap, "crc": ref["colormap"]}, "palcrc": ref["palette"]})
+117
View File
@@ -0,0 +1,117 @@
# data/q3shader and data/q3skin fixtures (tools/fixtures.py): shader scripts in the style of the Quake III Arena
# Shader Manual (comments, quoted tokens, braces on their own lines or not, several stages) and .skin files; reference
# structure from an independent tokenizer here (COM_ParseExt rules: tokens per line, // and /* */ comments).
# tests/gen/q3shader.luau { scripts = { { text, shaders = { { name, directives, stages } } } }, skins = { { text, entries } } }
import re
SCRIPTS = [
"""// base walls
textures/base_wall/metalfloor_wall_10
{
qer_editorimage textures/base_wall/metalfloor_wall_10.tga
surfaceparm metalsteps
{
map $lightmap
rgbGen identity
}
{
map textures/base_wall/metalfloor_wall_10.tga
blendFunc GL_DST_COLOR GL_ZERO
rgbGen identity
}
}
textures/sfx/flame1 {
surfaceparm nolightmap
cull none /* both sides */
q3map_surfacelight 2500
{
animMap 10 textures/sfx/flame1.tga textures/sfx/flame2.tga textures/sfx/flame3.tga
blendFunc GL_ONE GL_ONE
tcMod scale 1 1 // per frame
}
}
""",
"""/*
* a sky and a quoted path
*/
textures/skies/hellsky
{
skyparms "env/hell sky" 512 -
surfaceparm noimpact
surfaceparm sky
{ map textures/skies/clouds.tga
tcMod scroll 0.05 0.06 }
}
models/players/sarge/band
{
deformVertexes wave 100 sin 0 2 0 1
{
map models/players/sarge/band.tga
alphaFunc GE128
depthWrite
}
}
""",
]
SKINS = [
"tag_head,\ntag_torso,\nh_head,models/players/sarge/band.tga\nh_cap,models/players/sarge/cigar.tga\n",
"u_torso,models/players/sarge/default.tga\r\nl_legs,models/players/sarge/default.tga\r\n",
]
def tokenize(text):
text = re.sub(r"/\*.*?\*/", lambda m: "\n" * m.group(0).count("\n"), text, flags=re.S)
lines = []
for raw in text.split("\n"):
raw = raw.split("//")[0] if '"' not in raw else raw
cur = []
for m in re.finditer(r'"([^"]*)"|([{}])|([^\s{}"]+)', raw):
if m.group(2):
if cur:
lines.append(cur)
cur = []
lines.append([m.group(2)])
else:
cur.append(m.group(1) if m.group(1) is not None else m.group(3))
if cur:
lines.append(cur)
return lines
def parse(text):
lines = tokenize(text)
out, k = [], 0
while k < len(lines):
sh = {"name": lines[k][0], "directives": [], "stages": []}
k += 2
stage = None
while True:
d = lines[k]
k += 1
if d == ["{"]:
stage = []
elif d == ["}"]:
if stage is None:
break
sh["stages"].append(stage)
stage = None
elif stage is not None:
stage.append(d)
else:
sh["directives"].append(d)
out.append(sh)
return out
def generate(ctx):
skins = []
for s in SKINS:
entries = []
for line in s.replace("\r", "").split("\n"):
if line.strip():
a, b = line.split(",", 1)
entries.append({"surface": a.strip(), "shader": b.strip()})
skins.append({"text": s, "entries": entries})
ctx.emit("q3shader", {"scripts": [{"text": s, "shaders": parse(s)} for s in SCRIPTS], "skins": skins})
+82
View File
@@ -0,0 +1,82 @@
# image/spr fixtures (tools/fixtures.py): sprites written from spritegn.h (Quake IDSP 1: two single frames and a
# group of three; Half-Life IDSP 2 with its palette, alpha test and index alpha; DarkPlaces SPR32); expected frame
# pixels (rgba CRCs), canvas positions from the frame origins, and group delays from the cumulative intervals.
# tests/gen/spr.luau { palette, sprites = { { name, data, version, w, h, origin, frames = { { x, y, w, h, crc, delay } } } } }
import struct, zlib
def frame_bytes(rng, w, h, bpp):
return bytes(rng.randrange(256) for _ in range(w * h * bpp))
def rgba(pix, pal, key=None, mode=None):
out = bytearray()
for i in pix:
if mode == "indexalpha":
out += pal[255 * 3:255 * 3 + 3] + bytes([i])
elif key is not None and i == key:
out += pal[i * 3:i * 3 + 3] + b"\0"
else:
out += pal[i * 3:i * 3 + 3] + b"\xff"
return zlib.crc32(bytes(out))
def sprite(rng, version, layout, pal, tex=3):
# layout: list of ("single", (ox, oy, w, h)) or ("group", [intervals], [(ox, oy, w, h)])
singles = []
body = b""
frames = []
for item in layout:
if item[0] == "single":
body += struct.pack("<i", 0)
entries = [(item[1], 0.1)]
else:
ivs = item[1]
body += struct.pack("<ii", 1, len(ivs)) + b"".join(struct.pack("<f", v) for v in ivs)
entries = [(f, ivs[k] - (ivs[k - 1] if k else 0)) for k, f in enumerate(item[2])]
for (ox, oy, w, h), delay in entries:
pix = frame_bytes(rng, w, h, 4 if version == 32 else 1)
body += struct.pack("<iiii", ox, oy, w, h) + pix
if version == 32:
crc = zlib.crc32(pix)
elif version == 2 and tex == 2:
crc = rgba(pix, pal, mode="indexalpha")
elif version == 2 and tex != 3:
crc = rgba(pix, pal)
else:
crc = rgba(pix, pal, 255)
frames.append({"ox": ox, "oy": oy, "w": w, "h": h, "crc": crc, "delay": struct.unpack("<f", struct.pack("<f", delay))[0]})
n = len(layout)
mw = max(f["w"] for f in frames)
mh = max(f["h"] for f in frames)
if version == 2:
head = b"IDSP" + struct.pack("<iiifiiifi", 2, 2, tex, 16.0, mw, mh, n, 0.0, 0) + struct.pack("<H", 256) + pal
else:
head = b"IDSP" + struct.pack("<iifiiifi", version, 2, 16.0, mw, mh, n, 0.0, 0)
minx = min(f["ox"] for f in frames)
maxy = max(f["oy"] for f in frames)
for f in frames:
f["x"], f["y"] = f["ox"] - minx, maxy - f["oy"]
w = max(f["ox"] + f["w"] for f in frames) - minx
h = maxy - min(f["oy"] - f["h"] for f in frames)
return {"data": head + body, "version": version, "w": w, "h": h, "origin": [-minx, maxy], "frames": frames}
def generate(ctx):
rng = ctx.rng(64)
pal = bytes(rng.randrange(256) for _ in range(768))
hlpal = bytes(rng.randrange(256) for _ in range(768))
sprites = []
q = sprite(rng, 1, [("single", (-8, 8, 16, 16)), ("single", (-12, 20, 24, 28)),
("group", [0.1, 0.25, 0.5], [(-4, 4, 8, 8), (-6, 6, 12, 12), (-8, 10, 16, 20)])], pal)
q["name"] = "quake"
sprites.append(q)
for tex, name in ((3, "hl_alphatest"), (2, "hl_indexalpha"), (0, "hl_normal")):
s = sprite(rng, 2, [("single", (-16, 16, 32, 32)), ("single", (-10, 12, 20, 24))], hlpal, tex)
s["name"] = name
s["tex"] = tex
sprites.append(s)
s32 = sprite(rng, 32, [("single", (-5, 5, 10, 10)), ("group", [0.2, 0.4], [(-5, 5, 10, 10), (-3, 9, 6, 12)])], pal)
s32["name"] = "spr32"
sprites.append(s32)
ctx.emit("spr", {"palette": pal, "hlpalette": hlpal, "sprites": sprites})
+77
View File
@@ -0,0 +1,77 @@
# archive/wad2 fixtures (tools/fixtures.py): a Quake gfx.wad-like WAD2 (palette, conchars, a qpic, miptex textures, one
# '{' keyed) and a Half-Life WAD3 (miptex with their palettes, a qpic with its palette, a font), written with
# tools/fixtures/_qbsp.py's WAD writer from wad.h; expected pixels decoded here (index -> palette, 255 or 0 keyed);
# plus the WAD2 compiled into a map by ericw-tools qbsp (it reads the miptex lumps: the BSP's copies must match).
# tests/gen/wad2.luau { wad2 = { data, palette, images = { [name] = { w, h, crc, kind } } }, wad3 = ..., bsp }
import importlib.util, os, struct, zlib
INPUTS = ["tools/fixtures/_qbsp.py"]
def helper(ctx):
spec = importlib.util.spec_from_file_location("_qbsp", os.path.join(ctx.root, "tools", "fixtures", "_qbsp.py"))
m = importlib.util.module_from_spec(spec)
spec.loader.exec_module(m)
return m
def rgba(pix, pal, key=None):
out = bytearray()
for i in pix:
if key is not None and i == key:
out += pal[i * 3:i * 3 + 3] + b"\0"
else:
out += pal[i * 3:i * 3 + 3] + b"\xff"
return zlib.crc32(bytes(out))
def generate(ctx):
H = helper(ctx)
rng = ctx.rng(22)
pal = bytes(rng.randrange(256) for _ in range(768))
images = {}
lumps = [("palette", 0x40, pal)]
con = bytes(rng.randrange(256) for _ in range(128 * 128))
lumps.append(("conchars", 0x44, con))
images["conchars"] = {"w": 128, "h": 128, "crc": rgba(con, pal, 0), "kind": "conchars"}
qw, qh = 24, 10
qp = bytes(rng.randrange(256) for _ in range(qw * qh))
lumps.append(("disc", 0x42, struct.pack("<II", qw, qh) + qp))
images["disc"] = {"w": qw, "h": qh, "crc": rgba(qp, pal, 255), "kind": "qpic"}
for name, w, h in (("brick", 32, 16), ("{fence", 16, 16)):
mips = [bytes(rng.randrange(256) for _ in range((w >> m) * (h >> m))) for m in range(4)]
lumps.append((name, 0x44, H.miptex(name, w, h, rng, pixels=mips)))
images[name] = {"w": w, "h": h, "crc": rgba(mips[0], pal, 255 if name[0] == "{" else None), "kind": "miptex",
"mip2": rgba(mips[2], pal, 255 if name[0] == "{" else None)}
wad2 = H.wad(lumps)
out = {"wad2": {"data": wad2, "palette": pal, "images": images, "names": [l[0] for l in lumps]}}
# WAD3
images3 = {}
lumps3 = []
for name, w, h in (("CRETE", 32, 32), ("{GRATE", 16, 32)):
p3 = bytes(rng.randrange(256) for _ in range(768))
mips = [bytes(rng.randrange(256) for _ in range((w >> m) * (h >> m))) for m in range(4)]
lumps3.append((name, 0x43, H.miptex(name, w, h, rng, p3, pixels=mips)))
images3[name] = {"w": w, "h": h, "crc": rgba(mips[0], p3, 255 if name[0] == "{" else None), "kind": "miptex"}
p3 = bytes(rng.randrange(256) for _ in range(768))
qp = bytes(rng.randrange(256) for _ in range(20 * 12))
lumps3.append(("LOGO", 0x42, struct.pack("<II", 20, 12) + qp + struct.pack("<H", 256) + p3))
images3["LOGO"] = {"w": 20, "h": 12, "crc": rgba(qp, p3, 255), "kind": "qpic"}
fw, fh = 256, 16
fp = bytes(rng.randrange(256) for _ in range(fw * fh))
chars = b"".join(struct.pack("<HH", (c % 32) * 8, 8) for c in range(256))
lumps3.append(("CONCHARS", 0x46, struct.pack("<IIII", fw, fh, 2, 8) + chars + fp + struct.pack("<H", 256) + p3))
images3["CONCHARS"] = {"w": fw, "h": fh, "crc": rgba(fp, p3, 255), "kind": "font"}
out["wad3"] = {"data": H.wad(lumps3, b"WAD3"), "images": images3, "names": [l[0] for l in lumps3]}
# qbsp copies the miptex it uses into the BSP
text = ('{\n"classname" "worldspawn"\n"wad" "gfx.wad"\n{\n'
"( 0 0 0 ) ( 0 1 0 ) ( 0 0 1 ) brick 0 0 0 1 1\n( 0 0 0 ) ( 0 0 1 ) ( 1 0 0 ) brick 0 0 0 1 1\n"
"( 0 0 0 ) ( 1 0 0 ) ( 0 1 0 ) brick 0 0 0 1 1\n( 64 64 64 ) ( 64 65 64 ) ( 65 64 64 ) brick 0 0 0 1 1\n"
"( 64 64 64 ) ( 65 64 64 ) ( 64 64 65 ) brick 0 0 0 1 1\n( 64 64 64 ) ( 64 64 65 ) ( 64 65 64 ) brick 0 0 0 1 1\n"
'}\n}\n{\n"classname" "info_player_start"\n"origin" "32 32 32"\n}\n')
res = H.compile(ctx, text, {"gfx.wad": wad2}, ["-nofill", "-noclip", "-nopercent"])
b = H.read_bsp(res["bsp"])
L = b["lumps"]["miptex"]
o = struct.unpack_from("<i", L, 4)[0]
out["bsp"] = {"miptex": L[o:o + 40 + 32 * 16 * 85 // 64]}
ctx.emit("wad2", out)