From ee36bd9342cce0e728431428b91d6f2074db2f21 Mon Sep 17 00:00:00 2001 From: Rangi Date: Mon, 15 Mar 2021 16:47:35 -0400 Subject: [PATCH] Add tools/palfix.py, and make Python tools executable --- tools/free_space.py | 0 tools/gfx.py | 0 tools/palfix.py | 62 +++++++++++++++++++++++++++++++++++++++++++ tools/sym_comments.py | 0 tools/used_space.py | 0 5 files changed, 62 insertions(+) mode change 100644 => 100755 tools/free_space.py mode change 100644 => 100755 tools/gfx.py create mode 100755 tools/palfix.py mode change 100644 => 100755 tools/sym_comments.py mode change 100644 => 100755 tools/used_space.py diff --git a/tools/free_space.py b/tools/free_space.py old mode 100644 new mode 100755 diff --git a/tools/gfx.py b/tools/gfx.py old mode 100644 new mode 100755 diff --git a/tools/palfix.py b/tools/palfix.py new file mode 100755 index 000000000..b7743bc23 --- /dev/null +++ b/tools/palfix.py @@ -0,0 +1,62 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- + +from __future__ import print_function + +import sys +from pokemontools import png + +def rgb8_to_rgb5(c): + r, g, b = c + return (r // 8, g // 8, b // 8) + +def rgb5_to_rgb8(c): + r, g, b = c + return ((r * 8) | (r // 4), (g * 8) | (g // 4), (b * 8) | (b // 4)) + +def invert(c): + r, g, b = c + return (31 - r, 31 - g, 31 - b) + +def luminance(c): + r, g, b = c + return (0.299 * r**2 + 0.587 * g**2 + 0.114 * b**2)**0.5 + +def rgb5_pixels(row): + for x in range(0, len(row), 4): + yield rgb8_to_rgb5(row[x:x+3]) + +def fix_pal(filename): + with open(filename, 'rb') as file: + width, height, data = png.Reader(file).asRGBA8()[:3] + data = list(data) + b_and_w = {(0, 0, 0), (31, 31, 31)} + colors = set(c for row in data for c in rgb5_pixels(row)) - b_and_w + if not colors: + colors = {(20, 20, 20), (10, 10, 10)} + elif len(colors) == 1: + c = colors.pop() + colors = {c, invert(c)} + elif len(colors) != 2: + return False + palette = tuple(sorted(colors | b_and_w, key=luminance, reverse=True)) + assert len(palette) == 4 + data = [list(map(palette.index, rgb5_pixels(row))) for row in data] + palette = tuple(map(rgb5_to_rgb8, palette)) + writer = png.Writer(width, height, palette=palette, compression=9) + with open(filename, 'wb') as file: + writer.write(file, data) + return True + +def main(): + if len(sys.argv) < 2: + print('Usage: %s pic.png' % sys.argv[0], file=sys.stderr) + sys.exit(1) + for filename in sys.argv[1:]: + if not filename.lower().endswith('.png'): + print(filename, 'is not a .png file!', file=sys.stderr) + elif not fix_pal(filename): + print(filename, 'has too many colors!', file=sys.stderr) + +if __name__ == '__main__': + main() diff --git a/tools/sym_comments.py b/tools/sym_comments.py old mode 100644 new mode 100755 diff --git a/tools/used_space.py b/tools/used_space.py old mode 100644 new mode 100755