1use 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
42pub const BASE_MODE: Machine = Machine {
44 work_ram_bytes: SUPERGRAFX.work_ram_bytes,
45 ..Machine::new("SuperGrafx (base mode)", true)
46};
47
48pub 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#[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 pub rest: Vec<String>,
100}
101
102impl SgxSetup {
103 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 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 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 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
218pub 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
262pub 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}