pcengine_rust/
pads.rs

1//! The pads: 2-button, 6-button and the 5-player multitap (the mouse is not modelled: U12)
2//! (`pads.py`).
3//!
4//! All implement `sockets::ControllerPort`: the console drives SEL and CLR, the device answers a
5//! nibble on D3-D0 (active low: 0 = pressed). Held-button state is a bit mask the host sets.
6//!
7//! Sources: [hw: pcetech 4] for the 2-button pad and the Turbo Tap; [doc: pce-devel
8//! PCE_Controller_Info] for the 6-button scan counting and the multitap port table.
9//!
10//! Differences forced by Rust: `Pad6` holds a `Pad2`'s mask where the reference subclasses it;
11//! the host sets `pressed` through `ControllerPort::set_pressed` (the board owns the device).
12
13use std::any::Any;
14
15use serde::{Deserialize, Serialize};
16
17use crate::sockets::{ControllerPort, DeviceState};
18
19// Button bits of the host-side state mask.
20pub const UP: u16 = 0x001;
21pub const RIGHT: u16 = 0x002;
22pub const DOWN: u16 = 0x004;
23pub const LEFT: u16 = 0x008;
24pub const I: u16 = 0x010;
25pub const II: u16 = 0x020;
26pub const SELECT: u16 = 0x040;
27pub const RUN: u16 = 0x080;
28pub const III: u16 = 0x100;
29pub const IV: u16 = 0x200;
30pub const V: u16 = 0x400;
31pub const VI: u16 = 0x800;
32
33fn decode<T: for<'a> Deserialize<'a>>(data: &[u8]) -> Result<T, String> {
34    bincode::deserialize(data).map_err(|error| format!("a pad's state: {error}"))
35}
36
37/// A 2-button pad: SEL high shows the directions, SEL low the buttons.
38///
39/// [hw: pcetech 4] While CLR is high the pad's multiplexer outputs 0 on D3-D0. [doc:
40/// controller-info] the 74HC157 gates all four outputs low on CLR.
41#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
42pub struct Pad2 {
43    pub pressed: u16,
44}
45
46impl Pad2 {
47    pub fn new() -> Pad2 {
48        Pad2 { pressed: 0 }
49    }
50
51    fn nibble(&self, sel: bool, clr: bool) -> u8 {
52        if clr {
53            return 0;
54        }
55        if sel {
56            return (!self.pressed & 0x0F) as u8;
57        }
58        (!(self.pressed >> 4) & 0x0F) as u8
59    }
60}
61
62impl DeviceState for Pad2 {
63    fn save_state(&self) -> Vec<u8> {
64        bincode::serialize(self).unwrap()
65    }
66
67    fn load_state(&mut self, data: &[u8]) -> Result<(), String> {
68        *self = decode(data)?;
69        Ok(())
70    }
71
72    fn state_identity(&self) -> String {
73        "Pad2".to_string()
74    }
75}
76
77impl ControllerPort for Pad2 {
78    fn write(&mut self, _sel: bool, _clr: bool) {}
79
80    fn read(&mut self, sel: bool, clr: bool) -> u8 {
81        self.nibble(sel, clr)
82    }
83
84    fn set_pressed(&mut self, _port: usize, pressed: u16) {
85        self.pressed = pressed;
86    }
87
88    fn as_any_mut(&mut self) -> &mut dyn Any {
89        self
90    }
91}
92
93/// The Avenue Pad 6 shape: on alternating scans (counted by CLR pulses) the SEL-high read
94/// shows 0000 and the SEL-low read shows III-VI instead of I, II, Select, Run. [doc:
95/// controller-info] Which scan comes first at power-up is not stated (a game scans twice).
96#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
97pub struct Pad6 {
98    pub pressed: u16,
99    pub second_scan: bool,
100    clr: bool,
101}
102
103impl Pad6 {
104    pub fn new() -> Pad6 {
105        Pad6::default()
106    }
107}
108
109impl DeviceState for Pad6 {
110    fn save_state(&self) -> Vec<u8> {
111        bincode::serialize(self).unwrap()
112    }
113
114    fn load_state(&mut self, data: &[u8]) -> Result<(), String> {
115        *self = decode(data)?;
116        Ok(())
117    }
118
119    fn state_identity(&self) -> String {
120        "Pad6".to_string()
121    }
122}
123
124impl ControllerPort for Pad6 {
125    fn write(&mut self, _sel: bool, clr: bool) {
126        if clr && !self.clr {
127            self.second_scan = !self.second_scan;
128        }
129        self.clr = clr;
130    }
131
132    fn read(&mut self, sel: bool, clr: bool) -> u8 {
133        if clr {
134            return 0;
135        }
136        if !self.second_scan {
137            return Pad2 {
138                pressed: self.pressed,
139            }
140            .nibble(sel, clr);
141        }
142        if sel {
143            return 0;
144        }
145        (!(self.pressed >> 8) & 0x0F) as u8
146    }
147
148    fn set_pressed(&mut self, _port: usize, pressed: u16) {
149        self.pressed = pressed;
150    }
151
152    fn as_any_mut(&mut self) -> &mut dyn Any {
153        self
154    }
155}
156
157/// The Turbo Tap: a counter picks which of five ports answers.
158///
159/// [hw: pcetech 4] The counter increments on each SEL 0 -> 1 transition while CLR is low and
160/// resets on a CLR 0 -> 1 transition with SEL high; after the fifth it answers $0 until reset;
161/// an empty port answers $F.
162///
163/// C10: pcetech says that right after the reset write ($03: SEL and CLR high) D3-D0 already
164/// show pad 1's directions; the pce-devel table puts CLR high on every port at that moment,
165/// which would read 0. `clr_high_reads_pad` selects pcetech's reading (tier 2, the default).
166pub struct MultiTap {
167    pub pads: Vec<Option<Box<dyn ControllerPort>>>,
168    pub clr_high_reads_pad: bool,
169    /// no port selected until the first reset sequence
170    pub counter: usize,
171    sel: bool,
172    clr: bool,
173}
174
175impl MultiTap {
176    pub const PORTS: usize = 5;
177
178    pub fn new(pads: Vec<Option<Box<dyn ControllerPort>>>) -> Result<MultiTap, String> {
179        if pads.len() != Self::PORTS {
180            return Err("a multitap has five ports".to_string());
181        }
182        Ok(MultiTap {
183            pads,
184            clr_high_reads_pad: true,
185            counter: Self::PORTS,
186            sel: false,
187            clr: false,
188        })
189    }
190}
191
192impl DeviceState for MultiTap {
193    fn save_state(&self) -> Vec<u8> {
194        let pads: Vec<Option<Vec<u8>>> = self
195            .pads
196            .iter()
197            .map(|pad| pad.as_ref().map(|pad| pad.save_state()))
198            .collect();
199        bincode::serialize(&(self.counter, self.sel, self.clr, pads)).unwrap()
200    }
201
202    fn load_state(&mut self, data: &[u8]) -> Result<(), String> {
203        let (counter, sel, clr, pads): (usize, bool, bool, Vec<Option<Vec<u8>>>) = decode(data)?;
204        if pads.len() != self.pads.len() {
205            return Err("a multitap with other ports".to_string());
206        }
207        for (pad, saved) in self.pads.iter_mut().zip(&pads) {
208            match (pad, saved) {
209                (Some(pad), Some(saved)) => pad.load_state(saved)?,
210                (None, None) => {}
211                _ => return Err("a multitap with other pads plugged in".to_string()),
212            }
213        }
214        (self.counter, self.sel, self.clr) = (counter, sel, clr);
215        Ok(())
216    }
217
218    fn state_identity(&self) -> String {
219        let pads: Vec<String> = self
220            .pads
221            .iter()
222            .map(|pad| pad.as_ref().map_or("-".to_string(), |p| p.state_identity()))
223            .collect();
224        format!("MultiTap({})", pads.join(","))
225    }
226}
227
228impl ControllerPort for MultiTap {
229    fn write(&mut self, sel: bool, clr: bool) {
230        if clr && !self.clr && sel {
231            self.counter = 0;
232        } else if sel && !self.sel && !clr && self.counter < Self::PORTS {
233            self.counter += 1;
234        }
235        self.sel = sel;
236        self.clr = clr;
237    }
238
239    fn read(&mut self, sel: bool, clr: bool) -> u8 {
240        if self.counter >= Self::PORTS {
241            return 0;
242        }
243        if clr && !self.clr_high_reads_pad {
244            return 0;
245        }
246        match self.pads[self.counter].as_mut() {
247            None => 0x0F,
248            Some(pad) => pad.read(sel, false),
249        }
250    }
251
252    fn set_pressed(&mut self, port: usize, pressed: u16) {
253        if let Some(Some(pad)) = self.pads.get_mut(port) {
254            pad.set_pressed(0, pressed);
255        }
256    }
257
258    fn as_any_mut(&mut self) -> &mut dyn Any {
259        self
260    }
261}