#!/usr/bin/env python3
"""Compare two folders of render_check screenshots, for checking that an engine change left a house alone.

Usage:  python tools/compare_renders.py <before_dir> <after_dir> [--diff-out <dir>]
Prints, per view, the share of pixels that changed by more than a small tolerance, and writes a
diff image (changed pixels in red over the dimmed "after" shot) when --diff-out is given.
Setup (once):  pip install pillow numpy
"""
import argparse, pathlib
import numpy as np
from PIL import Image

ap = argparse.ArgumentParser(); ap.add_argument('before'); ap.add_argument('after'); ap.add_argument('--diff-out'); ap.add_argument('--tol', type=int, default=12)
a = ap.parse_args()
for f in sorted(pathlib.Path(a.before).glob('*.png')):
    g = pathlib.Path(a.after) / f.name
    if not g.exists(): print(f'{f.name:12} missing in after'); continue
    A = np.asarray(Image.open(f).convert('RGB')).astype(int); B = np.asarray(Image.open(g).convert('RGB')).astype(int)
    if A.shape != B.shape: print(f'{f.name:12} size differs {A.shape} vs {B.shape}'); continue
    changed = np.abs(A - B).max(axis=2) > a.tol
    print(f'{f.name:12} {changed.mean()*100:6.3f}% of pixels changed')
    if a.diff_out:
        out = pathlib.Path(a.diff_out); out.mkdir(parents=True, exist_ok=True)
        img = (B * 0.45 + 140).clip(0, 255).astype('uint8'); img[changed] = [230, 30, 30]
        Image.fromarray(img).save(out / f.name)
