cge_nes 0.1.2

Cycle-accurate NES (Nintendo Entertainment System) emulator library: CPU, PPU, cartridge, input, and iNES ROM loading.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
//! PPU cycle-by-cycle emulation and rendering logic.
//!
//! This module handles the core PPU rendering pipeline, including:
//! * Cycle-accurate PPU state machine emulation
//! * Background tile fetching and rendering
//! * Sprite evaluation and rendering
//! * Per-scanline timing and synchronization
//! * Frame events (VBlank, NMI generation)
//!
//! The PPU processes one pixel per cycle during visible scanlines,
//! with additional cycles used for internal operations and fetching tile data.
//! The rendering pipeline is carefully timed to match real NES hardware behavior.

#[cfg(feature = "show_name_table_change")]
use crate::ppu::palette::{Color, EmphasisFlags};
use crate::ppu::ppu_render_pixel::BgTileToShow;
use crate::ppu::prepare_scanline::*;
use crate::ppu::registers::Registers;
use crate::ppu::scanline_pos::PpuState;
use crate::ppu::sprite::SpriteData;
use crate::ppu::vram_read_buffer::VramReadBuffer;
#[cfg(feature = "show_name_table_change")]
use crate::ppu::ScanlineEvent;
use crate::ppu::{
    FrameEvent, Ppu, PpuCartMemorySpace, SpriteDataArray, VramReadEvent, SCREEN_WIDTH, TILE_DIM,
};

const NAME_TABLE_ROW_COUNT: u16 = 30;
const NAME_TABLE_COL_COUNT: u16 = 32;

/// Returns true on cycles where the VRAM address coarse X should increment.
///
/// NES PPU increments the horizontal scroll every 8 cycles while fetching background
/// data. Within a visible scanline, this occurs for pixels 1..=256 on every tile
/// boundary (x % 8 == 0). During the tile prefetch at the end of the scanline, it also
/// increments at cycles 328 and 336. Cycle 0 and 337..=340 do not increment.
///
/// The function expects the position within the current scanline (0..=340) and mirrors
/// the hardware behavior described above. It does not check PPU rendering-enable flags;
/// the caller is responsible for gating by rendering state.
fn must_increment_vram_addr_horizontal(pos_at_scanline: u16) -> bool {
    if pos_at_scanline % 8 == 0 {
        if ((pos_at_scanline > 0) && (pos_at_scanline <= 256))
            || (pos_at_scanline == 328)
            || (pos_at_scanline == 336)
        {
            return true;
        }
    }
    false
}

/// Computes the pattern-table address of the row of `sprite` that is being
/// scanned on `screen_y`, taking the sprite's vertical-flip flag and the
/// large-sprites bit into account.
fn get_row_addr_for_sprite(sprite: &SpriteData, screen_y: u8, regs: &Registers) -> u16 {
    // Calculate the base address in the pattern table for this sprite
    let sprite_base_addr = sprite_base_address_in_pattern_table(sprite.obj_attributes(), &regs);
    // Determine the local Y offset within the sprite
    let local_y = screen_y.wrapping_sub(sprite.obj_attributes().y()).wrapping_sub(1);
    // Check if the sprite is vertically flipped
    let vertical_flip = sprite.obj_attributes().vertical_flip_flag();

    // Compute the address for the correct row in the pattern table
    set_fine_y_offset_to_pattern_table_addr(
        sprite_base_addr,
        local_y,
        vertical_flip,
        regs.large_sprites_flag(),
    )
}

/// Fetches the pattern-table bytes for the row of `sprite` currently being
/// scanned and stores them on the [`SpriteData`].
fn update_sprite_color_rows(
    sprite: &mut SpriteData,
    screen_y: u8,
    regs: &Registers,
    cart_memory: &mut impl PpuCartMemorySpace,
) {
    // Compute the address for the correct row in the pattern table
    let row_addr = get_row_addr_for_sprite(sprite, screen_y, &regs);
    // Fetch the color index bytes for this row
    let color_rows = get_color_index_row_bytes_from_pattern_table(row_addr, cart_memory);

    // Update the sprite's row color index bytes
    sprite.set_row_color_index_bytes(color_rows);
}

