ws-tex: image/pcx (read 1/2/4/8-bit, planes, palettes; write 8-bit palette / 24 / 32-bit RLE)

Tested against netpbm ppmtopcx / ImageMagick / Pillow files decoded by pcxtoppm; our files read by
ImageMagick. Shared test helper tests/image/_raster.luau and fixture helper tools/fixtures/_raster_ref.py.
This commit is contained in:
4DBug committed 2026-10-31 14:48:46 -05:00
1 parent abd01270f0
commit d294c211f9
8 files changed
+614

No files matched your search

+1
View File
@@ -13,6 +13,7 @@ is tested under both runtimes (luau `--codegen -O2` and LuaJIT through the build
| image | ico | .ico .cur | yes | yes | alpha: true, frames: true, depths: 1, 4, 8, 16, 24, 32 | `tests/image/ico.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 | 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` |
+12
View File
@@ -110,6 +110,18 @@ local list: { Entry } = {
return require("@formats/image/ktx")
end,
},
{
name = "pcx",
category = "image",
path = "image/pcx",
extensions = { "pcx", "pcc", "dcx" },
mime = { "image/vnd.zbrush.pcx", "image/x-pcx" },
deps = { "core/Err", "core/Bytes", "Types", "codecs/image/Pixels" },
caps = { decode = true, encode = true, alpha = true, palette = true, depths = { 1, 2, 4, 8, 24, 32 } },
load = function()
return require("@formats/image/pcx")
end,
},
{
name = "png",
category = "image",
+266
View File
@@ -0,0 +1,266 @@
--!strict
-- image/pcx: ZSoft PC Paintbrush (the ZSoft "Technical Reference Manual" PCX header and RLE; new code). Decode: 1-bit
-- monochrome, 1-bit x 2..4 planes (EGA, the header palette), 2 / 4-bit packed (the header palette), 8-bit with the
-- 256-colour palette at the end (grey when it is missing), 8-bit x 3 / 4 planes (RGB / RGBA); RLE (runs may cross
-- scan lines) and the rare uncompressed encoding; the window (xMin / yMin) and DPI (meta.dpi). Encode: rgba8 as
-- 8-bit palette (up to 256 opaque colours), 24-bit (3 planes) or 32-bit (4 planes, when there is alpha), RLE.
-- ------------------------------------------------------------------------------------------------ requires
local Err = require("@formats/core/Err")
local Bytes = require("@formats/core/Bytes")
local Types = require("@formats/Types")
local Pixels = require("@formats/codecs/image/Pixels")
-- ------------------------------------------------------------------------------------------------ contract
local Pcx = {
name = "pcx",
category = "image",
extensions = { "pcx", "pcc", "dcx" },
mime = { "image/vnd.zbrush.pcx", "image/x-pcx" },
deps = { "core/Err", "core/Bytes", "Types", "codecs/image/Pixels" },
caps = { decode = true, encode = true, alpha = true, palette = true, depths = { 1, 2, 4, 8, 24, 32 } },
}
-- ------------------------------------------------------------------------------------------------ types
export type DecodeOptions = {
maxPixels: number?, -- refuse larger images (default 2^26)
}
export type EncodeOptions = {
palette: boolean?, -- 8-bit palette when possible (default true); false: always 24 / 32-bit planes
}
local readu8, readu16 = buffer.readu8, buffer.readu16
-- ------------------------------------------------------------------------------------------------ sniff
function Pcx.sniff(r: Bytes.Reader): number
if r:size() < 128 then
return 0
end
local m, v, e, bpp = r:peekU8(0), r:peekU8(1), r:peekU8(2), r:peekU8(3)
if m ~= 10 or (v ~= 0 and v ~= 2 and v ~= 3 and v ~= 4 and v ~= 5) or e > 1 then
return 0
end
return if bpp == 1 or bpp == 2 or bpp == 4 or bpp == 8 then 0.8 else 0
end
-- ------------------------------------------------------------------------------------------------ decode
function Pcx.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Image?, Err.Err?)
local b, o, limit = r.buf, r.base, r.limit
if limit - o < 128 then
return nil, Err.new(Err.TRUNCATED, "short header", o)
end
if readu8(b, o) ~= 10 then
return nil, Err.new(Err.CORRUPT, "not a PCX file", o)
end
local version, enc, bpp = readu8(b, o + 1), readu8(b, o + 2), readu8(b, o + 3)
local x0, y0, x1, y1 = readu16(b, o + 4), readu16(b, o + 6), readu16(b, o + 8), readu16(b, o + 10)
local planes, bpl = readu8(b, o + 65), readu16(b, o + 66)
local w, h = x1 - x0 + 1, y1 - y0 + 1
if x1 < x0 or y1 < y0 then
return nil, Err.new(Err.CORRUPT, "bad window", o + 4)
end
local maxPixels = opts and opts.maxPixels or 2 ^ 26
if w * h > maxPixels then
return nil, Err.new(Err.LIMIT, string.format("%d x %d is over the %d pixel limit", w, h, maxPixels))
end
local kind
if bpp == 8 and planes == 1 then
kind = "pal8"
elseif bpp == 8 and (planes == 3 or planes == 4) then
kind = "rgb"
elseif bpp == 1 and planes >= 1 and planes <= 4 then
kind = "planar"
elseif (bpp == 2 or bpp == 4) and planes == 1 then
kind = "packed"
else
return nil, Err.new(Err.UNSUPPORTED, string.format("%d bits x %d planes", bpp, planes), o + 3)
end
if bpl * 8 < w * bpp then
return nil, Err.new(Err.CORRUPT, "bytes per line too small", o + 66)
end
-- the scan lines (planes after each other per line), RLE across lines
local total = bpl * planes * h
local raw = buffer.create(total)
local p, q = o + 128, 0
local truncated = false
if enc == 1 then
while q < total do
if p >= limit then
truncated = true
break
end
local c = readu8(b, p)
p += 1
if c >= 0xC0 then
if p >= limit then
truncated = true
break
end
local n = math.min(c - 0xC0, total - q)
buffer.fill(raw, q, readu8(b, p), n)
p += 1
q += n
else
buffer.writeu8(raw, q, c)
q += 1
end
end
else
local n = math.min(total, limit - p)
buffer.copy(raw, 0, b, p, n)
p += n
truncated = n < total
end
-- palettes
local pal = buffer.create(1024)
local function setPal(i: number, rr: number, gg: number, bb: number)
buffer.writeu32(pal, i * 4, rr + gg * 256 + bb * 65536 + 0xFF000000)
end
if kind == "pal8" then
local at = limit - 769
if at >= p and readu8(b, at) == 12 then
for i = 0, 255 do
setPal(i, readu8(b, at + 1 + i * 3), readu8(b, at + 2 + i * 3), readu8(b, at + 3 + i * 3))
end
else
for i = 0, 255 do
setPal(i, i, i, i)
end
end
elseif kind == "planar" and planes == 1 then
setPal(0, 0, 0, 0)
setPal(1, 255, 255, 255)
else
for i = 0, 15 do
setPal(i, readu8(b, o + 16 + i * 3), readu8(b, o + 17 + i * 3), readu8(b, o + 18 + i * 3))
end
end
local img = Types.Image.new(w, h, "rgba8")
local px = img.pixels
if kind == "pal8" or kind == "packed" then
Pixels.indexed(raw, 0, bpl, bpp, px, w, h, true, pal)
elseif kind == "planar" then
for y = 0, h - 1 do
local row = y * bpl * planes
for x = 0, w - 1 do
local idx = 0
for pl = 0, planes - 1 do
local byte = readu8(raw, row + pl * bpl + bit32.rshift(x, 3))
idx += bit32.band(bit32.rshift(byte, 7 - bit32.band(x, 7)), 1) * bit32.lshift(1, pl)
end
buffer.writeu32(px, (y * w + x) * 4, buffer.readu32(pal, idx * 4))
end
end
else
for y = 0, h - 1 do
local row = y * bpl * planes
for x = 0, w - 1 do
local d = (y * w + x) * 4
buffer.writeu8(px, d, readu8(raw, row + x))
buffer.writeu8(px, d + 1, readu8(raw, row + bpl + x))
buffer.writeu8(px, d + 2, readu8(raw, row + 2 * bpl + x))
buffer.writeu8(px, d + 3, if planes == 4 then readu8(raw, row + 3 * bpl + x) else 255)
end
end
end
if kind == "pal8" or kind == "packed" or (kind == "planar" and planes > 1) then
local list: { { number } } = {}
for i = 0, (if kind == "pal8" then 256 else bit32.lshift(1, bpp * planes)) - 1 do
local v = buffer.readu32(pal, i * 4)
list[i + 1] = { bit32.band(v, 255), bit32.band(bit32.rshift(v, 8), 255), bit32.band(bit32.rshift(v, 16), 255), 255 }
end
img.meta.palette = list
end
local hd, vd = readu16(b, o + 12), readu16(b, o + 14)
if hd > 0 and vd > 0 then
img.meta.dpi = { x = hd, y = vd }
end
if truncated then
img.meta.truncated = true
end
img.meta.source = { format = "pcx", version = version, bitDepth = bpp * planes, planes = planes, x = x0, y = y0, rle = enc == 1 }
return img, nil
end
-- ------------------------------------------------------------------------------------------------ encode
-- RLE of one plane row into w
local function rleRow(out: Bytes.Writer, src: buffer, p: number, n: number)
local i = 0
while i < n do
local v = readu8(src, p + i)
local run = 1
while i + run < n and run < 63 and readu8(src, p + i + run) == v do
run += 1
end
if run > 1 or v >= 0xC0 then
out:u8(0xC0 + run)
end
out:u8(v)
i += run
end
end
function Pcx.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, "needs 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, "size must be 1..65535")
end
local px = img.pixels
local cols, alpha = Pixels.colours(px, w * h, 256)
local usePal = not alpha and #cols <= 256 and not (opts and opts.palette == false)
local planes = if usePal then 1 elseif alpha then 4 else 3
local bpl = w + w % 2
local out = Bytes.writer(128 + w * h * planes + 800)
out:u8(10)
out:u8(5)
out:u8(1)
out:u8(8)
out:u16le(0)
out:u16le(0)
out:u16le(w - 1)
out:u16le(h - 1)
local dpi = img.meta and img.meta.dpi
out:u16le(if dpi then math.floor(dpi.x + 0.5) else 72)
out:u16le(if dpi then math.floor(dpi.y + 0.5) else 72)
out:fill(0, 48)
out:u8(0)
out:u8(planes)
out:u16le(bpl)
out:u16le(1)
out:fill(0, 58)
local row = buffer.create(bpl)
local index: { [number]: number } = {}
for i, c in cols do
index[c] = i - 1
end
for y = 0, h - 1 do
for pl = 0, planes - 1 do
for x = 0, w - 1 do
local s = (y * w + x) * 4
local v
if usePal then
v = index[bit32.band(buffer.readu32(px, s), 0xFFFFFF)] or 0
else
v = readu8(px, s + pl)
end
buffer.writeu8(row, x, v)
end
rleRow(out, row, 0, bpl)
end
end
if usePal then
out:u8(12)
for i = 0, 255 do
local c = cols[i + 1] or 0
out:u8(bit32.band(c, 255))
out:u8(bit32.band(bit32.rshift(c, 8), 255))
out:u8(bit32.rshift(c, 16))
end
end
return out:finish(), nil
end
return Pcx
+78
View File
@@ -0,0 +1,78 @@
-- tests/image/_raster: the shared checks of the simple raster formats' tests (pcx, sgi, sunras, xbm, xpm, ilbm, icns,
-- ani): decode every case against its reference rgba8 pixels, round-trip images through the encoder, fuzz samples.
local Bytes = require("@formats/core/Bytes")
local Types = require("@formats/Types")
local R = {}
local function maxDiff(a: buffer, b: buffer, n: number): (number, number)
local worst, at = 0, -1
for i = 0, n * 4 - 1 do
local d = math.abs(buffer.readu8(a, i) - buffer.readu8(b, i))
if d > worst then
worst, at = d, i // 4
end
end
return worst, at
end
R.maxDiff = maxDiff
-- cases: { { name, data, w, h, rgba, tol? } } (rgba: the reference decode)
function R.decodes(t: any, Fmt: any, cases: { any }, opts: any?): number
local n = 0
for _, c in cases do
local img, err = Fmt.decode(Bytes.reader(buffer.fromstring(c.data)), opts)
t:check(img, c.name .. ": " .. tostring(err))
if img then
t:check(img.width == c.w and img.height == c.h and img.format == "rgba8", string.format("%s: %d x %d %s", c.name, img.width, img.height, img.format))
if img.width == c.w and img.height == c.h then
local d, at = maxDiff(img.pixels, buffer.fromstring(c.rgba), c.w * c.h)
t:check(d <= (c.tol or 0), string.format("%s: %d off the reference at pixel %d", c.name, d, at))
end
n += 1
end
-- from inside a bigger buffer
local big = buffer.create(#c.data + 9)
buffer.writestring(big, 5, c.data)
local img2 = Fmt.decode(Bytes.reader(big, 5, #c.data), opts)
t:check(img2 and img and buffer.tostring(img2.pixels) == buffer.tostring(img.pixels), c.name .. ": from a sub-range")
end
return n
end
-- image(w, h, rgba string) -> Types.Image
function R.image(w: number, h: number, rgba: string): Types.Image
local img = Types.Image.new(w, h)
img.pixels = buffer.fromstring(rgba)
return img
end
-- roundTrip(t, Fmt, img, encodeOpts?, label, tol?) -> the encoded buffer
function R.roundTrip(t: any, Fmt: any, img: Types.Image, eopts: any?, label: string, tol: number?): buffer?
local enc, err = Fmt.encode(img, eopts)
t:check(enc, label .. ": encode " .. tostring(err))
if not enc then
return nil
end
local back, derr = Fmt.decode(Bytes.reader(enc))
t:check(back, label .. ": decode " .. tostring(derr))
if back then
t:check(back.width == img.width and back.height == img.height, label .. ": size")
local d = maxDiff(back.pixels, img.pixels, img.width * img.height)
t:check(d <= (tol or 0), string.format("%s: round trip %d off", label, d))
end
return enc
end
-- samples(cases, every?) -> the fuzz samples (every n-th case's data)
function R.samples(cases: { any }, every: number?): { string }
local samples = {}
for i, c in cases do
if i % (every or 1) == 0 then
table.insert(samples, c.data)
end
end
return samples
end
return R
+39
View File
@@ -0,0 +1,39 @@
-- image/pcx tests: files from netpbm (24-bit, 8-bit, packed 2 / 4-bit, 3 / 4 planes, mono), ImageMagick and Pillow
-- against pcxtoppm's decode; our files read by ImageMagick; round trips (palette, 24-bit, 32-bit alpha); errors; the
-- fuzz no-throw pass. Fixtures: tools/fixtures/pcx.py.
local T = require("@tests/T")
local Pcx = require("@formats/image/pcx")
local Bytes = require("@formats/core/Bytes")
local Err = require("@formats/core/Err")
local R = require("@tests/image/_raster")
local Fx = require("@tests/gen/pcx")
local t = T.suite("pcx")
t:eq(Pcx.name, "pcx", "name")
t:check(Pcx.caps.decode and Pcx.caps.encode, "caps")
t:note("%d files match pcxtoppm", R.decodes(t, Pcx, Fx.cases))
-- our files: ImageMagick reads what we decode
for _, o in Fx.ours do
local img = Pcx.decode(Bytes.reader(buffer.fromstring(o.data))) :: any
t:eq(R.maxDiff(img.pixels, buffer.fromstring(o.rgba), o.w * o.h), 0, o.name .. ": ImageMagick reads our file")
end
for _, c in Fx.cases do
R.roundTrip(t, Pcx, R.image(c.w, c.h, c.rgba), nil, c.name .. " re-encoded")
R.roundTrip(t, Pcx, R.image(c.w, c.h, c.rgba), { palette = false }, c.name .. " re-encoded 24-bit")
end
do
local img = R.image(3, 2, string.rep("\1\2\3\128", 6))
local enc = R.roundTrip(t, Pcx, img, nil, "alpha: 4 planes") :: buffer
t:eq(buffer.readu8(enc, 65), 4, "alpha -> 4 planes")
t:eq(Pcx.sniff(Bytes.reader(enc)), 0.8, "sniff")
t:eq(Pcx.sniff(Bytes.reader(buffer.fromstring("GIF89a"))), 0, "sniff other")
local _, e = Pcx.decode(Bytes.reader(buffer.fromstring(string.sub(buffer.tostring(enc), 1, 60))))
t:check(e and e.code == Err.TRUNCATED, "short header")
local _, e2 = Pcx.decode(Bytes.reader(enc), { maxPixels = 2 })
t:check(e2 and e2.code == Err.LIMIT, "limit")
end
t:fuzz("decode", function(b: buffer)
return Pcx.decode(Bytes.reader(b))
end, R.samples(Fx.cases), { mutations = 6 })
t:done()
+122
View File
@@ -0,0 +1,122 @@
# Shared by the simple raster fixture generators (pcx, sgi, sunras, xbm, xpm, ilbm, icns, ani): source images, a PNG
# writer, netpbm / ImageMagick runs in one temp dir, and a PNM / PAM reader for their output.
# work = Work(ctx) a temp dir; work.png(name, w, h, rgba); work.sh("netpbm", ["cmd", ...]); work.read(n)
# pnm_rgba(data) -> (w, h, rgba) for P1..P7 (PBM 1 = black; PAM GRAYSCALE[_ALPHA] / RGB[_ALPHA])
import os, random, shutil, struct, subprocess, tempfile, zlib
def png(w, h, rgba):
raw = b"".join(b"\0" + rgba[y * w * 4:(y + 1) * w * 4] for y in range(h))
def chunk(t, d):
return struct.pack(">I", len(d)) + t + d + struct.pack(">I", zlib.crc32(t + d))
return (b"\x89PNG\r\n\x1a\n" + chunk(b"IHDR", struct.pack(">IIBBBBB", w, h, 8, 6, 0, 0, 0)) +
chunk(b"IDAT", zlib.compress(raw)) + chunk(b"IEND", b""))
def photo(w, h, seed=1, alpha=False):
rng = random.Random(seed)
out = bytearray()
for y in range(h):
for x in range(w):
r = (x * 255) // max(1, w - 1)
g = (y * 255) // max(1, h - 1)
b = ((x * 7 + y * 3) * 4 + rng.randrange(8)) % 256
a = 255 if not alpha else ((x * 37 + y * 11) % 256)
out += bytes((r, g, b, a))
return bytes(out)
def palette_image(w, h, ncolours, seed=2):
rng = random.Random(seed)
cols = [(rng.randrange(256), rng.randrange(256), rng.randrange(256)) for _ in range(ncolours)]
out = bytearray()
for y in range(h):
for x in range(w):
out += bytes(cols[(x // 3 + y // 2 + (x * y) % 3) % ncolours]) + b"\xff"
return bytes(out)
class Work:
def __init__(self, ctx):
self.ctx = ctx
self.dir = tempfile.mkdtemp(prefix="formats-raster-")
def close(self):
shutil.rmtree(self.dir, ignore_errors=True)
def path(self, n):
return os.path.join(self.dir, n)
def write(self, n, data):
with open(self.path(n), "wb") as f:
f.write(data)
def read(self, n):
with open(self.path(n), "rb") as f:
return f.read()
def png(self, n, w, h, rgba):
self.write(n, png(w, h, rgba))
def sh(self, pkg, cmds):
script = " && ".join(cmds)
res = subprocess.run(["nix", "shell", "nixpkgs#" + pkg, "-c", "sh", "-c", "cd %s && %s" % (self.dir, script)], capture_output=True)
if res.returncode:
raise RuntimeError("%s failed: %s" % (pkg, res.stderr.decode()[-1500:]))
return res.stdout
def _tokens(data, n, pos):
out = []
while len(out) < n:
while data[pos:pos + 1].isspace():
pos += 1
if data[pos:pos + 1] == b"#":
while data[pos:pos + 1] not in (b"\n", b""):
pos += 1
continue
s = pos
while not data[pos:pos + 1].isspace():
pos += 1
out.append(int(data[s:pos]))
return out, pos + 1
def pnm_rgba(data):
kind = data[:2]
if kind == b"P7":
end = data.index(b"ENDHDR\n") + 7
hdr = dict(l.split(None, 1) for l in data[3:end - 7].decode().strip().split("\n") if l and not l.startswith("#"))
w, h, d, mx = int(hdr["WIDTH"]), int(hdr["HEIGHT"]), int(hdr["DEPTH"]), int(hdr["MAXVAL"])
raw, pos = data[end:], 0
elif kind in (b"P4",):
(w, h), pos = _tokens(data, 2, 2)
bits = data[pos:]
stride = (w + 7) // 8
out = bytearray()
for y in range(h):
for x in range(w):
v = 0 if (bits[y * stride + x // 8] >> (7 - x % 8)) & 1 else 255
out += bytes((v, v, v, 255))
return w, h, bytes(out)
else:
(w, h, mx), pos = _tokens(data, 3, 2)
d = 1 if kind == b"P5" else 3
raw = data[pos:]
bps = 2 if mx > 255 else 1
out = bytearray()
for i in range(w * h):
vals = []
for k in range(d):
o = (i * d + k) * bps
v = raw[o] if bps == 1 else (raw[o] << 8 | raw[o + 1])
vals.append((v * 255 + mx // 2) // mx)
if d == 1:
out += bytes((vals[0],) * 3 + (255,))
elif d == 2:
out += bytes((vals[0],) * 3 + (vals[1],))
elif d == 3:
out += bytes(vals) + b"\xff"
else:
out += bytes(vals)
return w, h, bytes(out)
+38
View File
@@ -108,3 +108,41 @@ if which == "exr" then
emit("ours_rgb_zip.exr", Exr.encode(opaque))
emit("ours_from_rgba8.exr", Exr.encode(image(16, 16, "rgba8", 2)))
end
-- the simple raster writers: a 37 x 23 photo-like image (opaque and with alpha) and a 12-colour one
local function photo(alpha: boolean): Types.Image
local img = image(37, 23, "rgba8", 0)
if not alpha then
for i = 0, 37 * 23 - 1 do
buffer.writeu8(img.pixels, i * 4 + 3, 255)
end
end
return img
end
local function few(): Types.Image
local img = Types.Image.new(30, 20)
for y = 0, 19 do
for x = 0, 29 do
local k = (x // 3 + y // 2) % 12
buffer.writeu32(img.pixels, (y * 30 + x) * 4, (k * 20) + (255 - k * 20) * 256 + ((k * 77) % 256) * 65536 + 0xFF000000)
end
end
return img
end
local function simple(): any
if which == "pcx" then
return require("@formats/image/pcx")
end
return nil
end
local Fmt = simple()
if Fmt then
for name, img in { opaque = photo(false), alpha = photo(true), few = few() } do
local out, err = Fmt.encode(img)
if out then
emit("ours_" .. name .. "." .. which, out)
else
print("skip\t" .. name .. "\t" .. tostring(err))
end
end
end
+58
View File
@@ -0,0 +1,58 @@
# PCX fixtures (tools/fixtures.py): files from netpbm's ppmtopcx (24-bit planes, 8-bit palette, packed 1 / 2 / 4-bit,
# 4-plane EGA, 1-bit mono), ImageMagick (24-bit, palette) and Pillow (RGB, P, L, 1), decoded by pcxtoppm (netpbm) as
# the reference; our encoder's files (tools/fixtures/_tex_encode.luau -a pcx) decoded by ImageMagick (it reads 4-plane alpha).
# tests/gen/pcx.luau { cases = { { name, data, w, h, rgba } }, ours = { { name, data, w, h, rgba } } }
import importlib.util, os, shutil, subprocess
_spec = importlib.util.spec_from_file_location("_raster_ref", os.path.join(os.path.dirname(os.path.abspath(__file__)), "_raster_ref.py"))
R = importlib.util.module_from_spec(_spec)
_spec.loader.exec_module(R)
INPUTS = ["tools/fixtures/_tex_encode.luau", "src/Formats/image/pcx"]
def ours(ctx, which):
exe = shutil.which("luau")
cmd = [exe] if exe else ["nix", "shell", "nixpkgs#luau", "-c", "luau"]
res = subprocess.run(cmd + ["tools/fixtures/_tex_encode.luau", "-a", which], cwd=ctx.root, capture_output=True, check=True)
files = {}
for line in res.stdout.decode().split("\n"):
if line.startswith("ours_") and "\t" in line:
n, hx = line.split("\t", 1)
files[n] = bytes.fromhex(hx.strip())
return files
def generate(ctx):
w = R.Work(ctx)
try:
w.png("photo.png", 37, 23, R.photo(37, 23))
w.png("pal.png", 40, 30, R.palette_image(40, 30, 200))
w.png("c16.png", 33, 17, R.palette_image(33, 17, 16, 5))
w.png("c4.png", 21, 9, R.palette_image(21, 9, 4, 6))
w.png("mono.png", 29, 13, bytes(v for i in range(29 * 13) for v in ((255,) * 3 if (i * 7) % 5 < 2 else (0,) * 3) + (255,)))
nb = ["pngtopam photo.png | pamtopnm > photo.ppm", "pngtopam pal.png | pamtopnm > pal.ppm", "pngtopam c16.png | pamtopnm > c16.ppm",
"pngtopam c4.png | pamtopnm > c4.ppm", "pngtopam mono.png | pamtopnm | ppmtopgm | pgmtopbm > mono.pbm",
"ppmtopcx -24bit photo.ppm > nb_24bit.pcx", "ppmtopcx -8bit pal.ppm > nb_8bit.pcx", "ppmtopcx -packed c16.ppm > nb_packed4.pcx",
"ppmtopcx -packed c4.ppm > nb_packed2.pcx", "ppmtopcx -planes 4 c16.ppm > nb_planes4.pcx", "ppmtopcx mono.pbm > nb_mono.pcx",
"ppmtopcx -planes 3 c4.ppm > nb_planes3.pcx"]
w.sh("netpbm", nb)
w.sh("imagemagick", ["magick photo.png -alpha off im_24bit.pcx", "magick pal.png -alpha off -type palette im_palette.pcx"])
code = ("from PIL import Image\nimport os\nos.chdir(%r)\nim=Image.open('photo.png').convert('RGB')\nim.save('pil_rgb.pcx')\n"
"Image.open('pal.png').convert('RGB').quantize(256).save('pil_p.pcx')\nim.convert('L').save('pil_l.pcx')\n"
"Image.open('mono.png').convert('1').save('pil_1.pcx')\n") % w.dir
ctx.python(["pillow"], code)
names = sorted(f for f in os.listdir(w.dir) if f.endswith(".pcx"))
mine = ours(ctx, "pcx")
for n, d in mine.items():
w.write(n, d)
allnames = names + sorted(mine)
w.sh("netpbm", ["pcxtoppm %s > %s.ppm" % (n, n) for n in names])
w.sh("imagemagick", ["magick %s -depth 8 pam:%s.ppm" % (n, n) for n in sorted(mine)])
cases, our = [], []
for n in allnames:
ww, hh, rgba = R.pnm_rgba(w.read(n + ".ppm"))
(our if n.startswith("ours_") else cases).append({"name": n, "data": w.read(n), "w": ww, "h": hh, "rgba": rgba})
ctx.emit("pcx", {"cases": cases, "ours": our})
finally:
w.close()