Files
rosetta/tools/fixtures/aseprite.py
T
4DBugandClaude Opus 5.5 434a304315 ws-cleanup: codecs/ grouped by domain; containers/Chunks, codecs/audio/Stream, codecs/image/Pixels, codecs/model/Mat4
C2, the hierarchy (tools/move.py, every reference rewritten mechanically):
- codecs/compress: Deflate Lzma Zstd Brotli Bzip2 Lzw; codecs/entropy: Huffman (from core) RangeCoder;
  codecs/image: Jpeg Dct Vp8 Vp8L Yuv Quantize Raster Blend Pixels; codecs/audio: Mdct Aac Alac Pcm Resample
  VorbisComment Tracker SoundFont Stream; codecs/video: H264 Mpeg1 Video; codecs/text: Json Xml Text Url;
  codecs/font: TrueType Cff; codecs/model: MeshFlatten Mat4. containers/ stays flat; core/ keeps Bytes Bits Err
  Crc32 Adler32 Base64 Md5 Input Sniff.
- LAYERS lint: codecs must sit in a domain folder; gen_registry lists codecs by domain (docs/FORMATS.md).
- Checked: build.py both targets, rojo build of build/roblox, the full suite on both runtimes.

C3, generic code out of format folders:
- containers/Chunks (new): the chunked-file walker (RIFF / RIFX / IFF / PNG / CAF layouts: endianness, size first,
  trailer, padding, lenient missing pad, open-ended ids, size hooks). containers/Riff walks with it (RF64 ds64
  through the resize hook); image/png, audio/aiff and audio/caf list their chunk handlers over it.
- codecs/audio/Stream (new): Stream.packets, the packet-decoder Decoder (read / seek with pre-roll / position,
  priming and end trimming) that aac, caf and m4a each carried (~70 lines each).