/// Updates the color row bytes for all sprites in the current scanline.
///
/// # Parameters
/// * `screen_y` - The Y coordinate of the current scanline (0-239)
/// * `sprites_for_scanline` - Array of sprites to be rendered on this scanline
/// * `regs` - PPU register state for pattern table selection and sprite size
/// * `cart_memory` - Memory interface for reading pattern table data
fn update_sprites_color_rows(
    screen_y: u8,
    sprites_for_scanline: &mut SpriteDataArray,
    regs: &Registers,
    cart_memory: &mut impl PpuCartMemorySpace,
) {
    // Iterate over each sprite in the scanline
    for sprite in sprites_for_scanline {
        update_sprite_color_rows(sprite, screen_y, regs, cart_memory);
    }
}

/// Build the background tile for the current pixel from the VRAM read buffer front.
///
/// The VRAM fetch pipeline continuously preloads nametable, attribute, and pattern
/// bytes ahead of the pixel being drawn. This function consumes the oldest
/// pipeline entry (by reading from the front of VramReadBuffer) to assemble a
/// BgTileToShow: it combines the two pattern bitplanes for the current row and
/// selects the palette quadrant from the attribute byte based on the tile's
/// coarse coordinates within the nametable.
///
/// Note: This does not pop the buffer; the caller should pop when the last pixel
/// of a tile column is reached so that front stays aligned with the current tile.
fn find_current_bg_tile(vram_read_buffer: &VramReadBuffer) -> BgTileToShow {
    let coords_in_table = vram_read_buffer.front_coords_in_name_table();

    // Get color bytes for the current tile row
    let row_colors = (
        vram_read_buffer.front_bg_high_data(),
        vram_read_buffer.front_bg_low_data(),
    );
    // Get the palette index for the current tile row
    let attribute_byte = vram_read_buffer.front_attr_data();
    let palette_index = palette_index_in_name_table3(coords_in_table, attribute_byte);

    // Return the background tile information
    BgTileToShow::new(row_colors, palette_index)
}

/// Determines whether sprites should be shown at the given screen coordinates.
///
/// # Parameters
/// * `screen_coords` - Tuple of (x,y) coordinates on screen (0-255, 0-239)
/// * `regs` - PPU register state containing sprite rendering flags
///
/// # Returns
/// `true` if sprites should be rendered at these coordinates, `false` otherwise
fn show_sprites(screen_coords: (u8, u8), regs: &Registers) -> bool {
    // Check if the current pixel is in the leftmost 8 pixels
    let left_most_tile = screen_coords.0 < TILE_DIM;

    // Sprites are shown if enabled, and either not in the leftmost tile or leftmost sprite rendering is enabled
    regs.show_sprites_flag() && (!left_most_tile || regs.show_sprites_leftmost_flag())
}

impl Ppu {
    /// Returns whether an NMI (Non-Maskable Interrupt) should be signaled by the PPU.
    ///
    /// # Returns
    /// `true` if an NMI should be generated, `false` otherwise
    pub fn nmi_signal(&self) -> bool {
        // Return the current NMI signal state
        self.nmi_signal
    }

