"""The OBJ (sprite) engine: which of the 128 OAM entries draw on a line, and what they draw. The engine works a line ahead. During line v it reads OAM and OBJ VRAM for line v + 1, two cycles per step, from cycle 40 of line v to cycle 40 of line v + 1, or to cycle 1000 when DISPCNT bit 5 ("H-Blank interval free") gives OAM to the CPU during HBlank. That window is the per-line budget GBATEK states as 1,210 or 954 cycles ("OBJ Attributes"): an OBJ the engine has not reached when the window closes does not draw, and one it is part way through is cut. The step loop below follows NanoBoyAdvance's engine (``sprite.cpp``, emulator-derived): an attribute fetch for the next OBJ overlaps the drawing of the current one, a regular OBJ draws two dots per step and an affine OBJ one, and the fetch of the next entry waits for the current one to be nearly drawn. Dot-exact (rung 4): :class:`Engine` runs the steps over the window, each when its cycle has passed and anything it reads is about to change (``PPU``). """ from __future__ import annotations #: (width, height) by attribute 0 shape (bits 14-15) and attribute 1 size (bits 14-15) SIZES = ( ((8, 8), (16, 16), (32, 32), (64, 64)), # square ((16, 8), (32, 8), (32, 16), (64, 32)), # wide ((8, 16), (8, 32), (16, 32), (32, 64)), # tall ((8, 8), (8, 8), (8, 8), (8, 8)), # prohibited shape ) NORMAL, SEMI_TRANSPARENT, WINDOW, PROHIBITED = range(4) # attribute 0 bits 10-11 class ObjLine: """One line of the OBJ layer, as the compositor reads it (per dot).""" __slots__ = ("alpha", "color", "mosaic", "priority", "window") def __init__(self) -> None: self.color = [0] * 240 # OBJ palette index, 0 = transparent self.priority = [0] * 240 self.alpha = [False] * 240 # semi-transparent: forces alpha blending self.window = [False] * 240 # inside the OBJ window self.mosaic = [False] * 240 class _Drawer: __slots__ = ( "affine", "draw_x", "flip_h", "height", "is_256", "matrix", "mode", "mosaic", "palette", "priority", "remaining", "texture_x", "texture_y", "tile", "width", ) def __init__(self) -> None: self.matrix = [0, 0, 0, 0] self.affine = self.flip_h = self.is_256 = self.mosaic = False self.draw_x = self.height = self.mode = self.palette = self.priority = 0 self.remaining = self.texture_x = self.texture_y = self.tile = self.width = 0 def _s16(value: int) -> int: return value - 0x10000 if value & 0x8000 else value def evaluate( oam: bytearray, vram: bytearray, line: int, dispcnt: int, mosaic_y: int, ) -> ObjLine: """Run the engine for ``line`` through its whole window with OAM, OBJ VRAM and DISPCNT as they are now.""" engine = Engine(_Source(oam, vram, dispcnt), line, mosaic_y) engine.run(engine.steps) return engine.out class _Source: """What :class:`Engine` reads, for running it outside a board (tests).""" def __init__(self, oam: bytearray, vram: bytearray, dispcnt: int) -> None: self.oam, self.vram, self.registers = oam, vram, [dispcnt] class Engine: """The engine for one line, run a step (two cycles) at a time over its window. Each step reads OAM, OBJ VRAM and DISPCNT as they are when it runs (``source.oam``, ``source.vram``, ``source.registers[0]``), so the board runs it up to the present before anything it reads changes, and before the CPU touches OAM or OBJ VRAM: ``last_oam`` and ``last_vram`` are the last steps that read them, and a CPU access in that cycle waits (quirk 18). A step taken while DISPCNT's OBJ enable (bit 12) is clear does nothing: the engine stands still and resumes where it stopped (NanoBoyAdvance ``DrawSpriteImpl``). """ __slots__ = ( "delay_wait", "done", "drawers", "drawing", "index", "initial_x", "initial_y", "last_oam", "last_vram", "line", "matrix_address", "mosaic_y", "out", "pending_wait", "read", "source", "step", "steps", "taken", "wait", ) def __init__(self, source: object, line: int, mosaic_y: int) -> None: self.source = source self.line = line self.mosaic_y = mosaic_y self.out = ObjLine() #: the window in steps: 1232 cycles, or 960 (to cycle 1000 of the line) with DISPCNT #: bit 5. NanoBoyAdvance stops at 964, with a note that "VRAM fetch appears to stop at #: cycle 960"; alyosha-tas ppu/Sprite_Last_VRAM_Access_Free (hardware-calibrated) finds #: no OBJ fetch in cycle 962 (C17) self.steps = (960 if source.registers[0] & 0x20 else 1232) // 2 # type: ignore[attr-defined] self.taken = 0 # steps run so far self.done = False # every entry seen and drawn: the remaining steps do nothing self.last_oam = self.last_vram = -1 self.drawers = (_Drawer(), _Drawer()) self.read = 0 # the drawer being drawn; the other is being filled self.drawing = False self.index = 0 self.step = 0 self.wait = 0 self.pending_wait = 0 self.delay_wait = False self.initial_x = self.initial_y = 0 self.matrix_address = 0 def run(self, until: int) -> None: """Run steps up to (not including) step ``until`` of the window.""" until = min(until, self.steps) if self.done or self.taken >= until: self.taken = max(self.taken, until) return source = self.source oam, vram, registers = source.oam, source.vram, source.registers # type: ignore[attr-defined] out = self.out line = self.line drawers = self.drawers read = self.read drawing = self.drawing index, step, wait = self.index, self.step, self.wait pending_wait, delay_wait = self.pending_wait, self.delay_wait initial_x, initial_y = self.initial_x, self.initial_y matrix_address = self.matrix_address last_oam, last_vram = self.last_oam, self.last_vram out_color, out_priority, out_alpha = out.color, out.priority, out.alpha out_window, out_mosaic = out.window, out.mosaic for taken in range(self.taken, until): if step == 6 and not drawing: self.done = True # nothing changes from here break dispcnt = registers[0] if not dispcnt & 0x1000: # OBJ layer disabled: the engine stands still continue one_dimensional = dispcnt & 0x40 # bit 6: OBJ tiles in a row, not a 32x32 grid boundary = 0x14000 if dispcnt & 7 >= 3 else 0x10000 # ----- the drawer: VRAM fetches for the OBJ in hand ----------------------------- if drawing: drawer = drawers[read] width, height = drawer.width, drawer.height plotted: tuple[int, ...] = () if drawer.affine: if not delay_wait: tx = drawer.texture_x >> 8 ty = drawer.texture_y >> 8 if 0 <= tx < width and 0 <= ty < height: tile = _tile_number(drawer, tx >> 3, ty >> 3, one_dimensional) if drawer.is_256: address = 0x10000 + (tile << 5) + ((ty & 7) << 3) + (tx & 7) color = 0 if address >= boundary: last_vram = taken color = vram[address] else: address = 0x10000 + (tile << 5) + ((ty & 7) << 2) + ((tx & 7) >> 1) data = 0 if address >= boundary: last_vram = taken data = vram[address] color = data >> 4 if tx & 1 else data & 15 if color: color |= drawer.palette << 4 plotted = (color,) else: drawer.draw_x += 1 # outside the texture: nothing fetched drawer.texture_x += drawer.matrix[0] drawer.texture_y += drawer.matrix[2] drawer.remaining -= 1 else: flip = width - 1 if drawer.flip_h else 0 tx = drawer.texture_x ^ flip ty = drawer.texture_y tile = _tile_number(drawer, tx >> 3, ty >> 3, one_dimensional) pair_x = tx & 6 if drawer.is_256: address = 0x10000 + (tile << 5) + ((ty & 7) << 3) + pair_x first = second = 0 if address >= boundary: last_vram = taken first, second = vram[address], vram[address + 1] palette = 0 else: address = 0x10000 + (tile << 5) + ((ty & 7) << 2) + (pair_x >> 1) data = 0 if address >= boundary: last_vram = taken data = vram[address] first, second = data & 15, data >> 4 palette = drawer.palette << 4 if drawer.flip_h: first, second = second, first plotted = (first and first | palette, second and second | palette) drawer.texture_x += 2 drawer.remaining -= 2 # plot: an opaque OBJ-window dot only marks the window; transparent dots of any # OBJ, like opaque normal ones, still take over the dot's priority and mosaic for color in plotted: x = drawer.draw_x drawer.draw_x = x + 1 if not 0 <= x < 240: continue if drawer.mode == WINDOW and color: out_window[x] = True elif drawer.priority < out_priority[x] or not out_color[x]: if color: out_color[x] = color out_alpha[x] = drawer.mode == SEMI_TRANSPARENT out_mosaic[x] = drawer.mosaic out_priority[x] = drawer.priority if drawer.remaining == 0: drawing = False # ----- the attribute fetcher: OAM for the next OBJ ------------------------------- if wait > 0 and not delay_wait: wait -= 1 continue delay_wait = False drawer = drawers[read ^ 1] if step == 0: if index == 128: step = 6 # every entry has been seen continue last_oam = taken base = index * 8 attr0 = oam[base] | oam[base + 1] << 8 attr1 = oam[base + 2] | oam[base + 3] << 8 active = False mode = attr0 >> 10 & 3 # bit 8 clear with bit 9 set: the OBJ is disabled if attr0 & 0x300 != 0x200 and mode != PROHIBITED: x = attr1 & 0x1FF if x >= 240: x -= 512 y = attr0 & 0xFF width, height = SIZES[attr0 >> 14][attr1 >> 14] half_width, half_height = width >> 1, height >> 1 affine = bool(attr0 & 0x100) if affine and attr0 & 0x200: # double size: the drawing area, not the texture half_width *= 2 half_height *= 2 y_max = (y + half_height * 2) & 255 # OBJs wrap from the bottom to the top if (line >= y or y_max < y) and line < y_max: mosaic = bool(attr0 & 0x1000) and mode != WINDOW drawer.width, drawer.height = width, height drawer.mode = mode drawer.mosaic = mosaic drawer.affine = affine drawer.draw_x = x drawer.remaining = half_width << 1 drawer.is_256 = bool(attr0 & 0x2000) local_y = (line - y) & 255 if mosaic: local_y = max(0, local_y - self.mosaic_y) if not affine: drawer.flip_h = bool(attr1 & 0x1000) drawer.texture_x = 0 drawer.texture_y = local_y ^ (height - 1) if attr1 & 0x2000 else local_y pending_wait = half_width - 2 else: initial_x = -half_width initial_y = local_y - half_height pending_wait = half_width * 2 - 1 matrix_address = (attr1 >> 9 & 31) * 32 + 6 active = True if x < 0: # clipped on the left: the engine skips the hidden dots clip = -x if affine else -x & ~1 drawer.draw_x += clip drawer.remaining -= clip if affine: pending_wait -= clip initial_x += clip else: pending_wait -= clip >> 1 drawer.texture_x += clip if drawer.remaining <= 0: active = False if active: step = 1 else: index += 1 elif step == 1: last_oam = taken attr2 = oam[index * 8 + 4] | oam[index * 8 + 5] << 8 drawer.tile = attr2 & 0x3FF drawer.priority = attr2 >> 10 & 3 drawer.palette = attr2 >> 12 if drawer.affine: step = 2 else: read ^= 1 drawing = True index += 1 step = 0 wait = pending_wait delay_wait = True elif 2 <= step <= 5: # PA, PB, PC, PD of the OBJ's affine group last_oam = taken drawer.matrix[step - 2] = _s16(oam[matrix_address] | oam[matrix_address + 1] << 8) matrix_address += 8 step += 1 if step == 6: pa, pb, pc, pd = drawer.matrix # the texture origin is the OBJ's centre, in 8.8 fixed point drawer.texture_x = pa * initial_x + pb * initial_y + (drawer.width << 7) drawer.texture_y = pc * initial_x + pd * initial_y + (drawer.height << 7) read ^= 1 drawing = True index += 1 step = 0 wait = pending_wait delay_wait = True self.taken = until self.read = read self.drawing = drawing self.index, self.step, self.wait = index, step, wait self.pending_wait, self.delay_wait = pending_wait, delay_wait self.initial_x, self.initial_y = initial_x, initial_y self.matrix_address = matrix_address self.last_oam, self.last_vram = last_oam, last_vram def _tile_number(drawer: _Drawer, block_x: int, block_y: int, one_dimensional: int) -> int: base = drawer.tile if drawer.is_256: if one_dimensional: return (base + block_y * (drawer.width >> 2) + (block_x << 1)) & 0x3FF return ((base + (block_y << 5)) & 0x3E0) | (((base & ~1) + (block_x << 1)) & 0x1F) if one_dimensional: return (base + block_y * (drawer.width >> 3) + block_x) & 0x3FF return ((base + (block_y << 5)) & 0x3E0) | ((base + block_x) & 0x1F)