#!/usr/bin/env python3 """Scanline SNES PPU renderer for scr_snes frames (reference for the C++ menu renderer). render_frame(snes, hdma_lines) -> 256x224 list of (r, g, b): starts from snes.frame_start (registers at the start of the frame), applies that frame's HDMA writes before each scanline, and composes BG1-4 / OBJ with priorities, windows, colour math and brightness. Modes 0, 1 and 7 are what TBG's screens use; 2-6 are handled as plain 4/8bpp layers (no offset-per-tile), which is enough for this game. """ import os import sys import types import zlib import struct sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) import scr_snes # noqa: E402 # Layer bit depths per BG mode (None = layer absent). BPP = {0: (2, 2, 2, 2), 1: (4, 4, 2, None), 2: (4, 4, None, None), 3: (8, 4, None, None), 4: (8, 2, None, None), 5: (4, 2, None, None), 6: (4, None, None, None), 7: (8, None, None, None)} def write_png(path, img): h = len(img) w = len(img[0]) raw = b''.join(b'\x00' + bytes(c for px in row for c in px) for row in img) def chunk(t, d): return struct.pack('>I', len(d)) + t + d + struct.pack('>I', zlib.crc32(t + d) & 0xFFFFFFFF) data = 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, 6)) + chunk(b'IEND', b'') open(path, 'wb').write(data) def color(cg, idx): v = cg[2 * idx] | (cg[2 * idx + 1] << 8) return (v & 31, (v >> 5) & 31, (v >> 10) & 31) class TileCache: """Decoded 8x8 tile rows: key (vram byte address of the tile, bpp) -> list of 8 rows of 8 colour indices.""" def __init__(self, vram): self.vram = vram self.c = {} def get(self, addr, bpp): k = (addr, bpp) t = self.c.get(k) if t is None: v = self.vram t = [] for y in range(8): row = [0] * 8 for plane_pair in range(bpp // 2): base = (addr + plane_pair * 16 + 2 * y) & 0xFFFF p0, p1 = v[base], v[(base + 1) & 0xFFFF] for x in range(8): bit = 7 - x row[x] |= (((p0 >> bit) & 1) | (((p1 >> bit) & 1) << 1)) << (2 * plane_pair) t.append(row) self.c[k] = t return t def _window_mask(st, sel_shift, line_mask_bits): """Per-pixel boolean list for one layer's window (sel byte nibble, logic 2 bits); None = window disabled.""" sel, logic = line_mask_bits w1_en, w1_inv, w2_en, w2_inv = sel & 2, sel & 1, sel & 8, sel & 4 if not (w1_en or w2_en): return None l1, r1, l2, r2 = st.wpos out = [] for x in range(256): a = (l1 <= x <= r1) != bool(w1_inv) if w1_en else None b = (l2 <= x <= r2) != bool(w2_inv) if w2_en else None if a is None: out.append(b) elif b is None: out.append(a) elif logic == 0: out.append(a or b) elif logic == 1: out.append(a and b) elif logic == 2: out.append(a != b) else: out.append(a == b) return out def _layer_window_settings(st, layer): """(4-bit select nibble, 2-bit logic) for BG1-4 (0-3), OBJ (4), colour window (5).""" if layer < 2: sel = (st.w12sel >> (4 * layer)) & 0xF elif layer < 4: sel = (st.w34sel >> (4 * (layer - 2))) & 0xF else: sel = (st.wobjsel >> (4 * (layer - 4))) & 0xF logic = (st.wbglog >> (2 * layer)) & 3 if layer < 4 else (st.wobjlog >> (2 * (layer - 4))) & 3 return sel, logic def _bg_line(st, vram, tiles, layer, y, bpp, mode): """Colour indices (CGRAM index or 0) and priority bit for 256 pixels of BG `layer` on scanline y.""" sc = st.bgsc[layer] map_base = (sc & 0xFC) << 9 # bytes wide, tall = sc & 1, sc & 2 chr_base = st.bgnba[layer] << 13 big = (st.bgmode >> (4 + layer)) & 1 tsize = 16 if big else 8 hofs, vofs = st.hofs[layer], st.vofs[layer] pal_base = 0 if mode == 0: pal_base = layer * 32 yy = (y + vofs) & 0x3FF out = [0] * 256 pri = [0] * 256 ty = yy // tsize for x in range(256): xx = (x + hofs) & 0x3FF tx = xx // tsize # 32x32 screens; wide/tall maps place the next screen after it mx, my = tx & 0x3F, ty & 0x3F if tsize == 16: mx, my = (xx >> 4) & 0x3F, (yy >> 4) & 0x3F scr = 0 if mx >= 32 and wide: scr += 1 if my >= 32 and tall: scr += 2 if wide else 1 e_addr = (map_base + scr * 0x800 + ((my & 31) * 32 + (mx & 31)) * 2) & 0xFFFF e = vram[e_addr] | (vram[(e_addr + 1) & 0xFFFF] << 8) tile = e & 0x3FF pal = (e >> 10) & 7 hf, vf = e & 0x4000, e & 0x8000 px, py = xx % tsize, yy % tsize if hf: px = tsize - 1 - px if vf: py = tsize - 1 - py if tsize == 16: tile += (1 if px >= 8 else 0) + (16 if py >= 8 else 0) px &= 7 py &= 7 t = tiles.get((chr_base + tile * 8 * bpp) & 0xFFFF, bpp) ci = t[py][px] if ci: if bpp == 8: out[x] = ci else: out[x] = pal_base + pal * (1 << bpp) + ci pri[x] = (e >> 13) & 1 return out, pri def _mode7_line(st, vram, y): a, b, c, d, cx, cy = [v - 0x10000 if i < 4 and v & 0x8000 else v for i, v in enumerate(st.m7)] cx = cx - 0x2000 if cx & 0x1000 else cx cy = cy - 0x2000 if cy & 0x1000 else cy h = st.m7hofs - 0x2000 if st.m7hofs & 0x1000 else st.m7hofs v = st.m7vofs - 0x2000 if st.m7vofs & 0x1000 else st.m7vofs sel = st.m7sel yy = 255 - y if sel & 2 else y out = [0] * 256 def clip(n): # 10-bit signed, as the hardware does for (scroll - centre) n &= 0x3FF return n - 0x400 if n & 0x200 else n hx = clip(h - cx) vy = clip(v - cy) base_x = ((a * hx) & ~63) + ((b * yy) & ~63) + ((b * vy) & ~63) + (cx << 8) base_y = ((c * hx) & ~63) + ((d * yy) & ~63) + ((d * vy) & ~63) + (cy << 8) for x in range(256): xx = 255 - x if sel & 1 else x px = (base_x + a * xx) >> 8 py = (base_y + c * xx) >> 8 outside = px < 0 or py < 0 or px >= 1024 or py >= 1024 if outside and sel & 0x80: if sel & 0x40: # fill with tile 0 tile = 0 else: continue # transparent else: tile = vram[(((py >> 3) & 127) * 128 + ((px >> 3) & 127)) * 2] ci = vram[(tile * 64 + (py & 7) * 8 + (px & 7)) * 2 + 1] out[x] = ci return out def _obj_line(st, vram, oam, tiles, y): """Per-pixel (cgram index, priority) for sprites on scanline y; index 0 = none. Up to 32 sprites per line.""" sizes = [((8, 8), (16, 16)), ((8, 8), (32, 32)), ((8, 8), (64, 64)), ((16, 16), (32, 32)), ((16, 16), (64, 64)), ((32, 32), (64, 64)), ((16, 32), (32, 64)), ((16, 32), (32, 32))][(st.obsel >> 5) & 7] base = (st.obsel & 7) << 14 gap = (((st.obsel >> 3) & 3) + 1) << 13 col = [0] * 256 pri = [0] * 256 count = 0 for i in range(128): o = i * 4 hi = oam[0x200 + i // 4] >> (2 * (i % 4)) x = oam[o] | ((hi & 1) << 8) if x >= 256: x -= 512 sy = oam[o + 1] tile = oam[o + 2] attr = oam[o + 3] w, h = sizes[1 if hi & 2 else 0] dy = (y - sy) & 0xFF if dy >= h: continue count += 1 if count > 32: break vf, hf = attr & 0x80, attr & 0x40 prio = (attr >> 4) & 3 pal = (attr >> 1) & 7 name = tile | ((attr & 1) << 8) ly = h - 1 - dy if vf else dy for px in range(w): sx = x + px if sx < 0 or sx >= 256 or col[sx]: continue # lower OAM index wins lx = w - 1 - px if hf else px n = name row_t = ((n >> 4) + (ly >> 3)) & 0xF col_t = ((n & 0xF) + (lx >> 3)) & 0xF nn = (n & 0x100) | (row_t << 4) | col_t addr = (base + (gap if nn & 0x100 else 0) + (nn & 0xFF) * 32) & 0xFFFF ci = tiles.get(addr, 4)[ly & 7][lx & 7] if ci: col[sx] = 128 + pal * 16 + ci pri[sx] = prio return col, pri def render_frame(snes, hdma_lines): st = types.SimpleNamespace(**{k: (list(v) if isinstance(v, list) else v) for k, v in snes.frame_start.items()}) st.reg, st.cpu, st.vram, st.cgram, st.oam = {}, snes.cpu, snes.vram, snes.cgram, snes.oam write = scr_snes.SNES.ppu_write.__get__(st) st._vram_word = scr_snes.SNES._vram_word.__get__(st) st._vram_step = scr_snes.SNES._vram_step.__get__(st) st._vread = scr_snes.SNES._vread.__get__(st) vram, cg, oam = snes.vram, snes.cgram, snes.oam tiles = TileCache(vram) img = [] for y in range(224): for reg, val in (hdma_lines[y] if y < len(hdma_lines) else []): write(reg, val) img.append(_render_line(st, vram, cg, oam, tiles, y + 1)) # BG line y+1 shows on screen line y return img def _render_line(st, vram, cg, oam, tiles, y): bright = st.inidisp & 0xF if st.inidisp & 0x80: return [(0, 0, 0)] * 256 mode = st.bgmode & 7 layers = {} if mode == 7: layers[0] = (_mode7_line(st, vram, y), [0] * 256) else: for L, bpp in enumerate(BPP[mode]): if bpp and ((st.tm | st.ts) >> L) & 1: layers[L] = _bg_line(st, vram, tiles, L, y, bpp, mode) obj = _obj_line(st, vram, oam, tiles, y - 1) if (st.tm | st.ts) & 0x10 else ([0] * 256, [0] * 256) # Priority order (front to back), as (layer, priority-bit) / ('o', obj priority) if mode == 0: order = [('o', 3), (0, 1), (1, 1), ('o', 2), (0, 0), (1, 0), ('o', 1), (2, 1), (3, 1), ('o', 0), (2, 0), (3, 0)] elif mode == 1: bg3hi = bool(st.bgmode & 8) order = ([(2, 1)] if bg3hi else []) + [('o', 3), (0, 1), (1, 1), ('o', 2), (0, 0), (1, 0), ('o', 1)] + \ ([] if bg3hi else [(2, 1)]) + [('o', 0), (2, 0)] elif mode == 7: order = [('o', 3), ('o', 2), ('o', 1), (0, 0), ('o', 0)] else: order = [('o', 3), (0, 1), ('o', 2), (1, 1), ('o', 1), (0, 0), ('o', 0), (1, 0)] win = {L: _window_mask(st, 0, _layer_window_settings(st, L)) for L in range(5)} cwin = _window_mask(st, 0, _layer_window_settings(st, 5)) def compose(mask, wmask): out_c = [0] * 256 out_l = [5] * 256 # 5 = backdrop for x in range(256): for o in order: if o[0] == 'o': if not (mask & 0x10) or (wmask & 0x10 and win[4] and win[4][x]): continue if obj[0][x] and obj[1][x] == o[1]: out_c[x], out_l[x] = obj[0][x], 4 break else: L, p = o if L not in layers or not (mask >> L) & 1: continue if (wmask >> L) & 1 and win[L] and win[L][x]: continue c, pr = layers[L] if c[x] and pr[x] == p: out_c[x], out_l[x] = c[x], L break return out_c, out_l main_c, main_l = compose(st.tm, st.tmw) math_on = st.cgadsub & 0x3F sub_c, sub_l = compose(st.ts, st.tsw) if math_on and st.cgwsel & 2 else (None, None) fixed = tuple(st.coldata) line = [] for x in range(256): c = color(cg, main_c[x]) layer = main_l[x] # colour math do_math = False if math_on: enabled = (st.cgadsub >> layer) & 1 if layer != 4 else ((st.cgadsub >> 4) & 1 and obj[0][x] >= 192) if layer == 5: enabled = (st.cgadsub >> 5) & 1 region = (st.cgwsel >> 4) & 3 # prevent-math region in_w = cwin[x] if cwin else False blocked = region == 3 or (region == 1 and not in_w) or (region == 2 and in_w) do_math = enabled and not blocked clip = (st.cgwsel >> 6) & 3 in_w = cwin[x] if cwin else False if clip == 3 or (clip == 1 and not in_w) or (clip == 2 and in_w): c = (0, 0, 0) if do_math: if sub_c is not None: o = color(cg, sub_c[x]) if sub_l[x] != 5 else fixed half = st.cgadsub & 0x40 and sub_l[x] != 5 else: o = fixed half = st.cgadsub & 0x40 if st.cgadsub & 0x80: c = tuple(max(0, a - b) for a, b in zip(c, o)) else: c = tuple(min(31, a + b) for a, b in zip(c, o)) if half: c = tuple(v >> 1 for v in c) k = bright / 15 line.append(tuple(int(((v << 3) | (v >> 2)) * k) for v in c)) return line