#!/usr/bin/env python3 """SNES graphics helpers (no dependencies): planar tile decode, BGR555 palettes, tilemaps, OAM, a mode-1 compositor and a tiny PNG writer. Used by gfx_extract.py and gfx_render.py.""" import struct import zlib # ---- PNG ---------------------------------------------------------------------------------------------- def write_png(path, w, h, rgb): """rgb: bytes/bytearray of w*h*3.""" raw = b''.join(b'\0' + bytes(rgb[y * w * 3:(y + 1) * w * 3]) for y in range(h)) def chunk(t, d): return struct.pack('>I', len(d)) + t + d + struct.pack('>I', zlib.crc32(t + d) & 0xFFFFFFFF) with open(path, 'wb') as f: f.write(b'\x89PNG\r\n\x1a\n' + chunk(b'IHDR', struct.pack('>IIBBBBB', w, h, 8, 2, 0, 0, 0)) + chunk(b'IDAT', zlib.compress(raw, 9)) + chunk(b'IEND', b'')) def read_png_rgb(path): """Minimal PNG reader for 8-bit RGB/RGBA non-interlaced images (Mesen screenshots).""" data = open(path, 'rb').read() assert data[:8] == b'\x89PNG\r\n\x1a\n' p, idat, w = 8, b'', 0 while p < len(data): n, t = struct.unpack('>I4s', data[p:p + 8]) d = data[p + 8:p + 8 + n] if t == b'IHDR': w, h, bd, ct = struct.unpack('>IIBB', d[:10]) assert bd == 8 and ct in (2, 6), (bd, ct) bpp = 3 if ct == 2 else 4 elif t == b'IDAT': idat += d p += 12 + n raw = zlib.decompress(idat) stride = w * bpp out = bytearray(w * h * 3) prev = bytearray(stride) for y in range(h): ft = raw[y * (stride + 1)] line = bytearray(raw[y * (stride + 1) + 1:(y + 1) * (stride + 1)]) for i in range(stride): a = line[i - bpp] if i >= bpp else 0 b = prev[i] c = prev[i - bpp] if i >= bpp else 0 if ft == 1: line[i] = (line[i] + a) & 0xFF elif ft == 2: line[i] = (line[i] + b) & 0xFF elif ft == 3: line[i] = (line[i] + ((a + b) >> 1)) & 0xFF elif ft == 4: pa, pb, pc = abs(b - c), abs(a - c), abs(a + b - 2 * c) line[i] = (line[i] + (a if pa <= pb and pa <= pc else b if pb <= pc else c)) & 0xFF for x in range(w): out[(y * w + x) * 3:(y * w + x) * 3 + 3] = line[x * bpp:x * bpp + 3] prev = line return w, h, out # ---- palettes --------------------------------------------------------------------------------------- def bgr555(lo, hi): v = lo | (hi << 8) r, g, b = v & 31, (v >> 5) & 31, (v >> 10) & 31 return ((r << 3) | (r >> 2), (g << 3) | (g >> 2), (b << 3) | (b >> 2)) def palette(data): """bytes (2 per colour) -> list of (r,g,b).""" return [bgr555(data[i], data[i + 1]) for i in range(0, len(data) - 1, 2)] # ---- tiles --------------------------------------------------------------------------------------------- def tile(data, off, bpp): """One 8x8 planar tile -> 64 colour indices. 2bpp = 16 bytes, 4bpp = 32 bytes (planes 0/1 then 2/3).""" px = [0] * 64 for y in range(8): for plane in range(bpp): base = off + (plane >> 1) * 16 + y * 2 + (plane & 1) b = data[base] if base < len(data) else 0 for x in range(8): if b & (0x80 >> x): px[y * 8 + x] |= 1 << plane return px def tile_sheet(data, bpp, pal, cols=16, scale=1): """Render every tile in `data` into a sheet image: returns (w, h, rgb).""" size = 8 * bpp n = len(data) // size rows = (n + cols - 1) // cols w, h = cols * 8, rows * 8 img = bytearray(w * h * 3) for t in range(n): px = tile(data, t * size, bpp) tx, ty = (t % cols) * 8, (t // cols) * 8 for i, c in enumerate(px): r, g, b = pal[c] if c < len(pal) else (255, 0, 255) o = ((ty + i // 8) * w + tx + i % 8) * 3 img[o:o + 3] = bytes((r, g, b)) return w, h, img # ---- mode-1 compositor ------------------------------------------------------------------------------- class Layer: """A BG layer: VRAM byte offsets of its chr and 32x32 tilemap, bpp, scroll.""" def __init__(self, chr_off, map_off, bpp, hscroll=0, vscroll=0): self.chr_off, self.map_off, self.bpp = chr_off, map_off, bpp self.hscroll, self.vscroll = hscroll, vscroll def render_mode1(vram, cgram, oam, layers, main_mask, obj_base=0, obj_offset=0x2000, obj_sizes=((8, 8), (32, 32)), width=256, height=224): """Compose a frame like the PPU (mode 1, BG3 priority bit clear). layers: dict 1..3 -> Layer. main_mask: bit0 BG1, bit1 BG2, bit2 BG3, bit4 OBJ. Returns rgb bytes.""" pal = palette(cgram) # Each pixel keeps (rank, colour); higher rank wins. Mode-1 order back->front: # BG3.0, OBJ.0, BG3.1, OBJ.1, BG2.0, BG1.0, OBJ.2, BG2.1, BG1.1, OBJ.3 rank_bg = {(3, 0): 1, (3, 1): 3, (2, 0): 5, (1, 0): 6, (2, 1): 8, (1, 1): 9} rank_obj = [2, 4, 7, 10] best = [0] * (width * height) col = [pal[0]] * (width * height) tile_cache = {} def get_tile(off, bpp): k = (off, bpp) if k not in tile_cache: tile_cache[k] = tile(vram, off, bpp) return tile_cache[k] for n, L in layers.items(): if not main_mask & (1 << (n - 1)): continue for sy in range(height): # The first visible scanline is PPU line 1, so BG rows appear one line lower than vscroll says. y = (sy + L.vscroll + 1) & 0xFF for sx in range(width): x = (sx + L.hscroll) & 0xFF e = L.map_off + ((y >> 3) * 32 + (x >> 3)) * 2 word = vram[e] | (vram[e + 1] << 8) tnum, palno, prio = word & 0x3FF, (word >> 10) & 7, (word >> 13) & 1 hf, vf = word & 0x4000, word & 0x8000 px, py = x & 7, y & 7 if hf: px = 7 - px if vf: py = 7 - py c = get_tile(L.chr_off + tnum * 8 * L.bpp, L.bpp)[py * 8 + px] if c == 0: continue r = rank_bg[(n, prio)] i = sy * width + sx if r > best[i]: best[i] = r col[i] = pal[palno * (1 << L.bpp) + c] if main_mask & 0x10: # Draw sprites from last to first so lower OAM indexes end up in front within a priority. for s in range(127, -1, -1): x0, y0, t, attr = oam[s * 4:s * 4 + 4] hi = (oam[512 + s // 4] >> ((s % 4) * 2)) & 3 if hi & 1: x0 -= 256 w, h = obj_sizes[(hi >> 1) & 1] palno, prio = (attr >> 1) & 7, (attr >> 4) & 3 hf, vf = attr & 0x40, attr & 0x80 name = t | ((attr & 1) << 8) for dy in range(h): yy = (y0 + dy) & 0xFF if yy >= height: continue ty = (h - 1 - dy) if vf else dy for dx in range(w): xx = x0 + dx if xx < 0 or xx >= width: continue tx = (w - 1 - dx) if hf else dx tn = name + (ty >> 3) * 16 + (tx >> 3) row, colm = (tn >> 4) & 15, tn & 15 tn = (tn & 0x100) | (row << 4) | colm off = obj_base + tn * 32 + (obj_offset if tn & 0x100 else 0) - (0x100 * 32 if tn & 0x100 else 0) c = get_tile(off & 0xFFFF, 4)[(ty & 7) * 8 + (tx & 7)] if c == 0: continue i = yy * width + xx r = rank_obj[prio] if r >= best[i]: best[i] = r col[i] = pal[128 + palno * 16 + c] out = bytearray(width * height * 3) for i, (r, g, b) in enumerate(col): out[i * 3:i * 3 + 3] = bytes((r, g, b)) return out def diff_stats(a, b): """Fraction of pixels whose RGB differs by more than 8 per channel.""" n = len(a) // 3 bad = sum(1 for i in range(n) if max(abs(a[i * 3 + k] - b[i * 3 + k]) for k in range(3)) > 8) return bad / n