pcengine_rust/sockets.rs
1//! The sockets: narrow traits an add-on crate implements to plug into this
2//! board (`sockets.py`; the reference's docs/sockets.md).
3//!
4//! `pcenginecd-rust` and `supergrafx-rust` depend on this crate and never copy
5//! from it, as the reference's add-ons pin the Python board. Test-only fakes
6//! for each socket live in `src/fake_devices.rs`; the base board implements
7//! only what it uses.
8//!
9//! Numbering follows docs/sockets.md.
10//!
11//! 1. `CardSlot` / `Card` the HuCard slot
12//! 2. `PortDevice` the expansion port (EXT BUS)
13//! 3. `PageHandler` one decode for every bus master (the page table is in pagetable.rs)
14//! 4. `BoardPins::hold` bus timing: wait states go through the board
15//! 5. `PortDevice::catch_up` clock domains: run up to `mclk`, callable inside an access
16//! 6. `IrqLine` interrupt levels, one bit per source, wired-OR
17//! 7. `PixelPath` per-line 9-bit pixels between the VDC(s) and the VCE
18//! 8. `VideoTiming` one record per line
19//! 9. `AudioSource` a source with a changeable rate and gain
20//! 10. `ResetKind` reset events
21//! 11. `ControllerPort` the pad port
22//! 12. Instances `Vdc`, `Vce`, `Psg` hold no module state
23//!
24//! Differences forced by Rust:
25//!
26//! - **`BoardPins` is handed to a device at every call**, not once by `bind`.
27//! The reference's devices keep the board's IRQ2 line and its `hold`
28//! callable; a Rust device cannot hold a reference into the board that owns
29//! it, so each access, `catch_up` and `reset` gets `&mut BoardPins`: the
30//! IRQ2 line, `hold`, the VDC instances (the SuperGrafx's VPC decodes their
31//! page and steers to either), the opcode of the instruction being run (the
32//! VPC steers only `ST0`-`ST2`) and, for the port device and the pixel
33//! path, the card in the slot (a CD unit answers a Super System Card's id
34//! registers from the card). The reference's add-ons reach the same things
35//! through references they were built with.
36//! - **A device that is two things in the reference is one trait object
37//! here.** The reference's `VideoPage` and `Vpc` share state by reference
38//! (one claims the VDC pages, the other is the pixel path); here `PixelPath`
39//! may also claim pages. The CD unit's CD-DA and ADPCM players, appended to
40//! `board.audio_sources` in the reference, are answered by
41//! `PortDevice::audio_sources`, mixed after the PSG and before the board's
42//! own list, which is the reference's order (PSG, CD-DA, ADPCM).
43//! - **Save states** cannot walk an object graph: every socket trait carries
44//! `DeviceState` (bytes out, bytes in, an identity for media), which the
45//! reference gets from `register_package`.
46//! - **Pad input**: the reference's host keeps the pad object and sets
47//! `pad.pressed`; here the board owns the device, so `ControllerPort` has
48//! `set_pressed(port, mask)`.
49
50use std::any::Any;
51use std::collections::BTreeSet;
52
53use serde::{Deserialize, Serialize};
54
55use crate::vdc::Vdc;
56
57// --- 10. Reset ---------------------------------------------------------------------------------
58
59/// The PC Engine has no reset button or reset instruction on the console itself; a
60/// CD unit is reset by a register write inside the add-on (docs/sockets.md). `Button` exists for
61/// the Duo/Shuttle-class consoles (unverified).
62#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
63pub enum ResetKind {
64 PowerOn,
65 Button,
66}
67
68// --- 6. Interrupts -----------------------------------------------------------------------------
69
70/// A wired-OR level with one bit per source (never a max).
71///
72/// The line is high while any source holds it; a source lowers its own bit when acknowledged.
73#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
74pub struct IrqLine {
75 pub name: String,
76 sources: BTreeSet<String>,
77}
78
79impl IrqLine {
80 pub fn new(name: &str) -> IrqLine {
81 IrqLine {
82 name: name.to_string(),
83 sources: BTreeSet::new(),
84 }
85 }
86
87 pub fn set(&mut self, source: &str, level: bool) {
88 if level {
89 if !self.sources.contains(source) {
90 self.sources.insert(source.to_string());
91 }
92 } else {
93 self.sources.remove(source);
94 }
95 }
96
97 pub fn level(&self) -> bool {
98 !self.sources.is_empty()
99 }
100
101 pub fn sources(&self) -> &BTreeSet<String> {
102 &self.sources
103 }
104}
105
106// --- 3 and 4. The decode and bus timing, seen from a device --------------------------------------
107
108/// What the board hands a card, a port device or the pixel path with every call.
109pub struct BoardPins<'a> {
110 /// The shared IRQ2 level (HuCard, expansion port, CD ADPCM): the device sets its own bit.
111 pub irq2: &'a mut IrqLine,
112 pub(crate) held: &'a mut i64,
113 /// The board's VDC instances (`machine.vdc_count` of them): the SuperGrafx's VPC claims
114 /// their pages and steers each access to one.
115 pub vdcs: &'a mut [Vdc],
116 /// The opcode of the instruction the CPU is running (`Pins::opcode`; 0 with no CPU): the
117 /// VPC steers only `ST0`-`ST2`, which the bus cannot tell from stores to `$FF:0000/2/3`.
118 pub opcode: u8,
119 /// The card in the slot, for the port device and the pixel path (`None` for the card's own
120 /// calls and for an empty slot).
121 pub card: Option<&'a mut (dyn Card + 'static)>,
122}
123
124impl BoardPins<'_> {
125 /// Stretch the current CPU cycle by this many master clocks (RDY held low), applied by the
126 /// board once the access returns.
127 pub fn hold(&mut self, clocks: i64) {
128 *self.held += clocks;
129 }
130}
131
132/// A `BoardPins` with no board behind it: for a device's own tests (this crate's and an
133/// add-on's), which call its `read`, `write` and `catch_up` directly.
134#[derive(Default)]
135pub struct DetachedPins {
136 pub irq2: IrqLine,
137 pub held: i64,
138 pub vdcs: Vec<Vdc>,
139 pub opcode: u8,
140}
141
142impl DetachedPins {
143 pub fn pins(&mut self) -> BoardPins<'_> {
144 BoardPins {
145 irq2: &mut self.irq2,
146 held: &mut self.held,
147 vdcs: &mut self.vdcs,
148 opcode: self.opcode,
149 card: None,
150 }
151 }
152}
153
154/// What a save state needs of a socket's device (the reference walks the object graph).
155pub trait DeviceState {
156 /// Everything of the device that changes as the console runs.
157 fn save_state(&self) -> Vec<u8> {
158 Vec::new()
159 }
160
161 /// Put the device in a saved state. A device without state accepts only an empty one.
162 fn load_state(&mut self, data: &[u8]) -> Result<(), String> {
163 if data.is_empty() {
164 Ok(())
165 } else {
166 Err("a state for a device that keeps none".to_string())
167 }
168 }
169
170 /// What the device is and which media it holds (a card's ROM by its SHA-1, a disc by its
171 /// table of contents): a state is refused by a system whose device answers otherwise.
172 fn state_identity(&self) -> String {
173 String::new()
174 }
175}
176
177/// Anything a range of 256-byte pages can be claimed by.
178///
179/// `address` is the 21-bit physical address after the MMU; `mclk` is the master-clock time of
180/// the access, so a device may run itself up to it inside the access (the CD unit's registers
181/// need that).
182pub trait PageHandler {
183 fn read(&mut self, address: u32, mclk: i64, pins: &mut BoardPins) -> u8;
184
185 fn write(&mut self, address: u32, value: u8, mclk: i64, pins: &mut BoardPins);
186}
187
188// --- 1. The HuCard slot --------------------------------------------------------------------------
189
190/// A HuCard: standard ROM, SF2, Populous, Tennokoe, a System Card, ...
191///
192/// A card is not confined to the ROM window (a Super System Card claims banks $68-$7F as RAM
193/// and the $18C1-$18C6 id registers), and a claim replaces the page's handler.
194pub trait Card: PageHandler + DeviceState {
195 /// The /CD line: a card grounds it so a CD unit can tell one is inserted.
196 /// [doc: wiki HuCard pinout]
197 fn grounds_cd(&self) -> bool;
198
199 /// Inclusive (first_page, last_page) ranges over the 8192 pages of 256 bytes.
200 fn claims(&self) -> Vec<(usize, usize)>;
201
202 fn reset(&mut self, kind: ResetKind, pins: &mut BoardPins);
203
204 /// For an add-on that knows which card it built (the CD unit and its System Card).
205 fn as_any_mut(&mut self) -> &mut dyn Any;
206}
207
208/// The slot. Empty is a real state: it answers $FF, does not ground /CD, and the I/O
209/// port's CD-sense bit follows the expansion port, not the slot (docs/sockets.md).
210#[derive(Default)]
211pub struct CardSlot {
212 pub card: Option<Box<dyn Card>>,
213}
214
215impl CardSlot {
216 pub fn new(card: Option<Box<dyn Card>>) -> CardSlot {
217 CardSlot { card }
218 }
219
220 pub fn grounds_cd(&self) -> bool {
221 self.card.as_ref().is_some_and(|card| card.grounds_cd())
222 }
223}
224
225// --- 2. The expansion port ---------------------------------------------------------------------
226
227/// The EXT BUS device: A0-A20, D0-D7, /RD, /WR, IRQ2, audio in, K7 (I/O port bit 7).
228///
229/// The video-bus pins (VD0-8, HSYNC, VSYNC, DCK, VCESEL) are not a socket until a device that
230/// uses them is found (U13).
231pub trait PortDevice: PageHandler + DeviceState {
232 /// K7: a device on the port pulls the I/O port's D7 low ("CD unit attached", C6 polarity).
233 fn present(&self) -> bool;
234
235 fn claims(&self) -> Vec<(usize, usize)>;
236
237 /// Socket 5: the device keeps its own rational ratio and remainder and runs up to `mclk`
238 /// when asked; the board asks at every advance (the reference's issue 0002).
239 fn catch_up(&mut self, mclk: i64, pins: &mut BoardPins);
240
241 fn reset(&mut self, kind: ResetKind, pins: &mut BoardPins);
242
243 /// Socket 9: the device's own mixer inputs (CD-DA, ADPCM), in a fixed order; mixed after
244 /// the PSG.
245 fn audio_sources(&mut self) -> Vec<&mut dyn AudioSource> {
246 Vec::new()
247 }
248
249 fn as_any_mut(&mut self) -> &mut dyn Any;
250}
251
252// --- 7 and 8. Pixels and per-line timing ---------------------------------------------------------
253
254/// One record per line, handed to anything that mixes or captures video.
255#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
256pub struct VideoTiming {
257 /// frame counter since power-on
258 pub frame: i64,
259 /// line index within the frame, 0 = first line after the vertical sync
260 pub line: i64,
261 /// master-clock time of the line's start (the VCE's hsync)
262 pub start_mclk: i64,
263 /// master clocks per dot: 4, 3 or 2 (VCE dot clock at the line's start)
264 pub dot_divider: i64,
265 /// 262 or 263
266 pub frame_lines: i64,
267 pub in_vsync: bool,
268}
269
270/// Where the VDC(s) meet the VCE. The default is VDC 1 straight into the VCE; the
271/// SuperGrafx's VPC replaces it, mixing two VDC lines. Line granularity, not dot.
272///
273/// Each row is the VDC's 9-bit pixel values for one line: bit 8 sprite/background, bits 7-4
274/// palette, bits 3-0 colour [hw: sgxtech], with palette index 0x000/0x100 for the
275/// backdrop/overscan colour. Returns the row handed to the VCE.
276///
277/// A path may also claim pages (the VPC decodes `$FF:0000-03FF`): `claims`, `read` and `write`
278/// default to none.
279pub trait PixelPath: DeviceState {
280 fn mix(&mut self, timing: &VideoTiming, rows: Vec<Vec<u16>>) -> Vec<u16>;
281
282 fn claims(&self) -> Vec<(usize, usize)> {
283 Vec::new()
284 }
285
286 fn read(&mut self, address: u32, mclk: i64, pins: &mut BoardPins) -> u8 {
287 let _ = (address, mclk, pins);
288 0xFF
289 }
290
291 fn write(&mut self, address: u32, value: u8, mclk: i64, pins: &mut BoardPins) {
292 let _ = (address, value, mclk, pins);
293 }
294
295 /// Called by `Board::reset` after the card and the port device (the reference's add-on
296 /// wrapper resets its VPC itself).
297 fn reset(&mut self, kind: ResetKind, pins: &mut BoardPins) {
298 let _ = (kind, pins);
299 }
300
301 fn as_any_mut(&mut self) -> &mut dyn Any;
302}
303
304/// VDC 1 straight into the VCE.
305#[derive(Default)]
306pub struct DirectPath;
307
308impl DeviceState for DirectPath {}
309
310impl PixelPath for DirectPath {
311 fn mix(&mut self, _timing: &VideoTiming, mut rows: Vec<Vec<u16>>) -> Vec<u16> {
312 rows.swap_remove(0)
313 }
314
315 fn as_any_mut(&mut self) -> &mut dyn Any {
316 self
317 }
318}
319
320// --- 9. Audio ----------------------------------------------------------------------------------
321
322/// A mixer input with a changeable rate and gain. The PSG is board-owned and first in the
323/// list; the CD adds CD-DA (44.1 kHz) and ADPCM (variable).
324pub trait AudioSource: DeviceState {
325 fn rate_hz(&self) -> f64;
326
327 fn gain(&self) -> f64;
328
329 /// True when the source's samples already carry its gain (the PSG): the mixer must not
330 /// apply it a second time.
331 fn applies_gain(&self) -> bool {
332 false
333 }
334
335 /// Stereo samples produced up to `mclk` since the last call.
336 fn take_samples(&mut self, mclk: i64) -> Vec<(i32, i32)>;
337}
338
339// --- 11. Controllers ---------------------------------------------------------------------------
340
341/// What plugs into the pad port: a 2-button pad, a multitap, a 6-button pad, a mouse.
342///
343/// SEL and CLR are the two lines the console drives ($1000 D0 and D1); the device answers a
344/// 4-bit nibble on D3-D0. The SuperGrafx S-EXP port shares the nibble through a mux and exposes
345/// output bits 2-7 (add-on).
346pub trait ControllerPort: DeviceState {
347 fn write(&mut self, sel: bool, clr: bool);
348
349 fn read(&mut self, sel: bool, clr: bool) -> u8;
350
351 /// The host's side: the buttons held on pad `port` (0 for a pad plugged straight in, 0-4
352 /// behind a multitap), as the bit mask of pads.rs.
353 fn set_pressed(&mut self, port: usize, pressed: u16) {
354 let _ = (port, pressed);
355 }
356
357 fn as_any_mut(&mut self) -> &mut dyn Any;
358}