merge ws/tex

This commit is contained in:
4DBug committed 2026-10-31 15:44:25 -05:00
commit 93a5afbe65
63 files changed
+11009 -3

No files matched your search

+146
View File
@@ -1392,3 +1392,149 @@ do
local dt = os.clock() - t0
print(string.format("%-8s %-30s %8.2f ms %7.1fx real time", runtime, "smacker audio 22 kHz stereo", dt * 1000, n / a.sampleRate / dt))
end
do
-- 3D (ws-3d): a 400 x 400 grid mesh (160k vertices, 318k triangles) through our own writers, then the readers; a
-- 128^3 noise voxel grid through VOX and greedy meshing
local Types = require("@formats/Types")
local MeshOps = require("@formats/ops/MeshOps")
local Gltf = require("@formats/model/gltf")
local Obj = require("@formats/model/obj")
local Stl = require("@formats/model/stl")
local Ply = require("@formats/model/ply")
local Vox = require("@formats/model/vox")
local N = 400
local pos = Types.Scene.accessor(nil, "f32", 3, N * N)
local uv = Types.Scene.accessor(nil, "f32", 2, N * N)
for y = 0, N - 1 do
for x = 0, N - 1 do
local i = y * N + x
buffer.writef32(pos.data, i * 12, x / N)
buffer.writef32(pos.data, i * 12 + 4, math.sin(x * 0.1) * math.cos(y * 0.1) * 0.05)
buffer.writef32(pos.data, i * 12 + 8, y / N)
buffer.writef32(uv.data, i * 8, x / N)
buffer.writef32(uv.data, i * 8 + 4, y / N)
end
end
local ind = Types.Scene.accessor(nil, "u32", 1, (N - 1) * (N - 1) * 6)
local k = 0
for y = 0, N - 2 do
for x = 0, N - 2 do
local a = y * N + x
for _, v in { a, a + N, a + 1, a + 1, a + N, a + N + 1 } do
buffer.writeu32(ind.data, k * 4, v)
k += 1
end
end
end
local prim = { attributes = { POSITION = pos, TEXCOORD_0 = uv }, indices = ind, mode = "triangles" } :: any
MeshOps.computeNormals(prim)
local scene = Types.Scene.fromPrimitive(prim, "grid")
bench("meshops computeNormals 318k tris", 3, buffer.len(pos.data), function()
MeshOps.computeNormals(prim)
end)
local glb = assert(Gltf.encode(scene, { binary = true }))
bench("gltf glb decode (" .. buffer.len(glb) // 1000 .. " KB)", 5, buffer.len(glb), function()
Gltf.decode(Bytes.reader(glb))
end)
bench("gltf glb encode", 3, buffer.len(glb), function()
Gltf.encode(scene, { binary = true })
end)
local obj = assert(Obj.encode(scene))
bench("obj decode (" .. buffer.len(obj) // 1000 .. " KB)", 2, buffer.len(obj), function()
Obj.decode(Bytes.reader(obj))
end)
bench("obj encode", 2, buffer.len(obj), function()
Obj.encode(scene)
end)
local stl = assert(Stl.encode(scene))
bench("stl binary decode (" .. buffer.len(stl) // 1000 .. " KB)", 5, buffer.len(stl), function()
Stl.decode(Bytes.reader(stl))
end)
local ply = assert(Ply.encode(scene))
bench("ply binary decode (" .. buffer.len(ply) // 1000 .. " KB)", 5, buffer.len(ply), function()
Ply.decode(Bytes.reader(ply))
end)
local Fbx = require("@formats/model/fbx")
local fbx = assert(Fbx.encode(scene))
bench("fbx binary decode (" .. buffer.len(fbx) // 1000 .. " KB)", 3, buffer.len(fbx), function()
Fbx.decode(Bytes.reader(fbx))
end)
bench("fbx binary encode (zlib arrays)", 2, buffer.len(fbx), function()
Fbx.encode(scene)
end)
bench("fbx binary encode (raw arrays)", 3, buffer.len(fbx), function()
Fbx.encode(scene, { compress = false })
end)
local fbxa = assert(Fbx.encode(scene, { ascii = true }))
bench("fbx ascii decode (" .. buffer.len(fbxa) // 1000 .. " KB)", 2, buffer.len(fbxa), function()
Fbx.decode(Bytes.reader(fbxa))
end)
local ThreeMf = require("@formats/model/3mf")
local tmf = assert(ThreeMf.encode(scene))
bench("3mf decode (" .. buffer.len(tmf) // 1000 .. " KB zipped)", 2, buffer.len(tmf), function()
ThreeMf.decode(Bytes.reader(tmf))
end)
bench("3mf encode", 2, buffer.len(tmf), function()
ThreeMf.encode(scene)
end)
local V = 128
local grid = Types.Voxels.new(V, V, V)
for z = 0, V - 1 do
for y = 0, V - 1 do
for x = 0, V - 1 do
local h = (math.sin(x * 0.11) + math.cos(y * 0.07) + 2) * V / 8 + z * 0
if z < h then
Types.Voxels.set(grid, x, y, z, 1 + (x // 8 + y // 8) % 6)
end
end
end
end
local vox = assert(Vox.encode(grid))
bench("vox decode (" .. buffer.len(vox) // 1000 .. " KB)", 5, buffer.len(vox), function()
Vox.decode(Bytes.reader(vox))
end)
bench("greedy mesh 128^3 (MB of cells)", 3, V * V * V, function()
MeshOps.voxelsToPrimitive(grid)
end)
end
do
-- textures (ws-tex): codecs/image/Bcn on a 256 x 256 image (tools/fixtures/bcn.py); MB/s of rgba8 output (decode)
-- or input (encode); BC6H of rgbaf32 output
local Bcn = require("@formats/codecs/image/Bcn")
local BB = require("@tests/gen/bcn_bench")
local w, h = BB.w, BB.h
local px = buffer.fromstring(BB.rgba)
for _, kind in { "bc1", "bc3", "bc5" } do
local blocks = Bcn.encode(kind, px, w, h) :: buffer
bench("bcn decode " .. kind .. " 256x256", 5, w * h * 4, function()
Bcn.decode(kind, blocks, 0, w, h)
end)
bench("bcn encode " .. kind .. " 256x256", 2, w * h * 4, function()
Bcn.encode(kind, px, w, h)
end)
end
local b7, b6 = buffer.fromstring(BB.bc7), buffer.fromstring(BB.bc6h)
bench("bcn decode bc7 256x256", 5, w * h * 4, function()
Bcn.decode("bc7", b7, 0, w, h)
end)
bench("bcn decode bc6h 256x256", 5, w * h * 16, function()
Bcn.decode("bc6h", b6, 0, w, h)
end)
end
do
-- OpenEXR (ws-tex): a 512 x 256 half RGBA image from the OpenEXR bindings (tools/fixtures/exr.py), ZIP and PIZ;
-- MB/s of rgbaf32 output; our ZIP encoder on the decoded floats
local Exr = require("@formats/image/exr")
local EB = require("@tests/gen/exr_bench")
local n = 512 * 256 * 16
for _, k in { "zip", "piz" } do
local data = buffer.fromstring(EB[k])
bench("exr decode " .. k .. " 512x256 half", 3, n, function()
Exr.decode(Bytes.reader(data), { native = true })
end)
end
local img = Exr.decode(Bytes.reader(buffer.fromstring(EB.zip)), { native = true }) :: any
bench("exr encode zip 512x256 half", 2, n, function()
Exr.encode(img)
end)
end
+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)
+22
View File
@@ -0,0 +1,22 @@
# Shared by the simple raster fixture generators: run our encoder (tools/fixtures/_tex_encode.luau -a <fmt>) and
# decode files with ImageMagick into rgba8 (through PAM).
import os, shutil, subprocess
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 magick_cases(R, w, names, fmt=None):
"""ImageMagick decodes of the named files in the work dir -> { name: (w, h, rgba) }"""
pre = (fmt + ":") if fmt else ""
w.sh("imagemagick", ["magick %s%s -depth 8 -alpha on pam:%s.pam" % (pre, n, n) for n in names])
return {n: R.pnm_rgba(w.read(n + ".pam")) for n in names}
+193
View File
@@ -0,0 +1,193 @@
-- tools/fixtures/_tex_encode.luau: our texture encoders' output for the reference tools to read (run by
-- tools/fixtures/{dds,ktx,exr}.py as `luau tools/fixtures/_tex_encode.luau -a <format>`). Prints "name\thex" lines.
-- The source images are generated here (tools/fixtures/_tex_reference.py makes the same ones: source()).
local Types = require("@formats/Types")
local which = ({ ... } :: { string })[1] or "dds"
local function hex(b: buffer): string
local t = table.create(buffer.len(b))
for i = 0, buffer.len(b) - 1 do
t[i + 1] = string.format("%02x", buffer.readu8(b, i))
end
return table.concat(t)
end
-- the test pattern (x, y, channel) -> 0..1, the same formula as _tex_reference.source()
local function value(x: number, y: number, c: number, w: number, h: number, salt: number): number
if c == 0 then
return x / math.max(1, w - 1)
elseif c == 1 then
return y / math.max(1, h - 1)
elseif c == 2 then
return ((x * 7 + y * 13 + salt * 31) % 64) / 63
end
return ((x + y + salt) % 5) / 4
end
local function image(w: number, h: number, fmt: string, salt: number, scale: number?): Types.Image
local img = Types.Image.new(w, h, fmt :: any)
for y = 0, h - 1 do
for x = 0, w - 1 do
for c = 0, 3 do
local v = value(x, y, c, w, h, salt)
local o = (y * w + x) * 4 + c
if fmt == "rgba8" then
buffer.writeu8(img.pixels, o, math.floor(v * 255 + 0.5))
elseif fmt == "rgba16" then
buffer.writeu16(img.pixels, o * 2, math.floor(v * 65535 + 0.5))
else
buffer.writef32(img.pixels, o * 4, if c < 3 then v * (scale or 1) else v)
end
end
end
end
return img
end
local function emit(name: string, b: buffer?, err: any?)
if not b then
error(name .. ": " .. tostring(err))
end
print(name .. "\t" .. hex(b))
end
if which == "dds" then
local Dds = require("@formats/image/dds")
local img = image(37, 23, "rgba8", 0)
for _, f in { "rgba8", "bgra8", "bc1", "bc3", "bc4", "bc5" } do
emit("ours_" .. f .. ".dds", Dds.encode(img, { pixelFormat = f :: any }))
emit("ours_" .. f .. "_mips.dds", Dds.encode(img, { pixelFormat = f :: any, mips = true }))
end
emit("ours_rgba8_dx10.dds", Dds.encode(img, { dx10 = true, mips = true }))
emit("ours_rgba16.dds", Dds.encode(image(37, 23, "rgba16", 0), { mips = true }))
emit("ours_rgba32f.dds", Dds.encode(image(37, 23, "rgbaf32", 0, 4), { mips = true }))
emit("ours_rgba16f.dds", Dds.encode(image(37, 23, "rgbaf32", 0, 4), { pixelFormat = "rgba16f" }))
local cube = image(16, 16, "rgba8", 0)
cube.frames = {}
for i = 1, 6 do
cube.frames[i] = { image = image(16, 16, "rgba8", i), delay = 0, x = 0, y = 0, dispose = "none", blend = "source" }
end
cube.meta.layout = "cube"
emit("ours_cube.dds", Dds.encode(cube, { mips = true }))
cube.meta.layout = "array"
emit("ours_array_bc1.dds", Dds.encode(cube, { pixelFormat = "bc1" }))
end
if which == "ktx" then
local Ktx = require("@formats/image/ktx")
local img = image(37, 23, "rgba8", 0)
emit("ours_rgba8.ktx2", Ktx.encode(img))
emit("ours_rgba8_mips.ktx2", Ktx.encode(img, { mips = true }))
emit("ours_srgb_zlib.ktx2", Ktx.encode(img, { mips = true, srgb = true, zlib = 6 }))
emit("ours_rgba16.ktx2", Ktx.encode(image(37, 23, "rgba16", 0), { mips = true }))
emit("ours_rgba32f.ktx2", Ktx.encode(image(37, 23, "rgbaf32", 0, 4), { mips = true }))
emit("ours_rgba16f.ktx2", Ktx.encode(image(37, 23, "rgbaf32", 0, 4), { pixelFormat = "rgba16f" }))
local cube = image(16, 16, "rgba8", 0)
cube.frames = {}
for i = 1, 6 do
cube.frames[i] = { image = image(16, 16, "rgba8", i), delay = 0, x = 0, y = 0, dispose = "none", blend = "source" }
end
cube.meta.layout = "cube"
emit("ours_cube.ktx2", Ktx.encode(cube, { mips = true }))
cube.meta.layout = "array"
emit("ours_array.ktx2", Ktx.encode(cube))
end
if which == "exr" then
local Exr = require("@formats/image/exr")
local f = image(37, 23, "rgbaf32", 0, 4)
for _, c in { "none", "zips", "zip" } do
emit("ours_half_" .. c .. ".exr", Exr.encode(f, { compression = c :: any }))
emit("ours_float_" .. c .. ".exr", Exr.encode(f, { compression = c :: any, pixelType = "float" }))
end
local opaque = image(20, 40, "rgbaf32", 1, 2)
for i = 0, 20 * 40 - 1 do
buffer.writef32(opaque.pixels, i * 16 + 12, 1)
end
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")
elseif which == "sgi" then
return require("@formats/image/sgi")
elseif which == "sunras" then
return require("@formats/image/sunras")
elseif which == "xbm" then
return require("@formats/image/xbm")
elseif which == "xpm" then
return require("@formats/image/xpm")
elseif which == "ilbm" then
return require("@formats/image/ilbm")
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
if which == "icns" then
-- square icons 16 / 32 / 48 / 128 as RLE entries (no encodeImage hook here)
local Icns = require("@formats/image/icns")
local base = image(128, 128, "rgba8", 1)
base.frames = {}
for i, s in { 16, 32, 48, 128 } do
base.frames[i] = { image = image(s, s, "rgba8", i), delay = 0, x = 0, y = 0, dispose = "none", blend = "source" }
end
base.pixels = base.frames[4].image.pixels
emit("ours_legacy.icns", Icns.encode(base))
end
if which == "ora" then
-- a layered document: background, an offset half-opaque multiply layer, a hidden one, a group with a screen layer
local Ora = require("@formats/layered/ora")
local Png = require("@formats/image/png")
local doc = Types.Layered.new(40, 30)
local bg = Types.Layered.layer("background", image(40, 30, "rgba8", 0))
for i = 0, 40 * 30 - 1 do
buffer.writeu8(bg.image.pixels, i * 4 + 3, 255)
end
local mid = Types.Layered.layer("mid", image(20, 10, "rgba8", 1), 5, 7)
mid.opacity, mid.blend = 0.5, "multiply"
local hidden = Types.Layered.layer("hidden", image(8, 8, "rgba8", 2), 1, 1)
hidden.visible = false
local inner = Types.Layered.layer("inner", image(10, 10, "rgba8", 3), 20, 15)
inner.blend = "screen"
local g = Types.Layered.group("group", { inner })
g.opacity = 0.75
doc.layers = { bg, mid, hidden, g }
emit("ours_doc.ora", Ora.encode(doc, { encodeImage = function(img: any, _f: string): (any, any)
return Png.encode(img)
end }))
end
+110
View File
@@ -0,0 +1,110 @@
# Shared by the texture fixture generators (bcn.py, etc.py, dds.py, ktx.py): reference block decoders through nix.
# godot(ctx, jobs) Godot 4's Image.decompress (bcdec for BC1-7, etcpak for ETC1 / ETC2 / EAC): each job is
# (raw block bytes, w, h, godot format number, float) -> rgba8 bytes, or rgbaf32 little-endian
# bytes when float is true
# pillow(ctx, jobs) Pillow's DDS reader (BcnDecode.c): each job is (dds bytes) -> (mode, raw bytes)
# dds_dx10(w, h, dxgi, data) / dds_fourcc(w, h, fourcc, data): minimal DDS files around block data
import os, shutil, struct, tempfile
# Godot Image.Format numbers (checked against Godot 4.7)
GODOT = {"bc1": 17, "bc2": 18, "bc3": 19, "bc4": 20, "bc5": 21, "bc7": 22, "bc6hs": 23, "bc6h": 24, "etc1": 25,
"eac_r11": 26, "eac_r11s": 27, "eac_rg11": 28, "eac_rg11s": 29, "etc2_rgb": 30, "etc2_rgba": 31,
"etc2_rgba1": 32}
GD_SCRIPT = r'''extends SceneTree
func _init():
var dir = OS.get_cmdline_user_args()[0]
var lines = FileAccess.get_file_as_string(dir + "/jobs.txt").split("\n", false)
for line in lines:
var a = line.split(" ")
var data = FileAccess.get_file_as_bytes(dir + "/" + a[0])
var img = Image.create_from_data(int(a[1]), int(a[2]), false, int(a[3]), data)
img.decompress()
if a[4] == "1":
img.convert(Image.FORMAT_RGBAF)
else:
img.convert(Image.FORMAT_RGBA8)
var f = FileAccess.open(dir + "/" + a[0] + ".out", FileAccess.WRITE)
f.store_buffer(img.get_data())
f.close()
quit()
'''
def godot(ctx, jobs):
work = tempfile.mkdtemp(prefix="formats-godot-")
try:
lines = []
for i, (data, w, h, fmt, flt) in enumerate(jobs):
with open(os.path.join(work, "j%d" % i), "wb") as f:
f.write(data)
lines.append("j%d %d %d %d %d" % (i, w, h, fmt, 1 if flt else 0))
with open(os.path.join(work, "jobs.txt"), "w") as f:
f.write("\n".join(lines) + "\n")
with open(os.path.join(work, "run.gd"), "w") as f:
f.write(GD_SCRIPT)
ctx.nix("godot", ["godot", "--headless", "--script", os.path.join(work, "run.gd"), "--", work])
out = []
for i in range(len(jobs)):
with open(os.path.join(work, "j%d.out" % i), "rb") as f:
out.append(f.read())
return out
finally:
shutil.rmtree(work, ignore_errors=True)
def pillow(ctx, files):
"""files: list of bytes (any format Pillow reads) -> list of (mode, w, h, raw bytes)"""
work = tempfile.mkdtemp(prefix="formats-pillow-")
try:
for i, data in enumerate(files):
with open(os.path.join(work, "f%d" % i), "wb") as f:
f.write(data)
code = ("import os\nfrom PIL import Image\nw=%r\nfor i in range(%d):\n"
" im=Image.open(os.path.join(w,'f%%d'%%i)); im.load()\n"
" open(os.path.join(w,'f%%d.out'%%i),'wb').write(im.tobytes())\n"
" open(os.path.join(w,'f%%d.mode'%%i),'w').write('%%s %%d %%d'%%(im.mode,im.width,im.height))\n") % (work, len(files))
ctx.python(["pillow"], code)
out = []
for i in range(len(files)):
mode, w, h = open(os.path.join(work, "f%d.mode" % i)).read().split()
out.append((mode, int(w), int(h), open(os.path.join(work, "f%d.out" % i), "rb").read()))
return out
finally:
shutil.rmtree(work, ignore_errors=True)
def dds_header(w, h, pf, caps=0x1000, mips=0, flags=0x1007, pitch=0, depth=0, caps2=0):
if mips:
flags |= 0x20000
return (b"DDS " + struct.pack("<7I", 124, flags, h, w, pitch, depth, mips) + b"\0" * 44 + pf +
struct.pack("<4I", caps, caps2, 0, 0) + b"\0" * 4)
def dds_dx10(w, h, dxgi, data, array=1, misc=0, mips=0, caps2=0):
pf = struct.pack("<2I", 32, 4) + b"DX10" + b"\0" * 20
return dds_header(w, h, pf, mips=mips, caps2=caps2) + struct.pack("<5I", dxgi, 3, misc, array, 0) + data
def dds_fourcc(w, h, fourcc, data, mips=0, caps2=0):
pf = struct.pack("<2I", 32, 4) + fourcc + b"\0" * 20
return dds_header(w, h, pf, mips=mips, caps2=caps2) + data
def rgba_from(mode, raw):
"""Pillow raw bytes of mode L / RGB / RGBA -> rgba8 bytes"""
if mode == "RGBA":
return raw
out = bytearray()
if mode == "L":
for v in raw:
out += bytes((v, v, v, 255))
elif mode == "LA":
for i in range(0, len(raw), 2):
out += bytes((raw[i], raw[i], raw[i], raw[i + 1]))
elif mode == "RGB":
for i in range(0, len(raw), 3):
out += raw[i:i + 3] + b"\xff"
else:
raise ValueError(mode)
return bytes(out)
+66
View File
@@ -0,0 +1,66 @@
# ANI fixtures (tools/fixtures.py): animated cursors assembled here around ICO / CUR frames written by Pillow (32 x 32
# RGBA; the CUR ones patched from Pillow's ICO with hotspots): with seq + rate chunks, with neither, with INFO text, and
# one with AF_ICON clear (UNSUPPORTED). References: Pillow's decode of every frame, the step order and delays here.
# tests/gen/ani.luau { cases = { { name, data, w, h, steps = { { frame, delay } }, frames = { rgba }, hotspot?,
# title?, unsupported? } } }
import importlib.util, os, struct
def _load(n):
spec = importlib.util.spec_from_file_location(n, os.path.join(os.path.dirname(os.path.abspath(__file__)), n + ".py"))
m = importlib.util.module_from_spec(spec)
spec.loader.exec_module(m)
return m
R, T = _load("_raster_ref"), _load("_tex_reference")
def chunk(cid, data):
return cid + struct.pack("<I", len(data)) + data + (b"\0" if len(data) % 2 else b"")
def riff_list(kind, items):
return chunk(b"LIST", kind + b"".join(chunk(c, d) for c, d in items))
def ani(icons, steps=None, rates=None, disp=10, flags=1, title=None):
n = len(icons)
ns = len(steps) if steps else n
body = b"ACON" + chunk(b"anih", struct.pack("<9I", 36, n, ns, 32, 32, 32, 1, disp, flags | (2 if steps else 0)))
if title:
body += riff_list(b"INFO", [(b"INAM", title.encode() + b"\0")])
if rates:
body += chunk(b"rate", struct.pack("<%dI" % len(rates), *rates))
if steps:
body += chunk(b"seq ", struct.pack("<%dI" % len(steps), *steps))
body += riff_list(b"fram", [(b"icon", d) for d in icons])
return b"RIFF" + struct.pack("<I", len(body)) + body
def generate(ctx):
w = R.Work(ctx)
try:
for i in range(4):
px = bytes(v for p in range(32 * 32) for v in (((p * (i + 3)) % 256, 40 * i, (p // 32) * 8, 255 if (p + i) % 5 else 0)))
w.png("f%d.png" % i, 32, 32, px)
ctx.python(["pillow"], "from PIL import Image\nimport os\nos.chdir(%r)\nfor i in range(4):\n Image.open('f%%d.png' %% i).save('f%%d.ico' %% i, sizes=[(32, 32)])\n" % w.dir)
icos = [w.read("f%d.ico" % i) for i in range(4)]
# CUR: type 2, the planes / bit count fields of the entry become the hotspot
curs = []
for i, d in enumerate(icos):
b = bytearray(d)
b[2:4] = struct.pack("<H", 2)
b[6 + 4:6 + 8] = struct.pack("<HH", 3 + i, 7)
curs.append(bytes(b))
refs = [T.rgba_from(m, raw) for (m, ww, hh, raw) in T.pillow(ctx, icos)]
cases = []
steps, rates = [0, 1, 2, 1, 3], [6, 12, 6, 30, 3]
cases.append({"name": "seq + rate", "data": ani(icos, steps, rates, title="spinner"), "w": 32, "h": 32,
"steps": [{"frame": s + 1, "delay": r / 60} for s, r in zip(steps, rates)], "frames": refs, "title": "spinner"})
cases.append({"name": "plain", "data": ani(icos[:3], disp=4), "w": 32, "h": 32,
"steps": [{"frame": i + 1, "delay": 4 / 60} for i in range(3)], "frames": refs[:3]})
cases.append({"name": "cursor frames", "data": ani(curs[:2], disp=8), "w": 32, "h": 32,
"steps": [{"frame": i + 1, "delay": 8 / 60} for i in range(2)], "frames": refs[:2], "hotspot": [3, 7]})
cases.append({"name": "raw bitmaps", "data": ani(icos[:1], flags=0), "unsupported": True})
ctx.emit("ani", {"cases": cases})
finally:
w.close()
+119
View File
@@ -0,0 +1,119 @@
# BCn fixtures (tools/fixtures.py): random BC1..BC7 blocks (every BC7 mode and BC6H mode forced in turn, the BC1
# 3-colour mode, odd image sizes) decoded by two references: Pillow's DDS reader and Godot 4 (bcdec); plus encoder
# baselines: test images and the PSNR Pillow's own BC1 / BC3 / BC5 encoder reaches on them.
# tests/gen/bcn.luau { cases = { { name, kind, w, h, data, pillow?, godot?, tol } }, enc = { { name, w, h,
# rgba, psnr = { bc1, bc3, bc5 } } } } (pillow / godot: rgba8 bytes, or rgbaf32 for BC6H)
# tests/gen/bcn_bench.luau a 256 x 256 image and random BC1 / BC6H / BC7 blocks for tools/bench.luau
import importlib.util, math, os, random, struct
_spec = importlib.util.spec_from_file_location("_tex_reference", os.path.join(os.path.dirname(os.path.abspath(__file__)), "_tex_reference.py"))
R = importlib.util.module_from_spec(_spec)
_spec.loader.exec_module(R)
DXGI = {"bc1": 71, "bc2": 74, "bc3": 77, "bc4": 80, "bc5": 83, "bc5s": 84, "bc6h": 95, "bc6hs": 96, "bc7": 98}
BLOCK = {"bc1": 8, "bc2": 16, "bc3": 16, "bc4": 8, "bc5": 16, "bc5s": 16, "bc6h": 16, "bc6hs": 16, "bc7": 16}
BC6_HEADERS = [0, 1, 2, 6, 10, 14, 18, 22, 26, 30, 3, 7, 11, 15, 19, 23, 27, 31]
def blocks(rng, kind, n, mode=None):
out = bytearray()
for _ in range(n):
b = bytearray(rng.getrandbits(8) for _ in range(BLOCK[kind]))
if kind == "bc7" and mode is not None:
b[0] = (b[0] & ~((2 << mode) - 1) & 0xFF) | (1 << mode)
elif kind.startswith("bc6h") and mode is not None:
bitsn = 2 if mode < 2 else 5
b[0] = (b[0] & ~((1 << bitsn) - 1) & 0xFF) | mode
out += b
return bytes(out)
def test_image(w, h, rng, alpha):
px = bytearray()
for y in range(h):
for x in range(w):
r = int(128 + 100 * math.sin(x / 7.0) * math.cos(y / 11.0))
g = int(255 * x / (w - 1))
b = int(255 * y / (h - 1)) if (x // 16 + y // 16) % 2 else 40
n = rng.randrange(-12, 13)
r, g, b = [max(0, min(255, v + n)) for v in (r, g, b)]
a = 255
if alpha:
a = 0 if (x - w / 2) ** 2 + (y - h / 2) ** 2 < (w / 4) ** 2 else 255
px += bytes((r, g, b, a))
return bytes(px)
def psnr(a, b, channels):
se, n = 0, 0
for i in range(0, len(a), 4):
for c in channels:
d = a[i + c] - b[i + c]
se += d * d
n += 1
return 99.0 if se == 0 else 10 * math.log10(255 * 255 * n / se)
def generate(ctx):
rng = random.Random(7)
cases = []
def add(name, kind, w, h, data):
cases.append({"name": name, "kind": kind, "w": w, "h": h, "data": data})
for kind in ("bc1", "bc2", "bc3", "bc4", "bc5", "bc5s"):
add(kind + " 32x32", kind, 32, 32, blocks(rng, kind, 64))
add(kind + " 13x7", kind, 13, 7, blocks(rng, kind, 8))
for m in range(8):
add("bc7 mode %d" % m, "bc7", 32, 16, blocks(rng, "bc7", 32, m))
add("bc7 15x9", "bc7", 15, 9, blocks(rng, "bc7", 12))
for kind in ("bc6h", "bc6hs"):
for m in BC6_HEADERS:
add("%s mode %d" % (kind, m), kind, 16, 16, blocks(rng, kind, 16, m))
# Pillow (BC1..BC5, BC5S, BC7, BC6H as clamped 8-bit)
files = [R.dds_dx10(c["w"], c["h"], DXGI[c["kind"]], c["data"]) for c in cases]
for c, (mode, w, h, raw) in zip(cases, R.pillow(ctx, files)):
c["pillow"] = R.rgba_from(mode, raw)
# Godot (bcdec): everything but the signed BC5 (no Godot format); BC6H as floats
gj, gi = [], []
for i, c in enumerate(cases):
if c["kind"] in R.GODOT:
gj.append((c["data"], c["w"], c["h"], R.GODOT[c["kind"]], c["kind"].startswith("bc6h")))
gi.append(i)
for i, out in zip(gi, R.godot(ctx, gj)):
cases[i]["godot"] = out
# encoder baselines: Pillow's encoder on the same images, decoded by Pillow
enc = []
for name, w, h, alpha in (("photo 64x64", 64, 64, False), ("alpha 64x48", 64, 48, True), ("odd 37x21", 37, 21, False)):
px = test_image(w, h, rng, alpha)
e = {"name": name, "w": w, "h": h, "rgba": px, "psnr": {}}
enc.append(e)
import tempfile, shutil
work = tempfile.mkdtemp(prefix="formats-bcn-")
try:
for i, e in enumerate(enc):
open(os.path.join(work, "src%d" % i), "wb").write(e["rgba"])
code = ("import os\nfrom PIL import Image\nw=%r\n"
"for i, (W, H) in enumerate(%r):\n"
" im=Image.frombytes('RGBA',(W,H),open(os.path.join(w,'src%%d'%%i),'rb').read())\n"
" for pf in ('DXT1','DXT5','BC5'):\n"
" p=os.path.join(w,'e%%d_%%s.dds'%%(i,pf))\n"
" (im if pf!='BC5' else im.convert('RGB')).save(p,pixel_format=pf)\n"
" back=Image.open(p).convert('RGBA')\n"
" open(p+'.rgba','wb').write(back.tobytes())\n") % (work, [(e["w"], e["h"]) for e in enc])
ctx.python(["pillow"], code)
for i, e in enumerate(enc):
for pf, kind, ch in (("DXT1", "bc1", (0, 1, 2)), ("DXT5", "bc3", (0, 1, 2, 3)), ("BC5", "bc5", (0, 1))):
back = open(os.path.join(work, "e%d_%s.dds.rgba" % (i, pf)), "rb").read()
e["psnr"][kind] = psnr(e["rgba"], back, ch)
finally:
shutil.rmtree(work, ignore_errors=True)
ctx.emit("bcn", {"cases": cases, "enc": enc})
# bench: a 512 x 512 image, and random BC7 blocks of every mode
w = h = 256
px = test_image(w, h, rng, True)
bench = {"w": w, "h": h, "rgba": px, "bc7": blocks(rng, "bc7", (w // 4) * (h // 4)),
"bc1": blocks(rng, "bc1", (w // 4) * (h // 4)), "bc6h": blocks(rng, "bc6h", (w // 4) * (h // 4), 3)}
ctx.emit("bcn_bench", bench)
+332
View File
@@ -0,0 +1,332 @@
# DDS fixtures (tools/fixtures.py):
# - files written by NVIDIA Texture Tools (nvcompress: uncompressed BGRA, BC1 / BC1a / BC2 / BC3 / BC4 / BC5 / BC6H /
# BC7, with and without mip chains, legacy and DX10 headers; nvassemble: cube maps, arrays, volumes) and by
# ImageMagick (none / DXT1 / DXT5 with mip maps);
# - hand-written ones for the uncompressed DXGI and legacy formats nothing here writes (floats, snorm, packed,
# shared exponent, YUY2, luminance, bit masks, D3DFMT numbers), with the values they hold;
# - our encoder's files (tools/fixtures/_tex_encode.luau -a dds) read back by Pillow and nvddsinfo.
# Reference pixels: every surface is cut out here (an independent walk of the DDS layout) and decoded by Pillow
# (BCn through a one-surface DX10 file; BC6H by Godot as floats); the hand-written files carry their expected values.
# tests/gen/dds.luau { cases = { { name, data, layout, mips, layers, depth, surfaces = { { level, layer, slice, w,
# h, rgba?, floats?, tol } } } }, ours = { { name, data, pillow?, info } } }
import importlib.util, json, math, os, random, shutil, struct, subprocess, tempfile, zlib
_spec = importlib.util.spec_from_file_location("_tex_reference", os.path.join(os.path.dirname(os.path.abspath(__file__)), "_tex_reference.py"))
R = importlib.util.module_from_spec(_spec)
_spec.loader.exec_module(R)
INPUTS = ["tools/fixtures/_tex_encode.luau", "src/Formats/image/dds", "src/Formats/codecs/image/Bcn", "src/Formats/codecs/image/Texture.luau"]
BLOCK = {"bc1": 8, "bc2": 16, "bc3": 16, "bc4": 8, "bc5": 16, "bc6h": 16, "bc7": 16}
DXGI_BC = {70: "bc1", 71: "bc1", 72: "bc1", 73: "bc2", 74: "bc2", 75: "bc2", 76: "bc3", 77: "bc3", 78: "bc3", 79: "bc4",
80: "bc4", 82: "bc5", 83: "bc5", 94: "bc6h", 95: "bc6h", 97: "bc7", 98: "bc7", 99: "bc7"}
FOURCC_BC = {b"DXT1": "bc1", b"DXT3": "bc2", b"DXT5": "bc3", b"ATI1": "bc4", b"BC4U": "bc4", b"ATI2": "bc5", b"BC5U": "bc5"}
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 source(w, h, salt=0):
out = bytearray()
for y in range(h):
for x in range(w):
r = x / max(1, w - 1)
g = y / max(1, h - 1)
b = ((x * 7 + y * 13 + salt * 31) % 64) / 63
a = ((x + y + salt) % 5) / 4
out += bytes(int(v * 255 + 0.5) for v in (r, g, b, a))
return bytes(out)
def layout(data):
"""an independent walk of a DDS file: (info, [(level, layer, slice, w, h, format, offset, size)])"""
flags, h, w, pitch, depth, mips = struct.unpack("<6I", data[8:32])
pf_flags, fourcc, bits, rm, gm, bm, am = struct.unpack("<I4s5I", data[80:108])
caps2 = struct.unpack("<I", data[112:116])[0]
mips = max(1, mips if flags & 0x20000 else 1)
off, layers, fmt, cube = 128, 1, None, False
if pf_flags & 4 and fourcc == b"DX10":
dxgi, dim, misc, arr = struct.unpack("<4I", data[128:144])
off, layers = 148, max(1, arr)
fmt = DXGI_BC.get(dxgi) or ("dxgi%d" % dxgi)
cube = bool(misc & 4)
volume = dim == 4
elif pf_flags & 4:
fmt = FOURCC_BC[fourcc]
volume = bool(caps2 & 0x200000)
cube = bool(caps2 & 0x200)
else:
fmt = "rgb%d" % bits
volume = bool(caps2 & 0x200000)
cube = bool(caps2 & 0x200)
d0 = max(1, depth) if volume else 1
count = layers * (6 if cube else 1)
out = []
for layer in range(count):
lw, lh, ld = w, h, d0
for level in range(mips):
if fmt in BLOCK:
size = ((lw + 3) // 4) * ((lh + 3) // 4) * BLOCK[fmt]
elif fmt.startswith("rgb"):
size = lw * lh * bits // 8
else:
size = lw * lh * 4 # dxgi28 / 87 (the only uncompressed DX10 ones nvassemble writes)
for s in range(ld):
out.append((level, layer, s, lw, lh, fmt, off, size))
off += size
lw, lh, ld = max(1, lw // 2), max(1, lh // 2), max(1, ld // 2)
return {"w": w, "h": h, "mips": mips, "layers": layers, "cube": cube, "volume": volume, "depth": d0, "masks": (rm, gm, bm, am), "bits": bits}, out
def mask_decode(raw, bits, masks):
"""legacy bit-mask pixels -> rgba8 with rounding (the Texel rule)"""
out = bytearray()
nb = bits // 8
for i in range(0, len(raw), nb):
v = int.from_bytes(raw[i:i + nb], "little")
px = []
for k, m in enumerate(masks):
if m == 0:
px.append(255 if k == 3 else 0)
continue
sh = (m & -m).bit_length() - 1
mx = m >> sh
px.append(int(((v & m) >> sh) / mx * 255 + 0.5))
out += bytes(px)
return bytes(out)
def references(ctx, cases):
"""fill c["surfaces"] for files from the tools: Pillow per surface (BCn / masks), Godot floats for BC6H"""
pil_files, pil_targets, gd_jobs, gd_targets = [], [], [], []
for c in cases:
info, surf = layout(c["data"])
c["layout"] = "volume" if info["volume"] else ("cube" if info["cube"] else ("array" if info["layers"] > 1 else "2d"))
c["mips"], c["layers"], c["depth"] = info["mips"], info["layers"], info["depth"]
c["surfaces"] = []
for (level, layer, s, w, h, fmt, off, size) in surf:
if level > 0 and (layer > 0 or s > 0):
continue
sd = {"level": level, "layer": layer, "slice": s, "w": w, "h": h, "tol": 0}
raw = c["data"][off:off + size]
c["surfaces"].append(sd)
if fmt == "bc6h":
gd_jobs.append((raw, w, h, R.GODOT["bc6h"], True))
gd_targets.append(sd)
elif fmt in BLOCK:
dx = {"bc1": 71, "bc2": 74, "bc3": 77, "bc4": 80, "bc5": 83, "bc7": 98}[fmt]
pil_files.append(R.dds_dx10(w, h, dx, raw))
pil_targets.append((sd, fmt))
elif fmt.startswith("rgb"):
sd["rgba"] = mask_decode(raw, info["bits"], info["masks"])
elif fmt == "dxgi28":
sd["rgba"] = raw
elif fmt == "dxgi87":
sd["rgba"] = bytes(raw[i + k] for i in range(0, len(raw), 4) for k in (2, 1, 0, 3))
for (sd, fmt), (mode, w, h, raw) in zip(pil_targets, R.pillow(ctx, pil_files)):
rgba = R.rgba_from(mode, raw)
if fmt == "bc5":
rgba = bytes(v if i % 4 < 2 else (255 if i % 4 == 3 else 0) for i, v in enumerate(rgba))
sd["rgba"] = rgba
for sd, out in zip(gd_targets, R.godot(ctx, gd_jobs)):
sd["floats"] = out
def hand_cases(rng):
"""uncompressed formats with known values: (name, dds bytes, expected rgba8, expected floats or None)"""
W, H = 5, 3
cases = []
def f32(v):
return struct.unpack("<f", struct.pack("<f", v))[0]
def half(v):
return struct.unpack("<e", struct.pack("<e", v))[0]
def q8(v):
return 0 if v != v or v <= 0 else (255 if v >= 1 else int(v * 255 + 0.5))
def add(name, dds, texels):
"""texels: list of (r, g, b, a) floats (the native values) -> expected rgba8 by the rules"""
cases.append({"name": name, "data": dds, "rgba8": bytes(q8(v) for t in texels for v in t),
"floats": b"".join(struct.pack("<4f", *t) for t in texels)})
# floats
vals = [(rng.uniform(-0.5, 3), rng.uniform(0, 1), rng.uniform(0, 1.5), rng.uniform(0, 1)) for _ in range(W * H)]
data = b"".join(struct.pack("<4f", *v) for v in vals)
add("dxgi R32G32B32A32_FLOAT", R.dds_dx10(W, H, 2, data), [tuple(f32(x) for x in v) for v in vals])
data = b"".join(struct.pack("<4e", *v) for v in vals)
add("dxgi R16G16B16A16_FLOAT", R.dds_dx10(W, H, 10, data), [tuple(half(x) for x in v) for v in vals])
add("d3dfmt 113 (A16B16G16R16F)", R.dds_fourcc(W, H, struct.pack("<I", 113), data), [tuple(half(x) for x in v) for v in vals])
data = b"".join(struct.pack("<f", v[0]) for v in vals)
add("dxgi R32_FLOAT (grey)", R.dds_dx10(W, H, 41, data), [(f32(v[0]),) * 3 + (1.0,) for v in vals])
data = b"".join(struct.pack("<2e", v[0], v[1]) for v in vals)
add("dxgi R16G16_FLOAT", R.dds_dx10(W, H, 34, data), [(half(v[0]), half(v[1]), 0.0, 1.0) for v in vals])
data = b"".join(struct.pack("<3f", *v[:3]) for v in vals)
add("dxgi R32G32B32_FLOAT", R.dds_dx10(W, H, 6, data), [tuple(f32(x) for x in v[:3]) + (1.0,) for v in vals])
# unorm / snorm
u16 = [tuple(rng.randrange(65536) for _ in range(4)) for _ in range(W * H)]
add("dxgi R16G16B16A16_UNORM", R.dds_dx10(W, H, 11, b"".join(struct.pack("<4H", *v) for v in u16)),
[tuple(x / 65535 for x in v) for v in u16])
add("d3dfmt 36 (A16B16G16R16)", R.dds_fourcc(W, H, struct.pack("<I", 36), b"".join(struct.pack("<4H", *v) for v in u16)),
[tuple(x / 65535 for x in v) for v in u16])
s8 = [tuple(rng.randrange(-128, 128) for _ in range(4)) for _ in range(W * H)]
cases_s8 = [tuple(max(x, -127) / 127 for x in v) for v in s8]
cases.append({"name": "dxgi R8G8B8A8_SNORM", "data": R.dds_dx10(W, H, 31, b"".join(struct.pack("<4b", *v) for v in s8)),
"rgba8": bytes(max(x, -127) + 128 for v in s8 for x in v),
"floats": b"".join(struct.pack("<4f", *v) for v in cases_s8)})
u8 = [tuple(rng.randrange(256) for _ in range(4)) for _ in range(W * H)]
add("dxgi R8_UNORM (grey)", R.dds_dx10(W, H, 61, bytes(v[0] for v in u8)), [(v[0] / 255,) * 3 + (1.0,) for v in u8])
add("dxgi R8G8_UNORM", R.dds_dx10(W, H, 49, bytes(x for v in u8 for x in v[:2])), [(v[0] / 255, v[1] / 255, 0.0, 1.0) for v in u8])
add("dxgi A8_UNORM", R.dds_dx10(W, H, 65, bytes(v[3] for v in u8)), [(0.0, 0.0, 0.0, v[3] / 255) for v in u8])
add("dxgi B8G8R8X8_UNORM", R.dds_dx10(W, H, 88, bytes(x for v in u8 for x in (v[2], v[1], v[0], 7))),
[(v[0] / 255, v[1] / 255, v[2] / 255, 1.0) for v in u8])
add("dxgi R16_UNORM (grey)", R.dds_dx10(W, H, 56, b"".join(struct.pack("<H", v[0]) for v in u16)), [(v[0] / 65535,) * 3 + (1.0,) for v in u16])
# packed
p32 = [rng.getrandbits(32) for _ in range(W * H)]
add("dxgi R10G10B10A2_UNORM", R.dds_dx10(W, H, 24, b"".join(struct.pack("<I", v) for v in p32)),
[((v & 1023) / 1023, ((v >> 10) & 1023) / 1023, ((v >> 20) & 1023) / 1023, (v >> 30) / 3) for v in p32])
def uf(v, mb):
e, m = v >> mb, v & ((1 << mb) - 1)
if e == 0:
return m / (1 << mb) * 2 ** -14
return (1 + m / (1 << mb)) * 2 ** (e - 15)
p11 = [rng.getrandbits(32) & ~((1 << 30) | (1 << 9) | (1 << 20)) for _ in range(W * H)] # keep exponents < 31
add("dxgi R11G11B10_FLOAT", R.dds_dx10(W, H, 26, b"".join(struct.pack("<I", v) for v in p11)),
[(uf(v & 2047, 6), uf((v >> 11) & 2047, 6), uf(v >> 22, 5), 1.0) for v in p11])
add("dxgi R9G9B9E5_SHAREDEXP", R.dds_dx10(W, H, 67, b"".join(struct.pack("<I", v) for v in p32)),
[tuple((v >> (9 * k) & 511) * 2.0 ** ((v >> 27) - 24) for k in range(3)) + (1.0,) for v in p32])
p16 = [rng.getrandbits(16) for _ in range(W * H)]
add("dxgi B5G6R5_UNORM", R.dds_dx10(W, H, 85, b"".join(struct.pack("<H", v) for v in p16)),
[((v >> 11) / 31, ((v >> 5) & 63) / 63, (v & 31) / 31, 1.0) for v in p16])
add("dxgi B5G5R5A1_UNORM", R.dds_dx10(W, H, 86, b"".join(struct.pack("<H", v) for v in p16)),
[(((v >> 10) & 31) / 31, ((v >> 5) & 31) / 31, (v & 31) / 31, (v >> 15) * 1.0) for v in p16])
add("dxgi B4G4R4A4_UNORM", R.dds_dx10(W, H, 115, b"".join(struct.pack("<H", v) for v in p16)),
[(((v >> 8) & 15) / 15, ((v >> 4) & 15) / 15, (v & 15) / 15, (v >> 12) / 15) for v in p16])
# legacy masks
def legacy(bits, flags, masks, data):
pf = struct.pack("<2I4s5I", 32, flags, b"\0\0\0\0", bits, *masks)
return R.dds_header(W, H, pf) + data
add("legacy R5G6B5", legacy(16, 0x40, (0xF800, 0x7E0, 0x1F, 0), b"".join(struct.pack("<H", v) for v in p16)),
[((v >> 11) / 31, ((v >> 5) & 63) / 63, (v & 31) / 31, 1.0) for v in p16])
add("legacy A1R5G5B5", legacy(16, 0x41, (0x7C00, 0x3E0, 0x1F, 0x8000), b"".join(struct.pack("<H", v) for v in p16)),
[(((v >> 10) & 31) / 31, ((v >> 5) & 31) / 31, (v & 31) / 31, (v >> 15) * 1.0) for v in p16])
add("legacy X8R8G8B8", legacy(32, 0x40, (0xFF0000, 0xFF00, 0xFF, 0), b"".join(struct.pack("<I", v) for v in p32)),
[(((v >> 16) & 255) / 255, ((v >> 8) & 255) / 255, (v & 255) / 255, 1.0) for v in p32])
add("legacy R8G8B8 (24-bit)", legacy(24, 0x40, (0xFF0000, 0xFF00, 0xFF, 0), b"".join(struct.pack("<I", v)[:3] for v in p32)),
[(((v >> 16) & 255) / 255, ((v >> 8) & 255) / 255, (v & 255) / 255, 1.0) for v in p32])
add("legacy A2B10G10R10", legacy(32, 0x41, (0x3FF, 0xFFC00, 0x3FF00000, 0xC0000000), b"".join(struct.pack("<I", v) for v in p32)),
[((v & 1023) / 1023, ((v >> 10) & 1023) / 1023, ((v >> 20) & 1023) / 1023, (v >> 30) / 3) for v in p32])
add("legacy L8", legacy(8, 0x20000, (0xFF, 0, 0, 0), bytes(v[0] for v in u8)), [(v[0] / 255,) * 3 + (1.0,) for v in u8])
add("legacy A8L8", legacy(16, 0x20001, (0xFF, 0, 0, 0xFF00), bytes(x for v in u8 for x in (v[0], v[3]))),
[(v[0] / 255,) * 3 + (v[3] / 255,) for v in u8])
add("legacy A8", legacy(8, 0x2, (0, 0, 0, 0xFF), bytes(v[3] for v in u8)), [(0.0, 0.0, 0.0, v[3] / 255) for v in u8])
add("legacy A4R4G4B4", legacy(16, 0x41, (0xF00, 0xF0, 0xF, 0xF000), b"".join(struct.pack("<H", v) for v in p16)),
[(((v >> 8) & 15) / 15, ((v >> 4) & 15) / 15, (v & 15) / 15, (v >> 12) / 15) for v in p16])
# YUY2 (BT.601 limited range)
def ycc(y, u, v):
c, d, e = 1.164 * (y - 16), u - 128, v - 128
cl = lambda x: max(0, min(255, int(math.floor(x + 0.5))))
return (cl(c + 1.596 * e), cl(c - 0.392 * d - 0.813 * e), cl(c + 2.017 * d), 255)
W2 = 6
yuy = bytes(rng.randrange(16, 240) for _ in range(W2 * H * 2))
exp = []
for y in range(H):
for x in range(W2):
q = y * W2 * 2 + (x // 2) * 4
exp.append(ycc(yuy[q + (2 if x % 2 else 0)], yuy[q + 1], yuy[q + 3]))
pf = struct.pack("<2I4s5I", 32, 4, b"YUY2", 0, 0, 0, 0, 0)
cases.append({"name": "fourcc YUY2", "data": R.dds_header(W2, H, pf) + yuy, "rgba8": bytes(v for t in exp for v in t)})
return cases
def generate(ctx):
rng = random.Random(5)
work = tempfile.mkdtemp(prefix="formats-dds-")
try:
cases = _tools(ctx, work)
references(ctx, cases)
hand = hand_cases(rng)
ours = _ours(ctx, work)
finally:
shutil.rmtree(work, ignore_errors=True)
ctx.emit("dds", {"cases": cases, "hand": hand, "ours": ours})
def _tools(ctx, work):
cases = []
for name, w, h in (("a", 37, 23), ("b", 64, 32)):
with open(os.path.join(work, name + ".png"), "wb") as f:
f.write(png(w, h, source(w, h)))
jobs = []
for src in ("a", "b"):
for fl in ("-rgb", "-bc1", "-bc1a", "-bc2", "-bc3", "-bc4", "-bc5", "-bc7"):
jobs.append((src, fl, []))
jobs.append((src, "-bc1", ["-nomips", "-dds10"]))
jobs.append(("a", "-bc6", ["-nomips"]))
script = []
for src, fl, extra in jobs:
out = "%s%s%s.dds" % (src, fl, "".join(extra))
script.append("nvcompress -silent %s %s %s.png %s" % (fl, " ".join(extra), src, out))
for i in range(6):
with open(os.path.join(work, "f%d.png" % i), "wb") as f:
f.write(png(16, 16, source(16, 16, i + 1)))
faces = " ".join("f%d.png" % i for i in range(6))
script.append("nvassemble -cube %s -o cube.dds" % faces)
script.append("nvassemble -array f0.png f1.png f2.png -o array.dds")
script.append("nvassemble -volume f0.png f1.png f2.png f3.png -o volume.dds")
ctx.nix("nvidia-texture-tools", ["sh", "-c", "cd %s && %s" % (work, " && ".join(script))])
im = []
for comp in ("none", "dxt1", "dxt5"):
im.append("magick a.png -define dds:compression=%s -define dds:mipmaps=3 im_%s.dds" % (comp, comp))
ctx.nix("imagemagick", ["sh", "-c", "cd %s && %s" % (work, " && ".join(im))])
names = ["%s%s%s.dds" % (s, f, "".join(e)) for s, f, e in jobs] + ["cube.dds", "array.dds", "volume.dds"] + ["im_%s.dds" % c for c in ("none", "dxt1", "dxt5")]
for n in names:
cases.append({"name": n, "data": open(os.path.join(work, n), "rb").read()})
return cases
def _ours(ctx, work):
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", "dds"], cwd=ctx.root, capture_output=True, check=True)
files = {}
for line in res.stdout.decode().split("\n"):
if "\t" in line:
n, hx = line.split("\t", 1)
files[n] = bytes.fromhex(hx.strip())
out = []
pil, pil_idx = [], []
names = sorted(files)
for n in names:
with open(os.path.join(work, n), "wb") as f:
f.write(files[n])
info = ctx.nix("nvidia-texture-tools", ["sh", "-c", "cd %s && for f in %s; do echo \"== $f\"; nvddsinfo $f; done" % (work, " ".join(names))]).decode(errors="replace")
blocks = {}
for part in info.split("== ")[1:]:
n, body = part.split("\n", 1)
blocks[n.strip()] = body
for i, n in enumerate(names):
body = blocks.get(n, "")
def field(key):
for line in body.split("\n"):
if line.strip().startswith(key):
return line.split(":", 1)[1].strip()
return ""
e = {"name": n, "data": files[n], "width": int(field("Width") or 0), "height": int(field("Height") or 0),
"mipcount": int(field("Mipmap count") or 0), "dxgi": field("DXGI Format"), "array": field("Array size"),
"caps2": field("Caps 2")}
out.append(e)
if not any(k in n for k in ("rgba16", "rgba32f", "rgba16f", "cube", "array")):
pil.append(files[n])
pil_idx.append(i)
for i, (mode, w, h, raw) in zip(pil_idx, R.pillow(ctx, pil)):
out[i]["pillow"] = R.rgba_from(mode, raw)
out[i]["pillowMode"] = mode
return out
+128
View File
@@ -0,0 +1,128 @@
# ETC fixtures (tools/fixtures.py): random ETC1 / ETC2 / EAC blocks, sorted by mode so that every ETC2 mode
# (individual, differential, T, H, planar; punch-through opaque and transparent) and every EAC multiplier case is
# covered, decoded by Godot 4 (etcpak's decoder, through Image.decompress).
# tests/gen/etc.luau { { name, kind, w, h, data, godot (rgba8 bytes) } }
import importlib.util, os, random
_spec = importlib.util.spec_from_file_location("_tex_reference", os.path.join(os.path.dirname(os.path.abspath(__file__)), "_tex_reference.py"))
R = importlib.util.module_from_spec(_spec)
_spec.loader.exec_module(R)
def mode(b, punch):
"""the ETC2 mode of an 8-byte colour block"""
hi = int.from_bytes(b[:4], "big")
if not punch and not (hi >> 1) & 1:
return "individual"
def s3(v):
return v - 8 if v >= 4 else v
r, g, bb = (hi >> 27) & 31, (hi >> 19) & 31, (hi >> 11) & 31
dr, dg, db = s3((hi >> 24) & 7), s3((hi >> 16) & 7), s3((hi >> 8) & 7)
if not 0 <= r + dr <= 31:
return "T"
if not 0 <= g + dg <= 31:
return "H"
if not 0 <= bb + db <= 31:
return "planar"
return "differential"
def colour_blocks(rng, n, want, punch=False, opaque=None):
out = bytearray()
while len(out) < n * 8:
b = bytearray(rng.getrandbits(8) for _ in range(8))
if opaque is not None:
b[3] = (b[3] & 0xFD) | (2 if opaque else 0)
if mode(b, punch) == want:
out += b
return bytes(out)
def eac_blocks(rng, n, zero_mult=False):
out = bytearray()
for _ in range(n):
b = bytearray(rng.getrandbits(8) for _ in range(8))
if zero_mult:
b[1] &= 0x0F
out += b
return bytes(out)
EAC = [[-3, -6, -9, -15, 2, 5, 8, 14], [-3, -7, -10, -13, 2, 6, 9, 12], [-2, -5, -8, -13, 1, 4, 7, 12],
[-2, -4, -6, -13, 1, 3, 5, 12], [-3, -6, -8, -12, 2, 5, 7, 11], [-3, -7, -9, -11, 2, 6, 8, 10],
[-4, -7, -8, -11, 3, 6, 7, 10], [-3, -5, -8, -11, 2, 4, 7, 10], [-2, -6, -8, -10, 1, 5, 7, 9],
[-2, -5, -8, -10, 1, 4, 7, 9], [-2, -4, -8, -10, 1, 3, 7, 9], [-2, -5, -7, -10, 1, 4, 6, 9],
[-3, -4, -7, -10, 2, 3, 6, 9], [-1, -2, -3, -10, 0, 1, 2, 9], [-4, -6, -8, -9, 3, 5, 7, 8],
[-3, -5, -7, -9, 2, 4, 6, 8]]
def s11(c):
"""signed EAC R11 / RG11 -> the 11-bit values (-1023..1023) per pixel and channel, as a flat list"""
two = c["kind"] == "eac_rg11s"
w, h, data = c["w"], c["h"], c["data"]
bw = (w + 3) // 4
out = [0] * (w * h * 2)
step = 16 if two else 8
for bi in range(len(data) // step):
bx, by = bi % bw, bi // bw
for ch in range(2 if two else 1):
b = data[bi * step + ch * 8: bi * step + ch * 8 + 8]
base = b[0] - 256 if b[0] >= 128 else b[0]
base = max(base, -127)
mult, tab = b[1] >> 4, EAC[b[1] & 15]
bits = int.from_bytes(b[2:], "big")
for i in range(16):
m = tab[(bits >> (45 - 3 * i)) & 7]
v = base * 8 + (m * mult * 8 if mult else m)
v = max(-1023, min(1023, v))
x, y = bx * 4 + i // 4, by * 4 + i % 4
if x < w and y < h:
out[(y * w + x) * 2 + ch] = v
return out
def generate(ctx):
rng = random.Random(11)
cases = []
def add(name, kind, w, h, data):
cases.append({"name": name, "kind": kind, "w": w, "h": h, "data": data})
add("etc1 individual", "etc1", 16, 16, colour_blocks(rng, 16, "individual"))
add("etc1 differential", "etc1", 16, 16, colour_blocks(rng, 16, "differential"))
add("etc1 random 13x6", "etc1", 13, 6, bytes(rng.getrandbits(8) for _ in range(8 * 8)))
for m in ("individual", "differential", "T", "H", "planar"):
add("etc2_rgb " + m, "etc2_rgb", 16, 16, colour_blocks(rng, 16, m))
for m in ("differential", "T", "H", "planar"):
for op in (True, False):
add("etc2_rgba1 %s %s" % (m, "opaque" if op else "transparent"), "etc2_rgba1", 16, 16,
colour_blocks(rng, 16, m, True, op))
for m in ("individual", "differential", "T", "H", "planar"):
rgba = bytearray()
col = colour_blocks(rng, 16, m)
alpha = eac_blocks(rng, 16, m == "planar")
for i in range(16):
rgba += alpha[i * 8:i * 8 + 8] + col[i * 8:i * 8 + 8]
add("etc2_rgba " + m, "etc2_rgba", 16, 16, bytes(rgba))
for kind in ("eac_r11", "eac_r11s"):
add(kind, kind, 16, 16, eac_blocks(rng, 16))
add(kind + " multiplier 0", kind, 8, 8, eac_blocks(rng, 4, True))
for kind in ("eac_rg11", "eac_rg11s"):
add(kind, kind, 16, 12, eac_blocks(rng, 24))
add("etc2_rgb 10x5", "etc2_rgb", 10, 5, bytes(rng.getrandbits(8) for _ in range(6 * 8)))
# Godot cannot decode RGB A1 or the signed EAC kinds: A1 blocks go through it as ETC2 RGB (the test checks the
# punch-through rules on top; the opaque bit is set for Godot, else ETC2 RGB reads the individual mode), signed EAC is checked against s11() below (the KDFS 1.3 rule, written here)
jobs, idx = [], []
for i, c in enumerate(cases):
k = "etc2_rgb" if c["kind"] == "etc2_rgba1" else c["kind"]
if k in ("eac_r11s", "eac_rg11s"):
c["spec"] = s11(c)
else:
data = c["data"]
if c["kind"] == "etc2_rgba1": # with the opaque bit set: ETC2 RGB's differential / T / H / planar
data = bytes(v | 2 if i % 8 == 3 else v for i, v in enumerate(data))
jobs.append((data, c["w"], c["h"], R.GODOT[k], False))
idx.append(i)
for i, out in zip(idx, R.godot(ctx, jobs)):
cases[i]["godot"] = out
ctx.emit("etc", cases)
+195
View File
@@ -0,0 +1,195 @@
# OpenEXR fixtures (tools/fixtures.py): files written by the OpenEXR 3.5 python bindings (every compression NONE /
# RLE / ZIPS / ZIP / PIZ, HALF / FLOAT / UINT channels, odd sizes, an offset data window, decreasing line order, a
# Y-only image, a layer (diffuse.R ...), subsampled channels, PXR24 / B44 / DWAA for the UNSUPPORTED path), tiled
# versions by exrmaketiled (one level, mip-map with unfiltered levels, rip-map, round up, several compressions),
# multipart files by exrmultipart; our encoder's files (tools/fixtures/_tex_encode.luau -a exr) read back by the
# bindings and exrheader. References: the bindings' read of each file (RGBA as little-endian f32; Y as grey).
# tests/gen/exr.luau { cases = { { name, data, w, h, floats?, unsupported?, opts?, mips? } }, ours = { { name,
# data, floats, compression, header_ok } } }
# tests/gen/exr_bench.luau a 512 x 256 half RGBA image in ZIP and PIZ
import os, shutil, subprocess, tempfile
INPUTS = ["tools/fixtures/_tex_encode.luau", "src/Formats/image/exr"]
WRITE = r'''
import OpenEXR, numpy as np, os, sys, json
w = sys.argv[1]
rng = np.random.default_rng(3)
def win(x0, y0, x1, y1):
return (np.array([x0, y0], dtype=np.int32), np.array([x1, y1], dtype=np.int32))
def img(h, wd, kind="f2"):
y, x = np.mgrid[0:h, 0:wd]
r = (x / max(1, wd - 1)) * 3 - 0.5
g = np.sin(y * 0.7) * 0.5 + 0.5
b = rng.random((h, wd)) * 0.01 + (x * y % 7) * 0.2
a = ((x + y) % 4) / 3.0
return [c.astype(kind) for c in (r, g, b, a)]
def save(name, header, channels):
h = {"type": OpenEXR.scanlineimage}
h.update(header)
OpenEXR.File(h, channels).write(os.path.join(w, name))
C = {"none": OpenEXR.NO_COMPRESSION, "rle": OpenEXR.RLE_COMPRESSION, "zips": OpenEXR.ZIPS_COMPRESSION,
"zip": OpenEXR.ZIP_COMPRESSION, "piz": OpenEXR.PIZ_COMPRESSION}
names = []
for cn, c in C.items():
r, g, b, a = img(23, 37)
save("half_rgba_%s.exr" % cn, {"compression": c}, {"R": r, "G": g, "B": b, "A": a})
r, g, b, a = img(19, 41, "f4")
save("float_rgb_%s.exr" % cn, {"compression": c}, {"R": r, "G": g, "B": b})
r, g, b, a = img(37, 70)
u = (rng.random((37, 70)) * 100000).astype("uint32")
save("mixed_%s.exr" % cn, {"compression": c, "lineOrder": OpenEXR.DECREASING_Y}, {"R": r, "G": g.astype("f4"), "B": u})
names += ["half_rgba_%s.exr" % cn, "float_rgb_%s.exr" % cn, "mixed_%s.exr" % cn]
r, g, b, a = img(20, 30)
save("window_zip.exr", {"compression": C["zip"], "dataWindow": win(5, -3, 34, 16), "displayWindow": win(0, 0, 39, 19)}, {"R": r, "G": g, "B": b, "A": a})
save("grey_piz.exr", {"compression": C["piz"]}, {"Y": r})
save("layer_zips.exr", {"compression": C["zips"]}, {"diffuse.R": r, "diffuse.G": g, "diffuse.B": b, "R": a, "G": a, "B": a})
r, g, b, a = img(64, 96)
save("big_piz.exr", {"compression": C["piz"]}, {"R": r, "G": g, "B": b, "A": a})
save("big_zip.exr", {"compression": C["zip"]}, {"R": r, "G": g, "B": b, "A": a})
names += ["window_zip.exr", "grey_piz.exr", "layer_zips.exr", "big_piz.exr", "big_zip.exr"]
y, x = np.mgrid[0:16, 0:24]
Y = (x / 23.0).astype("f2")
sub = (np.mgrid[0:8, 0:12][1] / 11.0).astype("f2")
# subsampled: hand-written (the bindings only write full-resolution channels): NONE, A at 2 x 2, R / G / B full
import struct
def attr(n, t, d):
return n.encode() + b"\0" + t.encode() + b"\0" + struct.pack("<i", len(d)) + d
chl = b""
for n, xs in (("A", 2), ("B", 1), ("G", 1), ("R", 1)):
chl += n.encode() + b"\0" + struct.pack("<iB3xii", 1, 0, xs, xs)
chl += b"\0"
W, H = 24, 16
hdr = (b"\x76\x2f\x31\x01" + struct.pack("<I", 2) + attr("channels", "chlist", chl) + attr("compression", "compression", b"\0") +
attr("dataWindow", "box2i", struct.pack("<4i", 0, 0, W - 1, H - 1)) + attr("displayWindow", "box2i", struct.pack("<4i", 0, 0, W - 1, H - 1)) +
attr("lineOrder", "lineOrder", b"\0") + attr("pixelAspectRatio", "float", struct.pack("<f", 1)) +
attr("screenWindowCenter", "v2f", struct.pack("<2f", 0, 0)) + attr("screenWindowWidth", "float", struct.pack("<f", 1)) + b"\0")
blocks = []
for yy in range(H):
line = b""
if yy % 2 == 0:
line += np.array([(x2 * 2) / 23.0 for x2 in range(W // 2)], dtype="f2").tobytes()
for ch in range(3):
line += Y[yy].tobytes()
blocks.append(struct.pack("<ii", yy, len(line)) + line)
off = len(hdr) + 8 * H
table = b""
for bl in blocks:
table += struct.pack("<Q", off)
off += len(bl)
open(os.path.join(w, "subsampled_none.exr"), "wb").write(hdr + table + b"".join(blocks))
names.append("subsampled_none.exr")
for cn, c in (("pxr24", OpenEXR.PXR24_COMPRESSION), ("b44", OpenEXR.B44_COMPRESSION), ("dwaa", OpenEXR.DWAA_COMPRESSION)):
r, g, b, a = img(8, 8)
save("unsupported_%s.exr" % cn, {"compression": c}, {"R": r, "G": g, "B": b})
r, g, b, a = img(256, 512)
save("bench_zip.exr", {"compression": C["zip"]}, {"R": r, "G": g, "B": b, "A": a})
save("bench_piz.exr", {"compression": C["piz"]}, {"R": r, "G": g, "B": b, "A": a})
print(json.dumps(names))
'''
READ = r'''
import OpenEXR, numpy as np, os, sys, json
w = sys.argv[1]
out = {}
for name in json.loads(sys.argv[2]):
f = OpenEXR.File(os.path.join(w, name), separate_channels=True)
hdr = f.header()
ch = f.channels()
(x0, y0), (x1, y1) = hdr["dataWindow"]
W, H = int(x1 - x0 + 1), int(y1 - y0 + 1)
layer = sys.argv[3] if len(sys.argv) > 3 and name.startswith("layer") else ""
px = np.zeros((H, W, 4), dtype="f4")
px[:, :, 3] = 1
def get(n):
c = ch.get(layer + n)
if c is None:
return None
p = c.pixels.astype("f4")
if p.shape != (H, W):
p = np.repeat(np.repeat(p, c.ySampling, axis=0), c.xSampling, axis=1)[:H, :W]
return p
if get("R") is None and get("Y") is not None:
for k in range(3):
px[:, :, k] = get("Y")
for k, n in enumerate("RGBA"):
p = get(n)
if p is not None:
px[:, :, k] = p
out[name] = {"w": W, "h": H, "floats": px.tobytes().hex(), "compression": str(hdr["compression"]).split(".")[-1]}
print(json.dumps(out))
'''
def generate(ctx):
work = tempfile.mkdtemp(prefix="formats-exr-")
try:
_generate(ctx, work)
finally:
shutil.rmtree(work, ignore_errors=True)
def py(ctx, code, *args):
expr = "with import <nixpkgs> {}; python3.withPackages (p: [p.openexr p.numpy])"
res = subprocess.run(["nix", "shell", "--impure", "--expr", expr, "-c", "python3", "-I", "-c", code] + list(args), capture_output=True)
if res.returncode:
raise RuntimeError("OpenEXR bindings failed: " + res.stderr.decode()[-2000:])
return res.stdout
def _generate(ctx, work):
import json
names = json.loads(py(ctx, WRITE, work))
tiled = []
sh = []
for cn in ("none", "rle", "zip", "piz"):
sh.append("exrmaketiled -o -t 16 8 -z %s half_rgba_zip.exr tiled_%s.exr" % (cn, cn))
tiled.append("tiled_%s.exr" % cn)
sh.append("exrmaketiled -m -t 8 8 -z zip -f R -f G -f B -f A half_rgba_zip.exr tiled_mip.exr")
sh.append("exrmaketiled -m -u -t 8 8 -z piz half_rgba_zip.exr tiled_mip_up.exr")
sh.append("exrmaketiled -r -t 16 16 -z zips half_rgba_zip.exr tiled_rip.exr")
sh.append("exrmaketiled -o -t 8 8 -z zip float_rgb_none.exr tiled_float.exr")
sh.append("exrmaketiled -o -t 7 5 -z zip window_zip.exr tiled_window.exr")
tiled += ["tiled_mip.exr", "tiled_mip_up.exr", "tiled_rip.exr", "tiled_float.exr", "tiled_window.exr"]
sh.append("exrmultipart -combine -i half_rgba_piz.exr::left half_rgba_rle.exr::right tiled_zip.exr::tiles -o multipart.exr")
ctx.nix("openexr", ["sh", "-c", "cd %s && %s" % (work, " && ".join(sh))])
ref = json.loads(py(ctx, READ, work, json.dumps(names + tiled), "diffuse."))
cases = []
for n in names + tiled:
r = ref[n]
c = {"name": n, "data": open(os.path.join(work, n), "rb").read(), "w": r["w"], "h": r["h"], "floats": bytes.fromhex(r["floats"])}
if n.startswith("layer"):
c["layer"] = "diffuse"
if n.startswith("tiled_mip") or n.startswith("tiled_rip"):
c["mips"] = True
cases.append(c)
# multipart: every part against the file it came from
mp = open(os.path.join(work, "multipart.exr"), "rb").read()
for i, (src, pname) in enumerate((("half_rgba_piz.exr", "left"), ("half_rgba_rle.exr", "right"), ("tiled_zip.exr", "tiles"))):
r = ref[src]
cases.append({"name": "multipart part %d (%s)" % (i + 1, pname), "data": mp, "part": i + 1, "partName": pname,
"w": r["w"], "h": r["h"], "floats": bytes.fromhex(r["floats"])})
for cn in ("pxr24", "b44", "dwaa"):
cases.append({"name": "unsupported_%s.exr" % cn, "data": open(os.path.join(work, "unsupported_%s.exr" % cn), "rb").read(), "unsupported": True})
ours = _ours(ctx, work)
ctx.emit("exr", {"cases": cases, "ours": ours})
ctx.emit("exr_bench", {"zip": open(os.path.join(work, "bench_zip.exr"), "rb").read(), "piz": open(os.path.join(work, "bench_piz.exr"), "rb").read()})
def _ours(ctx, work):
import json
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", "exr"], cwd=ctx.root, capture_output=True, check=True)
files = {}
for line in res.stdout.decode().split("\n"):
if "\t" in line:
n, hx = line.split("\t", 1)
files[n] = bytes.fromhex(hx.strip())
names = sorted(files)
for n in names:
open(os.path.join(work, n), "wb").write(files[n])
ref = json.loads(py(ctx, READ, work, json.dumps(names)))
rc = ctx.nix("openexr", ["sh", "-c", "cd %s && for f in %s; do exrheader $f > /dev/null 2>&1; echo $f $?; done" % (work, " ".join(names))]).decode()
ok = {line.split()[0]: line.split()[1] == "0" for line in rc.strip().split("\n")}
return [{"name": n, "data": files[n], "floats": bytes.fromhex(ref[n]["floats"]), "compression": ref[n]["compression"], "headerOk": ok.get(n, False)} for n in names]
+73
View File
@@ -0,0 +1,73 @@
# ICNS fixtures (tools/fixtures.py): a libicns png2icns file (is32 / il32 / ih32 RLE entries with their masks, ic07 /
# ic08 PNG entries), a JPEG 2000 entry that must be skipped (hand-written into hand.icns), a Pillow file (PNG entries), a hand-written one (ics# / ICN#
# 1-bit icons, an ic04 ARGB entry, an uncompressed is32); every entry's reference pixels from icns2png -x (libicns)
# or written here; our encoder's RLE file (tools/fixtures/_tex_encode.luau -a icns) read back by icns2png.
# tests/gen/icns.luau { cases = { { name, data, entries = { { type, w, h, rgba } }, skipped } }, ours = { ... } }
import importlib.util, os, re, struct
def _load(n):
spec = importlib.util.spec_from_file_location(n, os.path.join(os.path.dirname(os.path.abspath(__file__)), n + ".py"))
m = importlib.util.module_from_spec(spec)
spec.loader.exec_module(m)
return m
R, S, T = _load("_raster_ref"), _load("_simple"), _load("_tex_reference")
INPUTS = ["tools/fixtures/_tex_encode.luau", "src/Formats/image/icns"]
def extract(ctx, w, name):
"""icns2png -x name -> { 'WxH': rgba } (one per extracted entry)"""
log = w.sh("libicns", ["mkdir -p x_%s && cd x_%s && icns2png -x ../%s" % (name, name, name)]).decode()
files = sorted(f for f in os.listdir(w.path("x_" + name)) if f.endswith(".png"))
out = {}
for f, (mode, ww, hh, raw) in zip(files, T.pillow(ctx, [w.read(os.path.join("x_" + name, f)) for f in files])):
out["%dx%d" % (ww, hh)] = T.rgba_from(mode, raw)
return out
def generate(ctx):
w = R.Work(ctx)
try:
for s in (16, 32, 48, 128, 256):
w.png("i%d.png" % s, s, s, R.photo(s, s, s, True))
w.sh("libicns", ["png2icns libicns.icns i16.png i32.png i48.png i128.png i256.png"])
w.png("p64.png", 64, 64, R.photo(64, 64, 9, True))
ctx.python(["pillow"], "from PIL import Image\nimport os\nos.chdir(%r)\nImage.open('p64.png').save('pillow.icns')\n" % w.dir)
cases = []
lib = extract(ctx, w, "libicns.icns")
cases.append({"name": "libicns.icns", "data": w.read("libicns.icns"), "skipped": 0,
"entries": [{"type": t, "w": s, "h": s, "rgba": lib["%dx%d" % (s, s)]} for t, s in (("is32", 16), ("il32", 32), ("ih32", 48), ("ic07", 128), ("ic08", 256))]})
pil = extract(ctx, w, "pillow.icns")
cases.append({"name": "pillow.icns", "data": w.read("pillow.icns"), "skipped": 0,
"entries": [{"type": "", "w": int(k.split("x")[0]), "h": int(k.split("x")[1]), "rgba": v} for k, v in sorted(pil.items())]})
# hand-written: ics# (16x16 1-bit + mask), an uncompressed is32 + s8mk, an ic04 ARGB with RLE runs
bits = bytes((0xF0 if (i // 2) % 2 else 0x0F) for i in range(32))
mask = bytes((0xFF if i < 24 else 0x00) for i in range(32))
mono = []
for i in range(256):
b = (bits[i // 8] >> (7 - i % 8)) & 1
m = (mask[i // 8] >> (7 - i % 8)) & 1
mono += [0, 0, 0] if b else [255, 255, 255]
mono.append(255 if m else 0)
raw = bytes((i * 3 + k * 50) % 256 for k in range(3) for i in range(256))
alpha = bytes((i * 7) % 256 for i in range(256))
rgb = bytes(v for i in range(256) for v in (raw[i], raw[256 + i], raw[512 + i], alpha[i]))
def ch(t, d):
return t + struct.pack(">I", len(d) + 8) + d
# ARGB channels: A = 256 x 77 (two runs of 128), then R / G / B as runs
argb = b"ARGB" + bytes((253, 77, 253, 77)) + bytes((253, 10, 253, 10)) + bytes((253, 20, 253, 20)) + bytes((253, 30, 253, 30))
jp2 = b"\0\0\0\x0cjP \r\n\x87\n" + b"\0" * 20
body = ch(b"ics#", bits + mask) + ch(b"is32", raw) + ch(b"s8mk", alpha) + ch(b"ic04", argb) + ch(b"ic09", jp2)
hand = b"icns" + struct.pack(">I", len(body) + 8) + body
cases.append({"name": "hand.icns", "data": hand, "skipped": 1, "entries": [
{"type": "ics#", "w": 16, "h": 16, "rgba": bytes(mono)}, {"type": "is32", "w": 16, "h": 16, "rgba": rgb},
{"type": "ic04", "w": 16, "h": 16, "rgba": bytes((10, 20, 30, 77)) * 256}]})
mine = S.ours(ctx, "icns")
ours = []
for n, d in mine.items():
w.write(n, d)
ex = extract(ctx, w, n)
ours.append({"name": n, "data": d, "entries": [{"type": "", "w": int(k.split("x")[0]), "h": int(k.split("x")[1]), "rgba": v} for k, v in sorted(ex.items())]})
ctx.emit("icns", {"cases": cases, "ours": ours})
finally:
w.close()
+121
View File
@@ -0,0 +1,121 @@
# IFF ILBM fixtures (tools/fixtures.py): files from netpbm's ppmtoilbm (palette ByteRun1 / uncompressed, few planes,
# HAM6, HAM8, 24-bit deep) and hand-written ones (EHB, chunky PBM, a mask plane, a transparent colour index, an odd
# CMAP), decoded by ilbmtoppm as the reference (alpha separately: ilbmtoppm writes PPM; HAM values within the scaling
# difference: ilbmtoppm shifts, we replicate bits); our encoder's files
# (tools/fixtures/_tex_encode.luau -a ilbm) read by ilbmtoppm.
# tests/gen/ilbm.luau { cases = { { name, data, w, h, rgba, transparent? } }, ours = { ... } }
import importlib.util, os, random, struct
def _load(n):
spec = importlib.util.spec_from_file_location(n, os.path.join(os.path.dirname(os.path.abspath(__file__)), n + ".py"))
m = importlib.util.module_from_spec(spec)
spec.loader.exec_module(m)
return m
R, S = _load("_raster_ref"), _load("_simple")
INPUTS = ["tools/fixtures/_tex_encode.luau", "src/Formats/image/ilbm"]
def chunk(cid, data):
return cid + struct.pack(">I", len(data)) + data + (b"\0" if len(data) % 2 else b"")
def byterun1(row):
out = bytearray()
i = 0
while i < len(row):
run = 1
while i + run < len(row) and run < 128 and row[i + run] == row[i]:
run += 1
if run >= 2:
out += bytes((257 - run, row[i]))
i += run
else:
j = i
while j < len(row) and j - i < 128 and not (j + 1 < len(row) and row[j + 1] == row[j]):
j += 1
j = max(j, i + 1)
out += bytes((j - i - 1,)) + row[i:j]
i = j
return bytes(out)
def planar(w, h, idx, planes, mask=None, comp=True):
rb = ((w + 15) // 16) * 2
body = bytearray()
for y in range(h):
rows = []
for k in range(planes):
row = bytearray(rb)
for x in range(w):
if (idx[y * w + x] >> k) & 1:
row[x // 8] |= 0x80 >> (x % 8)
rows.append(bytes(row))
if mask is not None:
row = bytearray(rb)
for x in range(w):
if mask[y * w + x]:
row[x // 8] |= 0x80 >> (x % 8)
rows.append(bytes(row))
for row in rows:
body += byterun1(row) if comp else row
return bytes(body)
def ilbm(w, h, planes, body, cmap=b"", camg=None, masking=0, trans=0, comp=1, form=b"ILBM", extra=b""):
bmhd = struct.pack(">HHhhBBBxHBBhh", w, h, 0, 0, planes, masking, comp, trans, 10, 11, w, h)
data = form + chunk(b"BMHD", bmhd) + (chunk(b"CMAP", cmap) if cmap else b"") + (chunk(b"CAMG", struct.pack(">I", camg)) if camg is not None else b"") + extra + chunk(b"BODY", body)
return b"FORM" + struct.pack(">I", len(data)) + data
def generate(ctx):
rng = random.Random(8)
w = R.Work(ctx)
try:
w.png("photo.png", 37, 23, R.photo(37, 23))
w.png("pal.png", 31, 19, R.palette_image(31, 19, 60))
w.png("pal8.png", 26, 11, R.palette_image(26, 11, 7))
w.sh("netpbm", ["pngtopam photo.png | pamtopnm > photo.ppm", "pngtopam pal.png | pamtopnm > pal.ppm", "pngtopam pal8.png | pamtopnm > pal8.ppm",
"ppmtoilbm pal.ppm > nb_pal.iff", "ppmtoilbm -nocompress pal.ppm > nb_pal_raw.iff", "ppmtoilbm pal8.ppm > nb_3planes.iff",
"ppmtoilbm -ham6 photo.ppm > nb_ham6.iff", "ppmtoilbm -ham8 photo.ppm > nb_ham8.iff", "ppmtoilbm -24force photo.ppm > nb_24.iff"])
hand = []
# EHB: 6 planes, 32 colours
W, H = 20, 7
cm = bytes(rng.randrange(256) for _ in range(32 * 3))
idx = [rng.randrange(64) for _ in range(W * H)]
hand.append(("hand_ehb.iff", ilbm(W, H, 6, planar(W, H, idx, 6), cm, 0x80), None))
# chunky PBM (rows padded to even), 256 colours
cm2 = bytes(rng.randrange(256) for _ in range(256 * 3))
W2 = 14
idx2 = [rng.randrange(256) for _ in range(W2 * H)]
hand.append(("hand_pbm.lbm", ilbm(W2, H, 8, b"".join(byterun1(bytes(idx2[y * W2:(y + 1) * W2])) for y in range(H)), cm2, form=b"PBM "), None))
# a mask plane and a transparent colour index
cm3 = bytes(rng.randrange(256) for _ in range(16 * 3))
idx3 = [rng.randrange(16) for _ in range(W * H)]
mask = [rng.random() < 0.7 for _ in range(W * H)]
hand.append(("hand_mask.iff", ilbm(W, H, 4, planar(W, H, idx3, 4, mask), cm3, masking=1), [not m for m in mask]))
hand.append(("hand_transparent.iff", ilbm(W, H, 4, planar(W, H, idx3, 4, comp=False), cm3, masking=2, trans=5, comp=0,
extra=chunk(b"NAME", b"tiny\0")), [i == 5 for i in idx3]))
for n, data, _ in hand:
w.write(n, data)
names = sorted(f for f in os.listdir(w.dir) if f.endswith(".iff") or f.endswith(".lbm"))
mine = S.ours(ctx, "ilbm")
for n, d in mine.items():
w.write(n, d)
allnames = names + sorted(mine)
allnames = [n for n in allnames if n != "ours_alpha.ilbm"] # ilbmtoppm reads no 32-plane files
w.sh("netpbm", ["ilbmtoppm %s > %s.ppm" % (n, n) for n in allnames])
tmap = {n: t for n, _, t in hand}
out = {"cases": [], "ours": []}
for n in allnames:
ww, hh, rgba = R.pnm_rgba(w.read(n + ".ppm"))
c = {"name": n, "data": w.read(n), "w": ww, "h": hh, "rgba": rgba}
if "ham" in n:
# ilbmtoppm scales HAM values by shifting (4-bit v -> v << 4); we replicate the bits (v * 17)
c["tol"] = 15 if "ham6" in n else 3
if tmap.get(n):
c["transparent"] = [bool(v) for v in tmap[n]]
out["ours" if n.startswith("ours_") else "cases"].append(c)
ctx.emit("ilbm", out)
finally:
w.close()
+279
View File
@@ -0,0 +1,279 @@
# KTX fixtures (tools/fixtures.py):
# - KTX2 from KTX-Software 4.4 (`ktx create`): PNG sources (mip chains, sRGB, cube maps, arrays), --raw data in
# uncompressed / packed / float / BCn / ETC2 / EAC VkFormats, a 3D texture, `ktx deflate` Zstandard and ZLIB
# supercompression, Basis Universal (ETC1S and UASTC: must give UNSUPPORTED);
# - KTX1 from toktx (PNG sources, mips, cube map, odd widths with row padding) and nvcompress -ktx (BC1 / BC3 / BC7),
# plus hand-written big-endian and packed-type KTX1 files;
# - our encoder's KTX2 files (tools/fixtures/_tex_encode.luau -a ktx): `ktx validate` and `ktx extract` read them.
# References: the PNG sources / raw values themselves, `ktx extract` PNGs for the generated mip levels, Pillow (BCn,
# through a one-surface DDS) and Godot (ETC / EAC) for block data.
# tests/gen/ktx.luau { cases = { { name, data, layout?, mips?, surfaces = { { level, layer, slice, w, h, rgba?,
# floats?, tol } }, unsupported? } }, ours = { { name, data, valid, extract = { rgba / floats } } } }
import importlib.util, os, random, shutil, struct, subprocess, tempfile
_dir = os.path.dirname(os.path.abspath(__file__))
_spec = importlib.util.spec_from_file_location("_tex_reference", os.path.join(_dir, "_tex_reference.py"))
R = importlib.util.module_from_spec(_spec)
_spec.loader.exec_module(R)
_spec2 = importlib.util.spec_from_file_location("_dds_fixture", os.path.join(_dir, "dds.py"))
D = importlib.util.module_from_spec(_spec2)
_spec2.loader.exec_module(D)
INPUTS = ["tools/fixtures/_tex_encode.luau", "src/Formats/image/ktx", "tools/fixtures/dds.py"]
def q8(v):
return 0 if v != v or v <= 0 else (255 if v >= 1 else int(v * 255 + 0.5))
def generate(ctx):
work = tempfile.mkdtemp(prefix="formats-ktx-")
try:
cases = _cases(ctx, work, random.Random(9))
ours = _ours(ctx, work)
finally:
shutil.rmtree(work, ignore_errors=True)
ctx.emit("ktx", {"cases": cases, "ours": ours})
def read_png(ctx, paths):
return [R.rgba_from(m, raw) if m in ("RGB", "L", "LA", "RGBA") else raw for (m, w, h, raw) in
R.pillow(ctx, [open(p, "rb").read() for p in paths])]
def _cases(ctx, work, rng):
cases = []
sh = []
def run(cmd):
sh.append(cmd)
# sources
srcs = {}
for name, w, h, salt in (("a", 37, 23, 0), ("sq", 32, 32, 3)):
srcs[name] = (w, h, D.source(w, h, salt))
open(os.path.join(work, name + ".png"), "wb").write(D.png(w, h, srcs[name][2]))
faces = []
for i in range(6):
px = D.source(16, 16, i + 1)
faces.append(px)
open(os.path.join(work, "f%d.png" % i), "wb").write(D.png(16, 16, px))
fl = " ".join("f%d.png" % i for i in range(6))
run("ktx create --format R8G8B8A8_UNORM --assign-tf linear a.png k2_rgba8.ktx2")
run("ktx create --format R8G8B8A8_SRGB --assign-tf srgb --generate-mipmap sq.png k2_srgb_mips.ktx2")
run("ktx extract --level all k2_srgb_mips.ktx2 k2mips")
run("ktx create --format R8G8B8A8_UNORM --assign-tf linear --cubemap %s k2_cube.ktx2" % fl)
run("ktx create --format R8G8B8A8_UNORM --assign-tf linear --layers 3 f0.png f1.png f2.png k2_array.ktx2")
run("ktx create --format R8G8B8_UNORM --assign-tf linear a.png k2_rgb8.ktx2")
run("ktx deflate --zstd 12 k2_srgb_mips.ktx2 k2_zstd.ktx2")
run("ktx deflate --zlib 6 k2_cube.ktx2 k2_zlib.ktx2")
run("ktx create --format R8G8B8A8_UNORM --assign-tf linear --encode basis-lz a.png k2_basis.ktx2")
run("ktx create --format R8G8B8A8_UNORM --assign-tf linear --encode uastc a.png k2_uastc.ktx2")
# raw formats with known values
W, H = 8, 4
raws = []
def raw(name, vk, data, texels=None, block=None, w=W, h=H, extra="", parts=1):
n = len(data) // parts
files = []
for i in range(parts):
open(os.path.join(work, "%s_%d.raw" % (name, i)), "wb").write(data[i * n:(i + 1) * n])
files.append("%s_%d.raw" % (name, i))
run("ktx create --raw --width %d --height %d --format %s %s %s %s.ktx2" % (w, h, vk, extra, " ".join(files), name))
raws.append((name, texels, block, w, h, data))
u8 = bytes(rng.randrange(256) for _ in range(W * H * 4))
raw("k2_raw_rgba8", "R8G8B8A8_UNORM", u8, [tuple(u8[i + k] / 255 for k in range(4)) for i in range(0, len(u8), 4)])
raw("k2_raw_bgra8_srgb", "B8G8R8A8_SRGB", u8, [(u8[i + 2] / 255, u8[i + 1] / 255, u8[i] / 255, u8[i + 3] / 255) for i in range(0, len(u8), 4)])
raw("k2_raw_rg8", "R8G8_UNORM", u8[:W * H * 2], [(u8[i] / 255, u8[i + 1] / 255, 0.0, 1.0) for i in range(0, W * H * 2, 2)])
vals = [(rng.uniform(-1, 4), rng.uniform(0, 1), rng.uniform(0, 2), rng.uniform(0, 1)) for _ in range(W * H)]
hd = b"".join(struct.pack("<4e", *v) for v in vals)
raw("k2_raw_rgba16f", "R16G16B16A16_SFLOAT", hd, [struct.unpack("<4e", hd[i:i + 8]) for i in range(0, len(hd), 8)])
fd = b"".join(struct.pack("<4f", *v) for v in vals)
raw("k2_raw_rgba32f", "R32G32B32A32_SFLOAT", fd, [struct.unpack("<4f", fd[i:i + 16]) for i in range(0, len(fd), 16)])
u16 = [rng.randrange(65536) for _ in range(W * H)]
raw("k2_raw_r16", "R16_UNORM", b"".join(struct.pack("<H", v) for v in u16), [(v / 65535,) * 3 + (1.0,) for v in u16])
raw("k2_raw_r5g6b5", "R5G6B5_UNORM_PACK16", b"".join(struct.pack("<H", v) for v in u16),
[((v >> 11) / 31, ((v >> 5) & 63) / 63, (v & 31) / 31, 1.0) for v in u16])
p32 = [rng.getrandbits(32) for _ in range(W * H)]
raw("k2_raw_a2b10g10r10", "A2B10G10R10_UNORM_PACK32", b"".join(struct.pack("<I", v) for v in p32),
[((v & 1023) / 1023, ((v >> 10) & 1023) / 1023, ((v >> 20) & 1023) / 1023, (v >> 30) / 3) for v in p32])
raw("k2_raw_e5b9g9r9", "E5B9G9R9_UFLOAT_PACK32", b"".join(struct.pack("<I", v) for v in p32),
[tuple((v >> (9 * k) & 511) * 2.0 ** ((v >> 27) - 24) for k in range(3)) + (1.0,) for v in p32])
vol = bytes(rng.randrange(256) for _ in range(4 * 4 * 3 * 4))
raw("k2_raw_3d", "R8G8B8A8_UNORM", vol, None, None, 4, 4, "--depth 3", 3)
for kind, vk in (("bc1", "BC1_RGB_UNORM_BLOCK"), ("bc1", "BC1_RGBA_UNORM_BLOCK"), ("bc3", "BC3_UNORM_BLOCK"),
("bc7", "BC7_UNORM_BLOCK"), ("bc6h", "BC6H_UFLOAT_BLOCK"), ("etc2_rgba", "ETC2_R8G8B8A8_UNORM_BLOCK"),
("etc2_rgb", "ETC2_R8G8B8_UNORM_BLOCK"), ("eac_rg11", "EAC_R11G11_UNORM_BLOCK")):
bb = {"bc1": 8, "bc3": 16, "bc7": 16, "bc6h": 16, "etc2_rgba": 16, "etc2_rgb": 8, "eac_rg11": 16}[kind]
data = bytes(rng.getrandbits(8) for _ in range(4 * 2 * bb))
raw("k2_raw_" + vk.lower(), vk, data, None, kind, 13, 7)
# KTX1
run("toktx --genmipmap k1_mips.ktx sq.png")
run("toktx k1_rgba.ktx a.png")
run("toktx --cubemap k1_cube.ktx %s" % fl)
run("ktx2ktx2 -o k1_mips_as2.ktx2 k1_mips.ktx")
run("ktx extract --level all k1_mips_as2.ktx2 k1mips")
ctx.nix("ktx-tools", ["sh", "-c", "cd %s && %s" % (work, " && ".join(sh))])
ctx.nix("nvidia-texture-tools", ["sh", "-c", "cd %s && nvcompress -silent -ktx -bc1 a.png n_bc1.ktx && nvcompress -silent -ktx -bc3 a.png n_bc3.ktx && nvcompress -silent -ktx -bc7 -nomips a.png n_bc7.ktx" % work])
def rd(n):
return open(os.path.join(work, n), "rb").read()
def surf(level, layer, s, w, h, rgba=None, floats=None, tol=0):
d = {"level": level, "layer": layer, "slice": s, "w": w, "h": h, "tol": tol}
if rgba is not None:
d["rgba"] = rgba
if floats is not None:
d["floats"] = floats
return d
aw, ah, apx = srcs["a"]
sw, shh, spx = srcs["sq"]
cases.append({"name": "k2_rgba8.ktx2", "data": rd("k2_rgba8.ktx2"), "layout": "2d", "surfaces": [surf(0, 0, 0, aw, ah, apx)]})
mip_files = sorted(f for f in os.listdir(work) if f.startswith("k2mips") or f.startswith("output_level"))
mips = []
lw = sw
level = 0
while True:
p = os.path.join(work, "k2mips_level%d.png" % level)
if not os.path.exists(p):
p = os.path.join(work, "k2mips", "output_level%d.png" % level)
if not os.path.exists(p):
break
mips.append((level, p))
level += 1
if not mips:
raise RuntimeError("ktx extract wrote no mip levels: %r" % os.listdir(work))
pngs = read_png(ctx, [p for _, p in mips])
msurf = [surf(lv, 0, 0, max(1, sw >> lv), max(1, shh >> lv), px) for (lv, _), px in zip(mips, pngs)]
cases.append({"name": "k2_srgb_mips.ktx2", "data": rd("k2_srgb_mips.ktx2"), "layout": "2d", "mips": len(mips), "srgb": True, "surfaces": msurf})
cases.append({"name": "k2_zstd.ktx2", "data": rd("k2_zstd.ktx2"), "layout": "2d", "mips": len(mips), "surfaces": msurf})
csurf = [surf(0, i, 0, 16, 16, faces[i]) for i in range(6)]
cases.append({"name": "k2_cube.ktx2", "data": rd("k2_cube.ktx2"), "layout": "cube", "surfaces": csurf})
cases.append({"name": "k2_zlib.ktx2", "data": rd("k2_zlib.ktx2"), "layout": "cube", "surfaces": csurf})
cases.append({"name": "k2_array.ktx2", "data": rd("k2_array.ktx2"), "layout": "array", "surfaces": [surf(0, i, 0, 16, 16, faces[i]) for i in range(3)]})
opaque = bytes(v if i % 4 != 3 else 255 for i, v in enumerate(apx))
cases.append({"name": "k2_rgb8.ktx2", "data": rd("k2_rgb8.ktx2"), "layout": "2d", "surfaces": [surf(0, 0, 0, aw, ah, opaque)]})
cases.append({"name": "k2_basis.ktx2", "data": rd("k2_basis.ktx2"), "unsupported": True, "surfaces": []})
cases.append({"name": "k2_uastc.ktx2", "data": rd("k2_uastc.ktx2"), "unsupported": True, "surfaces": []})
pil, pil_t, gd, gd_t = [], [], [], []
for (name, texels, block, w, h, data) in raws:
c = {"name": name + ".ktx2", "data": rd(name + ".ktx2"), "layout": "volume" if name.endswith("3d") else "2d"}
if texels is not None:
c["surfaces"] = [surf(0, 0, 0, w, h, bytes(q8(v) for t in texels for v in t), b"".join(struct.pack("<4f", *t) for t in texels), 1)]
elif block is None:
c["surfaces"] = [surf(0, 0, s, w, h, data[s * w * h * 4:(s + 1) * w * h * 4]) for s in range(3)]
else:
sd = surf(0, 0, 0, w, h)
c["surfaces"] = [sd]
if block.startswith("bc") and block != "bc6h":
dx = {"bc1": 71, "bc3": 77, "bc7": 98}[block]
pil.append(R.dds_dx10(w, h, dx, data))
pil_t.append((sd, "RGB_UNORM" in name.upper()))
else:
gd.append((data, w, h, R.GODOT[block], block == "bc6h"))
gd_t.append((sd, block))
cases.append(c)
for (sd, opaque_), (mode, w, h, rw) in zip(pil_t, R.pillow(ctx, pil)):
px = R.rgba_from(mode, rw)
if opaque_:
px = bytes(v if i % 4 != 3 else 255 for i, v in enumerate(px))
sd["rgba"] = px
for (sd, block), out in zip(gd_t, R.godot(ctx, gd)):
if block == "bc6h":
sd["floats"] = out
elif block == "eac_rg11":
sd["rgba"] = bytes(v if i % 4 < 2 else (255 if i % 4 == 3 else 0) for i, v in enumerate(out))
sd["tol"] = 1
else:
sd["rgba"] = out
# KTX1
k1 = []
level = 0
while True:
p = os.path.join(work, "k1mips_level%d.png" % level)
if not os.path.exists(p):
p = os.path.join(work, "k1mips", "output_level%d.png" % level)
if not os.path.exists(p):
break
k1.append(p)
level += 1
k1png = read_png(ctx, k1)
cases.append({"name": "k1_mips.ktx", "data": rd("k1_mips.ktx"), "layout": "2d", "mips": len(k1),
"surfaces": [surf(lv, 0, 0, max(1, sw >> lv), max(1, shh >> lv), px) for lv, px in enumerate(k1png)]})
cases.append({"name": "k1_rgba.ktx", "data": rd("k1_rgba.ktx"), "layout": "2d", "surfaces": [surf(0, 0, 0, aw, ah, apx)]})
cases.append({"name": "k1_cube.ktx", "data": rd("k1_cube.ktx"), "layout": "cube",
"surfaces": [surf(0, i, 0, 16, 16, faces[i]) for i in range(6)]})
# nvcompress KTX1: the level-0 blocks follow the 64-byte header + key / value data + imageSize
nv = []
for n, dx in (("n_bc1.ktx", 71), ("n_bc3.ktx", 77), ("n_bc7.ktx", 98)):
d = rd(n)
kvb = struct.unpack("<I", d[60:64])[0]
off = 64 + kvb + 4
size = struct.unpack("<I", d[off - 4:off])[0]
nv.append((n, d, R.dds_dx10(aw, ah, dx, d[off:off + size])))
for (n, d, dds), (mode, w, h, rw) in zip(nv, R.pillow(ctx, [x[2] for x in nv])):
px = R.rgba_from(mode, rw)
if n == "n_bc1.ktx":
px = bytes(v if i % 4 != 3 else 255 for i, v in enumerate(px)) # GL_COMPRESSED_RGB_S3TC_DXT1
cases.append({"name": n, "data": d, "layout": "2d", "surfaces": [surf(0, 0, 0, aw, ah, px)]})
# hand-written KTX1: big-endian 16-bit RGBA, GL_UNSIGNED_SHORT_5_6_5, RGB8 with row padding and T=u orientation
def ktx1(gltype, typesize, glformat, internal, base, w, h, image, be=False, kv=b""):
f = ">" if be else "<"
hdr = b"\xabKTX 11\xbb\r\n\x1a\n" + struct.pack(f + "13I", 0x04030201, gltype, typesize, glformat, internal, base, w, h, 0, 0, 1, 1, len(kv))
return hdr + kv + struct.pack(f + "I", len(image)) + image
W2, H2 = 5, 3
v16 = [tuple(rng.randrange(65536) for _ in range(4)) for _ in range(W2 * H2)]
img = b"".join(struct.pack(">4H", *v) for v in v16) + b"\0" * 0 # rows of 40 bytes: already 4-aligned
cases.append({"name": "hand big-endian RGBA16", "data": ktx1(0x1403, 2, 0x1908, 0x805B, 0x1908, W2, H2, img, True), "layout": "2d",
"surfaces": [surf(0, 0, 0, W2, H2, bytes(q8(x / 65535) for v in v16 for x in v), b"".join(struct.pack("<4f", *(x / 65535 for x in v)) for v in v16), 1)]})
p565 = [rng.getrandbits(16) for _ in range(W2 * H2)]
rows = b"".join(b"".join(struct.pack("<H", p565[y * W2 + x]) for x in range(W2)) + b"\0\0" for y in range(H2))
cases.append({"name": "hand RGB 5_6_5 (row padding)", "data": ktx1(0x8363, 2, 0x1907, 0x8D62, 0x1907, W2, H2, rows), "layout": "2d",
"surfaces": [surf(0, 0, 0, W2, H2, bytes(q8(v) for p in p565 for v in ((p >> 11) / 31, ((p >> 5) & 63) / 63, (p & 31) / 31, 1.0)), None, 1)]})
rgb = bytes(rng.randrange(256) for _ in range(W2 * H2 * 3))
rows = b"".join(rgb[y * W2 * 3:(y + 1) * W2 * 3] + b"\0" for y in range(H2))
kv = b"KTXorientation\0S=r,T=u\0"
kv = struct.pack("<I", len(kv)) + kv + b"\0" * ((4 - len(kv) % 4) % 4)
flipped = b"".join(rgb[(H2 - 1 - y) * W2 * 3 + x * 3:(H2 - 1 - y) * W2 * 3 + x * 3 + 3] + b"\xff" for y in range(H2) for x in range(W2))
cases.append({"name": "hand RGB8 T=u", "data": ktx1(0x1401, 1, 0x1907, 0x8051, 0x1907, W2, H2, rows, False, kv), "layout": "2d",
"surfaces": [surf(0, 0, 0, W2, H2, flipped)]})
return cases
def _ours(ctx, work):
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", "ktx"], cwd=ctx.root, capture_output=True, check=True)
files = {}
for line in res.stdout.decode().split("\n"):
if "\t" in line:
n, hx = line.split("\t", 1)
files[n] = bytes.fromhex(hx.strip())
names = sorted(files)
sh = []
for n in names:
open(os.path.join(work, n), "wb").write(files[n])
base = n[:-5]
sh.append("(ktx validate %s > %s.val 2>&1; echo $? > %s.rc)" % (n, base, base))
sh.append("(ktx extract %s %s.x > /dev/null 2>&1 || true)" % (n, base))
ctx.nix("ktx-tools", ["sh", "-c", "cd %s && %s" % (work, " ; ".join(sh))])
out = []
pngs, idx = [], []
for i, n in enumerate(names):
base = n[:-5]
rc = open(os.path.join(work, base + ".rc")).read().strip()
e = {"name": n, "data": files[n], "valid": rc == "0", "report": open(os.path.join(work, base + ".val"), "rb").read()[:2000]}
for ext in (".x", ".x.png", ".x.exr"):
p = os.path.join(work, base + ext)
if os.path.exists(p) and os.path.isfile(p):
e["extracted"] = open(p, "rb").read()[:8]
if open(p, "rb").read(4) == b"\x89PNG":
pngs.append(p)
idx.append(i)
out.append(e)
for i, (mode, w, h, raw) in zip(idx, R.pillow(ctx, [open(p, "rb").read() for p in pngs])):
if mode in ("RGBA", "RGB", "L", "LA"):
out[i]["png"] = R.rgba_from(mode, raw)
return out
+95
View File
@@ -0,0 +1,95 @@
# OpenRaster fixtures (tools/fixtures.py): ORA files assembled here by the specification (python zipfile, the stored
# mimetype first, stack.xml, Pillow-written PNG layers, mergedimage.png, a thumbnail): plain layers with offsets /
# opacity / hidden / composite-ops, nested stacks (isolate and auto), a file without mergedimage; and our encoder's
# file (tools/fixtures/_tex_encode.luau -a ora) taken apart by python (zip order and method, stack.xml, PNG pixels
# through Pillow). References: the layer attributes and source pixels written here.
# tests/gen/ora.luau { cases = { { name, data, w, h, layers (bottom to top, depth-first) = { { name, x, y, opacity,
# visible, blend, depth, rgba?, w?, h? } }, merged? } }, ours = { ok, entries, layers } }
import importlib.util, io, os, struct, xml.etree.ElementTree as ET, zipfile
def _load(n):
spec = importlib.util.spec_from_file_location(n, os.path.join(os.path.dirname(os.path.abspath(__file__)), n + ".py"))
m = importlib.util.module_from_spec(spec)
spec.loader.exec_module(m)
return m
R, S, T = _load("_raster_ref"), _load("_simple"), _load("_tex_reference")
INPUTS = ["tools/fixtures/_tex_encode.luau", "src/Formats/layered/ora"]
OPS = {"svg:src-over": "normal", "svg:multiply": "multiply", "svg:screen": "screen", "svg:overlay": "overlay", "svg:color-dodge": "colorDodge"}
def build(stack_xml, pngs, merged=True, w=40, h=30):
buf = io.BytesIO()
z = zipfile.ZipFile(buf, "w")
z.writestr(zipfile.ZipInfo("mimetype"), "image/openraster", compress_type=zipfile.ZIP_STORED)
z.writestr("stack.xml", stack_xml, compress_type=zipfile.ZIP_DEFLATED)
for n, d in pngs.items():
z.writestr(n, d, compress_type=zipfile.ZIP_STORED)
if merged:
z.writestr("mergedimage.png", R.png(w, h, bytes(w * h * 4)), compress_type=zipfile.ZIP_STORED)
z.close()
return buf.getvalue()
def generate(ctx):
cases = []
imgs = {}
for i, (w, h) in enumerate(((40, 30), (20, 10), (8, 8), (10, 12), (6, 5))):
imgs["data/l%d.png" % i] = (w, h, R.photo(w, h, i + 1, i > 0))
pngs = {k: R.png(*v) for k, v in imgs.items()}
def lay(src, name, x, y, op, vis, depth):
w, h, px = imgs[src]
return {"name": name, "x": x, "y": y, "opacity": op[0], "visible": vis, "blend": op[1], "depth": depth, "rgba": px, "w": w, "h": h}
xml1 = '''<?xml version="1.0" encoding="UTF-8"?>
<image version="0.0.6" w="40" h="30" xres="144" yres="144"><stack>
<layer name="top hidden" src="data/l2.png" x="1" y="2" visibility="hidden" opacity="1.0"/>
<layer name="mid" src="data/l1.png" x="5" y="7" opacity="0.5" composite-op="svg:multiply"/>
<layer name="background" src="data/l0.png"/>
</stack></image>'''
cases.append({"name": "plain", "data": build(xml1, pngs), "w": 40, "h": 30, "dpi": 144, "merged": True, "layers": [
lay("data/l0.png", "background", 0, 0, (1.0, "normal"), True, 0), lay("data/l1.png", "mid", 5, 7, (0.5, "multiply"), True, 0),
lay("data/l2.png", "top hidden", 1, 2, (1.0, "normal"), False, 0)]})
xml2 = '''<image w="40" h="30"><stack>
<stack name="outer" isolation="isolate" opacity="0.8" x="2" y="3">
<layer name="a" src="data/l3.png" x="1" y="1" composite-op="svg:screen"/>
<stack name="inner" opacity="0.5"><layer name="b" src="data/l4.png" composite-op="svg:color-dodge"/></stack>
</stack>
<layer name="base" src="data/l0.png"/>
</stack></image>'''
cases.append({"name": "nested", "data": build(xml2, pngs, merged=False), "w": 40, "h": 30, "merged": False, "layers": [
lay("data/l0.png", "base", 0, 0, (1.0, "normal"), True, 0),
{"name": "outer", "x": 0, "y": 0, "opacity": 0.8, "visible": True, "blend": "normal", "depth": 0, "group": True},
{"name": "inner", "x": 0, "y": 0, "opacity": 0.5, "visible": True, "blend": "passThrough", "depth": 1, "group": True},
lay("data/l4.png", "b", 2, 3, (1.0, "colorDodge"), True, 2),
lay("data/l3.png", "a", 3, 4, (1.0, "screen"), True, 1)]})
# ours, taken apart
mine = S.ours(ctx, "ora")["ours_doc.ora"]
z = zipfile.ZipFile(io.BytesIO(mine))
infos = z.infolist()
ok = infos[0].filename == "mimetype" and infos[0].compress_type == zipfile.ZIP_STORED and z.read("mimetype") == b"image/openraster"
root = ET.fromstring(z.read("stack.xml"))
layers = []
def walk(node, depth):
for ch in node:
a = ch.attrib
e = {"tag": ch.tag, "name": a.get("name", ""), "depth": depth, "opacity": float(a.get("opacity", "1")),
"visible": a.get("visibility", "visible") == "visible", "op": a.get("composite-op", ""), "isolation": a.get("isolation", "")}
if ch.tag == "layer":
e["x"], e["y"] = int(a.get("x", "0")), int(a.get("y", "0"))
e["src"] = a["src"]
layers.append(e)
if ch.tag == "stack":
walk(ch, depth + 1)
walk(root.find("stack"), 0)
srcs = [l["src"] for l in layers if l["tag"] == "layer"] + ["mergedimage.png", "Thumbnails/thumbnail.png"]
decoded = T.pillow(ctx, [z.read(s) for s in srcs])
px = {s: {"w": d[1], "h": d[2], "rgba": T.rgba_from(d[0], d[3])} for s, d in zip(srcs, decoded)}
for l in layers:
if l["tag"] == "layer":
l.update(px[l["src"]])
ours = {"data": mine, "ok": ok, "w": int(root.attrib["w"]), "h": int(root.attrib["h"]), "entries": [i.filename for i in infos],
"layers": layers, "merged": px["mergedimage.png"], "thumb": [px["Thumbnails/thumbnail.png"]["w"], px["Thumbnails/thumbnail.png"]["h"]]}
ctx.emit("ora", {"cases": cases, "ours": ours})
+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()
+39
View File
@@ -0,0 +1,39 @@
# SGI fixtures (tools/fixtures.py): files from netpbm (pnmtosgi: RLE and verbatim, RGB and grey), ImageMagick (RGB,
# RGBA, 16-bit) and Pillow (L, RGB, RGBA), plus our encoder's files (tools/fixtures/_tex_encode.luau -a sgi); the
# reference is ImageMagick's decode of each file (16-bit within 1: it rounds where we keep the high byte).
# tests/gen/sgi.luau { cases = { { name, data, w, h, rgba, tol } }, ours = { ... } }
import importlib.util, os
def _load(n):
spec = importlib.util.spec_from_file_location(n, os.path.join(os.path.dirname(os.path.abspath(__file__)), n + ".py"))
m = importlib.util.module_from_spec(spec)
spec.loader.exec_module(m)
return m
R, S = _load("_raster_ref"), _load("_simple")
INPUTS = ["tools/fixtures/_tex_encode.luau", "src/Formats/image/sgi"]
def generate(ctx):
w = R.Work(ctx)
try:
w.png("photo.png", 37, 23, R.photo(37, 23))
w.png("alpha.png", 30, 17, R.photo(30, 17, 3, True))
w.sh("netpbm", ["pngtopam photo.png | pamtopnm > photo.ppm", "pnmtosgi -rle photo.ppm > nb_rle.sgi", "pnmtosgi -verbatim photo.ppm > nb_verbatim.sgi",
"ppmtopgm photo.ppm | pnmtosgi -rle > nb_grey.sgi"])
w.sh("imagemagick", ["magick photo.png -alpha off im_rgb.sgi", "magick alpha.png im_rgba.sgi", "magick photo.png -alpha off -depth 16 im_rgb16.sgi",
"magick alpha.png -compress none im_rgba_verbatim.sgi"])
ctx.python(["pillow"], ("from PIL import Image\nimport os\nos.chdir(%r)\nim=Image.open('alpha.png')\nim.save('pil_rgba.sgi')\n"
"im.convert('RGB').save('pil_rgb.sgi')\nim.convert('L').save('pil_l.sgi')\n") % w.dir)
names = sorted(f for f in os.listdir(w.dir) if f.endswith(".sgi"))
mine = S.ours(ctx, "sgi")
for n, d in mine.items():
w.write(n, d)
ref = S.magick_cases(R, w, names + sorted(mine))
out = {"cases": [], "ours": []}
for n in names + sorted(mine):
ww, hh, rgba = ref[n]
out["ours" if n.startswith("ours_") else "cases"].append({"name": n, "data": w.read(n), "w": ww, "h": hh, "rgba": rgba, "tol": 1 if "16" in n else 0})
ctx.emit("sgi", out)
finally:
w.close()
+45
View File
@@ -0,0 +1,45 @@
# Sun Raster fixtures (tools/fixtures.py): files from netpbm (pnmtorast: standard and byte-encoded, 1 / 8 / 24-bit) and
# ImageMagick (24-bit, 32-bit with alpha, 8-bit palette, 1-bit), plus our encoder's files (tools/fixtures/_tex_encode
# .luau -a sunras); the reference is rasttopnm for netpbm's and our files (RGB only) and ImageMagick's decode for the others.
# tests/gen/sunras.luau { cases = { { name, data, w, h, rgba } }, ours = { ... } }
import importlib.util, os
def _load(n):
spec = importlib.util.spec_from_file_location(n, os.path.join(os.path.dirname(os.path.abspath(__file__)), n + ".py"))
m = importlib.util.module_from_spec(spec)
spec.loader.exec_module(m)
return m
R, S = _load("_raster_ref"), _load("_simple")
INPUTS = ["tools/fixtures/_tex_encode.luau", "src/Formats/image/sunras"]
def generate(ctx):
w = R.Work(ctx)
try:
w.png("photo.png", 37, 23, R.photo(37, 23))
w.png("pal.png", 31, 19, R.palette_image(31, 19, 40))
w.png("alpha.png", 30, 17, R.photo(30, 17, 3, True))
w.sh("netpbm", ["pngtopam photo.png | pamtopnm > photo.ppm", "pngtopam pal.png | pamtopnm > pal.ppm",
"pnmtorast -standard photo.ppm > nb_24_standard.ras", "pnmtorast -rle photo.ppm > nb_24_rle.ras",
"pnmtorast -rle pal.ppm > nb_8_rle.ras", "ppmtopgm photo.ppm | pnmtorast -standard > nb_grey.ras",
"ppmtopgm photo.ppm | pgmtopbm | pnmtorast -rle > nb_1.ras"])
w.sh("imagemagick", ["magick photo.png -alpha off im_24.ras", "magick alpha.png im_32.ras", "magick pal.png -alpha off -type palette im_8.ras",
"magick photo.png -monochrome im_1.ras"])
names = sorted(f for f in os.listdir(w.dir) if f.endswith(".ras"))
mine = S.ours(ctx, "sunras")
for n, d in mine.items():
w.write(n, d)
# netpbm's own files through rasttopnm (ImageMagick cuts the last row of nb_8_rle short), the rest through ImageMagick
nb = [n for n in names if n.startswith("nb_")] + sorted(mine)
w.sh("netpbm", ["rasttopnm %s > %s.pnm" % (n, n) for n in nb])
ref = S.magick_cases(R, w, [n for n in names if not n.startswith("nb_")], "sun")
for n in nb:
ref[n] = R.pnm_rgba(w.read(n + ".pnm"))
out = {"cases": [], "ours": []}
for n in names + sorted(mine):
ww, hh, rgba = ref[n]
out["ours" if n.startswith("ours_") else "cases"].append({"name": n, "data": w.read(n), "w": ww, "h": hh, "rgba": rgba})
ctx.emit("sunras", out)
finally:
w.close()
+43
View File
@@ -0,0 +1,43 @@
# XBM fixtures (tools/fixtures.py): files from netpbm (pbmtoxbm X11 and -x10), ImageMagick and Pillow (with a hotspot),
# a hand-written one (comments, odd spacing); the reference is xbmtopbm (netpbm); our encoder's files
# (tools/fixtures/_tex_encode.luau -a xbm) read by xbmtopbm.
# tests/gen/xbm.luau { cases = { { name, data, w, h, rgba, hotspot? } }, ours = { ... } }
import importlib.util, os
def _load(n):
spec = importlib.util.spec_from_file_location(n, os.path.join(os.path.dirname(os.path.abspath(__file__)), n + ".py"))
m = importlib.util.module_from_spec(spec)
spec.loader.exec_module(m)
return m
R, S = _load("_raster_ref"), _load("_simple")
INPUTS = ["tools/fixtures/_tex_encode.luau", "src/Formats/image/xbm"]
def generate(ctx):
w = R.Work(ctx)
try:
mono = bytes(v for i in range(29 * 13) for v in ((0,) * 3 if (i * 7 + i // 29) % 5 < 2 else (255,) * 3) + (255,))
w.png("mono.png", 29, 13, mono)
w.png("mono2.png", 16, 9, bytes(v for i in range(16 * 9) for v in ((0,) * 3 if (i % 3 == 0) else (255,) * 3) + (255,)))
w.sh("netpbm", ["pngtopam mono.png | pamtopnm | ppmtopgm | pgmtopbm -threshold > mono.pbm", "pbmtoxbm mono.pbm > nb_x11.xbm",
"pbmtoxbm -x10 mono.pbm > nb_x10.xbm"])
w.sh("imagemagick", ["magick mono2.png im.xbm"])
ctx.python(["pillow"], "from PIL import Image\nimport os\nos.chdir(%r)\nImage.open('mono.png').convert('1').save('pil.xbm', hotspot=(3, 4))\n" % w.dir)
w.write("hand.xbm", b"/* a comment */\n#define hand_width 10\n#define hand_height 2\nstatic unsigned char hand_bits[] = {\n 0xff,0x03, /* row 0 */\n 0x00, 0x01 };\n")
names = sorted(f for f in os.listdir(w.dir) if f.endswith(".xbm"))
mine = S.ours(ctx, "xbm")
for n, d in mine.items():
w.write(n, d)
allnames = names + sorted(mine)
w.sh("netpbm", ["xbmtopbm %s > %s.pbm" % (n, n) for n in allnames])
out = {"cases": [], "ours": []}
for n in allnames:
ww, hh, rgba = R.pnm_rgba(w.read(n + ".pbm"))
c = {"name": n, "data": w.read(n), "w": ww, "h": hh, "rgba": rgba}
if n == "pil.xbm":
c["hotspot"] = [3, 4]
out["ours" if n.startswith("ours_") else "cases"].append(c)
ctx.emit("xbm", out)
finally:
w.close()
+58
View File
@@ -0,0 +1,58 @@
# XPM fixtures (tools/fixtures.py): files from netpbm (ppmtoxpm -hexonly), ImageMagick (with alpha: None) and
# hand-written ones (colour names, #RGB / #RRRRGGGGBBBB, g / m keys, two chars per pixel, XPM 2); the reference is
# ImageMagick's decode (the XPM 2 file's values are written here: ImageMagick does not read XPM 2); our encoder's files (tools/fixtures/_tex_encode.luau -a xpm) read by ImageMagick.
# tests/gen/xpm.luau { cases = { { name, data, w, h, rgba } }, ours = { ... } }
import importlib.util, os
def _load(n):
spec = importlib.util.spec_from_file_location(n, os.path.join(os.path.dirname(os.path.abspath(__file__)), n + ".py"))
m = importlib.util.module_from_spec(spec)
spec.loader.exec_module(m)
return m
R, S = _load("_raster_ref"), _load("_simple")
INPUTS = ["tools/fixtures/_tex_encode.luau", "src/Formats/image/xpm"]
HAND = b'''/* XPM */
static char * hand_xpm[] = {
/* width height ncolors cpp */
"6 4 6 2",
" c None",
".. c red",
"XX g4 #888 c LightBlue m white",
"oo c #FFFF00000000",
"++ s mine c navy",
"@@ c Gold",
" ..XXoo++@@",
"..XXoo++@@ ",
"XXoo++@@ ..",
"oo++@@ ..XX"};
'''
XPM2 = b"! XPM2\n3 2 2 1\na c #102030\nb c white\nabb\nbab\n"
def generate(ctx):
w = R.Work(ctx)
try:
w.png("pal.png", 31, 19, R.palette_image(31, 19, 40))
w.png("alpha.png", 20, 11, bytes(v for i in range(20 * 11) for v in (((i * 40) % 256, 80, 200, 255 if i % 3 else 0))))
w.sh("netpbm", ["pngtopam pal.png | pamtopnm > pal.ppm", "ppmtoxpm -hexonly pal.ppm > nb.xpm"])
w.sh("imagemagick", ["magick pal.png -alpha off im.xpm", "magick alpha.png im_alpha.xpm"])
w.write("hand.xpm", HAND)
w.write("hand2.xpm", XPM2)
names = sorted(f for f in os.listdir(w.dir) if f.endswith(".xpm") and f != "hand2.xpm")
mine = S.ours(ctx, "xpm")
for n, d in mine.items():
w.write(n, d)
ref = S.magick_cases(R, w, names + sorted(mine), "xpm")
out = {"cases": [], "ours": []}
for n in names + sorted(mine):
ww, hh, rgba = ref[n]
# ImageMagick keeps the colour of transparent pixels; we decode None as transparent black
rgba = bytes(0 if rgba[i - i % 4 + 3] == 0 else v for i, v in enumerate(rgba))
out["ours" if n.startswith("ours_") else "cases"].append({"name": n, "data": w.read(n), "w": ww, "h": hh, "rgba": rgba})
a, b = bytes((0x10, 0x20, 0x30, 255)), b"\xff" * 4
out["cases"].append({"name": "hand2.xpm (XPM 2)", "data": XPM2, "w": 3, "h": 2, "rgba": a + b + b + b + a + b})
ctx.emit("xpm", out)
finally:
w.close()