"""The dot-exact background and merge engines for one visible line (rung 4). These run cycle by cycle, as NanoBoyAdvance 1.8.3's ``background.inl`` and ``merge.cpp`` do (emulator-derived; docs/timing.md "The PPU's line"), and are the board's model of what the hardware reads and when: - text BGs: a map entry every 8 dots per layer, at the dot that ``BGxHOFS``'s fine scroll makes the tile boundary, then 2 (16 colours) or 4 (256 colours) tile halfwords, each layer on its own cycle of four; the pixel for dot x leaves the shifter at cycle 4 x + 36 to 39; - affine BGs: a map byte and a tile byte per dot, BG3 on cycles 32/33 + 4 x, BG2 on 34/35; - bitmap BG2: one fetch per dot, at cycle 35 + 4 x; - the merge: dot x's top layer is chosen and its palette entry read at cycle 46 + 4 x, its blend (and the second palette read) at 48 + 4 x; dots leave in pairs, green swap applied. Everything is read when it is used, so a register or memory write lands on the dots the PPU reaches after it. The board runs this engine only for lines where something the PPU reads changes (or is read by the CPU, for the waits) while it draws; other lines take the line renderer, which gives the same picture (``PPU``, docs/validation.md rung 4). ``vram_access`` and ``pram_access`` hold the last cycle (board time of its start) the engine read BG VRAM or palette RAM; a CPU access in that cycle waits one more (quirk 18). """ from __future__ import annotations from typing import TYPE_CHECKING from gba_python.ppu.compose import blend, brighten, darken if TYPE_CHECKING: from gba_python.ppu import PPU FLAG = 0x80000000 # a bitmap pixel that is a colour, not a palette index (NBA's flag) BD, OBJ = 5, 4 # merge layer numbers: BGs are 0-3 #: the BGs each mode draws, by number MODE_BGS = ((0, 1, 2, 3), (0, 1, 2), (2, 3), (2,), (2,), (2,), (), ()) class DotLine: """BG and merge engines for one visible line, started at the line's cycle 0 (``t0``).""" def __init__(self, ppu: PPU, t0: int) -> None: self.ppu = ppu self.t0 = t0 self.line = ppu.vcount self.bg_cycle = 0 # cycles the BG engine has run (NBA bg.cycle) self.merge_cycle = 0 self.buffer = [[0] * 240 for _ in range(4)] # text BGs: the tile in the shifter (NBA bg.text[id]) self.fetches = [0, 0, 0, 0] self.piso = [0, 0, 0, 0] self.remaining = [0, 0, 0, 0] self.tile_palette = [0, 0, 0, 0] self.tile_flip = [False] * 4 self.tile_address = [0, 0, 0, 0] # affine BGs: the internal point, copied at the line start (NBA bg.affine[id]) self.affine_x = [ppu.affine_current[0][0], ppu.affine_current[1][0]] self.affine_y = [ppu.affine_current[0][1], ppu.affine_current[1][1]] self.out_of_bounds = [False, False] self.affine_tile = [0, 0] self.vram_access = -1 self.pram_access = -1 # merge self.mosaic_x = [0, 0] self.forced_blank = False self.held = (0, 0, False, False) # the OBJ pixel latch: colour, priority, alpha, mosaic self.layers = [BD, BD] self.colors = [0, 0] self.force_alpha = False self.color_l = 0 # ----- memory as the BG engine sees it ------------------------------------------------ def _forced_blank(self) -> bool: ppu = self.ppu return bool((ppu.dispcnt_latch[0] | ppu.registers[0]) & 0x80) def _fetch16(self, cycle: int, address: int) -> int: """A BG halfword fetch (NBA ``FetchVRAM_BG``): nothing in forced blank; past the OBJ boundary the BG engine's last halfword.""" ppu = self.ppu if self._forced_blank(): return 0 latch = ppu.bg_latch if address < ppu.sprite_vram_boundary: self.vram_access = self.t0 + cycle - 1 # the cycle's start: NBA counts from one vram = ppu.vram address &= ~1 latch.value = vram[address] | vram[address + 1] << 8 return latch.value def _fetch8(self, cycle: int, address: int) -> int: ppu = self.ppu if self._forced_blank(): return 0 latch = ppu.bg_latch if address < ppu.sprite_vram_boundary: self.vram_access = self.t0 + cycle - 1 # the cycle's start: NBA counts from one vram = ppu.vram even = address & ~1 latch.value = vram[even] | vram[even + 1] << 8 return vram[address] return latch.value >> ((address & 1) << 3) & 0xFF # ----- running ------------------------------------------------------------------------ def run_to(self, now: int) -> None: """Run the engines up to (not including) board cycle ``now``.""" target = now - self.t0 if target > 1232: target = 1232 if self.bg_cycle < target: self._run_bg(target) merge_target = min(target, 1006) if self.merge_cycle < merge_target: self._run_merge(merge_target) def _run_bg(self, target: int) -> None: ppu = self.ppu registers = ppu.registers mode = registers[0] & 7 enabled = ppu.dispcnt_latch[0] & registers[0] text_ids = (0, 1, 2, 3) if mode == 0 else (0, 1) if mode == 1 else () text_on = [bool(enabled & 0x100 << i) and i in text_ids for i in range(4)] affine_on = [ (mode == 1 or mode == 2) and bool(enabled & 0x400), mode == 2 and bool(enabled & 0x800), ] bitmap_on = 3 <= mode <= 5 and bool(enabled & 0x400) for bg_cycle in range(self.bg_cycle, target): cycle = bg_cycle + 1 # NBA counts from one here if mode <= 1: bg = cycle & 3 if text_on[bg]: self._text(bg, cycle) if cycle < 1007: if mode == 1 or mode == 2: bg = ~(cycle >> 1) & 1 # 0: BG2, 1: BG3 if affine_on[bg] and cycle >= 32: self._affine(bg, cycle) elif bitmap_on and cycle >= 32 and cycle & 3 == 3: self._bitmap(mode, cycle) self.bg_cycle = target def _text(self, bg: int, cycle: int) -> None: ppu = self.ppu registers = ppu.registers bgcnt = registers[4 + bg] full = bgcnt & 0x80 if self.fetches[bg] > 0 and self.remaining[bg] == 0: address = self.tile_address[bg] data = self._fetch16(cycle, address) if self.tile_flip[bg]: data = (data >> 8 | data << 8) & 0xFFFF if not full: data = (data & 0xF0F0) >> 4 | (data & 0x0F0F) << 4 self.tile_address[bg] = address - 2 else: self.tile_address[bg] = address + 2 self.piso[bg] = data self.remaining[bg] = 4 self.fetches[bg] -= 1 piso = self.piso[bg] if full: index = piso & 0xFF self.piso[bg] = piso >> 8 self.remaining[bg] -= 2 else: index = piso & 15 if index: index |= self.tile_palette[bg] << 4 self.piso[bg] = piso >> 4 self.remaining[bg] -= 1 screen_x = (cycle >> 2) - 9 if 0 <= screen_x < 240: self.buffer[bg][screen_x] = index hofs = registers[8 + 2 * bg] & 0x1FF step = (cycle >> 2) + (hofs & 7) if cycle < 1007 and step >= 8 and step & 7 == 0: map_block = bgcnt >> 8 & 31 line = ppu.vcount + (registers[9 + 2 * bg] & 0x1FF) if bgcnt & 0x40: line -= ppu.bg_mosaic_y grid_x = (hofs >> 3) + (step >> 3) - 1 grid_y = line >> 3 size = bgcnt >> 14 if size == 1: map_block += grid_x >> 5 & 1 elif size == 2: map_block += grid_y >> 5 & 1 elif size == 3: map_block += (grid_x >> 5 & 1) + ((grid_y >> 5 & 1) << 1) entry = self._fetch16( cycle, (map_block << 11) + ((grid_y & 31) << 6) + ((grid_x & 31) << 1) ) # Map fetches in cycles 1004-1006 are not followed by tile fetches (NBA). if cycle < 1004: number = entry & 0x3FF flip_x = bool(entry & 0x400) tile_y = line & 7 if entry & 0x800: tile_y = 7 - tile_y tile_base = (bgcnt >> 2 & 3) << 14 self.tile_palette[bg] = entry >> 12 self.tile_flip[bg] = flip_x if full: address = tile_base + (number << 6) + (tile_y << 3) self.tile_address[bg] = address + 6 if flip_x else address self.fetches[bg] = 4 else: address = tile_base + (number << 5) + (tile_y << 2) self.tile_address[bg] = address + 2 if flip_x else address self.fetches[bg] = 2 self.remaining[bg] = 0 def _affine(self, bg: int, cycle: int) -> None: registers = self.ppu.registers bgcnt = registers[6 + bg] if not cycle & 1: log_size = bgcnt >> 14 size = 128 << log_size x = self.affine_x[bg] >> 8 y = self.affine_y[bg] >> 8 base = (0x20 + 0x10 * bg) >> 1 self.affine_x[bg] += _s16(registers[base]) # PA self.affine_y[bg] += _s16(registers[base + 2]) # PC if bgcnt & 0x2000: # wrap x &= size - 1 y &= size - 1 self.out_of_bounds[bg] = False else: self.out_of_bounds[bg] = bool((x | y) & -size) address = ((bgcnt >> 8 & 31) << 11) + ((y >> 3) << (4 + log_size)) + (x >> 3) tile = self._fetch8(cycle, address & 0xFFFF) self.affine_tile[bg] = ((bgcnt >> 2 & 3) << 14) + (tile << 6) + ((y & 7) << 3) + (x & 7) else: index = self._fetch8(cycle, self.affine_tile[bg]) if self.out_of_bounds[bg]: index = 0 x = (cycle - 32) >> 2 if x < 240: self.buffer[2 + bg][x] = index def _bitmap(self, mode: int, cycle: int) -> None: registers = self.ppu.registers screen_x = (cycle - 32) >> 2 x = self.affine_x[0] >> 8 y = self.affine_y[0] >> 8 page = 0xA000 if registers[0] & 0x10 else 0 if mode == 3: data = self._fetch16(cycle, ((y * 240 + x) * 2) & 0x1FFFF) value = data | FLAG if 0 <= x < 240 and 0 <= y < 160 else 0 elif mode == 4: data = self._fetch8(cycle, (page + y * 240 + x) & 0x1FFFF) value = data if 0 <= x < 240 and 0 <= y < 160 else 0 else: data = self._fetch16(cycle, (page + (y * 160 + x) * 2) & 0x1FFFF) value = data | FLAG if 0 <= x < 160 and 0 <= y < 128 else 0 if screen_x < 240: self.buffer[2][screen_x] = value self.affine_x[0] += _s16(registers[0x20 >> 1]) self.affine_y[0] += _s16(registers[0x24 >> 1]) # ----- the merge ---------------------------------------------------------------------- def _palette(self, cycle: int, index: int) -> int: self.pram_access = self.t0 + cycle palette = self.ppu.palette return palette[index << 1] | palette[(index << 1) + 1] << 8 def _run_merge(self, target: int) -> None: ppu = self.ppu registers = ppu.registers dispcnt = registers[0] mode = dispcnt & 7 enabled = ppu.dispcnt_latch[0] & dispcnt bgcnt = registers[4:8] # the enabled BGs, front to back bg_list = sorted( (bg for bg in MODE_BGS[mode] if enabled & 0x100 << bg), key=lambda bg: (bgcnt[bg] & 3, bg), ) enable_obj = bool(enabled & 0x1000) win0, win1 = dispcnt & 0x2000, dispcnt & 0x4000 obj_window = bool(dispcnt & 0x8000) and enable_obj have_windows = bool(win0 or win1 or obj_window) winin, winout = registers[0x48 >> 1], registers[0x4A >> 1] inside0, inside1 = ppu.window_buffer objects = ppu.objects bldcnt = registers[0x50 >> 1] bldalpha = registers[0x52 >> 1] eva, evb, evy = bldalpha & 31, bldalpha >> 8 & 31, registers[0x54 >> 1] & 31 effect = bldcnt >> 6 & 3 mosaic = registers[0x4C >> 1] bg_size_x, obj_size_x = (mosaic & 15) + 1, (mosaic >> 8 & 15) + 1 buffer = self.buffer layers, colors = self.layers, self.colors row = ppu._drawing row_base = self.line * 240 greenswap = registers[1] & 1 for merge_cycle in range(self.merge_cycle, target): cycle = merge_cycle - 46 if cycle < 0: continue phase = cycle & 3 if phase & 1: continue x = cycle >> 2 if have_windows: if win0 and inside0[x]: allow = winin & 0x3F elif win1 and inside1[x]: allow = winin >> 8 & 0x3F elif obj_window and objects.window[x]: allow = winout >> 8 & 0x3F else: allow = winout & 0x3F else: allow = 0x3F if phase == 0: self.forced_blank = self._forced_blank() if self.forced_blank: colors[0] = 0x7FFF continue priorities = [3, 3] layers[0] = layers[1] = BD colors[0] = colors[1] = 0 found = 0 for bg in bg_list: if not allow >> bg & 1: continue mx = x - self.mosaic_x[0] if bgcnt[bg] & 0x40 else x value = buffer[bg][mx] if value: layers[found] = bg colors[found] = value priorities[found] = bgcnt[bg] & 3 found += 1 if found == 2: break self.force_alpha = False if enable_obj: current = ( objects.color[x], objects.priority[x], objects.alpha[x], objects.mosaic[x], ) else: current = (0, 0, False, False) held = self.held if not current[3] or not held[3] or current[1] < held[1] or self.mosaic_x[1] == 0: self.held = held = current if enable_obj and allow >> OBJ & 1 and held[0]: if held[1] <= priorities[0]: layers[1], colors[1] = layers[0], colors[0] layers[0], colors[0] = OBJ, held[0] | 256 self.force_alpha = held[2] elif held[1] <= priorities[1]: layers[1], colors[1] = OBJ, held[0] | 256 if not colors[0] & FLAG: colors[0] = self._palette(merge_cycle, colors[0]) else: # phase 2 if not self.forced_blank: have_src = bldcnt >> 8 >> layers[1] & 1 if self.force_alpha and have_src: if not colors[1] & FLAG: colors[1] = self._palette(merge_cycle, colors[1]) colors[0] = blend(colors[0] & 0xFFFF, colors[1] & 0xFFFF, eva, evb) elif allow & 0x20: have_dst = bldcnt >> layers[0] & 1 if effect == 1 and have_dst and have_src: if not colors[1] & FLAG: colors[1] = self._palette(merge_cycle, colors[1]) colors[0] = blend(colors[0] & 0xFFFF, colors[1] & 0xFFFF, eva, evb) elif effect == 2 and have_dst: colors[0] = brighten(colors[0] & 0xFFFF, evy) elif effect == 3 and have_dst: colors[0] = darken(colors[0] & 0xFFFF, evy) if x & 1: left, right = self.color_l, colors[0] & 0xFFFF if greenswap: left, right = left & ~0x3E0 | right & 0x3E0, right & ~0x3E0 | left & 0x3E0 row[row_base + x - 1] = left & 0x7FFF row[row_base + x] = right & 0x7FFF else: self.color_l = colors[0] & 0xFFFF self.mosaic_x[0] += 1 if self.mosaic_x[0] == bg_size_x: self.mosaic_x[0] = 0 self.mosaic_x[1] += 1 if self.mosaic_x[1] == obj_size_x: self.mosaic_x[1] = 0 self.merge_cycle = target def _s16(value: int) -> int: return value - 0x10000 if value & 0x8000 else value