    /// Advance one step of the background VRAM fetch pipeline based on the current cycle.
    ///
    /// The PPU fetches background data in a repeating 8-cycle pattern per tile:
    /// - Compute/push nametable address (TileAddrSet)
    /// - Read nametable byte (TileDataRead)
    /// - Compute/push attribute address (AttrAddrSet)
    /// - Read attribute byte (AttrDataRead)
    /// - Compute/push background low pattern address (BackgroundLowAddrSet)
    /// - Read low pattern byte (BackgroundLowDataRead)
    /// - Compute/push background high pattern address (BackgroundHighAddrSet)
    /// - Read high pattern byte; upon read, a new pipeline entry is started (BackgroundHighDataRead)
    ///
    /// This function consults the timing state machine (scanline_pos) to know which
    /// event should occur on the current cycle, performs any address calculations
    /// using the VRAM address components in registers, and reads bytes from the
    /// cartridge memory interface. Results are staged in VramReadBuffer so that
    /// the oldest entry corresponds to the tile currently being drawn.
    #[inline]
    fn run_vram_read_event(&mut self, cart_memory: &mut impl PpuCartMemorySpace) {
        // Step one event of the 8-cycle BG fetch pipeline (addr set vs data read).
        let event = self.scanline_pos.current_vram_read_event();
        match event {
            VramReadEvent::None => {
                // idle
            }
            VramReadEvent::TileAddrSet => {
                // compute nametable addr and record coarse coords
                let vram_addr_components = &self.regs.v_addr_components();
                let tile_address_in_name_table = vram_addr_components.build_nametable_address();
                self.vram_read_buffer
                    .set_tile_addr(tile_address_in_name_table);

                let coords_in_table = (
                    vram_addr_components.coarse_x as u16 % NAME_TABLE_COL_COUNT,
                    vram_addr_components.coarse_y as u16 % NAME_TABLE_ROW_COUNT,
                );
                self.vram_read_buffer
                    .set_coords_in_name_table(coords_in_table);

                self.vram_read_buffer
                    .set_second_bg_table_selected(self.regs.bg_second_table_selected());
            }
            VramReadEvent::TileDataRead => {
                // read nametable byte (tile index)
                let tile_index = cart_memory.read(self.vram_read_buffer.back_tile_addr());
                self.vram_read_buffer.set_tile_data(tile_index);
            }
            VramReadEvent::AttrAddrSet => {
                // compute attribute table addr
                let attr_address = self.regs.v_addr_components().build_attribute_address();
                self.vram_read_buffer.set_attr_addr(attr_address);
            }
            VramReadEvent::AttrDataRead => {
                // read attribute byte
                let attribute = cart_memory.read(self.vram_read_buffer.back_attr_addr());
                self.vram_read_buffer.set_attr_data(attribute);
            }
            VramReadEvent::BackgroundLowAddrSet => {
                // compute low bitplane row addr for fine Y
                let tile_index = self.vram_read_buffer.back_tile_data();
                let second_bg_table_selected =
                    self.vram_read_buffer.back_bg_second_table_selected();
                let tile_base_addr =
                    bg_base_address_in_pattern_table(tile_index, second_bg_table_selected);
                let row_addr = set_fine_y_offset_to_pattern_table_addr(
                    tile_base_addr,
                    self.regs.v_addr_components().fine_y,
                    false,
                    false,
                );
                let row_addr = row_addr & 0x1FF7;
                self.vram_read_buffer.set_bg_low_addr(row_addr);
            }
            VramReadEvent::BackgroundLowDataRead => {
                // read low bitplane byte
                let bg_low_byte = cart_memory.read(self.vram_read_buffer.back_bg_low_addr());
                self.vram_read_buffer.set_bg_low_data(bg_low_byte);
            }
            VramReadEvent::BackgroundHighAddrSet => {
                // compute high bitplane row addr for fine Y
                let tile_index = self.vram_read_buffer.back_tile_data();
                let second_bg_table_selected =
                    self.vram_read_buffer.back_bg_second_table_selected();
                let tile_base_addr =
                    bg_base_address_in_pattern_table(tile_index, second_bg_table_selected);
                let row_addr = set_fine_y_offset_to_pattern_table_addr(
                    tile_base_addr,
                    self.regs.v_addr_components().fine_y,
                    false,
                    false,
                );
                let row_addr = (row_addr & 0x1FF7) | 0b_1000;
                self.vram_read_buffer.set_bg_high_addr(row_addr);
            }
            VramReadEvent::BackgroundHighDataRead => {
                // read high bitplane byte
                let bg_high_byte = cart_memory.read(self.vram_read_buffer.back_bg_high_addr());
                self.vram_read_buffer.set_bg_high_data(bg_high_byte);
            }
            VramReadEvent::SpriteAddrSet {
                sprite_index,
                is_high_byte,
            } => {
                // Sprite fetch cycles only happen during the second-half garbage
                // fetch on cycles 257-320. When cycle-accurate sprite reads are
                // requested (e.g. for MMC3 IRQ emulation), compute the pattern
                // table address of the sprite row for the next scanline and
                // latch it in `sprite_addr` so the following data-read event
                // knows where to read from.
                if self.cycle_accurate_sprites_enabled {
                    let next_y = if self.scanline_pos.current_scanline() < 261 {
                        self.scanline_pos.current_scanline() as u8 + 1
                    } else {
                        (self.scanline_pos.current_scanline() - 261) as u8 + 1
                    };
                    let row_addr = if let Some(sprite) =
                        self.sprites_for_next_scanline.get(sprite_index as usize)
                    {
                        let row_addr = get_row_addr_for_sprite(sprite, next_y, &self.regs);
                        if is_high_byte {
                            row_addr | 0b_1000
                        } else {
                            row_addr
                        }
                    } else {
                        0x1FFF
                    };

                    //self.regs.set_v(row_addr);
                    self.sprite_addr = row_addr;
                }
            }
            VramReadEvent::SpriteDataRead {
                sprite_index,
                is_high_byte,
            } => {
                // Reads from `sprite_addr` (latched by the matching SpriteAddrSet)
                // and stores the byte into the matching sprite's row color index
                // for the next scanline. `is_high_byte` selects the high or low
                // bitplane so both bytes for the same row end up in the same entry.
                if self.cycle_accurate_sprites_enabled {
                    let row_byte = cart_memory.read(self.sprite_addr);
                    if let Some(sprite) = self
                        .sprites_for_next_scanline
                        .get_mut(sprite_index as usize)
                    {
                        sprite.set_row_color_index_byte(row_byte, is_high_byte);
                    }
                }
            }
        }
    }

