"""Phase-1 frame encoder: one picture -> the VDP data for it, plus a prediction of what the screen will show. Colour system (PLAN.md section 3.1, steps 3-5, single band for now): four palette lines of 16 fitted to the picture, each cell choosing its line and its shade (normal, or shadow via a cleared priority bit in shadow/highlight mode); pen 0 of every line is the backdrop (black). Tiles are deduplicated under all four flips. The prediction goes through the same DAC ramp and the same shade rule the emulator's render.py uses, so an emulator screenshot is expected to be *equal*, not similar. """ from __future__ import annotations import json from dataclasses import dataclass, field from pathlib import Path import numpy as np from PIL import Image from .vdp import ( CELLS_X, CELLS_Y, HEIGHT, HIGHLIGHT, LEVELS, NORMAL, PLANE_W, SHADOW, TILE, WIDTH, cram_word, name_word, raw_to_rgb, rgb_to_raw, tile_bytes, ) LINES = 4 PENS = 16 #: Luma weights (BT.601, scaled to sum 3) on squared channel error: the eye forgives #: chroma error far more than brightness error. LUMA_W = np.array([0.299, 0.587, 0.114], dtype=np.float64) * 3.0 REFIT_ROUNDS = 2 @dataclass class FrameAssets: cram: list[int] # 64 CRAM words tiles: list[bytes] # tile 0 is blank name_table: np.ndarray # (32, 64) uint16 expected: np.ndarray # (HEIGHT, WIDTH, 3) uint8 stats: dict = field(default_factory=dict) def write(self, out: Path) -> None: out.mkdir(parents=True, exist_ok=True) (out / "cram.bin").write_bytes(b"".join(w.to_bytes(2, "big") for w in self.cram)) (out / "tiles.bin").write_bytes(b"".join(self.tiles)) (out / "nametable.bin").write_bytes(self.name_table.astype(">u2").tobytes()) Image.fromarray(self.expected).save(out / "expected.png") (out / "stats.json").write_text(json.dumps(self.stats, indent=2)) # -- picture in ---------------------------------------------------------------------- def load_picture(path: Path) -> np.ndarray: """A source field -> (HEIGHT, WIDTH, 3) uint8: scale to 320x240 (the 4:3 frame), then crop 8 lines top and bottom for V28 (decision D1).""" img = Image.open(path).convert("RGB").resize((WIDTH, 240), Image.LANCZOS) arr = np.asarray(img) top = (240 - HEIGHT) // 2 return arr[top : top + HEIGHT].copy() # -- palettes ------------------------------------------------------------------------ def _weighted_dist(pixels: np.ndarray, palette_rgb: np.ndarray) -> np.ndarray: """(..., 3) pixels vs (P, 3) palette -> (..., P) luma-weighted squared distance.""" diff = pixels[..., None, :].astype(np.float64) - palette_rgb[None, :, :].astype(np.float64) return np.sum(diff * diff * LUMA_W, axis=-1) def _median_cut(pixels: np.ndarray, colours: int) -> np.ndarray: """(N, 3) uint8 -> (colours, 3) raw 0-7 CRAM values, via PIL's median cut, snapped to the DAC ramp and deduplicated (so a line never wastes a pen on a repeat).""" if len(pixels) == 0: return np.zeros((colours, 3), dtype=np.uint8) side = int(np.ceil(np.sqrt(len(pixels)))) padded = np.zeros((side * side, 3), dtype=np.uint8) padded[: len(pixels)] = pixels padded[len(pixels) :] = pixels[-1] img = Image.fromarray(padded.reshape(side, side, 3)) q = img.quantize(colors=colours, method=Image.MEDIANCUT) pal = np.array(q.getpalette()[: colours * 3], dtype=np.int32).reshape(-1, 3) raw = rgb_to_raw(pal) uniq = np.unique(raw, axis=0) out = np.zeros((colours, 3), dtype=np.uint8) out[: len(uniq)] = uniq if len(uniq) < colours: out[len(uniq) :] = uniq[-1] return out def _cells(rgb: np.ndarray) -> np.ndarray: """(H, W, 3) -> (cy, cx, 8, 8, 3).""" h, w, _ = rgb.shape return rgb.reshape(h // TILE, TILE, w // TILE, TILE, 3).transpose(0, 2, 1, 3, 4) def _cell_means(rgb: np.ndarray) -> np.ndarray: """(cy, cx, 3) mean colour per cell.""" return _cells(rgb).mean(axis=(2, 3)) def _kmeans(points: np.ndarray, k: int, rounds: int = 12, seed: int = 1) -> np.ndarray: """Labels for (N, 3) points; plain Lloyd's with k-means++-ish seeding.""" rng = np.random.default_rng(seed) centres = points[rng.choice(len(points), 1)] while len(centres) < k: d = np.min(np.sum((points[:, None, :] - centres[None]) ** 2, axis=-1), axis=1) centres = np.vstack([centres, points[rng.choice(len(points), p=d / d.sum())]]) labels = np.zeros(len(points), dtype=np.int64) for _ in range(rounds): labels = np.argmin(np.sum((points[:, None, :] - centres[None]) ** 2, axis=-1), axis=1) for i in range(k): if np.any(labels == i): centres[i] = points[labels == i].mean(axis=0) return labels def fit_lines(rgb: np.ndarray, cell_groups: np.ndarray, shade_of: np.ndarray | None) -> np.ndarray: """(LINES, PENS, 3) raw CRAM values: pen 0 black, pens 1-15 fitted to the pixels of the cells in each group. A cell already chosen as shadow contributes its pixels mapped back to the normal ramp (what CRAM must hold for the shadow ramp to show them), so the refit sees what it is actually fitting for.""" lines = np.zeros((LINES, PENS, 3), dtype=np.uint8) cells = _cells(rgb) # (cy, cx, 8, 8, 3) for line in range(LINES): mask = cell_groups == line if not np.any(mask): continue pix = cells[mask].reshape(-1, 3) if shade_of is not None: shadow_mask = (shade_of == SHADOW)[mask] if np.any(shadow_mask): sh = cells[mask][shadow_mask].reshape(-1, 3) # nearest shadow level -> same raw index -> its normal level raw = np.argmin(np.abs(sh[..., None].astype(np.int32) - LEVELS[SHADOW][None, :]), axis=-1) mapped = LEVELS[NORMAL][raw].astype(np.uint8) pix = np.concatenate([cells[mask][~shadow_mask].reshape(-1, 3), mapped]) lines[line, 1:] = _median_cut(pix, PENS - 1) return lines # -- per-cell assignment ------------------------------------------------------------- def assign_cells(rgb: np.ndarray, lines: np.ndarray) -> tuple[np.ndarray, np.ndarray, np.ndarray, float]: """For every cell choose (line, shade) and quantize its pixels. Returns (line_of (cy,cx), shade_of (cy,cx), pens (H,W) uint8, total error). """ cells = _cells(rgb) cy_n, cx_n = cells.shape[:2] best_err = np.full((cy_n, cx_n), np.inf) line_of = np.zeros((cy_n, cx_n), dtype=np.int64) shade_of = np.zeros((cy_n, cx_n), dtype=np.int64) pens = np.zeros((cy_n, cx_n, TILE, TILE), dtype=np.uint8) for line in range(LINES): for shade in (NORMAL, SHADOW): pal = raw_to_rgb(lines[line], shade) # (16, 3) dist = _weighted_dist(cells, pal) # (cy, cx, 8, 8, 16) idx = np.argmin(dist, axis=-1) err = np.take_along_axis(dist, idx[..., None], axis=-1)[..., 0].sum(axis=(2, 3)) better = err < best_err best_err = np.where(better, err, best_err) line_of = np.where(better, line, line_of) shade_of = np.where(better, shade, shade_of) pens[better] = idx[better] flat = pens.transpose(0, 2, 1, 3).reshape(rgb.shape[0], rgb.shape[1]) return line_of, shade_of, flat, float(best_err.sum()) # -- tiles and name table ------------------------------------------------------------ def _flips(t: np.ndarray) -> list[tuple[bool, bool, np.ndarray]]: return [(False, False, t), (True, False, t[:, ::-1]), (False, True, t[::-1, :]), (True, True, t[::-1, ::-1])] def build_tiles(pens: np.ndarray, line_of: np.ndarray, shade_of: np.ndarray) -> tuple[list[bytes], np.ndarray, int]: """Deduplicate cells into tiles under the four flips; fill the 64x32 name table.""" blank = tile_bytes(np.zeros((TILE, TILE), dtype=np.uint8)) tiles = [blank] index: dict[bytes, int] = {blank: 0} table = np.zeros((32, PLANE_W), dtype=np.uint16) for cy in range(CELLS_Y): for cx in range(CELLS_X): t = pens[cy * TILE : (cy + 1) * TILE, cx * TILE : (cx + 1) * TILE] tid, hf, vf = -1, False, False for h, v, variant in _flips(t): key = tile_bytes(np.ascontiguousarray(variant)) if key in index: tid, hf, vf = index[key], h, v break if tid < 0: key = tile_bytes(t) tid = len(tiles) tiles.append(key) index[key] = tid table[cy, cx] = name_word(tid, int(line_of[cy, cx]), shade_of[cy, cx] == NORMAL, hf, vf) return tiles, table, len(tiles) def predict(pens: np.ndarray, line_of: np.ndarray, shade_of: np.ndarray, lines: np.ndarray) -> np.ndarray: """What the VDP will show: each cell's pens through its line, through its shade.""" out = np.zeros((HEIGHT, WIDTH, 3), dtype=np.uint8) for cy in range(CELLS_Y): for cx in range(CELLS_X): pal = raw_to_rgb(lines[line_of[cy, cx]], int(shade_of[cy, cx])) ys, xs = slice(cy * TILE, (cy + 1) * TILE), slice(cx * TILE, (cx + 1) * TILE) out[ys, xs] = pal[pens[ys, xs]] return out # -- the whole frame ----------------------------------------------------------------- def fit_region(rgb: np.ndarray) -> tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray, list[float]]: """Fit four lines to one region (a whole frame or a band) and assign its cells. Returns (lines, line_of, shade_of, pens, error history).""" cy_n, cx_n = rgb.shape[0] // TILE, rgb.shape[1] // TILE groups = _kmeans(_cell_means(rgb).reshape(-1, 3), LINES).reshape(cy_n, cx_n) lines = fit_lines(rgb, groups, None) line_of, shade_of, pens, err = assign_cells(rgb, lines) history = [err] for _ in range(REFIT_ROUNDS): lines2 = fit_lines(rgb, line_of, shade_of) l2, s2, p2, e2 = assign_cells(rgb, lines2) if e2 >= err: break lines, line_of, shade_of, pens, err = lines2, l2, s2, p2, e2 history.append(err) return lines, line_of, shade_of, pens, history def measure_bands(rgb: np.ndarray, band_counts: tuple[int, ...] = (1, 2, 4, 7)) -> dict[int, float]: """Weighted error per pixel when the frame is split into N horizontal bands, each with its own four lines (the raster-reload technique, measured before building it).""" out = {} for n in band_counts: band_h = HEIGHT // n assert band_h % TILE == 0, n total = 0.0 for b in range(n): _, _, _, _, history = fit_region(rgb[b * band_h : (b + 1) * band_h]) total += history[-1] out[n] = total / (WIDTH * HEIGHT) return out def measure_pixel_shade(rgb: np.ndarray) -> tuple[float, float, float]: """Error per pixel with (a) per-cell shade as built, (b) a per-pixel 3-level mask over high-priority cells (the sprite-operator stretch goal: every pixel picks normal, shadow or highlight of its line's colour), (c) the mask restricted to normal/highlight only. Uses the lines fitted for (a); a refit for (b) would do better still, so (b) is a floor on the gain.""" lines, line_of, shade_of, pens, history = fit_region(rgb) cells = _cells(rgb) base = history[-1] three = 0.0 two = 0.0 for cy in range(cells.shape[0]): for cx in range(cells.shape[1]): line = lines[line_of[cy, cx]] pal3 = np.concatenate([raw_to_rgb(line, s) for s in (NORMAL, SHADOW, HIGHLIGHT)]) pal2 = np.concatenate([raw_to_rgb(line, s) for s in (NORMAL, HIGHLIGHT)]) three += _weighted_dist(cells[cy, cx], pal3).min(axis=-1).sum() two += _weighted_dist(cells[cy, cx], pal2).min(axis=-1).sum() n = rgb.shape[0] * rgb.shape[1] return base / n, three / n, two / n def encode_frame(rgb: np.ndarray) -> FrameAssets: lines, line_of, shade_of, pens, history = fit_region(rgb) err = history[-1] tiles, table, n_tiles = build_tiles(pens, line_of, shade_of) cram = [cram_word(*map(int, lines[line, pen])) for line in range(LINES) for pen in range(PENS)] expected = predict(pens, line_of, shade_of, lines) stats = { "cells": CELLS_X * CELLS_Y, "unique_tiles": n_tiles, "tile_bytes": n_tiles * 32, "shadow_cells": int((shade_of == SHADOW).sum()), "cells_per_line": [int((line_of == i).sum()) for i in range(LINES)], "weighted_error_per_pixel": err / (WIDTH * HEIGHT), "error_history": [e / (WIDTH * HEIGHT) for e in history], } return FrameAssets(cram, tiles, table, expected, stats)