pcenginecd_rust/
syscard.rs

1//! The System Card: a HuCard holding the BIOS, and on a Super System Card 192 KiB more RAM
2//! (`syscard.py`).
3//!
4//! [hw: pcetech 8, 8.1] The Super System Card (v3.0) maps 192 KiB of RAM at banks `$68-$7F` and
5//! answers identification registers `$18C1-$18C6` (and `$18C7`) in the CD unit's register page;
6//! with the unit's own 64 KiB at `$80-$87` that is 256 KiB. The BIOS tests `$18C5 == $55 &&
7//! $18C6 == $AA` (US) or `$18C1 == $AA && $18C2 == $55` with `$18C3` as a version (Japan) and
8//! refuses to run without them ("Dragon Slayer will run for a bit like this").
9//!
10//! How a card is recognised as a Super System Card is not documented by the hardware sources:
11//! MAME makes it a separate cartridge type from its software list, Mednafen picks it by the
12//! card's identity in its own database; here a 256 KiB image is a Super System Card (the System
13//! Card v1/v2 images are 128 KiB) -- U37, tier 5. `super_system_card` overrides.
14//!
15//! The id registers' values are MAME's (`pce_scdsys_shared::register_r`: `$1`=AA, `$2`=55,
16//! `$3`=00, `$5`=AA/55, `$6`=55/AA for Japan/US, `$7`=03); Mesen2 answers `$C0-$C3` = 00 AA 55
17//! 03 instead (C16: they differ at `$18C3`, which only changes the X value the BIOS reports).
18//!
19//! Differences forced by Rust: the card holds a `RomCard` where the reference subclasses it;
20//! the unit reaches `register_read` through `BoardPins::card` (the reference's unit keeps the
21//! card it was built with).
22
23use std::any::Any;
24
25use pcengine_rust::cards::{RomCard, BANK};
26use pcengine_rust::sockets::{BoardPins, Card, DeviceState, PageHandler, ResetKind};
27
28pub const SUPER_RAM_FIRST_BANK: u32 = 0x68;
29/// $68-$7F
30pub const SUPER_RAM_BANKS: u32 = 24;
31pub const SUPER_SYSTEM_CARD_BYTES: usize = 256 * 1024;
32
33pub struct SystemCard {
34    rom: RomCard,
35    pub super_system_card: bool,
36    pub region_us: bool,
37    /// the Super System Card's RAM (`None` on a System Card v1/v2)
38    pub ram: Option<Vec<u8>>,
39}
40
41impl SystemCard {
42    /// `super_system_card`: `None` decides by the image's size (256 KiB is a Super System Card).
43    pub fn new(
44        data: &[u8],
45        super_system_card: Option<bool>,
46        region_us: bool,
47    ) -> Result<SystemCard, String> {
48        let rom = RomCard::new(data)?;
49        let super_system_card =
50            super_system_card.unwrap_or(rom.data.len() == SUPER_SYSTEM_CARD_BYTES);
51        let ram = super_system_card.then(|| vec![0; SUPER_RAM_BANKS as usize * BANK]);
52        Ok(SystemCard {
53            rom,
54            super_system_card,
55            region_us,
56            ram,
57        })
58    }
59
60    /// The BIOS image (the copier header stripped, padded to whole banks).
61    pub fn data(&self) -> &[u8] {
62        &self.rom.data
63    }
64
65    fn ram_offset(address: u32) -> Option<usize> {
66        let bank = (address >> 13) & 0xFF;
67        (SUPER_RAM_FIRST_BANK..SUPER_RAM_FIRST_BANK + SUPER_RAM_BANKS)
68            .contains(&bank)
69            .then(|| address as usize - SUPER_RAM_FIRST_BANK as usize * BANK)
70    }
71
72    /// `$18C0 + offset`, called by the CD unit (it owns the page).
73    pub fn register_read(&self, offset: u8) -> u8 {
74        if !self.super_system_card {
75            return 0xFF;
76        }
77        let us = self.region_us;
78        match offset {
79            1 => 0xAA,
80            2 => 0x55,
81            3 => 0x00,
82            5 => {
83                if us {
84                    0x55
85                } else {
86                    0xAA
87                }
88            }
89            6 => {
90                if us {
91                    0xAA
92                } else {
93                    0x55
94                }
95            }
96            7 => 0x03,
97            _ => 0x00,
98        }
99    }
100}
101
102impl DeviceState for SystemCard {
103    fn save_state(&self) -> Vec<u8> {
104        self.ram.clone().unwrap_or_default()
105    }
106
107    fn load_state(&mut self, data: &[u8]) -> Result<(), String> {
108        match self.ram.as_mut() {
109            Some(ram) if ram.len() == data.len() => ram.copy_from_slice(data),
110            None if data.is_empty() => {}
111            _ => return Err("a state of another System Card (its RAM)".to_string()),
112        }
113        Ok(())
114    }
115
116    fn state_identity(&self) -> String {
117        format!(
118            "SystemCard super {} us {} {}",
119            self.super_system_card,
120            self.region_us,
121            self.rom.state_identity()
122        )
123    }
124}
125
126impl PageHandler for SystemCard {
127    fn read(&mut self, address: u32, mclk: i64, pins: &mut BoardPins) -> u8 {
128        if let (Some(ram), Some(offset)) = (self.ram.as_ref(), Self::ram_offset(address)) {
129            return ram[offset];
130        }
131        self.rom.read(address, mclk, pins)
132    }
133
134    fn write(&mut self, address: u32, value: u8, _mclk: i64, _pins: &mut BoardPins) {
135        if let (Some(ram), Some(offset)) = (self.ram.as_mut(), Self::ram_offset(address)) {
136            ram[offset] = value;
137        }
138    }
139}
140
141impl Card for SystemCard {
142    fn grounds_cd(&self) -> bool {
143        self.rom.grounds_cd()
144    }
145
146    fn claims(&self) -> Vec<(usize, usize)> {
147        self.rom.claims()
148    }
149
150    fn reset(&mut self, kind: ResetKind, _pins: &mut BoardPins) {
151        if kind == ResetKind::PowerOn {
152            if let Some(ram) = self.ram.as_mut() {
153                ram.fill(0); // U7: power-up RAM is arbitrary; Mednafen zeroes it
154            }
155        }
156    }
157
158    fn as_any_mut(&mut self) -> &mut dyn Any {
159        self
160    }
161}