    /// Runs a single PPU cycle, advancing timing, fetching data, and possibly rendering a pixel.
    ///
    /// Behavior depends on the current PPU state (pre-render, rendering, post-render, vblank).
    /// During rendering scanlines, it may:
    /// - Prepare sprites at x==0
    /// - Latch or clear background tile cache and compute final pixel color for visible x
    /// - Step the VRAM fetch pipeline once per cycle via run_vram_read_event
    ///
    /// It also performs VRAM address maintenance outside of vblank:
    /// - At x==256: increment vertical VRAM address (fine Y/coarse Y with carry into nametable Y)
    /// - At x==257: copy horizontal scroll bits (coarse X/nametable X) into current VRAM address
    /// - At x in {1..=256} where x%8==0, and at x==328 or x==336: increment coarse X
    ///   (see must_increment_vram_addr_horizontal)
    ///
    /// Finally, it updates the NMI signal based on vblank status and PPUCTRL.
    ///
    /// # Parameters
    /// * `cart_memory` - Memory interface for accessing pattern tables and name tables
    ///
    /// # Returns
    /// A `FrameEvent` indicating any significant rendering events that occurred
    #[inline]
    pub fn run_cycle(&mut self, cart_memory: &mut impl PpuCartMemorySpace) -> FrameEvent {
        // Get the current PPU state (pre-render, rendering, post-render, vblank)
        let current_state = self.scanline_pos.current_state();

        #[cfg(test)]
        {
            let x = self.scanline_pos.pos_at_scanline();
            let y = self.scanline_pos.current_scanline();
            if x == 0 {
                let pixels_drawn = self.screen_colors.len();
                println!("starting {current_state:?} {y}: {pixels_drawn} pixels drawn");
            }
        }

        // Run the appropriate logic for the current PPU state
        match current_state {
            PpuState::PreRenderScanline => self.run_pre_render_cycle(cart_memory),
            PpuState::Rendering => self.run_render_cycle(cart_memory),
            PpuState::PostRenderScanline => {
                debug_assert_eq!(self.screen_colors.len(), self.screen_colors.capacity())
            }
            PpuState::VBlank => self.run_vblank_cycle(),
        }

        // Update VRAM address components based on current state and position in scanline
        if current_state != PpuState::VBlank {
            match self.scanline_pos.pos_at_scanline() {
                256 => self.regs.vram_addr_increment_vertical(),
                257 => self.regs.vram_addr_update_horizontal_bits(),
                _ => (),
            }

            if must_increment_vram_addr_horizontal(self.scanline_pos.pos_at_scanline()) {
                self.regs.vram_addr_increment_horizontal();
            }
        }

        // Update the NMI signal based on vblank and NMI enable flag
        self.nmi_signal = self.regs.vblank_started() && self.regs.nmi_enabled();

        // Get the current frame event (if any)
        let frame_event = self.scanline_pos.current_frame_event();

        #[cfg(test)]
        {
            self.cycles_since_reset += 1;
        }

        #[cfg(test)]
        if (frame_event != FrameEvent::None) && (frame_event != FrameEvent::EndOfScanline) {
            println!("{frame_event:?}\t\t {} cycles", self.cycles_since_reset);
        }

        // Advance to the next PPU cycle
        self.scanline_pos.advance_cycle();
        self.regs.update_render_toggle_buffers();

        #[cfg(feature = "show_name_table_change")]
        {
            self.last_event = ScanlineEvent::None;
        }

        frame_event
    }

