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

+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()