196 lines
9.9 KiB
Python
196 lines
9.9 KiB
Python
# 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/Rosetta/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]
|