    /// Handles logic for the pre-render scanline.
    ///
    /// Called during the pre-render scanline (-1) to prepare for the next frame.
    fn run_pre_render_cycle(&mut self, cart_memory: &mut impl PpuCartMemorySpace) {
        // On the second PPU cycle of the pre-render scanline, clear status flags
        if self.scanline_pos.pos_at_scanline() == 1 {
            self.regs.frame_begin_clear_flags();
        }

        self.run_vram_read_event(cart_memory);

        match self.scanline_pos.pos_at_scanline() {
            280..=304 => {
                self.regs.vram_addr_update_vertical_bits();
            }
            _ => (),
        }
    }

    /// Handles rendering logic for a visible scanline.
    ///
    /// # Parameters
    /// * `cart_memory` - Memory interface for accessing pattern tables and name tables
    #[inline]
    fn run_render_cycle(&mut self, cart_memory: &mut impl PpuCartMemorySpace) {
        // Get the current pixel coordinates
        let x = self.scanline_pos.pos_at_scanline();
        let y = self.scanline_pos.current_scanline() as u8;

        // At the start of a scanline, clear per-scanline state and prepare sprites
        if x == 0 {
            if y == 0 {
                self.screen_colors.clear();
            }
            self.prepare_scanline(cart_memory);
        }

        // Only render visible pixels
        if x < SCREEN_WIDTH {
            #[cfg(feature = "show_name_table_change")]
            if self.last_event == ScanlineEvent::ShowBg {
                self.screen_colors
                    .push(Color::new(0x19, EmphasisFlags::empty()));
                return;
            } else if self.last_event == ScanlineEvent::DontShowBg {
                self.screen_colors
                    .push(Color::new(0x16, EmphasisFlags::empty()));
                return;
            }

            // Handle sprite evaluation for the current pixel
            if self.sprites_start_col.len() > 0 {
                let start_col = unsafe { self.sprites_start_col.get_unchecked(0) };
                if x == start_col.x as u16 {
                    self.sprite_zero_pos = u8::MAX;

                    self.sprites_start_col.remove(0);
                    self.sprites_at_current_pixel.clear();

                    // Add every sprite that covers this pixel, in OAM order.
                    for sprite in self.sprites_for_scanline.iter() {
                        if sprite.obj_attributes().x() as u16 <= x {
                            if (sprite.obj_attributes().x() as u16 + 8) > x {
                                if sprite.oam_index() == 0 {
                                    self.sprite_zero_pos =
                                        self.sprites_at_current_pixel.len() as u8;
                                }
                                self.sprites_at_current_pixel.push(*sprite);
                            }
                        }
                    }
                }
            }

            let x = x as u8;
            let screen_coords = (x, y);

            // Update the background tile cache for this pixel
            self.update_bg_tile(screen_coords);

            // Determine if sprites should be shown at this pixel
            let show_sprites = show_sprites(screen_coords, &self.regs);
            // Calculate the final color for this pixel
            let color = self.calculate_pixel_color_index((x, y), self.bg_tile, show_sprites);
            // Store the color in the framebuffer
            self.screen_colors.push(color);
        }

        self.run_vram_read_event(cart_memory);
    }