- codecs/image/Pixels: image/bmp/Pixels promoted (+ rgb555); image/ico's DIB decoder uses its row loops instead of
  its own (the AND mask / alpha rule stay ICO's).
- codecs/model/Mat4 (new): matrices / quaternions / TRS shared by FBX (Xform keeps only the FBX transform model),
  Collada (Math keeps only <lookat> / <skew>) and USD (its matrix helpers and general 4x4 inverse); Mat4.mul is
  Types.Scene.mul. The Collada normal matrix is now the inverse transpose (it was the inverse; same result for the
  fixtures' bind shapes).
- README rewritten (install for Rojo and LÖVE / LuaJIT, quick start per category, F.* and F.ops, host notes:
  FORMATS_NO_JIT_TUNE, paths, layout); docs/STYLE.md: the codec domains, "what belongs in a format folder" with the
  shared building blocks and the DUP rule, conventions (WAVE order, lower-case tags, loops, the api hooks
  decodeImage / encodeImage / openAudio / plugins / resolve, the codecs/video/Video registry), Err.from, the type
  baseline. New tests: tests/containers/chunks, tests/codecs/mat4. Type baseline 93.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-31 12:25:03 -05:00

214 lines
10 KiB
Python

# Aseprite fixtures (tools/fixtures.py). Sprites written here by a small writer following docs/ase-file-specs.md
# (RGBA / grayscale / indexed, raw / zlib / linked cels, groups, hidden layers, blend modes, layer and cel opacity,
# old and new palette chunks, tags, user data), sprites written by LibreSprite (the reference: an Aseprite 1.1 fork,
# in nixpkgs) and LibreSprite's flattened rendering of every frame:
# tests/gen/aseprite.luau { cases = { { name, data, width, height, nframes, cels = { { frame, layer, x, y, w, h,
# crc } }, frames = { RGBA of LibreSprite's frame i } } } }
# tests/gen/aseprite_ours.luau { frames = { ... }, ours = { ... } }: our encoder's sprite (tools/fixtures/_ours.luau)
# rendered by LibreSprite, with our flatten of the same frames
import json, os, shutil, struct, subprocess, tempfile, zlib
INPUTS = ["src/Formats/layered/aseprite", "src/Formats/codecs/image/Blend.luau", "tools/fixtures/_ours.luau"]
def s(text):
b = text.encode()
return struct.pack("<H", len(b)) + b
def chunk(ctype, body):
return struct.pack("<IH", len(body) + 6, ctype) + body
def layer_chunk(name, flags=3, ltype=0, level=0, blend=0, opacity=255):
return chunk(0x2004, struct.pack("<HHHHHHB3x", flags, ltype, level, 0, 0, blend, opacity) + s(name))
def cel_chunk(layer, x, y, w, h, pixels, opacity=255, kind=2, link=None, z=0):
head = struct.pack("<HhhBHh5x", layer, x, y, opacity, 1 if link is not None else kind, z)
if link is not None:
return chunk(0x2005, head + struct.pack("<H", link))
if kind == 0:
return chunk(0x2005, head + struct.pack("<HH", w, h) + pixels)
return chunk(0x2005, head + struct.pack("<HH", w, h) + zlib.compress(pixels))
def palette_chunk(colors, names=None):
body = struct.pack("<III8x", len(colors), 0, len(colors) - 1)
for i, c in enumerate(colors):
n = (names or {}).get(i)
body += struct.pack("<H4B", 1 if n else 0, *c) + (s(n) if n else b"")
return chunk(0x2019, body)
def old_palette_chunk(colors):
body = struct.pack("<HBB", 1, 0, len(colors) & 255) + b"".join(bytes(c[:3]) for c in colors)
return chunk(0x0004, body)
def tags_chunk(tags):
body = struct.pack("<H8x", len(tags))
for name, a, b, d, rep in tags:
body += struct.pack("<HHBH6x3Bx", a, b, d, rep, 255, 0, 0) + s(name)
return chunk(0x2018, body)
def user_chunk(text=None, color=None):
f = (1 if text is not None else 0) | (2 if color else 0)
return chunk(0x2020, struct.pack("<I", f) + (s(text) if text is not None else b"") + (bytes(color) if color else b""))
def sprite(w, h, depth, frames, transparent=0, flags=3, ncolors=0):
"""frames: [(duration_ms, [chunk bytes])]"""
body = b""
for dur, chunks in frames:
data = b"".join(chunks)
body += struct.pack("<IHHHxxI", len(data) + 16, 0xF1FA, min(len(chunks), 0xFFFF), dur, len(chunks)) + data
head = struct.pack("<IHHHHHIH II B3x H BB hhHH", 128 + len(body), 0xA5E0, len(frames), w, h, depth, flags, 100, 0, 0, transparent, ncolors, 1, 1, 0, 0, 16, 16)
head += b"\0" * (128 - len(head))
return head + body
def rgba(w, h, seed, alpha=True):
out = bytearray()
for y in range(h):
for x in range(w):
a = 255 if not alpha or (x + y) % 4 else (x * 50 + seed * 30) % 256
out += bytes(((x * (seed + 2) * 9 + y * 3) % 256, (y * (seed + 1) * 11 + x) % 256, ((x + seed) * (y + 2) * 5) % 256, a))
return bytes(out)
def case_rgba():
W, H = 32, 24
cels = []
def cel(frame, layer, x, y, w, h, px, **kw):
cels.append({"frame": frame, "layer": layer, "x": x, "y": y, "w": w, "h": h, "crc": zlib.crc32(px)})
return cel_chunk(layer - 1, x, y, w, h, px, **kw)
bg = rgba(W, H, 1, alpha=False)
pal = [(i, 255 - i, (i * 7) % 256, 255) for i in range(0, 256, 16)]
f1 = [
palette_chunk(pal, {0: "first", 3: "fourth"}),
layer_chunk("Background", flags=1 | 2 | 8),
layer_chunk("Group", ltype=1, flags=3),
layer_chunk("Mul", level=1, blend=1, opacity=200),
user_chunk("mul layer", (1, 2, 3, 4)),
layer_chunk("Half", level=1),
layer_chunk("Hidden", flags=2),
layer_chunk("Top"),
tags_chunk([("walk", 0, 1, 0, 0), ("back", 1, 2, 2, 3)]),
user_chunk("walk tag"),
user_chunk(None),
cel(1, 1, 0, 0, W, H, bg, kind=0),
cel(1, 3, 4, 3, 16, 12, rgba(16, 12, 2)),
user_chunk("a cel"),
cel(1, 4, 10, 8, 14, 10, rgba(14, 10, 3), opacity=128),
cel(1, 5, 0, 0, 8, 8, rgba(8, 8, 4)),
cel(1, 6, 20, 2, 10, 20, rgba(10, 20, 5)),
]
f2 = [
cel_chunk(0, 0, 0, W, H, bg, link=0),
cel(2, 3, 6, 5, 16, 12, rgba(16, 12, 6)),
cel(2, 6, -4, 10, 12, 8, rgba(12, 8, 7), kind=0),
]
f3 = [
cel_chunk(0, 0, 0, W, H, bg, link=0),
cel_chunk(2, 4, 3, 16, 12, b"", link=0),
cel(3, 4, 1, 1, 30, 20, rgba(30, 20, 8), opacity=64),
]
# linked cels repeat their target
cels.append({"frame": 2, "layer": 1, "x": 0, "y": 0, "w": W, "h": H, "crc": zlib.crc32(bg)})
cels.append({"frame": 3, "layer": 1, "x": 0, "y": 0, "w": W, "h": H, "crc": zlib.crc32(bg)})
cels.append({"frame": 3, "layer": 3, "x": 4, "y": 3, "w": 16, "h": 12, "crc": zlib.crc32(rgba(16, 12, 2))})
return sprite(W, H, 32, [(100, f1), (150, f2), (200, f3)], ncolors=len(pal)), cels
def case_gray():
cels = []
px = bytes(v for x in range(10 * 6) for v in ((x * 4) % 256, 255 if x % 3 else 128))
exp = b"".join(bytes((px[i * 2],) * 3 + (px[i * 2 + 1],)) for i in range(60))
cels.append({"frame": 1, "layer": 1, "x": 1, "y": 1, "w": 10, "h": 6, "crc": zlib.crc32(exp)})
cels.append({"frame": 2, "layer": 1, "x": 3, "y": 2, "w": 10, "h": 6, "crc": zlib.crc32(exp)})
f1 = [layer_chunk("G"), cel_chunk(0, 1, 1, 10, 6, px)]
f2 = [cel_chunk(0, 3, 2, 10, 6, px, kind=0)]
return sprite(14, 9, 16, [(80, f1), (80, f2)]), cels
def case_indexed():
# the background cel covers the sprite (as Aseprite writes it): its transparent index stays opaque
pal = [(0, 0, 0, 255), (255, 0, 0, 255), (0, 255, 0, 255), (0, 0, 255, 255), (255, 255, 0, 255)]
idx = bytes((x + y) % 5 for y in range(7) for x in range(9))
bgi = bytes((x * y) % 5 for y in range(9) for x in range(12))
exp = b"".join(bytes(pal[i][:3]) + bytes((0 if i == 0 else 255,)) for i in idx)
exp_bg = b"".join(bytes(pal[i]) for i in bgi)
cels = [{"frame": 1, "layer": 1, "x": 0, "y": 0, "w": 12, "h": 9, "crc": zlib.crc32(exp_bg)},
{"frame": 1, "layer": 2, "x": 2, "y": 1, "w": 9, "h": 7, "crc": zlib.crc32(exp)}]
f1 = [old_palette_chunk(pal), layer_chunk("Back", flags=1 | 2 | 8), layer_chunk("Sprite"), cel_chunk(0, 0, 0, 12, 9, bgi), cel_chunk(1, 2, 1, 9, 7, idx)]
return sprite(12, 9, 8, [(100, f1)], transparent=0, ncolors=5), cels
def libresprite(ctx, argv, cwd):
if shutil.which("libresprite"):
subprocess.run(["libresprite"] + argv, check=True, capture_output=True, cwd=cwd)
else:
subprocess.run(["nix", "shell", "nixpkgs#libresprite", "-c", "libresprite"] + argv, check=True, capture_output=True, cwd=cwd)
def rgba_of(ctx, png):
argv = ["magick", png, "-depth", "8", "rgba:-"]
try:
return subprocess.run(argv, check=True, capture_output=True).stdout
except (OSError, subprocess.CalledProcessError):
return ctx.nix("imagemagick", argv)
def render(ctx, data, nframes):
"""LibreSprite's flattened frames of an .ase (RGBA bytes each)"""
with tempfile.TemporaryDirectory() as d:
open(os.path.join(d, "in.aseprite"), "wb").write(data)
libresprite(ctx, ["-b", "in.aseprite", "--save-as", "f.png"], d)
if nframes == 1:
return [rgba_of(ctx, os.path.join(d, "f.png"))]
return [rgba_of(ctx, os.path.join(d, "f%d.png" % i)) for i in range(1, nframes + 1)]
def resave(ctx, data, ext_in="aseprite"):
with tempfile.TemporaryDirectory() as d:
open(os.path.join(d, "in." + ext_in), "wb").write(data)
libresprite(ctx, ["-b", "in." + ext_in, "--save-as", "out.aseprite"], d)
return open(os.path.join(d, "out.aseprite"), "rb").read()
def run_ours(ctx, fmt):
script = os.path.join(ctx.root, "tools", "fixtures", "_ours.luau")
luau = shutil.which("luau")
argv = [luau, script, "-a", fmt] if luau else ["nix", "shell", "nixpkgs#luau", "-c", "luau", script, "-a", fmt]
return json.loads(subprocess.run(argv, check=True, capture_output=True, cwd=ctx.root).stdout)
def gif(ctx):
with tempfile.TemporaryDirectory() as d:
a, b, g = os.path.join(d, "a.png"), os.path.join(d, "b.png"), os.path.join(d, "anim.gif")
for argv in (["magick", "-size", "12x8", "gradient:red-blue", a], ["magick", "-size", "12x8", "xc:green", b], ["magick", "-delay", "20", a, b, "-loop", "0", g]):
try:
subprocess.run(argv, check=True, capture_output=True)
except (OSError, subprocess.CalledProcessError):
ctx.nix("imagemagick", argv)
return open(g, "rb").read()
def generate(ctx):
cases = []
for name, (data, cels) in (("rgba", case_rgba()), ("gray", case_gray()), ("indexed", case_indexed())):
n = struct.unpack_from("<H", data, 6)[0]
w, h = struct.unpack_from("<HH", data, 8)
cases.append({"name": name, "data": data, "width": w, "height": h, "nframes": n, "cels": cels, "frames": render(ctx, data, n)})
# sprites LibreSprite writes: our rgba case re-saved, and a GIF converted
re = resave(ctx, cases[0]["data"])
cases.append({"name": "libresprite-resave", "data": re, "width": 32, "height": 24, "nframes": 3, "cels": [], "frames": render(ctx, re, 3)})
g = resave(ctx, gif(ctx), "gif")
cases.append({"name": "libresprite-gif", "data": g, "width": 12, "height": 8, "nframes": 2, "cels": [], "frames": render(ctx, g, 2)})
ctx.emit("aseprite", {"cases": cases})
o = run_ours(ctx, "aseprite")
data = bytes.fromhex(o["data"])
ctx.emit("aseprite_ours", {"nframes": o["nframes"], "frames": render(ctx, data, o["nframes"]), "ours": [bytes.fromhex(f) for f in o["frames"]]})