import Image
import numpy
import sys
import GDprep
import compress
import array

def ld(f):
    return numpy.array(Image.open(f).convert("L")) > 0

stripes = [ld("stripes%d.png" % i) for i in range(1,6)]
vstripes = ld("vstripes.png")
alpha = numpy.array(Image.open("lighting.png").split()[3])

def get16x16(sheet, x, y):
    return sheet.crop((x, y, x + 16, y + 16))

def genNxN(hh, name, im, pal, imageram, center = (0,0)):
    print >>hh, """static void draw_%s(int x, int y, byte pal) { """ % name
    ncolors = len(pal)
    for spriteimage in [im]:
        for y in range(0, im.size[1], 16):
            for x in range(0, im.size[0], 16):
                t = get16x16(spriteimage, x, y)
                if GDprep.isnonblank(t, pal):
                    (page, palsel) = imageram.add(array.array('B', t.tostring()), ncolors)
                    print >>hh, "GD.xsprite(x, y, %d, %d, %d, pal, 0);" % (x - center[0], y - center[1], page)
    print >>hh, "}"

def getlut(im, ncol): 
    assert im.mode == "P"
    lut = im.resize((ncol, 1))
    lut.putdata(range(ncol))
    return lut.convert("L")

l7 =Image.open("lighting_7.png")
lut = numpy.array(getlut(l7, 8))[0]
print list(lut)
lighting = numpy.array(l7) - 1      # 0 darkest, 6 lightest

coded = numpy.where(alpha, (lighting * 32) + ((stripes[0] ^ vstripes)* 16 + stripes[1] * 8 + stripes[2] * 4 + stripes[3] * 2 + stripes[4]), 255)
codedim = Image.fromarray(coded.astype(numpy.uint8))

# for i in range(32):
#     out = numpy.where(16 & (coded + i), 255, 0).astype(numpy.uint8)
#     Image.fromarray(out).save("out%02d.png" % i)

hh = open("../../ball.h", "w")
ir = GDprep.ImageRAM()
genNxN(hh, "ball", codedim, [0] * 255 + [0x8000], ir, (56, 56))
print len(ir.used())
uncompressed = ir.used().tostring()
cc = compress.Codec(b_off = 9, b_len = 3)
compressed = cc.toarray(uncompressed)
print "uncompressed", len(uncompressed), "compressed", len(compressed), 
GDprep.dump(hh, "ball", compressed)

fn = "bg"
(picdata, chrdata, paldata) = GDprep.encode(Image.open("bg.png").convert("RGB"))
GDprep.dump(hh, "%s_pic" % fn, picdata)
GDprep.dump(hh, "%s_chr" % fn, chrdata)
GDprep.dump(hh, "%s_pal" % fn, paldata)
