"""The video display processor: TMS9918A modes 0-3 and Sega's Mode 4. One class serves the SG-1000's TMS9918A, the Master System's 315-5124 (SMS1) and 315-5246 (SMS2), and the Game Gear's VDP. What differs between them is data on :class:`VDPVariant`; docs/undocumented-behavior.md lists each difference with its source and tier. Sources, cited by short name in the comments: - "msvdp": Charles MacDonald, ``reference/smspower/msvdp-20021112.txt``. - "Young": Sean Young, ``reference/smspower/tms9918a.txt`` (TMS9918A modes and sprites). - "FluBBa": ``VDPTest-ReadMe.txt`` in ``SMSVDPTest-SMS-1.31.zip`` (timing measured on real SMS1, SMS2 and Mega Drive hardware). - "wiki": the SMS Power pages in ``reference/smspower-wiki/`` (named per comment). Time. The VDP counts in *mclocks*: 684 per scanline, 3 per CPU cycle (FluBBa's MClock 0-683). A line here starts where the V counter changes; line-local ``m`` is MClock - LINE_ORIGIN (mod 684). FluBBa lists each event twice, as an HClock and as an HCount, and the two disagree by a few dots (he gives "HClock -16 (HCount 0xF4)", but -16 / 2 is $F8). His tests measure HCounts, so those are used, with the H counter as (MClock - 93) / 4 (fitted to his table; see latch_h_counter): ==================== ====== ========== ============ event HCount MClock line-local m ==================== ====== ========== ============ V counter changes $F4 47 0 VINT/OVR flags set $F5 49 2 frame IRQ asserted $F3 43 680 (previous line) line IRQ asserted $F3 44 681 (previous line) ==================== ====== ========== ============ Rendering is per line at ``m = 0``; mid-line register changes take effect on the next line (a documented simplification: FluBBa found the name-table base is *not* latched per line, docs/undocumented-behavior.md VDP item 9). """ from __future__ import annotations from dataclasses import dataclass MCLOCKS_PER_CYCLE = 3 MCLOCKS_PER_LINE = 684 # 342 dots, 228 CPU cycles # Line-local event times (see the module docstring). @dataclass(frozen=True) class VDPTiming: """Where each event falls in the line, per VDP (docs/timing.md). ``line_origin``: the MClock at which the V counter changes (line-local m = 0). ``frame_irq``: mclocks after the start of the last active line at which the frame IRQ rises (683: the end of that line; 684 + k: m = k of the next line). ``line_irq``: line-local m of the line counter's step. ``flags``: line-local m at which the frame and overflow flags become visible (0: as the line begins; negative: that many mclocks before it, at the end of the previous line, when the next line's sprites are parsed for overflow). ``collision``: the COL flag appears at MClock 2x + this, for pixel x. """ line_origin: int frame_irq: int line_irq: int flags: int collision: int # The SMS1 and SMS2 constants, fitted to FluBBa's SMS VDP Test (all 55 pass). SMS_TIMING = VDPTiming(line_origin=47, frame_irq=683, line_irq=1, flags=0, collision=117) LINE_ORIGIN = SMS_TIMING.line_origin # Pixels are drawn at the start of the active display, HCount $00 = MClock 93, as # MAME's TMS9928A (HORZ_DISPLAY_START) does; a game that rewrites the sprite table # while the beam runs sees the difference against drawing at the V counter change. RENDER_MCLOCK = 93 # The Game Gear, from enik2's measurements of a 2-ASIC and a 1-ASIC unit (forum # thread 10695, VDPTEST_GG): the V counter changes 3 (2-ASIC) or 2 (1-ASIC) Z80 # cycles later than on the SMS relative to the H counter, the VINT and OVR flags # at ZClock -13 on both, collisions 2 HCount later. The rest is fitted to his # VDPTEST_GG (docs/timing.md). GG_2ASIC_TIMING = VDPTiming(line_origin=56, frame_irq=680, line_irq=1, flags=-3, collision=123) # The Mega Drive in Mode 4, fitted to FluBBa's Mega Drive tests (docs/timing.md). MD_TIMING = VDPTiming(line_origin=56, frame_irq=681, line_irq=1, flags=-3, collision=17) GG_1ASIC_TIMING = VDPTiming(line_origin=53, frame_irq=680, line_irq=1, flags=0, collision=123) # Status register bits (msvdp section 4; Young section 2). STATUS_FRAME = 0x80 STATUS_OVERFLOW = 0x40 # the TMS9918A's "fifth sprite" flag STATUS_COLLISION = 0x20 # The TMS9918A's fixed palette, NTSC, as RGB (wiki Palette.pmwiki, "SG-1000/SC-3000", # values from Sean Young's tms9918a.txt). Index 0 is transparent (shows the backdrop). TMS9918A_RGB = ( 0x000000, 0x000000, 0x21C842, 0x5EDC78, 0x5455ED, 0x7D76FC, 0xD4524D, 0x42EBF5, 0xFC5554, 0xFF7978, 0xD4C154, 0xE6CE80, 0x21B03B, 0xC95BBA, 0xCCCCCC, 0xFFFFFF, ) # fmt: skip # The Master System VDPs show the TMS colours as fixed entries of their own 64-colour # palette (wiki Palette.pmwiki, "Master System/Mark III", "Palette value" column). SMS_LEGACY_CRAM = ( 0x00, 0x00, 0x08, 0x0C, 0x10, 0x30, 0x01, 0x3C, 0x02, 0x03, 0x05, 0x0F, 0x04, 0x33, 0x15, 0x3F, ) # fmt: skip def sms_rgb(value: int) -> int: """A Master System CRAM byte (--BBGGRR) as RGB888 (msvdp section 5).""" red, green, blue = value & 3, (value >> 2) & 3, (value >> 4) & 3 return (red * 85) << 16 | (green * 85) << 8 | blue * 85 def gg_rgb(value: int) -> int: """A Game Gear CRAM word (----BBBBGGGGRRRR) as RGB888 (msvdp section 5).""" red, green, blue = value & 15, (value >> 4) & 15, (value >> 8) & 15 return (red * 17) << 16 | (green * 17) << 8 | blue * 17 @dataclass(frozen=True) class VDPVariant: """What differs between the VDPs (docs/undocumented-behavior.md, "VDP"). ``mode4``: Sega's Mode 4 and its registers 8-10 exist. ``sms1_masks``: legacy register bits are ANDed into VRAM addresses (wiki VDPRegisters.pmwiki). ``extra_heights``: M1/M3 with M4+M2 select 224/240 lines (msvdp section 6). ``sms1_zoom``: only some sprites on a line are zoomed horizontally (msvdp section 10 says the first four; the wiki's VDPRegisters.pmwiki says the first N - 4: open, see docs/undocumented-behavior.md). ``game_gear``: 64-byte CRAM with the even-byte latch and 12-bit colour (msvdp section 5). ``status_low_bits``: the TMS9918A reports the fifth-sprite number; the Sega chips return undriven bits, which MAME 0.285 reads as $1F (seen in its I/O logs, docs/mame-oracle.md). ``tms_cram``: the TMS9918A modes take their colours from CRAM, not a fixed palette: "The Game Gear maps the TMS9918a colours to the corresponding palette indices. However, it does not set the palette" (the wiki's Palette.pmwiki). The indices are the second palette, 16-31, as in MAME 0.285 (``palette_offset`` $10): Justin Harder Reel loads only those before showing a TMS-mode picture. ``mega_drive``: the Mega Drive's 315-5313 running Mode 4, as it does under a Power Base Converter (msvdp section 13, quoted where each rule is applied; FluBBa's Mega Drive tests): the first control byte waits in a latch, a data write leaves the read buffer alone and goes to CRAM whenever code bit 1 is set, five bits pick the register, the TMS9918A modes show a black screen, sprites do not zoom, and sprites neither collide in the border nor overflow with the display off. """ name: str mode4: bool timing: VDPTiming = SMS_TIMING sms1_masks: bool = False extra_heights: bool = False sms1_zoom: bool = False game_gear: bool = False tms_status_low_bits: bool = False tms_cram: bool = False mega_drive: bool = False TMS9918A = VDPVariant("TMS9918A", mode4=False, tms_status_low_bits=True) SEGA_315_5124 = VDPVariant("315-5124 (SMS1)", mode4=True, sms1_masks=True, sms1_zoom=True) SEGA_315_5246 = VDPVariant("315-5246 (SMS2)", mode4=True, extra_heights=True) SEGA_315_5313 = VDPVariant( "315-5313 (Mega Drive, Mode 4)", mode4=True, timing=MD_TIMING, mega_drive=True ) SEGA_GAME_GEAR = VDPVariant( "Game Gear", mode4=True, timing=GG_2ASIC_TIMING, extra_heights=True, game_gear=True, tms_cram=True, ) # A Game Gear running a Master System cartridge (SMS-compatibility mode): SMS CRAM # and the whole 256x192 picture (msvdp section 14), with the Game Gear's timing. SEGA_GAME_GEAR_SMS_MODE = VDPVariant( "Game Gear (SMS mode, 2 ASIC)", mode4=True, timing=GG_2ASIC_TIMING, extra_heights=True, tms_cram=True, ) SEGA_GAME_GEAR_1ASIC_SMS_MODE = VDPVariant( "Game Gear (SMS mode, 1 ASIC)", mode4=True, timing=GG_1ASIC_TIMING, extra_heights=True, tms_cram=True, ) # V counter sequences: (last value before the jump, value after it), per region and # active height (msvdp section 11, checked on an NTSC SMS2). _V_JUMPS = { ("NTSC", 192): ((0xDA, 0xD5),), ("NTSC", 224): ((0xEA, 0xE5),), ("NTSC", 240): ((0xFF, 0x00),), # "does not work on NTSC machines" ("PAL", 192): ((0xF2, 0xBA),), ("PAL", 224): ((0xFF, 0x00), (0x02, 0xCA)), ("PAL", 240): ((0xFF, 0x00), (0x0A, 0xD2)), } LINES_PER_FRAME = {"NTSC": 262, "PAL": 313} def v_counter_table(region: str, height: int) -> tuple[int, ...]: """The value port $7E returns on each line of the frame, line 0 first.""" values: list[int] = [] value = 0 jumps = list(_V_JUMPS[(region, height)]) # each applies once, in order for _ in range(LINES_PER_FRAME[region]): values.append(value) value = jumps.pop(0)[1] if jumps and value == jumps[0][0] else (value + 1) & 0xFF return tuple(values) class VDP: """Ports, registers, VRAM/CRAM, counters, interrupts and the line renderer. The board calls :meth:`run` with CPU cycles, reads :attr:`irq`, and takes finished frames from :attr:`frame` (rows of RGB888 ints) when :attr:`frame_ready` is set. """ def __init__(self, variant: VDPVariant = SEGA_315_5246, region: str = "NTSC") -> None: self.variant = variant self.region = region #: False skips pixel generation; status flags, counters and sprite evaluation #: (overflow, collision) still run, so every port read is unchanged. self.render = True self.lines_per_frame = LINES_PER_FRAME[region] self.reset() def reset(self) -> None: self.vram = bytearray(0x4000) self.cram = bytearray(64 if self.variant.game_gear else 32) self.registers = bytearray(16) self.address = 0 self.code = 0 self.second_byte = False # the first/second control-byte latch self.first_byte = 0 # Mega Drive: the first control byte, until the second self.read_buffer = 0 self.cram_latch = 0 # Game Gear: the even CRAM byte waiting for its odd half self.status = 0 self.frame_pending = False # frame IRQ asserted, status bit not yet visible self.line_pending = False self.line_counter = 0 self.overflow_pending = False self.collision_at: int | None = None # line-local m at which COL becomes visible self.line = 0 self.m = 0 self.frame_count = 0 self.lines_started = 0 # every line begun: the C-Sync pulses the 315-5297 counts self.frame_ready = False self.y_scroll = 0 # register 9 as latched when the active display began self._x_scroll_line = 0 # register 8 as latched at this line's start self.h_counter = 0 self.fifth_sprite = 0x1F # Sega VDPs: status bits 4-0 are undriven on hardware (msvdp section 4). MAME # 0.285 reads $1F, except after a sprite overflow, when it reports bits # derived from the overflowing sprite's number (315_5124.cpp, # sprite_count_overflow). No hardware source is known for that rule; it is # kept so the MAME lockstep can compare status reads exactly. # The TMS9918A's status register powers up as 0, low bits included (MAME # tms9928a device_reset); the Sega chips' as $1F. self.low_bits = 0 if self.variant.tms_status_low_bits else 0x1F self._overflow_bits = 0x1F self.frame: list[list[int]] = [] self._rows: list[list[int]] = [] self._v_table = v_counter_table(self.region, 192) self._next_due = 0 # line-local m of the next event; run() fast-paths below it def visible_frame(self) -> list[list[int]]: """The last complete frame as a screen shows it. The Game Gear's LCD shows "the central 160x144 pixel section" of the picture (the wiki's GGVDP.pmwiki): columns 48-207 and, of a 192-line picture, lines 24-167; of a 224-line one, lines 40-183, as MAME 0.285 shows (Micro Machines). """ if self.variant.game_gear: top = (len(self.frame) - 144) // 2 return [row[48:208] for row in self.frame[top : top + 144]] return self.frame # -- modes ---------------------------------------------------------------- @property def mode4(self) -> bool: return self.variant.mode4 and bool(self.registers[0] & 0x04) @property def height(self) -> int: """Active lines: 192, or 224/240 in Mode 4 on the SMS2 and GG (msvdp section 6).""" if not (self.mode4 and self.variant.extra_heights and self.registers[0] & 0x02): return 192 m1, m3 = self.registers[1] & 0x10, self.registers[1] & 0x08 if m1 and not m3: return 224 if m3 and not m1: return 240 return 192 @property def display_enabled(self) -> bool: return bool(self.registers[1] & 0x40) @property def irq(self) -> bool: """The INT output: each pending flag gated by its enable (msvdp section 12).""" frame = self.frame_pending and bool(self.registers[1] & 0x20) line = self.line_pending and self.mode4 and bool(self.registers[0] & 0x10) return frame or line # -- ports ---------------------------------------------------------------- def write_control(self, value: int) -> None: """The two-byte command word (msvdp section 3; FluBBa "1byte wr sets rd adr").""" if not self.second_byte: if self.variant.mega_drive: # "it is latched and the LSB of the address register is not updated # until the second byte is written" (msvdp section 13; FluBBa "1byte # wr keeps rd adr"). self.first_byte = value else: self.address = (self.address & 0x3F00) | value self.second_byte = True return self.second_byte = False low = self.first_byte if self.variant.mega_drive else self.address & 0xFF self.address = ((value & 0x3F) << 8) | low self.code = value >> 6 if self.code == 0: self.read_buffer = self.vram[self.address] self.address = (self.address + 1) & 0x3FFF elif self.code == 2 or (self.code == 3 and not self.variant.mode4): # Register write. The TMS9918A decodes bit 7 alone and has registers 0-7 # (Young section 2); the Sega VDPs use bits 3-0 and ignore 11-15 # (msvdp section 3; FluBBa "Unused regs, no effect", "VDP Register mirrors"). number = value & (0x0F if self.variant.mode4 else 0x07) if self.variant.mega_drive: # Five bits: $90 and $B0 are not register 0 there, $A0 is (FluBBa's # Mega Drive "VDP Register mirrors"). Its registers 11-23 belong to # Mode 5 and are not modelled. number = value & 0x1F if number <= 10: self.registers[number] = self.address & 0xFF def read_status(self) -> int: """Status flags; the read clears them, the latch and the line IRQ (msvdp 3, 4, 12).""" value = self.status value |= self.low_bits # TMS9918A: after a read the low bits hold the fifth-sprite number; the Sega # chips return to $1F (MAME 0.285: tms9928a register_read, 315_5124 control_read). self.low_bits = self.fifth_sprite if self.variant.tms_status_low_bits else 0x1F self.status = 0 self.frame_pending = False self.line_pending = False self.second_byte = False return value def read_data(self) -> int: """The read buffer, then refill it from VRAM (msvdp section 3).""" value = self.read_buffer self.read_buffer = self.vram[self.address] self.address = (self.address + 1) & 0x3FFF self.second_byte = False return value def write_data(self, value: int) -> None: """VRAM or CRAM by code; the byte also loads the read buffer (FluBBa).""" if self.variant.mega_drive: # "data will go to CRAM if bit 1 of the code register is set" and "the # read buffer is not updated" (msvdp section 13; FluBBa "Write after # code2 wr", "VRAM wr keep VDPbuffer"). if self.code & 2: self._write_cram(value) else: self.vram[self.address] = value self.address = (self.address + 1) & 0x3FFF self.second_byte = False return if self.code == 3 and self.variant.mode4: self._write_cram(value) else: self.vram[self.address] = value self.read_buffer = value self.address = (self.address + 1) & 0x3FFF self.second_byte = False def _write_cram(self, value: int) -> None: if not self.variant.game_gear: self.cram[self.address & 0x1F] = value & 0x3F return # Game Gear: an even address stores into a latch; an odd address writes the # latch and this byte as one colour (msvdp section 5). index = self.address & 0x3F if index & 1: self.cram[index - 1] = self.cram_latch self.cram[index] = value & 0x0F else: self.cram_latch = value def read_v_counter(self) -> int: return self._v_table[self.line] def read_h_counter(self) -> int: """The H counter as latched by the last TH edge (msvdp section 11).""" return self.h_counter def latch_h_counter(self) -> None: """Called by the I/O chip when TH changes. FluBBa gives HCount = (MClock - 94) / 4. His own table of all 228 values ("HCounter correct", HCounterValues in testmain.asm), sampled every 229 cycles, is reproduced exactly only by (MClock - 93) / 4 with CPU cycle boundaries at MClock = 2 (mod 3), which is where ours fall (m = 0 mod 3, MClock = m + LINE_ORIGIN, and LINE_ORIGIN = 2 mod 3). So 93, a one-mclock correction fitted to his table. """ mclock = (self.m + self.variant.timing.line_origin) % MCLOCKS_PER_LINE self.h_counter = ((mclock - 93) >> 2) & 0xFF # -- time ----------------------------------------------------------------- def run(self, cycles: int) -> None: """Advance by CPU cycles, firing each line event it passes.""" target = self.m + cycles * MCLOCKS_PER_CYCLE if target < self._next_due: self.m = target # the common case: no event inside this instruction return while True: event = self._next_event() if event > target: break target -= self._fire(event) self.m = target self._next_due = self._next_event() def _next_event(self) -> int: # The end of the line (684) is always ahead, so there is always a next event. timing = self.variant.timing events = [ timing.line_irq, timing.frame_irq % MCLOCKS_PER_LINE, RENDER_MCLOCK - timing.line_origin, MCLOCKS_PER_LINE, ] if timing.flags: events.append(timing.flags % MCLOCKS_PER_LINE) if self.collision_at is not None: events.append(self.collision_at) return min(event for event in events if event > self.m) def _fire(self, event: int) -> int: """Handle one event at line-local time ``event``; return mclocks to rebase by.""" self.m = event if event == MCLOCKS_PER_LINE: self._start_line() return MCLOCKS_PER_LINE if event == self.collision_at: self.status |= STATUS_COLLISION self.collision_at = None timing = self.variant.timing if event == RENDER_MCLOCK - timing.line_origin and self.line < self.height: # The Sega VDPs counted this line's sprite overflow as it began. count = self.variant.tms_status_low_bits self._rows.append(self._render_line(self.line, count_overflow=count)) if event == timing.line_irq and self.mode4: self._line_counter_tick() frame_line, frame_m = divmod(timing.frame_irq, MCLOCKS_PER_LINE) if event == frame_m and self.line == self.height + frame_line: # "VINT fires at the end of the first logical line of the bottom border" # (MAME 315_5124.cpp); the mclock is fitted per VDP (VDPTiming). self.frame_pending = True if timing.flags and event == timing.flags % MCLOCKS_PER_LINE: if timing.flags < 0: # Before the V counter changes: parse the next line's sprites for # overflow now, then show both flags. self._scan_overflow((self.line + 1) % self.lines_per_frame) self._commit_flags() return 0 def _scan_overflow(self, line: int) -> None: if self.variant.mega_drive and not (self.display_enabled and self.mode4): return # FluBBa's Mega Drive "No disp, no spr ovr" if line < self.height and self.mode4: self._mode4_sprites(line, None, overflow=True) elif line < self.height and not self.registers[1] & 0x10: self._tms_sprites(line, None, overflow=True) def _line_counter_tick(self) -> None: # Decremented on every active line and the one after; reloaded from # register 10 on the other lines; underflow reloads and raises the line # interrupt (msvdp section 12). It runs just after the V counter changes, # one dot after the frame IRQ (FluBBa: HINT one dot after VINT), for the # line now beginning: with register 10 = N the handler reads V counter N # (FluBBa's "Line IRQ VCount"). The exact mclocks of both IRQs are fitted to # his "Frame IRQ HCount" and "Line IRQ HCount" (docs/timing.md). line = self.line if line <= self.height: if self.line_counter == 0: self.line_counter = self.registers[10] self.line_pending = True else: self.line_counter -= 1 else: self.line_counter = self.registers[10] def _commit_flags(self) -> None: """Make the pending frame and overflow flags visible in the status register. FluBBa puts them just after the frame IRQ; his "VINT flag HCount" allows only the window from one mclock after our IRQ to the V counter change, so they are committed as the line changes (docs/timing.md). """ flag_line = self.height + 1 if self.variant.timing.flags >= 0 else self.height if self.frame_pending and self.line == flag_line: self.status |= STATUS_FRAME if self.overflow_pending: self.status |= STATUS_OVERFLOW self.low_bits &= self._overflow_bits self.overflow_pending = False def _start_line(self) -> None: self.m = 0 self.line += 1 self.lines_started += 1 if self.line == self.height: self.frame = self._rows self._rows = [] self.frame_ready = True self.frame_count += 1 if self.line == self.lines_per_frame: self.line = 0 self._v_table = v_counter_table(self.region, self.height) if self.line == 0: # "The vertical scroll value cannot be changed during the active display # period, any changes made will be stored in a temporary location and # used only when the active display period ends" (msvdp section 9): the # value in force as the display begins holds for the whole of it. MAME # 0.285 latches it at the same point (315_5124.cpp m_reg9copy). self.y_scroll = self.registers[9] if self.line < self.height: # FluBBa: X scroll is latched at HCount $F3, before the line's pixels. self._x_scroll_line = self.registers[8] if not self.variant.tms_status_low_bits and self.variant.timing.flags >= 0: self._scan_overflow(self.line) # parsed during the previous line if self.variant.mega_drive and self.mode4 and self.display_enabled: # The Mega Drive has the line's sprites drawn before the line goes # out, so a collision on it is known as it begins. self._mode4_sprites(self.line, [True] * 256, overflow=False) elif self._border_sprite_line(self.line) is not None: self._border_sprites(self._border_sprite_line(self.line)) # The sprite unit parses line L during line L - 1, so an overflow found for # this line shows as it begins, with the frame flag (msvdp section 10), or # at the VDP's own flag time (VDPTiming.flags). if not self.variant.timing.flags: self._commit_flags() def _border_sprite_line(self, line: int) -> int | None: """The signed line number of a top-border line whose sprites still collide. FluBBa's "Offscreen Y, col": sprites overlapping in the vertical border set the collision flag on the Sega VDPs. MAME 0.285 (315_5124.cpp draw_scanline) evaluates the last 13 lines of the top border, 192-line mode only, as lines -13 to -1; we follow it. Overflow is not flagged there ("Offscreen Y, no ovr"). """ if not self.variant.mode4 or self.height != 192 or not self.display_enabled: return None if self.variant.mega_drive: return None # FluBBa's Mega Drive "Offscreen Y, no col" signed = line - self.lines_per_frame return signed if -13 <= signed <= -1 else None def _border_sprites(self, line: int) -> None: if self.mode4: self._mode4_sprites(line, [True] * 256, overflow=False) elif not self.registers[1] & 0x10: self._tms_sprites(line, [0] * 256, overflow=False) # -- rendering ------------------------------------------------------------ def _backdrop_rgb(self) -> int: if self.mode4: return self._cram_rgb(16 + (self.registers[7] & 0x0F)) return self._tms_rgb(self.registers[7] & 0x0F) def _cram_rgb(self, index: int) -> int: if self.variant.game_gear: low, high = self.cram[index * 2], self.cram[index * 2 + 1] return gg_rgb(high << 8 | low) return sms_rgb(self.cram[index]) def _tms_rgb(self, colour: int) -> int: if self.variant.tms_cram: return self._cram_rgb(16 + colour) if self.variant.mode4: return sms_rgb(SMS_LEGACY_CRAM[colour]) return TMS9918A_RGB[colour] def _render_line(self, line: int, count_overflow: bool = True) -> list[int]: """Draw one active line. ``count_overflow`` False: the Sega VDPs count sprite overflow when the line begins (see _start_line), not here.""" overflow = count_overflow and None # None: each sprite routine's own default if self.variant.mega_drive and not (self.display_enabled and self.mode4): # "When the TMS9918 modes are selected, the display is always blanked # and is colored black" (msvdp section 13); and with the display off no # sprite overflows (FluBBa's Mega Drive "No disp, no spr ovr"). if self.mode4: return [self._backdrop_rgb()] * 256 return [0] * 256 if self.render else [] if not self.display_enabled: # Blanked: the backdrop fills the line, but sprite overflow is still # evaluated (FluBBa "No disp, spr ovr"); collisions are not ("No disp, # no spr col"). if self.mode4: self._mode4_sprites(line, None, overflow=overflow) else: self._tms_sprites(line, None, overflow=overflow) return [self._backdrop_rgb()] * 256 if not self.render: # Flags only: sprites are evaluated against an all-transparent background. if self.mode4: self._mode4_sprites(line, [False] * 256, overflow=overflow) else: self._tms_sprites(line, [0] * 256, overflow=overflow) return [] if self.mode4: return self._render_mode4(line, overflow) return self._render_tms(line, overflow) # Mode 4 (msvdp sections 8-10) --------------------------------------------- def _render_mode4(self, line: int, overflow: bool | None = None) -> list[int]: regs = self.registers height = self.height backdrop = self._backdrop_rgb() if height == 192: name_base = (regs[2] & 0x0E) << 10 # SMS1: register 2 bit 0 is ANDed with name-table address bit 10. sms1_masked = self.variant.sms1_masks and not regs[2] & 0x01 name_mask = 0x3BFF if sms1_masked else 0x3FFF rows_mod = 28 * 8 else: name_base = ((regs[2] & 0x0C) << 10) | 0x0700 name_mask = 0x3FFF rows_mod = 32 * 8 x_scroll = 0 if (regs[0] & 0x40 and line < 16) else self._x_scroll_line fine = x_scroll & 7 pixels = [0] * 256 # background colour index 0-31 priority = [False] * 256 for x in range(256): if x < fine: pixels[x] = -1 # left edge under fine scroll: backdrop (msvdp section 9) continue column = (x - fine) >> 3 y_scroll = 0 if (regs[0] & 0x80 and column >= 24) else self.y_scroll bg_y = (line + y_scroll) % rows_mod bg_x = (x - x_scroll) & 0xFF entry_address = (name_base + ((bg_y >> 3) << 6) + ((bg_x >> 3) << 1)) & name_mask entry = self.vram[entry_address] | self.vram[(entry_address + 1) & 0x3FFF] << 8 tile = entry & 0x1FF row = bg_y & 7 if entry & 0x400: row = 7 - row bit = bg_x & 7 if not entry & 0x200: bit = 7 - bit pattern = tile * 32 + row * 4 colour = 0 for plane in range(4): colour |= ((self.vram[(pattern + plane) & 0x3FFF] >> bit) & 1) << plane pixels[x] = colour + (16 if entry & 0x800 else 0) priority[x] = bool(entry & 0x1000) and colour != 0 sprites = self._mode4_sprites(line, priority, overflow=overflow) row_rgb = [] mask_left = bool(regs[0] & 0x20) for x in range(256): if mask_left and x < 8: row_rgb.append(backdrop) elif sprites[x] is not None: row_rgb.append(self._cram_rgb(sprites[x])) elif pixels[x] < 0: row_rgb.append(backdrop) else: row_rgb.append(self._cram_rgb(pixels[x])) return row_rgb def _sega_overflow(self, sprite_index: int) -> None: """Flag a sprite overflow on a Sega VDP, for the status bit at HCount $F5. Flagged only while the frame flag is clear (MAME 0.285 ``sprite_count_overflow``). MAME keeps scanning after the limit and ANDs a number derived from each extra sprite's index (the byte offset, in the TMS modes) into the status low bits; see the ``low_bits`` comment in reset(). """ if self.status & STATUS_FRAME: return if not self.overflow_pending: self._overflow_bits = 0x1F self.overflow_pending = True bits = (sprite_index + 1) // 2 if sprite_index < 14 else sprite_index // 2 self._overflow_bits &= bits @staticmethod def _mode4_sprite_row(line: int, y: int, zoom: bool) -> int: """The pattern row a sprite at ``y`` shows on ``line`` (in range if 0 to its unzoomed height - 1). A sprite's first line is y + 1 (msvdp section 10). Zoomed, the halved line is compared with the halved Y, as in MAME 0.285 (315_5124.cpp ``select_sprites``, "or else an off-by-one bug could occur, as seen with Tarzan"): with an odd Y the first row starts a line early and shows on two lines (Racer's zoomed score digits). No hardware source says. """ if not zoom: return (line - (y + 1)) & 0xFF top = y - 256 if y >= 240 else y return ((line - 1) >> 1) - (top >> 1) def _mode4_sprites( self, line: int, bg_priority: list[bool] | None, overflow: bool | None = None ) -> list[int | None]: """Up to eight sprites on the line; sets overflow and schedules collision. ``overflow`` None: count overflow here unless this VDP parses it early (VDPTiming.flags negative, see _scan_overflow). """ if overflow is None: overflow = self.variant.timing.flags >= 0 regs = self.registers out: list[int | None] = [None] * 256 sat = (regs[5] & 0x7E) << 7 pattern_base = 0x2000 if regs[6] & 0x04 else 0 tall = bool(regs[1] & 0x02) # "Sprites cannot be zoomed using bit 0 of register #1" on the Mega Drive # (msvdp section 13). zoom = bool(regs[1] & 0x01) and not self.variant.mega_drive size = (16 if tall else 8) * (2 if zoom else 1) found: list[int] = [] for index in range(64): y = self.vram[sat + index] if y == 0xD0 and self.height == 192: break # the end-of-list marker, 192-line mode only (msvdp section 10) if not 0 <= self._mode4_sprite_row(line, y, zoom) < size >> zoom: continue if len(found) < 8: found.append(index) elif overflow: self._sega_overflow(index) # a ninth sprite (msvdp section 10) if bg_priority is None: return out x_table = sat | 0x80 if self.variant.sms1_masks and not regs[5] & 0x01: x_table = sat # SMS1: register 5 bit 0 ANDed with address bit 7 opaque = [False] * 256 collision_x = None zoomed_wide = len(found) if not self.variant.sms1_zoom else min(len(found), 4) for slot, index in enumerate(found): y = self.vram[sat + index] x = self.vram[x_table + index * 2] - (8 if regs[0] & 0x08 else 0) tile = self.vram[x_table + index * 2 + 1] if tall: tile &= 0xFE row = self._mode4_sprite_row(line, y, zoom) address = pattern_base + tile * 32 + row * 4 if self.variant.sms1_masks: address &= 0x27FF | ((regs[6] & 0x03) << 11) planes = [self.vram[(address + plane) & 0x3FFF] for plane in range(4)] wide = zoom and slot < zoomed_wide for column in range(16 if wide else 8): screen_x = x + column if not 0 <= screen_x < 256: continue bit = 7 - (column >> 1 if wide else column) colour = sum(((planes[p] >> bit) & 1) << p for p in range(4)) if colour == 0: continue if opaque[screen_x]: if collision_x is None: collision_x = screen_x continue # the earlier sprite in the buffer wins opaque[screen_x] = True if not bg_priority[screen_x]: out[screen_x] = 16 + colour if collision_x is not None: # "COL flag is set at the pixel it occurs", and "colliding pixels at xpos # 0x83 gives a HCount of 0x47" (FluBBa): HCount x / 2 + 6, a pipeline # delay of 12 dots. MClock = 4 * HCount + 93 = 2x + 117 on the SMS # (VDPTiming.collision; the Game Gear reads $49, enik2). timing = self.variant.timing if self.variant.mega_drive: # The Mega Drive shows the flag at one point of the line whatever # the pixel: FluBBa, "COL flag is set at the pixel it occurs. -13 # (HCount 0xFF) on MD", before the line's first pixel goes out # (see _start_line). Here VDPTiming.collision is that point. if self.m < timing.collision: self.collision_at = timing.collision return out at = 2 * collision_x + timing.collision - timing.line_origin self.collision_at = min(MCLOCKS_PER_LINE - 1, at) return out # TMS9918A modes 0-3 (Young sections 3-4; TI data manual) --------------------- def _render_tms(self, line: int, overflow: bool | None = None) -> list[int]: regs = self.registers m1, m2, m3 = regs[1] & 0x10, regs[0] & 0x02, regs[1] & 0x08 backdrop = self._backdrop_rgb() row, pixel_row = line >> 3, line & 7 name_base = (regs[2] & 0x0F) << 10 colours: list[int] = [0] * 256 if m1: # Text (Young 3.2); modes 1+3 and 1+2+3 also land here (Young 3.7) pattern_base = (regs[4] & 0x07) << 11 if m2: # Undocumented mode 1+2: three pattern tables (Young 3.5) pattern_base = (regs[4] & 0x04) << 11 foreground, background = regs[7] >> 4, regs[7] & 0x0F for column in range(40): name = self.vram[name_base + row * 40 + column] if m2: name |= ((row >> 3) << 8) & (((regs[4] & 0x03) << 8) | 0xFF) bits = self.vram[(pattern_base + name * 8 + pixel_row) & 0x3FFF] for pixel in range(6): lit = bits & (0x80 >> pixel) colours[6 + column * 6 + pixel] = foreground if lit else background # The 240 pixels sit 6 from the left of the other modes' 256, not 8: # the left border is 13 pixel clocks in the pattern modes and 19 in # text, the right one 15 and 25 (TMS9918A data manual, table 3-3). # Young 3.2 has "8 pixels border at the left and right". result = [self._tms_rgb(c) if c else backdrop for c in colours] result[:6] = [backdrop] * 6 result[246:] = [backdrop] * 10 self._tms_sprites(line, None, overflow=overflow) # sprites off in text mode return result for column in range(32): name = self.vram[name_base + row * 32 + column] if m3: # Multicolor (Young 3.4) pattern_base = (regs[4] & 0x07) << 11 byte = self.vram[pattern_base + name * 8 + (row & 3) * 2 + (pixel_row >> 2)] left, right = byte >> 4, byte & 0x0F for pixel in range(8): colours[column * 8 + pixel] = left if pixel < 4 else right continue if m2: # Graphics II: tables in thirds, registers 3 and 4 as masks (Young 3.3) character = name | (line >> 6) << 8 pattern_address = ((regs[4] & 0x04) << 11) | ( (character & (((regs[4] & 0x03) << 8) | 0xFF)) << 3 ) colour_address = ((regs[3] & 0x80) << 6) | ( (character & (((regs[3] & 0x7F) << 3) | 0x07)) << 3 ) bits = self.vram[pattern_address + pixel_row] colour = self.vram[colour_address + pixel_row] else: # Graphics I (Young 3.1) bits = self.vram[((regs[4] & 0x07) << 11) + name * 8 + pixel_row] colour = self.vram[(regs[3] << 6) + (name >> 3)] foreground, background = colour >> 4, colour & 0x0F for pixel in range(8): colours[column * 8 + pixel] = foreground if bits & (0x80 >> pixel) else background sprites = self._tms_sprites(line, colours, overflow=overflow) return [ self._tms_rgb(s) if s else (self._tms_rgb(c) if c else backdrop) for s, c in zip(sprites, colours, strict=True) ] def _tms_sprites( self, line: int, colours: list[int] | None, overflow: bool | None = None ) -> list[int]: """32 one-colour sprites, four per line, fifth-sprite and collision flags. Young section 4; the bookkeeping of the fifth-sprite number follows MAME 0.285 ``tms9928a.cpp`` (a detector), which agrees with Young where Young speaks: the number is the fifth sprite's, else the last one examined (31, or the first with Y = 208). MAME updates it on each displayed line only while the 5S flag is clear, sets 5S only while the frame flag is clear, and evaluates nothing while the display is blanked or in text mode. """ if overflow is None: overflow = self.variant.timing.flags >= 0 regs = self.registers out = [0] * 256 blanked = colours is None or not regs[1] & 0x40 if blanked and self.variant.tms_status_low_bits: return out # MAME: a blanked line leaves the sprite state untouched if regs[1] & 0x10: if self.variant.tms_status_low_bits: self.fifth_sprite = 31 # text mode: "sprites are disabled" (MAME) return out sat = (regs[5] & 0x7F) << 7 pattern_base = (regs[6] & 0x07) << 11 big = bool(regs[1] & 0x02) zoom = bool(regs[1] & 0x01) size = (16 if big else 8) * (2 if zoom else 1) shown = 0 examined = 31 fifth_found = False opaque = [False] * 256 for index in range(32): examined = index base = sat + index * 4 y = self.vram[base] if y == 0xD0: break top = (y - 256 if y > 0xE0 else y) + 1 # "vert pos 255 is ... the first line" if not top <= line < top + size: continue if shown == 4: if not self.variant.tms_status_low_bits: if overflow: self._sega_overflow(index * 4) # Sega VDP in a TMS mode continue fifth_found = True break shown += 1 if blanked: continue # a Sega VDP still counts sprites for overflow (FluBBa) x = self.vram[base + 1] attributes = self.vram[base + 3] if attributes & 0x80: x -= 32 # early clock (Young 4.1) colour = attributes & 0x0F pattern = self.vram[base + 2] if big: pattern &= 0xFC row = line - top if zoom: row >>= 1 for column in range(size): screen_x = x + column if not 0 <= screen_x < 256: continue source = column >> 1 if zoom else column byte = pattern_base + pattern * 8 + row + (16 if source >= 8 else 0) if not self.vram[byte & 0x3FFF] & (0x80 >> (source & 7)): continue # Collision counts pattern bits whatever the colour (Young 4.3). if opaque[screen_x]: self.status |= STATUS_COLLISION opaque[screen_x] = True # "If the colour is 0, the sprite is transparent (not visible)" (Young # 4.1): a lower-priority sprite shows through it (Ping Pong's ball). if colour and not out[screen_x]: out[screen_x] = colour if self.variant.tms_status_low_bits: # MAME keeps the number (m_FifthSprite) current on every displayed line, # and copies it into the status register only while 5S is clear. self.fifth_sprite = examined if not self.status & STATUS_OVERFLOW: self.low_bits = examined if fifth_found and not self.status & STATUS_FRAME: self.status |= STATUS_OVERFLOW return out