supergrafx_rust/
trace.rs

1//! The lockstep gate's side of this add-on: how a traced SuperGrafx is built from a command
2//! line, and the save-state checks. **Not a module of the reference**: its counterparts there
3//! are `scripts/sgx_ours.py` (the modes and `--vpc-option`) and `scripts/sgx_state.py`.
4//!
5//! The lines themselves are the base board's (`pcengine_rust::trace::frame_line`: the CPU bus
6//! log, the mixed picture, the audio and the CPU state of a frame), and so is the command line
7//! (`pcengine_rust::trace::Setup`), to which this adds:
8//!
9//! - `--mode sgx|compat|base`: the add-on in native position (default), the back-panel switch
10//!   in PC Engine position, or the **fallback**: the card on the plain base board with a row of
11//!   32 KiB and one VDC (the reference's `sgx_ours.py --mode base`);
12//! - `--vpc NAME=VALUE`: a named switch by the reference's attribute name
13//!   (`PRIORITY_LABELS=sgxtech`, `WINDOW_ORIGIN=48,48,48` for the dividers 4, 3 and 2,
14//!   `WINDOW_OFF_AT_OR_BELOW=N`, `ST_STEERS_IN_COMPAT=true`);
15//! - `--compat-at FRAME`: the switch is moved to PC Engine position once FRAME frames have
16//!   completed (U-SGX4 needs a `$0E` bit left over from native mode).
17//!
18//! `roundtrip` and `runahead` are the base board's `trace::roundtrip` and `runahead` over a
19//! machine built here (the base's build its own boards from a `Setup`, so they could not be
20//! called).
21
22use pcengine_rust::board::{Board, BoardOptions};
23use pcengine_rust::cards::make_card;
24use pcengine_rust::machine::Machine;
25use pcengine_rust::pads::{self, Pad2};
26use pcengine_rust::sockets::ControllerPort;
27use pcengine_rust::state::{load_snapshot, load_state, save_snapshot, save_state};
28use pcengine_rust::system::System;
29use pcengine_rust::trace::{frame_line, Setup};
30
31use crate::board::{set_compat, SuperGrafx, SuperGrafxOptions};
32use crate::machine::SUPERGRAFX;
33use crate::vpc::{PriorityLabels, Vpc, WindowOrigin};
34
35#[derive(Clone, Copy, Debug, PartialEq, Eq)]
36pub enum Mode {
37    Sgx,
38    Compat,
39    Base,
40}
41
42/// The fallback's machine row: the SuperGrafx's RAM on a board with one VDC and no VPC.
43pub const BASE_MODE: Machine = Machine {
44    work_ram_bytes: SUPERGRAFX.work_ram_bytes,
45    ..Machine::new("SuperGrafx (base mode)", true)
46};
47
48/// A named switch of the reference's `Vpc`, by its attribute name. `ST_STEERS_IN_COMPAT`
49/// (the page's) is answered with `Ok(Some(value))`.
50pub fn set_vpc_switch(vpc: &mut Vpc, name: &str, value: &str) -> Result<Option<bool>, String> {
51    let number = |text: &str| {
52        text.trim()
53            .parse::<i64>()
54            .map_err(|_| format!("{name}: a number, not {text}"))
55    };
56    match name {
57        "PRIORITY_LABELS" => {
58            vpc.priority_labels = match value {
59                "detectors" => PriorityLabels::Detectors,
60                "sgxtech" => PriorityLabels::Sgxtech,
61                _ => return Err(format!("{name}: detectors or sgxtech, not {value}")),
62            }
63        }
64        "WINDOW_ORIGIN" => {
65            let parts: Vec<&str> = value.split(',').collect();
66            if parts.len() != 3 {
67                return Err(format!(
68                    "{name}: three numbers (dividers 4, 3, 2), not {value}"
69                ));
70            }
71            vpc.window_origin = WindowOrigin {
72                divider4: number(parts[0])?,
73                divider3: number(parts[1])?,
74                divider2: number(parts[2])?,
75            };
76        }
77        "WINDOW_OFF_AT_OR_BELOW" => vpc.window_off_at_or_below = number(value)?,
78        "ST_STEERS_IN_COMPAT" => {
79            return match value {
80                "true" | "True" | "1" => Ok(Some(true)),
81                "false" | "False" | "0" => Ok(Some(false)),
82                _ => Err(format!("{name}: true or false, not {value}")),
83            }
84        }
85        _ => return Err(format!("no VPC switch {name}")),
86    }
87    Ok(None)
88}
89
90/// How a traced machine is built: the base board's `Setup` and this add-on's own arguments.
91#[derive(Clone, Debug)]
92pub struct SgxSetup {
93    pub base: Setup,
94    pub mode: Mode,
95    pub vpc: Vpc,
96    pub st_steers_in_compat: bool,
97    pub compat_at: Option<i64>,
98    /// Arguments neither parser knows (a binary's own).
99    pub rest: Vec<String>,
100}
101
102impl SgxSetup {
103    /// The reference's defaults around a card image, in native position.
104    pub fn for_image(image: Vec<u8>) -> SgxSetup {
105        SgxSetup {
106            base: Setup::for_image(image),
107            mode: Mode::Sgx,
108            vpc: Vpc::new(),
109            st_steers_in_compat: false,
110            compat_at: None,
111            rest: Vec::new(),
112        }
113    }
114
115    pub fn parse(args: &[String]) -> Result<SgxSetup, String> {
116        let base = Setup::parse(args)?;
117        let mut setup = SgxSetup::for_image(Vec::new());
118        let mut iter = base.rest.iter();
119        while let Some(arg) = iter.next() {
120            let mut value = || iter.next().ok_or_else(|| format!("{arg} needs a value"));
121            match arg.as_str() {
122                "--mode" => {
123                    setup.mode = match value()?.as_str() {
124                        "sgx" => Mode::Sgx,
125                        "compat" => Mode::Compat,
126                        "base" => Mode::Base,
127                        other => return Err(format!("no mode {other}: sgx, compat or base")),
128                    }
129                }
130                "--vpc" => {
131                    let text = value()?;
132                    let (name, to) = text
133                        .split_once('=')
134                        .ok_or_else(|| format!("--vpc NAME=VALUE, not {text}"))?;
135                    if let Some(flag) = set_vpc_switch(&mut setup.vpc, name, to)? {
136                        setup.st_steers_in_compat = flag;
137                    }
138                }
139                "--compat-at" => {
140                    let text = value()?;
141                    setup.compat_at =
142                        Some(text.parse().map_err(|_| format!("not a number: {text}"))?);
143                }
144                _ => setup.rest.push(arg.clone()),
145            }
146        }
147        setup.base = base;
148        Ok(setup)
149    }
150
151    /// One more machine, built the same way each time.
152    pub fn build(&self) -> Result<System, String> {
153        let base = &self.base;
154        let pad: Option<Box<dyn ControllerPort>> = match base.device.as_str() {
155            "none" => None,
156            _ => Some(Box::new(Pad2::new())),
157        };
158        let board = BoardOptions {
159            machine: BASE_MODE,
160            card: Some(make_card(&base.image)?),
161            port: None,
162            pad,
163            pixel_path: None,
164            power_on_seed: base.seed,
165            start_line: base.start_line,
166            start_offset: base.start_offset,
167            vblank_dots: base.vblank_dots,
168            vertical_at_line_start: base.vertical_at_line_start,
169            dma_resumes: base.dma_resumes,
170            psg: base.psg,
171            timer_underflow_window_mclk: base.timer_window,
172        };
173        if self.mode == Mode::Base {
174            return Ok(System::new(Board::new(board)?));
175        }
176        let machine = SuperGrafx::new(SuperGrafxOptions {
177            compat: self.mode == Mode::Compat,
178            vpc: Some(self.vpc.clone()),
179            st_steers_in_compat: self.st_steers_in_compat,
180            board,
181        })?;
182        Ok(machine.build())
183    }
184
185    /// Before a frame: hold the buttons of the presses, and move the switch if it is time.
186    pub fn before_frame(&self, system: &mut System) {
187        if self.compat_at == Some(system.frame()) {
188            set_compat(system, true);
189        }
190        self.base.apply_presses(system);
191    }
192
193    /// Run `frames` frames; a line a frame.
194    pub fn run_frames(&self, system: &mut System, frames: i64) -> Vec<String> {
195        (0..frames)
196            .map(|_| {
197                self.before_frame(system);
198                system.run_frame();
199                frame_line(system)
200            })
201            .collect()
202    }
203
204    fn started(&self) -> Result<System, String> {
205        let mut system = self.build()?;
206        system.board_mut().bus_log = Some(Vec::new());
207        Ok(system)
208    }
209}
210
211fn settle(system: &mut System) {
212    if let Some(log) = system.board_mut().bus_log.as_mut() {
213        log.clear();
214    }
215    system.board_mut().take_audio();
216}
217
218/// Save states, proven complete (the base board's `trace::roundtrip`, the reference's
219/// `scripts/sgx_state.py`): power on, run to frame `at` plus `extra` instructions, save, then
220/// load the state into a fresh system and into one that had run elsewhere, and run each to frame
221/// `to`: every frame after the save must be the same, by the gate's own lines, and the loaded
222/// system saved at once must give the same bytes.
223pub fn roundtrip(setup: &SgxSetup, at: i64, to: i64, extra: i64) -> Result<String, String> {
224    let mut first = setup.started()?;
225    setup.run_frames(&mut first, at);
226    for _ in 0..extra {
227        first.step();
228    }
229    let state = save_state(&first);
230    settle(&mut first);
231    let expected = setup.run_frames(&mut first, to - at);
232    for (label, warm) in [
233        ("a fresh system", 0),
234        ("a system that had run", 1.max(at / 2)),
235    ] {
236        let mut second = setup.started()?;
237        setup.run_frames(&mut second, warm);
238        load_state(&mut second, &state).map_err(|error| format!("{label}: {error}"))?;
239        if save_state(&second) != state {
240            return Err(format!(
241                "{label}: saved again at once, the state is not the same bytes"
242            ));
243        }
244        settle(&mut second);
245        let got = setup.run_frames(&mut second, to - at);
246        for (n, (a, b)) in expected.iter().zip(&got).enumerate() {
247            if a != b {
248                return Err(format!(
249                    "{label}: differs in frame {} after the save\n  expected {a}\n  got      {b}",
250                    n + 1
251                ));
252            }
253        }
254    }
255    Ok(format!(
256        "{} bytes; {} frames after the save equal, twice",
257        state.len(),
258        to - at
259    ))
260}
261
262/// The snapshot pair in a run-ahead pass (the base board's `trace::runahead`): every frame is
263/// run, a snapshot taken, `ahead` more frames run with other buttons held, and the snapshot put
264/// back. Each frame's line, and the state at the end, must equal a run's that never looked ahead.
265pub fn runahead(setup: &SgxSetup, frames: i64, ahead: i64) -> Result<String, String> {
266    let mut plain = setup.started()?;
267    let expected = setup.run_frames(&mut plain, frames);
268    let mut system = setup.started()?;
269    let mut bytes = 0;
270    for (n, wanted) in expected.iter().enumerate() {
271        setup.before_frame(&mut system);
272        system.run_frame();
273        let line = frame_line(&mut system);
274        if &line != wanted {
275            return Err(format!(
276                "frame {} differs after a snapshot was put back\n  expected {wanted}\n  got      {line}",
277                n + 1
278            ));
279        }
280        let snapshot = save_snapshot(&system);
281        bytes = snapshot.len();
282        for _ in 0..ahead {
283            system
284                .board_mut()
285                .set_pressed(0, pads::RUN | pads::I | pads::RIGHT);
286            system.run_frame();
287        }
288        load_snapshot(&mut system, &snapshot)?;
289        if let Some(log) = system.board_mut().bus_log.as_mut() {
290            log.clear();
291        }
292    }
293    if save_state(&system) != save_state(&plain) {
294        return Err("the end state is not the plain run's".to_string());
295    }
296    Ok(format!(
297        "{frames} frames, {ahead} ahead of each, equal to the plain run; a snapshot is {bytes} bytes"
298    ))
299}