"""The ColecoVision board: decode, the timeline, the waits, the interrupts. One timeline in CPU clocks (3.579545 MHz); the VDP runs three master clocks to each. The board asks z80-python for one step, counts the M1 cycles the core reports through ``read_m1`` (each costs one wait clock), adds the SN76489A's READY wait after each sound write, and brings the VDP (and the sound chip) to the moment of each port access before serving it. Sources are cited as in ``docs/memory-map.md``. Where inside an instruction a port access falls comes from z80-python's own access table (``z80_python.timing``, derived from SingleStepTests, tier 5): the access's T-state offset, plus one clock for each M1 cycle already made in the step, plus the READY waits already served in it. """ from __future__ import annotations from collections.abc import Callable from tms9918_python import TMS9918 from z80_python import Z80CPU, M1Cycle from z80_python.timing import instruction_timing from colecovision_python.cartridge import Cartridge, NoCartridge from colecovision_python.controllers import JOYSTICK, KEYPAD, ControllerPort, Unplugged from colecovision_python.machine import MASTER_PER_CPU_CLOCK, NTSC, BoardOptions, Machine from colecovision_python.sockets import Sockets _FETCH = M1Cycle.FETCH #: With ``mame_video_rounding``: how far (in 1 / 10,738,635 of a master clock) the VDP is #: run ahead of MAME's rounded ratio. Fitted, not derived: MAME's frame interrupt reaches #: its Z80 about one CPU clock before the exact time of the pixel position its timer names #: (its scheduler's time-to-cycles rounding). On Donkey Kong's port stream (1,000 frames) #: biases of 0, 1 and 2 master clocks first diverge at accesses 58,279, 60,654 and 65,531 #: (an NMI one instruction late), 3 master clocks runs to 66,954 (then a sprite-status #: difference), 4 to 8 diverge at 58,374 (an NMI one instruction early). MAME_ROUNDING_BIAS = 3 * 10_738_635 class Board: """The console's circuitry around its three chips. ``bios``: the 8K OS-7 image. ``cartridge``: anything with the :class:`~colecovision_python.cartridge.Cartridge` methods, or None for an empty slot. ``psg``: a ``sn76489_python.SN76489`` (or anything with ``write(value)`` and ``run(input_clocks)``), or None (then sound writes are only logged and waited for). The board runs it to each write's clock; :meth:`run_psg` brings it to any clock. ``io_log``: if a list, every port access is appended as ``(kind, port, value, instruction_start_clock, access_clock)``, kind "IR" or "IW", the shape of the MAME log (docs/mame-oracle.md). """ def __init__( self, bios: bytes, cartridge: Cartridge | None = None, *, machine: Machine = NTSC, options: BoardOptions | None = None, sockets: Sockets | None = None, port1: ControllerPort | None = None, port2: ControllerPort | None = None, psg: object | None = None, ram: bytes | None = None, io_log: list | None = None, ) -> None: if len(bios) != 8192: raise ValueError(f"the BIOS is 8,192 bytes, not {len(bios)}") self.machine = machine self.options = options = options or BoardOptions() self.sockets = sockets or Sockets() self.bios = bytes(bios) # U6: the 2114s' power-on contents are unknown; zeros unless seeded. self.ram = bytearray(ram) if ram is not None else bytearray(1024) if len(self.ram) != 1024: raise ValueError("ram must be 1,024 bytes") self.cartridge = cartridge if cartridge is not None else NoCartridge(options.open_bus_memory) self.ports: list[ControllerPort] = [Unplugged(), Unplugged()] self.psg = psg self.psg_clock = 0 # CPU clocks the sound chip has been run to self.io_log = io_log #: Called with the CPU clock of each controller read before it is served, so a #: host's input script can change the pads at an exact moment (tools only). self.input_hook: Callable[[int], None] | None = None self.vdp = TMS9918(machine.vdp_variant, 16384, **options.vdp) if options.vdp_phase: # STOPGAP (docs/core-issues/0001-vdp-power-on-phase.md): tms9918-python has # no way to start its counters anywhere but line 0, dot 0, so the board runs # it to the phase before power-on. That run passes the flag point and sets # F; one status read puts the status back to its power-on value (F, 5S and # C clear; nothing else in the chip is touched by it at this point: the # flip-flop is already clear and IE is 0). Remove when the core takes a phase. self.vdp.run(options.vdp_phase) self.vdp.read(1) self.vdp.take_frame() # The controller strobe flip-flop (U24A/B): one segment at a time [TM; SCH]. # Its state at power-on is not given; the BIOS writes $C0 first thing. self.segment = KEYPAD # The spinner circuit, per port (docs/controllers.md; U15 for the widths). self.spinner_int_clocks = [39, 39] # MAME: 11 us "TODO: measure" (U15) self.one_shot_clocks = [1790, 1790] # MAME: 500 us "TODO" (U15) self._one_shot_until = [-1, -1] self._int_pulse_until = -1 self.clock = 0 # CPU clocks since power-on, at the end of the last step self.vdp_clock = 0 # CPU clocks the VDP has been run to self._mame_rounding = options.mame_video_rounding self._vdp_master = 0 # master clocks run since power-on (MAME rounding only) self.steps = 0 self._step_start = 0 self._step_pc: int | None = None self._m1 = 0 self._extra = 0 self._nmi_level = False self._expansion_nmi = False self._timing_cache: dict[tuple[int, ...], int] = {} self.plug(0, port1) self.plug(1, port2) memory_readers = self._build_readers() self._readers = memory_readers self.cpu = Z80CPU( self.read_byte, self.write_byte, read_port=self.read_port, write_port=self.write_port, read_m1=self._read_m1, ) for name, value in options.power_on_cpu.items(): setattr(self.cpu, name, value) # ------------------------------------------------------------------ memory def _build_readers(self) -> list[Callable[[int], int]]: """One reader per 8K block (U5 decodes A13-A15 with a 74LS138 [SCH sheet 9]).""" bios, ram, cart = self.bios, self.ram, self.cartridge open_bus = self.options.open_bus_memory def read_bios(address: int) -> int: return bios[address] def read_open(address: int) -> int: return open_bus def read_ram(address: int) -> int: # 1K in two 2114s on A0-A9, selected by the whole $6000 block: 8 mirrors. return ram[address & 0x3FF] cart_read = cart.read return [read_bios, read_open, read_open, read_ram, cart_read, cart_read, cart_read, cart_read] def read_byte(self, address: int) -> int: memory = self.sockets.memory if memory is not None and address < 0x8000: claimed = memory.read(address) if claimed is not None: return claimed return self._readers[address >> 13](address) def write_byte(self, address: int, value: int) -> None: if address < 0x8000: memory = self.sockets.memory if memory is not None and memory.write(address, value): return if address >= 0x6000: self.ram[address & 0x3FF] = value return # The slot has no /WR: the cartridge sees an access (docs/cartridge.md). self.cartridge.write(address, value) def peek(self, address: int) -> int: """A memory byte without side effects (no bank switch, no socket log).""" if address >= 0x8000: return self.cartridge.peek(address) return self._readers[address >> 13](address) def _read_m1(self, address: int, kind: M1Cycle) -> int: """Every M1 cycle gets one wait clock (U8A, a 74LS74 held reset while /M1 is high, pulls /WAIT for one clock [SCH sheet 9; DB sheet 4]). HALT cycles too; the NMI response and the interrupt acknowledge by option (C11).""" if kind is _FETCH: self._m1 += 1 return self.read_byte(address) if kind is M1Cycle.HALT: self._m1 += 1 return 0 if self.options.m1_wait_on_acknowledge: self._m1 += 1 if kind is M1Cycle.ACKNOWLEDGE and self.options.acknowledge_reads_vdp: # U3: an acknowledge is /IORQ with /WR high and PC on the address bus; the # I/O decoder has no /M1 term, so PC's low byte selects a read strobe. low = address & 0xFF if 0xA0 <= low <= 0xBF: self._catch_up(self._step_start + 3) self.vdp.read(low & 1) self._check_nmi() return 0 # ------------------------------------------------------------------ I/O def _access_clock(self) -> int: """The CPU clock of the port access being made in the current step (or now, for a host's own access between steps).""" pc = self._step_pc if pc is None: return self.clock peek = self.peek key = (peek(pc), peek((pc + 1) & 0xFFFF), peek((pc + 2) & 0xFFFF), peek((pc + 3) & 0xFFFF)) offset = self._timing_cache.get(key) if offset is None: timing = instruction_timing(key) offset = next(a.t for a in timing.accesses if a.kind in ("in", "out")) self._timing_cache[key] = offset return self._step_start + offset + self._m1 + self._extra def read_port(self, port: int) -> int: port &= 0xFF if port < 0x80: io = self.sockets.io value = io.read(port) if io is not None else None value = self.options.open_bus_port if value is None else value else: block = port & 0x60 if block == 0x20: # $A0-$BF: the VDP, A0 = MODE self._catch_up(self._access_clock()) value = self.vdp.read(port & 1) self._check_nmi() elif block == 0x60: # $E0-$FF: the controllers, A1 picks the port value = self._read_controller((port >> 1) & 1, self._access_clock()) else: # $80-$9F, $C0-$DF: write strobes only (U4) value = self.options.open_bus_port if self.io_log is not None: self.io_log.append(("IR", port, value, self._step_start, None)) return value def write_port(self, port: int, value: int) -> None: port &= 0xFF if self.io_log is not None: self.io_log.append(("IW", port, value, self._step_start, None)) if port < 0x80: io = self.sockets.io if io is not None: io.write(port, value) return block = port & 0x60 if block == 0x20: self._catch_up(self._access_clock()) self.vdp.write(port & 1, value) self._check_nmi() elif block == 0x60: # The SN76489A; READY holds the CPU while the chip takes the byte (C9). clock = self._access_clock() if self.psg is not None: self.run_psg(clock) self.psg.write(value) self._extra += self.options.ready_wait elif block == 0x40: self.segment = JOYSTICK # $C0-$DF: "reset to segment 0" [OS7] else: self.segment = KEYPAD # $80-$9F def _read_controller(self, index: int, clock: int) -> int: """Bits 0-3 and 6 from the device; 4, 5 and 7 from the console's spinner circuit (docs/controllers.md, two tracings and MiSTer agree on the map).""" device = self.ports[index] if self.input_hook is not None: self.input_hook(clock) # a host's scripted inputs, brought to this moment self._spinner_until(clock) value = device.read(self.segment) & 0x4F # Bit 4: the one-shot's node, low for a while after a shaped pin-9 edge; bit 7: the # shaping NAND's output, held high by that node for the same while (C12, as wired: # the node feeds the NAND's second input [DB sheet 3]). Idle bit 7: U14, 0 here. if clock >= self._one_shot_until[index]: value |= 0x10 else: value |= 0x80 # Bit 5: pin 7, read directly. if device.pin7(clock): value |= 0x20 return value def _spinner_until(self, clock: int) -> None: """Apply the spinner edges up to ``clock``: each starts the port's one-shot and pulses /INT (wired-OR of both ports).""" for index in (0, 1): for edge_clock, _pin7 in self.ports[index].spinner_edges(clock): self._one_shot_until[index] = edge_clock + self.one_shot_clocks[index] end = edge_clock + self.spinner_int_clocks[index] if end > self._int_pulse_until: self._int_pulse_until = end # ------------------------------------------------------------------ time def _catch_up(self, clock: int) -> None: """Run the VDP to CPU clock ``clock``: exactly three master clocks per CPU clock ([TM p. III-5]), or MAME's rounded ratio when ``mame_video_rounding`` is set.""" delta = clock - self.vdp_clock if delta > 0: if self._mame_rounding: # MAME 0.285 runs its screen on a 5,369,317 Hz pixel clock (XTAL / 2 = # 5,369,317.5 truncated), so its video falls behind the CPU by one part in # 10,738,635: measured as frame notifiers every 59,736.0056 CPU clocks. master = (clock * 3 * 10_738_634 + MAME_ROUNDING_BIAS) // 10_738_635 self.vdp.run(master - self._vdp_master) self._vdp_master = master else: self.vdp.run(delta * MASTER_PER_CPU_CLOCK) self.vdp_clock = clock def run_psg(self, clock: int) -> None: """Run the sound chip to CPU clock ``clock``: it is clocked by the CPU clock (3.579545 MHz [TM]); sn76489-python counts input clocks.""" delta = clock - self.psg_clock if delta > 0: self.psg.run(delta) self.psg_clock = clock def _check_nmi(self) -> None: """/NMI is the VDP's /INT; the Z80 takes its falling edge, i.e. the rising edge of the core's ``int_line`` (asserted) [memory-map.md, "Interrupts"].""" level = self.vdp.int_line if level and not self._nmi_level: self.cpu.request_non_maskable_interrupt() self._nmi_level = level def step(self) -> int: """One CPU step (an instruction, a HALT cycle or an interrupt response) with its waits; returns the CPU clocks it took.""" start = self.clock self._step_start = start cpu = self.cpu self._step_pc = cpu.pc self._m1 = 0 self._extra = 0 t_states = cpu.step() self._step_pc = None total = t_states + self._m1 + self._extra wait = self.sockets.wait if wait is not None: total += wait.wait_clocks(start) end = start + total self.clock = end self.steps += 1 self._catch_up(end) self._check_nmi() if self._int_sources: self._update_int(end) return total def plug(self, index: int, device: ControllerPort | None) -> None: """Put ``device`` in port ``index`` (0 or 1); None unplugs it.""" self.ports[index] = device or Unplugged() self._int_sources = self.sockets.interrupts is not None or any( getattr(d, "has_spinner", False) for d in self.ports ) def _update_int(self, clock: int) -> None: """The maskable /INT: the spinner pulses, wired-OR with the expansion port's.""" self._spinner_until(clock) level = clock < self._int_pulse_until interrupts = self.sockets.interrupts if interrupts is not None: level = level or interrupts.int_line nmi = interrupts.nmi_line if nmi and not self._expansion_nmi: self.cpu.request_non_maskable_interrupt() self._expansion_nmi = nmi if level: self.cpu.request_maskable_interrupt(0xFF) elif self.cpu.maskable_interrupt_pending: self.cpu.clear_maskable_interrupt()