pcengine_rust/
cards.rs

1//! HuCards: the standard ROM card, Street Fighter II', Populous and Tennokoe (`cards.py`).
2//!
3//! A card is on the CPU's physical bus: PA20 is its chip enable, so it answers banks $00-$7F (the
4//! 1 MiB window = pages 0x0000-0x0FFF); there is no header (docs/cartridge.md). Mirroring of
5//! smaller images:
6//!
7//! - 384 KiB: the first 256 KiB fills banks $00-$3F twice, the last 128 KiB fills $40-$7F four
8//!   times [emu: MAME `pce_slot.cpp` rom_map_setup `0 1 0 1 2 2 2 2`; Mednafen `huc.cpp`].
9//! - 512 KiB: $00-$3F straight, $40-$7F the upper 256 KiB twice [emu: Mednafen; MAME generic].
10//! - other power-of-two sizes: mirrored to fill the window.
11//! - anything else (768 KiB, odd homebrew sizes): U18, provisional: banks repeat modulo the image.
12//!
13//! All tier 3-4; confirmed only by games running.
14//!
15//! Differences forced by Rust: the mapper cards hold a `RomCard` where the reference subclasses
16//! it; a card's identity in a save state is the SHA-1 and length of its image, computed once
17//! when it is built (the reference hashes the bytes each time it saves); `from_path` is left to
18//! the caller (`std::fs::read`).
19
20use std::any::Any;
21
22use serde::Deserialize;
23use sha1::{Digest, Sha1};
24
25use crate::sockets::{BoardPins, Card, DeviceState, PageHandler, ResetKind};
26
27pub const BANK: usize = 8 * 1024;
28pub const WINDOW_BANKS: usize = 128; // $00-$7F
29pub const COPIER_HEADER: usize = 512;
30
31/// A 512-byte copier header is the only thing to strip (size mod 8192 = 512).
32pub fn strip_copier_header(data: &[u8]) -> &[u8] {
33    if data.len() % BANK == COPIER_HEADER {
34        &data[COPIER_HEADER..]
35    } else {
36        data
37    }
38}
39
40/// For each of the 128 banks of the window, which 8 KiB bank of the image answers.
41pub fn bank_map(rom_banks: usize) -> Vec<usize> {
42    if rom_banks == 48 {
43        // 384 KiB
44        return (0..WINDOW_BANKS)
45            .map(|b| if b < 64 { b % 32 } else { 32 + (b % 16) })
46            .collect();
47    }
48    if rom_banks == 64 {
49        // 512 KiB
50        return (0..WINDOW_BANKS)
51            .map(|b| if b < 64 { b } else { 32 + (b % 32) })
52            .collect();
53    }
54    (0..WINDOW_BANKS).map(|b| b % rom_banks).collect()
55}
56
57fn rom_identity(kind: &str, data: &[u8]) -> String {
58    let digest = Sha1::digest(data);
59    let hex: String = digest.iter().map(|byte| format!("{byte:02x}")).collect();
60    format!("{kind} rom {hex} length {}", data.len())
61}
62
63fn decode<T: for<'a> Deserialize<'a>>(data: &[u8]) -> Result<T, String> {
64    bincode::deserialize(data).map_err(|error| format!("a card's state: {error}"))
65}
66
67/// The standard HuCard: ROM only, mirrored to fill the window.
68pub struct RomCard {
69    pub data: Vec<u8>,
70    map: Vec<usize>,
71    identity: String,
72}
73
74impl RomCard {
75    pub fn new(data: &[u8]) -> Result<RomCard, String> {
76        let mut data = strip_copier_header(data).to_vec();
77        if data.is_empty() {
78            return Err("an empty HuCard image; an empty slot is no card".to_string());
79        }
80        if data.len() % BANK != 0 {
81            // U18: pad a ragged image with zeros
82            data.resize(data.len() + BANK - data.len() % BANK, 0);
83        }
84        let map = bank_map(data.len() / BANK);
85        let identity = rom_identity("RomCard", &data);
86        Ok(RomCard {
87            data,
88            map,
89            identity,
90        })
91    }
92
93    #[inline]
94    fn rom_read(&self, address: u32) -> u8 {
95        let bank = ((address >> 13) & 0x7F) as usize;
96        self.data[self.map[bank] * BANK + (address & 0x1FFF) as usize]
97    }
98}
99
100impl DeviceState for RomCard {
101    fn state_identity(&self) -> String {
102        self.identity.clone()
103    }
104}
105
106impl PageHandler for RomCard {
107    fn read(&mut self, address: u32, _mclk: i64, _pins: &mut BoardPins) -> u8 {
108        self.rom_read(address)
109    }
110
111    fn write(&mut self, _address: u32, _value: u8, _mclk: i64, _pins: &mut BoardPins) {
112        // a plain ROM ignores writes
113    }
114}
115
116impl Card for RomCard {
117    fn grounds_cd(&self) -> bool {
118        true // [doc: wiki HuCard pinout] a card grounds /CD
119    }
120
121    fn claims(&self) -> Vec<(usize, usize)> {
122        vec![(0x0000, 0x0FFF)]
123    }
124
125    fn reset(&mut self, _kind: ResetKind, _pins: &mut BoardPins) {}
126
127    fn as_any_mut(&mut self) -> &mut dyn Any {
128        self
129    }
130}
131
132// --- the mappers beyond plain ROM (M5) ----------------------------------------------------------
133
134/// [emu: Mednafen huc.cpp sf2_threshold] an image this big has the mapper
135pub const SF2_THRESHOLD: usize = 2048 * 1024;
136pub const SF2_FIXED: usize = 512 * 1024;
137
138/// Street Fighter II' Champion Edition (2.5 MiB) and the larger homebrew form.
139///
140/// The first 512 KiB answer banks $00-$3F; banks $40-$7F show one of the further 512 KiB pages,
141/// chosen by a write to bank $00 at $1FF0-$1FFF (the page is the low bits of the address). MAME's
142/// `pce_sf2` decodes $1FF0-$1FF3 and four pages; Mednafen decodes $1FF0-$1FFF and masks by the
143/// page count: the same for the real card. [emu: both; no manufacturer document]
144/// (docs/cartridge.md)
145pub struct Sf2Card {
146    pub data: Vec<u8>,
147    pub page_mask: usize,
148    pub page: usize,
149    identity: String,
150}
151
152impl Sf2Card {
153    pub fn new(data: &[u8]) -> Result<Sf2Card, String> {
154        let mut data = strip_copier_header(data).to_vec();
155        if data.len() < SF2_THRESHOLD {
156            return Err("an SF2 image is at least 2 MiB".to_string());
157        }
158        // whole 512 KiB pages after the fixed part
159        let pages = (data.len() - SF2_FIXED).div_ceil(SF2_FIXED);
160        // a power of two, as Mednafen rounds the image up
161        let pages = pages.next_power_of_two();
162        data.resize(SF2_FIXED * (1 + pages), 0);
163        let identity = rom_identity("Sf2Card", &data);
164        Ok(Sf2Card {
165            data,
166            page_mask: pages - 1,
167            page: 0,
168            identity,
169        })
170    }
171}
172
173impl DeviceState for Sf2Card {
174    fn save_state(&self) -> Vec<u8> {
175        bincode::serialize(&self.page).unwrap()
176    }
177
178    fn load_state(&mut self, data: &[u8]) -> Result<(), String> {
179        self.page = decode(data)?;
180        Ok(())
181    }
182
183    fn state_identity(&self) -> String {
184        self.identity.clone()
185    }
186}
187
188impl PageHandler for Sf2Card {
189    fn read(&mut self, address: u32, _mclk: i64, _pins: &mut BoardPins) -> u8 {
190        let offset = (address & 0xFFFFF) as usize;
191        if offset < SF2_FIXED {
192            return self.data[offset];
193        }
194        self.data[offset + self.page * SF2_FIXED] // banks $40-$7F: the chosen page
195    }
196
197    fn write(&mut self, address: u32, _value: u8, _mclk: i64, _pins: &mut BoardPins) {
198        if address & 0x1FFFF0 == 0x1FF0 {
199            // bank $00, $1FF0-$1FFF
200            self.page = (address & 0xF) as usize & self.page_mask;
201        }
202    }
203}
204
205impl Card for Sf2Card {
206    fn grounds_cd(&self) -> bool {
207        true
208    }
209
210    fn claims(&self) -> Vec<(usize, usize)> {
211        vec![(0x0000, 0x0FFF)]
212    }
213
214    fn reset(&mut self, _kind: ResetKind, _pins: &mut BoardPins) {
215        self.page = 0;
216    }
217
218    fn as_any_mut(&mut self) -> &mut dyn Any {
219        self
220    }
221}
222
223/// Populous: 32 KiB of battery RAM in banks $40-$43 (four 8 KiB banks, not mirrored);
224/// the rest as a plain card. [emu: Mednafen: detected by "POPULOUS" at $1F26; MAME `pce_populous`
225/// at $80000-$87FFF.] Power-up contents are Mednafen's $FF (U7: arbitrary for a battery RAM).
226pub struct PopulousCard {
227    pub rom: RomCard,
228    pub ram: Vec<u8>,
229    identity: String,
230}
231
232impl PopulousCard {
233    pub fn new(data: &[u8]) -> Result<PopulousCard, String> {
234        let rom = RomCard::new(data)?;
235        let identity = rom_identity("PopulousCard", &rom.data);
236        Ok(PopulousCard {
237            rom,
238            ram: vec![0xFF; 0x8000],
239            identity,
240        })
241    }
242}
243
244impl DeviceState for PopulousCard {
245    fn save_state(&self) -> Vec<u8> {
246        self.ram.clone()
247    }
248
249    fn load_state(&mut self, data: &[u8]) -> Result<(), String> {
250        if data.len() != self.ram.len() {
251            return Err("a Populous card's state of another size".to_string());
252        }
253        self.ram.copy_from_slice(data);
254        Ok(())
255    }
256
257    fn state_identity(&self) -> String {
258        self.identity.clone()
259    }
260}
261
262impl PageHandler for PopulousCard {
263    fn read(&mut self, address: u32, _mclk: i64, _pins: &mut BoardPins) -> u8 {
264        if (0x40..=0x43).contains(&(address >> 13)) {
265            return self.ram[(address & 0x7FFF) as usize];
266        }
267        self.rom.rom_read(address)
268    }
269
270    fn write(&mut self, address: u32, value: u8, _mclk: i64, _pins: &mut BoardPins) {
271        if (0x40..=0x43).contains(&(address >> 13)) {
272            self.ram[(address & 0x7FFF) as usize] = value;
273        }
274    }
275}
276
277impl Card for PopulousCard {
278    fn grounds_cd(&self) -> bool {
279        true
280    }
281
282    fn claims(&self) -> Vec<(usize, usize)> {
283        vec![(0x0000, 0x0FFF)]
284    }
285
286    fn reset(&mut self, _kind: ResetKind, _pins: &mut BoardPins) {}
287
288    fn as_any_mut(&mut self) -> &mut dyn Any {
289        self
290    }
291}
292
293/// Tennokoe Bank: a 512 KiB HuCard with 8 KiB of backup RAM (four 2 KiB banks) at $80000-$81FFF
294/// of the card's space (banks $40, mirrored through the 64 KiB up to $8FFFF), locked at power-up
295/// (reads $FF, writes ignored); a write of a non-zero value anywhere in $F0000-$FFFFF unlocks it, a
296/// zero locks it. [emu: MAME `pce_tennokoe`, whose own comment calls the lock "a complete guess"
297/// (U29, tier 5); none in the library, so only unit-tested.]
298pub struct TennokoeCard {
299    pub rom: RomCard,
300    pub ram: Vec<u8>,
301    pub locked: bool,
302    identity: String,
303}
304
305impl TennokoeCard {
306    pub fn new(data: &[u8]) -> Result<TennokoeCard, String> {
307        let rom = RomCard::new(data)?;
308        let identity = rom_identity("TennokoeCard", &rom.data);
309        Ok(TennokoeCard {
310            rom,
311            ram: vec![0xFF; 0x2000],
312            locked: true,
313            identity,
314        })
315    }
316}
317
318impl DeviceState for TennokoeCard {
319    fn save_state(&self) -> Vec<u8> {
320        bincode::serialize(&(&self.ram, self.locked)).unwrap()
321    }
322
323    fn load_state(&mut self, data: &[u8]) -> Result<(), String> {
324        let (ram, locked): (Vec<u8>, bool) = decode(data)?;
325        if ram.len() != self.ram.len() {
326            return Err("a Tennokoe card's state of another size".to_string());
327        }
328        self.ram = ram;
329        self.locked = locked;
330        Ok(())
331    }
332
333    fn state_identity(&self) -> String {
334        self.identity.clone()
335    }
336}
337
338impl PageHandler for TennokoeCard {
339    fn read(&mut self, address: u32, _mclk: i64, _pins: &mut BoardPins) -> u8 {
340        let bank = (address >> 13) & 0x7F;
341        if bank < 0x40 {
342            return self.rom.rom_read(address);
343        }
344        if bank < 0x48 {
345            return if self.locked {
346                0xFF
347            } else {
348                self.ram[(address & 0x1FFF) as usize]
349            };
350        }
351        0xFF // nothing else is decoded above the ROM
352    }
353
354    fn write(&mut self, address: u32, value: u8, _mclk: i64, _pins: &mut BoardPins) {
355        let offset = address & 0xFFFFF;
356        if (0x80000..0x90000).contains(&offset) {
357            if !self.locked {
358                self.ram[(address & 0x1FFF) as usize] = value;
359            }
360        } else if offset >= 0xF0000 {
361            self.locked = value == 0;
362        }
363    }
364}
365
366impl Card for TennokoeCard {
367    fn grounds_cd(&self) -> bool {
368        true
369    }
370
371    fn claims(&self) -> Vec<(usize, usize)> {
372        vec![(0x0000, 0x0FFF)]
373    }
374
375    fn reset(&mut self, _kind: ResetKind, _pins: &mut BoardPins) {
376        self.locked = true;
377    }
378
379    fn as_any_mut(&mut self) -> &mut dyn Any {
380        self
381    }
382}
383
384/// The card an image is: SF2 from 2 MiB up (Mednafen's threshold), Populous by its title string
385/// at $1F26, else a plain ROM. Tennokoe has no detection (no header): build it explicitly.
386pub fn make_card(data: &[u8]) -> Result<Box<dyn Card>, String> {
387    let body = strip_copier_header(data);
388    if body.len() >= SF2_THRESHOLD {
389        return Ok(Box::new(Sf2Card::new(data)?));
390    }
391    if body.len() >= 0x1F26 + 8 && &body[0x1F26..0x1F26 + 8] == b"POPULOUS" {
392        return Ok(Box::new(PopulousCard::new(data)?));
393    }
394    Ok(Box::new(RomCard::new(data)?))
395}