    /// Updates which background tile row should be used for the current pixel.
    ///
    /// Applies scroll to the current screen coordinates, respects leftmost-8 masking
    /// from PPUMASK, and decides when to latch a new tile from the VRAM read buffer.
    /// A new BgTileToShow is constructed when either rendering resumes after being
    /// masked or the scrolled X crosses a tile boundary (x % 8 == 0). When the last
    /// pixel of a tile column is reached (x % 8 == 7), the front entry of the
    /// VramReadBuffer is popped so the next tile becomes current.
    ///
    /// # Parameters
    /// * `screen_coords` - Tuple of (x,y) coordinates on screen (0-255, 0-239)
    #[inline]
    fn update_bg_tile(&mut self, screen_coords: (u8, u8)) {
        // Check if the current pixel is in the leftmost 8 pixels
        let left_most_tile = screen_coords.0 < TILE_DIM;

        // Get the current scroll values and apply them to the screen coordinates
        let scroll = self.regs.scroll();
        let scrolled_coords = (
            screen_coords.0.wrapping_add(scroll.0),
            screen_coords.1.wrapping_add(scroll.1),
        );

        // If background rendering is enabled for this pixel, update the background tile cache
        if self.regs.show_bg_flag() && (!left_most_tile || self.regs.show_bg_leftmost_flag()) {
            if self.bg_tile.is_none() || ((scrolled_coords.0 % TILE_DIM) == 0) {
                self.bg_tile = Some(find_current_bg_tile(&self.vram_read_buffer));
            }
        } else {
            self.bg_tile = None;
        }

        // If we just finished a tile column, pop the front entry from the buffer to start the next tile
        if (scrolled_coords.0 % TILE_DIM) == (TILE_DIM - 1) {
            self.vram_read_buffer.pop_front();
        }
    }

    /// Handles logic for the vblank period.
    ///
    /// Called during vblank scanlines (241-260) to handle vblank status flags.
    fn run_vblank_cycle(&mut self) {
        // On the first scanline and first cycle of vblank, set the vblank flag
        if self.scanline_pos.first_vblank_scanline() {
            if self.scanline_pos.pos_at_scanline() == 0 {
                self.regs.start_vblank();
            }
        }
    }

