# Which squares of the SKCombat texture sheets tile seamlessly (edge difference vs. ordinary pixel-to-pixel difference)?
import numpy as np, sys, os, json
from PIL import Image, ImageDraw
S = sys.argv[1]
res = []
for atlas in ('greece', 'nature'):
    im = np.asarray(Image.open(os.path.join(S, 'tex', atlas + '.jpg')).convert('RGB')).astype(np.float32)
    for size in (256, 512):
        for y in range(0, 2048, size):
            for x in range(0, 2048, size):
                t = im[y:y + size, x:x + size]
                if t.std() < 6: continue  # empty / black
                inner = (np.abs(np.diff(t, axis=1)).mean() + np.abs(np.diff(t, axis=0)).mean()) / 2
                seam = (np.abs(t[:, 0] - t[:, -1]).mean() + np.abs(t[0] - t[-1]).mean()) / 2
                res.append({'a': atlas, 'x': x, 'y': y, 's': size, 'r': round(float(seam / max(inner, 1e-3)), 2)})
res.sort(key=lambda r: r['r'])
json.dump(res, open(os.path.join(S, 'tiles.json'), 'w'))
good = [r for r in res if r['r'] < 1.6]
print(len(res), 'squares,', len(good), 'look seamless')
# contact sheet: each good square tiled 2×2 at 128 px, labelled
cell = 128
cols = 8
rows = (len(good) + cols - 1) // cols
sheet = Image.new('RGB', (cols * (cell * 2 + 8), rows * (cell * 2 + 22)), (30, 30, 30))
d = ImageDraw.Draw(sheet)
src = {a: Image.open(os.path.join(S, 'tex', a + '.jpg')).convert('RGB') for a in ('greece', 'nature')}
for i, r in enumerate(good):
    t = src[r['a']].crop((r['x'], r['y'], r['x'] + r['s'], r['y'] + r['s'])).resize((cell, cell))
    ox = (i % cols) * (cell * 2 + 8); oy = (i // cols) * (cell * 2 + 22)
    for dx in (0, cell):
        for dy in (0, cell): sheet.paste(t, (ox + dx, oy + dy))
    d.text((ox + 2, oy + cell * 2 + 4), '%d %s %d,%d/%d r%.2f' % (i, r['a'][0], r['x'] // 256, r['y'] // 256, r['s'] // 256, r['r']), fill=(255, 255, 0))
sheet.save(os.path.join(S, 'tiles_sheet.png'))
json.dump(good, open(os.path.join(S, 'tiles_good.json'), 'w'))
print(sheet.size)
