vec: layered/psd (PSD/PSB read: all modes/depths, RLE/ZIP, groups, masks, clipping; write: 8-bit RGB layers + merged), codecs/Blend (blend modes, layer-tree compositing), ops/LayerOps (flatten, frames, leaves); Types: Layer gains optional children/clip/mask + Layered.layer/group constructors (backward compatible). Tests vs psd-tools incl. psd-tools reading our PSD

This commit is contained in:
4DBug committed 2026-10-31 08:39:56 -05:00
1 parent 2521f3dfa6
commit 71aaeb64db
11 files changed
+2461 -3

No files matched your search

+184
View File
@@ -0,0 +1,184 @@
-- layered/psd tests: PSD / PSB files of every colour mode and depth, compression, groups, pass-through, clipping,
-- masks, fill opacity and blend mode (written by tools/fixtures/psd.py) plus an ImageMagick PSD, against psd-tools:
-- the merged image and every layer's pixels exact (8-bit; 16 / 32-bit within rounding), our flatten (ops/LayerOps)
-- against psd-tools' composite by PSNR; our encoder's PSD read back by psd-tools (tools/fixtures/_ours.luau), round
-- trips, the contract and the fuzz pass. Fixtures: tools/fixtures/psd.py.
local T = require("@tests/T")
local Psd = require("@formats/layered/psd")
local LayerOps = require("@formats/ops/LayerOps")
local Bytes = require("@formats/core/Bytes")
local Crc32 = require("@formats/core/Crc32")
local Err = require("@formats/core/Err")
local Fx = require("@tests/gen/psd")
local Ours = require("@tests/gen/psd_ours")
local t = T.suite("psd")
local function decode(s: string | buffer, opts: any?): (any, any)
local b = if type(s) == "string" then buffer.fromstring(s) else s
return Psd.decode(Bytes.reader(b), opts)
end
-- PSNR of two rgba8 buffers, colours premultiplied by alpha (the colour of a transparent pixel does not matter);
-- identical -> 99
local function psnr(a: buffer, b: string, opaque: boolean?): 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)
if opaque then
aa, ab = 255, 255
end
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
local function leaves(layers: any): { any }
local out = {}
for l in LayerOps.leaves(layers) do
table.insert(out, l)
end
return out
end
t:eq(Psd.name, "psd", "name")
t:eq(Psd.category, "layered", "category")
t:check(Psd.caps.decode and Psd.caps.encode, "caps")
-- PSNR floors for our flatten vs psd-tools' composite: blend modes where psd-tools' formulas differ from the W3C ones
-- (Photoshop's own differ from both) get a lower bar
local LOW = { ["blend-diss"] = 8, ["blend-hMix"] = 15, ["blend-sLit"] = 30, ["blend-vLit"] = 25, ["blend-lLit"] = 30, ["blend-pLit"] = 30, ["blend-div"] = 30, ["blend-idiv"] = 30, ["blend-fdiv"] = 25, ["blend-hue"] = 25, ["blend-sat"] = 25, ["blend-colr"] = 25, ["blend-lum"] = 25 }
local samples = {}
for _, c in Fx.cases do
local doc, err = decode(c.data)
t:check(doc, c.name .. ": " .. tostring(err))
t:eq(doc.kind, "layered", c.name .. ": kind")
t:check(doc.width == c.width and doc.height == c.height, c.name .. ": size")
local comp = doc.meta.composite
if #c.composite > 0 then
local src = doc.meta.source
local exact = (src.bitDepth == 8 or src.bitDepth == 1) and src.colorMode ~= "lab" and src.colorMode ~= "cmyk"
if exact then
t:check(buffer.tostring(comp.pixels) == c.composite, c.name .. ": merged image = psd-tools")
else
-- (PIL turns Lab into RGBA with alpha 0: compare the colours only)
local p = psnr(comp.pixels, c.composite, src.colorMode == "lab")
-- 16 / 32 bits: rounding; CMYK / Lab: different conversions (ours: naive CMYK, D65 Lab)
local floor = if src.colorMode == "lab" then 20 elseif src.colorMode == "cmyk" then 30 else 45
t:check(p > floor, string.format("%s: merged image PSNR %.1f", c.name, p))
t:note("%s: merged image vs psd-tools %.1f dB", c.name, p)
end
end
-- layers, in order, against psd-tools
local ours = leaves(doc.layers)
local ref = {}
for _, l in c.layers do
if not l.group then
table.insert(ref, l)
end
end
t:eq(#ours, #ref, c.name .. ": leaf count")
for i, r in ref do
local l = ours[i]
t:eq(l.name, r.name, c.name .. ": layer name")
if r.width > 0 then
t:check(l.x == r.left and l.y == r.top and l.image.width == r.width and l.image.height == r.height, c.name .. ": " .. r.name .. ": bounds")
end
if r.crc and doc.meta.source.bitDepth == 8 then
t:eq(Crc32.of(l.image.pixels), r.crc, c.name .. ": " .. r.name .. ": pixels")
end
end
-- our flatten vs psd-tools' composite
if c.flat and #ours > 0 then
local flat = LayerOps.flatten(doc) :: any
local p = psnr(flat.pixels, c.flat)
local floor = LOW[c.name] or 38
t:check(p >= floor, string.format("%s: flatten PSNR %.1f dB (floor %d)", c.name, p, floor))
if p < 99 then
t:note("%s: flatten vs psd-tools %.1f dB", c.name, p)
end
end
if #samples < 8 and (c.name == "rgb-layers" or c.name == "psb" or c.name == "rgb16-lr16" or c.name == "gray" or c.name == "indexed" or c.name == "bitmap" or c.name == "rgb32" or c.name == "cmyk") then
table.insert(samples, c.data)
end
end
-- the full document's structure
do
local doc
for _, c in Fx.cases do
if c.name == "rgb-layers" then
doc = decode(c.data)
end
end
local L = doc.layers
t:eq(#L, 8, "top level: bg, multiply, isolated, pass, base, clipped, masked, fill")
t:eq(L[2].blend, "multiply", "blend")
t:eq(math.floor(L[2].opacity * 255 + 0.5), 200, "opacity")
t:eq(L[3].name, "Isolated", "group name")
t:eq(L[3].blend, "normal", "isolated group blend")
t:eq(#L[3].children, 2, "group children")
t:eq(L[4].blend, "passThrough", "pass-through group")
t:eq(L[4].children[1].name, "Diff \u{e9}\u{65e5}", "unicode name (luni)")
t:eq(L[4].children[2].visible, false, "hidden layer")
t:eq(L[6].clip, true, "clipping layer")
t:check(L[7].mask and L[7].mask.image.format == "gray8" and L[7].mask.x == 8 and L[7].mask.y == 5, "mask")
t:eq(math.floor(L[8].fillOpacity * 255 + 0.5), 128, "fill opacity")
local only = decode(Fx.cases[1].data, { layers = false })
t:check(only and #only.layers == 0 and only.meta.composite, "layers = false: merged image only")
-- round trip: our PSD of the decoded document decodes to the same layers, and its merged image is our flatten
local out, eerr = Psd.encode(doc)
t:check(out, "encode: " .. tostring(eerr))
local back = decode(out :: buffer)
t:check(back, "decode our PSD")
local a, b = leaves(doc.layers), leaves(back.layers)
t:eq(#b, #a, "round trip: leaves")
for i, l in a do
t:eq(b[i].name, l.name, "rt name")
t:check(buffer.tostring(b[i].image.pixels) == buffer.tostring(l.image.pixels), "rt pixels " .. l.name)
t:check(b[i].x == l.x and b[i].y == l.y, "rt position")
t:eq(b[i].blend, l.blend, "rt blend")
t:eq(b[i].visible, l.visible, "rt visible")
t:eq(b[i].clip, l.clip, "rt clip")
t:eq(b[i].opacity, l.opacity, "rt opacity")
end
t:eq(back.layers[4].blend, "passThrough", "rt pass-through group")
t:check(back.layers[7].mask and buffer.tostring(back.layers[7].mask.image.pixels) == buffer.tostring(L[7].mask.image.pixels), "rt mask")
local flat = LayerOps.flatten(doc) :: any
-- the merged image is stored matted with white (as Photoshop does): exact where opaque, rounding elsewhere
local p = psnr(back.meta.composite.pixels, buffer.tostring(flat.pixels))
t:check(p > 45, string.format("rt merged = flatten (%.1f dB)", p))
table.insert(samples, buffer.tostring(out :: buffer))
end
-- psd-tools reads our encoder's PSD (checked when the fixtures were made)
for _, c in Ours.checks do
t:check(c.ok, "psd-tools on our PSD: " .. c.label)
end
t:note("psd-tools agrees with our PSD on %d facts", #Ours.checks)
-- errors
do
local _, e = decode("8BPS\0\1\0\0\0\0\0\0\0\3\0\0\0\10\0\0\0\10\0\8\0\3")
t:check(e and e.code == Err.TRUNCATED, "truncated after the header: " .. tostring(e))
local _, e2 = decode("8BPS\0\1\0\0\0\0\0\0\0\3\0\0\0\10\0\0\0\10\0\7\0\3")
t:check(e2 and e2.code == Err.CORRUPT, "bad depth: " .. tostring(e2))
local _, e3 = decode(Fx.cases[1].data, { maxPixels = 100 })
t:check(e3 and e3.code == Err.LIMIT, "maxPixels")
t:eq(Psd.sniff(Bytes.reader(buffer.fromstring("8BPS\0\1"))), 1, "sniff")
t:eq(Psd.sniff(Bytes.reader(buffer.fromstring("8BPS\0\3"))), 0, "sniff version 3")
local _, e4 = Psd.encode({ width = 4, height = 4, layers = { { name = "x" } } } :: any)
t:check(e4 and e4.code == Err.ARG, "encode: layer without an image")
end
t:fuzz("decode", function(b: buffer)
return Psd.decode(Bytes.reader(b))
end, samples, { mutations = 30, keepHeader = 4 })
t:done()
+144
View File
@@ -0,0 +1,144 @@
-- ops/LayerOps + codecs/Blend tests: blend mode formulas on single pixels against hand-computed W3C values, opacity,
-- masks, clipping, isolated vs pass-through groups, hidden layers, frames, leaves, bad arguments. (Whole-document
-- flattening against psd-tools is in tests/layered/psd.luau.)
local T = require("@tests/T")
local LayerOps = require("@formats/ops/LayerOps")
local Blend = require("@formats/codecs/Blend")
local Types = require("@formats/Types")
local Err = require("@formats/core/Err")
local t = T.suite("layerops")
local function px(r: number, g: number, b: number, a: number): Types.Image
local img = Types.Image.new(1, 1)
buffer.writeu8(img.pixels, 0, r)
buffer.writeu8(img.pixels, 1, g)
buffer.writeu8(img.pixels, 2, b)
buffer.writeu8(img.pixels, 3, a)
return img
end
local function get(img: any): (number, number, number, number)
local p = img.pixels
return buffer.readu8(p, 0), buffer.readu8(p, 1), buffer.readu8(p, 2), buffer.readu8(p, 3)
end
local function doc(layers: { any }): any
local d = Types.Layered.new(1, 1)
d.layers = layers
return d
end
local L = Types.Layered.layer
-- separable modes on opaque pixels: backdrop (200, 100, 50), source (100, 150, 250); values from the W3C formulas
local cases = {
normal = { 100, 150, 250 },
multiply = { 78, 59, 49 },
screen = { 222, 191, 251 },
darken = { 100, 100, 50 },
lighten = { 200, 150, 250 },
difference = { 100, 50, 200 },
exclusion = { 143, 132, 202 },
linearDodge = { 255, 250, 255 },
linearBurn = { 45, 0, 45 },
subtract = { 100, 0, 0 },
overlay = { 188, 118, 98 },
hardLight = { 157, 127, 247 },
colorDodge = { 255, 243, 255 },
colorBurn = { 115, 0, 46 },
hardMix = { 255, 0, 255 },
}
for mode, want in cases do
local top = L("top", px(100, 150, 250, 255))
top.blend = mode
local img = LayerOps.flatten(doc({ L("bottom", px(200, 100, 50, 255)), top })) :: any
local r, g, b, a = get(img)
t:check(math.abs(r - want[1]) <= 1 and math.abs(g - want[2]) <= 1 and math.abs(b - want[3]) <= 1 and a == 255, string.format("%s: got %d %d %d, want %d %d %d", mode, r, g, b, want[1], want[2], want[3]))
end
-- non-separable: luminosity of the source on the backdrop's hue
do
local top = L("top", px(255, 255, 255, 255))
top.blend = "luminosity"
local r, g, b = get(LayerOps.flatten(doc({ L("bottom", px(255, 0, 0, 255)), top })))
t:check(r == 255 and g == 255 and b == 255, "luminosity of white")
top.blend = "color"
local r2, g2, b2 = get(LayerOps.flatten(doc({ L("bottom", px(128, 128, 128, 255)), top })))
t:check(r2 == g2 and g2 == b2 and math.abs(r2 - 128) <= 1, "colour of a grey source keeps the grey")
end
-- opacity and alpha: 50% red over opaque blue
do
local top = L("top", px(255, 0, 0, 255))
top.opacity = 0.5
local r, g, b, a = get(LayerOps.flatten(doc({ L("bottom", px(0, 0, 255, 255)), top })))
t:check(math.abs(r - 128) <= 1 and g == 0 and math.abs(b - 128) <= 1 and a == 255, "opacity mix")
local r2, _, _, a2 = get(LayerOps.flatten(doc({ top })))
t:check(r2 == 255 and math.abs(a2 - 128) <= 1, "over transparent: alpha scales")
end
-- hidden layers, masks, clipping
do
local top = L("top", px(255, 0, 0, 255))
top.visible = false
local r = get(LayerOps.flatten(doc({ L("bottom", px(0, 0, 255, 255)), top })))
t:eq(r, 0, "hidden layer skipped")
local r2 = get(LayerOps.flatten(doc({ L("bottom", px(0, 0, 255, 255)), top }), { hidden = true }))
t:eq(r2, 255, "hidden = true includes it")
top.visible = true
local m = Types.Image.new(1, 1, "gray8")
top.mask = { image = m, x = 0, y = 0, default = 255 }
t:eq((get(LayerOps.flatten(doc({ L("bottom", px(0, 0, 255, 255)), top })))), 0, "black mask hides")
top.mask = { image = m, x = 5, y = 5, default = 255 }
t:eq((get(LayerOps.flatten(doc({ L("bottom", px(0, 0, 255, 255)), top })))), 255, "outside the mask: default white")
top.mask = nil
local base = L("base", px(0, 255, 0, 0)) -- transparent base: the clipped layer shows nowhere
top.clip = true
local r3, g3, b3, a3 = get(LayerOps.flatten(doc({ base, top })))
t:check(a3 == 0, "clipped to a transparent base: " .. r3 .. g3 .. b3 .. a3)
base = L("base", px(0, 255, 0, 255))
local r4, g4 = get(LayerOps.flatten(doc({ base, top })))
t:check(r4 == 255 and g4 == 0, "clipped to an opaque base")
end
-- groups: an isolated multiply group multiplies its composite; pass-through multiplies each child onto the backdrop
do
local child = L("child", px(128, 128, 128, 255))
child.blend = "multiply"
local g = Types.Layered.group("g", { child })
local bottom = L("bottom", px(200, 200, 200, 255))
local r = get(LayerOps.flatten(doc({ bottom, g })))
t:check(math.abs(r - 100) <= 1, "pass-through: child multiplies the backdrop: " .. r)
g.blend = "normal"
local r2 = get(LayerOps.flatten(doc({ bottom, g })))
t:eq(r2, 128, "isolated group: the child multiplies nothing")
g.blend = "passThrough"
g.opacity = 0.5
local r3 = get(LayerOps.flatten(doc({ bottom, g })))
t:check(math.abs(r3 - 150) <= 1, "pass-through opacity mixes before / after: " .. r3)
end
-- frames, leaves, flattenFrames
do
local d = doc({ L("a", px(1, 2, 3, 255)) })
d.frames = { { layers = d.layers, delay = 0.1 }, { layers = { L("b", px(9, 8, 7, 255)) }, delay = 0.2 } }
t:eq((get(LayerOps.flatten(d, { frame = 2 }))), 9, "frame 2")
local anim = LayerOps.flattenFrames(d) :: any
t:check(anim.frames and #anim.frames == 2 and anim.frames[2].delay == 0.2, "flattenFrames")
local _, e = LayerOps.flatten(d, { frame = 5 })
t:check(e and e.code == Err.ARG, "missing frame")
local names = {}
for l, depth in LayerOps.leaves({ L("x", px(0, 0, 0, 0)), Types.Layered.group("g", { L("y", px(0, 0, 0, 0)), Types.Layered.group("h", { L("z", px(0, 0, 0, 0)) }) }) }) do
table.insert(names, (l :: any).name .. depth)
end
t:eq(table.concat(names, " "), "x0 y1 z2", "leaves with depth")
local _, e2 = LayerOps.flatten(5 :: any)
t:check(e2 and e2.code == Err.ARG, "flatten of a non-Layered")
end
-- Blend.composite clips its rectangles (no throw, nothing outside)
do
local dst = buffer.create(4 * 4 * 4)
local src = buffer.create(3 * 3 * 4)
buffer.fill(src, 0, 255)
for _, pos in { { -2, -2 }, { 3, 3 }, { -10, 0 }, { 100, 100 } } do
Blend.composite(dst, 4, 4, src, 3, 3, pos[1], pos[2], 1, "multiply")
end
Blend.composite(dst, 4, 4, src, 3, 3, 0, 0, 1, "nope")
Blend.composite(dst, 4, 4, src, 30, 30, 0, 0, 1, "normal") -- src too short: ignored
t:eq(buffer.readu8(dst, 0), 255, "composite clipping")
t:check(Blend.MODES.softLight and not Blend.MODES.nope, "MODES")
end
t:done()