rename: src/Formats -> src/Rosetta, @formats -> @rosetta requires, build/luajit/rosetta + rosetta._compat, build/roblox/Rosetta, ROSETTA_* env/globals, writer vendor strings
This commit is contained in:
1 parent
2956576d7f
commit
22ddcd78fa
941 files changed
+3364
-3364
No files matched your search
@@ -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("@rosetta/core/Err")
|
||||
local Bytes = require("@rosetta/core/Bytes")
|
||||
local Types = require("@rosetta/Types")
|
||||
local Deflate = require("@rosetta/codecs/compress/Deflate")
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ contract
|
||||
local Aseprite = {
|
||||
name = "aseprite",
|
||||
category = "layered",
|
||||
extensions = { "aseprite", "ase" },
|
||||
mime = { "image/x-aseprite" },
|
||||
deps = { "core/Err", "core/Bytes", "Types", "codecs/compress/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
|
||||
@@ -0,0 +1,293 @@
|
||||
--!strict
|
||||
-- layered/ora: OpenRaster (the OpenRaster 0.0.6 specification, freedesktop.org; new code): a zip (containers/Zip) with
|
||||
-- a stored "mimetype" first, stack.xml (codecs/text/Xml), PNG layers, mergedimage.png and Thumbnails/thumbnail.png.
|
||||
-- Decode: the stack tree (nested <stack> = groups: isolation="auto" is passThrough; <layer> name / src / x / y /
|
||||
-- opacity / visibility / composite-op, svg:* ops mapped to the codecs/image/Blend names, unknown ones kept as written),
|
||||
-- layers bottom to top as Types.Layered, the PNGs through the api hook opts.decodeImage (F.load passes it; without it:
|
||||
-- UNSUPPORTED), mergedimage.png as meta.composite, the resolution (meta.dpi). Encode: a Layered (rgba8 layers, groups)
|
||||
-- with every layer, the merged image (codecs/image/Blend flattens the tree, or opts.composite) and a thumbnail (up to
|
||||
-- 256 px, nearest) as PNGs through opts.encodeImage. Not supported: non-PNG layer sources, the <text> / <filter> /
|
||||
-- <selection> elements (ignored).
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ requires
|
||||
local Err = require("@rosetta/core/Err")
|
||||
local Bytes = require("@rosetta/core/Bytes")
|
||||
local Types = require("@rosetta/Types")
|
||||
local Zip = require("@rosetta/containers/Zip")
|
||||
local Xml = require("@rosetta/codecs/text/Xml")
|
||||
local Blend = require("@rosetta/codecs/image/Blend")
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ contract
|
||||
local Ora = {
|
||||
name = "ora",
|
||||
category = "layered",
|
||||
extensions = { "ora" },
|
||||
mime = { "image/openraster" },
|
||||
deps = { "core/Err", "core/Bytes", "Types", "containers/Zip", "codecs/text/Xml", "codecs/image/Blend" },
|
||||
caps = { decode = true, encode = true, layers = true, groups = true, depths = { 8 } },
|
||||
}
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ types
|
||||
export type DecodeOptions = {
|
||||
decodeImage: ((buffer) -> (Types.Image?, Err.Err?))?, -- decodes the PNG layers (the api passes one)
|
||||
composite: boolean?, -- decode mergedimage.png into meta.composite (default true)
|
||||
maxLayers: number?, -- default 10000
|
||||
}
|
||||
export type EncodeOptions = {
|
||||
encodeImage: ((Types.Image, string) -> (buffer?, Err.Err?))?, -- writes the PNGs (the api passes one)
|
||||
composite: Types.Image?, -- the merged image (default: the layers flattened with codecs/image/Blend)
|
||||
thumbnail: boolean?, -- write Thumbnails/thumbnail.png (default true)
|
||||
}
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ constants
|
||||
local MIME = "image/openraster"
|
||||
local OPS: { [string]: string } = {
|
||||
["svg:src-over"] = "normal", ["svg:multiply"] = "multiply", ["svg:screen"] = "screen", ["svg:overlay"] = "overlay",
|
||||
["svg:darken"] = "darken", ["svg:lighten"] = "lighten", ["svg:color-dodge"] = "colorDodge", ["svg:color-burn"] = "colorBurn",
|
||||
["svg:hard-light"] = "hardLight", ["svg:soft-light"] = "softLight", ["svg:difference"] = "difference",
|
||||
["svg:exclusion"] = "exclusion", ["svg:hue"] = "hue", ["svg:saturation"] = "saturation", ["svg:color"] = "color",
|
||||
["svg:luminosity"] = "luminosity", ["svg:plus"] = "linearDodge",
|
||||
}
|
||||
local BACK: { [string]: string } = {}
|
||||
for k, v in OPS do
|
||||
BACK[v] = k
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ sniff
|
||||
function Ora.sniff(r: Bytes.Reader): number
|
||||
-- a zip whose first (stored) entry is "mimetype" holding image/openraster
|
||||
if r:peek(4) == "PK\3\4" and r:peek(8, 30) == "mimetype" and r:peek(#MIME, 38) == MIME then
|
||||
return 1
|
||||
end
|
||||
return 0
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ decode
|
||||
local function num(v: any, default: number): number
|
||||
local n = tonumber(v)
|
||||
return if n and n == n then n else default
|
||||
end
|
||||
|
||||
function Ora.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Layered?, Err.Err?)
|
||||
local zip, zerr = Zip.open(r)
|
||||
if not zip then
|
||||
return nil, zerr
|
||||
end
|
||||
local mt = zip:readString("mimetype")
|
||||
if mt and string.gsub(mt, "%s+$", "") ~= MIME then
|
||||
return nil, Err.new(Err.CORRUPT, "mimetype is not " .. MIME)
|
||||
end
|
||||
local stackText, serr = zip:readString("stack.xml")
|
||||
if not stackText then
|
||||
return nil, serr or Err.new(Err.CORRUPT, "missing stack.xml")
|
||||
end
|
||||
local doc, xerr = Xml.decode(stackText)
|
||||
if not doc then
|
||||
return nil, xerr
|
||||
end
|
||||
local root = doc.root
|
||||
if not root or root.name ~= "image" then
|
||||
return nil, Err.new(Err.CORRUPT, "stack.xml has no <image> root")
|
||||
end
|
||||
local decodeImage = opts and opts.decodeImage
|
||||
if not decodeImage then
|
||||
return nil, Err.new(Err.UNSUPPORTED, "PNG layers need the decodeImage hook")
|
||||
end
|
||||
local W, H = num(root.attrs.w, 0), num(root.attrs.h, 0)
|
||||
if W < 1 or H < 1 or W > 65536 or H > 65536 then
|
||||
return nil, Err.new(Err.CORRUPT, "bad image size")
|
||||
end
|
||||
local maxLayers = opts and opts.maxLayers or 10000
|
||||
local count = 0
|
||||
local function png(path: string): (Types.Image?, Err.Err?)
|
||||
local data, derr = zip:read(path)
|
||||
if not data then
|
||||
return nil, derr or Err.new(Err.CORRUPT, "missing " .. path)
|
||||
end
|
||||
local ok, img, ierr = pcall(decodeImage, data)
|
||||
if not ok or not img then
|
||||
return nil, Err.new(Err.CORRUPT, path .. ": " .. tostring(if ok then ierr else img))
|
||||
end
|
||||
return img, nil
|
||||
end
|
||||
-- a <stack>'s children, top first in the file -> bottom to top
|
||||
local function stack(node: any, ox: number, oy: number): ({ Types.Layer }?, Err.Err?)
|
||||
local out: { Types.Layer } = {}
|
||||
for _, ch in node.children do
|
||||
if type(ch) ~= "table" then
|
||||
continue
|
||||
end
|
||||
local a = ch.attrs or {}
|
||||
local visible = a.visibility ~= "hidden"
|
||||
local op = a["composite-op"] or "svg:src-over"
|
||||
local blend = OPS[op] or op
|
||||
local x, y = ox + num(a.x, 0), oy + num(a.y, 0)
|
||||
count += 1
|
||||
if count > maxLayers then
|
||||
return nil, Err.new(Err.LIMIT, "too many layers")
|
||||
end
|
||||
if ch.name == "layer" then
|
||||
local src = a.src
|
||||
if type(src) ~= "string" then
|
||||
continue
|
||||
end
|
||||
if string.lower(string.sub(src, -4)) ~= ".png" then
|
||||
return nil, Err.new(Err.UNSUPPORTED, "layer source " .. src)
|
||||
end
|
||||
local img, perr = png(src)
|
||||
if not img then
|
||||
return nil, perr
|
||||
end
|
||||
local layer = Types.Layered.layer(a.name or src, img :: Types.Image, x, y)
|
||||
layer.opacity = math.clamp(num(a.opacity, 1), 0, 1)
|
||||
layer.visible = visible
|
||||
layer.blend = blend
|
||||
table.insert(out, 1, layer)
|
||||
elseif ch.name == "stack" then
|
||||
local kids, kerr = stack(ch, x, y)
|
||||
if not kids then
|
||||
return nil, kerr
|
||||
end
|
||||
local g = Types.Layered.group(a.name or "group", kids :: { Types.Layer })
|
||||
g.opacity = math.clamp(num(a.opacity, 1), 0, 1)
|
||||
g.visible = visible
|
||||
g.blend = if a.isolation == "isolate" then (if blend == "normal" then "normal" else blend) else "passThrough"
|
||||
table.insert(out, 1, g)
|
||||
end
|
||||
end
|
||||
return out, nil
|
||||
end
|
||||
local top = Xml.child(root, "stack")
|
||||
if not top then
|
||||
return nil, Err.new(Err.CORRUPT, "stack.xml has no <stack>")
|
||||
end
|
||||
local layers, lerr = stack(top, 0, 0)
|
||||
if not layers then
|
||||
return nil, lerr
|
||||
end
|
||||
local doc2 = Types.Layered.new(W, H)
|
||||
doc2.layers = layers :: { Types.Layer }
|
||||
if not (opts and opts.composite == false) and zip:find("mergedimage.png") then
|
||||
doc2.meta.composite = png("mergedimage.png")
|
||||
end
|
||||
local xr, yr = tonumber(root.attrs.xres), tonumber(root.attrs.yres)
|
||||
if xr and yr then
|
||||
doc2.meta.dpi = { x = xr, y = yr }
|
||||
end
|
||||
doc2.meta.source = { format = "ora", version = root.attrs.version, layers = count }
|
||||
return doc2, nil
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ encode
|
||||
-- nearest-neighbour downscale to fit max x max
|
||||
local function thumbnail(img: Types.Image, max: number): Types.Image
|
||||
local w, h = img.width, img.height
|
||||
local s = math.min(1, max / math.max(w, h))
|
||||
local tw, th = math.max(1, math.floor(w * s)), math.max(1, math.floor(h * s))
|
||||
local t = Types.Image.new(tw, th, "rgba8")
|
||||
for y = 0, th - 1 do
|
||||
local sy = math.min(h - 1, math.floor(y / s))
|
||||
for x = 0, tw - 1 do
|
||||
local sx = math.min(w - 1, math.floor(x / s))
|
||||
buffer.writeu32(t.pixels, (y * tw + x) * 4, buffer.readu32(img.pixels, (sy * w + sx) * 4))
|
||||
end
|
||||
end
|
||||
return t
|
||||
end
|
||||
|
||||
function Ora.encode(doc: Types.Layered, opts: EncodeOptions?): (buffer?, Err.Err?)
|
||||
if type(doc) ~= "table" or type(doc.layers) ~= "table" or type(doc.width) ~= "number" or doc.width < 1 or doc.height < 1 then
|
||||
return nil, Err.new(Err.ARG, "needs a Layered document")
|
||||
end
|
||||
local encodeImage = opts and opts.encodeImage
|
||||
if not encodeImage then
|
||||
return nil, Err.new(Err.UNSUPPORTED, "PNG layers need the encodeImage hook")
|
||||
end
|
||||
local W, H = doc.width, doc.height
|
||||
local zw = Zip.writer()
|
||||
zw:add("mimetype", MIME, { method = "store" })
|
||||
local files: { { any } } = {}
|
||||
local n = 0
|
||||
local function png(img: Types.Image, label: string): (buffer?, Err.Err?)
|
||||
if type(img) ~= "table" or img.format ~= "rgba8" then
|
||||
return nil, Err.new(Err.ARG, label .. ": layers need rgba8 images")
|
||||
end
|
||||
local ok, data, err = pcall(encodeImage, img, "png")
|
||||
if not ok or not data then
|
||||
return nil, Err.new(Err.ARG, label .. ": " .. tostring(if ok then err else data))
|
||||
end
|
||||
return data, nil
|
||||
end
|
||||
-- layers bottom to top -> xml children top first
|
||||
local function stack(layers: { Types.Layer }): ({ any }?, Err.Err?)
|
||||
local kids = {}
|
||||
for i = #layers, 1, -1 do
|
||||
local l = layers[i]
|
||||
local attrs: { [string]: string } = {
|
||||
name = l.name or "",
|
||||
opacity = string.format("%.6g", l.opacity or 1),
|
||||
visibility = if l.visible == false then "hidden" else "visible",
|
||||
}
|
||||
if l.children then
|
||||
attrs.isolation = if l.blend == "passThrough" then "auto" else "isolate"
|
||||
if l.blend ~= "passThrough" then
|
||||
attrs["composite-op"] = BACK[l.blend] or l.blend
|
||||
end
|
||||
local sub, serr = stack(l.children)
|
||||
if not sub then
|
||||
return nil, serr
|
||||
end
|
||||
table.insert(kids, Xml.element("stack", attrs, sub))
|
||||
else
|
||||
n += 1
|
||||
local path = string.format("data/layer%03d.png", n)
|
||||
local data, perr = png(l.image, "layer " .. tostring(l.name))
|
||||
if not data then
|
||||
return nil, perr
|
||||
end
|
||||
table.insert(files, { path, data })
|
||||
attrs.src = path
|
||||
attrs.x = tostring(math.floor(l.x or 0))
|
||||
attrs.y = tostring(math.floor(l.y or 0))
|
||||
attrs["composite-op"] = BACK[l.blend or "normal"] or l.blend or "svg:src-over"
|
||||
table.insert(kids, Xml.element("layer", attrs))
|
||||
end
|
||||
end
|
||||
return kids, nil
|
||||
end
|
||||
local kids, kerr = stack(doc.layers)
|
||||
if not kids then
|
||||
return nil, kerr
|
||||
end
|
||||
local rootAttrs: { [string]: string } = { version = "0.0.6", w = tostring(W), h = tostring(H) }
|
||||
local dpi = doc.meta and doc.meta.dpi
|
||||
if dpi then
|
||||
rootAttrs.xres, rootAttrs.yres = tostring(dpi.x), tostring(dpi.y)
|
||||
end
|
||||
local xml = Xml.encode(Xml.document(Xml.element("image", rootAttrs, { Xml.element("stack", {}, kids :: any) })), { indent = 1 })
|
||||
zw:add("stack.xml", xml :: string)
|
||||
for _, f in files do
|
||||
zw:add(f[1], f[2], { method = "store" })
|
||||
end
|
||||
local merged = opts and opts.composite
|
||||
if not merged then
|
||||
local m = Types.Image.new(W, H, "rgba8")
|
||||
Blend.flatten(doc.layers, m.pixels, W, H, false)
|
||||
merged = m
|
||||
end
|
||||
local mdata, merr = png(merged :: Types.Image, "mergedimage")
|
||||
if not mdata then
|
||||
return nil, merr
|
||||
end
|
||||
zw:add("mergedimage.png", mdata, { method = "store" })
|
||||
if not (opts and opts.thumbnail == false) then
|
||||
local tdata, terr = png(thumbnail(merged :: Types.Image, 256), "thumbnail")
|
||||
if not tdata then
|
||||
return nil, terr
|
||||
end
|
||||
zw:add("Thumbnails/thumbnail.png", tdata, { method = "store" })
|
||||
end
|
||||
return zw:finish()
|
||||
end
|
||||
|
||||
return Ora
|
||||
@@ -0,0 +1,369 @@
|
||||
--!strict
|
||||
--!native
|
||||
-- layered/psd/Channels: PSD / PSB channel data. Decodes one channel (raw, PackBits RLE, ZIP, ZIP with prediction) to a
|
||||
-- plane of big-endian samples, converts planes to rgba8 for every colour mode, and PackBits-encodes rows for the
|
||||
-- writer. Adobe Photoshop File Formats Specification (2016), "Channel image data" / "Image data section".
|
||||
-- Never throws: every read is range-checked first; failures return nil, "message".
|
||||
local Deflate = require("@rosetta/codecs/compress/Deflate")
|
||||
local PackBits = require("@rosetta/codecs/compress/PackBits")
|
||||
|
||||
local Channels = {}
|
||||
|
||||
local readu8, writeu8, readu16, writeu16, readu32, writeu32 = buffer.readu8, buffer.writeu8, buffer.readu16, buffer.writeu16, buffer.readu32, buffer.writeu32
|
||||
local readf32, writef32, bcreate, bcopy, blen, bfill = buffer.readf32, buffer.writef32, buffer.create, buffer.copy, buffer.len, buffer.fill
|
||||
local floor, min, max = math.floor, math.min, math.max
|
||||
local byteswap = bit32.byteswap
|
||||
|
||||
-- rowBytes(w, depth) -> bytes per row of one channel
|
||||
function Channels.rowBytes(w: number, depth: number): number
|
||||
if depth == 1 then
|
||||
return (w + 7) // 8
|
||||
end
|
||||
return w * (depth // 8)
|
||||
end
|
||||
|
||||
-- rleCounts(src, p, limit, rows, psb) -> { counts }, offset after them | nil
|
||||
function Channels.rleCounts(src: buffer, p: number, limit: number, rows: number, psb: boolean): ({ number }?, number)
|
||||
local size = if psb then 4 else 2
|
||||
if rows < 0 or p + rows * size > limit then
|
||||
return nil, p
|
||||
end
|
||||
local counts: { number } = table.create(rows) :: { number }
|
||||
for i = 1, rows do
|
||||
if psb then
|
||||
counts[i] = byteswap(readu32(src, p))
|
||||
else
|
||||
counts[i] = readu8(src, p) * 256 + readu8(src, p + 1)
|
||||
end
|
||||
p += size
|
||||
end
|
||||
return counts, p
|
||||
end
|
||||
|
||||
-- rle(src, p, limit, counts, first, rows, rowBytes, dst, d) -> offset after the rows | nil, message
|
||||
function Channels.rle(src: buffer, p: number, limit: number, counts: { number }, first: number, rows: number, rowBytes: number, dst: buffer, d: number): (number?, string?)
|
||||
for i = 0, rows - 1 do
|
||||
local c = counts[first + i] or 0
|
||||
if p + c > limit then
|
||||
return nil, "RLE row past the end"
|
||||
end
|
||||
local _, _, clean = PackBits.decode(src, p, p + c, dst, d + i * rowBytes, rowBytes)
|
||||
if not clean then
|
||||
-- a short or overlong row: keep what decoded, zero the rest (Photoshop is lenient too)
|
||||
return nil, "bad RLE row"
|
||||
end
|
||||
p += c
|
||||
end
|
||||
return p, nil
|
||||
end
|
||||
|
||||
-- unpredict(plane, w, h, depth): undo ZIP-with-prediction deltas in place
|
||||
local function unpredict(plane: buffer, w: number, h: number, depth: number)
|
||||
if depth == 8 then
|
||||
for y = 0, h - 1 do
|
||||
local o = y * w
|
||||
local acc = readu8(plane, o)
|
||||
for x = 1, w - 1 do
|
||||
acc = (acc + readu8(plane, o + x)) % 256
|
||||
writeu8(plane, o + x, acc)
|
||||
end
|
||||
end
|
||||
elseif depth == 16 then
|
||||
for y = 0, h - 1 do
|
||||
local o = y * w * 2
|
||||
local acc = readu8(plane, o) * 256 + readu8(plane, o + 1)
|
||||
for x = 1, w - 1 do
|
||||
local q = o + x * 2
|
||||
acc = (acc + readu8(plane, q) * 256 + readu8(plane, q + 1)) % 65536
|
||||
writeu8(plane, q, acc // 256)
|
||||
writeu8(plane, q + 1, acc % 256)
|
||||
end
|
||||
end
|
||||
elseif depth == 32 then
|
||||
-- byte deltas over the row, then the row is 4 byte planes (all high bytes first)
|
||||
local rb = w * 4
|
||||
local tmp = bcreate(rb)
|
||||
for y = 0, h - 1 do
|
||||
local o = y * rb
|
||||
local acc = readu8(plane, o)
|
||||
for x = 1, rb - 1 do
|
||||
acc = (acc + readu8(plane, o + x)) % 256
|
||||
writeu8(plane, o + x, acc)
|
||||
end
|
||||
for x = 0, w - 1 do
|
||||
writeu8(tmp, x * 4, readu8(plane, o + x))
|
||||
writeu8(tmp, x * 4 + 1, readu8(plane, o + w + x))
|
||||
writeu8(tmp, x * 4 + 2, readu8(plane, o + 2 * w + x))
|
||||
writeu8(tmp, x * 4 + 3, readu8(plane, o + 3 * w + x))
|
||||
end
|
||||
bcopy(plane, o, tmp, 0, rb)
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
-- channel(src, p, limit, w, h, depth, psb) -> plane (h rows of rowBytes) | nil, message. src[p, limit) holds the
|
||||
-- 2-byte compression code and the data of one layer channel.
|
||||
function Channels.channel(src: buffer, p: number, limit: number, w: number, h: number, depth: number, psb: boolean): (buffer?, string?)
|
||||
local rb = Channels.rowBytes(w, depth)
|
||||
local plane = bcreate(rb * h)
|
||||
if w == 0 or h == 0 then
|
||||
return plane, nil
|
||||
end
|
||||
if p + 2 > limit then
|
||||
return nil, "channel data past the end"
|
||||
end
|
||||
local comp = readu8(src, p) * 256 + readu8(src, p + 1)
|
||||
p += 2
|
||||
if comp == 0 then
|
||||
if p + rb * h > limit then
|
||||
return nil, "raw channel data past the end"
|
||||
end
|
||||
bcopy(plane, 0, src, p, rb * h)
|
||||
elseif comp == 1 then
|
||||
local counts, q = Channels.rleCounts(src, p, limit, h, psb)
|
||||
if not counts then
|
||||
return nil, "RLE row counts past the end"
|
||||
end
|
||||
local ok, err = Channels.rle(src, q, limit, counts, 1, h, rb, plane, 0)
|
||||
if not ok then
|
||||
return nil, err
|
||||
end
|
||||
elseif comp == 2 or comp == 3 then
|
||||
local out, err = Deflate.zlib(src, p, limit - p, rb * h)
|
||||
if not out then
|
||||
return nil, "ZIP channel: " .. tostring(err)
|
||||
end
|
||||
plane = out
|
||||
if comp == 3 then
|
||||
unpredict(plane, w, h, depth)
|
||||
end
|
||||
else
|
||||
return nil, "unknown channel compression " .. comp
|
||||
end
|
||||
return plane, nil
|
||||
end
|
||||
|
||||
-- sample8(plane, i, depth) -> sample i as 0..255
|
||||
local function sample8(plane: buffer, i: number, depth: number): number
|
||||
if depth == 8 then
|
||||
return readu8(plane, i)
|
||||
elseif depth == 16 then
|
||||
return floor((readu8(plane, i * 2) * 256 + readu8(plane, i * 2 + 1)) / 257 + 0.5)
|
||||
elseif depth == 32 then
|
||||
local f = readf32(plane, i * 4) -- the plane holds big-endian floats: swapped by the caller
|
||||
if f ~= f then
|
||||
return 0
|
||||
end
|
||||
return floor(max(0, min(1, f)) * 255 + 0.5)
|
||||
end
|
||||
-- 1-bit (rows are padded, so this is only right for whole-byte widths; toRGBA reads bitmaps itself): 1 = black
|
||||
return if readu8(plane, i // 8) // 2 ^ (7 - i % 8) % 2 == 1 then 0 else 255
|
||||
end
|
||||
|
||||
-- swap32(plane): big-endian f32 samples to native order, in place
|
||||
function Channels.swap32(plane: buffer)
|
||||
for i = 0, blen(plane) // 4 - 1 do
|
||||
writeu32(plane, i * 4, byteswap(readu32(plane, i * 4)))
|
||||
end
|
||||
end
|
||||
|
||||
-- lab(L, a, b) 0..255 each (PSD Lab) -> sRGB r, g, b 0..255 (D50 -> D65 approximated by D65 white)
|
||||
local function srgb(c: number): number
|
||||
c = if c <= 0.0031308 then 12.92 * c else 1.055 * c ^ (1 / 2.4) - 0.055
|
||||
return floor(max(0, min(1, c)) * 255 + 0.5)
|
||||
end
|
||||
local function lab(l8: number, a8: number, b8: number): (number, number, number)
|
||||
local L = l8 * 100 / 255
|
||||
local a, b = a8 - 128, b8 - 128
|
||||
local fy = (L + 16) / 116
|
||||
local fx = fy + a / 500
|
||||
local fz = fy - b / 200
|
||||
local function f(t: number): number
|
||||
return if t > 6 / 29 then t * t * t else 3 * (6 / 29) ^ 2 * (t - 4 / 29)
|
||||
end
|
||||
local X, Y, Z = 0.95047 * f(fx), f(fy), 1.08883 * f(fz)
|
||||
local r = 3.2404542 * X - 1.5371385 * Y - 0.4985314 * Z
|
||||
local g = -0.969266 * X + 1.8760108 * Y + 0.041556 * Z
|
||||
local bl = 0.0556434 * X - 0.2040259 * Y + 1.0572252 * Z
|
||||
return srgb(r), srgb(g), srgb(bl)
|
||||
end
|
||||
|
||||
-- toRGBA(planes, w, h, depth, mode, palette?, dst?) -> rgba8 buffer. planes: { [1..k] = colour planes, alpha = plane? }
|
||||
-- mode: PSD colour mode (0 bitmap, 1 grey, 2 indexed, 3 RGB, 4 CMYK, 7 multichannel, 8 duotone, 9 Lab)
|
||||
function Channels.toRGBA(planes: { [any]: buffer }, w: number, h: number, depth: number, mode: number, palette: buffer?): buffer
|
||||
local n = w * h
|
||||
local out = bcreate(n * 4)
|
||||
local c1, c2, c3, c4 = planes[1], planes[2], planes[3], planes[4]
|
||||
local alpha = planes.alpha
|
||||
local bitmapW = (w + 7) // 8
|
||||
if depth == 8 and (mode == 3 or mode == 1) and c1 and blen(c1) >= n then
|
||||
-- the common case, without a call per sample
|
||||
local g8 = if mode == 3 and c2 and blen(c2) >= n then c2 else c1
|
||||
local b8 = if mode == 3 and c3 and blen(c3) >= n then c3 else c1
|
||||
local a8 = if alpha and blen(alpha) >= n then alpha else nil
|
||||
for i = 0, n - 1 do
|
||||
local a = if a8 then readu8(a8, i) else 255
|
||||
writeu32(out, i * 4, readu8(c1, i) + readu8(g8, i) * 256 + readu8(b8, i) * 65536 + a * 16777216)
|
||||
end
|
||||
return out
|
||||
end
|
||||
for i = 0, n - 1 do
|
||||
local r, g, b = 0, 0, 0
|
||||
if mode == 3 then
|
||||
r = if c1 then sample8(c1, i, depth) else 0
|
||||
g = if c2 then sample8(c2, i, depth) else r
|
||||
b = if c3 then sample8(c3, i, depth) else r
|
||||
elseif mode == 4 then
|
||||
local cc = if c1 then sample8(c1, i, depth) else 255
|
||||
local mm = if c2 then sample8(c2, i, depth) else 255
|
||||
local yy = if c3 then sample8(c3, i, depth) else 255
|
||||
local kk = if c4 then sample8(c4, i, depth) else 255
|
||||
r = floor(cc * kk / 255 + 0.5)
|
||||
g = floor(mm * kk / 255 + 0.5)
|
||||
b = floor(yy * kk / 255 + 0.5)
|
||||
elseif mode == 2 then
|
||||
local k = if c1 then readu8(c1, i) else 0
|
||||
if palette and blen(palette) >= 768 then
|
||||
r = readu8(palette, k)
|
||||
g = readu8(palette, 256 + k)
|
||||
b = readu8(palette, 512 + k)
|
||||
else
|
||||
r, g, b = k, k, k
|
||||
end
|
||||
elseif mode == 0 then
|
||||
local y, x = i // w, i % w
|
||||
local bit = if c1 then readu8(c1, y * bitmapW + x // 8) // 2 ^ (7 - x % 8) % 2 else 0
|
||||
r = if bit == 1 then 0 else 255
|
||||
g, b = r, r
|
||||
elseif mode == 9 then
|
||||
local L = if c1 then sample8(c1, i, depth) else 0
|
||||
local A = if c2 then sample8(c2, i, depth) else 128
|
||||
local B = if c3 then sample8(c3, i, depth) else 128
|
||||
r, g, b = lab(L, A, B)
|
||||
else -- grey, duotone, multichannel: the first channel as grey
|
||||
r = if c1 then sample8(c1, i, depth) else 0
|
||||
g, b = r, r
|
||||
end
|
||||
local a = if alpha then sample8(alpha, i, depth) else 255
|
||||
writeu32(out, i * 4, r + g * 256 + b * 65536 + a * 16777216)
|
||||
end
|
||||
return out
|
||||
end
|
||||
|
||||
-- gray8(plane, w, h, depth) -> 1 byte per pixel
|
||||
function Channels.gray8(plane: buffer, w: number, h: number, depth: number): buffer
|
||||
local n = w * h
|
||||
local out = bcreate(n)
|
||||
for i = 0, n - 1 do
|
||||
writeu8(out, i, sample8(plane, i, depth))
|
||||
end
|
||||
return out
|
||||
end
|
||||
|
||||
-- unmatte(rgba, n): Photoshop stores a transparent merged image matted with white (C * a + 255 * (1 - a)): undo it
|
||||
function Channels.unmatte(rgba: buffer, n: number)
|
||||
for i = 0, n - 1 do
|
||||
local o = i * 4
|
||||
local a = readu8(rgba, o + 3)
|
||||
if a == 0 then
|
||||
writeu32(rgba, o, 0)
|
||||
elseif a < 255 then
|
||||
local f = a / 255
|
||||
for k = 0, 2 do
|
||||
local v = (readu8(rgba, o + k) - 255 * (1 - f)) / f
|
||||
writeu8(rgba, o + k, floor(max(0, min(255, v)) + 1e-6))
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
-- matte(rgba, n) -> a copy matted with white (the writer's merged image)
|
||||
function Channels.matte(rgba: buffer, n: number): buffer
|
||||
local out = bcreate(n * 4)
|
||||
bcopy(out, 0, rgba, 0, n * 4)
|
||||
for i = 0, n - 1 do
|
||||
local o = i * 4
|
||||
local a = readu8(out, o + 3)
|
||||
if a < 255 then
|
||||
local f = a / 255
|
||||
for k = 0, 2 do
|
||||
writeu8(out, o + k, floor(readu8(out, o + k) * f + 255 * (1 - f) + 0.5))
|
||||
end
|
||||
end
|
||||
end
|
||||
return out
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ writer helpers
|
||||
-- packRow(src, o, n, out, d) -> bytes written: PackBits of src[o, o + n) into out at d (out needs n + n // 128 + 1)
|
||||
function Channels.packRow(src: buffer, o: number, n: number, out: buffer, d: number): number
|
||||
local start = d
|
||||
local i = 0
|
||||
while i < n do
|
||||
-- a run of at least 3 equal bytes?
|
||||
local v = readu8(src, o + i)
|
||||
local run = 1
|
||||
while i + run < n and run < 128 and readu8(src, o + i + run) == v do
|
||||
run += 1
|
||||
end
|
||||
if run >= 3 then
|
||||
writeu8(out, d, 257 - run)
|
||||
writeu8(out, d + 1, v)
|
||||
d += 2
|
||||
i += run
|
||||
else
|
||||
-- literals up to the next run of 3
|
||||
local j = i
|
||||
while j < n and j - i < 128 do
|
||||
if j + 2 < n and readu8(src, o + j) == readu8(src, o + j + 1) and readu8(src, o + j) == readu8(src, o + j + 2) then
|
||||
break
|
||||
end
|
||||
j += 1
|
||||
end
|
||||
local c = j - i
|
||||
writeu8(out, d, c - 1)
|
||||
bcopy(out, d + 1, src, o + i, c)
|
||||
d += c + 1
|
||||
i = j
|
||||
end
|
||||
end
|
||||
return d - start
|
||||
end
|
||||
|
||||
-- planes8(rgba, w, h) -> r, g, b, a planes (1 byte per pixel each)
|
||||
function Channels.planes8(rgba: buffer, w: number, h: number): (buffer, buffer, buffer, buffer)
|
||||
local n = w * h
|
||||
local r, g, b, a = bcreate(n), bcreate(n), bcreate(n), bcreate(n)
|
||||
if blen(rgba) < n * 4 then
|
||||
return r, g, b, a
|
||||
end
|
||||
for i = 0, n - 1 do
|
||||
local v = readu32(rgba, i * 4)
|
||||
writeu8(r, i, v % 256)
|
||||
writeu8(g, i, v // 256 % 256)
|
||||
writeu8(b, i, v // 65536 % 256)
|
||||
writeu8(a, i, v // 16777216)
|
||||
end
|
||||
return r, g, b, a
|
||||
end
|
||||
|
||||
-- rleChannel(plane, w, h, psb) -> the RLE data of one channel (counts, then rows), without the compression code
|
||||
function Channels.rleChannel(plane: buffer, w: number, h: number, psb: boolean): buffer
|
||||
local cs = if psb then 4 else 2
|
||||
local out = bcreate(h * cs + h * (w + w // 128 + 2))
|
||||
local d = h * cs
|
||||
for y = 0, h - 1 do
|
||||
local n = Channels.packRow(plane, y * w, w, out, d)
|
||||
if psb then
|
||||
writeu32(out, y * 4, byteswap(n))
|
||||
else
|
||||
writeu16(out, y * 2, byteswap(n) // 65536)
|
||||
end
|
||||
d += n
|
||||
end
|
||||
local res = bcreate(d)
|
||||
bcopy(res, 0, out, 0, d)
|
||||
return res
|
||||
end
|
||||
|
||||
return Channels
|
||||
@@ -0,0 +1,743 @@
|
||||
--!strict
|
||||
-- layered/psd: Adobe Photoshop PSD and PSB (Adobe Photoshop File Formats Specification, 2016). Supports: decode of
|
||||
-- bitmap, greyscale, indexed, RGB, CMYK, Lab, duotone and multichannel documents at 1 / 8 / 16 / 32 bits; layers
|
||||
-- (raw, PackBits RLE, ZIP and ZIP-with-prediction channels; 16 / 32-bit layers in Lr16 / Lr32), their blend mode,
|
||||
-- opacity, fill opacity (iOpa), visibility, clipping, Unicode names (luni), user masks (as grey masks), groups (lsct /
|
||||
-- lsdk section dividers -> group layers with children; pass-through kept as the "passThrough" blend); the merged image
|
||||
-- (meta.composite); image resources (meta.resources, ICC profile in meta.icc). Everything converts to rgba8.
|
||||
-- Encode: an 8-bit RGB PSD (PSB when a side is over 30000) with the RLE merged composite (ops-free: codecs/image/Blend
|
||||
-- flattens the tree, or opts.composite) and every layer as RLE RGBA channels, groups as section dividers, masks,
|
||||
-- clipping, opacity / fill, hidden flags and Unicode names.
|
||||
-- Not supported: adjustment / fill / type / smart-object layer contents (their pixels, if any, are used), layer
|
||||
-- effects, vector masks, colour management, 16 / 32-bit or non-RGB output.
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ requires
|
||||
local Err = require("@rosetta/core/Err")
|
||||
local Bytes = require("@rosetta/core/Bytes")
|
||||
local Types = require("@rosetta/Types")
|
||||
local Text = require("@rosetta/codecs/text/Text")
|
||||
local Blend = require("@rosetta/codecs/image/Blend")
|
||||
local Channels = require("@rosetta/layered/psd/Channels")
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ contract
|
||||
local Psd = {
|
||||
name = "psd",
|
||||
category = "layered",
|
||||
extensions = { "psd", "psb" },
|
||||
mime = { "image/vnd.adobe.photoshop" },
|
||||
deps = { "core/Err", "core/Bytes", "Types", "codecs/image/Blend", "codecs/compress/Deflate", "codecs/compress/PackBits", "codecs/text/Text" },
|
||||
caps = { decode = true, encode = true, layers = true, groups = true, depths = { 1, 8, 16, 32 } },
|
||||
}
|
||||
|
||||
export type DecodeOptions = {
|
||||
layers: boolean?, -- read the layers (default true; false reads only the merged image)
|
||||
maxPixels: number?, -- refuse documents / layers larger than this (default 2^26)
|
||||
maxLayers: number?, -- default 10000
|
||||
}
|
||||
export type EncodeOptions = {
|
||||
composite: Types.Image?, -- the merged image to store (default: the layers flattened with codecs/image/Blend)
|
||||
}
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ constants
|
||||
local BLEND_KEYS: { [string]: string } = {
|
||||
norm = "normal",
|
||||
diss = "dissolve",
|
||||
dark = "darken",
|
||||
["mul "] = "multiply",
|
||||
idiv = "colorBurn",
|
||||
lbrn = "linearBurn",
|
||||
dkCl = "darkerColor",
|
||||
lite = "lighten",
|
||||
scrn = "screen",
|
||||
["div "] = "colorDodge",
|
||||
lddg = "linearDodge",
|
||||
lgCl = "lighterColor",
|
||||
over = "overlay",
|
||||
sLit = "softLight",
|
||||
hLit = "hardLight",
|
||||
vLit = "vividLight",
|
||||
lLit = "linearLight",
|
||||
pLit = "pinLight",
|
||||
hMix = "hardMix",
|
||||
diff = "difference",
|
||||
smud = "exclusion",
|
||||
fsub = "subtract",
|
||||
fdiv = "divide",
|
||||
["hue "] = "hue",
|
||||
["sat "] = "saturation",
|
||||
colr = "color",
|
||||
["lum "] = "luminosity",
|
||||
pass = "passThrough",
|
||||
}
|
||||
local BLEND_NAMES: { [string]: string } = {}
|
||||
for k, v in BLEND_KEYS do
|
||||
BLEND_NAMES[v] = k
|
||||
end
|
||||
BLEND_NAMES.add = "lddg"
|
||||
|
||||
-- colour channels per mode (the rest are alpha / spot channels)
|
||||
local COLOR_CHANNELS = { [0] = 1, [1] = 1, [2] = 1, [3] = 3, [4] = 4, [7] = 1, [8] = 1, [9] = 3 }
|
||||
local MODE_NAMES = { [0] = "bitmap", [1] = "gray", [2] = "indexed", [3] = "rgb", [4] = "cmyk", [7] = "multichannel", [8] = "duotone", [9] = "lab" }
|
||||
-- additional layer info keys with 8-byte lengths in PSB
|
||||
local LONG_KEYS = { LMsk = true, Lr16 = true, Lr32 = true, Layr = true, Mt16 = true, Mt32 = true, Mtrn = true, Alph = true, FMsk = true, lnk2 = true, FEid = true, FXid = true, PxSD = true }
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ sniff
|
||||
function Psd.sniff(r: Bytes.Reader): number
|
||||
local h = r:peek(6)
|
||||
if string.sub(h, 1, 4) == "8BPS" and (string.sub(h, 5, 6) == "\0\1" or string.sub(h, 5, 6) == "\0\2") then
|
||||
return 1
|
||||
end
|
||||
return 0
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ decode
|
||||
type Ctx = { psb: boolean, depth: number, mode: number, maxPixels: number, maxLayers: number }
|
||||
|
||||
local function len(r: Bytes.Reader, psb: boolean): number
|
||||
return if psb then r:u64be() else r:u32be()
|
||||
end
|
||||
|
||||
local function utf16be(s: string): string
|
||||
return (string.gsub(Text.utf16(buffer.fromstring(s), 0, #s, true), "%z", ""))
|
||||
end
|
||||
|
||||
-- the layer records + channel data at r (a Reader over the layer info, after its length): flat records | nil, Err
|
||||
local function layerRecords(r: Bytes.Reader, c: Ctx): ({ any }?, boolean, Err.Err?)
|
||||
local count = r:i16be()
|
||||
local absAlpha = count < 0
|
||||
count = math.abs(count)
|
||||
if r.err then
|
||||
return nil, absAlpha, r.err
|
||||
end
|
||||
if count > c.maxLayers then
|
||||
return nil, absAlpha, Err.new(Err.LIMIT, "over " .. c.maxLayers .. " layers")
|
||||
end
|
||||
local recs = {}
|
||||
for li = 1, count do
|
||||
local top, left, bottom, right = r:i32be(), r:i32be(), r:i32be(), r:i32be()
|
||||
local nch = r:u16be()
|
||||
if r.err then
|
||||
return nil, absAlpha, r.err
|
||||
end
|
||||
if nch > 56 then
|
||||
return nil, absAlpha, Err.new(Err.CORRUPT, "layer " .. li .. ": " .. nch .. " channels", r.pos)
|
||||
end
|
||||
local chans = {}
|
||||
for k = 1, nch do
|
||||
chans[k] = { id = r:i16be(), size = len(r, c.psb) }
|
||||
end
|
||||
if r:string(4) ~= "8BIM" and not r.err then
|
||||
return nil, absAlpha, Err.new(Err.CORRUPT, "layer " .. li .. ": bad blend mode signature", r.pos - 4)
|
||||
end
|
||||
local key = r:string(4)
|
||||
local opacity, clipping, flags = r:u8(), r:u8(), r:u8()
|
||||
r:skip(1)
|
||||
local extraLen = r:u32be()
|
||||
if r.err then
|
||||
return nil, absAlpha, r.err
|
||||
end
|
||||
local ex = r:slice(extraLen)
|
||||
local rec: { [string]: any } = {
|
||||
top = top,
|
||||
left = left,
|
||||
bottom = bottom,
|
||||
right = right,
|
||||
chans = chans,
|
||||
blend = BLEND_KEYS[key] or "normal",
|
||||
blendKey = key,
|
||||
opacity = opacity / 255,
|
||||
clip = clipping ~= 0,
|
||||
hidden = bit32.band(flags, 2) ~= 0,
|
||||
flags = flags,
|
||||
}
|
||||
-- mask data
|
||||
local ml = ex:u32be()
|
||||
if ml > 0 then
|
||||
local mr = ex:slice(ml)
|
||||
if ml >= 18 then
|
||||
rec.mask = { top = mr:i32be(), left = mr:i32be(), bottom = mr:i32be(), right = mr:i32be(), default = mr:u8(), flags = mr:u8() }
|
||||
end
|
||||
end
|
||||
-- blending ranges
|
||||
ex:skip(ex:u32be())
|
||||
-- name: Pascal string padded to 4
|
||||
local nl = ex:u8()
|
||||
rec.name = ex:string(nl)
|
||||
ex:skip((4 - (nl + 1) % 4) % 4)
|
||||
-- additional layer info
|
||||
while ex:remaining() >= 12 do
|
||||
local sig = ex:string(4)
|
||||
if sig ~= "8BIM" and sig ~= "8B64" then
|
||||
break
|
||||
end
|
||||
local k = ex:string(4)
|
||||
local l = if c.psb and LONG_KEYS[k] then ex:u64be() else ex:u32be()
|
||||
if ex.err then
|
||||
break
|
||||
end
|
||||
local d = ex:slice(l)
|
||||
if k == "luni" then
|
||||
local n = d:u32be()
|
||||
local s = d:string(math.min(n * 2, d:remaining()))
|
||||
rec.name = utf16be(s)
|
||||
elseif k == "lsct" or k == "lsdk" then
|
||||
rec.section = d:u32be()
|
||||
if d:remaining() >= 8 and d:string(4) == "8BIM" then
|
||||
rec.sectionBlend = d:string(4)
|
||||
end
|
||||
elseif k == "iOpa" then
|
||||
rec.fill = d:u8() / 255
|
||||
elseif k == "lyid" then
|
||||
rec.id = d:u32be()
|
||||
end
|
||||
end
|
||||
if r.err then
|
||||
return nil, absAlpha, r.err
|
||||
end
|
||||
recs[li] = rec
|
||||
end
|
||||
-- channel image data
|
||||
local b = r.buf
|
||||
for li, rec in recs do
|
||||
local w, h = rec.right - rec.left, rec.bottom - rec.top
|
||||
if w < 0 or h < 0 or w > 300000 or h > 300000 then
|
||||
return nil, absAlpha, Err.new(Err.CORRUPT, "layer " .. li .. ": bad bounds", r.pos)
|
||||
end
|
||||
if w * h > c.maxPixels then
|
||||
return nil, absAlpha, Err.new(Err.LIMIT, string.format("layer %d: %d x %d is over the pixel limit", li, w, h))
|
||||
end
|
||||
local planes: { [any]: buffer } = {}
|
||||
for _, ch in rec.chans do
|
||||
local p = r.pos
|
||||
if ch.size < 0 or p + ch.size > r.limit then
|
||||
return nil, absAlpha, Err.new(Err.TRUNCATED, "layer " .. li .. ": channel data past the end", p)
|
||||
end
|
||||
r.pos = p + ch.size
|
||||
local cw, chh = w, h
|
||||
if ch.id == -2 or ch.id == -3 then
|
||||
local m = rec.mask
|
||||
if not m then
|
||||
continue
|
||||
end
|
||||
cw, chh = m.right - m.left, m.bottom - m.top
|
||||
if cw < 0 or chh < 0 or cw * chh > c.maxPixels then
|
||||
continue
|
||||
end
|
||||
end
|
||||
if ch.size < 2 then
|
||||
continue -- an empty channel
|
||||
end
|
||||
local plane, perr = Channels.channel(b, p, p + ch.size, cw, chh, c.depth, c.psb)
|
||||
if not plane then
|
||||
return nil, absAlpha, Err.new(Err.CORRUPT, "layer " .. li .. " channel " .. ch.id .. ": " .. tostring(perr), p)
|
||||
end
|
||||
if c.depth == 32 then
|
||||
Channels.swap32(plane)
|
||||
end
|
||||
if ch.id == -1 then
|
||||
planes.alpha = plane
|
||||
elseif ch.id == -2 then
|
||||
rec.maskPlane = Channels.gray8(plane, cw, chh, c.depth)
|
||||
elseif ch.id >= 0 and ch.id < 56 then
|
||||
planes[ch.id + 1] = plane
|
||||
end
|
||||
end
|
||||
local img = Types.Image.new(w, h)
|
||||
if w > 0 and h > 0 then
|
||||
img.pixels = Channels.toRGBA(planes, w, h, c.depth, c.mode, nil)
|
||||
end
|
||||
rec.image = img
|
||||
end
|
||||
return recs, absAlpha, nil
|
||||
end
|
||||
|
||||
-- records (bottom to top) -> a layer tree
|
||||
local function tree(recs: { any }): { Types.Layer }
|
||||
local root: { Types.Layer } = {}
|
||||
local stack: { { Types.Layer } } = {}
|
||||
local cur = root
|
||||
local function layerOf(rec: any): Types.Layer
|
||||
local l: any = {
|
||||
name = rec.name,
|
||||
image = rec.image,
|
||||
x = rec.left,
|
||||
y = rec.top,
|
||||
opacity = rec.opacity,
|
||||
blend = rec.blend,
|
||||
visible = not rec.hidden,
|
||||
}
|
||||
if rec.clip then
|
||||
l.clip = true
|
||||
end
|
||||
if rec.fill and rec.fill < 1 then
|
||||
l.fillOpacity = rec.fill
|
||||
end
|
||||
if rec.id then
|
||||
l.id = rec.id
|
||||
end
|
||||
if rec.mask and rec.maskPlane then
|
||||
local m = rec.mask
|
||||
local mi = Types.Image.new(m.right - m.left, m.bottom - m.top, "gray8")
|
||||
mi.pixels = rec.maskPlane
|
||||
l.mask = { image = mi, x = m.left, y = m.top, default = m.default, disabled = bit32.band(m.flags, 2) ~= 0 }
|
||||
end
|
||||
return l
|
||||
end
|
||||
for _, rec in recs do
|
||||
local s = rec.section
|
||||
if s == 3 then
|
||||
table.insert(stack, cur)
|
||||
cur = {}
|
||||
elseif s == 1 or s == 2 then
|
||||
local g = layerOf(rec)
|
||||
g.image = Types.Image.new(0, 0)
|
||||
g.children = cur
|
||||
if rec.sectionBlend and BLEND_KEYS[rec.sectionBlend] then
|
||||
g.blend = BLEND_KEYS[rec.sectionBlend]
|
||||
end
|
||||
;(g :: any).collapsed = s == 2
|
||||
cur = table.remove(stack) or root
|
||||
table.insert(cur, g)
|
||||
else
|
||||
table.insert(cur, layerOf(rec))
|
||||
end
|
||||
end
|
||||
-- unbalanced dividers: splice the open groups' layers back in
|
||||
while #stack > 0 do
|
||||
local parent = table.remove(stack) :: { Types.Layer }
|
||||
for _, l in cur do
|
||||
table.insert(parent, l)
|
||||
end
|
||||
cur = parent
|
||||
end
|
||||
return cur
|
||||
end
|
||||
|
||||
function Psd.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Layered?, Err.Err?)
|
||||
local o: DecodeOptions = opts or {}
|
||||
local c: Ctx = { psb = false, depth = 8, mode = 3, maxPixels = o.maxPixels or 2 ^ 26, maxLayers = o.maxLayers or 10000 }
|
||||
if Psd.sniff(r) == 0 then
|
||||
return nil, Err.new(Err.CORRUPT, "not a PSD (bad signature)", r.pos)
|
||||
end
|
||||
r:skip(4)
|
||||
local version = r:u16be()
|
||||
r:skip(6)
|
||||
local nch, h, w, depth, mode = r:u16be(), r:u32be(), r:u32be(), r:u16be(), r:u16be()
|
||||
if r.err then
|
||||
return nil, r.err
|
||||
end
|
||||
c.psb, c.depth, c.mode = version == 2, depth, mode
|
||||
if nch < 1 or nch > 56 then
|
||||
return nil, Err.new(Err.CORRUPT, "bad channel count " .. nch)
|
||||
end
|
||||
local maxSide = if c.psb then 300000 else 30000
|
||||
if w < 1 or h < 1 or w > maxSide or h > maxSide then
|
||||
return nil, Err.new(Err.CORRUPT, string.format("bad size %d x %d", w, h))
|
||||
end
|
||||
if not (depth == 1 or depth == 8 or depth == 16 or depth == 32) then
|
||||
return nil, Err.new(Err.CORRUPT, "bad depth " .. depth)
|
||||
end
|
||||
if COLOR_CHANNELS[mode] == nil then
|
||||
return nil, Err.new(Err.CORRUPT, "bad colour mode " .. mode)
|
||||
end
|
||||
if (mode == 0) ~= (depth == 1) then
|
||||
return nil, Err.new(Err.UNSUPPORTED, "1-bit data outside bitmap mode")
|
||||
end
|
||||
if w * h > c.maxPixels then
|
||||
return nil, Err.new(Err.LIMIT, string.format("%d x %d is over the %d pixel limit", w, h, c.maxPixels))
|
||||
end
|
||||
local layered = Types.Layered.new(w, h)
|
||||
-- colour mode data
|
||||
local cm = r:slice(r:u32be())
|
||||
local palette: buffer? = nil
|
||||
if mode == 2 and cm:size() >= 768 then
|
||||
palette = cm:bytes(768)
|
||||
local pal = {}
|
||||
for i = 0, 255 do
|
||||
pal[i + 1] = { buffer.readu8(palette :: buffer, i), buffer.readu8(palette :: buffer, 256 + i), buffer.readu8(palette :: buffer, 512 + i), 255 }
|
||||
end
|
||||
layered.meta.palette = pal
|
||||
end
|
||||
-- image resources
|
||||
local rr = r:slice(r:u32be())
|
||||
if r.err then
|
||||
return nil, r.err
|
||||
end
|
||||
local resources = {}
|
||||
while rr:remaining() >= 12 and rr:string(4) == "8BIM" do
|
||||
local id = rr:u16be()
|
||||
local nl = rr:u8()
|
||||
local name = rr:string(nl)
|
||||
rr:skip((nl + 1) % 2)
|
||||
local size = rr:u32be()
|
||||
if rr.err or size > rr:remaining() then
|
||||
break
|
||||
end
|
||||
local data = rr:bytes(size)
|
||||
rr:skip(size % 2)
|
||||
table.insert(resources, { id = id, name = name, data = data })
|
||||
if id == 0x040F then
|
||||
layered.meta.icc = data
|
||||
end
|
||||
end
|
||||
layered.meta.resources = resources
|
||||
-- layer and mask information
|
||||
local lm = r:slice(len(r, c.psb))
|
||||
if r.err then
|
||||
return nil, r.err
|
||||
end
|
||||
local recs: { any }? = nil
|
||||
local absAlpha = false
|
||||
if o.layers ~= false and lm:size() > 0 then
|
||||
local liLen = len(lm, c.psb)
|
||||
local li = lm:slice(liLen)
|
||||
if lm.err then
|
||||
return nil, lm.err
|
||||
end
|
||||
if liLen > 0 then
|
||||
local list, aa, lerr = layerRecords(li, c)
|
||||
if not list then
|
||||
return nil, lerr
|
||||
end
|
||||
recs, absAlpha = list, aa
|
||||
end
|
||||
-- global layer mask info, then additional info (16 / 32-bit layers live in Lr16 / Lr32)
|
||||
lm:skip(lm:u32be())
|
||||
while not lm.err and lm:remaining() >= 12 do
|
||||
local sig = lm:string(4)
|
||||
if sig ~= "8BIM" and sig ~= "8B64" then
|
||||
break
|
||||
end
|
||||
local k = lm:string(4)
|
||||
local l = if c.psb and LONG_KEYS[k] then lm:u64be() else lm:u32be()
|
||||
if lm.err then
|
||||
break
|
||||
end
|
||||
local d = lm:slice(l)
|
||||
if (k == "Lr16" or k == "Lr32" or k == "Layr") and recs == nil then
|
||||
local list, aa, lerr = layerRecords(d, c)
|
||||
if not list then
|
||||
return nil, lerr
|
||||
end
|
||||
recs, absAlpha = list, aa
|
||||
end
|
||||
lm:align(4)
|
||||
end
|
||||
end
|
||||
if recs then
|
||||
layered.layers = tree(recs)
|
||||
end
|
||||
-- the merged image
|
||||
local comp = r:u16be()
|
||||
if r.err then
|
||||
return nil, r.err
|
||||
end
|
||||
local cc = COLOR_CHANNELS[mode]
|
||||
if mode == 7 then
|
||||
cc = math.min(nch, 3)
|
||||
end
|
||||
local useAlpha = nch > cc and (absAlpha or recs == nil) and mode ~= 7
|
||||
local nread = math.min(nch, cc + (if useAlpha then 1 else 0))
|
||||
local rb = Channels.rowBytes(w, depth)
|
||||
local planes: { [any]: buffer } = {}
|
||||
local b = r.buf
|
||||
if comp == 0 then
|
||||
for k = 1, nread do
|
||||
local p = r.pos + (k - 1) * rb * h
|
||||
if p + rb * h > r.limit then
|
||||
return nil, Err.new(Err.TRUNCATED, "merged image past the end", p)
|
||||
end
|
||||
local plane = buffer.create(rb * h)
|
||||
buffer.copy(plane, 0, b, p, rb * h)
|
||||
planes[k] = plane
|
||||
end
|
||||
elseif comp == 1 then
|
||||
local counts, q = Channels.rleCounts(b, r.pos, r.limit, h * nch, c.psb)
|
||||
if not counts then
|
||||
return nil, Err.new(Err.TRUNCATED, "merged image row counts past the end", r.pos)
|
||||
end
|
||||
local p: number = q
|
||||
for k = 1, nread do
|
||||
local plane = buffer.create(rb * h)
|
||||
local np, perr = Channels.rle(b, p, r.limit, counts, (k - 1) * h + 1, h, rb, plane, 0)
|
||||
if not np then
|
||||
return nil, Err.new(Err.CORRUPT, "merged image: " .. tostring(perr), p)
|
||||
end
|
||||
p = np
|
||||
planes[k] = plane
|
||||
end
|
||||
elseif comp == 2 or comp == 3 then
|
||||
-- one zlib stream per channel would be Channels.channel; Photoshop writes all channels in one stream
|
||||
local all = Channels.channel(b, r.pos - 2, r.limit, w, h * nread, depth, c.psb)
|
||||
if not all then
|
||||
return nil, Err.new(Err.CORRUPT, "merged image: bad ZIP data", r.pos)
|
||||
end
|
||||
for k = 1, nread do
|
||||
local plane = buffer.create(rb * h)
|
||||
buffer.copy(plane, 0, all, (k - 1) * rb * h, rb * h)
|
||||
planes[k] = plane
|
||||
end
|
||||
else
|
||||
return nil, Err.new(Err.CORRUPT, "bad merged image compression " .. comp)
|
||||
end
|
||||
if useAlpha then
|
||||
planes.alpha = planes[cc + 1]
|
||||
planes[cc + 1] = nil :: any
|
||||
end
|
||||
if depth == 32 then
|
||||
for _, p in planes do
|
||||
Channels.swap32(p)
|
||||
end
|
||||
end
|
||||
local composite = Types.Image.new(w, h)
|
||||
composite.pixels = Channels.toRGBA(planes, w, h, depth, mode, palette)
|
||||
if planes.alpha then
|
||||
Channels.unmatte(composite.pixels, w * h)
|
||||
end
|
||||
composite.meta.source = { format = "psd", bitDepth = depth, colorType = MODE_NAMES[mode] }
|
||||
layered.meta.composite = composite
|
||||
layered.meta.source = { format = "psd", version = version, bitDepth = depth, colorMode = MODE_NAMES[mode], channels = nch, psb = c.psb }
|
||||
return layered, nil
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ encode
|
||||
type Rec = { layer: any, section: number?, name: string }
|
||||
|
||||
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 buffer.len(v.pixels) >= v.width * v.height * 4
|
||||
end
|
||||
|
||||
local function pascal(name: string): string
|
||||
local s = string.gsub(name, "[\128-\255]", "?")
|
||||
s = string.sub(s, 1, 255)
|
||||
local pad = (4 - (#s + 1) % 4) % 4
|
||||
return string.char(#s) .. s .. string.rep("\0", pad)
|
||||
end
|
||||
|
||||
local function block(w: Bytes.Writer, key: string, data: string)
|
||||
w:string("8BIM")
|
||||
w:string(key)
|
||||
local pad = (4 - #data % 4) % 4 -- additional info is padded to 4
|
||||
w:u32be(#data + pad)
|
||||
w:string(data)
|
||||
w:fill(0, pad)
|
||||
end
|
||||
|
||||
local function u32s(v: number): string
|
||||
return string.char(v // 16777216 % 256, v // 65536 % 256, v // 256 % 256, v % 256)
|
||||
end
|
||||
|
||||
local function luni(name: string): string
|
||||
local out = {}
|
||||
local n = 0
|
||||
for _, cp in utf8.codes(name) do
|
||||
if cp >= 0x10000 then
|
||||
local v = cp - 0x10000
|
||||
local hi, lo = 0xD800 + v // 1024, 0xDC00 + v % 1024
|
||||
table.insert(out, string.char(hi // 256, hi % 256, lo // 256, lo % 256))
|
||||
n += 2
|
||||
else
|
||||
table.insert(out, string.char(cp // 256, cp % 256))
|
||||
n += 1
|
||||
end
|
||||
end
|
||||
return u32s(n) .. table.concat(out)
|
||||
end
|
||||
|
||||
function Psd.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 > 300000 or H > 300000 then
|
||||
return nil, Err.new(Err.ARG, "bad document size")
|
||||
end
|
||||
local psb = W > 30000 or H > 30000
|
||||
-- the records, bottom to top
|
||||
local recs: { Rec } = {}
|
||||
local bad: string? = nil
|
||||
local function walk(list: { any }, depth: number)
|
||||
for _, l in list do
|
||||
if type(l) ~= "table" then
|
||||
bad = "a layer is not a table"
|
||||
return
|
||||
end
|
||||
if type(l.children) == "table" then
|
||||
if depth > 64 then
|
||||
bad = "groups nested too deep"
|
||||
return
|
||||
end
|
||||
table.insert(recs, { layer = l, section = 3, name = "</Layer group>" })
|
||||
walk(l.children, depth + 1)
|
||||
table.insert(recs, { layer = l, section = if l.collapsed then 2 else 1, name = tostring(l.name or "Group") })
|
||||
else
|
||||
if not isImage(l.image) then
|
||||
bad = "layer " .. tostring(l.name) .. ": needs an rgba8 image"
|
||||
return
|
||||
end
|
||||
table.insert(recs, { layer = l, name = tostring(l.name or "Layer") })
|
||||
end
|
||||
end
|
||||
end
|
||||
walk(layered.layers, 0)
|
||||
if bad then
|
||||
return nil, Err.new(Err.ARG, bad :: string)
|
||||
end
|
||||
if #recs > 32767 then
|
||||
return nil, Err.new(Err.ARG, "too many layers")
|
||||
end
|
||||
local function lenW(w: Bytes.Writer, v: number)
|
||||
if psb then
|
||||
w:u64be(v)
|
||||
else
|
||||
w:u32be(v)
|
||||
end
|
||||
end
|
||||
-- layer records and channel data
|
||||
local info = Bytes.writer(4096)
|
||||
local data = Bytes.writer(65536)
|
||||
info:i16be(-#recs) -- negative: the merged image's first alpha channel is its transparency
|
||||
for _, rec in recs do
|
||||
local l = rec.layer
|
||||
local img = if rec.section then nil else l.image
|
||||
local x, y = math.floor(tonumber(l.x) or 0), math.floor(tonumber(l.y) or 0)
|
||||
local w, h = if img then img.width else 0, if img then img.height else 0
|
||||
if rec.section then
|
||||
x, y = 0, 0
|
||||
end
|
||||
info:i32be(y)
|
||||
info:i32be(x)
|
||||
info:i32be(y + h)
|
||||
info:i32be(x + w)
|
||||
local chans: { { id: number, data: buffer } } = {}
|
||||
if img and w > 0 and h > 0 then
|
||||
local pr, pg, pb, pa = Channels.planes8(img.pixels, w, h)
|
||||
chans = {
|
||||
{ id = -1, data = Channels.rleChannel(pa, w, h, psb) },
|
||||
{ id = 0, data = Channels.rleChannel(pr, w, h, psb) },
|
||||
{ id = 1, data = Channels.rleChannel(pg, w, h, psb) },
|
||||
{ id = 2, data = Channels.rleChannel(pb, w, h, psb) },
|
||||
}
|
||||
else
|
||||
chans = { { id = -1, data = buffer.create(0) }, { id = 0, data = buffer.create(0) }, { id = 1, data = buffer.create(0) }, { id = 2, data = buffer.create(0) } }
|
||||
end
|
||||
-- the mask
|
||||
local m = if rec.section == nil and type(l.mask) == "table" and type(l.mask.image) == "table" and type(l.mask.image.pixels) == "buffer" then l.mask else nil
|
||||
local mw, mh = 0, 0
|
||||
if m then
|
||||
local mi = m.image
|
||||
mw, mh = mi.width, mi.height
|
||||
local plane = mi.pixels
|
||||
if mi.format == "rgba8" then
|
||||
plane = (Channels.planes8(mi.pixels, mw, mh))
|
||||
elseif mi.format ~= "gray8" and mi.format ~= "alpha8" then
|
||||
return nil, Err.new(Err.ARG, "mask images are gray8 / alpha8 / rgba8")
|
||||
end
|
||||
if buffer.len(plane) < mw * mh then
|
||||
return nil, Err.new(Err.ARG, "bad mask image")
|
||||
end
|
||||
table.insert(chans, { id = -2, data = Channels.rleChannel(plane, mw, mh, psb) })
|
||||
end
|
||||
info:u16be(#chans)
|
||||
for _, ch in chans do
|
||||
info:i16be(ch.id)
|
||||
lenW(info, buffer.len(ch.data) + 2)
|
||||
data:u16be(if buffer.len(ch.data) > 0 then 1 else 0)
|
||||
data:bytes(ch.data)
|
||||
end
|
||||
info:string("8BIM")
|
||||
local blend = if type(l.blend) == "string" then l.blend else "normal"
|
||||
local key = BLEND_NAMES[blend] or "norm"
|
||||
if rec.section and rec.section ~= 3 then
|
||||
key = if blend == "passThrough" then "pass" else key
|
||||
end
|
||||
info:string(key)
|
||||
info:u8(math.clamp(math.floor((tonumber(l.opacity) or 1) * 255 + 0.5), 0, 255))
|
||||
info:u8(if l.clip and rec.section == nil then 1 else 0)
|
||||
local flags = 8 -- bit 3: bit 4 is meaningful
|
||||
if l.visible == false and rec.section ~= 3 then
|
||||
flags += 2
|
||||
end
|
||||
if rec.section then
|
||||
flags += 16 -- pixel data irrelevant to the appearance
|
||||
end
|
||||
info:u8(flags)
|
||||
info:u8(0)
|
||||
local ex = Bytes.writer(256)
|
||||
if m then
|
||||
ex:u32be(20)
|
||||
local mx, my = math.floor(tonumber(m.x) or 0), math.floor(tonumber(m.y) or 0)
|
||||
ex:i32be(my)
|
||||
ex:i32be(mx)
|
||||
ex:i32be(my + mh)
|
||||
ex:i32be(mx + mw)
|
||||
ex:u8(math.clamp(math.floor(tonumber(m.default) or 0), 0, 255))
|
||||
ex:u8(if m.disabled then 2 else 0)
|
||||
ex:u16be(0)
|
||||
else
|
||||
ex:u32be(0)
|
||||
end
|
||||
ex:u32be(0) -- blending ranges
|
||||
ex:string(pascal(rec.name))
|
||||
block(ex, "luni", luni(rec.name))
|
||||
if rec.section then
|
||||
block(ex, "lsct", u32s(rec.section) .. (if rec.section ~= 3 then "8BIM" .. key else ""))
|
||||
end
|
||||
local fill = tonumber(l.fillOpacity)
|
||||
if fill and fill < 1 and rec.section == nil then
|
||||
block(ex, "iOpa", string.char(math.clamp(math.floor(fill * 255 + 0.5), 0, 255)) .. "\0\0\0")
|
||||
end
|
||||
local exb = ex:finish()
|
||||
info:u32be(buffer.len(exb))
|
||||
info:bytes(exb)
|
||||
end
|
||||
info:bytes(data:finish())
|
||||
if info:tell() % 2 == 1 then
|
||||
info:u8(0)
|
||||
end
|
||||
local infoB = info:finish()
|
||||
-- the merged image
|
||||
local comp: Types.Image? = opts and opts.composite
|
||||
if comp ~= nil and (not isImage(comp) or comp.width ~= W or comp.height ~= H) then
|
||||
return nil, Err.new(Err.ARG, "opts.composite must be a " .. W .. " x " .. H .. " rgba8 Image")
|
||||
end
|
||||
local merged: buffer
|
||||
if comp then
|
||||
merged = comp.pixels
|
||||
else
|
||||
merged = buffer.create(W * H * 4)
|
||||
Blend.flatten(layered.layers, merged, W, H, false)
|
||||
end
|
||||
local out = Bytes.writer(buffer.len(infoB) + W * H * 4 + 1024)
|
||||
out:string("8BPS")
|
||||
out:u16be(if psb then 2 else 1)
|
||||
out:fill(0, 6)
|
||||
out:u16be(4)
|
||||
out:u32be(H)
|
||||
out:u32be(W)
|
||||
out:u16be(8)
|
||||
out:u16be(3)
|
||||
out:u32be(0) -- colour mode data
|
||||
out:u32be(0) -- image resources
|
||||
local lmLen = (if psb then 8 else 4) + buffer.len(infoB) + 4
|
||||
lenW(out, lmLen)
|
||||
lenW(out, buffer.len(infoB))
|
||||
out:bytes(infoB)
|
||||
out:u32be(0) -- global layer mask info
|
||||
-- merged: RLE, all row counts first
|
||||
out:u16be(1)
|
||||
local pr, pg, pb, pa = Channels.planes8(Channels.matte(merged, W * H), W, H)
|
||||
local cs = if psb then 4 else 2
|
||||
local parts = {}
|
||||
for k, plane in { pr, pg, pb, pa } do
|
||||
local ch = Channels.rleChannel(plane, W, H, psb)
|
||||
parts[k] = ch
|
||||
out:bytes(ch, 0, H * cs)
|
||||
end
|
||||
for k = 1, 4 do
|
||||
out:bytes(parts[k], H * cs)
|
||||
end
|
||||
return out:finish(), nil
|
||||
end
|
||||
|
||||
return Psd
|
||||
Reference in new issue
Block a user