// SPDX-License-Identifier: MIT //! Controllers on the two joystick ports: joysticks, paddles, keypads, the //! Driving controller and the Booster Grip (the SaveKey is in savekey.rs). //! //! The port's nine pins (DOC: nocash 2k6specs "Controllers: External Port //! Pin-Outs"): pins 1-4 are SWCHA D4-D7 on the left port and D0-D3 on the //! right, pin 6 is INPT4/INPT5, pins 5 and 9 are INPT0/INPT1 (left) and //! INPT2/INPT3 (right), pin 7 is +5 V and pin 8 ground. A switch closed to //! ground reads 0. //! //! Joysticks and the console switches are plain levels (`RIOT::set_input_a`, //! `RIOT.input_b`, `TIA.fire`); [`Joystick`] sets them for one port. //! A paddle is a timing measurement and a keypad a matrix scanned through a RIOT //! port: each installs itself as `TIA.pad_source`, which the TIA asks for the //! pads' levels I0-I5 when the 6507 reads one (one pad source at a time). //! //! **Paddles** (docs/timing.md "Inputs"). Each of I0-I3 has a 1,800 Ω resistor //! and a 0.068 µF capacitor to ground on the console board (DOC: 2600 //! schematic, sheet 1, `reference/schematics/Schematic_Atari2600_2000.png`), //! charged from +5 V through the paddle's pot. VBLANK D7 grounds the pads, //! emptying the capacitors; from its release the voltage rises as //! 1 - exp(-t/RC) and the pad reads 1 once it passes the input's trip point. //! The pot's range and the trip point are nocash's (DOC, below); the die traces //! have no paddle (tia-fpga left them off the board). The time is the TIA's //! own, in half colour clocks. //! //! **The Driving controller** (DOC: nocash "Controllers: Steering"): a 16-position //! rotary binary switch, of which bit 1 drives pin 1 and bit 1 XOR bit 0 drives //! pin 2, each closing to ground; the button is pin 6. So pins 1 and 2 read a //! two-bit Gray code that repeats every four positions: 11, 10, 00, 01 for //! positions 0-3 (pin 1 first, 1 = open). Pins 3 and 4 are not connected and //! read 1. Which way round is clockwise is not in the document: HYPOTHESIS that //! turning clockwise counts the switch up; Indy 500's car turning the same way //! as the knob would settle it (milestone 6 records the experiment). //! //! **The Booster Grip** (DOC: nocash "3-Button Joystick Adapter", used by Omega //! Race and Thrust): a joystick with two more buttons that connect pins 5 and 9 //! to +5 V, with no resistor of their own, so a pressed button charges its pad //! through the console's 1,800 Ω like a paddle at its 0 Ω end, and a released //! one leaves the pad uncharged (it reads 0, as with nothing plugged in, C19). //! Programs dump the pads with VBLANK D7 and read them later, as for paddles. //! nocash calls them the 2nd button (pin 5: INPT0/INPT2) and the 3rd (pin 9: //! INPT1/INPT3); which of CBS's printed names ("trigger", "booster") goes with //! which pin no permitted source says. //! //! **Keypads** (docs/timing.md "Inputs"). Twelve keys in four rows and three //! columns. The rows are driven from SWCHA (left port D4-D7, right D0-D3, top //! row first), so a program makes a row's bit an output and drives it low; a //! pressed key in that row pulls its column low. The columns are read on //! INPT0, INPT1, INPT4 (left) and INPT2, INPT3, INPT5 (right). The columns //! settle instantly here; a console's column lines have an RC delay programs //! wait out, so a program that waits reads the same. //! //! Rust-forced differences (a2600-python `controllers.py` at 28fb095): a device //! holds no reference to the chips; the methods that change pins take the TIA //! and the RIOT as arguments (`set`, `turn`, `press`). The state a pad source //! reads at read time (paddle positions, pressed keys) is shared with the //! installed closure (`Rc>`), and the keypads hold the board's //! shared RIOT. `Joystick.set`'s keyword arguments are a [`Stick`]; a paddle //! position of `None` is `Option`. use std::cell::RefCell; use std::collections::BTreeSet; use std::rc::Rc; use serde::{Deserialize, Serialize}; use crate::riot::RIOT; use crate::tia::TIA; pub const R_SERIES: f64 = 1800.0; // ohms; DOC: 2600 schematic, sheet 1 pub const CAPACITANCE: f64 = 0.068e-6; // farads; DOC: 2600 schematic, sheet 1 pub const POT_MAX: f64 = 1.0e6; // ohms; DOC: nocash 2k6specs "POT Timing Table" (1M at -135 degrees) // The trip point, as a fraction of the supply. DOC: nocash's table gives 380 // scanlines for the 1 MOhm end and 190 for 500 kOhm; under the schematic's RC // that is a trip at 1 - exp(-t/RC) of the supply, about 0.30 (a TTL-like // threshold; milestone 6). The table is "counted in scanline units" and says // a console varies by at least one line and drifts as it warms: so the value // is the document's typical console, not a measurement here. Milestone 3 had // taken half the supply as a fit (742 lines at 1 MOhm, twice the document's). pub const NOCASH_LINES_AT_POT_MAX: f64 = 380.0; const NTSC_LINE_S: f64 = 228.0 / (315e6 / 88.0); /// `TRIP`: computed as the reference computes it (`1 - exp(-t / RC)`). pub fn trip() -> f64 { 1.0 - (-NOCASH_LINES_AT_POT_MAX * NTSC_LINE_S / ((R_SERIES + POT_MAX) * CAPACITANCE)).exp() } /// Four paddles on I0-I3; `position[i]` from 0.0 (no resistance) to 1.0 (POT_MAX). /// /// `None` leaves a pad to `TIA.inputs`: 0 on the board, as a pad with /// no pot never charges (docs/undocumented-behavior.md C19). #[derive(Clone)] pub struct Paddles { pub position: Rc; 4]>>, pub seconds_per_step: f64, pub trip: f64, } impl Paddles { pub fn new(tia: &mut TIA, colour_clock_hz: f64) -> Paddles { let paddles = Paddles { position: Rc::new(RefCell::new([None; 4])), seconds_per_step: 1.0 / (2.0 * colour_clock_hz), trip: -(1.0 - trip()).ln(), }; let source = paddles.clone(); tia.pad_source = Some(Box::new(move |tia: &TIA| source.levels(tia))); paddles } /// Half colour clocks from the dump's release until pad `i` reads 1. pub fn trip_steps(&self, i: usize) -> f64 { let position = self.position.borrow()[i].unwrap_or(0.0); let resistance = R_SERIES + POT_MAX * position; resistance * CAPACITANCE * self.trip / self.seconds_per_step } pub fn levels(&self, tia: &TIA) -> u32 { let mut levels = tia.inputs; if tia.vblank & 0x80 != 0 { return levels; } let elapsed = (tia.now() - tia.dump_released) as f64; let position = *self.position.borrow(); for (i, p) in position.iter().enumerate() { if p.is_some() { if elapsed >= self.trip_steps(i) { levels |= 1 << i; } else { levels &= !(1 << i); } } } levels } } /// Two 12-key keypads; `pressed[port]` is a set of (row, column), 0-3 x 0-2. #[derive(Clone)] pub struct Keypads { pub riot: Rc>, pub pressed: Rc; 2]>>, } impl Keypads { pub const COLUMN_PADS: [[u32; 3]; 2] = [[0, 1, 4], [2, 3, 5]]; pub fn new(tia: &mut TIA, riot: Rc>) -> Keypads { let keypads = Keypads { riot, pressed: Rc::new(RefCell::new([BTreeSet::new(), BTreeSet::new()])), }; let source = keypads.clone(); tia.pad_source = Some(Box::new(move |tia: &TIA| source.levels(tia))); keypads } pub fn levels(&self, tia: &TIA) -> u32 { let driven_low = { let riot = self.riot.borrow(); riot.ddr_a & !riot.out_a }; let mut levels = tia.inputs; for port in 0..2 { let shift = if port == 0 { 4 } else { 0 }; for &(row, column) in self.pressed.borrow()[port].iter() { if (driven_low >> (shift + row)) & 1 != 0 { levels &= !(1 << Self::COLUMN_PADS[port][column as usize]); } } } levels } } /// `Joystick.set`'s switches (all released by default). #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] pub struct Stick { pub up: bool, pub down: bool, pub left: bool, pub right: bool, pub fire: bool, } /// A joystick on `port` (0 left, 1 right): four switches and a button. /// /// DOC: nocash "Controllers: Joysticks": up, down, left, right on pins 1-4 /// (SWCHA D4-D7 left, D0-D3 right), the button on pin 6 (INPT4/INPT5), each /// closing to ground. #[derive(Clone, Copy, Debug)] pub struct Joystick { pub port: usize, pub shift: u32, } impl Joystick { pub fn new(port: usize) -> Joystick { Joystick { port, shift: if port == 0 { 4 } else { 0 }, } } pub fn set(&self, tia: &mut TIA, riot: &mut RIOT, stick: Stick) { let closed = stick.up as u8 | (stick.down as u8) << 1 | (stick.left as u8) << 2 | (stick.right as u8) << 3; let mask = 0x0F << self.shift; riot.set_input_a((riot.input_a & !mask) | (!closed & 0x0F) << self.shift); tia.fire[self.port] = stick.fire; } } /// The Driving controller's pins 1 and 2 for switch positions 0-3, 1 = open /// (DOC: nocash "Controllers: Steering"; pin 1 = NOT bit 1, pin 2 = NOT (bit 1 XOR bit 0)). pub const GRAY: [u8; 4] = { let mut gray = [0u8; 4]; let mut n = 0; while n < 4 { gray[n] = (1 - ((n as u8 >> 1) & 1)) | (1 - (((n as u8 >> 1) ^ n as u8) & 1)) << 1; n += 1; } gray }; /// A Driving controller on `port`: `turn(+1)` is one click clockwise /// (HYPOTHESIS for the sense, see the module notes); `fire` the button. #[derive(Clone, Debug, Serialize, Deserialize)] pub struct DrivingController { pub port: usize, pub shift: u32, pub position: i64, // the 16-position switch pub fire: bool, } impl DrivingController { pub fn new(tia: &mut TIA, riot: &mut RIOT, port: usize) -> DrivingController { let wheel = DrivingController { port, shift: if port == 0 { 4 } else { 0 }, position: 0, fire: false, }; wheel.apply(tia, riot); wheel } pub fn turn(&mut self, tia: &mut TIA, riot: &mut RIOT, clicks: i64) { self.position = (self.position + clicks).rem_euclid(16); self.apply(tia, riot); } pub fn press(&mut self, tia: &mut TIA, riot: &mut RIOT, fire: bool) { self.fire = fire; self.apply(tia, riot); } fn apply(&self, tia: &mut TIA, riot: &mut RIOT) { let mask = 0x0F << self.shift; let levels = GRAY[(self.position & 3) as usize] | 0b1100; // pins 3 and 4 not connected riot.set_input_a((riot.input_a & !mask) | levels << self.shift); tia.fire[self.port] = self.fire; } } /// A Booster Grip on `port`: a [`Joystick`] plus the buttons on pins 5 and 9. /// /// The two buttons are pads charged through the console's RC (module notes), /// so they share a [`Paddles`] with anything else on I0-I3. #[derive(Clone)] pub struct BoosterGrip { pub joystick: Joystick, pub paddles: Paddles, pub port: usize, } impl BoosterGrip { pub fn new(paddles: Paddles, port: usize) -> BoosterGrip { BoosterGrip { joystick: Joystick::new(port), paddles, port, } } pub fn set(&self, tia: &mut TIA, riot: &mut RIOT, pin5: bool, pin9: bool, stick: Stick) { self.joystick.set(tia, riot, stick); let first = 2 * self.port; let mut position = self.paddles.position.borrow_mut(); position[first] = if pin5 { Some(0.0) } else { None }; position[first + 1] = if pin9 { Some(0.0) } else { None }; } }