    /// Prepares sprite and background data for the next scanline.
    ///
    /// When [`cycle_accurate_sprites_enabled`] is false, this is the only
    /// place where the renderer reads CHR ROM/RAM for sprites and the pattern
    /// data is cached on the [`SpriteData`] immediately. When the flag is set
    /// (typically because the cartridge's mapper needs the extra CHR reads to
    /// drive a scanline counter, e.g. MMC3), the pattern data is *not* read
    /// here; it will be read cycle-by-cycle during the sprite fetch window at
    /// cycles 257..=320 of the current scanline and stored against the sprites
    /// prepared for the *next* scanline.
    ///
    /// # Parameters
    /// * `cart_memory` - Memory interface for accessing pattern tables and name tables
    fn prepare_scanline(&mut self, cart_memory: &mut impl PpuCartMemorySpace) {
        // Clear background state
        self.bg_tile = None;

        // Get the current scanline number
        let y = self.scanline_pos.current_scanline() as u8;

        self.sprites_at_current_pixel.clear();
        // If sprite rendering is enabled, prepare sprite data for this scanline
        if true && self.regs.show_sprites_flag() {
            let (sprites, y) = if self.cycle_accurate_sprites_enabled {
                // Cycle-accurate mode: we are preparing sprites for the NEXT
                // scanline, so promote the previously-prepared set and start
                // a fresh one for the line after this.
                self.sprites_for_scanline = self.sprites_for_next_scanline.clone();
                (&mut self.sprites_for_next_scanline, y + 1)
            } else {
                (&mut self.sprites_for_scanline, y)
            };
            let large_sprites = self.regs.large_sprites_flag();
            let overflow = prepare_sprites_for_scanline(y, large_sprites, &self.oam, sprites);
            if overflow {
                self.regs.set_sprite_overflow();
            }

            if !self.cycle_accurate_sprites_enabled {
                // Eagerly read the sprite row now; this is what the cycle-
                // accurate code path skips so the CHR access happens later.
                update_sprites_color_rows(y, sprites, &self.regs, cart_memory);
            }

            sort_sprites_by_col(&self.sprites_for_scanline, &mut self.sprites_start_col);
        } else {
            self.sprites_for_scanline.clear();
        }
    }
}

#[cfg(test)]
mod test {
    use super::*;
    use crate::ppu::oam;
    use crate::ppu::sprite::SpriteData;
    use crate::ppu::Register;

    struct MockPpuMem;

    impl PpuCartMemorySpace for MockPpuMem {
        fn read(&mut self, addr: u16) -> u8 {
            match addr {
                // Second pattern table, tile row 10, tile col 5, pixel row 2, lower plane
                0b_0001_1010_0101_0010 => 0xCC,
                // Second pattern table, tile row 10, tile col 5, pixel row 2, higher plane
                0b_0001_1010_0101_1010 => 0xAA,
                // Fourth name table, name row 1, name col 1
                0x2C21 => 0b_1010_0101,
                // Fourth name table, attr row 0, attr col 0
                0x2FC0 => 0b_0000_0010,
                _ => 0xFF,
            }
        }

        fn write(&mut self, _data: u8, _addr: u16) {
            unreachable!()
        }
    }

    #[test]
    fn sprite_color_rows() {
        let mut mem = MockPpuMem;
        let mut regs = Registers::default();
        regs.write_register(0b_0001_1011, Register::PpuControl);

        let mut sprites = SpriteDataArray::new();

        let sprite_data =
            SpriteData::with_oam_index(oam::Entry::with_data(1, 165, Default::default(), 5), 0);
        sprite_data.obj_attributes().set_palette(4);
        sprites.push(sprite_data);

        update_sprites_color_rows(4, &mut sprites, &regs, &mut mem);

        assert_eq!(sprites[0].row_color_index_bytes(), Some((0xAA, 0xCC)));
    }

    //#[test]
    //fn bg_color_rows() {
    //    let mut mem = MockPpuMem;
    //    let mut regs = Registers::default();
    //    regs.write_register(0b_0001_1011, Register::PpuControl);
    //
    //    let tile = find_current_bg_tile(&regs, (8, 10), &mut mem);
    //
    //    assert_eq!(tile.row_color_index_bytes(), (0xAA, 0xCC));
    //    assert_eq!(tile.palette_index(), 2);
    //}
}