//! Galaga's flight paths as readable text and back: the byte language the //! sub CPU's path interpreter runs (`docs/ram-map.md`, "The path language"; //! `docs/paths.md`). `decode` walks the paths from their known starts and //! every jump target; `listing` prints them; `assemble` turns the text back //! into bytes. `tests/paths.rs` requires the round trip to reproduce the //! ROM exactly. //! //! Operand lengths are from the interpreter's handlers (sub CPU 0x0920 jump //! table, `[disasm: gg1-5.s]`), not from comments: a segment is 3 bytes; //! `fe` and `f3` carry an inline 8-entry duration table (9 bytes); `fd`, //! `fa`, `f7`, `f2`, `f0` and `ef` a 16-bit address (3 bytes); `fc` and `f6` //! one byte (2); the rest none. //! //! No ROM bytes live in this file: the path starts are addresses, and //! listings are generated from the player's own set. use std::collections::{BTreeMap, BTreeSet}; /// Where paths start in the sub CPU ROM: the labelled path streams of the /// community disassembly (`db_flv_*` and kin in gg1-5.s), addresses only; /// the last two sit at the end of the ROM, reached from the main CPU's /// entrance table at 0x2a3c. pub const ROOTS: [u16; 36] = [ 0x001d, 0x0067, 0x009f, 0x00d4, 0x00f1, 0x017b, 0x01b0, 0x01e8, 0x01f5, 0x020b, 0x021b, 0x022b, 0x0241, 0x025d, 0x0279, 0x029e, 0x02ba, 0x02d9, 0x02fb, 0x031d, 0x0333, 0x034f, 0x03a9, 0x0411, 0x0444, 0x0454, 0x046b, 0x0473, 0x04ab, 0x04c6, 0x04cf, 0x04d8, 0x04ea, 0x0502, 0x0fda, 0x0ff0, ]; #[derive(Clone, Debug, PartialEq, Eq)] pub enum Op { /// A segment: speed on odd and even frames (0-15 each), signed turn rate /// added to the heading each step, and its length in steps. Fly { odd: u8, even: u8, turn: i8, frames: u8, }, /// `ff`: the object leaves play; the queue entry is freed. End, /// `fe`: the segment length is picked from the table by the fighter's X. TimeByFighterX([u8; 8]), /// `fd` Jump(u16), /// `fc`: keep flying until Y reaches this value. UntilY(u8), /// `fb`: head for the home cell (state 9, homing). Home, /// `fa`: jump unless continuous bombing is on. JumpUnlessBombing(u16), /// `f9`: X = the home column. Pauses a frame. XToHomeColumn, /// `f8`: Y = 0x9c, back in from the top. Pauses a frame. ReenterTop, /// `f7`: jump if the object is a transient (slots 0x1c-0x1f). JumpIfTransient(u16), /// `f6`: heading = n x 4; reloads the bomb timers. Pauses a frame. Heading(u8), /// `f5`: object state 3. State3, /// `f4`: the capture boss aims its beam at the fighter. AimBeam, /// `f3`: the segment length is picked by the X distance to the fighter. TimeByFighterDistance([u8; 8]), /// `f2`: split off a bonus-bee clone flying from the address. SplitClone(u16), /// `f1`: Y = home row origin + 0x20. Pauses a frame. YToHomeRow, /// `f0`: jump if stage parameter 0x99c8 is non-zero. JumpIfStageA(u16), /// `ef`: jump if stage parameter 0x99c9 is non-zero. JumpIfStageB(u16), /// `ee` (remix extension, `extend random_jump`): jump half the time. RandomJump(u16), } impl Op { pub fn size(&self) -> usize { match self { Op::Fly { .. } => 3, Op::TimeByFighterX(_) | Op::TimeByFighterDistance(_) => 9, Op::Jump(_) | Op::JumpUnlessBombing(_) | Op::JumpIfTransient(_) | Op::SplitClone(_) | Op::JumpIfStageA(_) | Op::JumpIfStageB(_) | Op::RandomJump(_) => 3, Op::UntilY(_) | Op::Heading(_) => 2, _ => 1, } } /// Where control can go besides the next op. pub fn target(&self) -> Option { match *self { Op::Jump(a) | Op::JumpUnlessBombing(a) | Op::JumpIfTransient(a) | Op::SplitClone(a) | Op::JumpIfStageA(a) | Op::JumpIfStageB(a) | Op::RandomJump(a) => Some(a), _ => None, } } /// Whether the op after this one is never reached from it. pub fn stops(&self) -> bool { matches!(self, Op::End | Op::Jump(_)) } /// Decode one op from `bytes` (starting at its first byte); `extended` /// when the remix's interpreter extension is in (token 0xee). pub fn decode(bytes: &[u8], extended: bool) -> Result { let b = |i: usize| { bytes .get(i) .copied() .ok_or_else(|| "path runs off the end".to_string()) }; let addr = || -> Result { Ok(u16::from(b(1)?) | u16::from(b(2)?) << 8) }; let table = || -> Result<[u8; 8], String> { let mut t = [0; 8]; for (i, v) in t.iter_mut().enumerate() { *v = b(1 + i)?; } Ok(t) }; let token = b(0)?; Ok(match token { 0xee if extended => Op::RandomJump(addr()?), 0x00..=0xee => Op::Fly { odd: token & 0x0f, even: token >> 4, turn: b(1)? as i8, frames: b(2)?, }, 0xff => Op::End, 0xfe => Op::TimeByFighterX(table()?), 0xfd => Op::Jump(addr()?), 0xfc => Op::UntilY(b(1)?), 0xfb => Op::Home, 0xfa => Op::JumpUnlessBombing(addr()?), 0xf9 => Op::XToHomeColumn, 0xf8 => Op::ReenterTop, 0xf7 => Op::JumpIfTransient(addr()?), 0xf6 => Op::Heading(b(1)?), 0xf5 => Op::State3, 0xf4 => Op::AimBeam, 0xf3 => Op::TimeByFighterDistance(table()?), 0xf2 => Op::SplitClone(addr()?), 0xf1 => Op::YToHomeRow, 0xf0 => Op::JumpIfStageA(addr()?), 0xef => Op::JumpIfStageB(addr()?), }) } pub fn encode(&self, out: &mut Vec) { let addr = |out: &mut Vec, token: u8, a: u16| { out.extend_from_slice(&[token, a as u8, (a >> 8) as u8]); }; match *self { Op::Fly { odd, even, turn, frames, } => out.extend_from_slice(&[(even << 4) | (odd & 0x0f), turn as u8, frames]), Op::End => out.push(0xff), Op::TimeByFighterX(t) => { out.push(0xfe); out.extend_from_slice(&t); } Op::Jump(a) => addr(out, 0xfd, a), Op::UntilY(y) => out.extend_from_slice(&[0xfc, y]), Op::Home => out.push(0xfb), Op::JumpUnlessBombing(a) => addr(out, 0xfa, a), Op::XToHomeColumn => out.push(0xf9), Op::ReenterTop => out.push(0xf8), Op::JumpIfTransient(a) => addr(out, 0xf7, a), Op::Heading(n) => out.extend_from_slice(&[0xf6, n]), Op::State3 => out.push(0xf5), Op::AimBeam => out.push(0xf4), Op::TimeByFighterDistance(t) => { out.push(0xf3); out.extend_from_slice(&t); } Op::SplitClone(a) => addr(out, 0xf2, a), Op::YToHomeRow => out.push(0xf1), Op::JumpIfStageA(a) => addr(out, 0xf0, a), Op::JumpIfStageB(a) => addr(out, 0xef, a), Op::RandomJump(a) => addr(out, 0xee, a), } } fn text(&self, label: &dyn Fn(u16) -> String) -> String { let table = |t: &[u8; 8]| { t.iter() .map(|v| format!("{v}")) .collect::>() .join(" ") }; match self { Op::Fly { odd, even, turn, frames, } => format!("fly {odd} {even} turn {turn} for {frames}"), Op::End => "end".into(), Op::TimeByFighterX(t) => format!("time_by_fighter_x {}", table(t)), Op::Jump(a) => format!("jump {}", label(*a)), Op::UntilY(y) => format!("until_y 0x{y:02x}"), Op::Home => "home".into(), Op::JumpUnlessBombing(a) => format!("jump_unless_bombing {}", label(*a)), Op::XToHomeColumn => "x_to_home_column".into(), Op::ReenterTop => "reenter_top".into(), Op::JumpIfTransient(a) => format!("jump_if_transient {}", label(*a)), Op::Heading(n) => format!("heading 0x{n:02x}"), Op::State3 => "state3".into(), Op::AimBeam => "aim_beam".into(), Op::TimeByFighterDistance(t) => format!("time_by_fighter_distance {}", table(t)), Op::SplitClone(a) => format!("split_clone {}", label(*a)), Op::YToHomeRow => "y_to_home_row".into(), Op::JumpIfStageA(a) => format!("jump_if_stage_a {}", label(*a)), Op::JumpIfStageB(a) => format!("jump_if_stage_b {}", label(*a)), Op::RandomJump(a) => format!("random_jump {}", label(*a)), } } } /// Every op reachable from `roots`, by address, and which addresses are /// jump targets or roots (the labels). #[derive(Debug)] pub struct Program { pub ops: BTreeMap, pub labels: BTreeSet, } /// Decode everything reachable from `roots` in `rom` (the sub CPU's view: /// its 4 KB ROM, addresses from 0). Fails if two ops overlap, which would /// mean an operand length is wrong. pub fn decode(rom: &[u8], roots: &[u16]) -> Result { decode_with(rom, roots, false) } /// `decode`, with the interpreter extension's tokens when `extended`. pub fn decode_with(rom: &[u8], roots: &[u16], extended: bool) -> Result { let mut ops = BTreeMap::new(); let mut labels: BTreeSet = roots.iter().copied().collect(); let mut work: Vec = roots.to_vec(); while let Some(start) = work.pop() { let mut pc = start; loop { if ops.contains_key(&pc) { break; } let op = Op::decode(rom.get(usize::from(pc)..).unwrap_or(&[]), extended) .map_err(|e| format!("0x{pc:04x}: {e}"))?; if let Some(t) = op.target() { if labels.insert(t) { work.push(t); } } let len = op.size() as u16; let stops = op.stops(); ops.insert(pc, op); pc += len; if stops { break; } } } // No op may start inside another. let mut end = 0u16; for (&at, op) in &ops { if at < end { return Err(format!("op at 0x{at:04x} starts inside the op before it")); } end = at + op.size() as u16; } Ok(Program { ops, labels }) } pub fn label(a: u16) -> String { format!("p{a:04x}") } /// The program as text: runs of ops, each run headed by its address, a /// label line for every root or jump target. pub fn listing(program: &Program) -> String { let mut out = String::new(); let mut next: Option = None; for (&at, op) in &program.ops { if next != Some(at) { out.push_str(&format!("\norg 0x{at:04x}\n")); } if program.labels.contains(&at) { out.push_str(&format!("{}:\n", label(at))); } out.push_str(&format!(" {}\n", op.text(&label))); next = Some(at + op.size() as u16); } out } /// Text back to bytes: `org ADDR` starts a run, `NAME:` defines a label, /// one op per line, `;` starts a comment. Returns (address, bytes) runs. /// Labels may be used before they are defined; `pXXXX` names an address /// directly when no label of that name exists. pub fn assemble(text: &str) -> Result)>, String> { assemble_with_labels(text).map(|(runs, _)| runs) } /// `assemble`, also returning the labels' addresses. #[allow(clippy::type_complexity)] pub fn assemble_with_labels( text: &str, ) -> Result<(Vec<(u16, Vec)>, BTreeMap), String> { // Pass 1: addresses of labels. let mut labels: BTreeMap = BTreeMap::new(); let mut lines: Vec<(usize, String)> = Vec::new(); for (n, raw) in text.lines().enumerate() { let line = raw.split(';').next().unwrap().trim(); if !line.is_empty() && !line.starts_with("extend ") && !line.starts_with("entrance ") && !line.starts_with("title_") && !line.starts_with("sprite ") && !line.starts_with("tile ") { lines.push((n + 1, line.to_string())); } } let mut pc: Option = None; for (n, line) in &lines { if let Some(rest) = line.strip_prefix("org ") { pc = Some(number(rest).map_err(|e| format!("line {n}: {e}"))?); } else if let Some(name) = line.strip_suffix(':') { let at = pc.ok_or(format!("line {n}: label before any org"))?; if labels.insert(name.to_string(), at).is_some() { return Err(format!("line {n}: label {name} defined twice")); } } else { let op = parse(line, &|_| Ok(0)).map_err(|e| format!("line {n}: {e}"))?; let at = pc.ok_or(format!("line {n}: op before any org"))?; pc = Some(at + op.size() as u16); } } // Pass 2: bytes. let resolve = |name: &str| -> Result { if let Some(&a) = labels.get(name) { return Ok(a); } if let Some(hex) = name.strip_prefix('p') { if let Ok(a) = u16::from_str_radix(hex, 16) { return Ok(a); } } number(name).map_err(|_| format!("unknown label {name}")) }; let mut runs: Vec<(u16, Vec)> = Vec::new(); for (n, line) in &lines { if let Some(rest) = line.strip_prefix("org ") { runs.push((number(rest).unwrap(), Vec::new())); } else if !line.ends_with(':') { let op = parse(line, &resolve).map_err(|e| format!("line {n}: {e}"))?; op.encode(&mut runs.last_mut().unwrap().1); } } Ok((runs, labels)) } fn number(s: &str) -> Result { let s = s.trim(); let v = if let Some(hex) = s.strip_prefix("0x") { u16::from_str_radix(hex, 16) } else { s.parse() }; v.map_err(|_| format!("not a number: {s}")) } fn parse(line: &str, resolve: &dyn Fn(&str) -> Result) -> Result { let words: Vec<&str> = line.split_whitespace().collect(); let arg = |i: usize| { words .get(i) .copied() .ok_or(format!("{line}: missing operand")) }; let byte = |i: usize| -> Result { let v = number(arg(i)?)?; u8::try_from(v).map_err(|_| format!("{line}: {v} does not fit a byte")) }; let table = || -> Result<[u8; 8], String> { let mut t = [0; 8]; for (i, v) in t.iter_mut().enumerate() { *v = byte(1 + i)?; } Ok(t) }; let target = || resolve(arg(1)?); Ok(match words[0] { "fly" => { // fly ODD EVEN turn T for N if words.len() != 7 || words[3] != "turn" || words[5] != "for" { return Err(format!("{line}: want `fly ODD EVEN turn T for N`")); } let odd = byte(1)?; let even = byte(2)?; if odd > 15 || even > 15 { return Err(format!("{line}: speeds are 0-15")); } let turn: i8 = arg(4)? .parse() .map_err(|_| format!("{line}: turn is -128..127"))?; let op = Op::Fly { odd, even, turn, frames: byte(6)?, }; let mut probe = Vec::new(); op.encode(&mut probe); if probe[0] >= 0xef { return Err(format!( "{line}: speeds {odd} {even} encode as a command byte" )); } op } "end" => Op::End, "time_by_fighter_x" => Op::TimeByFighterX(table()?), "jump" => Op::Jump(target()?), "until_y" => Op::UntilY(byte(1)?), "home" => Op::Home, "jump_unless_bombing" => Op::JumpUnlessBombing(target()?), "x_to_home_column" => Op::XToHomeColumn, "reenter_top" => Op::ReenterTop, "jump_if_transient" => Op::JumpIfTransient(target()?), "heading" => Op::Heading(byte(1)?), "state3" => Op::State3, "aim_beam" => Op::AimBeam, "time_by_fighter_distance" => Op::TimeByFighterDistance(table()?), "split_clone" => Op::SplitClone(target()?), "y_to_home_row" => Op::YToHomeRow, "jump_if_stage_a" => Op::JumpIfStageA(target()?), "jump_if_stage_b" => Op::JumpIfStageB(target()?), "random_jump" => Op::RandomJump(target()?), other => return Err(format!("unknown op {other}")), }) } /// Where new path code may go: the sub CPU's unconnected space. pub const FREE_SPACE: std::ops::Range = 0x1000..0x4000; /// The sub CPU's power-on self-test sums its ROM, 0x0000-0x0fff, and stops /// the game ("ROM 11") unless the 8-bit sum is 0xff (the loop at sub 0x0588, /// `[disasm: gg1-5.s]`; measured: a mod that ignored it stopped there). A mod /// that changes bytes in the ROM therefore sets this byte to bring the sum /// back: the last of the 8 filler bytes at 0x00f8-0x00ff, which follow the /// path at 0x00f1 (whose `end` is 0x00f7) and precede the formation table at /// 0x0100; no path or code reads them (`[disasm]`: "probably fill"). pub const CHECKSUM_FILL: u16 = 0x00ff; const FILLER: std::ops::RangeInclusive = 0x00f8..=0x00ff; /// The remix's interpreter extension (`extend random_jump` in a mod). /// /// The path interpreter (sub 0x090e) treats tokens below 0xef as segments /// and dispatches 0xef-0xff through a 17-entry table at 0x0920 indexed by /// the complemented token. No token is free, so the extension changes two /// operands of that dispatch: `cp 0xef` (0x090f) becomes `cp 0xee`, making /// 0xee a command, and `ld hl,0x0920` (0x0916) points at a copy of the table, /// made from the player's ROM at load time, with an 18th entry for 0xee. No /// original path uses 0xee as a segment token (`PathMod::check`). pub mod extension { /// The dispatch as the ROM has it: `ld a,(hl)` / `cp 0xef` / `jp c,0x0bdc` /// / `push hl` / `cpl` / `ld hl,0x0920` (instruction encodings, restated /// from the disassembly's text), checked before patching. pub const DISPATCH_AT: u16 = 0x090e; pub const DISPATCH: [u8; 11] = [ 0x7e, 0xfe, 0xef, 0xda, 0xdc, 0x0b, 0xe5, 0x2f, 0x21, 0x20, 0x09, ]; pub const TABLE: u16 = 0x0920; pub const TABLE_ENTRIES: usize = 17; /// Where the extension lives in the free space; mods keep out of it. pub const AREA: std::ops::Range = 0x3f00..0x4000; pub const HANDLER: u16 = 0x3f00; pub const NEW_TABLE: u16 = 0x3f80; /// `random_jump`, entered like the other handlers (HL = the token, IX = /// the queue entry, B and C free). Mixes the refresh register, the /// object's X (queue +0x02), the frame counter (0x92a0) and the fighter's /// X (0x9362), then takes the bit selected by the op's address (so /// consecutive random jumps look at different bits): set = jump through /// the ROM's own jump handler (0x0b46, as `fd` does), clear = skip the /// op's 3 bytes and read the next token (0x090e), as `f7` does. /// Deterministic, so movies replay. pub const HANDLER_CODE: [u8; 36] = [ 0xed, 0x5f, // ld a,r 0xdd, 0xae, 0x02, // xor (ix+0x02) 0x4f, // ld c,a 0x3a, 0xa0, 0x92, // ld a,(0x92a0) 0xa9, // xor c 0x4f, // ld c,a 0x3a, 0x62, 0x93, // ld a,(0x9362) 0xa9, // xor c 0x4f, // ld c,a 0x7d, // ld a,l 0xe6, 0x07, // and 0x07 0x47, // ld b,a 0x04, // inc b 0xcb, 0x09, // rrc c (loop) 0x10, 0xfc, // djnz loop 0xcb, 0x41, // bit 0,c 0xc2, 0x46, 0x0b, // jp nz,0x0b46 0x23, 0x23, 0x23, // inc hl x3 0xc3, 0x0e, 0x09, // jp 0x090e ]; /// The extension's runs over this sub ROM. pub fn runs(sub_rom: &[u8]) -> Result)>, String> { let at = usize::from(DISPATCH_AT); if sub_rom[at..at + DISPATCH.len()] != DISPATCH { return Err( "the path interpreter's dispatch is not where the extension expects it".into(), ); } let mut table = sub_rom[usize::from(TABLE)..usize::from(TABLE) + 2 * TABLE_ENTRIES].to_vec(); table.extend_from_slice(&HANDLER.to_le_bytes()); Ok(vec![ (DISPATCH_AT + 2, vec![0xee]), (DISPATCH_AT + 9, NEW_TABLE.to_le_bytes().to_vec()), (HANDLER, HANDLER_CODE.to_vec()), (NEW_TABLE, table), ]) } } /// A path mod: text in the path language (`assemble`) laid over the sub /// CPU's program space. Runs inside the original ROM must replace whole ops /// (typically a path's first op with a `jump` to new code in `FREE_SPACE`). /// A line `extend random_jump` adds the interpreter extension. #[derive(Clone, Debug)] pub struct PathMod { pub name: String, pub text: String, pub runs: Vec<(u16, Vec)>, pub extended: bool, /// `entrance N LABEL`: entrance-table entry N (0-23) flies LABEL. pub entrances: Vec<(usize, u16)>, /// `title_text ROW COLOUR TEXT`, `title_shift SCORE TABLE` and /// `title_run ROW COL COUNT CODE COLOUR` lines: a new title screen /// (`galaga::title`). pub title: Option, /// `sprite CODE HEX`: sprite CODE (hex) replaced by 64 bytes in the /// sprite ROM's layout (a replacement sprite EPROM; `Video::set_sprite`). pub sprites: Vec<(u8, Vec)>, /// `tile CODE HEX`: tile CODE (hex) replaced by 16 bytes in the tile /// ROM's layout (a replacement tile EPROM; `Video::set_tile`). pub tiles: Vec<(u8, Vec)>, } /// The main CPU's entrance table (`[disasm: gg1-3.s]` db_2A3C; measured: the /// stages use it in families, see docs/paths.md): 24 words, bits 0-12 the /// path's address in the sub CPU (so new entrance paths must lie below /// 0x2000), bits 13-15 a start position and heading. pub mod entrance { pub const TABLE: u16 = 0x2a3c; pub const ENTRIES: usize = 24; /// The main CPU's power-on test sums each 4 KB ROM section and expects 0 /// (`c_rom_test_csum_calc`, main 0x3520 area, `[disasm: gg1-4.s]`; /// measured: all four sections sum to 0). A mod that changes the table /// sets this byte, the last of the 275 bytes of 0xff padding at /// 0x2aed-0x2bff that follow the code in the table's section /// (`[disasm: gg1-3.s]` ".ds 0x0113 ; pad"), to bring its sum back. pub const CHECKSUM_FILL: u16 = 0x2bff; pub const PAD: std::ops::RangeInclusive = 0x2aed..=0x2bff; pub const SECTION: std::ops::Range = 0x2000..0x3000; pub fn word(main_rom: &[u8], n: usize) -> u16 { let at = usize::from(TABLE) + 2 * n; u16::from(main_rom[at]) | u16::from(main_rom[at + 1]) << 8 } } impl PathMod { pub fn parse(name: &str, text: &str) -> Result { let mut extended = false; for line in text.lines() { let line = line.split(';').next().unwrap().trim(); if let Some(what) = line.strip_prefix("extend ") { match what.trim() { "random_jump" => extended = true, other => return Err(format!("{name}: unknown extension {other}")), } } } let (runs, labels) = assemble_with_labels(text).map_err(|e| format!("{name}: {e}"))?; let mut entrances = Vec::new(); for (n, line) in text.lines().enumerate() { let line = line.split(';').next().unwrap().trim(); if let Some(rest) = line.strip_prefix("entrance ") { let words: Vec<&str> = rest.split_whitespace().collect(); let [entry, target] = words[..] else { return Err(format!("{name}: line {}: want `entrance N LABEL`", n + 1)); }; let entry: usize = entry .parse() .ok() .filter(|&e| e < entrance::ENTRIES) .ok_or(format!("{name}: line {}: entries are 0-23", n + 1))?; let at = *labels .get(target) .ok_or(format!("{name}: line {}: unknown label {target}", n + 1))?; if at >= 0x2000 { return Err(format!( "{name}: line {}: {target} is at 0x{at:04x}; entrance paths must lie below 0x2000", n + 1 )); } entrances.push((entry, at)); } } let mut title: Option = None; let mut sprites = Vec::new(); let mut tiles = Vec::new(); for (n, line) in text.lines().enumerate() { let line = line.split(';').next().unwrap().trim(); let bad = |what: &str| format!("{name}: line {}: {what}", n + 1); if let Some(rest) = line.strip_prefix("title_text ") { let mut it = rest.splitn(3, ' '); let row: u8 = it .next() .and_then(|v| v.parse().ok()) .ok_or(bad("title_text ROW COLOUR TEXT"))?; let colour: u8 = it .next() .and_then(|v| v.parse().ok()) .ok_or(bad("title_text ROW COLOUR TEXT"))?; let words = it .next() .ok_or(bad("title_text ROW COLOUR TEXT"))? .trim() .trim_matches('"') .to_string(); let t = title.get_or_insert_with(Default::default); t.text = Some((words, colour)); t.text_row = row; } else if let Some(rest) = line.strip_prefix("title_shift ") { let v: Vec = rest .split_whitespace() .filter_map(|x| x.parse().ok()) .collect(); let [score, table] = v[..] else { return Err(bad("title_shift SCORE TABLE")); }; let t = title.get_or_insert_with(Default::default); t.score_shift = score; t.table_shift = table; } else if let Some(rest) = line.strip_prefix("sprite ") { let mut it = rest.split_whitespace(); let code = it .next() .and_then(|v| u8::from_str_radix(v.trim_start_matches("0x"), 16).ok()) .filter(|&c| c < 0x80) .ok_or(bad("sprite CODE HEX: CODE is 00-7f"))?; let hex = it.next().ok_or(bad("sprite CODE HEX"))?; if hex.len() != 128 { return Err(bad("sprite CODE HEX: 64 bytes of hex")); } let bytes = (0..64) .map(|i| u8::from_str_radix(&hex[2 * i..2 * i + 2], 16)) .collect::, _>>() .map_err(|_| bad("sprite CODE HEX: not hex"))?; sprites.push((code, bytes)); } else if let Some(rest) = line.strip_prefix("tile ") { let mut it = rest.split_whitespace(); let code = it .next() .and_then(|v| u8::from_str_radix(v.trim_start_matches("0x"), 16).ok()) .ok_or(bad("tile CODE HEX: CODE is 00-ff"))?; let hex = it.next().ok_or(bad("tile CODE HEX"))?; if hex.len() != 32 { return Err(bad("tile CODE HEX: 16 bytes of hex")); } let bytes = (0..16) .map(|i| u8::from_str_radix(&hex[2 * i..2 * i + 2], 16)) .collect::, _>>() .map_err(|_| bad("tile CODE HEX: not hex"))?; tiles.push((code, bytes)); } else if let Some(rest) = line.strip_prefix("title_run ") { let v: Vec = rest .split_whitespace() .filter_map(|x| x.parse().ok()) .collect(); let [row, col, count, code, colour] = v[..] else { return Err(bad("title_run ROW COL COUNT CODE COLOUR")); }; if !(2..=33).contains(&row) || col as usize + count as usize > 28 || count == 0 { return Err(bad("title_run off the screen")); } title .get_or_insert_with(Default::default) .runs .push(super::title::Run { row, col, count, code, colour, }); } } Ok(PathMod { name: name.to_string(), text: text.to_string(), runs, extended, entrances, title, sprites, tiles, }) } pub fn load(path: &std::path::Path) -> Result { let text = std::fs::read_to_string(path).map_err(|e| format!("{}: {e}", path.display()))?; let name = path.file_stem().unwrap().to_string_lossy().to_string(); PathMod::parse(&name, &text) } /// Everything laid over this `sub_rom`: the mod's runs, the extension's /// if it asks for it, and, if they change the ROM's sum, the byte at /// `CHECKSUM_FILL` that restores it. pub fn runs_for(&self, sub_rom: &[u8]) -> Result)>, String> { let mut runs = self.runs.clone(); if self.extended { runs.extend(extension::runs(sub_rom)?); } let mut rom = sub_rom[..0x1000].to_vec(); for (at, bytes) in &runs { let at = usize::from(*at); if at < rom.len() { rom[at..at + bytes.len()].copy_from_slice(bytes); } } let sum = rom.iter().fold(0u8, |a, &b| a.wrapping_add(b)); if sum != 0xff { let fill = rom[usize::from(CHECKSUM_FILL)].wrapping_add(0xff_u8.wrapping_sub(sum)); runs.push((CHECKSUM_FILL, vec![fill])); } Ok(runs) } /// The sub CPU's program space (16 KB) with the mod laid over `sub_rom`. pub fn patched(&self, sub_rom: &[u8]) -> Result, String> { let mut image = vec![0u8; 0x4000]; image[..sub_rom.len()].copy_from_slice(sub_rom); for (at, bytes) in self.runs_for(sub_rom)? { let at = usize::from(at); image[at..at + bytes.len()].copy_from_slice(&bytes); } Ok(image) } /// Check the mod against the original ROM and return the modded /// program: runs in the original ROM cover whole ops, runs elsewhere lie /// in `FREE_SPACE` (outside the extension's area), and everything /// reachable from the original starts and the runs' starts decodes /// without overlap. pub fn check(&self, sub_rom: &[u8]) -> Result { let original = decode(sub_rom, &ROOTS)?; if FILLER.clone().any(|a| sub_rom[usize::from(a)] != 0xff) { return Err("this sub ROM has no 0xff filler at 0x00f8-0x00ff".into()); } if self.extended { if let Some((at, _)) = original.ops.iter().find(|(_, op)| { matches!( op, Op::Fly { odd: 14, even: 14, .. } ) }) { return Err(format!( "{}: the original path at 0x{at:04x} uses token 0xee, which the extension takes", self.name )); } } let mut roots: Vec = ROOTS.to_vec(); for (at, bytes) in &self.runs { let end = *at as usize + bytes.len(); if usize::from(*at) < sub_rom.len() { if !original.ops.contains_key(at) { return Err(format!( "{}: run at 0x{at:04x} does not start on an op", self.name )); } let ends_on_op = original.ops.contains_key(&(end as u16)) || original .ops .iter() .any(|(&a, op)| usize::from(a) + op.size() == end); if !ends_on_op { return Err(format!( "{}: run at 0x{at:04x} ends inside an op (0x{end:04x})", self.name )); } } else if !FREE_SPACE.contains(at) || end > usize::from(FREE_SPACE.end) { return Err(format!( "{}: run at 0x{at:04x} is outside the ROM and the free space", self.name )); } else if end > usize::from(extension::AREA.start) { return Err(format!( "{}: run at 0x{at:04x} reaches the extension's area at 0x{:04x}", self.name, extension::AREA.start )); } if FILLER.contains(at) || (*at < 0x00f8 && end > 0x00f8) { return Err(format!( "{}: run at 0x{at:04x} touches the checksum filler", self.name )); } roots.push(*at); } roots.extend(self.entrances.iter().map(|&(_, at)| at)); let program = decode_with(&self.patched(sub_rom)?, &roots, self.extended) .map_err(|e| format!("{}: {e}", self.name))?; if !self.extended { if let Some((at, _)) = program .ops .iter() .find(|(_, op)| matches!(op, Op::RandomJump(_))) { return Err(format!( "{}: random_jump at 0x{at:04x} needs `extend random_jump`", self.name )); } } if let Some(a) = FILLER.clone().find(|a| program.ops.contains_key(a)) { return Err(format!( "{}: a path reaches the filler at 0x{a:04x}", self.name )); } Ok(program) } /// The mod's changes to the main CPU's program (its entrance-table /// entries, keeping each entry's start bits, and the section's checksum /// byte), over this 16 KB `main_rom`. pub fn main_runs_for(&self, main_rom: &[u8]) -> Result)>, String> { let mut title_runs = match &self.title { Some(spec) => { super::title::runs(main_rom, spec).map_err(|e| format!("{}: {e}", self.name))? } None => Vec::new(), }; if self.entrances.is_empty() { return Ok(title_runs); } if entrance::PAD .clone() .any(|a| main_rom[usize::from(a)] != 0xff) { return Err("this main ROM has no 0xff padding at 0x2aed-0x2bff".into()); } let mut section = main_rom [usize::from(entrance::SECTION.start)..usize::from(entrance::SECTION.end)] .to_vec(); let mut runs = Vec::new(); for &(n, at) in &self.entrances { let word = (entrance::word(main_rom, n) & 0xe000) | at; let addr = entrance::TABLE + 2 * n as u16; let o = usize::from(addr - entrance::SECTION.start); section[o..o + 2].copy_from_slice(&word.to_le_bytes()); runs.push((addr, word.to_le_bytes().to_vec())); } let sum = section.iter().fold(0u8, |a, &b| a.wrapping_add(b)); if sum != 0 { let o = usize::from(entrance::CHECKSUM_FILL - entrance::SECTION.start); runs.push((entrance::CHECKSUM_FILL, vec![section[o].wrapping_sub(sum)])); } runs.append(&mut title_runs); Ok(runs) } /// Lay the mod's sprites and tiles over a video pipeline (the picture /// side: the board's CPUs never read the sprite or tile ROMs). pub fn apply_video(&self, video: &mut super::video::Video) { for (code, bytes) in &self.sprites { video.set_sprite(usize::from(*code), bytes); } for (code, bytes) in &self.tiles { video.set_tile(usize::from(*code), bytes); } } /// Lay the mod (extension, entrances and checksum bytes included) over a /// board's sub and main CPUs. /// Lay the mod over a board that may already carry another mod (a /// movie's): the bytes are worked out from the unmodified ROMs, so the /// shared parts (title, extension) come out the same and the paths /// overwrite the other mod's. For scoring a design mid-game; the /// power-on checksums are long past. pub fn apply_over( &self, machine: &mut super::Machine, roms: &super::roms::RomSet, ) -> Result<(), String> { use super::bus::Cpu; for (at, bytes) in self.main_runs_for(&roms.main)? { machine.patch_rom(Cpu::Main, at, &bytes)?; } for (at, bytes) in self.runs_for(&roms.sub[..0x1000])? { machine.patch_rom(Cpu::Sub, at, &bytes)?; } Ok(()) } pub fn apply(&self, machine: &mut super::Machine) -> Result<(), String> { use super::bus::Cpu; let sub_rom = machine.cpu(Cpu::Sub).bus.program()[..0x1000].to_vec(); let main_rom = machine.cpu(Cpu::Main).bus.program().to_vec(); let main_runs = self.main_runs_for(&main_rom)?; for (at, bytes) in self.runs_for(&sub_rom)? { machine.patch_rom(Cpu::Sub, at, &bytes)?; } for (at, bytes) in main_runs { machine.patch_rom(Cpu::Main, at, &bytes)?; } Ok(()) } }