merge ws/vec: svg (+raster), psd, aseprite, tiled, srt/vtt/ass, codecs/Blend, core/Base64, ops/LayerOps
This commit is contained in:
commit
9821cd129b
38 files changed
+9899
-5
No files matched your search
@@ -471,3 +471,48 @@ do
|
||||
MeshOps.voxelsToPrimitive(grid)
|
||||
end)
|
||||
end
|
||||
do
|
||||
-- layered + vector (ws-vec): PSD decode / encode of 8 RGBA layers 1024 x 768, flatten (codecs/Blend), SVG
|
||||
-- rasterize at 512 x 512 (codecs/Raster). No fixtures: the inputs are built here.
|
||||
local Types = require("@formats/Types")
|
||||
local Psd = require("@formats/layered/psd")
|
||||
local LayerOps = require("@formats/ops/LayerOps")
|
||||
local Svg = require("@formats/vector/svg")
|
||||
local W, H = 1024, 768
|
||||
local doc = Types.Layered.new(W, H)
|
||||
local modes = { "normal", "multiply", "screen", "overlay", "normal", "softLight", "difference", "normal" }
|
||||
for k = 1, 8 do
|
||||
local img = Types.Image.new(W, H)
|
||||
local px = img.pixels
|
||||
for i = 0, W * H - 1 do
|
||||
local x, y = i % W, i // W
|
||||
buffer.writeu32(px, i * 4, ((x * k) % 256) + ((y * 3) % 256) * 256 + (((x + y) // 4) % 256) * 65536 + (if (x // 64 + y // 64 + k) % 3 == 0 then 0 else 200) * 16777216)
|
||||
end
|
||||
local l = Types.Layered.layer("L" .. k, img)
|
||||
l.blend = modes[k]
|
||||
doc.layers[k] = l
|
||||
end
|
||||
local psd = assert(Psd.encode(doc))
|
||||
bench("psd decode 8 layers 1024x768", 2, W * H * 4 * 9, function()
|
||||
Psd.decode(Bytes.reader(psd))
|
||||
end)
|
||||
bench("psd encode 8 layers (RLE)", 1, W * H * 4 * 9, function()
|
||||
Psd.encode(doc)
|
||||
end)
|
||||
bench("flatten 8 layers (blend modes)", 2, W * H * 4 * 8, function()
|
||||
LayerOps.flatten(doc)
|
||||
end)
|
||||
local shapes = {}
|
||||
for k = 0, 39 do
|
||||
table.insert(shapes, string.format("<circle cx='%d' cy='%d' r='%d' fill='url(#g)' stroke='#222' stroke-width='2' opacity='0.8'/>", (k * 37) % 100, (k * 53) % 100, 5 + k % 12))
|
||||
table.insert(shapes, string.format("<path d='M%d %d q 20 -30 40 0 t 40 0' fill='none' stroke='hsl(%d, 70%%, 50%%)' stroke-width='3' stroke-dasharray='4 2'/>", k % 50, k * 2, k * 9))
|
||||
end
|
||||
local text = "<svg xmlns='http://www.w3.org/2000/svg' width='100' height='100'><defs><radialGradient id='g' fx='0.3' fy='0.3'><stop offset='0' stop-color='#fff'/><stop offset='1' stop-color='#36c'/></radialGradient></defs>" .. table.concat(shapes) .. "</svg>"
|
||||
local v = assert(Svg.decode(Bytes.reader(buffer.fromstring(text))))
|
||||
bench("svg parse (80 elements)", 5, #text, function()
|
||||
Svg.decode(Bytes.reader(buffer.fromstring(text)))
|
||||
end)
|
||||
bench("svg rasterize 512x512 (80 shapes)", 2, 512 * 512 * 4, function()
|
||||
Svg.rasterize(v, 512, 512)
|
||||
end)
|
||||
end
|
||||
@@ -0,0 +1,180 @@
|
||||
-- tools/fixtures/_ours.luau: our encoders' output for the reference tools to read (run by tools/fixtures/*.py through
|
||||
-- `luau tools/fixtures/_ours.luau -a <format>`). Prints one JSON object: { "data": hex of the encoded file, ... the
|
||||
-- facts the python side checks the reference's reading against }.
|
||||
local Types = require("@formats/Types")
|
||||
local Crc32 = require("@formats/core/Crc32")
|
||||
local LayerOps = require("@formats/ops/LayerOps")
|
||||
|
||||
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
|
||||
|
||||
local function jstr(s: string): string
|
||||
return '"' .. string.gsub(s, '[%c"\\]', function(c: string): string
|
||||
return string.format("\\u%04x", string.byte(c))
|
||||
end) .. '"'
|
||||
end
|
||||
|
||||
local function json(v: any): string
|
||||
if type(v) == "table" then
|
||||
if #v > 0 or next(v) == nil then
|
||||
local t = {}
|
||||
for i, x in v do
|
||||
t[i] = json(x)
|
||||
end
|
||||
return "[" .. table.concat(t, ",") .. "]"
|
||||
end
|
||||
local t = {}
|
||||
for k, x in v do
|
||||
table.insert(t, jstr(k) .. ":" .. json(x))
|
||||
end
|
||||
return "{" .. table.concat(t, ",") .. "}"
|
||||
elseif type(v) == "string" then
|
||||
return jstr(v)
|
||||
elseif type(v) == "boolean" then
|
||||
return if v then "true" else "false"
|
||||
end
|
||||
return tostring(v)
|
||||
end
|
||||
|
||||
-- a deterministic rgba8 image
|
||||
local function image(w: number, h: number, seed: number, alpha: boolean?): Types.Image
|
||||
local img = Types.Image.new(w, h)
|
||||
for y = 0, h - 1 do
|
||||
for x = 0, w - 1 do
|
||||
local o = (y * w + x) * 4
|
||||
buffer.writeu8(img.pixels, o, (x * (seed + 3) * 7 + y * 5) % 256)
|
||||
buffer.writeu8(img.pixels, o + 1, (y * (seed + 1) * 9 + x) % 256)
|
||||
buffer.writeu8(img.pixels, o + 2, ((x + seed) * (y + 1) * 3) % 256)
|
||||
buffer.writeu8(img.pixels, o + 3, if alpha and (x + y) % 3 == 0 then (x * 40 + seed) % 256 else 255)
|
||||
end
|
||||
end
|
||||
return img
|
||||
end
|
||||
local function gray(w: number, h: number): Types.Image
|
||||
local img = Types.Image.new(w, h, "gray8")
|
||||
for i = 0, w * h - 1 do
|
||||
buffer.writeu8(img.pixels, i, (i * 13) % 256)
|
||||
end
|
||||
return img
|
||||
end
|
||||
|
||||
-- the Layered document tests/layered/psd.luau also builds (keep them in step)
|
||||
local function psdDoc(): Types.Layered
|
||||
local L = Types.Layered
|
||||
local doc = L.new(36, 24)
|
||||
local bg = L.layer("Background", image(36, 24, 1))
|
||||
local mul = L.layer("Multiply", image(20, 12, 2, true), 4, 3)
|
||||
mul.blend = "multiply"
|
||||
mul.opacity = 200 / 255
|
||||
local scr = L.layer("Screen", image(18, 18, 3, true), 12, 4)
|
||||
scr.blend = "screen"
|
||||
local iso = L.group("Isolated", { scr })
|
||||
iso.blend = "normal"
|
||||
iso.opacity = 180 / 255
|
||||
local hid = L.layer("Hidden", image(8, 8, 4), 1, 1)
|
||||
hid.visible = false
|
||||
local diff = L.layer("Diff \u{e9}\u{65e5}", image(14, 10, 5, true), 18, 12)
|
||||
diff.blend = "difference"
|
||||
local pass = L.group("Pass", { hid, diff })
|
||||
local base = L.layer("Base", image(10, 8, 6), 24, 14)
|
||||
local clip = L.layer("Clipped", image(14, 12, 7, true), 20, 10)
|
||||
clip.clip = true
|
||||
local masked = L.layer("Masked", image(16, 10, 8), 2, 12)
|
||||
masked.mask = { image = gray(12, 8), x = 4, y = 13, default = 0 }
|
||||
local fill = L.layer("Fill", image(8, 24, 9, true), 28, 0)
|
||||
fill.fillOpacity = 128 / 255
|
||||
fill.blend = "lighten"
|
||||
doc.layers = { bg, mul, iso, pass, base, clip, masked, fill }
|
||||
return doc
|
||||
end
|
||||
|
||||
-- an animated sprite (tests/layered/aseprite.luau builds the same one)
|
||||
local function aseDoc(): Types.Layered
|
||||
local L = Types.Layered
|
||||
local doc = L.new(24, 16)
|
||||
local bgImg = image(24, 16, 1)
|
||||
local shared = image(10, 8, 2, true)
|
||||
local frames = {}
|
||||
for f = 1, 3 do
|
||||
local bg = L.layer("Background", bgImg)
|
||||
local mul = L.layer("Mul", if f == 2 then image(10, 8, 7, true) else shared, 3 + (if f == 2 then 1 else 0), 2)
|
||||
mul.blend = "multiply"
|
||||
local half = L.layer("Half", image(12, 9, 3 + f, true), f * 2, 4)
|
||||
half.fillOpacity = 128 / 255
|
||||
local g = L.group("Group", { mul, half })
|
||||
local top = L.layer("Top", image(6, 6, 9 + f, true), 16 - f, 8)
|
||||
top.opacity = 200 / 255
|
||||
frames[f] = { layers = { bg, g, top }, delay = 0.05 * f }
|
||||
end
|
||||
doc.frames = frames
|
||||
doc.layers = frames[1].layers
|
||||
doc.meta.tags = { { name = "all", from = 1, to = 3, direction = "pingpong", ["repeat"] = 0 } }
|
||||
return doc
|
||||
end
|
||||
|
||||
-- a Tiled map (tools/fixtures/tiled.py has Tiled read our TMX and TMJ of it)
|
||||
local function tiledMap(): Types.TileMap
|
||||
local m: any = Types.TileMap.new(5, 4, 16, 16)
|
||||
m.nextLayerId, m.nextObjectId = 5, 4
|
||||
m.properties = { name = "ours", n = 7, f = 0.5, ok = false, c = "#ff112233" }
|
||||
m.propertyTypes = { c = "color" }
|
||||
m.tilesets = { { firstGid = 1, name = "tiles", tileWidth = 16, tileHeight = 16, columns = 4, count = 8, spacing = 0, margin = 0, imageSource = "tiles.png", imageWidth = 64, imageHeight = 32, properties = {}, tiles = { { id = 2, class = "Wall", properties = { hard = true } }, { id = 4, properties = {}, animation = { { tileId = 4, duration = 120 }, { tileId = 5, duration = 80 } } } } } }
|
||||
local data = {}
|
||||
for i = 1, 20 do
|
||||
data[i] = (i * 3) % 9
|
||||
end
|
||||
data[2] += 0x80000000
|
||||
data[10] += 0x40000000
|
||||
local tiles = { type = "tiles", id = 1, name = "ground", width = 5, height = 4, data = data, visible = true, opacity = 0.8, offsetX = 2, offsetY = 0, properties = { deep = 3 }, encoding = "base64", compression = "zlib" }
|
||||
local objs = {
|
||||
{ id = 1, name = "a", class = "Spawn", x = 4, y = 5.5, width = 8, height = 8, rotation = 30, visible = true, shape = "rectangle", properties = { team = "red" } },
|
||||
{ id = 2, name = "b", class = "", x = 20, y = 10, width = 0, height = 0, rotation = 0, visible = true, shape = "polyline", points = { { 0, 0 }, { 8, 4 }, { 16, 0 } }, properties = {} },
|
||||
{ id = 3, name = "c", class = "", x = 30, y = 30, width = 60, height = 14, rotation = 0, visible = false, shape = "text", text = { text = "hi there", fontFamily = "sans-serif", pixelSize = 14, wrap = true, color = "#00ff00", bold = false, italic = true, underline = false, strikeout = false, kerning = true, halign = "right", valign = "top" }, properties = {} },
|
||||
}
|
||||
local og = { type = "objects", id = 3, name = "things", visible = true, opacity = 1, drawOrder = "topdown", objects = objs, properties = {} }
|
||||
local img = { type = "image", id = 4, name = "sky", visible = true, opacity = 1, imageSource = "sky.png", imageWidth = 40, imageHeight = 20, repeatX = true, repeatY = false, properties = {} }
|
||||
local group = { type = "group", id = 2, name = "grp", visible = true, opacity = 0.5, layers = { og, img }, properties = {} }
|
||||
m.layers = { tiles, group }
|
||||
return m
|
||||
end
|
||||
|
||||
local which, arg = ...
|
||||
if which == "psd" then
|
||||
local Psd = require("@formats/layered/psd")
|
||||
local doc = psdDoc()
|
||||
local data = Psd.encode(doc) :: buffer
|
||||
local flat = LayerOps.flatten(doc) :: Types.Image
|
||||
local layers = {}
|
||||
for l, depth in LayerOps.leaves(doc.layers) do
|
||||
local lay = l :: any
|
||||
table.insert(layers, { name = lay.name, crc = Crc32.of(lay.image.pixels), left = lay.x, top = lay.y, width = lay.image.width, height = lay.image.height, blend = lay.blend, visible = lay.visible, clip = lay.clip == true, opacity = math.floor(lay.opacity * 255 + 0.5), depth = depth })
|
||||
end
|
||||
print(json({ data = hex(data), composite = Crc32.of(flat.pixels), layers = layers }))
|
||||
elseif which == "aseprite" then
|
||||
local Ase = require("@formats/layered/aseprite")
|
||||
local doc = aseDoc()
|
||||
local data = Ase.encode(doc) :: buffer
|
||||
local frames = {}
|
||||
for f = 1, 3 do
|
||||
frames[f] = hex((LayerOps.flatten(doc, { frame = f }) :: Types.Image).pixels)
|
||||
end
|
||||
print(json({ data = hex(data), nframes = 3, frames = frames }))
|
||||
elseif which == "tiled" then
|
||||
local Tiled = require("@formats/vector/tiled")
|
||||
local m = tiledMap()
|
||||
local tmx = Tiled.encode(m, { format = "tmx" }) :: buffer
|
||||
local tmj = Tiled.encode(m, { format = "tmj" }) :: buffer
|
||||
print(json({ tmx = hex(tmx), tmj = hex(tmj) }))
|
||||
elseif which == "svg" then
|
||||
-- the SVG text given on the command line, decoded and written back by our encoder
|
||||
local Svg = require("@formats/vector/svg")
|
||||
local Bytes = require("@formats/core/Bytes")
|
||||
local v = Svg.decode(Bytes.reader(buffer.fromstring(arg)))
|
||||
local out = if v then Svg.encode(v) else nil
|
||||
print(json({ svg = if out then buffer.tostring(out) else "" }))
|
||||
end
|
||||
@@ -0,0 +1,213 @@
|
||||
# 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/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"]]})
|
||||
@@ -0,0 +1,389 @@
|
||||
# PSD fixtures (tools/fixtures.py): PSD / PSB files written here (a small writer below: every colour mode, 1/8/16/32
|
||||
# bits, raw / RLE / ZIP / ZIP-with-prediction channels, groups, pass-through, clipping, masks, fill opacity, hidden
|
||||
# layers, Unicode names, every blend mode) and one written by ImageMagick, all read by psd-tools (the reference):
|
||||
# tests/gen/psd.luau { cases = { { name, data, width, height, composite (RGBA of psd-tools' merged image),
|
||||
# layers = { { name, left, top, width, height, crc (RGBA of psd-tools' layer.topil()) } },
|
||||
# flat (psd-tools' composite of the layers, RGBA) } } }
|
||||
# tests/gen/psd_ours.luau { checks = { { label, ok } } }: our encoder's PSD (tools/fixtures/_ours.luau, run with
|
||||
# luau) read by psd-tools, compared with the layers and the flattened image we wrote.
|
||||
import json, os, random, shutil, struct, subprocess, tempfile, zlib
|
||||
|
||||
INPUTS = ["src/Formats/layered/psd", "src/Formats/codecs/Blend.luau", "src/Formats/ops/LayerOps.luau", "tools/fixtures/_ours.luau"]
|
||||
|
||||
BLEND = ["norm", "diss", "dark", "mul ", "idiv", "lbrn", "dkCl", "lite", "scrn", "div ", "lddg", "lgCl", "over", "sLit",
|
||||
"hLit", "vLit", "lLit", "pLit", "hMix", "diff", "smud", "fsub", "fdiv", "hue ", "sat ", "colr", "lum "]
|
||||
|
||||
|
||||
def packbits(row):
|
||||
out, i, n = bytearray(), 0, len(row)
|
||||
while i < n:
|
||||
j = i
|
||||
while j + 1 < n and row[j + 1] == row[i] and j - i < 127:
|
||||
j += 1
|
||||
if j - i >= 2:
|
||||
out += bytes([257 - (j - i + 1), row[i]])
|
||||
i = j + 1
|
||||
else:
|
||||
k = i
|
||||
while k < n and k - i < 128 and not (k + 2 < n and row[k] == row[k + 1] == row[k + 2]):
|
||||
k += 1
|
||||
out += bytes([k - i - 1]) + row[i:k]
|
||||
i = k
|
||||
return bytes(out)
|
||||
|
||||
|
||||
def bytes_per(depth):
|
||||
return {8: 1, 16: 2, 32: 4}[depth]
|
||||
|
||||
|
||||
def channel_data(plane, w, h, depth, comp, psb=False):
|
||||
"""plane: bytes (rows of w samples, big endian) -> compression code + data"""
|
||||
rb = w * bytes_per(depth)
|
||||
if w == 0 or h == 0:
|
||||
return struct.pack(">H", 0)
|
||||
if comp == 0:
|
||||
return struct.pack(">H", 0) + plane
|
||||
if comp == 1:
|
||||
rows = [packbits(plane[y * rb:(y + 1) * rb]) for y in range(h)]
|
||||
fmt = ">I" if psb else ">H"
|
||||
return struct.pack(">H", 1) + b"".join(struct.pack(fmt, len(r)) for r in rows) + b"".join(rows)
|
||||
if comp == 2:
|
||||
return struct.pack(">H", 2) + zlib.compress(plane)
|
||||
# zip with prediction
|
||||
out = bytearray()
|
||||
for y in range(h):
|
||||
row = plane[y * rb:(y + 1) * rb]
|
||||
if depth == 8:
|
||||
out += bytes([row[0]] + [(row[x] - row[x - 1]) & 255 for x in range(1, w)])
|
||||
elif depth == 16:
|
||||
vals = struct.unpack(">%dH" % w, row)
|
||||
out += struct.pack(">%dH" % w, *([vals[0]] + [(vals[x] - vals[x - 1]) & 0xFFFF for x in range(1, w)]))
|
||||
else:
|
||||
planes = bytes(row[x * 4 + k] for k in range(4) for x in range(w))
|
||||
out += bytes([planes[0]] + [(planes[x] - planes[x - 1]) & 255 for x in range(1, len(planes))])
|
||||
return struct.pack(">H", 3) + zlib.compress(bytes(out))
|
||||
|
||||
|
||||
def pascal(name, pad=4):
|
||||
b = name.encode("latin-1", "replace")[:255]
|
||||
s = bytes([len(b)]) + b
|
||||
while len(s) % pad:
|
||||
s += b"\0"
|
||||
return s
|
||||
|
||||
|
||||
def block(key, data, psb=False):
|
||||
while len(data) % 4:
|
||||
data += b"\0"
|
||||
return b"8BIM" + key + (struct.pack(">Q", len(data)) if psb and key in (b"Lr16", b"Lr32", b"Layr") else struct.pack(">I", len(data))) + data
|
||||
|
||||
|
||||
def luni(name):
|
||||
u = name.encode("utf-16-be")
|
||||
return struct.pack(">I", len(u) // 2) + u
|
||||
|
||||
|
||||
class Layer:
|
||||
def __init__(self, name, left, top, w, h, chans, blend="norm", opacity=255, clip=0, hidden=False, section=None,
|
||||
section_blend=None, fill=None, mask=None, comp=1):
|
||||
self.__dict__.update(locals())
|
||||
|
||||
|
||||
def layer_info(layers, depth, psb, neg):
|
||||
recs, data = bytearray(), bytearray()
|
||||
for L in layers:
|
||||
recs += struct.pack(">iiii", L.top, L.left, L.top + L.h, L.left + L.w)
|
||||
chans = list(L.chans.items())
|
||||
if L.mask:
|
||||
chans.append((-2, L.mask["plane"]))
|
||||
recs += struct.pack(">H", len(chans))
|
||||
for cid, plane in chans:
|
||||
if cid == -2:
|
||||
m = L.mask
|
||||
cd = channel_data(plane, m["w"], m["h"], depth, 1, psb)
|
||||
else:
|
||||
cd = channel_data(plane, L.w, L.h, depth, L.comp, psb)
|
||||
recs += struct.pack(">h", cid) + (struct.pack(">Q", len(cd)) if psb else struct.pack(">I", len(cd)))
|
||||
data += cd
|
||||
flags = 8 | (2 if L.hidden else 0) | (16 if L.section else 0)
|
||||
recs += b"8BIM" + L.blend.encode() + bytes([L.opacity, L.clip, flags, 0])
|
||||
ex = bytearray()
|
||||
if L.mask:
|
||||
m = L.mask
|
||||
ex += struct.pack(">IiiiiBBH", 20, m["top"], m["left"], m["top"] + m["h"], m["left"] + m["w"], m["default"], m.get("flags", 0), 0)
|
||||
else:
|
||||
ex += struct.pack(">I", 0)
|
||||
ex += struct.pack(">I", 0)
|
||||
ex += pascal(L.name)
|
||||
ex += block(b"luni", luni(L.name))
|
||||
if L.section is not None:
|
||||
ex += block(b"lsct", struct.pack(">I", L.section) + (b"8BIM" + L.section_blend.encode() if L.section_blend else b""))
|
||||
if L.fill is not None:
|
||||
ex += block(b"iOpa", bytes([L.fill, 0, 0, 0]))
|
||||
recs += struct.pack(">I", len(ex)) + ex
|
||||
body = struct.pack(">h", -len(layers) if neg else len(layers)) + recs + data
|
||||
if len(body) % 2:
|
||||
body += b"\0"
|
||||
return body
|
||||
|
||||
|
||||
def psd(w, h, mode, depth, nch, merged_planes, layers=None, psb=False, comp=1, palette=None, lr16=False, neg=True, resources=b""):
|
||||
out = b"8BPS" + struct.pack(">H", 2 if psb else 1) + b"\0" * 6 + struct.pack(">HIIHH", nch, h, w, depth, mode)
|
||||
cm = palette or b""
|
||||
out += struct.pack(">I", len(cm)) + cm
|
||||
out += struct.pack(">I", len(resources)) + resources
|
||||
L = lambda n: struct.pack(">Q", n) if psb else struct.pack(">I", n)
|
||||
if layers:
|
||||
li = layer_info(layers, depth, psb, neg)
|
||||
if lr16:
|
||||
lm = L(0) + struct.pack(">I", 0) + block(b"Lr16" if depth == 16 else b"Lr32", li, psb)
|
||||
else:
|
||||
lm = L(len(li)) + li + struct.pack(">I", 0)
|
||||
out += L(len(lm)) + lm
|
||||
else:
|
||||
out += L(0)
|
||||
rb = (w + 7) // 8 if depth == 1 else w * bytes_per(depth)
|
||||
if comp == 0:
|
||||
out += struct.pack(">H", 0) + b"".join(merged_planes)
|
||||
elif comp == 1:
|
||||
rows = [packbits(p[y * rb:(y + 1) * rb]) for p in merged_planes for y in range(h)]
|
||||
fmt = ">I" if psb else ">H"
|
||||
out += struct.pack(">H", 1) + b"".join(struct.pack(fmt, len(r)) for r in rows) + b"".join(rows)
|
||||
else:
|
||||
out += struct.pack(">H", 2) + zlib.compress(b"".join(merged_planes))
|
||||
return out
|
||||
|
||||
|
||||
def plane8(w, h, f):
|
||||
return bytes(f(x, y) & 255 for y in range(h) for x in range(w))
|
||||
|
||||
|
||||
def plane16(w, h, f):
|
||||
return b"".join(struct.pack(">H", f(x, y) & 0xFFFF) for y in range(h) for x in range(w))
|
||||
|
||||
|
||||
def plane32(w, h, f):
|
||||
return b"".join(struct.pack(">f", f(x, y)) for y in range(h) for x in range(w))
|
||||
|
||||
|
||||
def rgba_layer(name, left, top, w, h, seed, **kw):
|
||||
rng = random.Random(seed)
|
||||
k = [rng.randrange(1, 9) for _ in range(8)]
|
||||
chans = {
|
||||
0: plane8(w, h, lambda x, y: x * k[0] * 7 + y * k[1]),
|
||||
1: plane8(w, h, lambda x, y: y * k[2] * 9 + x * k[3]),
|
||||
2: plane8(w, h, lambda x, y: (x ^ y) * k[4] * 5),
|
||||
-1: plane8(w, h, lambda x, y: 255 if (x + y) % 5 else 90 + (x * k[5] * 13) % 160),
|
||||
}
|
||||
return Layer(name, left, top, w, h, chans, **kw)
|
||||
|
||||
|
||||
def divider():
|
||||
return Layer("</Layer group>", 0, 0, 0, 0, {0: b"", 1: b"", 2: b"", -1: b""}, section=3)
|
||||
|
||||
|
||||
def group(name, blend="pass", opacity=255, hidden=False):
|
||||
return Layer(name, 0, 0, 0, 0, {0: b"", 1: b"", 2: b"", -1: b""}, blend=blend, opacity=opacity, section=1, section_blend=blend, hidden=hidden)
|
||||
|
||||
|
||||
def merged_rgb(w, h, alpha=True):
|
||||
ps = [plane8(w, h, lambda x, y, c=c: x * 5 + y * 3 + c * 70) for c in range(3)]
|
||||
if alpha:
|
||||
ps.append(plane8(w, h, lambda x, y: 255 - x))
|
||||
return ps
|
||||
|
||||
|
||||
def cases():
|
||||
W, H = 40, 30
|
||||
out = []
|
||||
# 1. a full RGB document: groups, pass-through, clipping, masks, fill, hidden, every compression
|
||||
mask = {"top": 5, "left": 8, "w": 20, "h": 12, "default": 0, "plane": plane8(20, 12, lambda x, y: x * 12)}
|
||||
layers = [
|
||||
rgba_layer("Background", 0, 0, W, H, 1, comp=0),
|
||||
rgba_layer("Multiply", 5, 4, 20, 15, 2, blend="mul ", opacity=200),
|
||||
divider(),
|
||||
rgba_layer("Screen", -3, 10, 25, 25, 3, blend="scrn", comp=2),
|
||||
rgba_layer("Overlay", 15, 2, 30, 12, 4, blend="over", comp=3),
|
||||
group("Isolated", blend="norm", opacity=180),
|
||||
divider(),
|
||||
rgba_layer("Diff é日", 10, 10, 20, 15, 5, blend="diff"),
|
||||
rgba_layer("Hidden", 0, 0, 10, 10, 6, hidden=True),
|
||||
group("Pass"),
|
||||
rgba_layer("Base", 20, 15, 15, 10, 7),
|
||||
rgba_layer("Clipped", 15, 12, 20, 14, 8, clip=1, blend="mul "),
|
||||
rgba_layer("Masked", 2, 2, 30, 20, 9, mask=mask),
|
||||
rgba_layer("Fill", 25, 0, 15, 30, 10, fill=128, blend="lite"),
|
||||
]
|
||||
out.append(("rgb-layers", psd(W, H, 3, 8, 4, merged_rgb(W, H), layers)))
|
||||
# 2. every blend mode on its own (two layers)
|
||||
for key in BLEND:
|
||||
ls = [rgba_layer("Bottom", 0, 0, 24, 16, 11, comp=0), rgba_layer("Top " + key, 4, 2, 18, 12, 12, blend=key, opacity=230)]
|
||||
out.append(("blend-" + key.strip(), psd(24, 16, 3, 8, 4, merged_rgb(24, 16), ls)))
|
||||
# 3. 16-bit RGB with the layers in Lr16, ZIP with prediction
|
||||
ch16 = lambda s: {0: plane16(12, 9, lambda x, y: x * 5000 + y * 31 + s), 1: plane16(12, 9, lambda x, y: y * 7000 + s), 2: plane16(12, 9, lambda x, y: (x * y * 997) + s), -1: plane16(12, 9, lambda x, y: 65535 - x * 3000)}
|
||||
l16 = [Layer("L16a", 0, 0, 12, 9, ch16(1), comp=3), Layer("L16b", 3, 2, 12, 9, ch16(77), comp=1, blend="mul ")]
|
||||
m16 = [plane16(16, 12, lambda x, y, c=c: x * 4000 + y * 100 + c * 9000) for c in range(3)] + [plane16(16, 12, lambda x, y: 65535)]
|
||||
out.append(("rgb16-lr16", psd(16, 12, 3, 16, 4, m16, l16, lr16=True)))
|
||||
# 4. 32-bit: merged only (floats) and a layer in Lr32
|
||||
m32 = [plane32(10, 7, lambda x, y, c=c: (x + c) / 12.0) for c in range(3)]
|
||||
l32 = [Layer("F", 1, 1, 6, 5, {0: plane32(6, 5, lambda x, y: x / 6.0), 1: plane32(6, 5, lambda x, y: y / 5.0), 2: plane32(6, 5, lambda x, y: 0.5), -1: plane32(6, 5, lambda x, y: 1.0)}, comp=3)]
|
||||
out.append(("rgb32", psd(10, 7, 3, 32, 3, m32, l32, lr16=True, comp=0)))
|
||||
# 5. greyscale with layers, raw merged
|
||||
gl = [Layer("G1", 0, 0, 20, 10, {0: plane8(20, 10, lambda x, y: x * 12), -1: plane8(20, 10, lambda x, y: 255)}),
|
||||
Layer("G2", 5, 3, 10, 6, {0: plane8(10, 6, lambda x, y: 200 - y * 20), -1: plane8(10, 6, lambda x, y: 128 + x * 10)}, blend="scrn")]
|
||||
out.append(("gray", psd(20, 10, 1, 8, 2, [plane8(20, 10, lambda x, y: x * 12 + y), plane8(20, 10, lambda x, y: 255)], gl, comp=0)))
|
||||
# 6. CMYK, merged + a layer
|
||||
cm = [plane8(14, 8, lambda x, y, c=c: 255 - (x * 15 + c * 40) % 256) for c in range(4)]
|
||||
cl = [Layer("C", 2, 1, 8, 5, {0: plane8(8, 5, lambda x, y: 200), 1: plane8(8, 5, lambda x, y: 40 * x), 2: plane8(8, 5, lambda x, y: 255), 3: plane8(8, 5, lambda x, y: 220 + y), -1: plane8(8, 5, lambda x, y: 255)})]
|
||||
out.append(("cmyk", psd(14, 8, 4, 8, 4, cm, cl)))
|
||||
# 7. indexed (merged only), 8. bitmap (merged only), 9. Lab
|
||||
pal = bytes(range(256)) + bytes((i * 3) % 256 for i in range(256)) + bytes(255 - i for i in range(256))
|
||||
out.append(("indexed", psd(17, 9, 2, 8, 1, [plane8(17, 9, lambda x, y: x * 15 + y)], palette=pal, comp=1)))
|
||||
out.append(("bitmap", psd(24, 7, 0, 1, 1, [bytes((x * 37 + y * 11) & 255 for y in range(7) for x in range(3))], comp=0)))
|
||||
out.append(("lab", psd(9, 5, 9, 8, 3, [plane8(9, 5, lambda x, y: x * 28), plane8(9, 5, lambda x, y: 100 + y * 10), plane8(9, 5, lambda x, y: 150)], comp=1)))
|
||||
# 10. PSB with layers (8-byte lengths, 4-byte RLE counts)
|
||||
out.append(("psb", psd(W, H, 3, 8, 4, merged_rgb(W, H), [rgba_layer("A", 0, 0, W, H, 21), rgba_layer("B", 3, 3, 10, 10, 22, blend="mul ")], psb=True)))
|
||||
# 11. no alpha in the merged image, positive layer count
|
||||
out.append(("rgb-noalpha", psd(W, H, 3, 8, 3, merged_rgb(W, H, False), [rgba_layer("Only", 0, 0, W, H, 31)], neg=False)))
|
||||
return out
|
||||
|
||||
|
||||
REF = r'''
|
||||
import json, os, sys, zlib
|
||||
from psd_tools import PSDImage
|
||||
d = %r
|
||||
res = []
|
||||
for name in sorted(os.listdir(d)):
|
||||
if not name.endswith(".psd"):
|
||||
continue
|
||||
psd = PSDImage.open(os.path.join(d, name))
|
||||
c = {"name": name[:-4], "width": psd.width, "height": psd.height}
|
||||
try:
|
||||
im = psd.topil()
|
||||
c["composite"] = im.convert("RGBA").tobytes().hex() if im is not None else ""
|
||||
except Exception as e:
|
||||
c["composite"] = ""
|
||||
layers = []
|
||||
for l in psd.descendants():
|
||||
if l.is_group():
|
||||
layers.append({"name": l.name, "group": True})
|
||||
continue
|
||||
e = {"name": l.name, "left": l.left, "top": l.top, "width": l.width, "height": l.height}
|
||||
try:
|
||||
im = l.topil()
|
||||
if im is not None:
|
||||
e["crc"] = zlib.crc32(im.convert("RGBA").tobytes())
|
||||
except Exception:
|
||||
pass
|
||||
layers.append(e)
|
||||
c["layers"] = layers
|
||||
try:
|
||||
f = psd.composite(force=True, color=0.0, alpha=0.0)
|
||||
c["flat"] = f.convert("RGBA").tobytes().hex()
|
||||
except Exception as e:
|
||||
c["flaterr"] = str(e)
|
||||
res.append(c)
|
||||
print(json.dumps(res))
|
||||
'''
|
||||
|
||||
|
||||
def pyrun(ctx, code):
|
||||
try:
|
||||
return ctx.python(["psd-tools", "numpy", "pillow"], code)
|
||||
except subprocess.CalledProcessError as e:
|
||||
raise RuntimeError("psd-tools failed:\n" + e.stderr.decode(errors="replace"))
|
||||
|
||||
|
||||
def reference(ctx, files):
|
||||
with tempfile.TemporaryDirectory() as d:
|
||||
for name, data in files:
|
||||
open(os.path.join(d, name + ".psd"), "wb").write(data)
|
||||
res = json.loads(pyrun(ctx, REF % d))
|
||||
by = {r["name"]: r for r in res}
|
||||
out = []
|
||||
for name, data in files:
|
||||
r = by[name]
|
||||
case = {"name": name, "data": data, "width": r["width"], "height": r["height"], "composite": bytes.fromhex(r["composite"])}
|
||||
if "flat" in r:
|
||||
case["flat"] = bytes.fromhex(r["flat"])
|
||||
case["layers"] = r["layers"]
|
||||
out.append(case)
|
||||
return out
|
||||
|
||||
|
||||
def imagemagick(ctx):
|
||||
# image 0 is the merged image, the rest are layers (ImageMagick 7.1 writes the blend key of some layers byte-reversed
|
||||
# ("mron"), which psd-tools refuses: these layers avoid it)
|
||||
with tempfile.TemporaryDirectory() as d:
|
||||
p = os.path.join(d, "im.psd")
|
||||
argv = ["magick", "-size", "32x24", "gradient:red-blue", "(", "-clone", "0", ")",
|
||||
"(", "-size", "8x8", "radial-gradient:yellow-none", "-repage", "+20+10", ")", p]
|
||||
try:
|
||||
subprocess.run(argv, check=True, capture_output=True)
|
||||
except (OSError, subprocess.CalledProcessError):
|
||||
ctx.nix("imagemagick", argv)
|
||||
return open(p, "rb").read()
|
||||
|
||||
|
||||
def generate(ctx):
|
||||
files = cases()
|
||||
files.append(("imagemagick", imagemagick(ctx)))
|
||||
ctx.emit("psd", {"cases": reference(ctx, files)})
|
||||
ctx.emit("psd_ours", {"checks": ours(ctx)})
|
||||
|
||||
|
||||
def run_ours(ctx, fmt):
|
||||
"""our encoder's output and facts, from tools/fixtures/_ours.luau"""
|
||||
script = os.path.join(ctx.root, "tools", "fixtures", "_ours.luau")
|
||||
argv = [shutil.which("luau") or "luau", script, "-a", fmt]
|
||||
if shutil.which("luau"):
|
||||
out = subprocess.run(argv, check=True, capture_output=True, cwd=ctx.root).stdout
|
||||
else:
|
||||
out = subprocess.run(["nix", "shell", "nixpkgs#luau", "-c", "luau", script, "-a", fmt], check=True, capture_output=True, cwd=ctx.root).stdout
|
||||
return json.loads(out)
|
||||
|
||||
|
||||
OURS = r'''
|
||||
import json, sys, zlib
|
||||
from psd_tools import PSDImage
|
||||
psd = PSDImage.open(%r)
|
||||
res = {"width": psd.width, "height": psd.height, "composite": zlib.crc32(psd.topil().convert("RGBA").tobytes()), "layers": []}
|
||||
for l in psd.descendants():
|
||||
if l.is_group():
|
||||
res["layers"].append({"group": True, "name": l.name, "blend": str(l.blend_mode), "opacity": l.opacity, "visible": l.visible})
|
||||
continue
|
||||
res["layers"].append({"name": l.name, "left": l.left, "top": l.top, "width": l.width, "height": l.height,
|
||||
"crc": zlib.crc32(l.topil().convert("RGBA").tobytes()), "blend": str(l.blend_mode), "opacity": l.opacity,
|
||||
"visible": l.visible, "clip": bool(l.clipping_layer), "mask": l.has_mask()})
|
||||
print(json.dumps(res))
|
||||
'''
|
||||
|
||||
PSD_BLEND = {"normal": "NORMAL", "multiply": "MULTIPLY", "screen": "SCREEN", "difference": "DIFFERENCE", "lighten": "LIGHTEN"}
|
||||
|
||||
|
||||
def ours(ctx):
|
||||
o = run_ours(ctx, "psd")
|
||||
with tempfile.TemporaryDirectory() as d:
|
||||
p = os.path.join(d, "ours.psd")
|
||||
open(p, "wb").write(bytes.fromhex(o["data"]))
|
||||
ref = json.loads(pyrun(ctx, OURS % p))
|
||||
checks = []
|
||||
def check(label, ok):
|
||||
checks.append({"label": label, "ok": bool(ok)})
|
||||
check("psd-tools: composite = our flatten", ref["composite"] == o["composite"])
|
||||
leaves = [l for l in ref["layers"] if not l.get("group")]
|
||||
check("psd-tools: leaf count", len(leaves) == len(o["layers"]))
|
||||
for want, got in zip(o["layers"], leaves):
|
||||
n = want["name"]
|
||||
check(n + ": name", got["name"] == n)
|
||||
check(n + ": pixels", got["crc"] == want["crc"])
|
||||
check(n + ": bounds", (got["left"], got["top"], got["width"], got["height"]) == (want["left"], want["top"], want["width"], want["height"]))
|
||||
check(n + ": blend", got["blend"].endswith(PSD_BLEND.get(want["blend"], "?")))
|
||||
check(n + ": opacity", got["opacity"] == want["opacity"])
|
||||
check(n + ": visible", got["visible"] == want["visible"])
|
||||
check(n + ": clip", got["clip"] == want["clip"])
|
||||
groups = [l for l in ref["layers"] if l.get("group")]
|
||||
check("psd-tools: two groups", [g["name"] for g in groups] == ["Isolated", "Pass"])
|
||||
check("psd-tools: pass-through group", len(groups) == 2 and groups[1]["blend"].endswith("PASS_THROUGH") and groups[0]["blend"].endswith("NORMAL"))
|
||||
check("psd-tools: masked layer has a mask", any(l.get("mask") for l in leaves if l["name"] == "Masked"))
|
||||
return checks
|
||||
@@ -0,0 +1,140 @@
|
||||
# Subtitle fixtures (tests/gen/subtitles.luau, for tests/subtitle/srt.luau, vtt.luau and ass.luau) with
|
||||
# ffmpeg as the reference: a random SRT script converted by ffmpeg to SRT / WebVTT / ASS, and hand-written WebVTT /
|
||||
# ASS / SSA files with their features, converted by ffmpeg to SRT. Every case carries the expected cues
|
||||
# ({ start_ms, stop_ms, plain text }) so the tests compare our decode with ffmpeg's view of the same file.
|
||||
import os, random, re, shutil, subprocess, tempfile
|
||||
|
||||
WORDS = ["alpha", "beta", "gamma", "delta", "omega", "café", "naïve", "日本", "fox", "dog", "42", "hello", "world"]
|
||||
|
||||
|
||||
def ffmpeg(ctx, src_bytes, src_ext, dst_ext):
|
||||
with tempfile.TemporaryDirectory() as d:
|
||||
src = os.path.join(d, "in." + src_ext)
|
||||
dst = os.path.join(d, "out." + dst_ext)
|
||||
open(src, "wb").write(src_bytes)
|
||||
argv = ["ffmpeg", "-hide_banner", "-loglevel", "error", "-y", "-i", src, dst]
|
||||
if shutil.which("ffmpeg"):
|
||||
subprocess.run(argv, check=True, capture_output=True)
|
||||
else:
|
||||
ctx.nix("ffmpeg", argv)
|
||||
return open(dst, "rb").read()
|
||||
|
||||
|
||||
def plain(s):
|
||||
return re.sub(r"{[^}]*}", "", re.sub(r"<[^>]*>", "", s)).replace("&", "&")
|
||||
|
||||
|
||||
def srt_time(ms):
|
||||
return "%02d:%02d:%02d,%03d" % (ms // 3600000, ms // 60000 % 60, ms // 1000 % 60, ms % 1000)
|
||||
|
||||
|
||||
def random_srt(rng, n):
|
||||
cues, t = [], 500
|
||||
for i in range(n):
|
||||
start = t + rng.randrange(0, 3000)
|
||||
stop = start + rng.randrange(300, 5000)
|
||||
t = stop
|
||||
lines = []
|
||||
for _ in range(rng.randrange(1, 3)):
|
||||
words = [rng.choice(WORDS) for _ in range(rng.randrange(1, 6))]
|
||||
if rng.random() < 0.3:
|
||||
k = rng.randrange(len(words))
|
||||
tag = rng.choice("ibu")
|
||||
words[k] = "<%s>%s</%s>" % (tag, words[k], tag)
|
||||
lines.append(" ".join(words))
|
||||
cues.append((start, stop, "\n".join(lines)))
|
||||
text = "".join("%d\n%s --> %s\n%s\n\n" % (i + 1, srt_time(a), srt_time(b), t) for i, (a, b, t) in enumerate(cues))
|
||||
return text.encode(), [{"start": a, "stop": b, "plain": plain(t)} for a, b, t in cues]
|
||||
|
||||
|
||||
VTT = """WEBVTT - a test file
|
||||
Kind: captions
|
||||
|
||||
STYLE
|
||||
::cue { color: yellow }
|
||||
|
||||
REGION
|
||||
id:r1 width:40%
|
||||
|
||||
NOTE this is a comment
|
||||
over two lines
|
||||
|
||||
intro
|
||||
00:01.000 --> 00:04.500 align:start position:10%
|
||||
<v Roger>Hello <i>there</i></v>
|
||||
|
||||
00:05.250 --> 00:07.000
|
||||
first line
|
||||
second line
|
||||
|
||||
01:00:02.000 --> 01:00:03.123 line:0
|
||||
<c.loud>an hour in</c> & more
|
||||
"""
|
||||
|
||||
ASS = """[Script Info]
|
||||
; Script generated by hand
|
||||
Title: test
|
||||
ScriptType: v4.00+
|
||||
PlayResX: 640
|
||||
PlayResY: 480
|
||||
|
||||
[V4+ Styles]
|
||||
Format: Name, Fontname, Fontsize, PrimaryColour, SecondaryColour, OutlineColour, BackColour, Bold, Italic, Underline, StrikeOut, ScaleX, ScaleY, Spacing, Angle, BorderStyle, Outline, Shadow, Alignment, MarginL, MarginR, MarginV, Encoding
|
||||
Style: Default,Arial,20,&H00FFFFFF,&H000000FF,&H00000000,&H00000000,0,0,0,0,100,100,0,0,1,2,2,2,10,10,10,1
|
||||
Style: Top,Verdana,24,&H0000FFFF,&H000000FF,&H00000000,&H80000000,-1,0,0,0,100,100,0,0,1,2,0,8,10,10,10,1
|
||||
|
||||
[Events]
|
||||
Format: Layer, Start, End, Style, Name, MarginL, MarginR, MarginV, Effect, Text
|
||||
Dialogue: 0,0:00:01.00,0:00:03.50,Default,Bob,0,0,0,,Hello, {\\i1}world{\\i0}!
|
||||
Comment: 0,0:00:02.00,0:00:04.00,Default,,0,0,0,,a comment line
|
||||
Dialogue: 1,0:00:04.20,0:00:06.00,Top,,0,0,0,,{\\an8\\b1}Bold top{\\b0}\\Nsecond line
|
||||
Dialogue: 0,0:01:02.03,0:01:05.99,Default,,0,0,0,,{\\pos(10,20)}commas, inside, the text
|
||||
|
||||
[Fonts]
|
||||
fontname: x.ttf
|
||||
ABCDEF
|
||||
"""
|
||||
|
||||
SSA = """[Script Info]
|
||||
Title: old
|
||||
ScriptType: v4.00
|
||||
|
||||
[V4 Styles]
|
||||
Format: Name, Fontname, Fontsize, PrimaryColour, SecondaryColour, TertiaryColour, BackColour, Bold, Italic, BorderStyle, Outline, Shadow, Alignment, MarginL, MarginR, MarginV, AlphaLevel, Encoding
|
||||
Style: Default,Tahoma,24,16777215,65535,65535,-2147483640,-1,0,1,3,0,2,30,30,30,0,0
|
||||
|
||||
[Events]
|
||||
Format: Marked, Start, End, Style, Name, MarginL, MarginR, MarginV, Effect, Text
|
||||
Dialogue: Marked=0,0:00:00.50,0:00:02.00,Default,,0000,0000,0000,,old style
|
||||
Dialogue: Marked=0,0:00:02.50,0:00:04.25,Default,,0000,0000,0000,,{\\i1}two{\\i0}\\Nlines
|
||||
"""
|
||||
|
||||
|
||||
def parse_srt(data):
|
||||
"""the cues of an SRT (ffmpeg's output) -> [{start, stop, plain}]"""
|
||||
out = []
|
||||
text = data.decode("utf-8-sig").replace("\r\n", "\n")
|
||||
for block in re.split(r"\n\s*\n", text.strip()):
|
||||
lines = block.split("\n")
|
||||
for k, l in enumerate(lines):
|
||||
m = re.match(r"(\d+):(\d+):(\d+)[,.](\d+) --> (\d+):(\d+):(\d+)[,.](\d+)", l)
|
||||
if m:
|
||||
g = [int(x) for x in m.groups()]
|
||||
out.append({"start": ((g[0] * 60 + g[1]) * 60 + g[2]) * 1000 + g[3], "stop": ((g[4] * 60 + g[5]) * 60 + g[6]) * 1000 + g[7], "plain": plain("\n".join(lines[k + 1:]))})
|
||||
break
|
||||
return out
|
||||
|
||||
|
||||
def generate(ctx):
|
||||
rng = random.Random(7)
|
||||
src, cues = random_srt(rng, 40)
|
||||
out = {"srt": src, "cues": cues}
|
||||
for ext in ("srt", "vtt", "ass"):
|
||||
out["ffmpeg_" + ext] = ffmpeg(ctx, src, "srt", ext)
|
||||
hand = []
|
||||
for name, ext, data in (("vtt", "vtt", VTT), ("ass", "ass", ASS), ("ssa", "ssa", SSA)):
|
||||
b = data.encode()
|
||||
ref = ffmpeg(ctx, b, ext, "srt")
|
||||
hand.append({"name": name, "data": b, "ffmpeg_srt": ref, "cues": parse_srt(ref)})
|
||||
out["hand"] = hand
|
||||
ctx.emit("subtitles", out)
|
||||
@@ -0,0 +1,202 @@
|
||||
# SVG fixtures (tools/fixtures.py): hand-written SVGs, one feature area each, rendered by resvg (nixpkgs#resvg, the
|
||||
# reference rasterizer), and the same documents decoded and written back by our encoder (tools/fixtures/_ours.luau)
|
||||
# then rendered by resvg too:
|
||||
# tests/gen/svg.luau { cases = { { name, svg, width, height, ref (resvg RGBA), ours (our SVG text), ours_ref
|
||||
# (resvg's RGBA of our SVG) } } }
|
||||
import json, os, shutil, subprocess, tempfile
|
||||
|
||||
INPUTS = ["src/Formats/vector/svg", "tools/fixtures/_ours.luau"]
|
||||
|
||||
def svg(w, h, body, extra=""):
|
||||
return '<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="%d" height="%d"%s>\n%s\n</svg>\n' % (w, h, extra, body)
|
||||
|
||||
CASES = {
|
||||
"shapes": svg(64, 64, """
|
||||
<rect x="4" y="4" width="20" height="14" fill="red"/>
|
||||
<rect x="30" y="4" width="28" height="16" rx="5" fill="#0a0" stroke="black" stroke-width="2"/>
|
||||
<circle cx="14" cy="34" r="9" fill="blue"/>
|
||||
<ellipse cx="44" cy="34" rx="14" ry="7" fill="orange" stroke="purple"/>
|
||||
<line x1="4" y1="50" x2="30" y2="60" stroke="black" stroke-width="3"/>
|
||||
<polyline points="34,60 40,48 46,58 52,46 60,60" fill="none" stroke="teal" stroke-width="2"/>
|
||||
<polygon points="4,62 10,52 16,62" fill="magenta"/>"""),
|
||||
"path-commands": svg(64, 64, """
|
||||
<path d="M4 4 L20 4 H28 V12 L4 12 Z" fill="#c00"/>
|
||||
<path d="m34 4 l10 0 h8 v8 l-18 0 z" fill="#0c0"/>
|
||||
<path d="M4 20 C10 14 18 30 24 20 S36 26 40 20" fill="none" stroke="blue" stroke-width="2"/>
|
||||
<path d="M4 34 Q14 24 24 34 T44 34 T60 30" fill="none" stroke="black" stroke-width="2"/>
|
||||
<path d="m4 44 c4-6 12 6 16 0 s8-6 12 0 q4 6 8 0 t8 0" fill="none" stroke="#a0a" stroke-width="2"/>
|
||||
<path d="M4,60L10,52,16,60zM20 60 52 60 36 50z" fill="gold" stroke="brown"/>"""),
|
||||
"arcs": svg(64, 64, """
|
||||
<path d="M8 16 A12 8 0 0 1 32 16" fill="none" stroke="red" stroke-width="2"/>
|
||||
<path d="M36 16 A12 8 0 1 0 60 16" fill="none" stroke="blue" stroke-width="2"/>
|
||||
<path d="M8 40 a10 10 0 1 1 20 0 a10 10 0 1 1 -20 0" fill="#9c9"/>
|
||||
<path d="M36 32 A14 6 30 0 1 58 48" fill="none" stroke="black" stroke-width="2"/>
|
||||
<path d="M36 58 A3 3 0 0 1 58 58" fill="none" stroke="purple" stroke-width="2"/>"""),
|
||||
"transforms": svg(64, 64, """
|
||||
<g transform="translate(32 32)">
|
||||
<rect x="-6" y="-6" width="12" height="12" fill="red" transform="rotate(30)"/>
|
||||
<g transform="scale(1.5, 0.75)"><circle cx="12" cy="-20" r="5" fill="blue"/></g>
|
||||
<rect x="-28" y="10" width="14" height="10" fill="green" transform="skewX(20)"/>
|
||||
<rect x="10" y="10" width="10" height="10" fill="orange" transform="matrix(1 0.3 -0.2 1 2 0) rotate(-15 15 15)"/>
|
||||
</g>"""),
|
||||
"stroke-styles": svg(64, 64, """
|
||||
<polyline points="6,20 18,6 30,20" fill="none" stroke="black" stroke-width="6" stroke-linejoin="miter"/>
|
||||
<polyline points="36,20 48,6 60,20" fill="none" stroke="black" stroke-width="6" stroke-linejoin="round"/>
|
||||
<polyline points="6,40 18,26 30,40" fill="none" stroke="black" stroke-width="6" stroke-linejoin="bevel"/>
|
||||
<polyline points="36,40 48,38 60,40" fill="none" stroke="black" stroke-width="5" stroke-miterlimit="1.5"/>
|
||||
<line x1="8" y1="48" x2="56" y2="48" stroke="blue" stroke-width="5" stroke-linecap="butt"/>
|
||||
<line x1="8" y1="55" x2="56" y2="55" stroke="blue" stroke-width="5" stroke-linecap="round"/>
|
||||
<line x1="8" y1="62" x2="56" y2="62" stroke="blue" stroke-width="3" stroke-linecap="square"/>"""),
|
||||
"dashes": svg(64, 64, """
|
||||
<line x1="4" y1="8" x2="60" y2="8" stroke="black" stroke-width="3" stroke-dasharray="6 3"/>
|
||||
<line x1="4" y1="18" x2="60" y2="18" stroke="red" stroke-width="3" stroke-dasharray="5,2,1" stroke-dashoffset="3"/>
|
||||
<circle cx="20" cy="42" r="14" fill="none" stroke="blue" stroke-width="3" stroke-dasharray="8 4"/>
|
||||
<rect x="40" y="30" width="20" height="24" fill="none" stroke="green" stroke-width="2" stroke-dasharray="4" stroke-linecap="round"/>"""),
|
||||
"fill-rule": svg(64, 32, """
|
||||
<path d="M16 2 L22 30 L2 12 L30 12 L10 30 Z" fill="navy" fill-rule="nonzero"/>
|
||||
<path d="M48 2 L54 30 L34 12 L62 12 L42 30 Z" fill="navy" fill-rule="evenodd"/>"""),
|
||||
"opacity": svg(64, 64, """
|
||||
<rect x="2" y="2" width="60" height="60" fill="#eee"/>
|
||||
<g opacity="0.5"><rect x="6" y="6" width="24" height="24" fill="red"/><rect x="16" y="16" width="24" height="24" fill="blue"/></g>
|
||||
<rect x="34" y="6" width="24" height="24" fill="green" fill-opacity="0.4" stroke="black" stroke-width="4" stroke-opacity="0.6"/>
|
||||
<circle cx="20" cy="48" r="12" fill="orange" stroke="purple" stroke-width="6" opacity="0.6"/>
|
||||
<circle cx="46" cy="48" r="12" fill="rgba(0,0,255,0.5)"/>"""),
|
||||
"linear-gradient": svg(64, 64, """
|
||||
<defs>
|
||||
<linearGradient id="a"><stop offset="0" stop-color="red"/><stop offset="0.5" stop-color="yellow"/><stop offset="1" stop-color="blue"/></linearGradient>
|
||||
<linearGradient id="b" x1="0" y1="0" x2="0.3" y2="0" spreadMethod="reflect"><stop offset="0" stop-color="#000"/><stop offset="1" stop-color="#fff"/></linearGradient>
|
||||
<linearGradient id="c" x1="0" y1="0" x2="0.25" y2="0.25" spreadMethod="repeat"><stop offset="0%" stop-color="green"/><stop offset="100%" stop-color="white" stop-opacity="0.2"/></linearGradient>
|
||||
<linearGradient id="d" gradientTransform="rotate(90 0.5 0.5)"><stop offset="0" stop-color="purple"/><stop offset="1" stop-color="orange"/></linearGradient>
|
||||
</defs>
|
||||
<rect x="2" y="2" width="60" height="12" fill="url(#a)"/>
|
||||
<rect x="2" y="16" width="60" height="12" fill="url(#b)"/>
|
||||
<rect x="2" y="30" width="28" height="30" fill="url(#c)"/>
|
||||
<circle cx="47" cy="45" r="14" fill="url(#d)" stroke="url(#a)" stroke-width="3"/>"""),
|
||||
"radial-gradient": svg(64, 64, """
|
||||
<defs>
|
||||
<radialGradient id="r1"><stop offset="0" stop-color="white"/><stop offset="1" stop-color="blue"/></radialGradient>
|
||||
<radialGradient id="r2" cx="0.5" cy="0.5" r="0.5" fx="0.25" fy="0.25"><stop offset="0" stop-color="yellow"/><stop offset="0.6" stop-color="red"/><stop offset="1" stop-color="black"/></radialGradient>
|
||||
<radialGradient id="r3" gradientUnits="userSpaceOnUse" cx="16" cy="48" r="8" spreadMethod="repeat"><stop offset="0" stop-color="#fff"/><stop offset="1" stop-color="#080"/></radialGradient>
|
||||
</defs>
|
||||
<rect x="2" y="2" width="28" height="28" fill="url(#r1)"/>
|
||||
<ellipse cx="47" cy="16" rx="15" ry="12" fill="url(#r2)"/>
|
||||
<rect x="2" y="34" width="28" height="28" fill="url(#r3)"/>
|
||||
<circle cx="47" cy="48" r="13" fill="url(#r2)" fill-opacity="0.7"/>"""),
|
||||
"gradient-href": svg(64, 32, """
|
||||
<defs>
|
||||
<linearGradient id="base"><stop offset="0" stop-color="#f00"/><stop offset="1" stop-color="#00f"/></linearGradient>
|
||||
<linearGradient id="tilted" xlink:href="#base" x2="0" y2="1"/>
|
||||
<radialGradient id="rad" href="#base"/>
|
||||
</defs>
|
||||
<rect x="2" y="2" width="28" height="28" fill="url(#tilted)"/>
|
||||
<rect x="34" y="2" width="28" height="28" fill="url(#rad)"/>"""),
|
||||
"css": svg(64, 64, """
|
||||
<style>
|
||||
rect { fill: red; stroke: black }
|
||||
.blue { fill: blue }
|
||||
#special { fill: green; stroke-width: 4 }
|
||||
circle.big, ellipse { fill: orange; }
|
||||
/* a comment */
|
||||
@media print { rect { fill: pink } }
|
||||
</style>
|
||||
<rect x="4" y="4" width="20" height="20"/>
|
||||
<rect x="30" y="4" width="20" height="20" class="blue"/>
|
||||
<rect x="4" y="30" width="20" height="20" class="blue" id="special"/>
|
||||
<rect x="30" y="30" width="20" height="20" class="blue" style="fill: purple"/>
|
||||
<circle class="big" cx="58" cy="58" r="5"/>
|
||||
<ellipse cx="10" cy="58" rx="6" ry="4" fill="black"/>"""),
|
||||
"use-symbol": svg(64, 64, """
|
||||
<defs>
|
||||
<g id="dot"><circle r="5" fill="red"/><circle r="2" fill="white"/></g>
|
||||
<symbol id="sym" viewBox="0 0 10 10"><rect width="10" height="10" fill="blue"/><path d="M0 0 L10 10" stroke="white"/></symbol>
|
||||
<rect id="bar" width="20" height="4"/>
|
||||
</defs>
|
||||
<use href="#dot" x="10" y="10"/>
|
||||
<use xlink:href="#dot" transform="translate(30 10) scale(1.5)"/>
|
||||
<use href="#sym" x="4" y="24" width="20" height="20"/>
|
||||
<use href="#sym" x="30" y="24" width="30" height="15"/>
|
||||
<use href="#bar" x="4" y="54" fill="green"/>
|
||||
<use href="#bar" x="30" y="54" style="fill: orange" opacity="0.5"/>"""),
|
||||
"viewbox-meet": svg(64, 40, """
|
||||
<rect width="100" height="100" fill="#ccc"/><circle cx="50" cy="50" r="40" fill="red"/>""", ' viewBox="0 0 100 100" preserveAspectRatio="xMinYMax meet"'),
|
||||
"viewbox-slice": svg(64, 40, """
|
||||
<rect width="100" height="100" fill="#ccc"/><circle cx="50" cy="50" r="40" fill="blue"/>""", ' viewBox="0 0 100 100" preserveAspectRatio="xMidYMid slice"'),
|
||||
"viewbox-none": svg(64, 40, """
|
||||
<rect width="100" height="100" fill="#ccc"/><circle cx="50" cy="50" r="40" fill="green"/>""", ' viewBox="0 0 100 100" preserveAspectRatio="none"'),
|
||||
"nested-svg": svg(64, 64, """
|
||||
<rect width="64" height="64" fill="#eef"/>
|
||||
<svg x="8" y="8" width="48" height="24" viewBox="0 0 20 10"><circle cx="5" cy="5" r="5" fill="red"/><circle cx="15" cy="5" r="5" fill="blue"/></svg>
|
||||
<svg x="8" y="36" width="20" height="20"><rect x="5" y="5" width="50%" height="50%" fill="green"/><circle cx="20" cy="10" r="8" fill="red"/></svg>"""),
|
||||
"clip-path": svg(64, 64, """
|
||||
<defs>
|
||||
<clipPath id="c1"><circle cx="16" cy="16" r="12"/></clipPath>
|
||||
<clipPath id="c2" clipPathUnits="objectBoundingBox"><rect x="0.25" y="0" width="0.5" height="1"/></clipPath>
|
||||
<clipPath id="c3"><path d="M34 34 h26 v26 h-26z M40 40 h14 v14 h-14z" clip-rule="evenodd"/></clipPath>
|
||||
</defs>
|
||||
<rect x="2" y="2" width="30" height="30" fill="red" clip-path="url(#c1)"/>
|
||||
<g clip-path="url(#c2)"><rect x="34" y="2" width="28" height="28" fill="blue"/><circle cx="48" cy="16" r="10" fill="yellow"/></g>
|
||||
<rect x="2" y="34" width="28" height="28" fill="green" clip-path="url(#c2)"/>
|
||||
<rect x="34" y="34" width="28" height="28" fill="purple" clip-path="url(#c3)"/>"""),
|
||||
"units": svg(64, 64, """
|
||||
<rect x="2mm" y="2mm" width="10mm" height="5mm" fill="red"/>
|
||||
<rect x="40pt" y="4" width="12pt" height="12pt" fill="blue"/>
|
||||
<rect x="10%" y="50%" width="25%" height="10%" fill="green"/>
|
||||
<circle cx="48" cy="48" r="1em" fill="orange" style="font-size: 8px"/>
|
||||
<rect x="4" y="52" width="1in" height="0.1in" fill="black" transform="scale(0.5)"/>"""),
|
||||
"colors": svg(64, 32, """
|
||||
<g color="teal">
|
||||
<rect x="0" y="0" width="8" height="16" fill="cornflowerblue"/>
|
||||
<rect x="8" y="0" width="8" height="16" fill="#f80"/>
|
||||
<rect x="16" y="0" width="8" height="16" fill="#ff008080"/>
|
||||
<rect x="24" y="0" width="8" height="16" fill="rgb(10%, 50%, 90%)"/>
|
||||
<rect x="32" y="0" width="8" height="16" fill="rgba(200, 0, 100, 0.5)"/>
|
||||
<rect x="40" y="0" width="8" height="16" fill="hsl(120, 100%, 25%)"/>
|
||||
<rect x="48" y="0" width="8" height="16" fill="currentColor"/>
|
||||
<rect x="56" y="0" width="8" height="16" fill="transparent" stroke="currentColor"/>
|
||||
<rect x="0" y="16" width="64" height="16" fill="none" stroke="DarkOrchid" stroke-width="4"/>
|
||||
</g>"""),
|
||||
"inheritance": svg(64, 64, """
|
||||
<g fill="red" stroke="blue" stroke-width="3">
|
||||
<rect x="4" y="4" width="24" height="24"/>
|
||||
<g fill="green"><rect x="36" y="4" width="24" height="24" stroke="inherit"/></g>
|
||||
<g style="stroke: none"><circle cx="16" cy="46" r="12"/></g>
|
||||
<g display="none"><rect x="36" y="36" width="24" height="24"/></g>
|
||||
<rect x="36" y="36" width="10" height="10" visibility="hidden"/>
|
||||
<g visibility="hidden"><rect x="48" y="48" width="12" height="12" visibility="visible"/></g>
|
||||
</g>"""),
|
||||
}
|
||||
|
||||
|
||||
def resvg(ctx, data, w, h):
|
||||
with tempfile.TemporaryDirectory() as d:
|
||||
src, png = os.path.join(d, "in.svg"), os.path.join(d, "out.png")
|
||||
open(src, "wb").write(data)
|
||||
argv = ["resvg", "-w", str(w), "-h", str(h), src, png]
|
||||
if shutil.which("resvg"):
|
||||
subprocess.run(argv, check=True, capture_output=True)
|
||||
else:
|
||||
subprocess.run(["nix", "shell", "nixpkgs#resvg", "-c"] + argv, check=True, capture_output=True)
|
||||
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 ours(ctx, text):
|
||||
script = os.path.join(ctx.root, "tools", "fixtures", "_ours.luau")
|
||||
luau = shutil.which("luau")
|
||||
argv = [luau, script, "-a", "svg", text] if luau else ["nix", "shell", "nixpkgs#luau", "-c", "luau", script, "-a", "svg", text]
|
||||
return json.loads(subprocess.run(argv, check=True, capture_output=True, cwd=ctx.root).stdout)["svg"]
|
||||
|
||||
|
||||
def generate(ctx):
|
||||
import re
|
||||
cases = []
|
||||
for name, text in CASES.items():
|
||||
w, h = (int(x) for x in re.search(r'width="(\d+)" height="(\d+)"', text).groups())
|
||||
data = text.encode()
|
||||
mine = ours(ctx, text)
|
||||
cases.append({"name": name, "svg": data, "width": w, "height": h, "ref": resvg(ctx, data, w, h), "ours": mine,
|
||||
"ours_ref": resvg(ctx, mine.encode(), w, h)})
|
||||
ctx.emit("svg", {"cases": cases})
|
||||
@@ -0,0 +1,279 @@
|
||||
# Tiled fixtures (tools/fixtures.py), with Tiled itself (nixpkgs#tiled, run headless) as the reference:
|
||||
# tests/gen/tiled.luau { cases = { { name, tmx (hand-written), tmj (Tiled's export), tiled_tmx (Tiled's re-save) } },
|
||||
# tsx, tsj (an external tileset and Tiled's JSON export of it) }
|
||||
# tests/gen/tiled_ours.luau { checks = { { label, ok } } }: a map built and written by our encoder (TMX with
|
||||
# base64 + zlib data, and TMJ; tools/fixtures/_ours.luau) re-exported by Tiled as JSON and
|
||||
# compared with our own TMJ
|
||||
import base64, gzip, json, os, shutil, struct, subprocess, tempfile, zlib
|
||||
|
||||
INPUTS = ["src/Formats/vector/tiled", "tools/fixtures/_ours.luau"]
|
||||
|
||||
TSX = """<?xml version="1.0" encoding="UTF-8"?>
|
||||
<tileset version="1.10" tiledversion="1.10.2" name="ext" tilewidth="16" tileheight="16" spacing="0" margin="0" tilecount="8" columns="4">
|
||||
<tileoffset x="2" y="-3"/>
|
||||
<properties>
|
||||
<property name="kind" value="terrain"/>
|
||||
</properties>
|
||||
<image source="tiles.png" width="64" height="32"/>
|
||||
<tile id="1" type="Water" probability="0.5">
|
||||
<properties>
|
||||
<property name="speed" type="float" value="0.25"/>
|
||||
</properties>
|
||||
<animation>
|
||||
<frame tileid="1" duration="100"/>
|
||||
<frame tileid="2" duration="150"/>
|
||||
</animation>
|
||||
</tile>
|
||||
<tile id="5">
|
||||
<objectgroup draworder="index" id="2">
|
||||
<object id="1" x="1" y="2" width="10" height="12"/>
|
||||
<object id="2" x="3" y="3">
|
||||
<ellipse/>
|
||||
</object>
|
||||
</objectgroup>
|
||||
</tile>
|
||||
</tileset>
|
||||
"""
|
||||
|
||||
|
||||
def layer_bytes(gids):
|
||||
return b"".join(struct.pack("<I", g) for g in gids)
|
||||
|
||||
|
||||
def ortho():
|
||||
W, H = 6, 4
|
||||
g1 = [(x + y * W) % 9 for y in range(H) for x in range(W)]
|
||||
g1[3] |= 0x80000000
|
||||
g1[7] |= 0x40000000
|
||||
g1[11] |= 0x20000000
|
||||
g2 = [(x * y) % 5 for y in range(H) for x in range(W)]
|
||||
g3 = [9 + (x + y) % 8 if (x + y) % 3 else 0 for y in range(H) for x in range(W)]
|
||||
g4 = [1 + (x % 2) for y in range(H) for x in range(W)]
|
||||
csv = ",\n".join(",".join(str(g) for g in g1[y * W:(y + 1) * W]) for y in range(H))
|
||||
z = base64.b64encode(zlib.compress(layer_bytes(g2))).decode()
|
||||
gz = base64.b64encode(gzip.compress(layer_bytes(g3), mtime=0)).decode()
|
||||
raw = base64.b64encode(layer_bytes(g4)).decode()
|
||||
return f"""<?xml version="1.0" encoding="UTF-8"?>
|
||||
<map version="1.10" tiledversion="1.10.2" class="Level" orientation="orthogonal" renderorder="left-up" width="{W}" height="{H}" tilewidth="16" tileheight="16" backgroundcolor="#ff102030" infinite="0" nextlayerid="9" nextobjectid="10">
|
||||
<properties>
|
||||
<property name="title" value="Ünïcode & more"/>
|
||||
<property name="count" type="int" value="42"/>
|
||||
<property name="ratio" type="float" value="1.5"/>
|
||||
<property name="on" type="bool" value="true"/>
|
||||
<property name="tint" type="color" value="#80ff0000"/>
|
||||
<property name="file" type="file" value="other.tmx"/>
|
||||
<property name="target" type="object" value="3"/>
|
||||
<property name="notes">line one
|
||||
line two</property>
|
||||
</properties>
|
||||
<tileset firstgid="1" name="inner" tilewidth="16" tileheight="16" spacing="0" margin="0" tilecount="8" columns="4">
|
||||
<image source="tiles.png" width="64" height="32"/>
|
||||
<tile id="0">
|
||||
<properties>
|
||||
<property name="solid" type="bool" value="true"/>
|
||||
</properties>
|
||||
</tile>
|
||||
<tile id="3" type="Door"/>
|
||||
</tileset>
|
||||
<tileset firstgid="9" source="ext.tsx"/>
|
||||
<layer id="1" name="csv" width="{W}" height="{H}" opacity="0.75" offsetx="3" offsety="-2" tintcolor="#ff00ff">
|
||||
<properties>
|
||||
<property name="layerprop" value="x"/>
|
||||
</properties>
|
||||
<data encoding="csv">
|
||||
{csv}
|
||||
</data>
|
||||
</layer>
|
||||
<layer id="2" name="zlib" width="{W}" height="{H}" visible="0" parallaxx="0.5">
|
||||
<data encoding="base64" compression="zlib">
|
||||
{z}
|
||||
</data>
|
||||
</layer>
|
||||
<layer id="3" name="gzip" width="{W}" height="{H}" locked="1">
|
||||
<data encoding="base64" compression="gzip">
|
||||
{gz}
|
||||
</data>
|
||||
</layer>
|
||||
<layer id="4" name="raw" class="Deco" width="{W}" height="{H}">
|
||||
<data encoding="base64">
|
||||
{raw}
|
||||
</data>
|
||||
</layer>
|
||||
<group id="5" name="group" opacity="0.5" offsetx="1">
|
||||
<imagelayer id="6" name="sky" repeatx="1">
|
||||
<image source="sky.png" width="40" height="20"/>
|
||||
</imagelayer>
|
||||
<objectgroup id="7" name="things" color="#a0a0a4" draworder="index">
|
||||
<object id="1" name="box" type="Crate" x="10" y="12.5" width="16" height="8" rotation="45">
|
||||
<properties>
|
||||
<property name="weight" type="float" value="2.25"/>
|
||||
</properties>
|
||||
</object>
|
||||
<object id="2" name="ring" x="40" y="5" width="10" height="10">
|
||||
<ellipse/>
|
||||
</object>
|
||||
<object id="3" name="spot" x="7" y="9">
|
||||
<point/>
|
||||
</object>
|
||||
<object id="4" name="poly" x="20" y="20">
|
||||
<polygon points="0,0 16,0 8,-12.5"/>
|
||||
</object>
|
||||
<object id="5" name="line" x="30" y="30" visible="0">
|
||||
<polyline points="0,0 5,5 10,0 15,5"/>
|
||||
</object>
|
||||
<object id="6" name="label" x="2" y="40" width="80" height="20">
|
||||
<text fontfamily="Serif" pixelsize="12" wrap="1" color="#ff0000" bold="1" halign="center" valign="bottom">Hello <Tiled></text>
|
||||
</object>
|
||||
<object id="7" name="tile" gid="2147483651" x="50" y="50" width="16" height="16"/>
|
||||
</objectgroup>
|
||||
</group>
|
||||
</map>
|
||||
"""
|
||||
|
||||
|
||||
def iso():
|
||||
W, H = 3, 3
|
||||
tiles = "\n".join(' <tile gid="%d"/>' % ((x + y) % 4) for y in range(H) for x in range(W))
|
||||
return f"""<?xml version="1.0" encoding="UTF-8"?>
|
||||
<map version="1.10" tiledversion="1.10.2" orientation="hexagonal" renderorder="right-down" width="{W}" height="{H}" tilewidth="32" tileheight="28" infinite="0" hexsidelength="14" staggeraxis="x" staggerindex="even" nextlayerid="2" nextobjectid="1">
|
||||
<tileset firstgid="1" name="inner" tilewidth="16" tileheight="16" tilecount="8" columns="4">
|
||||
<image source="tiles.png" width="64" height="32"/>
|
||||
</tileset>
|
||||
<layer id="1" name="xmltiles" width="{W}" height="{H}">
|
||||
<data>
|
||||
{tiles}
|
||||
</data>
|
||||
</layer>
|
||||
</map>
|
||||
"""
|
||||
|
||||
|
||||
def infinite():
|
||||
def chunk(cx, cy):
|
||||
g = [(cx // 16 + cy // 16 + x + y) % 5 for y in range(16) for x in range(16)]
|
||||
rows = ",\n".join(",".join(str(v) for v in g[y * 16:(y + 1) * 16]) for y in range(16))
|
||||
return f' <chunk x="{cx}" y="{cy}" width="16" height="16">\n{rows}\n</chunk>'
|
||||
# Tiled's canonical layout: chunks by row, the layer's size = the chunks' bounds
|
||||
chunks = "\n".join(chunk(cx, cy) for cx, cy in ((16, -16), (-16, 0), (0, 0)))
|
||||
return f"""<?xml version="1.0" encoding="UTF-8"?>
|
||||
<map version="1.10" tiledversion="1.10.2" orientation="orthogonal" renderorder="right-down" width="30" height="20" tilewidth="16" tileheight="16" infinite="1" nextlayerid="2" nextobjectid="1">
|
||||
<tileset firstgid="1" name="inner" tilewidth="16" tileheight="16" tilecount="8" columns="4">
|
||||
<image source="tiles.png" width="64" height="32"/>
|
||||
</tileset>
|
||||
<layer id="1" name="chunks" width="48" height="32">
|
||||
<data encoding="csv">
|
||||
{chunks}
|
||||
</data>
|
||||
</layer>
|
||||
</map>
|
||||
"""
|
||||
|
||||
|
||||
def tiled(ctx, argv, cwd):
|
||||
env = dict(os.environ, QT_QPA_PLATFORM="offscreen")
|
||||
if shutil.which("tiled"):
|
||||
subprocess.run(["tiled"] + argv, check=True, capture_output=True, cwd=cwd, env=env)
|
||||
else:
|
||||
subprocess.run(["nix", "shell", "nixpkgs#tiled", "-c", "tiled"] + argv, check=True, capture_output=True, cwd=cwd, env=env)
|
||||
|
||||
|
||||
def magick(ctx, argv):
|
||||
try:
|
||||
subprocess.run(argv, check=True, capture_output=True)
|
||||
except (OSError, subprocess.CalledProcessError):
|
||||
ctx.nix("imagemagick", argv)
|
||||
|
||||
|
||||
def workdir(ctx, d):
|
||||
magick(ctx, ["magick", "-size", "64x32", "gradient:red-blue", os.path.join(d, "tiles.png")])
|
||||
magick(ctx, ["magick", "-size", "40x20", "xc:skyblue", os.path.join(d, "sky.png")])
|
||||
open(os.path.join(d, "ext.tsx"), "w").write(TSX)
|
||||
|
||||
|
||||
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 gids(layer):
|
||||
"""a JSON tile layer's gids (arrays, or base64 with compression) -> list"""
|
||||
d = layer.get("data")
|
||||
if isinstance(d, str):
|
||||
raw = base64.b64decode(d)
|
||||
c = layer.get("compression", "")
|
||||
raw = zlib.decompress(raw) if c == "zlib" else gzip.decompress(raw) if c == "gzip" else raw
|
||||
return list(struct.unpack("<%dI" % (len(raw) // 4), raw))
|
||||
return d
|
||||
|
||||
|
||||
IGNORE = {"version", "tiledversion", "compressionlevel", "encoding", "compression", "opacity_obj"}
|
||||
|
||||
|
||||
DEFAULTS = {"offsetx": 0, "offsety": 0, "parallaxx": 1, "parallaxy": 1, "locked": False}
|
||||
|
||||
|
||||
def norm(v, obj=False):
|
||||
"""a JSON map without the fields that only say which Tiled wrote it, or that hold defaults"""
|
||||
if isinstance(v, dict):
|
||||
out = {}
|
||||
if v.get("type") == "tilelayer" and "data" in v:
|
||||
v = dict(v, data=gids(v))
|
||||
for k, x in v.items():
|
||||
if k in IGNORE or (k in DEFAULTS and x == DEFAULTS[k]) or (obj and k == "opacity"):
|
||||
continue
|
||||
out[k] = [norm(o, True) for o in x] if k == "objects" else norm(x)
|
||||
return out
|
||||
if isinstance(v, list):
|
||||
return [norm(x) for x in v]
|
||||
if isinstance(v, float) and v.is_integer():
|
||||
return int(v)
|
||||
return v
|
||||
|
||||
|
||||
def diff(a, b, path="", out=None):
|
||||
out = [] if out is None else out
|
||||
if isinstance(a, dict) and isinstance(b, dict):
|
||||
for k in sorted(set(a) | set(b)):
|
||||
if k not in a or k not in b:
|
||||
out.append("%s.%s: %s vs %s" % (path, k, a.get(k, "<missing>"), b.get(k, "<missing>")))
|
||||
else:
|
||||
diff(a[k], b[k], path + "." + k, out)
|
||||
elif isinstance(a, list) and isinstance(b, list):
|
||||
if len(a) != len(b):
|
||||
out.append("%s: length %d vs %d" % (path, len(a), len(b)))
|
||||
for i, (x, y) in enumerate(zip(a, b)):
|
||||
diff(x, y, "%s[%d]" % (path, i), out)
|
||||
elif a != b:
|
||||
out.append("%s: %r vs %r" % (path, a, b))
|
||||
return out
|
||||
|
||||
|
||||
def generate(ctx):
|
||||
cases = []
|
||||
with tempfile.TemporaryDirectory() as d:
|
||||
workdir(ctx, d)
|
||||
for name, text in (("ortho", ortho()), ("hex", iso()), ("infinite", infinite())):
|
||||
open(os.path.join(d, name + ".tmx"), "w").write(text)
|
||||
tiled(ctx, ["--export-map", name + ".tmx", name + "-out.tmj"], d)
|
||||
tiled(ctx, ["--export-map", name + ".tmx", name + "-out.tmx"], d)
|
||||
cases.append({"name": name, "tmx": text, "tmj": open(os.path.join(d, name + "-out.tmj"), "rb").read(),
|
||||
"tiled_tmx": open(os.path.join(d, name + "-out.tmx"), "rb").read()})
|
||||
tiled(ctx, ["--export-tileset", "ext.tsx", "ext.tsj"], d)
|
||||
tsj = open(os.path.join(d, "ext.tsj"), "rb").read()
|
||||
ctx.emit("tiled", {"cases": cases, "tsx": TSX, "tsj": tsj})
|
||||
|
||||
# our encoder's files, read by Tiled
|
||||
o = run_ours(ctx, "tiled")
|
||||
open(os.path.join(d, "ours.tmx"), "wb").write(bytes.fromhex(o["tmx"]))
|
||||
open(os.path.join(d, "ours.tmj"), "wb").write(bytes.fromhex(o["tmj"]))
|
||||
tiled(ctx, ["--export-map", "ours.tmx", "ours-from-tmx.tmj"], d)
|
||||
tiled(ctx, ["--export-map", "ours.tmj", "ours-from-tmj.tmj"], d)
|
||||
mine = norm(json.loads(bytes.fromhex(o["tmj"])))
|
||||
checks = []
|
||||
for label, f in (("Tiled on our TMX", "ours-from-tmx.tmj"), ("Tiled on our TMJ", "ours-from-tmj.tmj")):
|
||||
theirs = norm(json.load(open(os.path.join(d, f))))
|
||||
dd = diff(mine, theirs)
|
||||
checks.append({"label": label + (": " + "; ".join(dd[:5]) if dd else ""), "ok": not dd})
|
||||
ctx.emit("tiled_ours", {"checks": checks})
|
||||
Reference in new issue
Block a user