83 lines
1.8 KiB
Lua
83 lines
1.8 KiB
Lua
local args = { ... }
|
|
local ccpi = require("ccpi")
|
|
|
|
local bit = {
|
|
band = function(a, b) return a & b end,
|
|
bor = function(a, b) return a | b end,
|
|
blshift = function(a, b) return a << b end,
|
|
brshift = function(a, b) return a >> b end,
|
|
}
|
|
|
|
local function write_varint(fp, value)
|
|
value = bit.band(value, 0xFFFFFFFF)
|
|
mask = 0xFFFFFF80
|
|
while true do
|
|
if bit.band(value, mask) == 0 then
|
|
fp:write(string.char(bit.band(value, 0xff)))
|
|
return
|
|
end
|
|
|
|
fp:write(string.char(bit.bor(0x80, bit.band(value, 0x7f))))
|
|
value = bit.brshift(value, 7)
|
|
end
|
|
end
|
|
|
|
local function write_palette(fp, pal)
|
|
for i = 1, 16 do
|
|
fp:write(string.char(
|
|
bit.brshift(pal[i], 16),
|
|
bit.band(bit.brshift(pal[i], 8), 0xff),
|
|
bit.band(pal[i], 0xff)
|
|
))
|
|
end
|
|
end
|
|
|
|
local function write_pixeldata_v0(img, fp)
|
|
for y = 1, img.h do
|
|
for x = 1, img.w do
|
|
fp:write(img.lines[y].s:sub(x, x))
|
|
local bg = tonumber(img.lines[y].bg:sub(x, x), 16)
|
|
local fg = tonumber(img.lines[y].fg:sub(x, x), 16)
|
|
fp:write(string.char(bit.bor(bg, bit.blshift(fg, 4))))
|
|
end
|
|
end
|
|
end
|
|
|
|
local fp_out = io.open(table.remove(args, 1), "wb")
|
|
fp_out:write("CPI" .. string.char(0x80))
|
|
|
|
local fp = io.open(table.remove(args, 1), "rb")
|
|
print(fp, fp.close)
|
|
local img, err = ccpi.parse({
|
|
read = function(sz) return fp:read(sz) end,
|
|
})
|
|
fp:close()
|
|
if err ~= nil then
|
|
printError(err)
|
|
return
|
|
end
|
|
|
|
write_varint(fp_out, img.w)
|
|
write_varint(fp_out, img.h)
|
|
write_varint(fp_out, #args)
|
|
|
|
write_palette(fp_out, img.palette)
|
|
write_pixeldata_v0(img, fp_out)
|
|
|
|
for i, arg in ipairs(args) do
|
|
print(arg)
|
|
local fp = io.open(arg, "rb")
|
|
img, err = ccpi.parse({
|
|
read = function(sz) return fp:read(sz) end,
|
|
})
|
|
fp:close()
|
|
if err ~= nil then
|
|
printError(err)
|
|
return
|
|
end
|
|
write_palette(fp_out, img.palette)
|
|
write_pixeldata_v0(img, fp_out)
|
|
end
|
|
|
|
fp_out:close()
|