#!/usr/bin/env python3

# Turns a picture into a C array the game carries inside itself.
#
# The menus can draw an arbitrary image - see port/include/menuimage.h - but
# only one that is in the binary: a community pack's cover art has to be on
# screen before anything has been downloaded, so it cannot be a file beside the
# executable and it cannot be fetched. What goes in is a PNG small enough to be
# worth compiling in, and this is what makes one.
#
# 256 colours rather than truecolour, which for a picture drawn at this size is
# a third of the bytes and about 35dB - the difference is not visible in a menu
# and 118KB of source for one thumbnail is.
#
# Usage:
#
#     tools/mkmenuimage ../Ultimate_Plus_HD_Cover.webp g_MenuImageUltimatePlusHd 256 384 \
#         > port/src/communityart.c
#
# One run per cover; port/src/communityart.c is the three Plus HD covers'
# output concatenated, with the repeated #include taken out.

import sys
from PIL import Image


def main():
    if len(sys.argv) < 5:
        print(__doc__ or "usage: mkmenuimage <image> <symbol> <width> <height>",
              file=sys.stderr)
        return 1

    path, symbol, width, height = sys.argv[1], sys.argv[2], int(sys.argv[3]), int(sys.argv[4])

    im = Image.open(path).convert("RGB").resize((width, height), Image.LANCZOS)
    im = im.quantize(colors=256, method=Image.MEDIANCUT, dither=Image.FLOYDSTEINBERG)

    tmp = f"/tmp/mkmenuimage-{symbol}.png"
    im.save(tmp, "PNG", optimize=True)

    with open(tmp, "rb") as f:
        data = f.read()

    out = sys.stdout
    out.write("// Generated by tools/mkmenuimage from %s - do not edit.\n" % path)
    out.write("// %dx%d, %d bytes of PNG.\n\n" % (width, height, len(data)))
    out.write('#include <PR/ultratypes.h>\n\n')
    out.write("const u8 %s[%d] = {\n" % (symbol, len(data)))

    for i in range(0, len(data), 20):
        out.write("\t" + "".join("0x%02x," % b for b in data[i:i + 20]) + "\n")

    out.write("};\n\n")
    out.write("const u32 %sLen = %d;\n" % (symbol, len(data)))

    return 0


if __name__ == "__main__":
    sys.exit(main())
