// SPDX-License-Identifier: MIT //! Suzy's sprite engine: the SCB walk, unpacking, sizing, stretch, tilt, quadrants, //! clipping, the eight sprite types, the collision buffer and depository, EVERON //! (`suzy/engine.py`). //! //! Modelling level: functional per destination row (milestone 4), with each RAM access //! charged to the bus so the CPU, display DMA and refresh interleave; the per-access //! costs are milestone 5's (`COSTS` below). //! //! Sources (no emulator source was read; restart rules): //! //! - DOC "Spec §6": the Epyx specification, chapter 6 "Sprite/Collision" (SCB layout, //! types, collision process, stretch, tilt, skip, size offsets, packing notes, bugs). //! - DOC "Appx 2": the hardware address appendix (SPRCTL0, SPRCTL1, SPRCOLL, SPRGO, //! SPRSYS, the SCB register file). //! - DOC "App 4": the Epyx appendix 4 "Sprite Engine" (data lines: offset 0 ends the //! sprite, 1 changes quadrant counter-clockwise; clipping and super-clipping). //! - TEST ROM / LT: lynx-tests `lynx-sprite-performance.md` (MIT; measured on //! consoles by its author): the packet header layout, 8.8 size accumulators, the //! pen behaviour by type table, the literal end-of-row counts, Everon. //! //! Differences forced by Rust: //! //! - The Python walk is a generator (`_walk`, `yield from _sprite`) advanced one `yield` //! per `run`. Rust has no stable generators, so the walk is an explicit state machine, //! [`Step`], whose states are exactly the generator's suspension points: after an SCB //! header (`AfterHeader`) and after each destination row (`Sprite` in phase `Rows`). //! Everything the generator keeps in local variables across a `yield` is a field of //! [`SpriteState`]; everything it reads live (Suzy's registers) is read live here too. //! The state can be saved, which a Python generator cannot. //! - `_decode` is a generator consumed lazily by `_row`; here it is [`Decoder`], an //! iterator with the same laziness (its `consumed` count depends on where `_row` //! stops). //! - The engine reaches Suzy and the bus through [`EngineBus`] (the Python engine keeps a //! reference to its Suzy and is handed the board as `bus`). //! - The pen rules ("T"/"O"/"X", None/"P"/"D"/"W") are enums; `touched`, `groups` and //! `cells` (dicts whose order does not matter: only sums and counts are taken) are //! fixed arrays and a small vector. //! - `TIMELINE` (an environment variable read at import) is read once per process. use std::sync::OnceLock; use serde::{Deserialize, Serialize}; use crate::suzy::Suzy; /// What the engine needs of the board: Suzy's registers, RAM and the bus clock. pub trait EngineBus { /// Suzy owns the bus for `ticks` (the board's `suzy_cycles`). fn suzy_cycles(&mut self, ticks: i64); fn ram(&mut self) -> &mut [u8]; fn suzy(&mut self) -> &mut Suzy; } // SCB register file offsets (DOC Appx 2, $FC00 + offset; words, low byte first). pub const TILTACUM: usize = 0x02; pub const HOFF: usize = 0x04; pub const VOFF: usize = 0x06; pub const VIDBAS: usize = 0x08; pub const COLLBAS: usize = 0x0A; pub const VIDADR: usize = 0x0C; pub const COLLADR: usize = 0x0E; pub const SCBNEXT: usize = 0x10; pub const SPRDLINE: usize = 0x12; pub const HPOSSTRT: usize = 0x14; pub const VPOSSTRT: usize = 0x16; pub const SPRHSIZ: usize = 0x18; pub const SPRVSIZ: usize = 0x1A; pub const STRETCH: usize = 0x1C; pub const TILT: usize = 0x1E; pub const SPRDOFF: usize = 0x20; pub const SPRVPOS: usize = 0x22; pub const COLLOFF: usize = 0x24; pub const VSIZACUM: usize = 0x26; pub const HSIZOFF: usize = 0x28; pub const VSIZOFF: usize = 0x2A; pub const SCBADR: usize = 0x2C; pub const PROCADR: usize = 0x2E; pub const SCREEN_W: i64 = 160; // DOC Spec §5: 160 x 102 pens, 80 bytes a line pub const SCREEN_H: i64 = 102; /// Suzy's time (milestone 5), in ticks. The spec gives no cycle counts (Spec §6 names the /// pipeline: source FIFO, unpacker, pixel builder, pixel FIFO, merger, collision unit). /// LT (lynx-sprite-performance.md, measured on consoles): a destination row costs about /// the *maximum* of its overlapping paths plus fixed work, not their sum. Built so: /// /// ```text /// row = ROW + max(PEN * pens decoded, OUT * outputs, BUS * (source bytes + video /// bytes) + RMW * merged bytes + collision groups) + XOR * video bytes /// + STRETCH_ROW / TILT_ROW when enabled /// ``` pub struct Costs { pub scb: i64, pub offset: i64, pub reject: i64, pub row: i64, pub pen16: i64, pub out16: i64, pub bus16: i64, pub rmw: i64, pub xor: i64, pub coll: i64, pub coll_detect: i64, pub stretch: i64, pub tilt: i64, } pub const COSTS: Costs = Costs { // HYPOTHESIS: one SCB byte read (no measurement isolates it). scb: 4, // TEST ROM (LT "Stretch and tilt"): a source record's offset read takes 2 ticks; a // record that generates no row adds an 18-tick reject stage. offset: 2, reject: 18, // FITTED (scripts/m5_fit.py, coordinate descent) to sprites1 1-8, the literal and // expansion rows: fixed row work, ticks per decoded pen, per generated output (LT: // "72 + 2 * outputs" for one pen expanded), per bus byte (LT: the 4,2,2,2 // destination-word slots, 2.5 a byte); started from those LT values (76, 2, 2, // 2.56). Only 3 of the 8 fitting tests land inside their windows: the structure is // short of the hardware's (1 bpp and 2 bpp full rows differ on hardware, not here). // Held out (sprites2-5): validation.md "M5". row: 68, pen16: 32, // sixteenths of a tick out16: 32, bus16: 40, // TEST ROM (LT): a read/write merge adds about 2 ticks per destination byte; XOR // about 2 per destination byte; collision RAM transactions per 8-pixel screen group: // write or read 10, read plus write or detect 18; stretch 8 and tilt 18 per row. rmw: 2, xor: 2, coll: 10, coll_detect: 18, stretch: 8, tilt: 18, }; pub const YIELD_TICKS: i64 = 40; // DOC Spec §4: Suzy yields the bus to Mikey within 40 ticks /// The named switch between the two row timelines (docs/validation.md "M5 structure"): /// "paths" = the max-of-paths model above (LT's rule, four constants FITTED on /// sprites1); "measured" = the timeline read from the Batman Returns capture /// (`measured_row`). The default is the one that scores better on held-out windows: /// on sprites2-5 (held out from the paths fit; nothing was fitted for "measured") the /// measured timeline puts 15 of 32 inside their windows, the paths model 13 (2026-11-14). /// True for "measured" (`LYNX_SUZY_TIMELINE`, read once). pub fn timeline_measured() -> bool { static TIMELINE: OnceLock = OnceLock::new(); *TIMELINE.get_or_init(|| { std::env::var("LYNX_SUZY_TIMELINE").unwrap_or_else(|_| "measured".into()) == "measured" }) } /// MEASURED (scripts/la_sprite.py --dest E000-FFE0 on lynx2-mikey-batman-75hz, first 80 ms; /// the most common gap of each phase, Suzy's RAS groups only, display DMA and refresh set /// aside): a RAS group's first CAS 4 ticks after the previous group's last, then one CAS /// every 2 ticks; 32 ticks from the line's offset byte to its first data group; 22 from /// the last destination group to the next line; a destination group of 4 pixels-pairs /// starts 16 ticks after the one before when not bus-bound (8 pixels: 2 a pixel). pub struct Measured { pub offset: i64, pub start: i64, pub ras: i64, pub pixel: i64, pub end: i64, } pub const MEASURED: Measured = Measured { offset: 4, start: 32, ras: 4, pixel: 2, end: 22, }; /// Video behaviour of a pen: transparent, opaque, exclusive-or. #[derive(Clone, Copy, PartialEq, Eq, Debug)] pub enum Video { T, O, X, } /// Collision behaviour: preserve (no detect, no write), detect then write the sprite's /// number, write without detecting (background). #[derive(Clone, Copy, PartialEq, Eq, Debug)] pub enum Coll { P, D, W, } type Rule = (Video, Option); use Coll::{D as CD, P as CP, W as CW}; use Video::{O as VO, T as VT, X as VX}; /// The eight types (DOC Appx 2 SPRCTL0 B2-B0; DOC Spec §6 table with the shadow error; /// LT "Pen behavior by type"). Per type, per pen class: (video, collision) where video /// is "T" transparent, "O" opaque, "X" exclusive-or, and collision is None (no activity), /// "P" preserve (no detect, no write), "D" detect then write the sprite's number, "W" /// write without detecting (background). // pen 0 pen E pen F other pens pub const TYPES: [[Rule; 4]; 8] = [ [ (VO, Some(CW)), (VO, Some(CP)), (VO, Some(CW)), (VO, Some(CW)), ], // 0 background, shadow [(VO, None), (VO, None), (VO, None), (VO, None)], // 1 background, no collision [(VT, None), (VO, Some(CP)), (VT, Some(CD)), (VO, Some(CD))], // 2 boundary-shadow [(VT, None), (VO, Some(CD)), (VT, Some(CD)), (VO, Some(CD))], // 3 boundary [(VT, None), (VO, Some(CD)), (VO, Some(CD)), (VO, Some(CD))], // 4 normal [(VT, None), (VO, None), (VO, None), (VO, None)], // 5 non-collideable [(VT, None), (VX, Some(CP)), (VX, Some(CD)), (VX, Some(CD))], // 6 exclusive-or, shadow [(VT, None), (VO, Some(CP)), (VO, Some(CD)), (VO, Some(CD))], // 7 shadow ]; /// DOC Spec §6: "At the completion of the processing of each collideable sprite, the /// hardware writes a byte into the 'collision depository'"; background types write no /// depository (Spec §6 "Background-Shadow Sprites"); LT: types 2, 3, 4, 6, 7. pub const DEPOSITORY_TYPES: [u8; 5] = [2, 3, 4, 6, 7]; fn signed(value: i64) -> i64 { if value & 0x8000 != 0 { value - 0x10000 } else { value } } /// Where the sprite loop stands (the generator's position inside `_sprite`). #[derive(Clone, Copy, PartialEq, Eq, Debug, Serialize, Deserialize)] pub enum Phase { /// The top of the quadrant loop (`while True:` around the quadrant's set-up). QuadrantTop, /// The top of the source-line loop (the offset read). OffsetTop, /// Inside `for _ in range(rows)`, `rows_left` rows still to draw. Rows, } /// The locals of `_sprite` that live across a `yield`. #[derive(Clone, Debug, Serialize, Deserialize)] pub struct SpriteState { pub scb: i64, pub depth: u8, pub ctl0: u8, pub ctl1: u8, pub bpp: u32, pub kind: u8, pub collide: bool, pub number: u8, /// `state = [fred, ever on screen]`. pub fred: u8, pub ever: bool, pub hoff: i64, pub voff: i64, pub ref_h: i64, pub ref_v: i64, pub quadrant: u8, pub first: Option<(bool, bool)>, pub data: i64, pub left: bool, pub hacc0: i64, pub vstep: i64, pub y: i64, pub hpos: i64, pub vacc: i64, pub offset: i64, pub line: i64, pub rows_left: i64, pub phase: Phase, } /// The generator's suspension points (`_walk`). #[derive(Clone, Debug, Serialize, Deserialize)] pub enum Step { /// Armed, not yet run, or at the top of the SCB loop. Walk, /// Suspended at the `yield` after an SCB's first five bytes. AfterHeader { scb: i64 }, /// Inside `yield from self._sprite(scb, depth)`. Sprite(Box), /// `_sprite` returned: the stop-request test, then the next SCB. AfterSprite, } /// Runs one sprite list from SCBNEXT. `start` arms it; `run(bus)` advances it /// by one destination row (or one SCB header) and returns True when the list is done. #[derive(Clone, Default, Serialize, Deserialize)] pub struct SpriteEngine { pub consumed: i64, // bits of the current source line decoded so far pub pens: [u8; 16], // the pen index palette (DOC Spec §6: 16 nybbles) pub steps: Option, } /// The lazy pen-index stream of one source line (`_decode`). pub struct Decoder { data: Vec, bits: i64, position: i64, bpp: u32, literal_all: bool, state: DecodeState, } enum DecodeState { Header, Literal(i64), Repeat(u8, i64), Done, } impl Decoder { fn take(&mut self, n: u32, consumed: &mut i64) -> u8 { let mut value = 0u32; for _ in 0..n { let byte = self.data[(self.position >> 3) as usize]; value = (value << 1) | ((byte >> (7 - (self.position & 7))) & 1) as u32; self.position += 1; } *consumed = self.position; value as u8 } /// The next pen index, or None at the end of the line. pub fn next(&mut self, consumed: &mut i64) -> Option { let bpp = self.bpp as i64; if self.literal_all { // DOC Appx 2 SPRCTL1 B7: totally literal if self.position + bpp <= self.bits { return Some(self.take(self.bpp, consumed)); } return None; } loop { match self.state { DecodeState::Done => return None, DecodeState::Header => { if self.position + 5 > self.bits { self.state = DecodeState::Done; continue; } let header = self.take(5, consumed); if header == 0 { // DOC Spec §6: '00000' ends the line self.state = DecodeState::Done; continue; } let count = (header & 0x0F) as i64 + 1; // LT: bit 4 literal, bits 3-0 count - 1 if header & 0x10 != 0 { self.state = DecodeState::Literal(count); } else { if self.position + bpp > self.bits { self.state = DecodeState::Done; continue; } let index = self.take(self.bpp, consumed); self.state = DecodeState::Repeat(index, count); } } DecodeState::Literal(left) => { if left == 0 { self.state = DecodeState::Header; continue; } if self.position + bpp > self.bits { self.state = DecodeState::Done; continue; } self.state = DecodeState::Literal(left - 1); return Some(self.take(self.bpp, consumed)); } DecodeState::Repeat(index, left) => { if left == 0 { self.state = DecodeState::Header; continue; } self.state = DecodeState::Repeat(index, left - 1); return Some(index); } } } } } enum Outcome { Yield, Return, } impl SpriteEngine { pub fn new() -> SpriteEngine { SpriteEngine { pens: [0; 16], steps: None, consumed: 0, } } pub fn start(&mut self) { // DOC Spec §6: "This engine starts only from its beginning." self.steps = Some(Step::Walk); } pub fn run(&mut self, bus: &mut B) -> bool { loop { let Some(step) = self.steps.take() else { return true; }; match step { Step::Walk => { let suzy = bus.suzy(); let scb = suzy.word(SCBNEXT); // DOC Spec §16 bug list: only the upper byte of SCBNEXT is tested for the end. if scb >> 8 == 0 { return true; // the generator returned: steps stays None } suzy.set_word(SCBADR, scb); // DOC Spec §6 "Skip Sprite": the first 5 bytes are always read and loaded. let v = self.read(bus, scb); bus.suzy().sprctl0 = v; let v = self.read(bus, scb + 1); bus.suzy().sprctl1 = v; let v = self.read(bus, scb + 2); bus.suzy().sprcoll = v; let v = self.read16(bus, scb + 3); bus.suzy().set_word(SCBNEXT, v); self.steps = Some(Step::AfterHeader { scb }); return false; // yield } Step::AfterHeader { scb } => { let ctl1 = bus.suzy().sprctl1; if ctl1 & 0x04 == 0 { let mut address = scb + 5; for offset in [SPRDLINE, HPOSSTRT, VPOSSTRT] { let v = self.read16(bus, address); bus.suzy().set_word(offset, v); address += 2; } // DOC Appx 2 SPRCTL1 B5-B4, reload depth: 1 = H/V size, 2 = + stretch, // 3 = + tilt. let depth = (ctl1 >> 4) & 3; let reload = if depth != 0 { depth as usize + 1 } else { 0 }; for offset in [SPRHSIZ, SPRVSIZ, STRETCH, TILT].into_iter().take(reload) { let v = self.read16(bus, address); bus.suzy().set_word(offset, v); address += 2; } if ctl1 & 0x08 == 0 { // DOC Appx 2 SPRCTL1 B3: 0 = reload the palette for i in 0..8 { let byte = self.read(bus, address + i); // DOC Spec §6 "Bits in Bytes": PIN 0 is the upper nybble of byte 0. self.pens[2 * i as usize] = byte >> 4; self.pens[2 * i as usize + 1] = byte & 0x0F; } } let state = self.sprite_start(bus, scb, depth); self.steps = Some(Step::Sprite(Box::new(state))); } else { self.steps = Some(Step::AfterSprite); } } Step::Sprite(mut state) => match self.sprite(bus, &mut state) { Outcome::Yield => { self.steps = Some(Step::Sprite(state)); return false; } Outcome::Return => self.steps = Some(Step::AfterSprite), }, Step::AfterSprite => { // DOC Appx 2 SPRSYS B1: stop at the end of the current sprite. if bus.suzy().stop_request != 0 { return true; } self.steps = Some(Step::Walk); } } } } // -- RAM, through the bus ------------------------------------------------------------ /// Hold the bus for `ticks`, yielding to display DMA and refresh between /// chunks (DOC Spec §4: within 40 ticks). fn charge(&self, bus: &mut B, mut ticks: i64) { while ticks > 0 { let chunk = ticks.min(YIELD_TICKS); bus.suzy_cycles(chunk); ticks -= chunk; } } /// An SCB byte read (the row traffic is charged per row by `row`). fn read(&self, bus: &mut B, address: i64) -> u8 { self.charge(bus, COSTS.scb); bus.ram()[(address & 0xFFFF) as usize] } fn read16(&self, bus: &mut B, address: i64) -> i64 { self.read(bus, address) as i64 | ((self.read(bus, address + 1) as i64) << 8) } fn write(&self, bus: &mut B, address: i64, value: u8) { self.charge(bus, COSTS.scb); bus.ram()[(address & 0xFFFF) as usize] = value; } // -- one sprite ---------------------------------------------------------------------- /// `_sprite` up to its first loop: the locals it sets once. fn sprite_start(&mut self, bus: &mut B, scb: i64, depth: u8) -> SpriteState { let suzy = bus.suzy(); let (ctl0, ctl1) = (suzy.sprctl0, suzy.sprctl1); let bpp = (ctl0 >> 6) as u32 + 1; // DOC Appx 2 SPRCTL0 B7-B6: bits per pixel - 1 let kind = ctl0 & 7; // DOC Spec §6 "Anti-Collision Devices": SPRCOLL B5 or SPRSYS B5 disable all // collision activity for the sprite. let collide = suzy.sprcoll & 0x20 == 0 && suzy.sprsys & 0x20 == 0; let number = suzy.sprcoll & 0x0F; let (hoff, voff) = (signed(suzy.word(HOFF)), signed(suzy.word(VOFF))); let (ref_h, ref_v) = (suzy.word(HPOSSTRT), suzy.word(VPOSSTRT)); // DOC Appx 2 SPRCTL1 B0 = start drawing left, B1 = start drawing up; DOC App 4: // quadrants follow counter-clockwise: right-down, right-up, left-up, left-down. let quadrant = match (ctl1 & 1, (ctl1 >> 1) & 1) { (0, 0) => 0, (0, 1) => 1, (1, 1) => 2, _ => 3, }; suzy.set_word(TILTACUM, 0); // LT: the tilt accumulator starts from zero let data = suzy.word(SPRDLINE); SpriteState { scb, depth, ctl0, ctl1, bpp, kind, collide, number, fred: 0, // fred (DOC Spec §6 "Collision Process"), ever on screen ever: false, hoff, voff, ref_h, ref_v, quadrant, first: None, data, left: false, hacc0: 0, vstep: 0, y: 0, hpos: 0, vacc: 0, offset: 0, line: 0, rows_left: 0, phase: Phase::QuadrantTop, } } /// `_sprite`'s loops, from where `s.phase` says, to the next `yield` or the return. fn sprite(&mut self, bus: &mut B, s: &mut SpriteState) -> Outcome { loop { match s.phase { Phase::QuadrantTop => { let suzy = bus.suzy(); let mut left = s.quadrant == 2 || s.quadrant == 3; let mut up = s.quadrant == 1 || s.quadrant == 2; // DOC Spec §6 "Horizontal and Vertical Size Offset": up and left start from 0, // down and right from VSIZOFF / HSIZOFF. TEST ROM (sprites2 8, the Alpine // Games protection SCB: H-flipped, drawn leftwards, HSIZOFF $7F needed for // its third pen to reach x = 159): the quadrant's direction before the flip // chooses the offset. let hacc0 = if left { 0 } else { suzy.word(HSIZOFF) }; let vacc0 = if up { 0 } else { suzy.word(VSIZOFF) }; if s.ctl0 & 0x20 != 0 { // DOC Appx 2 SPRCTL0 B5: H flip (the pivot is the reference) left = !left; } if s.ctl0 & 0x10 != 0 { // B4: V flip up = !up; } if s.first.is_none() { s.first = Some((left, up)); } let (first_left, first_up) = s.first.unwrap(); let (hstep, vstep) = (if left { -1 } else { 1 }, if up { -1 } else { 1 }); // HYPOTHESIS: a quadrant drawn the other way from the first one starts one // pixel (line) beyond the reference, so the reference line is drawn once // (DOC Spec §6: "there will be a positional alteration if the starting // quadrant is changed"). Settled by lynx-tests where a test covers it. s.y = signed(s.ref_v) - s.voff + if up != first_up { vstep } else { 0 }; s.hpos = signed(s.ref_h) + if left != first_left { hstep } else { 0 }; suzy.set_word(HPOSSTRT, s.ref_h); s.vacc = vacc0; s.left = left; s.hacc0 = hacc0; s.vstep = vstep; s.phase = Phase::OffsetTop; } Phase::OffsetTop => { self.charge(bus, COSTS.offset); let offset = bus.ram()[(s.data & 0xFFFF) as usize] as i64; if offset == 0 { // DOC App 4: end of sprite data self.depository(bus, s); return Outcome::Return; } if offset == 1 { // DOC App 4: end of quadrant s.data += 1; s.quadrant = (s.quadrant + 1) & 3; s.phase = Phase::QuadrantTop; continue; } s.offset = offset; s.line = (s.data + 1) & 0xFFFF; // LT: 8.8 size accumulators; the integer part is the row count. let suzy = bus.suzy(); s.vacc += suzy.word(SPRVSIZ); let rows = s.vacc >> 8; s.vacc &= 0xFF; suzy.set_word(VSIZACUM, s.vacc); if rows == 0 { self.charge(bus, COSTS.reject); } s.rows_left = rows; s.phase = Phase::Rows; } Phase::Rows => { if s.rows_left == 0 { s.data = (s.data + s.offset) & 0xFFFF; s.phase = Phase::OffsetTop; continue; } s.rows_left -= 1; let mut ticks = if 0 <= s.y && s.y < SCREEN_H { self.row(bus, s) } else { COSTS.reject // HYPOTHESIS: an off-window row is rejected }; ticks += if s.depth >= 2 { COSTS.stretch } else { 0 }; ticks += if s.depth >= 3 { COSTS.tilt } else { 0 }; self.charge(bus, ticks); s.y += s.vstep; // DOC Spec §6 "Horizontal Stretch", "Vertical Stretch", "Tilt": after // every destination line, when the reload depth enables them. let suzy = bus.suzy(); if s.depth >= 2 { let stretch = suzy.word(STRETCH); suzy.set_word(SPRHSIZ, suzy.word(SPRHSIZ) + stretch); if suzy.sprsys & 0x10 != 0 { // DOC Appx 2 SPRSYS B4: Vstretch suzy.set_word(SPRVSIZ, suzy.word(SPRVSIZ) + stretch); } } if s.depth >= 3 { let total = suzy.word(TILTACUM) + signed(suzy.word(TILT)); s.hpos += total >> 8; suzy.set_word(TILTACUM, total & 0xFF); suzy.set_word(HPOSSTRT, s.hpos); } return Outcome::Yield; } } } } /// One destination row of one source line; returns its ticks (`COSTS`). fn row(&mut self, bus: &mut B, s: &mut SpriteState) -> i64 { let (line, length, bpp, kind) = (s.line, s.offset - 1, s.bpp, s.kind); let (collide, number, y, left) = (s.collide, s.number, s.y, s.left); let mut x = s.hpos - s.hoff; let mut hacc = s.hacc0; let pens = self.pens; let rules = &TYPES[kind as usize]; let suzy = bus.suzy(); let hsize = suzy.word(SPRHSIZ); let step: i64 = if left { -1 } else { 1 }; let video = suzy.word(VIDBAS) + y * 80; let colls = suzy.word(COLLBAS) + y * 80; let literal_all = suzy.sprctl1 & 0x80 != 0; let (mut decoded, mut outputs) = (0i64, 0i64); // Destination bytes touched: x >> 1 -> (pixels written opaque/XOR, pixels seen). let mut touched = [(false, 0i64, 0i64); 80]; // collision 8-pixel screen group -> detected let mut groups = [(false, false); 20]; let mut xor = false; let mut source = self.decode(bus, line, length, bpp, literal_all); let mut consumed = self.consumed; while let Some(index) = source.next(&mut consumed) { decoded += 1; hacc += hsize; let count = hacc >> 8; hacc &= 0xFF; if count == 0 { continue; } let pen = pens[index as usize]; let rule = rules[match pen { 0 => 0, 0x0E => 1, 0x0F => 2, _ => 3, }]; let mut stop = false; for _ in 0..count { outputs += 1; if (0..SCREEN_W).contains(&x) { s.ever = true; let cell = &mut touched[(x >> 1) as usize]; cell.0 = true; cell.2 += 1; if rule.0 != Video::T { cell.1 += 1; xor = xor || rule.0 == Video::X; } if collide && matches!(rule.1, Some(Coll::D) | Some(Coll::W)) { let g = &mut groups[(x >> 3) as usize]; g.1 = (g.0 && g.1) || rule.1 == Some(Coll::D); g.0 = true; } self.plot(bus, video, colls, x, pen, rule, collide, number, s); } else if (x >= SCREEN_W && step > 0) || (x < 0 && step < 0) { stop = true; // App 4 + LT: the first off-window output ends the line break; } x += step; } if stop { break; } } self.consumed = consumed; let source_bytes = length.min((self.consumed + 7) >> 3); let touched_count = touched.iter().filter(|c| c.0).count() as i64; let mut merged = touched .iter() .filter(|c| c.0 && c.1 != 0 && c.1 < 2) .count() as i64; merged += touched .iter() .filter(|c| c.0 && c.1 == 0 && c.2 != 0) .count() as i64; let mut bus_ticks = (COSTS.bus16 * (source_bytes + touched_count)) >> 4; bus_ticks += COSTS.rmw * merged; bus_ticks += groups .iter() .filter(|g| g.0) .map(|g| if g.1 { COSTS.coll_detect } else { COSTS.coll }) .sum::(); if timeline_measured() { return Self::measured_row(video, &touched, &groups, source_bytes, xor); } let paths = [ (COSTS.pen16 * decoded) >> 4, (COSTS.out16 * outputs) >> 4, bus_ticks, ]; let mut ticks = COSTS.row + paths.into_iter().max().unwrap(); if xor { ticks += COSTS.xor * touched_count; } ticks } /// A destination row on the timeline read from a game capture (`MEASURED` /// below: scripts/la_sprite.py on lynx2-mikey-batman-75hz, modes of the gaps): /// the line's offset byte, a wait, the source bytes in RAS groups of up to four /// 2-tick CAS cycles, then the destination bytes in 4-byte-aligned RAS groups, /// each as long as its bus cycles or its pixels at 2 ticks each, whichever is /// longer, then the line-end wait. Collision groups are charged like destination /// groups (HYPOTHESIS: the capture's game draws without visible collision runs). fn measured_row( video: i64, touched: &[(bool, i64, i64); 80], groups: &[(bool, bool); 20], source_bytes: i64, xor: bool, ) -> i64 { let m = &MEASURED; let mut ticks = m.offset + m.start; let mut k = 0; while k < source_bytes { ticks += m.ras + 2 * ((4.min(source_bytes - k)) - 1); k += 4; } // group key -> (cas, pixels) let mut cells: Vec<(i64, i64, i64)> = Vec::with_capacity(24); for (byte, &(present, opaque, seen)) in touched.iter().enumerate() { if !present { continue; } let key = ((video + byte as i64) & 0xFFFF) >> 2; let position = match cells.iter().position(|c| c.0 == key) { Some(p) => p, None => { cells.push((key, 0, 0)); cells.len() - 1 } }; let group = &mut cells[position]; group.1 += 1 + if (opaque != 0 && opaque < 2) || (opaque == 0 && seen != 0) { 1 } else { 0 }; group.2 += seen; } for &(_, cas, pixels) in &cells { ticks += (m.ras + 2 * (cas - 1)).max(m.pixel * pixels); } for &(present, detected) in groups { if present { ticks += m.ras + 2 * ((if detected { 8 } else { 4 }) - 1); } } if xor { ticks += 2 * touched.iter().filter(|c| c.0).count() as i64; // TEST ROM (LT): XOR about 2 per destination byte } ticks + m.end } #[allow(clippy::too_many_arguments)] fn plot( &self, bus: &mut B, video: i64, colls: i64, x: i64, pen: u8, rule: Rule, collide: bool, number: u8, s: &mut SpriteState, ) { let shift = if x & 1 != 0 { 0 } else { 4 }; // DOC Spec §6 "Bits in Bytes": left pixel in bits 7-4 let ram = bus.ram(); let address = ((video + (x >> 1)) & 0xFFFF) as usize; let (mode, collision) = rule; if mode != Video::T { let byte = ram[address]; let old = (byte >> shift) & 0x0F; let new = if mode == Video::X { old ^ pen } else { pen }; ram[address] = (byte & !(0x0Fu8 << shift)) | (new << shift); } let collision = match collision { None | Some(Coll::P) => return, Some(c) => c, }; if !collide { return; } let address = ((colls + (x >> 1)) & 0xFFFF) as usize; let byte = ram[address]; if collision == Coll::D { s.fred = s.fred.max((byte >> shift) & 0x0F); } ram[address] = (byte & !(0x0Fu8 << shift)) | (number << shift); } /// The pen indices of one source line (DOC Spec §6 "Data Packing Format"; LT). /// /// The line's last bit is never decoded: DOC Spec §6 "the last meaningful bit of /// the data packet at the end of a scan line [must] not occur in the last bit of a /// byte"; TEST ROM (LT "End-of-row hardware bug": 7/3/2/1 extra zero indices from /// a pad byte at 1/2/3/4 bpp) agrees with a stream one bit shorter than the line. fn decode( &mut self, bus: &mut B, line: i64, length: i64, bpp: u32, literal_all: bool, ) -> Decoder { let ram = bus.ram(); let data: Vec = (0..length.max(0)) .map(|i| ram[((line + i) & 0xFFFF) as usize]) .collect(); self.consumed = 0; Decoder { data, bits: 8 * length - 1, position: 0, bpp, literal_all, state: DecodeState::Header, } } fn depository(&self, bus: &mut B, s: &SpriteState) { let suzy = bus.suzy(); let address = (s.scb + signed(suzy.word(COLLOFF))) & 0xFFFF; let everon = suzy.sprgo & 0x04 != 0; // DOC Appx 2 SPRGO B2: enable the everon detector let mut value: Option = None; if s.collide && DEPOSITORY_TYPES.contains(&s.kind) { value = Some(s.fred); } if everon { // DOC Spec §12.5 + LT: bit 7 is 1 only when the sprite never touched the // screen. HYPOTHESIS (U16): written for every type, the low bits being the // collision result where there is one and kept otherwise. let low = match value { Some(v) => v, None => bus.ram()[address as usize] & 0x7F, }; value = Some(low | if s.ever { 0 } else { 0x80 }); } if let Some(value) = value { self.write(bus, address, value); } } }