--!strict --!native --!optimize 2 -- image/gif/Decode: the per-frame pixel work (native; never throws): palette indexes (plain or interlaced rows) to -- rgba8, and drawing a frame onto the canvas (transparent pixels leave the canvas as it is). The caller sizes every -- buffer: indexes fw * fh bytes, the palette 256 u32 entries, the frame fw * fh * 4, the canvas cw * ch * 4. local readu8, readu32, writeu32 = buffer.readu8, buffer.readu32, buffer.writeu32 local Decode = {} -- the source row of output row y in an interlaced frame (passes: every 8th from 0, every 8th from 4, every 4th from -- 2, every 2nd from 1) local function interlacedRow(fh: number): { number } local map = table.create(fh, 0) local r = 0 for _, pass in { { 0, 8 }, { 4, 8 }, { 2, 4 }, { 1, 2 } } do local y = pass[1] while y < fh do map[y + 1] = r r += 1 y += pass[2] end end return map end -- toRgba(indexes, fw, fh, interlaced, palette, out): out = the frame in rgba8 (palette: 256 u32 entries, the -- transparent one already alpha 0) function Decode.toRgba(indexes: buffer, fw: number, fh: number, interlaced: boolean, palette: buffer, out: buffer) local rows = if interlaced then interlacedRow(fh) else nil for y = 0, fh - 1 do local src = (if rows then rows[y + 1] else y) * fw local dst = y * fw * 4 for x = 0, fw - 1 do writeu32(out, dst + x * 4, readu32(palette, readu8(indexes, src + x) * 4)) end end end -- draw(canvas, cw, ch, frame, fx, fy, fw, fh): frame pixels with alpha > 0 replace the canvas (clipped) function Decode.draw(canvas: buffer, cw: number, ch: number, frame: buffer, fx: number, fy: number, fw: number, fh: number) local x0, y0 = math.max(0, fx), math.max(0, fy) local x1, y1 = math.min(cw, fx + fw), math.min(ch, fy + fh) for y = y0, y1 - 1 do local s = ((y - fy) * fw - fx) * 4 local d = y * cw * 4 for x = x0, x1 - 1 do local v = readu32(frame, s + x * 4) if v >= 0x01000000 then writeu32(canvas, d + x * 4, v) end end end end -- clear(canvas, cw, ch, fx, fy, fw, fh): the frame's rectangle to transparent black (dispose to background) function Decode.clear(canvas: buffer, cw: number, ch: number, fx: number, fy: number, fw: number, fh: number) local x0, y0 = math.max(0, fx), math.max(0, fy) local x1, y1 = math.min(cw, fx + fw), math.min(ch, fy + fh) if x1 <= x0 then return end for y = y0, y1 - 1 do buffer.fill(canvas, (y * cw + x0) * 4, 0, (x1 - x0) * 4) end end return Decode