// SPDX-License-Identifier: MIT // Cites MAME 0.285 bus/a7800/rom.cpp (BSD-3-Clause, Fabio Priuli) for facts where named; // no code taken. Notice: NOTICE, section 2. //! The bank-switching schemes and the $4000 options (milestone 3), and the POKEY socket. //! //! Sources (docs/cartridge.md "Schemes"): Stolberg's bankswitching guide v1.40 //! (DOC: the wiki, tier 3) for the decoders, the A78 v4 header's vocabulary for the //! options (DOC); MAME 0.285's `bus/a7800/rom.cpp` read as a detector's statement //! where named (OBSERVED). Every cartridge sees every bus cycle (connector.rs) and //! decodes for itself; MARIA's DMA reads arrive with `halt` true and read the //! same mapping (DOC: [MT84] Figure 2's footnote, the decoder selects during HALT). //! //! - **SuperGame** (DOC: Stolberg): 16 KiB banks; a write of n to $8000-$BFFF maps //! bank n there (n masked to the dump's bank count, so 64 KiB dumps mirror: //! HYPOTHESIS, a board's latch width would settle it; bank writes OBSERVED equal //! to MAME 0.285's traces); the last bank is fixed at $C000-$FFFF. $4000-$7FFF by //! option: nothing (undriven: "some games have nothing connected in this area", //! Stolberg), 16 KiB RAM, 8 KiB RAM repeated twice, bank 6 fixed ("fixed-bank", //! EXFIX), or a further ROM bank (144 KiB dumps: the first 16 KiB, so the //! switchable banks are 1-8 and the fixed one is the last: C9), or a POKEY //! repeating every 16 bytes (DOC: Stolberg, the A78 v4 header). //! - **Activision** (78AC, DOC: Stolberg): banks of 16 KiB at $A000-$DFFF chosen by //! a write to $FF80-$FF87 (the low three address bits; Stolberg is unsure about //! higher addresses: HYPOTHESIS, U16, they are ignored here; a cartridge's logic //! chip would settle it); $4000-$5FFF the second 8 KiB of bank 6, $6000-$7FFF its //! first 8 KiB, $8000-$9FFF the second 8 KiB of bank 7, $E000-$FFFF its first //! 8 KiB (Stolberg's layout, which is No-Intro's chip order; MAME's list stores //! these dumps in another order). //! - **Absolute** (78AB, F-18 Hornet; DOC: Stolberg): the last 32 KiB fixed at //! $8000; a write of 1 or 2 to $8000 maps the first or second 16 KiB at $4000 //! (other values and addresses: HYPOTHESIS, U17, ignored; a cartridge's logic //! chip would settle it). //! - **Mirror RAM** (Rescue on Fractalus): 2 KiB at $4000-$4FFF as eight 256-byte //! blocks each appearing twice (DOC: Stolberg; the dump's own accesses agree, C24). //! //! Cartridge RAM starts at zero: HYPOTHESIS (U27: a console photograph or capture //! of Rescue on Fractalus's attract screen would settle it). //! //! Rust-forced differences (a7800-python `cartridge/schemes.py` at d6b220d): the POKEY //! sockets are a list of `(base, socket)` in the description's order (a Python dict //! keeps insertion order); a socket's chip is shared (`Rc>`) with the //! sound tap; the snapshot is a serialised struct with the same fields as the //! reference's dictionary (version, bank, RAM, each POKEY's `snapshot()`); `build` //! returns `Result` where Python raises `NotImplementedError`; the High Score //! Cartridge's `save_path` is a `PathBuf`. use std::cell::RefCell; use std::path::PathBuf; use std::rc::Rc; use pokey::{State as PokeyState, C012294, POKEY}; use serde::{Deserialize, Serialize}; use super::connector::Cartridge; use super::description::CartDescription; use crate::cartridge_any; pub const BANK: usize = 0x4000; // DOC: Stolberg (16 KiB banks) // The cartridge snapshot's layout. 2: the POKEY sockets' state (pokey-python 6ed1ffa's // snapshot()) joins it; 1 (unversioned) held only the bank and the RAM. pub const STATE_VERSION: u32 = 2; /// A socket for pokey-python's chip (the restarted core; its docs/adoption.md is /// the interface): A3-A0 as the register number (DOC: 16 registers; the decode and /// mirrors are the cartridge's, [`Banked::pokey_at`]), the bus access first and /// then one `tick()` per Φ2 period at the cartridge port, stretched TIA/RIOT /// cycles, RDY repeats and MARIA's DMA periods included (DOC: [1702B] p. 29, C22; /// during DMA, U10; docs/timing.md "Φ2 periods at the cartridge port"; the board's /// `period_end`). The chip starts as `POKEY()` leaves it (every register and /// counter 0: pokey-python's choice, the chip has no defined power-on state). /// /// Not wired: /IRQ (no licensed dump is known to connect it; the A78 v4 header's /// interrupt field names it for homebrew, and which POKEY its "pokey1" bit means is /// not settled here), the pot pins (unconnected on a 7800 cartridge: the core's /// default, never crossing) and /KR1-/KR2 (the core's default, 0). pub struct Pokey { pub chip: Rc>, } impl Pokey { pub fn new() -> Pokey { Pokey { chip: Rc::new(RefCell::new(POKEY::new((*C012294).clone(), false))), } } pub fn read(&self, register: u8) -> u8 { self.chip.borrow_mut().read(register & 0x0F) } pub fn write(&self, register: u8, value: u8) { self.chip.borrow_mut().write(register & 0x0F, value) } pub fn tick(&self) { self.chip.borrow_mut().tick() } } #[derive(Serialize, Deserialize)] struct BankedState { version: u32, bank: usize, ram: Vec, pokeys: Vec<(u16, PokeyState)>, } /// SuperGame, Activision, Absolute, linear-with-options: one class, the scheme as data. pub struct Banked { pub desc: CartDescription, pub name: String, pub rom: Vec, pub scheme: String, pub at_4000: String, pub banks: usize, pub bank: usize, pub ram: Vec, pub pokeys: Vec<(u16, Pokey)>, pub extra: usize, pub base: u32, // linear only } impl Banked { pub fn new(desc: &CartDescription) -> Banked { let rom = desc.payload.clone(); let ram_size = if ["ram16", "ram8-mirror", "mirror-ram-2k"].contains(&desc.at_4000.as_str()) { 0x4000 } else { 0 }; let extra = if desc.scheme == "supergame" && desc.at_4000 == "rom" { 1 } else { 0 }; let base = if desc.scheme == "linear" { 0x10000 - rom.len() as u32 } else { 0 }; Banked { desc: desc.clone(), name: desc.scheme.clone(), banks: std::cmp::max(1, rom.len() / BANK), rom, scheme: desc.scheme.clone(), at_4000: desc.at_4000.clone(), bank: 0, ram: vec![0; ram_size], pokeys: desc.pokey.iter().map(|&base| (base, Pokey::new())).collect(), extra, base, } } /// `_pokey`: the socket an address selects, and its register. fn pokey_at(&self, address: u16) -> Option<(usize, u8)> { // Decode: mirrored over $4000-$7FFF for the $4000 kind, 16 bytes at $440/$450/$800 // otherwise (DOC: the A78 v4 header's audio field, docs/cartridge.md) for (index, (base, _)) in self.pokeys.iter().enumerate() { let base = *base; if base == 0x4000 { if (0x4000..0x8000).contains(&address) { return Some((index, (address & 0x0F) as u8)); } } else if base <= address && address < base + 0x10 { return Some((index, (address & 0x0F) as u8)); } } None } fn linear(&self, address: u16) -> Option { if address as u32 >= self.base { return Some(self.rom[(address as u32 - self.base) as usize]); } None } } impl Cartridge for Banked { fn name(&self) -> &str { &self.name } fn access(&mut self, address: u16, data: u8, read: bool, _halt: bool, _t: u64) -> Option { if !self.pokeys.is_empty() && address < 0x8000 { if let Some((index, register)) = self.pokey_at(address) { let chip = &self.pokeys[index].1; if !read { chip.write(register, data); return None; } if !(self.scheme == "linear" && address as u32 >= self.base) { return Some(chip.read(register)); } // ROM covers $4000 (the 48K and 52K bankset formats): POKEY is write-only // (DOC: the wiki's bankset page, docs/cartridge.md) } } if address < 0x4000 { return if self.scheme == "linear" && read { self.linear(address) } else { None }; } let address_u = address as usize; if address < 0x8000 { let option = self.at_4000.as_str(); if option == "ram16" { if read { return Some(self.ram[address_u & 0x3FFF]); } self.ram[address_u & 0x3FFF] = data; return None; } if option == "ram8-mirror" { if read { return Some(self.ram[address_u & 0x1FFF]); } self.ram[address_u & 0x1FFF] = data; return None; } if option == "mirror-ram-2k" { // DOC: Stolberg (C24); above $4FFF undriven if address >= 0x5000 { return None; } let index = ((address_u - 0x4000) >> 9) << 8 | (address_u & 0xFF); if read { return Some(self.ram[index]); } self.ram[index] = data; return None; } if !read { return None; } let scheme = self.scheme.as_str(); if scheme == "supergame" { if option == "rom" { return Some(self.rom[address_u & 0x3FFF]); } if option == "fixed-bank" { // DOC: Stolberg; which dumps: from the dumps (C9) return Some(self.rom[(6 % self.banks) * BANK + (address_u & 0x3FFF)]); } return None; } if scheme == "activision" { return Some(self.rom[6 * BANK + ((address_u + 0x2000) & 0x3FFF)]); } if scheme == "absolute" { return Some(self.rom[self.bank * BANK + (address_u & 0x3FFF)]); } return self.linear(address); } // $8000-$FFFF let scheme = self.scheme.as_str(); if scheme == "supergame" { if address < 0xC000 { if !read { self.bank = data as usize % (self.banks - self.extra); return None; } return Some(self.rom[(self.bank + self.extra) * BANK + (address_u & 0x3FFF)]); } return if read { Some(self.rom[(self.banks - 1) * BANK + (address_u & 0x3FFF)]) } else { None }; } if scheme == "activision" { if !read { if (0xFF80..=0xFF87).contains(&address) { // DOC: Stolberg; $FF88 up ignored, U16 self.bank = address_u & 7; } return None; } if address < 0xA000 { return Some(self.rom[7 * BANK + 0x2000 + (address_u & 0x1FFF)]); } if address < 0xE000 { return Some(self.rom[self.bank * BANK + (address_u - 0xA000)]); } return Some(self.rom[7 * BANK + (address_u & 0x1FFF)]); } if scheme == "absolute" { if !read { if address == 0x8000 && (data == 1 || data == 2) { // DOC: Stolberg; the rest U17 self.bank = data as usize - 1; } return None; } return Some(self.rom[0x8000 + (address_u - 0x8000)]); } if read { self.linear(address) } else { None } } fn tick(&mut self, _data_bus: u8) { for (_, chip) in self.pokeys.iter() { chip.tick(); } } fn snapshot(&self) -> Vec { let state = BankedState { version: STATE_VERSION, bank: self.bank, ram: self.ram.clone(), pokeys: self .pokeys .iter() .map(|(base, socket)| (*base, socket.chip.borrow().snapshot())) .collect(), }; bincode::serialize(&state).expect("cartridge state") } fn restore(&mut self, state: &[u8]) -> Result<(), String> { let state: BankedState = bincode::deserialize(state).map_err(|e| e.to_string())?; if state.version != STATE_VERSION { return Err(format!( "cartridge state version {}, this board reads {STATE_VERSION}", state.version )); } self.bank = state.bank; self.ram.copy_from_slice(&state.ram); for (base, chip_state) in state.pokeys { let socket = self .pokeys .iter() .find(|(b, _)| *b == base) .ok_or_else(|| format!("no POKEY at {base:#x}"))?; socket.1.chip.borrow_mut().restore(&chip_state); } Ok(()) } fn pokeys(&self) -> Vec>> { self.pokeys.iter().map(|(_, socket)| socket.chip.clone()).collect() } cartridge_any!(); } /// The High Score Cartridge as a pass-through (DOC: wiki "7800 HSC technical /// reference", "HSC layout"): its 4 KiB ROM at $3000-$3FFF (bring your own, /// the 'High Score Cartridge' dump, by the table), 2 KiB of battery RAM at /// $1000-$17FF, and the game cartridge plugged into it for everything else. /// The RAM is kept in `save_path` (under `~/.local/share/a7800-python/`); a /// fresh one starts at zero (HYPOTHESIS, U27 class: a new unit's RAM state). pub struct HighScore { pub rom: Vec, pub game: Box, pub save_path: Option, pub ram: Vec, } impl HighScore { pub fn new(rom: &[u8], game: Box, save_path: Option) -> Result { if rom.len() != 0x1000 { return Err("the High Score Cartridge ROM is 4 KiB".to_string()); } let mut ram = vec![0u8; 0x800]; if let Some(path) = save_path.as_ref() { if path.exists() { let data = std::fs::read(path).map_err(|e| e.to_string())?; let n = data.len().min(0x800); ram[..n].copy_from_slice(&data[..n]); } } Ok(HighScore { rom: rom.to_vec(), game, save_path, ram, }) } pub fn save(&self) -> Result<(), String> { if let Some(path) = self.save_path.as_ref() { if let Some(parent) = path.parent() { std::fs::create_dir_all(parent).map_err(|e| e.to_string())?; } std::fs::write(path, &self.ram).map_err(|e| e.to_string())?; } Ok(()) } } impl Cartridge for HighScore { fn name(&self) -> &str { "High Score Cartridge" } fn irq(&self) -> bool { self.game.irq() } fn access(&mut self, address: u16, data: u8, read: bool, halt: bool, t: u64) -> Option { let game = self.game.access(address, data, read, halt, t); if (0x1000..0x1800).contains(&address) { if read { return Some(self.ram[address as usize - 0x1000]); } self.ram[address as usize - 0x1000] = data; return None; } if (0x3000..0x4000).contains(&address) { return if read { Some(self.rom[address as usize - 0x3000]) } else { None }; } game } fn tick(&mut self, data_bus: u8) { self.game.tick(data_bus); } fn pokeys(&self) -> Vec>> { Vec::new() // the reference's HighScore has no `pokeys` attribute } cartridge_any!(); } #[derive(Serialize, Deserialize)] struct BanksetState { sally: Vec, maria: Vec, } /// Banksets (DOC: the wiki's "Bankset Bankswitching", tier 3): two images, SALLY's /// then MARIA's, each a SuperGame or linear board; the cartridge shows MARIA's set /// while MARIA holds the bus (her DMA reads arrive with `halt` true; the wiki's /// switch, "until the second falling edge of PHI2" after HALT falls, lies inside the /// periods the board already gives MARIA). A bank-select write switches both /// sets. Bankset RAM (`ram32-halt`): SALLY's 16 KiB at $4000, MARIA's other /// 16 KiB at $4000, and SALLY's writes to $C000-$FFFF go to MARIA's RAM. A POKEY /// belongs to SALLY's side; where ROM covers $4000 it is write-only (all DOC: the /// wiki; judged against the designers' Bankset Test Suite README, DOC; which banks /// a RAM board's $8000 window reaches is open, U26). pub struct Bankset { pub desc: CartDescription, pub name: String, pub sally: Banked, pub maria: Banked, pub bank_ram: bool, } impl Bankset { pub fn new(desc: &CartDescription) -> Bankset { let half = desc.payload.len() / 2; let at = if desc.at_4000 == "ram32-halt" { "ram16".to_string() } else { desc.at_4000.clone() }; let mut sally_desc = desc.clone(); sally_desc.payload = desc.payload[..half].to_vec(); sally_desc.at_4000 = at.clone(); sally_desc.bankset = false; let mut maria_desc = desc.clone(); maria_desc.payload = desc.payload[half..].to_vec(); maria_desc.at_4000 = at; maria_desc.pokey = Vec::new(); maria_desc.bankset = false; Bankset { desc: desc.clone(), name: format!("bankset {}", desc.scheme), sally: Banked::new(&sally_desc), maria: Banked::new(&maria_desc), bank_ram: desc.at_4000 == "ram32-halt", } } } impl Cartridge for Bankset { fn name(&self) -> &str { &self.name } fn access(&mut self, address: u16, data: u8, read: bool, halt: bool, t: u64) -> Option { if read { return if halt { self.maria.access(address, data, true, halt, t) } else { self.sally.access(address, data, true, halt, t) }; } if self.bank_ram && address >= 0xC000 { self.maria.ram[address as usize & 0x3FFF] = data; return None; } if (0x8000..0xC000).contains(&address) { self.maria.access(address, data, false, halt, t); } self.sally.access(address, data, false, halt, t) } fn tick(&mut self, data_bus: u8) { self.sally.tick(data_bus); } fn snapshot(&self) -> Vec { bincode::serialize(&BanksetState { sally: self.sally.snapshot(), maria: self.maria.snapshot(), }) .expect("cartridge state") } fn restore(&mut self, state: &[u8]) -> Result<(), String> { let state: BanksetState = bincode::deserialize(state).map_err(|e| e.to_string())?; self.sally.restore(&state.sally)?; self.maria.restore(&state.maria) } fn pokeys(&self) -> Vec>> { self.sally.pokeys() // for sound.rs's mix } cartridge_any!(); } pub fn build(desc: &CartDescription) -> Result, String> { if !["linear", "supergame", "activision", "absolute"].contains(&desc.scheme.as_str()) { return Err(format!("scheme {} arrives in milestone 7", desc.scheme)); } if desc.bankset { return Ok(Box::new(Bankset::new(desc))); } Ok(Box::new(Banked::new(desc))) }