pcengine_rust/vdc/sequencer.rs
1//! The VDC's vertical state machine and the horizontal events of one line (`vdc/sequencer.py`).
2//!
3//! Provisional, emulator tier 5 (U19): no tier 1-3 source gives the dot at which the vblank flag
4//! rises or the raster compare fires. This is Mednafen's `huc6270/vdc.cpp` (HSync/VSync/IncRCR
5//! and the HPHASE machine), restated in master clocks so that it runs from the board's one
6//! timeline. What *is* published: the frame layout and "VDS+VSW lines before the first active
7//! line", [hw: pcetech 7]; the flag rules of status bit 5 [hw: pcetech 5]; the RCR range
8//! $40-$146 counted from the first active line [hw: pcetech 5.1].
9//!
10//! Vertical phases run VSW -> VDS -> VDW -> VCR -> VSW, counted once per line at the end of the
11//! displayed width (4 dots before it ends: Mednafen's HDW_FINAL). The VCE starts the VSW phase at
12//! the vertical sync, which is the last three lines of its frame, so with VSW = $02 and VDS = $17
13//! the first line of the display period is frame line 25, as pcetech 7 says.
14//!
15//! Horizontal events within a line (dot = the VCE's dot divider in master clocks, measured from the
16//! VCE's hsync start at the line's origin):
17//!
18//! ```text
19//! origin + 237 hsync ends (`HSYNC_CLOCKS`, emu)
20//! + 8 dots HDS: the display-start phase begins; a pending line counter step
21//! from the previous line is taken here if not yet done
22//! + (HDS + 1) * 8 dots HDW: the display width begins; vblank flag test, sprite scan (M3)
23//! + (HDW + 1) * 8 - 4 HDW final: the line counter steps (RCR compare, phase counters)
24//! ```
25//!
26//! Differences forced by Rust: `Sequencer` is the state; its methods are `impl Vdc` here, with
27//! the reference's names behind `seq_` (the reference's sequencer calls back into the chip
28//! through a reference). The event kinds are an enum where the reference has strings; the
29//! list is kept sorted by time with a stable sort, as the reference's `list.sort` is.
30
31use serde::{Deserialize, Serialize};
32
33use crate::machine::HSYNC_CLOCKS;
34use crate::vdc::chip::Vdc;
35
36#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
37pub enum VPhase {
38 Vsw = 0,
39 Vds = 1,
40 Vdw = 2,
41 Vcr = 3,
42}
43
44impl VPhase {
45 fn following(self) -> VPhase {
46 match self {
47 VPhase::Vsw => VPhase::Vds,
48 VPhase::Vds => VPhase::Vdw,
49 VPhase::Vdw => VPhase::Vcr,
50 VPhase::Vcr => VPhase::Vsw,
51 }
52 }
53}
54
55/// [emu: Mednafen `Cycles_Between_RCRIRQ_And_HDWEnd = 4`]
56pub const FINAL_DOTS: i64 = 4;
57/// [emu: Mednafen HSW phase counter 8 after leaving hsync]
58pub const HSW_DOTS: i64 = 8;
59
60#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
61pub enum Event {
62 Byr,
63 Bxr,
64 Leave,
65 Collision,
66 Vblank,
67 Hds,
68 Hdw,
69 Final,
70}
71
72/// State and events only; the chip owns the registers.
73#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
74pub struct Sequencer {
75 /// The vblank flag test happens this many dots after the sync ends (negative: before it
76 /// ends).
77 ///
78 /// Default -8 (U19, provisional, tier 1): the position that fits Covell's hardware
79 /// photographs best, anchored on the test's own text (docs/m1-record.md): 0, MAME's, leaves
80 /// the splits 7-13 dots right of the hardware's; -8 leaves -0.6 to +6.6. None is Mednafen's,
81 /// the start of the display width (32 dots on for HDS = 2), which Covell calls too late.
82 pub vblank_dots: Option<i64>,
83 /// Experiment (MAME's `huc6270.cpp`): the vertical phase counters step as each line
84 /// *starts*, and the vblank flag is raised as the display period ends; Mednafen's (the
85 /// default) step 4 dots before the end of each line's display width, almost a line later.
86 pub vertical_at_line_start: bool,
87 /// [emu: Mednafen Reset] power-up phase VDS with one line left; arbitrary but fixed (U1).
88 pub vphase: VPhase,
89 pub vphase_counter: i64,
90 pub rcr_count: i64,
91 pub scanline_from_vsync: i64,
92 pub need_rcr_inc: bool,
93 pub need_vb_irq_test: bool,
94 pub burst_mode: bool,
95 /// this line is in the display period and not burst
96 pub display_line: bool,
97 /// CR as the line's display start latched it
98 pub cr_cache: u16,
99 // cached at the vertical sync / start of the VSW phase
100 pub vds: i64,
101 pub vsw: i64,
102 pub vdw: i64,
103 pub vcr: i64,
104 // line geometry, set by hsync()
105 pub divider: i64,
106 pub origin: i64,
107 pub hds_start: i64,
108 pub active_start: i64,
109 pub final_at: i64,
110 pub active_end: i64,
111 events: Vec<(i64, Event)>,
112 next_line: (i64, i64, i64, i64),
113}
114
115impl Sequencer {
116 pub fn new(vblank_dots: Option<i64>, vertical_at_line_start: bool) -> Sequencer {
117 Sequencer {
118 vblank_dots,
119 vertical_at_line_start,
120 vphase: VPhase::Vds,
121 vphase_counter: 1,
122 rcr_count: 0,
123 scanline_from_vsync: 0,
124 need_rcr_inc: false,
125 need_vb_irq_test: false,
126 burst_mode: false,
127 display_line: false,
128 cr_cache: 0,
129 vds: 0,
130 vsw: 0,
131 vdw: 0,
132 vcr: 0,
133 divider: 4,
134 origin: 0,
135 hds_start: 0,
136 active_start: 0,
137 final_at: 0,
138 active_end: 0,
139 events: Vec::new(),
140 next_line: (0, 4, 0, 0),
141 }
142 }
143
144 /// The current line is in the display period and not burst (valid from HDW start).
145 #[inline]
146 pub fn active_display(&self) -> bool {
147 self.display_line
148 }
149
150 fn sort(&mut self) {
151 self.events.sort_by_key(|event| event.0);
152 }
153}
154
155impl Vdc {
156 // -- the board's hooks ------------------------------------------------------------------------
157
158 #[inline]
159 pub(crate) fn seq_next_event(&self) -> Option<i64> {
160 self.seq.events.first().map(|event| event.0)
161 }
162
163 pub(crate) fn seq_run_to(&mut self, mclk: i64) {
164 while !self.seq.events.is_empty() && self.seq.events[0].0 <= mclk {
165 let (when, kind) = self.seq.events.remove(0);
166 self.now = when;
167 match kind {
168 Event::Byr => self.latch_byr(),
169 Event::Bxr => self.latch_bxr(),
170 Event::Leave => self.seq_leave_hsync(),
171 Event::Collision => self.collision_hit(),
172 Event::Vblank => self.seq_vblank(),
173 Event::Hds => self.seq_hds(),
174 Event::Hdw => self.seq_hdw(),
175 Event::Final => self.seq_final(),
176 }
177 }
178 }
179
180 /// The VCE's horizontal sync starts: cache the horizontal registers; the line proper
181 /// begins when the sync ends. Events of the previous line may still be pending: with
182 /// HDS = 2 and HDW = $1F a 5 MHz line's width-end lands 8 master clocks into the next
183 /// line's sync, and it must still run (emu: Mednafen caches at sync start, restarts at
184 /// sync end).
185 pub(crate) fn seq_hsync(&mut self, mclk: i64, divider: i64) {
186 self.seq.next_line = (mclk, divider, self.regs.hds(), self.regs.hdw());
187 self.seq.events.push((mclk + HSYNC_CLOCKS, Event::Leave));
188 if let Some(vblank_dots) = self.seq.vblank_dots {
189 if vblank_dots < 0 {
190 // before the sync ends: the line's own events do not exist yet
191 self.seq
192 .events
193 .push((mclk + HSYNC_CLOCKS + vblank_dots * divider, Event::Vblank));
194 }
195 }
196 self.seq.sort();
197 }
198
199 fn seq_leave_hsync(&mut self) {
200 let (origin, divider, hds, hdw) = self.seq.next_line;
201 let seq = &mut self.seq;
202 seq.origin = origin;
203 seq.divider = divider;
204 seq.hds_start = origin + HSYNC_CLOCKS + HSW_DOTS * divider;
205 seq.active_start = seq.hds_start + (hds + 1) * 8 * divider;
206 seq.active_end = seq.active_start + (hdw + 1) * 8 * divider;
207 seq.final_at = seq.active_end - FINAL_DOTS * divider;
208 if self.seq.vertical_at_line_start {
209 self.seq_advance_vertical();
210 }
211 // Stale events of the previous line are dropped, as Mednafen's HPhase is overwritten.
212 // [emu: Mednafen TimeFromHDSStartToBYRLatch / TimeFromBYRLatchToBXRLatch] the scroll
213 // registers are latched a few dots after the display-start phase begins: BYR at dot 1,
214 // BXR at dot 3 for HDS <= 2; later and one dot apart for a wider HDS (U3).
215 let to_byr = if hds <= 2 { 1 } else { (hds + 1) * 8 - 21 };
216 let to_bxr = to_byr + if hds <= 2 { 2 } else { 1 };
217 let seq = &mut self.seq;
218 // (the fork: the list's own buffer again)
219 seq.events.clear();
220 seq.events.extend_from_slice(&[
221 (seq.hds_start, Event::Hds),
222 (seq.hds_start + to_byr * divider, Event::Byr),
223 (seq.hds_start + to_bxr * divider, Event::Bxr),
224 (seq.active_start, Event::Hdw),
225 (seq.final_at, Event::Final),
226 ]);
227 if let Some(vblank_dots) = seq.vblank_dots {
228 if vblank_dots >= 0 {
229 seq.events
230 .push((origin + HSYNC_CLOCKS + vblank_dots * divider, Event::Vblank));
231 seq.sort();
232 }
233 }
234 }
235
236 /// Run `kind` at `mclk` (a time inside the current line).
237 pub(crate) fn seq_schedule(&mut self, mclk: i64, kind: Event) {
238 self.seq.events.push((mclk, kind));
239 self.seq.sort();
240 }
241
242 /// The vertical sync starts (the last three lines of the VCE's frame).
243 ///
244 /// Deviation from Mednafen (tier 5), which drops the previous line's pending line-counter
245 /// step here: pcetech 5.1 (tier 2) gives RCR a range of 263 values ($40-$146) counted from
246 /// the first active line, so a 263-line frame must make 263 steps and the step is taken
247 /// now instead (U19).
248 pub(crate) fn seq_vsync(&mut self) {
249 if self.seq.need_rcr_inc {
250 self.seq_inc_rcr();
251 self.seq.need_rcr_inc = false;
252 }
253 if self.seq.vphase == VPhase::Vdw {
254 // [emu: Mednafen] the SAT transfer test runs whenever the phase is not VDW after the
255 // display period began, so a VDW that the sync cuts short (Rastan Saga II: VDS $18,
256 // VDW $FF) still transfers (C27, found by the M5 sweep).
257 self.display_ended();
258 }
259 self.seq_cache_vertical();
260 self.seq.vphase = VPhase::Vsw;
261 self.seq.vphase_counter = self.seq.vsw + 1;
262 self.seq.scanline_from_vsync = 0;
263 }
264
265 // -- events -----------------------------------------------------------------------------------
266
267 fn seq_hds(&mut self) {
268 self.seq.cr_cache = self.regs.cr();
269 if self.seq.need_rcr_inc {
270 self.seq_inc_rcr();
271 self.seq.need_rcr_inc = false;
272 }
273 }
274
275 fn seq_hdw(&mut self) {
276 self.seq.display_line = self.seq.vphase == VPhase::Vdw && !self.seq.burst_mode;
277 self.render_line();
278 self.seq.need_rcr_inc = true;
279 if self.seq.vblank_dots.is_none() && !self.seq.vertical_at_line_start {
280 self.seq_vblank();
281 }
282 self.commit_unless_dma();
283 }
284
285 fn seq_vblank(&mut self) {
286 if self.seq.vphase != VPhase::Vdw && self.seq.need_vb_irq_test {
287 self.seq.need_vb_irq_test = false;
288 self.vblank_test();
289 }
290 }
291
292 fn seq_final(&mut self) {
293 if self.seq.scanline_from_vsync == self.seq.vsw + 1 {
294 // [emu: Mednafen] burst mode is decided once a frame, from CR as the display
295 // period begins; pcetech 5.1 "locked when the next frame starts" (footnote 1).
296 self.seq.burst_mode = self.regs.cr() & 0xC0 == 0;
297 if self.seq.burst_mode {
298 self.burst_began();
299 }
300 }
301 if self.seq.need_rcr_inc {
302 self.seq_inc_rcr();
303 self.seq.need_rcr_inc = false;
304 }
305 }
306
307 fn seq_cache_vertical(&mut self) {
308 self.seq.vds = self.regs.vds();
309 self.seq.vsw = self.regs.vsw();
310 self.seq.vdw = self.regs.vdw();
311 self.seq.vcr = self.regs.vcr();
312 }
313
314 fn seq_inc_rcr(&mut self) {
315 self.line_counter_step(self.seq.rcr_count);
316 self.seq.rcr_count += 1;
317 if !self.seq.vertical_at_line_start {
318 self.seq_advance_vertical();
319 }
320 self.raster_test(self.seq.rcr_count);
321 if self.seq.vphase == VPhase::Vdw && !self.seq.burst_mode {
322 self.fetch_sprites(self.seq.rcr_count); // for the line about to be drawn
323 }
324 }
325
326 fn seq_advance_vertical(&mut self) {
327 self.seq.vphase_counter -= 1;
328 self.seq.scanline_from_vsync += 1;
329 if self.seq.vphase_counter <= 0 {
330 self.seq.vphase = self.seq.vphase.following();
331 if self.seq.vphase == VPhase::Vcr {
332 self.display_ended();
333 }
334 match self.seq.vphase {
335 VPhase::Vds => self.seq.vphase_counter = self.seq.vds + 2,
336 VPhase::Vdw => {
337 self.seq.vphase_counter = self.seq.vdw + 1;
338 self.seq.rcr_count = 0;
339 self.seq.need_vb_irq_test = true;
340 self.display_started();
341 }
342 VPhase::Vcr => {
343 self.seq.vphase_counter = self.seq.vcr;
344 if self.seq.vertical_at_line_start && self.seq.vblank_dots.is_none() {
345 self.seq.need_vb_irq_test = false;
346 self.vblank_test();
347 } else if self.seq.vertical_at_line_start {
348 // raised by the "vblank" event, N dots on
349 self.seq.need_vb_irq_test = true;
350 }
351 }
352 VPhase::Vsw => {
353 self.seq.vphase_counter = self.seq.vsw + 1;
354 self.seq.scanline_from_vsync = 0;
355 self.seq_cache_vertical();
356 }
357 }
358 }
359 }
360}