diff --git a/docs/FORMATS.md b/docs/FORMATS.md index 5f33ef3..fcf9733 100644 --- a/docs/FORMATS.md +++ b/docs/FORMATS.md @@ -6,6 +6,7 @@ is tested under both runtimes (luau `--codegen -O2` and LuaJIT through the build | Category | Format | Extensions | Read | Write | Capabilities | Test | |---|---|---|---|---|---|---| | image | png | .png .apng | yes | yes | animation: false, alpha: true, depths: 1, 2, 4, 8, 16 | `tests/image/png.luau` | +| layered | aseprite | .aseprite .ase | yes | yes | layers: true, groups: true, animation: true, depths: 8, 16, 32 | `tests/layered/aseprite.luau` | | layered | psd | .psd .psb | yes | yes | layers: true, groups: true, depths: 1, 8, 16, 32 | `tests/layered/psd.luau` | | subtitle | ass | .ass .ssa | yes | yes | styles: true | `tests/subtitle/ass.luau` | | subtitle | srt | .srt | yes | yes | styles: false | `tests/subtitle/srt.luau` | diff --git a/src/Formats/Registry.luau b/src/Formats/Registry.luau index cef9c24..c432968 100644 --- a/src/Formats/Registry.luau +++ b/src/Formats/Registry.luau @@ -26,6 +26,18 @@ local list: { Entry } = { return require("@formats/image/png") end, }, + { + name = "aseprite", + category = "layered", + path = "layered/aseprite", + extensions = { "aseprite", "ase" }, + mime = { "image/x-aseprite" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/Deflate" }, + caps = { decode = true, encode = true, layers = true, groups = true, animation = true, depths = { 8, 16, 32 } }, + load = function() + return require("@formats/layered/aseprite") + end, + }, { name = "psd", category = "layered", diff --git a/src/Formats/layered/aseprite/init.luau b/src/Formats/layered/aseprite/init.luau new file mode 100644 index 0000000..6799137 --- /dev/null +++ b/src/Formats/layered/aseprite/init.luau @@ -0,0 +1,754 @@ +--!strict +-- layered/aseprite: Aseprite .ase / .aseprite sprites (aseprite docs/ase-file-specs.md, v1.3). Supports: RGBA, +-- grayscale and indexed sprites (to rgba8; the transparent index is clear except on background layers); every +-- frame (duration -> delay); layers (normal and group, child levels -> a tree; visibility, blend mode, opacity, +-- flags, UUIDs skipped; a group of normal blend at full opacity is "passThrough"); cels (raw, zlib-compressed, linked: a linked cel shares the Image of the frame it points to +-- and records `link`), cel opacity (-> the leaf's fillOpacity), z-index; the palette (new 0x2019 chunk and the old +-- 0x0004 / 0x0011 ones; entry names), tags (meta.tags, frames 1-based), user data text / colour on layers, cels and +-- tags, the pixel ratio and grid. A Layered value: layers = frame 1's tree, frames[i] = { layers = frame i's tree, +-- delay }. +-- Encode: RGBA (or grayscale / indexed when opts.depth or meta.colorDepth asks and the pixels fit), one layer chunk +-- per node of frame 1's tree, zlib cels, linked cels where a frame reuses an earlier frame's Image at the same place, +-- palette, tags. +-- Not supported: tilemap layers / tilesets (skipped: meta.skipped counts them), slices, external files, colour +-- profiles (sRGB assumed). + +-- ------------------------------------------------------------------------------------------------ requires +local Err = require("@formats/core/Err") +local Bytes = require("@formats/core/Bytes") +local Types = require("@formats/Types") +local Deflate = require("@formats/codecs/Deflate") + +-- ------------------------------------------------------------------------------------------------ contract +local Aseprite = { + name = "aseprite", + category = "layered", + extensions = { "aseprite", "ase" }, + mime = { "image/x-aseprite" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/Deflate" }, + caps = { decode = true, encode = true, layers = true, groups = true, animation = true, depths = { 8, 16, 32 } }, +} + +export type DecodeOptions = { + maxPixels: number?, -- refuse sprites / cels larger than this (default 2^26) + maxFrames: number?, -- default 65535 +} +export type EncodeOptions = { + depth: number?, -- 32 (RGBA), 16 (grayscale) or 8 (indexed, with layered.meta.palette); default meta.colorDepth if + -- the pixels fit it, else 32 + level: number?, -- zlib level for the cels (default 6) +} + +-- ------------------------------------------------------------------------------------------------ constants +local BLENDS = { [0] = "normal", "multiply", "screen", "overlay", "darken", "lighten", "colorDodge", "colorBurn", "hardLight", "softLight", "difference", "exclusion", "hue", "saturation", "color", "luminosity", "linearDodge", "subtract", "divide" } +local BLEND_IDS: { [string]: number } = {} +for k, v in BLENDS do + BLEND_IDS[v] = k +end +BLEND_IDS.add = 16 +BLEND_IDS.passThrough = 0 +local DIRECTIONS = { [0] = "forward", "reverse", "pingpong", "pingpongReverse" } +local DIRECTION_IDS = { forward = 0, reverse = 1, pingpong = 2, pingpongReverse = 3 } + +-- ------------------------------------------------------------------------------------------------ sniff +function Aseprite.sniff(r: Bytes.Reader): number + if r:peekU8(4) == 0xE0 and r:peekU8(5) == 0xA5 then + local d = r:peekU8(12) + if (d == 32 or d == 16 or d == 8) and r:peekU8(13) == 0 then + return 1 + end + return 0.5 + end + return 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +local function str(r: Bytes.Reader): string + return r:string(r:u16le()) +end + +-- cel pixels (depth bytes per pixel) -> rgba8 +local function toRGBA(src: buffer, so: number, n: number, depth: number, palette: buffer, transparent: number, background: boolean): buffer + local out = buffer.create(n * 4) + if depth == 32 then + buffer.copy(out, 0, src, so, n * 4) + elseif depth == 16 then + for i = 0, n - 1 do + local v, a = buffer.readu8(src, so + i * 2), buffer.readu8(src, so + i * 2 + 1) + buffer.writeu32(out, i * 4, v + v * 256 + v * 65536 + a * 16777216) + end + else + for i = 0, n - 1 do + local k = buffer.readu8(src, so + i) + local c = buffer.readu32(palette, k * 4) + if k == transparent and not background then + c = 0 + end + buffer.writeu32(out, i * 4, c) + end + end + return out +end + +type LayerInfo = { name: string, flags: number, type: number, level: number, blend: number, opacity: number, userData: any? } + +function Aseprite.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Layered?, Err.Err?) + local maxPixels = opts and opts.maxPixels or 2 ^ 26 + local maxFrames = opts and opts.maxFrames or 65535 + if r:size() < 128 then + return nil, Err.new(Err.TRUNCATED, "header needs 128 bytes", r.pos) + end + r:skip(4) + if r:u16le() ~= 0xA5E0 then + return nil, Err.new(Err.CORRUPT, "bad magic", r.pos - 2) + end + local nframes, w, h, depth = r:u16le(), r:u16le(), r:u16le(), r:u16le() + local hflags = r:u32le() + r:skip(2 + 8) + local transparent = r:u8() + r:skip(3) + local ncolors = r:u16le() + local pw, ph = r:u8(), r:u8() + local gx, gy, gw, gh = r:i16le(), r:i16le(), r:u16le(), r:u16le() + r:seek(128) + if depth ~= 32 and depth ~= 16 and depth ~= 8 then + return nil, Err.new(Err.CORRUPT, "bad colour depth " .. depth) + end + if w < 1 or h < 1 then + return nil, Err.new(Err.CORRUPT, "bad size") + end + if w * h > maxPixels then + return nil, Err.new(Err.LIMIT, string.format("%d x %d is over the pixel limit", w, h)) + end + if nframes > maxFrames then + return nil, Err.new(Err.LIMIT, "too many frames") + end + local bpp = depth // 8 + local palette = buffer.create(1024) + local palList: { { number } } = {} + local palNames: { [number]: string } = {} + local infos: { LayerInfo } = {} + local tags: { any } = {} + local frames: { { cels: { [number]: any }, delay: number } } = {} + local skipped = 0 + local lastUser: any = nil -- the object the next user data chunk belongs to + local tagUser = 0 -- tags waiting for their user data chunks + for fi = 1, nframes do + local fstart = r.pos + local fbytes = r:u32le() + local fmagic = r:u16le() + local oldChunks = r:u16le() + local duration = r:u16le() + r:skip(2) + local newChunks = r:u32le() + if r.err then + return nil, r.err + end + if fmagic ~= 0xF1FA then + return nil, Err.new(Err.CORRUPT, "frame " .. fi .. ": bad magic", fstart + 4) + end + if fbytes < 16 or fstart + fbytes > r.limit then + return nil, Err.new(Err.TRUNCATED, "frame " .. fi .. " runs past the end", fstart) + end + local nchunks = if newChunks ~= 0 then newChunks else oldChunks + local frame = { cels = {}, delay = duration / 1000 } + frames[fi] = frame + local fr = Bytes.reader(r.buf, r.pos, fstart + fbytes - r.pos) + for _ = 1, nchunks do + if fr:remaining() < 6 then + break + end + local cstart = fr.pos + local csize = fr:u32le() + local ctype = fr:u16le() + if csize < 6 or cstart + csize > fr.limit then + return nil, Err.new(Err.CORRUPT, string.format("frame %d: chunk 0x%04x size %d", fi, ctype, csize), cstart) + end + local c = Bytes.reader(fr.buf, cstart + 6, csize - 6) + fr.pos = cstart + csize + if ctype == 0x2004 then + local info: LayerInfo = { flags = c:u16le(), type = c:u16le(), level = c:u16le(), name = "", blend = 0, opacity = 255 } + c:skip(4) + info.blend = c:u16le() + info.opacity = c:u8() + c:skip(3) + info.name = str(c) + if c.err then + return nil, c.err + end + if info.type == 2 then + skipped += 1 + end + table.insert(infos, info) + lastUser = info + elseif ctype == 0x2005 then + local li = c:u16le() + local x, y = c:i16le(), c:i16le() + local op = c:u8() + local ctyp = c:u16le() + local z = c:i16le() + c:skip(5) + if c.err then + return nil, c.err + end + local cel: any = { x = x, y = y, opacity = op, z = z } + if ctyp == 0 or ctyp == 2 then + local cw, ch = c:u16le(), c:u16le() + if c.err then + return nil, c.err + end + if cw * ch > maxPixels then + return nil, Err.new(Err.LIMIT, "cel over the pixel limit") + end + local n = cw * ch + local raw: buffer, ro: number + if ctyp == 0 then + if not c:need(n * bpp) then + return nil, c.err + end + raw, ro = c.buf, c.pos + else + local z2, zerr = Deflate.zlib(c.buf, c.pos, c.limit - c.pos, n * bpp) + if not z2 then + -- some writers leave padding after the stream: inflate without the exact size + local loose = Deflate.zlib(c.buf, c.pos, c.limit - c.pos) + if not loose or buffer.len(loose) < n * bpp then + return nil, Err.new(Err.CORRUPT, "frame " .. fi .. ": cel data: " .. tostring(zerr and zerr.message), c.pos) + end + z2 = loose + end + raw, ro = z2 :: buffer, 0 + end + cel.w, cel.h, cel.raw, cel.ro = cw, ch, raw, ro + elseif ctyp == 1 then + cel.link = c:u16le() + 1 + else + cel.skip = true -- tilemap cel + end + frame.cels[li + 1] = cel + lastUser = cel + elseif ctype == 0x2018 then + local n = c:u16le() + c:skip(8) + tagUser = 0 + for _ = 1, n do + local from, to = c:u16le(), c:u16le() + local dir = c:u8() + local rep = c:u16le() + c:skip(6) + local cr, cg, cb = c:u8(), c:u8(), c:u8() + c:skip(1) + local name = str(c) + if c.err then + return nil, c.err + end + table.insert(tags, { name = name, from = from + 1, to = to + 1, direction = DIRECTIONS[dir] or "forward", ["repeat"] = rep, color = { cr, cg, cb } }) + tagUser += 1 + end + lastUser = nil + elseif ctype == 0x2019 then + local size = c:u32le() + local first, last = c:u32le(), c:u32le() + c:skip(8) + if first > last or last > 255 or size > 256 then + return nil, Err.new(Err.CORRUPT, "bad palette range", cstart) + end + for k = first, last do + local f = c:u16le() + local cr, cg, cb, ca = c:u8(), c:u8(), c:u8(), c:u8() + if bit32.band(f, 1) ~= 0 then + palNames[k + 1] = str(c) + end + buffer.writeu32(palette, k * 4, cr + cg * 256 + cb * 65536 + ca * 16777216) + palList[k + 1] = { cr, cg, cb, ca } + end + for k = #palList + 1, size do + palList[k] = { 0, 0, 0, 255 } + end + if c.err then + return nil, c.err + end + elseif (ctype == 0x0004 or ctype == 0x0011) and #palList == 0 then + -- old palettes (used when there is no 0x2019 chunk): packets of (skip, count) entries of RGB + local packets = c:u16le() + local k = 0 + for _ = 1, packets do + k += c:u8() + local n = c:u8() + if n == 0 then + n = 256 + end + for _ = 1, n do + local cr, cg, cb = c:u8(), c:u8(), c:u8() + if ctype == 0x0011 then + cr, cg, cb = cr * 255 // 63, cg * 255 // 63, cb * 255 // 63 + end + if k < 256 then + buffer.writeu32(palette, k * 4, cr + cg * 256 + cb * 65536 + 0xFF000000) + end + k += 1 + end + end + if c.err then + return nil, c.err + end + for i = 0, math.min(k, 256) - 1 do + local v = buffer.readu32(palette, i * 4) + palList[i + 1] = { v % 256, v // 256 % 256, v // 65536 % 256, 255 } + end + palList = table.move(palList, 1, math.min(k, 256), 1, {}) + elseif ctype == 0x2020 then + local f = c:u32le() + local ud: any = {} + if bit32.band(f, 1) ~= 0 then + ud.text = str(c) + end + if bit32.band(f, 2) ~= 0 then + ud.color = { c:u8(), c:u8(), c:u8(), c:u8() } + end + if not c.err then + if tagUser > 0 then + -- after a tags chunk, user data chunks follow for each tag in order + local t = tags[#tags - tagUser + 1] + if t then + t.userData = ud + end + tagUser -= 1 + elseif lastUser then + lastUser.userData = ud + end + end + end + -- others (colour profile, slices, tilesets, external files, cel extras, masks, paths) are skipped + end + r.pos = fstart + fbytes + end + local _ = ncolors + -- the layer tree of one frame + local function build(fi: number): { Types.Layer } + local root: { Types.Layer } = {} + local stack: { { Types.Layer } } = { root } -- stack[level + 1] = the children list at that level + for li, info in infos do + local level = math.min(info.level, #stack - 1) + local list = stack[level + 1] + local l: any = { + name = info.name, + x = 0, + y = 0, + opacity = if bit32.band(hflags, 1) ~= 0 or info.type ~= 0 then info.opacity / 255 else 1, + blend = BLENDS[info.blend] or "normal", + visible = bit32.band(info.flags, 1) ~= 0, + flags = info.flags, + } + if info.userData then + l.userData = info.userData + end + if info.type == 1 then + l.image = Types.Image.new(0, 0) + l.children = {} + -- Aseprite renders a group straight onto the backdrop unless it has its own blend mode / opacity (then + -- into a buffer of its own): pass-through vs isolated + if bit32.band(hflags, 2) == 0 or (info.blend == 0 and info.opacity == 255) then + l.blend = "passThrough" + l.opacity = 1 + end + table.insert(list, l) + -- deeper layers go into this group + for k = #stack, level + 2, -1 do + stack[k] = nil + end + stack[level + 2] = l.children + else + for k = #stack, level + 2, -1 do + stack[k] = nil + end + l.image = Types.Image.new(0, 0) + if info.type == 2 then + l.tilemap = true + end + local cel = frames[fi].cels[li] + local guard = 0 + while cel and cel.link and guard < 8 do -- follow links (one hop in valid files) + l.link = cel.link + local target = frames[cel.link] + cel = if target then target.cels[li] else nil + guard += 1 + end + if cel and cel.image then + l.image = cel.image + l.x, l.y = cel.x, cel.y + if cel.opacity < 255 then + l.fillOpacity = cel.opacity / 255 + end + if cel.z ~= 0 then + l.zIndex = cel.z + end + if cel.userData then + l.celUserData = cel.userData + end + end + table.insert(list, l) + end + end + return root + end + -- cel images (shared by linked cels) + for _, f in frames do + for li, cel in pairs(f.cels) do -- sparse: pairs, not ipairs-style iteration + if cel.raw then + local info = infos[li] + local img = Types.Image.new(cel.w, cel.h) + img.pixels = toRGBA(cel.raw, cel.ro, cel.w * cel.h, depth, palette, transparent, info ~= nil and bit32.band(info.flags, 8) ~= 0) + cel.image = img + cel.raw = nil + end + end + end + local layered = Types.Layered.new(w, h) + local list = {} + for fi = 1, nframes do + list[fi] = { layers = build(fi), delay = frames[fi].delay } + end + if nframes > 0 then + layered.layers = list[1].layers + end + layered.frames = list + if #palList > 0 then + layered.meta.palette = palList + if next(palNames) then + layered.meta.paletteNames = palNames + end + end + layered.meta.tags = tags + layered.meta.colorDepth = depth + layered.meta.transparentIndex = transparent + layered.meta.pixelRatio = { if pw == 0 then 1 else pw, if ph == 0 then 1 else ph } + layered.meta.grid = { gx, gy, gw, gh } + if skipped > 0 then + layered.meta.skipped = skipped + end + layered.meta.source = { format = "aseprite", bitDepth = depth, colorType = if depth == 32 then "rgba" elseif depth == 16 then "graya" else "indexed" } + return layered, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +type Node = { layer: any, level: number } + +local function isImage(v: any): boolean + return type(v) == "table" and v.format == "rgba8" and type(v.pixels) == "buffer" and type(v.width) == "number" and type(v.height) == "number" and v.width >= 0 and v.height >= 0 and v.width < 65536 and v.height < 65536 and buffer.len(v.pixels) >= v.width * v.height * 4 +end + +-- the nodes of a tree in file order (a group, then its children one level deeper) +local function nodes(layers: { any }, level: number, out: { Node }): boolean + for _, l in layers do + if type(l) ~= "table" or level > 64 then + return false + end + table.insert(out, { layer = l, level = level }) + if type(l.children) == "table" then + if not nodes(l.children, level + 1, out) then + return false + end + end + end + return true +end + +local function writeStr(w: Bytes.Writer, s: string) + local n = math.min(#s, 65535) + w:u16le(n) + w:string(string.sub(s, 1, n)) +end + +function Aseprite.encode(layered: Types.Layered, opts: EncodeOptions?): (buffer?, Err.Err?) + if type(layered) ~= "table" or type(layered.layers) ~= "table" or type(layered.width) ~= "number" or type(layered.height) ~= "number" then + return nil, Err.new(Err.ARG, "needs a Layered value") + end + local W, H = math.floor(layered.width), math.floor(layered.height) + if W < 1 or H < 1 or W > 65535 or H > 65535 then + return nil, Err.new(Err.ARG, "bad sprite size") + end + local meta: any = if type(layered.meta) == "table" then layered.meta else {} + local level = opts and opts.level or 6 + -- frames: the layered frames, or one frame of the layers + local frameList: { any } = if type(layered.frames) == "table" and #layered.frames > 0 then layered.frames else { { layers = layered.layers, delay = 0.1 } } + local struct: { Node } = {} + if not nodes(frameList[1].layers, 0, struct) then + return nil, Err.new(Err.ARG, "bad layer tree") + end + if #struct > 65535 or #frameList > 65535 then + return nil, Err.new(Err.ARG, "too many layers / frames") + end + local perFrame: { { Node } } = {} + for fi, f in frameList do + if type(f) ~= "table" or type(f.layers) ~= "table" then + return nil, Err.new(Err.ARG, "frame " .. fi .. ": no layers") + end + local ns: { Node } = {} + if not nodes(f.layers, 0, ns) or #ns ~= #struct then + return nil, Err.new(Err.ARG, "frame " .. fi .. ": its layer tree differs from frame 1's") + end + for k, n in ns do + if (type(n.layer.children) == "table") ~= (type(struct[k].layer.children) == "table") then + return nil, Err.new(Err.ARG, "frame " .. fi .. ": its layer tree differs from frame 1's") + end + if type(n.layer.children) ~= "table" and not isImage(n.layer.image) then + return nil, Err.new(Err.ARG, "frame " .. fi .. ": layer " .. tostring(n.layer.name) .. " needs an rgba8 image") + end + end + perFrame[fi] = ns + end + -- the colour depth: requested, or the source's when every pixel fits + local depth = opts and opts.depth or meta.colorDepth or 32 + local explicit = opts ~= nil and opts.depth ~= nil + if depth ~= 32 and depth ~= 16 and depth ~= 8 then + return nil, Err.new(Err.ARG, "depth must be 32, 16 or 8") + end + local palette: { { number } } = if type(meta.palette) == "table" then meta.palette else {} + local transparent = if type(meta.transparentIndex) == "number" then meta.transparentIndex else 0 + local index: { [number]: number } = {} + for k = #palette, 1, -1 do + local c = palette[k] + if type(c) == "table" then + index[(c[1] or 0) + (c[2] or 0) * 256 + (c[3] or 0) * 65536 + (c[4] or 255) * 16777216] = k - 1 + end + end + if depth ~= 32 then + local fits = depth ~= 8 or #palette > 0 + for _, ns in perFrame do + for _, n in ns do + local img = n.layer.image + if fits and type(n.layer.children) ~= "table" then + local px = img.pixels + for i = 0, img.width * img.height - 1 do + local v = buffer.readu32(px, i * 4) + if depth == 16 then + local r, g, b = v % 256, v // 256 % 256, v // 65536 % 256 + if r ~= g or g ~= b then + fits = false + break + end + elseif v // 16777216 ~= 0 and index[v] == nil then + fits = false + break + end + end + end + end + end + if not fits then + if explicit then + return nil, Err.new(Err.ARG, "the pixels do not fit depth " .. depth .. (if depth == 8 then " with meta.palette" else "")) + end + depth = 32 + end + end + local bpp = depth // 8 + local function pixels(n: any): buffer + local img = n.layer.image + local count = img.width * img.height + if depth == 32 then + return img.pixels + end + local out = buffer.create(count * bpp) + local px = img.pixels + for i = 0, count - 1 do + local v = buffer.readu32(px, i * 4) + if depth == 16 then + buffer.writeu8(out, i * 2, v % 256) + buffer.writeu8(out, i * 2 + 1, v // 16777216) + else + local k = if v // 16777216 == 0 and bit32.band(tonumber(n.layer.flags) or 0, 8) == 0 then transparent else index[v] or transparent + buffer.writeu8(out, i, k) + end + end + return out + end + + local out = Bytes.writer(65536) + -- header (file size patched at the end) + out:u32le(0) + out:u16le(0xA5E0) + out:u16le(#frameList) + out:u16le(W) + out:u16le(H) + out:u16le(depth) + out:u32le(3) -- layer opacity and group opacity / blend valid + out:u16le(100) + out:u32le(0) + out:u32le(0) + out:u8(if depth == 8 then transparent else 0) + out:fill(0, 3) + out:u16le(if #palette > 0 and #palette < 256 then #palette else 0) + local ratio = if type(meta.pixelRatio) == "table" then meta.pixelRatio else { 1, 1 } + out:u8(math.clamp(tonumber(ratio[1]) or 1, 0, 255)) + out:u8(math.clamp(tonumber(ratio[2]) or 1, 0, 255)) + local grid = if type(meta.grid) == "table" then meta.grid else { 0, 0, 16, 16 } + out:i16le(tonumber(grid[1]) or 0) + out:i16le(tonumber(grid[2]) or 0) + out:u16le(math.clamp(tonumber(grid[3]) or 16, 0, 65535)) + out:u16le(math.clamp(tonumber(grid[4]) or 16, 0, 65535)) + out:fill(0, 84) + + local function chunk(fw: Bytes.Writer, ctype: number, body: Bytes.Writer) + local b = body:finish() + fw:u32le(buffer.len(b) + 6) + fw:u16le(ctype) + fw:bytes(b) + end + local function userData(fw: Bytes.Writer, ud: any): number + if type(ud) ~= "table" then + return 0 + end + local c = Bytes.writer(64) + local f = (if type(ud.text) == "string" then 1 else 0) + (if type(ud.color) == "table" then 2 else 0) + c:u32le(f) + if type(ud.text) == "string" then + writeStr(c, ud.text) + end + if type(ud.color) == "table" then + for k = 1, 4 do + c:u8(math.clamp(tonumber(ud.color[k]) or 0, 0, 255)) + end + end + chunk(fw, 0x2020, c) + return 1 + end + -- where each (layer, frame) cel's image was first written: linked cels + local firstAt: { [number]: { [any]: { frame: number, x: number, y: number, fill: number } } } = {} + for fi, f in frameList do + local fw = Bytes.writer(4096) + local count = 0 + if fi == 1 then + -- colour profile: sRGB + local cp = Bytes.writer(16) + cp:u16le(1) + cp:u16le(0) + cp:u32le(0) + cp:fill(0, 8) + chunk(fw, 0x2007, cp) + count += 1 + if #palette > 0 then + local p = Bytes.writer(#palette * 6 + 20) + local n = math.min(#palette, 256) + p:u32le(n) + p:u32le(0) + p:u32le(n - 1) + p:fill(0, 8) + local names = if type(meta.paletteNames) == "table" then meta.paletteNames else {} + for k = 1, n do + local c = palette[k] + local nm = names[k] + p:u16le(if type(nm) == "string" then 1 else 0) + p:u8(c[1] or 0) + p:u8(c[2] or 0) + p:u8(c[3] or 0) + p:u8(c[4] or 255) + if type(nm) == "string" then + writeStr(p, nm) + end + end + chunk(fw, 0x2019, p) + count += 1 + end + for _, n in struct do + local l = n.layer + local c = Bytes.writer(64) + local isGroup = type(l.children) == "table" + local flags = tonumber(l.flags) or 3 + flags = bit32.band(flags, bit32.bnot(1)) + (if l.visible == false then 0 else 1) + c:u16le(flags) + c:u16le(if isGroup then 1 else 0) + c:u16le(n.level) + c:u16le(0) + c:u16le(0) + c:u16le(BLEND_IDS[l.blend] or 0) + c:u8(math.clamp(math.floor((tonumber(l.opacity) or 1) * 255 + 0.5), 0, 255)) + c:fill(0, 3) + writeStr(c, tostring(l.name or "Layer")) + chunk(fw, 0x2004, c) + count += 1 + count += userData(fw, l.userData) + end + local tags = if type(meta.tags) == "table" then meta.tags else {} + if #tags > 0 then + local c = Bytes.writer(64) + c:u16le(#tags) + c:fill(0, 8) + for _, t in tags do + c:u16le(math.clamp((tonumber(t.from) or 1) - 1, 0, 65535)) + c:u16le(math.clamp((tonumber(t.to) or 1) - 1, 0, 65535)) + c:u8(DIRECTION_IDS[t.direction] or 0) + c:u16le(math.clamp(tonumber(t["repeat"]) or 0, 0, 65535)) + c:fill(0, 6) + local col = if type(t.color) == "table" then t.color else { 0, 0, 0 } + c:u8(col[1] or 0) + c:u8(col[2] or 0) + c:u8(col[3] or 0) + c:u8(0) + writeStr(c, tostring(t.name or "Tag")) + end + chunk(fw, 0x2018, c) + count += 1 + for _, t in tags do + if type(t.userData) == "table" then + count += userData(fw, t.userData) + else + local e = Bytes.writer(4) + e:u32le(0) + chunk(fw, 0x2020, e) + count += 1 + end + end + end + end + for li, n in perFrame[fi] do + local l = n.layer + if type(l.children) == "table" or l.image.width == 0 or l.image.height == 0 then + continue + end + local x, y = math.floor(tonumber(l.x) or 0), math.floor(tonumber(l.y) or 0) + local fill = math.clamp(math.floor((tonumber(l.fillOpacity) or 1) * 255 + 0.5), 0, 255) + local c = Bytes.writer(256) + c:u16le(li - 1) + c:i16le(x) + c:i16le(y) + c:u8(fill) + local seen = firstAt[li] and firstAt[li][l.image] + if seen and seen.x == x and seen.y == y and seen.fill == fill then + c:u16le(1) + c:i16le(tonumber(l.zIndex) or 0) + c:fill(0, 5) + c:u16le(seen.frame - 1) + else + c:u16le(2) + c:i16le(tonumber(l.zIndex) or 0) + c:fill(0, 5) + c:u16le(l.image.width) + c:u16le(l.image.height) + local z = Deflate.zlibCompress(pixels(n), { level = level }) + if not z then + return nil, Err.new(Err.ARG, "cel compression failed") + end + c:bytes(z) + firstAt[li] = firstAt[li] or {} + firstAt[li][l.image] = { frame = fi, x = x, y = y, fill = fill } + end + chunk(fw, 0x2005, c) + count += 1 + count += userData(fw, l.celUserData) + end + local body = fw:finish() + out:u32le(buffer.len(body) + 16) + out:u16le(0xF1FA) + out:u16le(math.min(count, 0xFFFF)) + out:u16le(math.clamp(math.floor((tonumber(f.delay) or 0.1) * 1000 + 0.5), 0, 65535)) + out:u16le(0) + out:u32le(count) + out:bytes(body) + end + out:setU32le(0, out:tell()) + return out:finish(), nil +end + +return Aseprite diff --git a/tests/layered/aseprite.luau b/tests/layered/aseprite.luau new file mode 100644 index 0000000..06558f6 --- /dev/null +++ b/tests/layered/aseprite.luau @@ -0,0 +1,172 @@ +-- layered/aseprite tests: sprites written by tools/fixtures/aseprite.py (RGBA / grayscale / indexed; raw, zlib and +-- linked cels; groups, hidden layers, blend modes, layer and cel opacity; old and new palettes; tags; user data) and +-- by LibreSprite (re-saved and from a GIF): every cel's pixels and position, and our flatten of every frame against +-- LibreSprite's rendering (PSNR); our encoder's sprite rendered by LibreSprite (tools/fixtures/_ours.luau); round +-- trips (linked cels kept), the contract and the fuzz pass. Fixtures: tools/fixtures/aseprite.py. +local T = require("@tests/T") +local Ase = require("@formats/layered/aseprite") +local LayerOps = require("@formats/ops/LayerOps") +local Types = require("@formats/Types") +local Bytes = require("@formats/core/Bytes") +local Crc32 = require("@formats/core/Crc32") +local Err = require("@formats/core/Err") +local Fx = require("@tests/gen/aseprite") +local Ours = require("@tests/gen/aseprite_ours") + +local t = T.suite("aseprite") + +local function decode(s: string | buffer, opts: any?): (any, any) + local b = if type(s) == "string" then buffer.fromstring(s) else s + return Ase.decode(Bytes.reader(b), opts) +end +local function psnr(a: buffer, b: string): number + local n = math.min(buffer.len(a), #b) + local se = 0 + for i = 0, n - 1, 4 do + local aa, ab = buffer.readu8(a, i + 3), string.byte(b, i + 4) + for k = 0, 2 do + local d = (buffer.readu8(a, i + k) * aa - string.byte(b, i + k + 1) * ab) / 255 + se += d * d + end + se += (aa - ab) * (aa - ab) + end + if se == 0 then + return 99 + end + return 10 * math.log10(255 * 255 / (se / n)) +end +-- the n-th node (groups included, file order) of a frame's tree +local function nodes(layers: { any }, out: { any }?): { any } + local o = out or {} + for _, l in layers do + table.insert(o, l) + if l.children then + nodes(l.children, o) + end + end + return o +end + +t:eq(Ase.name, "aseprite", "name") +t:eq(Ase.category, "layered", "category") +t:check(Ase.caps.decode and Ase.caps.encode, "caps") + +local samples = {} +for _, c in Fx.cases do + local doc, err = decode(c.data) + t:check(doc, c.name .. ": " .. tostring(err)) + t:check(doc.width == c.width and doc.height == c.height, c.name .. ": size") + t:eq(#doc.frames, c.nframes, c.name .. ": frames") + for _, cel in c.cels do + local l = nodes(doc.frames[cel.frame].layers)[cel.layer] + local label = string.format("%s: frame %d layer %d", c.name, cel.frame, cel.layer) + t:check(l and l.x == cel.x and l.y == cel.y and l.image.width == cel.w and l.image.height == cel.h, label .. ": position / size") + t:eq(Crc32.of(l.image.pixels), cel.crc, label .. ": pixels") + end + -- our flatten vs LibreSprite's rendering of each frame + for fi, want in c.frames do + local img = LayerOps.flatten(doc, { frame = fi }) :: any + local p = psnr(img.pixels, want) + t:check(p >= 40, string.format("%s: frame %d vs LibreSprite: %.1f dB", c.name, fi, p)) + if p < 99 then + t:note("%s frame %d: flatten vs LibreSprite %.1f dB", c.name, fi, p) + end + end + table.insert(samples, c.data) +end + +-- the hand-made RGBA sprite's details +do + local doc = decode(Fx.cases[1].data) + local L = doc.layers + t:eq(#L, 4, "top level: Background, Group, Hidden, Top") + t:eq(L[2].name, "Group", "group") + t:eq(#L[2].children, 2, "group children") + t:eq(L[2].children[1].blend, "multiply", "blend") + t:eq(math.floor(L[2].children[1].opacity * 255 + 0.5), 200, "layer opacity") + t:eq(math.floor(L[2].children[2].fillOpacity * 255 + 0.5), 128, "cel opacity -> fillOpacity") + t:eq(L[3].visible, false, "hidden") + t:eq(L[2].children[1].userData.text, "mul layer", "layer user data") + t:eq(L[2].children[1].userData.color[4], 4, "user data colour") + t:eq(L[2].children[1].celUserData.text, "a cel", "cel user data") + t:eq(doc.frames[2].delay, 0.15, "frame delay") + t:check(doc.frames[3].layers[1].image == L[1].image and doc.frames[3].layers[1].link == 1, "linked cel shares the image") + t:eq(#doc.meta.tags, 2, "tags") + t:check(doc.meta.tags[2].name == "back" and doc.meta.tags[2].from == 2 and doc.meta.tags[2].to == 3 and doc.meta.tags[2].direction == "pingpong" and doc.meta.tags[2]["repeat"] == 3, "tag fields") + t:eq(doc.meta.tags[1].userData.text, "walk tag", "tag user data") + t:eq(#doc.meta.palette, 16, "palette") + t:eq(doc.meta.paletteNames[4], "fourth", "palette names") + t:eq(doc.meta.colorDepth, 32, "depth") + local idx = decode(Fx.cases[3].data) + t:eq(#idx.meta.palette, 5, "old palette chunk") + t:eq(idx.meta.colorDepth, 8, "indexed") + + -- round trips: every frame's nodes and pixels, linked cels stay shared, depth kept + for ci, c in Fx.cases do + local d = decode(c.data) + local out, eerr = Ase.encode(d) + t:check(out, c.name .. ": encode: " .. tostring(eerr)) + local back = decode(out :: buffer) + t:check(back, c.name .. ": decode ours") + t:eq(#back.frames, #d.frames, c.name .. ": rt frames") + t:eq(back.meta.colorDepth, d.meta.colorDepth, c.name .. ": rt depth") + for fi, f in d.frames do + local a, b = nodes(f.layers), nodes(back.frames[fi].layers) + t:eq(#b, #a, c.name .. ": rt nodes") + for k, l in a do + t:eq(b[k].name, l.name, "rt name") + t:check(buffer.tostring(b[k].image.pixels) == buffer.tostring(l.image.pixels), c.name .. ": rt pixels " .. l.name .. " frame " .. fi) + t:check(b[k].x == l.x and b[k].y == l.y, "rt position") + t:eq(b[k].visible, l.visible, "rt visible") + t:eq(b[k].fillOpacity, l.fillOpacity, "rt cel opacity") + if not l.children then + t:eq(b[k].blend, l.blend, "rt blend") + end + end + t:eq(back.frames[fi].delay, f.delay, "rt delay") + end + if ci == 1 then + t:check(back.frames[3].layers[1].image == back.layers[1].image, "rt: linked cel written as a link") + t:eq(back.meta.tags[2].direction, "pingpong", "rt tags") + t:eq(back.meta.paletteNames[1], "first", "rt palette names") + end + table.insert(samples, buffer.tostring(out :: buffer)) + end + -- forced depths + local _, e = Ase.encode(doc, { depth = 16 }) + t:check(e and e.code == Err.ARG, "colour sprite as grayscale: " .. tostring(e)) + local g = decode(Fx.cases[2].data) + local g32 = decode(Ase.encode(g, { depth = 32 }) :: buffer) + t:eq(g32.meta.colorDepth, 32, "grayscale written as RGBA") +end + +-- LibreSprite renders our encoder's sprite like our flatten does +t:eq(#Ours.frames, Ours.nframes, "LibreSprite read every frame of our sprite") +for fi, want in Ours.frames do + local ours = Ours.ours[fi] + local p = psnr(buffer.fromstring(ours), want) + t:check(p >= 40, string.format("our sprite frame %d: LibreSprite vs our flatten %.1f dB", fi, p)) + t:note("our sprite frame %d: LibreSprite vs our flatten %.1f dB", fi, p) +end + +-- a Layered without frames is one frame +do + local d = Types.Layered.new(4, 3) + d.layers = { Types.Layered.layer("only", Types.Image.new(2, 2), 1, 1) } + local back = decode(Ase.encode(d) :: buffer) + t:check(back and #back.frames == 1 and back.layers[1].name == "only" and back.layers[1].x == 1, "single frame") + local _, e = Ase.encode({ width = 4, height = 4, layers = { { name = "x" } } } :: any) + t:check(e and e.code == Err.ARG, "layer without an image") + local _, e2 = decode("\0\0\0\0\224\165") + t:check(e2 and e2.code == Err.TRUNCATED, "short header") + local bad = buffer.fromstring(Fx.cases[1].data) + buffer.writeu16(bad, 12, 24) + local _, e3 = decode(bad) + t:check(e3 and e3.code == Err.CORRUPT, "bad depth") + t:eq(Ase.sniff(Bytes.reader(buffer.fromstring(Fx.cases[1].data))), 1, "sniff") +end + +t:fuzz("decode", function(b: buffer) + return Ase.decode(Bytes.reader(b)) +end, samples, { mutations = 30, keepHeader = 6 }) +t:done() diff --git a/tools/fixtures/_ours.luau b/tools/fixtures/_ours.luau index 37be39b..59aa5bf 100644 --- a/tools/fixtures/_ours.luau +++ b/tools/fixtures/_ours.luau @@ -87,6 +87,30 @@ local function psdDoc(): Types.Layered 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 + local which = ... if which == "psd" then local Psd = require("@formats/layered/psd") @@ -99,4 +123,13 @@ if which == "psd" then 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 })) end diff --git a/tools/fixtures/aseprite.py b/tools/fixtures/aseprite.py new file mode 100644 index 0000000..4624623 --- /dev/null +++ b/tools/fixtures/aseprite.py @@ -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("