# SPDX-License-Identifier: MIT AND ISC """The PPU's picture units: backgrounds, objects, windows, colour math. Ported from ares 9408cb4 ``sfc/ppu`` (ISC, notice below and in NOTICE): ``background.cpp``, ``mode7.cpp``, ``mosaic.cpp``, ``object.cpp``, ``oam.cpp`` (the size tables), ``window.cpp`` and ``dac.cpp``. ares is this board's worked model (OBSERVED, ares, per function); the register meanings, the BG mode table, the OAM layout, the window logic and the colour math are also stated by fullsnes ("SNES PPU Registers", "SNES PPU Video Memory", "SNES PPU Window", "SNES PPU Color-Math", "OBSEL") and anomie regs (DOC). The structure is ares's: the PPU's cycle schedule (``ppu.py``) calls these units at the clocks ares calls them, so a register written in the middle of a line takes effect at the pixel ares puts it. The code is Python written for reading and for PyPy: state is plain ints and preallocated lists, with no object made per pixel. ares notice (ISC): Copyright (c) 2004-2025 ares team, Near et al. Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE. """ from __future__ import annotations from typing import TYPE_CHECKING, Iterator if TYPE_CHECKING: from snes_python.ppu import PPU # Background colour depths (OBSERVED: ares Background::Mode). BPP2, BPP4, BPP8, MODE7, INACTIVE = 0, 1, 2, 3, 4 def _spread(byte: int) -> int: """Bit i of ``byte`` to bit 2i (two bitplanes interleaved per pixel).""" out = 0 for i in range(8): out |= ((byte >> i) & 1) << (2 * i) return out def _reverse8(byte: int) -> int: return int(f"{byte:08b}"[::-1], 2) # A tile row's planes interleaved so the next pixel is the low two bits # (OBSERVED: ares Background::fetchCharacter). The SNES stores the leftmost # pixel in bit 7 (DOC: fullsnes "SNES PPU Video Memory"), so an unmirrored # row is bit-reversed first. SPREAD = [_spread(b) for b in range(256)] SPREAD_REVERSED = [_spread(_reverse8(b)) for b in range(256)] def _signed13(value: int) -> int: value &= 0x1FFF return value - 0x2000 if value & 0x1000 else value def _signed16(value: int) -> int: value &= 0xFFFF return value - 0x10000 if value & 0x8000 else value def _clip(n: int) -> int: """13-bit sign extension of a mode 7 offset (OBSERVED: ares runMode7).""" return n | ~1023 if n & 0x2000 else n & 1023 class Mosaic: """The shared vertical mosaic counter (OBSERVED: ares mosaic.cpp).""" def __init__(self, ppu: PPU) -> None: self.ppu = ppu # HYPOTHESIS: power-on size 1 (ares randomises it). self.size = 1 self.vcounter = 0 def enable(self) -> bool: ppu = self.ppu return ( ppu.bg1.mosaic_enable or ppu.bg2.mosaic_enable or ppu.bg3.mosaic_enable or ppu.bg4.mosaic_enable ) def voffset(self) -> int: return self.size - self.vcounter def scanline(self) -> None: if self.ppu.line == 1: self.vcounter = self.size + 1 if self.enable() else 0 if self.vcounter: self.vcounter -= 1 if not self.vcounter: self.vcounter = self.size if self.enable() else 0 class Background: """One BG layer (OBSERVED: ares background.cpp, mode7.cpp).""" def __init__(self, ppu: PPU, index: int) -> None: self.ppu = ppu self.id = index # BGnSC, BGnmNBA, BGMODE (DOC: fullsnes "2107h-210Ch", "2105h"). self.screen_size = 0 self.screen_address = 0 self.tiledata_address = 0 self.tile_size = 0 self.mode = BPP2 self.priority0 = 0 self.priority1 = 0 self.above_enable = False self.below_enable = False self.hoffset = 0 self.voffset = 0 # The pixel handed to the window and colour math units this dot. self.above_priority = 0 self.above_palette = 0 self.above_group = 0 self.below_priority = 0 self.below_palette = 0 self.below_group = 0 # Horizontal mosaic. self.mosaic_enable = False self.mosaic_hcounter = 0 self.mosaic_hoffset = 0 self.mosaic_priority = 0 self.mosaic_palette = 0 self.mosaic_group = 0 # Offset-per-tile entries (BG3 fetches them for BG1/BG2). self.opt_hoffset = 0 self.opt_voffset = 0 # The line's tiles: 33 columns, 66 in hi-res. self.t_address = [0] * 66 self.t_palette = [0] * 66 self.t_group = [0] * 66 self.t_priority = [0] * 66 self.t_hmirror = [0] * 66 self.t_data = [[0] * 66 for _ in range(4)] self.rendering_index = 0 self.pixel_counter = 0 def scanline(self) -> None: """At H=0 of every line (OBSERVED: ares Background::scanline).""" ppu = self.ppu self.mosaic_hcounter = ppu.mosaic.size self.mosaic_hoffset = 0 self.rendering_index = 0 self.pixel_counter = ((self.hoffset & 7) << ppu.bg_hires) & 7 self.opt_hoffset = 0 self.opt_voffset = 0 def begin(self) -> None: """At H=56: drop the first tile's pixels scrolled off the left.""" shift = self.pixel_counter << 1 for plane in self.t_data: plane[0] >>= shift def fetch_name_table(self, h: int, _a: int = 0, _b: int = 0) -> None: ppu = self.ppu v = ppu.line if v == 0: return hires = ppu.bg_hires index = (h >> 5) << hires hpixel = ((h & ~31) >> 2) << hires vpixel = v hscroll = self.hoffset vscroll = self.voffset if hires: hscroll <<= 1 if ppu.interlace: vpixel = vpixel << 1 | (1 if ppu.board.field and not self.mosaic_enable else 0) if self.mosaic_enable: vpixel -= ppu.mosaic.voffset() << (1 if hires and ppu.interlace else 0) bg_mode = ppu.bg_mode mode = self.mode tile_size = self.tile_size screen_size = self.screen_size width = 256 << hires hmask = (width << tile_size << (screen_size & 1)) - 1 vmask = (width << tile_size << ((screen_size >> 1) & 1)) - 1 vtiles = 3 + tile_size htiles = 4 if hires else vtiles hscreen = 32 << 5 if screen_size & 1 else 0 vscreen = 32 << (5 + (screen_size & 1)) if screen_size & 2 else 0 vram = ppu.vram char_shift = 3 + mode char_mask = 0x7FFF >> char_shift char_index = self.tiledata_address >> char_shift palette_offset = self.id << 5 if bg_mode == 0 else 0 palette_shift = 2 << mode for _ in range(2 if hires else 1): hoffset = hpixel + hscroll voffset = vpixel + vscroll if bg_mode == 2 or bg_mode == 4 or bg_mode == 6: # Offset-per-tile (DOC: fullsnes "BG Offset-per-tile"; ares # fetchNameTable): bit 13 (BG1) / 14 (BG2) marks an entry # valid; mode 4 has one entry, bit 15 selecting H or V. bg3 = ppu.bg3 hlookup = bg3.opt_hoffset vlookup = bg3.opt_voffset valid = 1 << (13 + self.id) if bg_mode == 4: if hlookup & valid: if not hlookup & 0x8000: hoffset = hpixel + (hlookup & ~7) + (hscroll & 7) else: voffset = vpixel + vlookup else: if hlookup & valid: hoffset = hpixel + (hlookup & ~7) + (hscroll & 7) if vlookup & valid: voffset = vpixel + vlookup hoffset &= hmask voffset &= vmask htile = hoffset >> htiles vtile = voffset >> vtiles offset = (htile & 31) | (vtile & 31) << 5 if htile & 0x20: offset += hscreen if vtile & 0x20: offset += vscreen attributes = vram[(self.screen_address + offset) & 0x7FFF] character = attributes & 0x3FF group = (attributes >> 10) & 7 hmirror = (attributes >> 14) & 1 vmirror = attributes >> 15 if htiles == 4 and ((hoffset >> 3) & 1) != hmirror: character = (character + 1) & 0x3FF if vtiles == 4 and ((voffset >> 3) & 1) != vmirror: character = (character + 16) & 0x3FF origin = (character + char_index) & char_mask if vmirror: voffset ^= 7 self.t_address[index] = ((origin << char_shift) + (voffset & 7)) & 0xFFFF self.t_group[index] = group self.t_priority[index] = self.priority1 if attributes & 0x2000 else self.priority0 self.t_hmirror[index] = hmirror self.t_palette[index] = (palette_offset + (group << palette_shift)) & 0xFF index += 1 hpixel += 8 def fetch_offset(self, h: int, y: int, _b: int = 0) -> None: """BG3's offset-per-tile entry for the column (ares fetchOffset).""" ppu = self.ppu if ppu.line == 0: return hoffset = ((h >> 5) << 3) + (self.hoffset & ~7) voffset = y + self.voffset vtiles = 3 + self.tile_size htiles = 3 if ppu.bg_hires else vtiles htile = hoffset >> htiles vtile = voffset >> vtiles screen_size = self.screen_size offset = (htile & 31) | (vtile & 31) << 5 if htile & 0x20 and screen_size & 1: offset += 32 << 5 if vtile & 0x20 and screen_size & 2: offset += 32 << (5 + (screen_size & 1)) value = ppu.vram[(self.screen_address + offset) & 0x7FFF] if y == 0: self.opt_hoffset = value elif y == 8: self.opt_voffset = value def fetch_character(self, h: int, plane: int, half: int = 0) -> None: ppu = self.ppu if ppu.line == 0: return column = ((h >> 5) << ppu.bg_hires) + half data = ppu.vram[(self.t_address[column] + (plane << 3)) & 0x7FFF] if self.t_hmirror[column]: self.t_data[plane][column] = SPREAD[data & 0xFF] | SPREAD[data >> 8] << 1 else: self.t_data[plane][column] = ( SPREAD_REVERSED[data & 0xFF] | SPREAD_REVERSED[data >> 8] << 1 ) def run(self, below: bool, x: int) -> None: """One half-dot: ``below`` at H%4 == 0, the main half at H%4 == 2.""" ppu = self.ppu if ppu.line == 0: return hires = ppu.bg_hires if below: self.above_priority = 0 self.below_priority = 0 if not hires: return mode = self.mode if mode == MODE7: self.run_mode7() return if mode == INACTIVE: # Departure from ares, which still shifts the stale tiles of a # BG the mode does not have: nothing is drawn for it (DOC: # fullsnes "2105h - BGMODE" lists the BGs each mode has). return i = self.rendering_index data = self.t_data d = data[0][i] color = d & 3 data[0][i] = d >> 2 if mode >= BPP4: d = data[1][i] color |= (d & 3) << 2 data[1][i] = d >> 2 if mode == BPP8: d = data[2][i] color |= (d & 3) << 4 data[2][i] = d >> 2 d = data[3][i] color |= (d & 3) << 6 data[3][i] = d >> 2 priority = self.t_priority[i] palette = (self.t_palette[i] + color) & 0xFF if color else 0 group = self.t_group[i] self.pixel_counter = (self.pixel_counter + 1) & 7 if self.pixel_counter == 0: self.rendering_index = i + 1 counts = not hires or below if x == 0 and counts: self.mosaic_hcounter = ppu.mosaic.size self.mosaic_priority = priority self.mosaic_palette = palette self.mosaic_group = group elif counts and self._mosaic_tick(): self.mosaic_hcounter = ppu.mosaic.size self.mosaic_priority = priority self.mosaic_palette = palette self.mosaic_group = group elif self.mosaic_enable: priority = self.mosaic_priority palette = self.mosaic_palette group = self.mosaic_group if palette == 0: return if (not hires or not below) and self.above_enable: self.above_priority = priority self.above_palette = palette self.above_group = group if (not hires or below) and self.below_enable: self.below_priority = priority self.below_palette = palette self.below_group = group def _mosaic_tick(self) -> bool: self.mosaic_hcounter = (self.mosaic_hcounter - 1) & 0xFFFF return self.mosaic_hcounter == 0 def run_mode7(self) -> None: """One mode 7 pixel (OBSERVED: ares runMode7; DOC: wiki "Mode 7 transform", fullsnes "211Bh-2120h": products truncated to 6 fraction bits before the sum, 13-bit signed centre and offsets).""" ppu = self.ppu a = _signed16(ppu.m7a) b = _signed16(ppu.m7b) c = _signed16(ppu.m7c) d = _signed16(ppu.m7d) hcenter = _signed13(ppu.m7x) vcenter = _signed13(ppu.m7y) hoffset = _signed13(ppu.m7_hoffset) voffset = _signed13(ppu.m7_voffset) x = self.mosaic_hoffset y = ppu.line if ppu.bg1.mosaic_enable: # BG2's vertical mosaic follows BG1's enable (OBSERVED: ares). y -= ppu.mosaic.voffset() if not self.mosaic_enable: self.mosaic_hoffset += 1 elif self._mosaic_tick(): self.mosaic_hcounter = ppu.mosaic.size self.mosaic_hoffset += ppu.mosaic.size if ppu.m7_hflip: x = 255 - x if ppu.m7_vflip: y = 255 - y dh = _clip(hoffset - hcenter) dv = _clip(voffset - vcenter) origin_x = (a * dh & ~63) + (b * dv & ~63) + (b * y & ~63) + (hcenter << 8) origin_y = (c * dh & ~63) + (d * dv & ~63) + (d * y & ~63) + (vcenter << 8) pixel_x = (origin_x + a * x) >> 8 pixel_y = (origin_y + c * x) >> 8 palette_address = (pixel_y & 7) << 3 | (pixel_x & 7) tile_address = ((pixel_y >> 3) & 127) << 7 | ((pixel_x >> 3) & 127) out_of_bounds = (pixel_x | pixel_y) & ~1023 repeat = ppu.m7_repeat vram = ppu.vram # DOC: fullsnes "211Ah - M7SEL": 2 = transparent outside, 3 = tile 0 # outside the 1024x1024 map. tile = 0 if repeat == 3 and out_of_bounds else vram[tile_address] & 0xFF palette = 0 if repeat == 2 and out_of_bounds else vram[tile << 6 | palette_address] >> 8 if self.id == 0: priority = self.priority0 else: # EXTBG: bit 7 is BG2's priority (DOC: fullsnes "2133h - SETINI"). priority = self.priority1 if palette & 0x80 else self.priority0 palette &= 0x7F if palette == 0: return if self.above_enable: self.above_priority = priority self.above_palette = palette self.above_group = 0 if self.below_enable: self.below_priority = priority self.below_palette = palette self.below_group = 0 # OBJ sizes per OBSEL bits 5-7 (DOC: fullsnes "2101h - OBSEL"; 6 and 7 are # the undocumented 16x32/32x64 and 16x32/32x32). _SMALL_W = (8, 8, 8, 16, 16, 32, 16, 16) _SMALL_H = (8, 8, 8, 16, 16, 32, 32, 32) _LARGE_W = (16, 32, 64, 32, 64, 64, 32, 32) _LARGE_H = (16, 32, 64, 32, 64, 64, 64, 32) class Objects: """Sprites: range evaluation, the sliver fetch, the line's pixels (OBSERVED: ares object.cpp; DOC: fullsnes "OBJ", wiki/Sprites).""" def __init__(self, ppu: PPU) -> None: self.ppu = ppu self.above_enable = False self.below_enable = False self.interlace = False self.tiledata_address = 0 self.nameselect = 0 self.base_size = 0 self.priority = [0, 0, 0, 0] self.first_sprite = 0 self.above_priority = 0 self.above_palette = 0 self.below_priority = 0 self.below_palette = 0 self.x = 0 self.y = 0 self.item_count = 0 self.tile_count = 0 self.active = 0 # Two buffers: the line being evaluated and fetched, the line drawn. self.items = [[0] * 32, [0] * 32] self.n_items = [0, 0] self.tile_x = [[0] * 34, [0] * 34] self.tile_priority = [[0] * 34, [0] * 34] self.tile_palette = [[0] * 34, [0] * 34] self.tile_hflip = [[0] * 34, [0] * 34] self.tile_data = [[0] * 34, [0] * 34] self.n_tiles = [0, 0] # The drawn line resolved once: palette index (0 = none) and the # OAM priority of the sprite that wins each of the 256 dots. The # tiles are fixed once fetched, so this equals ares's per-dot walk # over the 34 slivers; enables and the priority map are applied per dot. self.line_palette = [0] * 256 self.line_priority = [0] * 256 self.line_ready = False def size(self, large: int) -> tuple[int, int]: base = self.base_size if large: return _LARGE_W[base], _LARGE_H[base] height = _SMALL_H[base] if self.interlace and base >= 6: # OBSERVED (ares OAM::Object::height): small 16x32 objects are # 16 high with OBJ interlace. height = 16 return _SMALL_W[base], height def sprite(self, n: int) -> tuple[int, int, int, int, int]: """(x, y, character, attributes, large) of object ``n`` from OAM (DOC: fullsnes "OAM Content").""" oam = self.ppu.oam high = oam[0x200 | n >> 2] >> ((n & 3) << 1) base = n << 2 return ( oam[base] | (high & 1) << 8, oam[base + 1], oam[base + 2], oam[base + 3], (high >> 1) & 1, ) def frame(self) -> None: ppu = self.ppu ppu.time_over = False ppu.range_over = False def scanline(self) -> None: ppu = self.ppu self.first_sprite = ppu.first_sprite self.x = 0 self.y = ppu.line self.item_count = 0 self.tile_count = 0 self.active ^= 1 self.n_items[self.active] = 0 self.n_tiles[self.active] = 0 self.line_ready = False if self.y == ppu.vdisp and not ppu.display_disable: # DOC: fullsnes "OAM": the OAM address reloads at V-Blank start # unless force-blanked (ares Object::scanline). ppu._oam_address_reset() def on_scanline(self, x: int, y: int, large: int) -> bool: width, height = self.size(large) # Objects wholly off the left edge are not in range (X = 256 is; # DOC: wiki/Sprites "X coordinate -256"). if x > 256 and x + width - 1 < 512: return False height >>= self.interlace return ((self.y - y) & 255) < height def evaluate(self, index: int) -> None: """One OAM entry checked for range, every 8 clocks (H = 8 * index).""" ppu = self.ppu if ppu.display_disable or self.item_count > 32: return n = (self.first_sprite + index) & 127 x, y, _, _, large = self.sprite(n) if not self.on_scanline(x, y, large): return ppu.render_oam_address = n if self.item_count < 32: buffer = self.active self.items[buffer][self.item_count] = n self.n_items[buffer] = self.item_count + 1 self.item_count += 1 if self.item_count > 32: # Departure from ares (which sets the flag after the sliver # fetch). DOC: fullsnes "213Eh - STAT77": "Bit6 when # V=OBJ.YLOC/H=OAM.INDEX*2", on the evaluation line. MEASURED # (probe suite OBJF D1, D4, the console 2026-10-25): bit 6 is # seen on line 99 at dot $5C/$61 for objects drawn from line 100. ppu.range_over = True def fetch(self) -> Iterator[int]: """The sliver fetch from H=1080: yields the clocks each step takes (OBSERVED: ares Object::fetch; 2 VRAM words per 8x1 sliver, 4 clocks each, up to 34 slivers, the last-found object first).""" ppu = self.ppu buffer = self.active items = self.items[buffer] tile_x = self.tile_x[buffer] tile_priority = self.tile_priority[buffer] tile_palette = self.tile_palette[buffer] tile_hflip = self.tile_hflip[buffer] tile_data = self.tile_data[buffer] vram = ppu.vram for i in range(self.n_items[buffer] - 1, -1, -1): if ppu.display_disable or ppu.line >= ppu.vdisp - 1: yield 8 continue n = items[i] ppu.render_oam_address = n sx0, sy, character, attributes, large = self.sprite(n) width, height = self.size(large) vflip = attributes >> 7 hflip = (attributes >> 6) & 1 tile_width = width >> 3 y = (self.y - sy) & 255 if self.interlace: y <<= 1 if vflip: if width == height: y = height - 1 - y elif y < width: y = width - 1 - y else: y = width + (width - 1) - (y - width) if self.interlace: y = y - ppu.board.field if vflip else y + ppu.board.field x = sx0 & 511 y &= 255 tiledata = self.tiledata_address if attributes & 1: tiledata = (tiledata + ((1 + self.nameselect) << 12)) & 0xFFFF chrx = character & 15 chry = (((character >> 4) + (y >> 3)) & 15) << 4 for tx in range(tile_width): sx = (x + (tx << 3)) & 511 if x != 256 and sx >= 256 and sx + 7 < 512: continue count = self.tile_count self.tile_count = count + 1 if count >= 34: break self.n_tiles[buffer] = count + 1 tile_x[count] = sx tile_priority[count] = (attributes >> 4) & 3 tile_palette[count] = 128 + (((attributes >> 1) & 7) << 4) tile_hflip[count] = hflip mx = tile_width - 1 - tx if hflip else tx pos = tiledata + ((chry + ((chrx + mx) & 15)) << 4) address = ((pos & 0xFFF0) + (y & 7)) & 0xFFFF if not ppu.display_disable: tile_data[count] = tile_data[count] & 0xFFFF0000 | vram[address & 0x7FFF] yield 4 if not ppu.display_disable: tile_data[count] = ( tile_data[count] & 0xFFFF | vram[(address + 8) & 0x7FFF] << 16 ) yield 4 # DOC: fullsnes "213Eh - STAT77": 33rd object in range, 35th sliver. if self.item_count > 32: ppu.range_over = True if self.tile_count > 34: ppu.time_over = True def _build_line(self) -> None: buffer = self.active ^ 1 line_palette = self.line_palette line_priority = self.line_priority for i in range(256): line_palette[i] = 0 tile_x = self.tile_x[buffer] tile_priority = self.tile_priority[buffer] tile_palette = self.tile_palette[buffer] tile_hflip = self.tile_hflip[buffer] tile_data = self.tile_data[buffer] for n in range(self.n_tiles[buffer]): tx = tile_x[n] if tx & 0x100: tx -= 0x200 data = tile_data[n] hflip = tile_hflip[n] for px in range(8): sx = tx + px if sx < 0 or sx > 255: continue shift = px if hflip else 7 - px color = ( (data >> shift) & 1 | (data >> (shift + 7)) & 2 | (data >> (shift + 14)) & 4 | (data >> (shift + 21)) & 8 ) if color: line_palette[sx] = tile_palette[n] + color line_priority[sx] = tile_priority[n] self.line_ready = True def run(self) -> None: self.above_priority = 0 self.below_priority = 0 if not self.line_ready: self._build_line() x = self.x self.x = x + 1 if x > 255: return palette = self.line_palette[x] if palette: priority = self.priority[self.line_priority[x]] if self.above_enable: self.above_palette = palette self.above_priority = priority if self.below_enable: self.below_palette = palette self.below_priority = priority class Window: """The two windows per layer and the colour window (OBSERVED: ares window.cpp; DOC: fullsnes "2123h-212Bh", "212Eh/212Fh", "2130h").""" # Layers 0-3 are BG1-4, 4 is OBJ, 5 is the colour window. def __init__(self, ppu: PPU) -> None: self.ppu = ppu self.one_enable = [0] * 6 self.one_invert = [0] * 6 self.two_enable = [0] * 6 self.two_invert = [0] * 6 self.mask = [0] * 6 self.above_enable = [0] * 5 self.below_enable = [0] * 5 self.col_above_mask = 0 self.col_below_mask = 0 self.one_left = 0 self.one_right = 0 self.two_left = 0 self.two_right = 0 self.above_color_enable = False self.below_color_enable = False self.x = 0 def scanline(self) -> None: self.x = 0 def test(self, layer: int, one: bool, two: bool) -> bool: if not self.one_enable[layer]: return bool(self.two_enable[layer]) and two != bool(self.two_invert[layer]) one = one != bool(self.one_invert[layer]) if not self.two_enable[layer]: return one two = two != bool(self.two_invert[layer]) mask = self.mask[layer] if mask == 0: return one or two if mask == 1: return one and two # 2 = XOR, 3 = XNOR. return (one != two) == (mask == 2) def run(self) -> None: x = self.x self.x = x + 1 one = self.one_left <= x <= self.one_right two = self.two_left <= x <= self.two_right ppu = self.ppu layers = ppu.bgs for i in range(4): if (self.one_enable[i] or self.two_enable[i]) and self.test(i, one, two): bg = layers[i] if self.above_enable[i]: bg.above_priority = 0 if self.below_enable[i]: bg.below_priority = 0 if (self.one_enable[4] or self.two_enable[4]) and self.test(4, one, two): obj = ppu.obj if self.above_enable[4]: obj.above_priority = 0 if self.below_enable[4]: obj.below_priority = 0 value = self.test(5, one, two) # Regions: 0 never, 1 outside the window, 2 inside, 3 always; the # "enable" is True where the main colour is kept / math is allowed. above = self.col_above_mask below = self.col_below_mask self.above_color_enable = above == 0 or (above == 1 and value) or (above == 2 and not value) self.below_color_enable = below == 0 or (below == 1 and value) or (below == 2 and not value) class DAC: """Priority between the layers, colour math, the frame buffer (OBSERVED: ares dac.cpp; DOC: fullsnes "SNES PPU Color-Math").""" def __init__(self, ppu: PPU) -> None: self.ppu = ppu self.direct_color = False self.blend_mode = False # CGADSUB enables for BG1-4, OBJ, backdrop. self.color_enable = [False] * 6 self.color_halve = False self.color_mode = False self.color_red = 0 self.color_green = 0 self.color_blue = 0 self.m_above_color = 0 self.m_below_color = 0 self.m_above_enable = False self.m_below_enable = False self.m_transparent = True self.m_blend_mode = False self.m_color_halve = False # The frame buffer: 478 rows of 512 raw DAC words (bits 0-14 BGR555, # bits 15-18 INIDISP brightness), two per dot: the sub-screen / # hi-res half first, then the main-screen half. Line V (1-239) is # row 2*(V-1), plus the field bit when interlaced. self.frame_buffer = [0] * (512 * 478) self.row_hires = [False] * 478 self.base = -1 self.row = 0 self.frame_interlace = False self.frame_overscan = False def scanline(self) -> None: ppu = self.ppu v = ppu.line self.base = -1 if 1 <= v <= 239: row = (v - 1) << 1 if self.frame_interlace and ppu.board.field: row += 1 self.row = row self.base = row * 512 self.row_hires[row] = False # OBSERVED (ares DAC::scanline): the line starts from the backdrop, # math off ("exact value initializations are not confirmed on # hardware", ares's own note). self.m_above_color = self.palette_color(0) self.m_below_color = self.m_above_color self.m_above_enable = False self.m_below_enable = False self.m_transparent = True self.m_blend_mode = False self.m_color_halve = False def palette_color(self, palette: int) -> int: ppu = self.ppu # The PPU's CGRAM address follows its own lookups (Q16). ppu.render_cgram_address = palette return ppu.cgram[palette] def fixed_color(self) -> int: return self.color_red | self.color_green << 5 | self.color_blue << 10 @staticmethod def direct(palette: int, group: int) -> int: """Direct colour (DOC: fullsnes "2130h - CGWSEL" bit 0: BBGGGRRR plus the tile's palette bits bgr as the low bits).""" return ( (palette << 7 & 0x6000) + (group << 10 & 0x1000) + (palette << 4 & 0x0380) + (group << 5 & 0x0040) + (palette << 2 & 0x001C) + (group << 1 & 0x0002) ) def blend(self, x: int, y: int) -> int: """Add or subtract per 5-bit channel, clamped, optionally halved.""" if not self.color_mode: if not self.m_color_halve: total = x + y carry = (total - ((x ^ y) & 0x0421)) & 0x8420 return ((total - carry) | (carry - (carry >> 5))) & 0x7FFF return ((x + y - ((x ^ y) & 0x0421)) >> 1) & 0x7FFF diff = x - y + 0x8420 borrow = (diff - ((x ^ y) & 0x8420)) & 0x8420 value = (diff - borrow) & (borrow - (borrow >> 5)) if not self.m_color_halve: return value & 0x7FFF return ((value & 0x7BDE) >> 1) & 0x7FFF def _direct_ok(self) -> bool: mode = self.ppu.bg_mode return self.direct_color and (mode == 3 or mode == 4 or mode == 7) def below(self, hires: bool) -> int: ppu = self.ppu if ppu.display_disable or (not ppu.overscan and ppu.line >= 225): return 0 bg1, bg2, bg3, bg4 = ppu.bgs obj = ppu.obj priority = 0 if bg1.below_priority: priority = bg1.below_priority if self._direct_ok(): self.m_below_color = self.direct(bg1.below_palette, bg1.below_group) else: self.m_below_color = self.palette_color(bg1.below_palette) if bg2.below_priority > priority: priority = bg2.below_priority self.m_below_color = self.palette_color(bg2.below_palette) if bg3.below_priority > priority: priority = bg3.below_priority self.m_below_color = self.palette_color(bg3.below_palette) if bg4.below_priority > priority: priority = bg4.below_priority self.m_below_color = self.palette_color(bg4.below_palette) if obj.below_priority > priority: priority = obj.below_priority self.m_below_color = self.palette_color(obj.below_palette) self.m_transparent = priority == 0 if self.m_transparent: self.m_below_color = self.palette_color(0) if not hires: return 0 if not self.m_below_enable: return self.m_below_color if self.m_above_enable else 0 return self.blend( self.m_below_color if self.m_above_enable else 0, self.m_above_color if self.m_blend_mode else self.fixed_color(), ) def above(self) -> int: ppu = self.ppu if ppu.display_disable or (not ppu.overscan and ppu.line >= 225): return 0 bg1, bg2, bg3, bg4 = ppu.bgs obj = ppu.obj enable = self.color_enable priority = 0 if bg1.above_priority: priority = bg1.above_priority if self._direct_ok(): self.m_above_color = self.direct(bg1.above_palette, bg1.above_group) else: self.m_above_color = self.palette_color(bg1.above_palette) self.m_below_enable = enable[0] if bg2.above_priority > priority: priority = bg2.above_priority self.m_above_color = self.palette_color(bg2.above_palette) self.m_below_enable = enable[1] if bg3.above_priority > priority: priority = bg3.above_priority self.m_above_color = self.palette_color(bg3.above_palette) self.m_below_enable = enable[2] if bg4.above_priority > priority: priority = bg4.above_priority self.m_above_color = self.palette_color(bg4.above_palette) self.m_below_enable = enable[3] if obj.above_priority > priority: priority = obj.above_priority self.m_above_color = self.palette_color(obj.above_palette) # DOC: fullsnes "2131h - CGADSUB": only OBJ palettes 4-7 take # colour math. self.m_below_enable = enable[4] and obj.above_palette >= 192 if priority == 0: self.m_above_color = self.palette_color(0) self.m_below_enable = enable[5] window = ppu.window if not window.below_color_enable: self.m_below_enable = False self.m_above_enable = window.above_color_enable if not self.m_below_enable: return self.m_above_color if self.m_above_enable else 0 if self.blend_mode and self.m_transparent: # DOC: fullsnes: with the sub-screen as the addend and nothing # on it, the fixed colour is used and the result is not halved. self.m_blend_mode = False self.m_color_halve = False else: self.m_blend_mode = self.blend_mode self.m_color_halve = self.color_halve and self.m_above_enable return self.blend( self.m_above_color if self.m_above_enable else 0, self.m_below_color if self.m_blend_mode else self.fixed_color(), ) def run(self) -> None: ppu = self.ppu if ppu.line == 0: return hires = ppu.pseudo_hires or ppu.bg_hires below = self.below(hires) sub_address = ppu.render_cgram_address above = self.above() # Departure from ares (whose last lookup, the main screen's, is left # as the PPU's CGRAM address). MEASURED (probe suite CGWS and CGRS, # the console 2026-10-25, sub-screen empty, BG1 on the main screen): # writes and reads in active display land at colour 0 on all 63 rows, # where the main-screen address gave colour 1 on 7 of them; the # sub-screen lookup's address matches all 63. HYPOTHESIS for why: the # sub-screen lookup is the later of the two in a dot. Open: MIDF's # active-display write (BG1 + OBJ on the main screen) lands at colour # 1 on the console, colour 0 here. ppu.render_cgram_address = sub_address base = self.base if base < 0: return x = ppu.window.x - 1 bright = ppu.brightness << 15 buffer = self.frame_buffer i = base + (x << 1) buffer[i] = bright | (below if hires else above) buffer[i + 1] = bright | above if hires: self.row_hires[self.row] = True __all__ = ["BPP2", "BPP4", "BPP8", "DAC", "INACTIVE", "MODE7", "Background", "Mosaic", "Objects", "Window"]