#!/usr/bin/env python3
"""A 1995 PC VGA monitor, simulated from the physics rather than an emulator's scanline filter.

    python3 -I tools/crt/crt.py <frame 320x200.png|bmp> <out dir>

What a 14" VGA colour monitor did to the game's 320 x 200 picture (mode 13h):
  - the DAC sends a voltage per pixel; the video amplifier's limited bandwidth smooths it along the line (in volts,
    before the tube's gamma): the dithering of the pictures melts into flat colours, as the artists intended;
  - 31 kHz monitor: each of the 200 lines is drawn twice (400 scanlines), so the dark gaps between lines are thin;
  - the electron beam is a gaussian spot whose width grows with its current: bright lines are wider (they bloom and
    fill the gaps), dark lines are thin;
  - light = voltage ^ 2.5 (the tube's gamma);
  - a slot / dot shadow mask (~0.28 mm pitch, ~1000 triads across, about 3 per game pixel): each triad lets the beam
    light only its red, green, blue phosphor; light diffuses a little in the phosphor and the glass (glow) and much
    more widely inside the thick front glass (halation);
  - slight misconvergence of the three guns, a curved screen, its corners darker, a grey black (the phosphor of a
    tube is not black in a lit room) and a faint reflection on the glass.
Writes crt-full.png (3840 x 2880: look at it at 100 %, the mask is real), crt-screen.png (scaled for a normal
screen, as seen from a little further) and crt-zoom.png (a detail at 2:1, the phosphors and the beam).
"""
import os
import sys

import numpy as np
from PIL import Image
from scipy.ndimage import gaussian_filter, gaussian_filter1d, map_coordinates

W, H = 3840, 2880            # the tube's face, 4:3
SRC_W, SRC_H = 320, 200
LINES = 400                  # double scan
OVERSCAN = 0.90              # the picture fills 90 % of the face (black border of the raster)


def raster(src):
    """The flat raster (before the glass): linear light, H x W x 3."""
    v = src.astype(np.float32) / 255.0                       # DAC voltage (0.7 V peak), 0..1
    pw = W // SRC_W                                          # 12 output pixels per game pixel
    row = np.repeat(v, pw, axis=1)                           # 200 x 3840 x 3 (steps)
    row = gaussian_filter1d(row, sigma=0.32 * pw, axis=1)    # amplifier bandwidth (volts)
    row[..., 0] = np.roll(row[..., 0], 2, axis=1)            # misconvergence: red a bit right,
    row[..., 2] = np.roll(row[..., 2], -2, axis=1)           # blue a bit left
    light = np.clip(row, 0, 1) ** 2.5                        # gamma of the tube
    light = np.repeat(light, 2, axis=0)                      # 400 scanlines (each line twice)
    pitch = H / LINES                                        # 7.2 px between scanlines
    y = np.arange(H, dtype=np.float32)
    out = np.zeros((H, W, 3), np.float32)
    for l in range(LINES):
        yc = (l + 0.5) * pitch
        a, b = int(max(0, yc - 3 * pitch)), int(min(H, yc + 3 * pitch))
        L = light[l]                                         # W x 3
        sigma = pitch * (0.28 + 0.22 * np.sqrt(L))           # spot width grows with the beam current
        d = (y[a:b, None, None] - yc)
        out[a:b] += L * np.exp(-0.5 * (d / sigma) ** 2) * pitch / (sigma * np.sqrt(2 * np.pi))
    return out


def mask(img):
    """Slot mask: R, G, B columns of 1 px (period 3 px), slots broken every 9 px, every other triad shifted."""
    h, w, _ = img.shape
    x = np.arange(w)[None, :]
    y = np.arange(h)[:, None]
    triad = x // 3
    gap = ((y + (triad % 2) * 4) % 9) == 0                   # the bars between slots
    m = np.full((h, w, 3), 0.12, np.float32)                 # leak (the beam spot is bigger than a slot)
    for c in range(3):
        m[..., c] = np.where((x % 3) == c, 1.0, 0.12)
    m[gap] *= 0.35
    out = img * m * 2.55                                     # what the mask hides, the tube is driven harder for
    out = gaussian_filter(out, sigma=(0.6, 0.6, 0))          # phosphor / glass diffusion
    return out


def glass(img):
    h, w, _ = img.shape
    halo = gaussian_filter(img, sigma=(60, 60, 0))           # halation in the thick front glass
    img = img + 0.07 * halo
    img = img / (1 + 0.15 * img)                             # phosphor saturation (soft knee)
    # the curved face: barrel distortion, the picture inside its overscan
    yy, xx = np.mgrid[0:h, 0:w].astype(np.float32)
    nx = (xx / w - 0.5) * 2
    ny = (yy / h - 0.5) * 2
    r2 = nx * nx * 0.75 + ny * ny * 0.75
    k = 1 + 0.012 * r2                                       # tubes of 1995: nearly flat
    sx = (nx * k / OVERSCAN * 0.5 + 0.5) * w
    sy = (ny * k / OVERSCAN * 0.5 + 0.5) * h
    out = np.stack([map_coordinates(img[..., c], [sy, sx], order=1, cval=0.0) for c in range(3)], axis=-1)
    inside = (np.abs(nx * k) < 0.985) & (np.abs(ny * k) < 0.985)
    vignette = (1 - 0.18 * (nx ** 2)) * (1 - 0.22 * (ny ** 2))
    out *= vignette[..., None]
    black = 0.012 + 0.010 * np.exp(-((nx + 0.6) ** 2 + (ny + 0.7) ** 2) / 0.35)   # grey black + a reflection
    out = out + black[..., None]
    out[~inside] = 0.0
    return out


def srgb(lin):
    lin = np.clip(lin, 0, 1)
    return (np.where(lin <= 0.0031308, lin * 12.92, 1.055 * lin ** (1 / 2.4) - 0.055) * 255 + 0.5).astype(np.uint8)


def main():
    src = np.asarray(Image.open(sys.argv[1]).convert('RGB').resize((SRC_W, SRC_H), Image.NEAREST))
    out_dir = sys.argv[2]
    os.makedirs(out_dir, exist_ok=True)
    img = glass(mask(raster(src)))
    full = Image.fromarray(srgb(img))
    full.save(os.path.join(out_dir, 'crt-full.png'))
    full.resize((1600, 1200), Image.LANCZOS).save(os.path.join(out_dir, 'crt-screen.png'))
    full.crop((1500, 300, 2300, 900)).resize((1600, 1200), Image.NEAREST).save(os.path.join(out_dir, 'crt-zoom.png'))
    Image.fromarray(src).resize((1600, 1000), Image.NEAREST).save(os.path.join(out_dir, 'pixels.png'))


if __name__ == '__main__':
    main()
