// SPDX-License-Identifier: MIT //! The 5200 controllers: analog sticks, keypads, two buttons, through POKEY and GTIA. //! //! [AHRM] 13.3 (tier 3), [FSM] Figure 1-6 (tier 2), [BUCH]: //! //! - **Stick**: port n drives POT(2n) horizontally and POT(2n+1) vertically, //! low = left/up. The board gives POKEY each pin's level through //! pokey-python's RC helper (`pokey_python.rc.PotRC`, the core's B5.8): a //! stick at count p crosses the threshold after p slow-scan steps //! (`SCAN_STEP` cycles each) of charging with the dump transistors off. CONSOL bit 2 //! powers the pots: with it low no pin ever crosses and every POT reads 228. //! The stick is not self-centring; defaults centre 114 (C10, a labelled //! choice). //! - **Keypad, Start/Pause/Reset**: on POKEY's keyboard scan, for the port that //! CONSOL bits 0-1 select. K0 and K5 are unconnected ([FSM] Figure 1-6), so a //! key with code k (KBCODE bits 1-4, [AHRM] 13.3 table) answers at every scan //! code c with (c >> 1) & 15 == k: four codes per 64-step scan. //! - **Upper button**: POKEY's /KR2 for the selected port: Shift, Control and //! Break ([AHRM] 13.3). //! - **Lower button**: GTIA TRIG(n), 0 when pressed. //! //! The 2-port row grounds POT4-POT7 ([FAQ] 4.10 item 2) and has no ports 3-4. //! //! Evidence tags (methodology): the wiring above is DOC ([AHRM] 13.3, [FSM] //! Figure 1-6, [BUCH], [FAQ]); PAM v1.1's Pokey Adjust screen matches [FSM] //! Figure 3-4 on this model (a manufacturer's test program, read from the //! screen). The stick's centre and span and every trak-ball constant are //! HYPOTHESIS (labelled choices, C10, U11). Port 3-4 use: OBSERVED in Super //! Breakout's own four-player mode only (U4). //! //! A transcription of a5200-python's `controllers.py` (at cf82d44). Rust-forced differences: //! //! - Python's `Controllers` holds the board and installs its own bound methods as POKEY's //! `key_response` and `pot_level`. A Rust closure the chip owns cannot reach the board, so //! what those two read is shared: the pads (`Rc>>`), GTIA's CONSOL lines //! (`gtia.consol_out`, a shared cell), the trak-ball pins (`Rc>`) and the //! capacitors (`Rc>`, pokey-rust's helper). The methods that touch the chips //! (`new`, `wire_pots`, `apply`, `frame`) take the board; `key_response` and `pot_level` are //! the functions the closures call. //! - `pot_target` uses `round_ties_even` (Python's `round`) and returns `Option`. //! - `Pad.keys` is a `BTreeSet` (Python's set; only membership is used). use std::cell::{Cell, RefCell}; use std::collections::BTreeSet; use std::rc::Rc; use pokey::rc::PotRC; use pokey::Look; use serde::{Deserialize, Serialize}; use crate::board::Board; use crate::machine::Machine; /// DOC: KBCODE bits 1-4 for each key ([AHRM] 13.3 table; [FSM] Figure 1-6). pub fn key_code(key: &str) -> Option { Some(match key { "1" => 0xF, "2" => 0xE, "3" => 0xD, "start" => 0xC, "4" => 0xB, "5" => 0xA, "6" => 0x9, "pause" => 0x8, "7" => 0x7, "8" => 0x6, "9" => 0x5, "reset" => 0x4, "*" => 0x3, "0" => 0x2, "#" => 0x1, _ => return None, }) } pub const NEVER: f64 = 10_000.0; // a pot count that never crosses within a scan (POT reads 228: DOC [AHRM] 13.3) // DOC: one slow pot-scan step per 15 kHz period of 114 machine cycles ([AHRM] 5.2, 5.9). The // core's RC helper keeps charge in cycles, so a stick at count p is a target of p steps. pub const SCAN_STEP: f64 = 114.0; /// PotRC's target (cycles of charging to threshold) for a pot count; None never crosses. pub fn pot_target(count: f64) -> Option { if count >= NEVER { None } else { Some((count * SCAN_STEP).round_ties_even() as i64) } } /// One controller's state, set by the frontend or a script. #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct Pad { pub x: f64, // HYPOTHESIS: a centred stick at 114 (C10; [BUCH] gives the range 1-228) pub y: f64, pub trigger: bool, // lower button pub top: bool, // upper button pub keys: BTreeSet, pub plugged: bool, // CX53 Trak-Ball instead of a stick (see TrakBall): the frontend sets the // ball's speed in counts per frame; x/y are then derived, not set. pub trakball: bool, pub vx: f64, pub vy: f64, } impl Default for Pad { fn default() -> Self { Pad { x: 114.0, y: 114.0, trigger: false, top: false, keys: BTreeSet::new(), plugged: true, trakball: false, vx: 0.0, vy: 0.0, } } } /// The CX53 Trak-Ball as the board sees it: speed in, pot position out (U11). /// /// [DANB] (trak-ball page, tier 3): the motion board is two tachometers with /// digital inputs (slotted encoder wheels between opto-interrupters) and /// analog outputs; rolling faster is "pushing an analog joystick further in /// the corresponding direction". [AHRM] 13.3: CONSOL bit 2 "doubles as the /// calibration control line for the trackball and as a trackball detection /// mechanism". The numbers here are labelled choices, not measurements: a /// ball speed of `full_speed` encoder counts per frame gives a full /// deflection of `span` pot counts either side of `centre`, the output /// follows the speed through a first-order lag of `lag` (fraction kept per /// frame), and with CONSOL bit 2 low the outputs sit at the centre (the /// calibration state) instead of reading 228 like an unpowered stick, which /// is what lets software tell the two apart. U11 stays open: the /// schematic's time constants were not read. /// /// Evidence: the speed-to-deflection behaviour is DOC ([DANB], [FSM] section /// 7); the CONSOL bit 2 behaviour is DOC ([AHRM] 13.3, [FSM] section 7) and /// is accepted by RealSports Football's and Soccer's own trak-ball tests /// (the cartridges' code, run on this board); 10 of the 12 [FAQ] titles /// follow a scripted roll. Every constant below is HYPOTHESIS: reading the /// motion board's RC values off [DANB]'s schematic and timing a real CX53 /// would settle them. #[derive(Clone, Debug, PartialEq)] pub struct TrakBall { pub out: [f64; 2], } impl TrakBall { pub const CENTRE: f64 = 114.0; // HYPOTHESIS (C10): the stick's labelled centre pub const SPAN: f64 = 100.0; // HYPOTHESIS: counts either side, inside [AHRM] 13.3's 160-count minimum pub const FULL_SPEED: f64 = 8.0; // HYPOTHESIS: encoder counts per frame for a full deflection pub const LAG: f64 = 0.5; // HYPOTHESIS: fraction of the previous output kept per frame pub fn new() -> Self { TrakBall { out: [Self::CENTRE, Self::CENTRE], } } /// One frame: the two pot counts for this frame's ball speed. pub fn step(&mut self, vx: f64, vy: f64, calibrating: bool) -> (f64, f64) { for (axis, speed) in [vx, vy].into_iter().enumerate() { let target = if calibrating { Self::CENTRE } else { let deflection = (speed / Self::FULL_SPEED).clamp(-1.0, 1.0); Self::CENTRE + deflection * Self::SPAN }; self.out[axis] = Self::LAG * self.out[axis] + (1.0 - Self::LAG) * target; } (self.out[0], self.out[1]) } } impl Default for TrakBall { fn default() -> Self { Self::new() } } pub struct Controllers { pub pads: Rc>>, pub rc: Rc>, pub _balls: [TrakBall; 4], pub _trak_pins: Rc>, } impl Controllers { pub fn new(board: &mut Board) -> Self { let machine = board.machine; let pads = Rc::new(RefCell::new( (0..machine.ports) .map(|n| Pad { plugged: n < 2, ..Pad::default() }) .collect::>(), )); let trak_pins = Rc::new(Cell::new([false; 8])); let rc = Self::_wire(board, &trak_pins); let key_pads = Rc::clone(&pads); let consol = board.gtia.consol_out.share(); board.pokey.key_response = Box::new(move |code| key_response(&key_pads.borrow(), consol.get(), &machine, code)); let mut controllers = Controllers { pads, rc, _balls: [ TrakBall::new(), TrakBall::new(), TrakBall::new(), TrakBall::new(), ], _trak_pins: trak_pins, }; controllers.apply(board); controllers } /// Eight pot capacitors following the chip's dump transistors (core B5.8). pub fn wire_pots(&mut self, board: &mut Board) { self.rc = Self::_wire(board, &self._trak_pins); } fn _wire(board: &mut Board, trak_pins: &Rc>) -> Rc> { let pokey = &mut board.pokey; let rc = Rc::new(RefCell::new(PotRC::new(pokey, None))); let above = Rc::clone(&rc); let consol = board.gtia.consol_out.share(); let trak = Rc::clone(trak_pins); pokey.pot_level = Box::new(move |n, look| pot_level(&above, consol.get(), trak.get(), n, look)); let dumped = Rc::clone(&rc); pokey.on_dump = Some(Box::new(move |level, look| { dumped.borrow_mut().dumped(level, look) })); rc } /// Push the pads' analog positions and buttons into the chips (steps each trak-ball). /// /// Once per frame, never on a save-state restore: what it derives (pot targets, /// trak-ball pins, the lag, GTIA's trigger inputs) is saved as it stands. pub fn apply(&mut self, board: &mut Board) { let mut pads = self.pads.borrow_mut(); let mut trak_pins = self._trak_pins.get(); for n in 0..4 { let mut trak = false; let counts = if n < pads.len() && pads[n].plugged { let pad = &mut pads[n]; if pad.trakball { trak = true; let calibrating = board.gtia.consol_out.get() & 4 == 0; (pad.x, pad.y) = self._balls[n].step(pad.vx, pad.vy, calibrating); } (pad.x.max(1.0), pad.y.max(1.0)) // DOC: range from 1 ([BUCH]) } else { (NEVER, NEVER) // HYPOTHESIS: an empty port reads like an open pot }; trak_pins[2 * n] = trak; trak_pins[2 * n + 1] = trak; self._trak_pins.set(trak_pins); for axis in 0..2 { let pin = 2 * n + axis; let count = if pin >= 4 && board.machine.pots_upper_grounded { NEVER } else if axis == 0 { counts.0 } else { counts.1 }; self.rc.borrow_mut().target[pin] = pot_target(count); } let pressed = n < pads.len() && pads[n].plugged && pads[n].trigger; board.gtia.set_trigger(n, pressed); } } /// Called once per frame by the console before it runs. pub fn frame(&mut self, board: &mut Board) { self.apply(board); } } /// `Controllers.pot_level`: POKEY's view of pin n. pub fn pot_level( rc: &RefCell, consol_out: u8, trak_pins: [bool; 8], n: usize, look: Look, ) -> bool { if consol_out & 4 == 0 && !trak_pins[n] { return false; // DOC: pots unpowered, nothing crosses ([AHRM] 13.3) } rc.borrow_mut().level(n, look) } /// `Controllers.key_response`: /KR1 and /KR2 for a scan code. pub fn key_response(pads: &[Pad], consol_out: u8, machine: &Machine, code: u8) -> u8 { // DOC: CONSOL bits 0-1 select the scanned port; the upper button on /KR2 // ([AHRM] 13.3, [FSM] Figure 1-6). Response bit 1 = KR2, bit 0 = KR1. let mut port = (consol_out & 3) as usize; if !machine.consol_bit1_selects_ports_34 { port &= 1; } if port >= pads.len() { return 0; } let pad = &pads[port]; if !pad.plugged { return 0; } let mut response = if pad.top { 2 } else { 0 }; if !pad.keys.is_empty() { let k = (code >> 1) & 0x0F; for key in &pad.keys { if key_code(key) == Some(k) { response |= 1; break; } } } response }