rsemu 0.0.0

A multiplatform emulator in pure Rust, built bottom-up on a generic framework.
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
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
//! Timing facts, asserted directly.
//!
//! Every test here names the NESdev page it comes from. A PPU test that only
//! says "the output looks right" is not a test of the thing that is hard.

use alloc::string::ToString;
use alloc::sync::Arc;
use alloc::vec::Vec;

use super::*;
use crate::core::clock::{ClockForest, Rational};
use crate::core::device::Deferred;
use crate::core::space::{RamStore, Region, RequesterId, UnassignedPolicy};
use crate::core::state::{MachineShape, Migrations, StateReader, StateWriter};
use crate::core::wire::{Wire, WireId, WireIdAllocator, WireSink};

// ---------------------------------------------------------------------------
// Fixtures
// ---------------------------------------------------------------------------

/// A PPU with 8 KiB of CHR RAM and 4 KiB of nametable RAM, no write lockout.
fn new_ppu() -> (NesPpu, Arc<RamStore>, Arc<RamStore>) {
    let mut props = Props::new();
    props.insert("warmup", false);
    let ppu = NesPpu::new(&props).expect("properties are valid");

    let chr = Arc::new(RamStore::new(0x2000));
    let nt = Arc::new(RamStore::new(0x1000));
    let space = AddressSpace::new("ppu", 14).with_unassigned(UnassignedPolicy::ZEROS);
    space
        .topology()
        .map(Arc::new(Region::ram("chr", Arc::clone(&chr))), 0x0000)
        .expect("chr fits");
    space
        .topology()
        .map(
            Arc::new(
                Region::mirror(
                    "nametables",
                    Arc::new(Region::ram("nt", Arc::clone(&nt))),
                    0x1000,
                )
                .expect("mirror fits"),
            ),
            0x2000,
        )
        .expect("nametables fit");
    ppu.attach_bus(Arc::new(space));
    (ppu, chr, nt)
}

/// Put the PPU at `(scanline, dot)` — the position of the dot about to run.
fn seek(ppu: &NesPpu, scanline: u16, dot: u16) {
    ppu.with_engine(|e| {
        e.scanline = scanline;
        e.dot = dot;
    });
}

/// Run two full frames and stop at the start of post-render.
///
/// The frame is fully drawn, but the pre-render line — which clears vblank,
/// sprite 0 hit and overflow at its dot 1 — has not run yet, so the status flags
/// are still there to be asserted on. Two frames because the first one starts on
/// scanline 0 with nothing primed.
fn draw_two_frames(ppu: &NesPpu) {
    ppu.advance_by(DOTS_PER_FRAME * 2 - u64::from(DOTS_PER_SCANLINE) * 22);
    assert_eq!(ppu.position(), (SCREEN_HEIGHT as u16, 0));
}

fn enable_rendering(ppu: &NesPpu) {
    ppu.write_register(
        PPUMASK,
        MASK_BG | MASK_SPRITE | MASK_BG_LEFT | MASK_SPRITE_LEFT,
    );
}

// ---------------------------------------------------------------------------
// Clock
// ---------------------------------------------------------------------------

#[test]
fn three_dots_per_cpu_cycle_exactly() {
    // ROADMAP.md §4.2: both counters descend from one crystal, so the ratio is
    // exact regardless of what the master frequency is believed to be.
    let mut forest = ClockForest::new();
    let master = forest
        .add_oscillator("master", Rational::new(236_250_000, 11).unwrap())
        .unwrap();
    let cpu = forest.add_domain("cpu", master, 1, 12).unwrap();
    let dots = add_clock_domain(&mut forest, master).unwrap();
    assert_eq!(forest.convert_ticks(cpu, dots, 1).unwrap(), 3);
    assert_eq!(forest.convert_ticks(cpu, dots, 29_780).unwrap(), 89_340);
}

// ---------------------------------------------------------------------------
// Frame geometry
// ---------------------------------------------------------------------------

#[test]
fn an_even_frame_is_341_by_262_dots() {
    // NESdev PPU rendering: 262 scanlines of 341 dots.
    let (ppu, _, _) = new_ppu();
    ppu.advance_by(DOTS_PER_FRAME);
    assert_eq!(ppu.frame(), 1);
    assert_eq!(ppu.position(), (0, 0));
    assert_eq!(DOTS_PER_FRAME, 89_342);
}

#[test]
fn an_odd_frame_skips_a_dot_when_rendering() {
    // NESdev PPU frame timing: with rendering enabled, an odd frame jumps
    // straight from (339, 261) to (0, 0).
    let (ppu, _, _) = new_ppu();
    enable_rendering(&ppu);
    ppu.advance_by(DOTS_PER_FRAME); // frame 0, even, full length
    assert_eq!(ppu.frame(), 1);
    assert_eq!(ppu.position(), (0, 0));
    ppu.advance_by(DOTS_PER_FRAME - 1); // frame 1, odd, one dot shorter
    assert_eq!(ppu.frame(), 2);
    assert_eq!(ppu.position(), (0, 0));
}

#[test]
fn the_odd_frame_skip_needs_rendering_enabled() {
    // "This is done internally by jumping directly from (339,261) to (0,0)" —
    // but only when rendering is on at that dot.
    let (ppu, _, _) = new_ppu();
    ppu.advance_by(DOTS_PER_FRAME);
    ppu.advance_by(DOTS_PER_FRAME);
    assert_eq!(ppu.frame(), 2);
    assert_eq!(ppu.position(), (0, 0));
}

// ---------------------------------------------------------------------------
// VBlank, NMI, and the $2002 race
// ---------------------------------------------------------------------------

/// Records every level change on a wire, for the NMI tests.
#[derive(Debug, Default)]
struct Recorder {
    levels: crate::core::sync::Mutex<Vec<bool>>,
}

impl WireSink for Recorder {
    fn set_level(&self, _src: WireId, _line: u32, level: Level) {
        self.levels.lock().push(level.is_high());
    }
}

fn with_nmi(ppu: &NesPpu) -> Arc<Recorder> {
    let ids = WireIdAllocator::new();
    let id = ids.alloc();
    let sink = Arc::new(Recorder::default());
    let wire = Wire::builder()
        .source(id)
        .sink(Arc::clone(&sink) as Arc<dyn WireSink>, 0)
        .build_shared();
    ppu.attach_nmi(WireSource::new(wire, id));
    sink
}

#[test]
fn the_vblank_flag_is_set_at_dot_1_of_scanline_241() {
    // NESdev PPU frame timing.
    let (ppu, _, _) = new_ppu();
    seek(&ppu, VBLANK_SCANLINE, 0);
    ppu.advance_by(1); // runs dot 0; reading here would be the race, so peek
    assert_eq!(ppu.with_engine(|e| e.status) & STATUS_VBLANK, 0);
    ppu.advance_by(1); // runs dot 1
    assert_eq!(ppu.with_engine(|e| e.status) & STATUS_VBLANK, STATUS_VBLANK);
    // And two dots later it is a plain read.
    ppu.advance_by(3);
    assert_eq!(ppu.read_register(PPUSTATUS) & STATUS_VBLANK, STATUS_VBLANK);
    assert_eq!(
        ppu.with_engine(|e| e.status) & STATUS_VBLANK,
        0,
        "cleared by the read"
    );
}

#[test]
fn the_vblank_flag_is_cleared_at_dot_1_of_the_pre_render_line() {
    let (ppu, _, _) = new_ppu();
    seek(&ppu, VBLANK_SCANLINE, 1);
    ppu.advance_by(1);
    ppu.with_engine(|e| e.status |= STATUS_SPRITE0 | STATUS_OVERFLOW);
    seek(&ppu, PRE_RENDER_SCANLINE, 0);
    ppu.advance_by(1);
    assert_ne!(ppu.with_engine(|e| e.status) & STATUS_VBLANK, 0);
    ppu.advance_by(1); // dot 1
    assert_eq!(
        ppu.with_engine(|e| e.status) & (STATUS_VBLANK | STATUS_SPRITE0 | STATUS_OVERFLOW),
        0
    );
}

#[test]
fn reading_2002_one_dot_before_the_set_suppresses_the_flag_entirely() {
    // NESdev PPU frame timing: "Reading one PPU clock before reads it as clear
    // and never sets the flag or generates NMI for that frame."
    let (ppu, _, _) = new_ppu();
    let nmi = with_nmi(&ppu);
    ppu.write_register(PPUCTRL, CTRL_NMI);
    seek(&ppu, VBLANK_SCANLINE, 1);
    assert_eq!(ppu.read_register(PPUSTATUS) & STATUS_VBLANK, 0);
    ppu.advance_by(3);
    assert_eq!(ppu.with_engine(|e| e.status) & STATUS_VBLANK, 0);
    assert!(
        !nmi.levels.lock().iter().any(|high| *high),
        "no NMI may be requested this frame"
    );
}

#[test]
fn reading_2002_on_the_set_dot_returns_the_flag_and_suppresses_the_nmi() {
    // "Reading on the same PPU clock or one later reads it as set, clears it,
    // and suppresses the NMI for that frame." The request is not announced for
    // NMI_ANNOUNCE_DOTS, so a read inside that window withdraws it before any
    // edge reaches the wire at all.
    for dot in [2u16, 3] {
        let (ppu, _, _) = new_ppu();
        let nmi = with_nmi(&ppu);
        ppu.write_register(PPUCTRL, CTRL_NMI);
        seek(&ppu, VBLANK_SCANLINE, 1);
        ppu.advance_by(u64::from(dot - 1)); // run up to and including dot 1
        assert_eq!(ppu.position(), (VBLANK_SCANLINE, dot));
        let status = ppu.read_register(PPUSTATUS);
        assert_eq!(status & STATUS_VBLANK, STATUS_VBLANK, "dot {dot}");
        assert!(ppu.with_engine(|e| e.suppress_nmi), "dot {dot}");
        // Through to the end of vblank: still nothing.
        ppu.advance_by(u64::from(DOTS_PER_SCANLINE) * 19);
        assert!(
            !nmi.levels.lock().iter().any(|high| *high),
            "dot {dot}: the NMI must stay suppressed for the frame"
        );
    }
}

#[test]
fn a_read_four_dots_after_the_set_is_too_late_to_suppress() {
    // Outside the window the request has already been announced, so the CPU has
    // seen the edge and clearing the flag only lowers the line again.
    let (ppu, _, _) = new_ppu();
    let nmi = with_nmi(&ppu);
    ppu.write_register(PPUCTRL, CTRL_NMI);
    seek(&ppu, VBLANK_SCANLINE, 1);
    ppu.advance_by(3);
    assert_eq!(ppu.position(), (VBLANK_SCANLINE, 4));
    assert_eq!(nmi.levels.lock().as_slice(), &[true]);
    ppu.read_register(PPUSTATUS);
    assert_eq!(nmi.levels.lock().as_slice(), &[true, false]);
}

#[test]
fn enabling_nmi_mid_vblank_requests_one_immediately() {
    // NESdev NMI: /NMI is pulled low iff vblank_flag and nmi_output are both
    // true, so toggling bit 7 during vblank can request several NMIs.
    let (ppu, _, _) = new_ppu();
    let nmi = with_nmi(&ppu);
    seek(&ppu, VBLANK_SCANLINE, 1);
    ppu.advance_by(10);
    assert!(nmi.levels.lock().is_empty(), "NMI output is still off");
    ppu.write_register(PPUCTRL, CTRL_NMI);
    assert_eq!(nmi.levels.lock().as_slice(), &[true]);
    ppu.write_register(PPUCTRL, 0);
    ppu.write_register(PPUCTRL, CTRL_NMI);
    assert_eq!(nmi.levels.lock().as_slice(), &[true, false, true]);
}

#[test]
fn the_nmi_falls_when_vblank_ends() {
    let (ppu, _, _) = new_ppu();
    let nmi = with_nmi(&ppu);
    ppu.write_register(PPUCTRL, CTRL_NMI);
    seek(&ppu, VBLANK_SCANLINE, 1);
    ppu.advance_by(3);
    assert_eq!(nmi.levels.lock().as_slice(), &[true]);
    // Straight through to the pre-render line's dot 1, where the flag clears.
    seek(&ppu, PRE_RENDER_SCANLINE, 0);
    ppu.advance_by(2);
    assert_eq!(nmi.levels.lock().as_slice(), &[true, false]);
}

// ---------------------------------------------------------------------------
// Registers
// ---------------------------------------------------------------------------

#[test]
fn the_2007_read_buffer_delays_by_one_access() {
    // NESdev PPU registers: a read returns the buffer, then refills it.
    let (ppu, _, nt) = new_ppu();
    nt.write_u8(0x000, 0x11).unwrap();
    nt.write_u8(0x001, 0x22).unwrap();
    ppu.write_register(PPUADDR, 0x20);
    ppu.write_register(PPUADDR, 0x00);
    let dummy = ppu.read_register(PPUDATA);
    assert_eq!(dummy, 0x00, "the first read returns the stale buffer");
    assert_eq!(ppu.read_register(PPUDATA), 0x11);
    assert_eq!(ppu.read_register(PPUDATA), 0x22);
}

#[test]
fn a_palette_read_is_not_buffered_but_still_fills_the_buffer() {
    // The palette answers immediately; the buffer gets the nametable byte
    // hiding under the mirror at $2F00 (NESdev PPU registers, PPUDATA).
    let (ppu, _, nt) = new_ppu();
    nt.write_u8(0xf01, 0x5a).unwrap();
    ppu.poke_palette(0x3f01, 0x21);
    ppu.write_register(PPUADDR, 0x3f);
    ppu.write_register(PPUADDR, 0x01);
    assert_eq!(ppu.read_register(PPUDATA) & 0x3f, 0x21);
    // The next read comes out of the buffer the palette read loaded.
    ppu.write_register(PPUADDR, 0x20);
    ppu.write_register(PPUADDR, 0x00);
    assert_eq!(ppu.read_register(PPUDATA), 0x5a);
}

#[test]
fn the_registers_mirror_every_eight_bytes_to_3fff() {
    let (ppu, _, _) = new_ppu();
    let port = ppu.port();
    let mut byte = [0u8; 1];
    // $2002 and $3FFA are the same register.
    ppu.with_engine(|e| e.status |= STATUS_VBLANK);
    port.read(0x3ffa - REGISTER_BASE, &mut byte, MemAttrs::DEFAULT)
        .unwrap();
    assert_eq!(byte[0] & STATUS_VBLANK, STATUS_VBLANK);
    // And it cleared the flag, because it really is the same register.
    assert_eq!(ppu.with_engine(|e| e.status) & STATUS_VBLANK, 0);
}

#[test]
fn the_write_toggle_is_shared_and_2002_clears_it() {
    // NESdev PPU scrolling: $2005 and $2006 share t and w.
    let (ppu, _, _) = new_ppu();
    ppu.write_register(PPUADDR, 0x21); // first write: t high byte
    assert!(ppu.with_engine(|e| e.w));
    ppu.read_register(PPUSTATUS);
    assert!(!ppu.with_engine(|e| e.w));
    // So this is treated as another *first* write, not the low byte.
    ppu.write_register(PPUADDR, 0x2c);
    ppu.write_register(PPUADDR, 0x00);
    assert_eq!(ppu.with_engine(|e| e.v), 0x2c00);
}

#[test]
fn scroll_writes_land_in_t_and_x_exactly() {
    // NESdev PPU scrolling, "$2005 first/second write".
    let (ppu, _, _) = new_ppu();
    ppu.write_register(PPUSCROLL, 0b1010_1011); // coarse X 10101, fine X 011
    assert_eq!(ppu.with_engine(|e| e.t) & 0x001f, 0b10101);
    assert_eq!(ppu.with_engine(|e| e.x), 0b011);
    ppu.write_register(PPUSCROLL, 0b0110_1101); // coarse Y 01101, fine Y 101
    let t = ppu.with_engine(|e| e.t);
    assert_eq!((t >> 5) & 0x1f, 0b01101);
    assert_eq!((t >> 12) & 0x07, 0b101);
}

#[test]
fn the_2006_high_write_clears_bit_14() {
    let (ppu, _, _) = new_ppu();
    ppu.write_register(PPUSCROLL, 0);
    ppu.write_register(PPUSCROLL, 0xff); // sets fine Y, i.e. t bits 12-14
    ppu.write_register(PPUADDR, 0xff); // ..AAAAAA: only 6 bits survive
    assert_eq!(ppu.with_engine(|e| e.t) & 0x7f00, 0x3f00);
}

#[test]
fn open_bus_fills_the_unused_bits_of_2002_and_decays() {
    // NESdev PPU registers, "PPU I/O latch".
    let mut props = Props::new();
    props.insert("warmup", false);
    props.insert("open-bus-decay-dots", 100u64);
    let ppu = NesPpu::new(&props).unwrap();
    ppu.attach_bus(Arc::new(AddressSpace::new("ppu", 14)));
    // A write to a write-only port charges the whole latch.
    ppu.write_register(PPUMASK, 0x1f);
    assert_eq!(ppu.read_register(PPUSTATUS) & 0x1f, 0x1f);
    // Reading a write-only port returns the latch, unchanged.
    assert_eq!(ppu.read_register(PPUCTRL), 0x1f);
    ppu.advance_by(200);
    assert_eq!(
        ppu.read_register(PPUSTATUS) & 0x1f,
        0x00,
        "the charge decayed"
    );
}

#[test]
fn a_debug_read_of_2002_has_no_side_effects() {
    // ROADMAP.md §15, invariant 5.
    let (ppu, _, _) = new_ppu();
    ppu.with_engine(|e| e.status |= STATUS_VBLANK);
    ppu.write_register(PPUADDR, 0x21); // sets w
    let port = ppu.port();
    let mut byte = [0u8; 1];
    port.read(2, &mut byte, MemAttrs::DEBUG).unwrap();
    assert_eq!(byte[0] & STATUS_VBLANK, STATUS_VBLANK);
    assert_eq!(ppu.with_engine(|e| e.status) & STATUS_VBLANK, STATUS_VBLANK);
    assert!(ppu.with_engine(|e| e.w), "the toggle must not have moved");
}

#[test]
fn a_debug_read_of_2007_does_not_advance_the_address() {
    let (ppu, _, nt) = new_ppu();
    nt.write_u8(0, 0x77).unwrap();
    ppu.write_register(PPUADDR, 0x20);
    ppu.write_register(PPUADDR, 0x00);
    let port = ppu.port();
    let mut byte = [0u8; 1];
    port.read(7, &mut byte, MemAttrs::DEBUG).unwrap();
    assert_eq!(ppu.with_engine(|e| e.v), 0x2000);
    // The real read still sees the stale buffer, i.e. the debug read did not
    // fill it either.
    assert_eq!(ppu.read_register(PPUDATA), 0x00);
}

#[test]
fn the_warmup_lockout_ignores_early_writes() {
    // NESdev PPU registers: $2000/$2001/$2005/$2006 are ignored for the first
    // ~29658 CPU cycles after reset.
    let ppu = NesPpu::new(&Props::new()).unwrap();
    ppu.attach_bus(Arc::new(AddressSpace::new("ppu", 14)));
    ppu.write_register(PPUCTRL, CTRL_NMI);
    assert_eq!(ppu.with_engine(|e| e.ctrl), 0, "too early");
    ppu.with_engine(|e| e.dots = WARMUP_DOTS);
    ppu.write_register(PPUCTRL, CTRL_NMI);
    assert_eq!(ppu.with_engine(|e| e.ctrl), CTRL_NMI);
    // $2003 and $2004 were never locked out.
    ppu.with_engine(|e| e.dots = 0);
    ppu.write_register(OAMADDR, 0x40);
    assert_eq!(ppu.oam_addr(), 0x40);
}

// ---------------------------------------------------------------------------
// Palette
// ---------------------------------------------------------------------------

#[test]
fn the_sprite_palette_zeros_alias_the_background_ones() {
    // NESdev PPU palettes: $3F10/$3F14/$3F18/$3F1C are $3F00/$3F04/$3F08/$3F0C.
    let (ppu, _, _) = new_ppu();
    for (sprite, background) in [
        (0x3f10, 0x3f00),
        (0x3f14, 0x3f04),
        (0x3f18, 0x3f08),
        (0x3f1c, 0x3f0c),
    ] {
        ppu.poke_palette(sprite, 0x2a);
        assert_eq!(ppu.peek_palette(background), 0x2a, "{sprite:#x}");
        ppu.poke_palette(background, 0x15);
        assert_eq!(ppu.peek_palette(sprite), 0x15, "{sprite:#x}");
    }
    // $3F11 is its own entry.
    ppu.poke_palette(0x3f01, 0x01);
    ppu.poke_palette(0x3f11, 0x02);
    assert_eq!(ppu.peek_palette(0x3f01), 0x01);
}

#[test]
fn palette_ram_repeats_through_3fff() {
    let (ppu, _, _) = new_ppu();
    ppu.poke_palette(0x3f03, 0x30);
    assert_eq!(ppu.peek_palette(0x3fe3), 0x30);
    assert_eq!(ppu.peek_palette(0x3f23), 0x30);
}

#[test]
fn palette_entries_are_six_bits() {
    let (ppu, _, _) = new_ppu();
    ppu.poke_palette(0x3f00, 0xff);
    assert_eq!(ppu.peek_palette(0x3f00), 0x3f);
}

#[test]
fn a_palette_read_reports_the_top_two_bits_as_open_bus() {
    let (ppu, _, _) = new_ppu();
    ppu.poke_palette(0x3f00, 0x0f);
    ppu.write_register(PPUMASK, 0xc0); // charges the latch with $C0
    ppu.write_register(PPUADDR, 0x3f);
    ppu.write_register(PPUADDR, 0x00);
    // $2006 writes recharged the latch with the last written byte, $00.
    ppu.write_register(PPUSTATUS, 0xc0); // read-only port: latch only
    assert_eq!(ppu.read_register(PPUDATA), 0xc0 | 0x0f);
}

// ---------------------------------------------------------------------------
// Background rendering
// ---------------------------------------------------------------------------

/// Fill CHR with a tile whose every pixel is colour 1, and one nametable entry.
fn plain_background(chr: &RamStore, nt: &RamStore, tile: u8) {
    for row in 0..8u64 {
        chr.write_u8(u64::from(tile) * 16 + row, 0xff).unwrap(); // low plane
        chr.write_u8(u64::from(tile) * 16 + 8 + row, 0x00).unwrap(); // high plane
    }
    for index in 0..0x3c0u64 {
        nt.write_u8(index, tile).unwrap();
    }
}

#[test]
fn the_background_pipeline_draws_a_uniform_screen() {
    let (ppu, chr, nt) = new_ppu();
    plain_background(&chr, &nt, 1);
    ppu.poke_palette(0x3f00, 0x0f); // backdrop
    ppu.poke_palette(0x3f01, 0x21); // colour 1 of palette 0
    ppu.write_register(PPUMASK, MASK_BG | MASK_BG_LEFT);
    draw_two_frames(&ppu);
    for x in [0usize, 1, 7, 8, 128, 255] {
        assert_eq!(ppu.pixel(x, 100).unwrap().index(), 0x21, "x = {x}");
    }
}

#[test]
fn the_left_column_mask_hides_the_first_eight_pixels() {
    let (ppu, chr, nt) = new_ppu();
    plain_background(&chr, &nt, 1);
    ppu.poke_palette(0x3f00, 0x0f);
    ppu.poke_palette(0x3f01, 0x21);
    ppu.write_register(PPUMASK, MASK_BG); // no MASK_BG_LEFT
    draw_two_frames(&ppu);
    assert_eq!(ppu.pixel(0, 100).unwrap().index(), 0x0f);
    assert_eq!(ppu.pixel(7, 100).unwrap().index(), 0x0f);
    assert_eq!(ppu.pixel(8, 100).unwrap().index(), 0x21);
}

#[test]
fn fine_x_shifts_the_background_left() {
    // A tile with only its leftmost pixel set, repeated: fine X moves the
    // pattern by that many pixels (NESdev PPU scrolling).
    let (ppu, chr, nt) = new_ppu();
    for row in 0..8u64 {
        chr.write_u8(16 + row, 0x80).unwrap();
        chr.write_u8(16 + 8 + row, 0x00).unwrap();
    }
    for index in 0..0x3c0u64 {
        nt.write_u8(index, 1).unwrap();
    }
    ppu.poke_palette(0x3f00, 0x0f);
    ppu.poke_palette(0x3f01, 0x21);
    ppu.write_register(PPUMASK, MASK_BG | MASK_BG_LEFT);
    ppu.write_register(PPUSCROLL, 3); // fine X = 3, coarse X = 0
    ppu.write_register(PPUSCROLL, 0);
    draw_two_frames(&ppu);
    assert_eq!(ppu.pixel(5, 100).unwrap().index(), 0x21);
    assert_eq!(ppu.pixel(4, 100).unwrap().index(), 0x0f);
}

#[test]
fn greyscale_masks_the_palette_index() {
    let (ppu, chr, nt) = new_ppu();
    plain_background(&chr, &nt, 1);
    ppu.poke_palette(0x3f01, 0x21);
    ppu.write_register(PPUMASK, MASK_BG | MASK_BG_LEFT | MASK_GREYSCALE);
    draw_two_frames(&ppu);
    assert_eq!(ppu.pixel(100, 100).unwrap().index(), 0x20);
}

#[test]
fn emphasis_travels_with_the_pixel() {
    let (ppu, _, _) = new_ppu();
    ppu.poke_palette(0x3f00, 0x0f);
    ppu.write_register(PPUMASK, MASK_EMPHASIS_R | MASK_EMPHASIS_B);
    draw_two_frames(&ppu);
    assert_eq!(ppu.pixel(10, 10).unwrap().emphasis(), 0b101);
}

#[test]
fn rendering_disabled_with_v_in_the_palette_shows_that_entry() {
    // NESdev PPU palettes: the backdrop override.
    let (ppu, _, _) = new_ppu();
    ppu.poke_palette(0x3f00, 0x0f);
    ppu.poke_palette(0x3f05, 0x16);
    ppu.write_register(PPUADDR, 0x3f);
    ppu.write_register(PPUADDR, 0x05);
    draw_two_frames(&ppu);
    assert_eq!(ppu.pixel(10, 10).unwrap().index(), 0x16);
}

#[test]
fn coarse_x_wraps_into_the_next_nametable() {
    // NESdev PPU scrolling, "coarse X increment".
    let (ppu, _, _) = new_ppu();
    ppu.with_engine(|e| e.v = 0x001f);
    enable_rendering(&ppu);
    seek(&ppu, 0, 8);
    ppu.advance_by(1);
    assert_eq!(ppu.with_engine(|e| e.v), 0x0400);
}

#[test]
fn y_increment_wraps_at_row_29_and_at_row_31() {
    // Row 29 is the last tile row; 30 and 31 hold attribute data, so hardware
    // treats them differently (NESdev PPU scrolling).
    let (ppu, _, _) = new_ppu();
    enable_rendering(&ppu);
    ppu.with_engine(|e| e.v = 0x7000 | (29 << 5));
    seek(&ppu, 0, 256);
    ppu.advance_by(1);
    assert_eq!(ppu.with_engine(|e| e.v) & 0x0be0, 0x0800, "toggles bit 11");

    ppu.with_engine(|e| e.v = 0x7000 | (31 << 5));
    seek(&ppu, 0, 256);
    ppu.advance_by(1);
    assert_eq!(ppu.with_engine(|e| e.v) & 0x0be0, 0x0000, "no toggle");
}

#[test]
fn dot_257_copies_the_horizontal_bits_and_280_to_304_the_vertical_ones() {
    let (ppu, _, _) = new_ppu();
    enable_rendering(&ppu);
    ppu.with_engine(|e| {
        e.v = 0;
        e.t = 0x7fff;
    });
    seek(&ppu, 0, 257);
    ppu.advance_by(1);
    assert_eq!(ppu.with_engine(|e| e.v), 0x041f);

    ppu.with_engine(|e| e.v = 0);
    seek(&ppu, PRE_RENDER_SCANLINE, 280);
    ppu.advance_by(1);
    assert_eq!(ppu.with_engine(|e| e.v), 0x7be0);
}

#[test]
fn writing_2007_while_rendering_moves_the_scroll_counters() {
    // NESdev PPU registers, PPUDATA: during rendering the address increment is
    // a coarse-X and a Y increment, not +1 or +32.
    let (ppu, _, _) = new_ppu();
    enable_rendering(&ppu);
    seek(&ppu, 0, 100);
    ppu.with_engine(|e| e.v = 0x0000);
    ppu.write_register(PPUDATA, 0x00);
    assert_eq!(ppu.with_engine(|e| e.v), 0x1001);
}

// ---------------------------------------------------------------------------
// Sprites
// ---------------------------------------------------------------------------

/// A sprite whose whole 8x8 tile is colour 1.
fn opaque_sprite(chr: &RamStore, tile: u8) {
    for row in 0..8u64 {
        chr.write_u8(u64::from(tile) * 16 + row, 0xff).unwrap();
        chr.write_u8(u64::from(tile) * 16 + 8 + row, 0x00).unwrap();
    }
}

#[test]
fn a_sprite_is_drawn_one_line_below_its_y_byte() {
    // NESdev PPU OAM: byte 0 is the Y coordinate minus one.
    let (ppu, chr, _) = new_ppu();
    opaque_sprite(&chr, 1);
    ppu.poke_palette(0x3f00, 0x0f);
    ppu.poke_palette(0x3f11, 0x27);
    ppu.poke_oam(0, 50); // Y
    ppu.poke_oam(1, 1); // tile
    ppu.poke_oam(2, 0); // attributes: palette 0, in front
    ppu.poke_oam(3, 40); // X
    ppu.write_register(PPUMASK, MASK_SPRITE | MASK_SPRITE_LEFT);
    draw_two_frames(&ppu);
    assert_eq!(ppu.pixel(40, 50).unwrap().index(), 0x0f, "not on line 50");
    assert_eq!(ppu.pixel(40, 51).unwrap().index(), 0x27);
    assert_eq!(ppu.pixel(47, 58).unwrap().index(), 0x27);
    assert_eq!(ppu.pixel(48, 58).unwrap().index(), 0x0f);
}

#[test]
fn sprites_never_appear_on_scanline_zero() {
    // Evaluation does not run on the pre-render line, so nothing is ever in
    // secondary OAM for line 0 (NESdev PPU sprite evaluation).
    let (ppu, chr, _) = new_ppu();
    opaque_sprite(&chr, 1);
    ppu.poke_palette(0x3f00, 0x0f);
    ppu.poke_palette(0x3f11, 0x27);
    ppu.poke_oam(0, 0xff); // Y = 255 wraps into range for line 0 if evaluated
    ppu.poke_oam(1, 1);
    ppu.poke_oam(3, 0);
    ppu.write_register(PPUMASK, MASK_SPRITE | MASK_SPRITE_LEFT);
    draw_two_frames(&ppu);
    assert_eq!(ppu.pixel(0, 0).unwrap().index(), 0x0f);
}

#[test]
fn an_8x16_sprite_takes_its_bank_from_the_tile_byte() {
    // NESdev PPU OAM: bit 0 of the tile byte selects the pattern table and the
    // bottom half is the next tile up.
    let (ppu, chr, _) = new_ppu();
    // Top half in bank $1000 tile $02, bottom half tile $03.
    for row in 0..8u64 {
        chr.write_u8(0x1000 + 0x02 * 16 + row, 0xff).unwrap();
        chr.write_u8(0x1000 + 0x03 * 16 + row, 0x00).unwrap();
        chr.write_u8(0x1000 + 0x03 * 16 + 8 + row, 0xff).unwrap();
    }
    ppu.poke_palette(0x3f00, 0x0f);
    ppu.poke_palette(0x3f11, 0x27); // colour 1
    ppu.poke_palette(0x3f12, 0x28); // colour 2
    ppu.poke_oam(0, 50);
    ppu.poke_oam(1, 0x03); // tile $02, bank 1
    ppu.poke_oam(2, 0);
    ppu.poke_oam(3, 40);
    ppu.write_register(PPUCTRL, CTRL_SPRITE_16);
    ppu.write_register(PPUMASK, MASK_SPRITE | MASK_SPRITE_LEFT);
    draw_two_frames(&ppu);
    assert_eq!(ppu.pixel(40, 51).unwrap().index(), 0x27, "top half");
    assert_eq!(ppu.pixel(40, 59).unwrap().index(), 0x28, "bottom half");
    assert_eq!(ppu.pixel(40, 67).unwrap().index(), 0x0f, "16 rows only");
}

#[test]
fn sprite_flipping_mirrors_the_pattern() {
    let (ppu, chr, _) = new_ppu();
    // A tile with only the leftmost column and the top row set.
    chr.write_u8(16, 0xff).unwrap();
    for row in 1..8u64 {
        chr.write_u8(16 + row, 0x80).unwrap();
    }
    ppu.poke_palette(0x3f00, 0x0f);
    ppu.poke_palette(0x3f11, 0x27);
    ppu.poke_oam(0, 50);
    ppu.poke_oam(1, 1);
    ppu.poke_oam(2, SPRITE_FLIP_X | SPRITE_FLIP_Y);
    ppu.poke_oam(3, 40);
    ppu.write_register(PPUMASK, MASK_SPRITE | MASK_SPRITE_LEFT);
    draw_two_frames(&ppu);
    // Flipped both ways, the solid row is at the bottom and the column right.
    assert_eq!(ppu.pixel(47, 58).unwrap().index(), 0x27);
    assert_eq!(ppu.pixel(40, 58).unwrap().index(), 0x27);
    assert_eq!(ppu.pixel(40, 51).unwrap().index(), 0x0f);
}

#[test]
fn only_eight_sprites_are_drawn_and_the_ninth_sets_overflow() {
    // NESdev PPU sprite evaluation: secondary OAM holds eight.
    let (ppu, chr, _) = new_ppu();
    opaque_sprite(&chr, 1);
    ppu.poke_palette(0x3f00, 0x0f);
    ppu.poke_palette(0x3f11, 0x27);
    for index in 0..9u8 {
        ppu.poke_oam(index * 4, 50);
        ppu.poke_oam(index * 4 + 1, 1);
        ppu.poke_oam(index * 4 + 2, 0);
        ppu.poke_oam(index * 4 + 3, index * 8);
    }
    ppu.write_register(PPUMASK, MASK_SPRITE | MASK_SPRITE_LEFT);
    draw_two_frames(&ppu);
    assert_eq!(
        ppu.pixel(56, 51).unwrap().index(),
        0x27,
        "the eighth is drawn"
    );
    assert_eq!(ppu.pixel(64, 51).unwrap().index(), 0x0f, "the ninth is not");
    assert_ne!(ppu.with_engine(|e| e.status) & STATUS_OVERFLOW, 0);
}

#[test]
fn the_overflow_bug_reads_a_tile_byte_as_a_y_coordinate() {
    // Step 3 of NESdev PPU sprite evaluation: on a miss the hardware increments
    // n *and* m without carry, so it walks OAM diagonally and range-checks bytes
    // that are not Y coordinates at all. Here exactly eight sprites are on the
    // line — no real overflow — but sprite 8's *tile* byte lands in the diagonal
    // walk with a value that is in range, and the flag comes up anyway.
    let (ppu, chr, _) = new_ppu();
    opaque_sprite(&chr, 1);
    for index in 0..8u8 {
        ppu.poke_oam(index * 4, 50);
        ppu.poke_oam(index * 4 + 1, 1);
        ppu.poke_oam(index * 4 + 2, 0);
        ppu.poke_oam(index * 4 + 3, index * 8);
    }
    // Sprites 8..63 are off-screen, so a correct chip would report nothing.
    for index in 8..64u8 {
        ppu.poke_oam(index * 4, 0xf0);
        ppu.poke_oam(index * 4 + 1, 0xf0);
        ppu.poke_oam(index * 4 + 2, 0xf0);
        ppu.poke_oam(index * 4 + 3, 0xf0);
    }
    // The walk examines (n=8, m=0), then (9, 1), then (10, 2): the second byte
    // it looks at is sprite 9's *tile* number.
    ppu.poke_oam(9 * 4 + 1, 50);
    ppu.write_register(PPUMASK, MASK_SPRITE | MASK_SPRITE_LEFT);
    draw_two_frames(&ppu);
    assert_ne!(
        ppu.with_engine(|e| e.status) & STATUS_OVERFLOW,
        0,
        "a tile byte in range must trip the buggy overflow search"
    );
}

#[test]
fn the_overflow_flag_stays_clear_with_eight_sprites_and_nothing_in_range() {
    let (ppu, chr, _) = new_ppu();
    opaque_sprite(&chr, 1);
    for index in 0..8u8 {
        ppu.poke_oam(index * 4, 50);
        ppu.poke_oam(index * 4 + 1, 1);
        ppu.poke_oam(index * 4 + 2, 0);
        ppu.poke_oam(index * 4 + 3, index * 8);
    }
    for index in 8..64u8 {
        for byte in 0..4u8 {
            ppu.poke_oam(index * 4 + byte, 0xf0);
        }
    }
    ppu.write_register(PPUMASK, MASK_SPRITE | MASK_SPRITE_LEFT);
    draw_two_frames(&ppu);
    assert_eq!(ppu.with_engine(|e| e.status) & STATUS_OVERFLOW, 0);
}

#[test]
fn sprite_priority_is_by_oam_index_then_by_the_priority_bit() {
    let (ppu, chr, nt) = new_ppu();
    opaque_sprite(&chr, 1);
    opaque_sprite(&chr, 2);
    plain_background(&chr, &nt, 3);
    // Tile 3 is transparent so the background does not interfere.
    for row in 0..8u64 {
        chr.write_u8(3 * 16 + row, 0x00).unwrap();
        chr.write_u8(3 * 16 + 8 + row, 0x00).unwrap();
    }
    ppu.poke_palette(0x3f00, 0x0f);
    ppu.poke_palette(0x3f11, 0x27); // sprite palette 0
    ppu.poke_palette(0x3f15, 0x28); // sprite palette 1
    ppu.poke_oam(0, 50);
    ppu.poke_oam(1, 1);
    ppu.poke_oam(2, 0);
    ppu.poke_oam(3, 40);
    ppu.poke_oam(4, 50);
    ppu.poke_oam(5, 2);
    ppu.poke_oam(6, 1); // palette 1
    ppu.poke_oam(7, 40);
    ppu.write_register(
        PPUMASK,
        MASK_BG | MASK_SPRITE | MASK_BG_LEFT | MASK_SPRITE_LEFT,
    );
    draw_two_frames(&ppu);
    assert_eq!(ppu.pixel(40, 51).unwrap().index(), 0x27, "lower index wins");
}

#[test]
fn a_behind_sprite_loses_to_opaque_background() {
    let (ppu, chr, nt) = new_ppu();
    opaque_sprite(&chr, 1);
    plain_background(&chr, &nt, 2);
    opaque_sprite(&chr, 2);
    ppu.poke_palette(0x3f00, 0x0f);
    ppu.poke_palette(0x3f01, 0x11); // background colour 1
    ppu.poke_palette(0x3f11, 0x27);
    ppu.poke_oam(0, 50);
    ppu.poke_oam(1, 1);
    ppu.poke_oam(2, SPRITE_BEHIND);
    ppu.poke_oam(3, 40);
    ppu.write_register(
        PPUMASK,
        MASK_BG | MASK_SPRITE | MASK_BG_LEFT | MASK_SPRITE_LEFT,
    );
    draw_two_frames(&ppu);
    assert_eq!(ppu.pixel(40, 51).unwrap().index(), 0x11);
}

// ---------------------------------------------------------------------------
// Sprite 0 hit
// ---------------------------------------------------------------------------

/// Put an opaque sprite 0 at `(x, y)` over an opaque background.
fn sprite_zero_scene(ppu: &NesPpu, chr: &RamStore, nt: &RamStore, x: u8, y: u8) {
    opaque_sprite(chr, 1);
    plain_background(chr, nt, 1);
    ppu.poke_palette(0x3f00, 0x0f);
    ppu.poke_palette(0x3f01, 0x11);
    ppu.poke_palette(0x3f11, 0x27);
    ppu.poke_oam(0, y);
    ppu.poke_oam(1, 1);
    ppu.poke_oam(2, 0);
    ppu.poke_oam(3, x);
}

#[test]
fn sprite_zero_hits_where_both_layers_are_opaque() {
    let (ppu, chr, nt) = new_ppu();
    sprite_zero_scene(&ppu, &chr, &nt, 40, 50);
    ppu.write_register(
        PPUMASK,
        MASK_BG | MASK_SPRITE | MASK_BG_LEFT | MASK_SPRITE_LEFT,
    );
    draw_two_frames(&ppu);
    assert_ne!(ppu.with_engine(|e| e.status) & STATUS_SPRITE0, 0);
}

#[test]
fn sprite_zero_never_hits_at_x_255() {
    // NESdev PPU registers, PPUSTATUS: no hit at x = 255.
    let (ppu, chr, nt) = new_ppu();
    sprite_zero_scene(&ppu, &chr, &nt, 255, 50);
    ppu.write_register(
        PPUMASK,
        MASK_BG | MASK_SPRITE | MASK_BG_LEFT | MASK_SPRITE_LEFT,
    );
    draw_two_frames(&ppu);
    assert_eq!(ppu.with_engine(|e| e.status) & STATUS_SPRITE0, 0);
}

#[test]
fn sprite_zero_never_hits_in_a_clipped_left_column() {
    let (ppu, chr, nt) = new_ppu();
    sprite_zero_scene(&ppu, &chr, &nt, 0, 50);
    // Background left column shown, sprites clipped: no hit in x 0..7.
    ppu.write_register(PPUMASK, MASK_BG | MASK_SPRITE | MASK_BG_LEFT);
    draw_two_frames(&ppu);
    assert_eq!(ppu.with_engine(|e| e.status) & STATUS_SPRITE0, 0);
}

#[test]
fn sprite_zero_never_hits_with_a_layer_disabled() {
    let (ppu, chr, nt) = new_ppu();
    sprite_zero_scene(&ppu, &chr, &nt, 40, 50);
    ppu.write_register(PPUMASK, MASK_SPRITE | MASK_SPRITE_LEFT); // no background
    draw_two_frames(&ppu);
    assert_eq!(ppu.with_engine(|e| e.status) & STATUS_SPRITE0, 0);
}

#[test]
fn sprite_zero_never_hits_on_a_transparent_background_pixel() {
    let (ppu, chr, nt) = new_ppu();
    sprite_zero_scene(&ppu, &chr, &nt, 40, 50);
    // Make the background tile transparent everywhere.
    for row in 0..8u64 {
        chr.write_u8(16 + row, 0x00).unwrap();
    }
    ppu.write_register(
        PPUMASK,
        MASK_BG | MASK_SPRITE | MASK_BG_LEFT | MASK_SPRITE_LEFT,
    );
    draw_two_frames(&ppu);
    assert_eq!(ppu.with_engine(|e| e.status) & STATUS_SPRITE0, 0);
}

#[test]
fn the_sprite_zero_flag_lands_one_dot_after_the_pixel() {
    // NESdev PPU rendering: "sprite 0 hit acts as if the image starts at cycle
    // 2", so a hit on pixel x is visible at dot x + 2.
    let (ppu, chr, nt) = new_ppu();
    sprite_zero_scene(&ppu, &chr, &nt, 0, 50);
    ppu.write_register(
        PPUMASK,
        MASK_BG | MASK_SPRITE | MASK_BG_LEFT | MASK_SPRITE_LEFT,
    );
    // Run to the line the sprite is on, then step dot by dot.
    ppu.advance_by(DOTS_PER_FRAME); // finish the first frame
    while ppu.position() != (51, 0) {
        ppu.advance_by(1);
    }
    ppu.advance_by(1); // dot 0: idle
    assert_eq!(ppu.with_engine(|e| e.status) & STATUS_SPRITE0, 0);
    ppu.advance_by(1); // dot 1 draws pixel 0 and arms the flag
    assert_eq!(
        ppu.with_engine(|e| e.status) & STATUS_SPRITE0,
        0,
        "not yet visible"
    );
    ppu.advance_by(1); // dot 2 publishes it
    assert_ne!(ppu.with_engine(|e| e.status) & STATUS_SPRITE0, 0);
}

// ---------------------------------------------------------------------------
// OAM
// ---------------------------------------------------------------------------

#[test]
fn the_unimplemented_attribute_bits_read_back_as_zero() {
    // NESdev PPU OAM: bits 2-4 of byte 2 do not exist.
    let (ppu, _, _) = new_ppu();
    ppu.write_register(OAMADDR, 2);
    ppu.write_register(OAMDATA, 0xff);
    ppu.write_register(OAMADDR, 2);
    assert_eq!(ppu.read_register(OAMDATA), 0xe3);
}

#[test]
fn writing_2004_while_rendering_bumps_oamaddr_without_storing() {
    // NESdev PPU registers, OAMDATA.
    let (ppu, _, _) = new_ppu();
    enable_rendering(&ppu);
    seek(&ppu, 10, 100);
    ppu.write_register(OAMADDR, 0x10);
    ppu.write_register(OAMDATA, 0x5a);
    assert_eq!(ppu.peek_oam(0x10), 0x00, "OAM is busy being evaluated");
    assert_eq!(ppu.oam_addr(), 0x14, "only the high six bits moved");
}

#[test]
fn reading_2004_during_the_secondary_oam_clear_returns_ff() {
    // NESdev PPU sprite evaluation, dots 1-64.
    let (ppu, _, _) = new_ppu();
    enable_rendering(&ppu);
    ppu.poke_oam(0, 0x12);
    seek(&ppu, 10, 30);
    assert_eq!(ppu.read_register(OAMDATA), 0xff);
    seek(&ppu, 10, 100);
    assert_eq!(ppu.read_register(OAMDATA), 0x12);
}

#[test]
fn oam_dma_bytes_go_through_the_2004_path() {
    let (ppu, _, _) = new_ppu();
    ppu.write_register(OAMADDR, 0);
    for index in 0..4u8 {
        ppu.oam_dma_write(0x40 + index);
    }
    assert_eq!(ppu.peek_oam(0), 0x40);
    assert_eq!(ppu.peek_oam(2), 0x42 & SPRITE_ATTR_IMPLEMENTED);
    assert_eq!(ppu.oam_addr(), 4);
}

#[test]
fn a_high_oamaddr_corrupts_the_first_eight_oam_bytes_at_rendering_start() {
    // NESdev PPU registers, OAMADDR: "if OAMADDR is not less than eight when
    // rendering begins, the eight bytes starting at OAMADDR & $F8 are copied to
    // the first eight bytes of OAM".
    let (ppu, _, _) = new_ppu();
    for index in 0..8u8 {
        ppu.poke_oam(index, 0x00);
        ppu.poke_oam(0x20 + index, 0xa0 + index);
    }
    enable_rendering(&ppu);
    ppu.write_register(OAMADDR, 0x20);
    seek(&ppu, PRE_RENDER_SCANLINE, 0);
    ppu.advance_by(1);
    for index in 0..8u8 {
        let expected = if index & 3 == 2 {
            (0xa0 + index) & SPRITE_ATTR_IMPLEMENTED
        } else {
            0xa0 + index
        };
        assert_eq!(ppu.peek_oam(index), expected, "byte {index}");
    }
}

#[test]
fn a_misaligned_oamaddr_reinterprets_oam_bytes() {
    // NESdev PPU registers, OAMADDR: evaluation starts at OAMADDR, so a base
    // that is not a multiple of four makes tile, attribute and X bytes act as Y
    // coordinates and shifts every sprite's fields along by that much.
    let (ppu, chr, _) = new_ppu();
    opaque_sprite(&chr, 1);
    ppu.poke_oam(0, 50);
    ppu.poke_oam(1, 1);
    ppu.poke_oam(2, 0);
    ppu.poke_oam(3, 40);
    ppu.poke_oam(4, 50);
    ppu.poke_oam(5, 1);
    ppu.poke_oam(6, 0);
    ppu.poke_oam(7, 60);
    ppu.write_register(PPUMASK, MASK_SPRITE | MASK_SPRITE_LEFT);
    // OAMADDR is forced back to zero at dots 257-320 of every rendering line,
    // so the write has to land after that window and before the next line's
    // evaluation starts at dot 65.
    ppu.advance_by(DOTS_PER_FRAME);
    while ppu.position() != (40, 330) {
        ppu.advance_by(1);
    }
    ppu.write_register(OAMADDR, 3);
    ppu.advance_by(u64::from(DOTS_PER_SCANLINE));
    assert_eq!(ppu.position(), (41, 330));
    ppu.with_engine(|e| {
        assert_eq!(e.eval_base, 3);
        // Byte 3 (=40) was read as a Y coordinate, and bytes 4, 5 and 6 as the
        // tile, attributes and X of a sprite that does not exist in OAM.
        assert_eq!(&e.secondary_oam[..4], &[40, 50, 1, 0]);
        assert_eq!(e.eval_found, 1);
    });
}

// ---------------------------------------------------------------------------
// Device lifecycle and snapshots
// ---------------------------------------------------------------------------

#[test]
fn realize_fails_without_a_bus() {
    let ppu = NesPpu::new(&Props::new()).unwrap();
    let mut deferred = Deferred::new();
    let mut ctx = RealizeCtx::new("ppu", RequesterId(1), &mut deferred);
    let err = ppu.realize(&mut ctx).unwrap_err().to_string();
    assert!(err.contains("attach_bus"), "{err}");
}

#[test]
fn realize_announces_the_nmi_line() {
    // ROADMAP.md §4.3: a freshly realized machine must have every wire driving
    // what its state implies.
    let (ppu, _, _) = new_ppu();
    let nmi = with_nmi(&ppu);
    let mut deferred = Deferred::new();
    let mut ctx = RealizeCtx::new("ppu", RequesterId(1), &mut deferred);
    ppu.realize(&mut ctx).unwrap();
    // Idle low, and announced rather than assumed.
    assert_eq!(nmi.levels.lock().as_slice(), &[] as &[bool]);
    assert!(!ppu.with_engine(|e| e.nmi_active()));
}

#[test]
fn a_cold_reset_returns_every_register_to_its_documented_value() {
    let (ppu, _, _) = new_ppu();
    ppu.write_register(PPUCTRL, 0xff);
    ppu.write_register(PPUMASK, 0xff);
    ppu.advance_by(1000);
    ppu.reset(ResetKind::Cold);
    ppu.with_engine(|e| {
        assert_eq!(e.ctrl, 0);
        assert_eq!(e.mask, 0);
        assert_eq!(e.status, 0);
        assert_eq!(e.v, 0);
        assert_eq!(e.t, 0);
        assert_eq!(e.dots, 0);
    });
}

/// A cheap order-sensitive hash, so a round trip is compared by value rather
/// than by a hand-written field-by-field assertion that can rot.
fn state_hash(ppu: &NesPpu) -> u64 {
    let mut w = StateWriter::new(MachineShape::new());
    {
        let mut chunk = w
            .chunk("/ppu", NES_PPU_CLASS.name, NES_PPU_CLASS.version)
            .unwrap();
        ppu.save(&mut chunk).unwrap();
    }
    let bytes = w.to_vec().unwrap();
    let mut hash = 0xcbf2_9ce4_8422_2325u64;
    for byte in bytes {
        hash ^= u64::from(byte);
        hash = hash.wrapping_mul(0x0000_0100_0000_01b3);
    }
    hash
}

#[test]
fn a_mid_frame_snapshot_round_trips_including_the_shift_registers() {
    // Invariant 6, and the reason the background shifters are saved: a snapshot
    // taken mid-scanline has to resume drawing the same pixels.
    let (ppu, chr, nt) = new_ppu();
    plain_background(&chr, &nt, 1);
    ppu.poke_palette(0x3f01, 0x21);
    enable_rendering(&ppu);
    // Stop somewhere with a fetch in flight and sprites half-evaluated.
    ppu.advance_by(DOTS_PER_FRAME + 100 * u64::from(DOTS_PER_SCANLINE) + 123);
    assert_ne!(ppu.with_engine(|e| e.bg_shift_lo), 0, "a tile is in flight");

    let mut w = StateWriter::new(MachineShape::new());
    {
        let mut chunk = w
            .chunk("/ppu", NES_PPU_CLASS.name, NES_PPU_CLASS.version)
            .unwrap();
        ppu.save(&mut chunk).unwrap();
    }
    let bytes = w.to_vec().unwrap();
    let before = state_hash(&ppu);

    let (restored, chr2, nt2) = new_ppu();
    plain_background(&chr2, &nt2, 1);
    let reader = StateReader::new(&bytes).unwrap();
    let chunk = reader
        .load(
            "/ppu",
            NES_PPU_CLASS.name,
            NES_PPU_CLASS.version,
            &Migrations::new(),
        )
        .unwrap();
    restored.load(&mut chunk.reader()).unwrap();
    assert_eq!(state_hash(&restored), before);

    // And they stay identical when both are run on.
    ppu.advance_by(5000);
    restored.advance_by(5000);
    assert_eq!(state_hash(&restored), state_hash(&ppu));
}

#[test]
fn a_short_chunk_is_rejected() {
    let (ppu, _, _) = new_ppu();
    let mut reader = ChunkReader::new(&[0u8; 4]);
    assert!(ppu.load(&mut reader).is_err());
}

// ---------------------------------------------------------------------------
// Framebuffer
// ---------------------------------------------------------------------------

#[test]
fn the_framebuffer_is_256_by_240_indexed_pixels() {
    let (ppu, _, _) = new_ppu();
    ppu.with_framebuffer(|fb| assert_eq!(fb.len(), FRAMEBUFFER_LEN));
    assert!(ppu.pixel(255, 239).is_some());
    assert!(ppu.pixel(256, 0).is_none());
    assert!(ppu.pixel(0, 240).is_none());
}

#[test]
fn a_pixel_packs_an_index_and_emphasis() {
    let pixel = Pixel::new(0x3f, 0b101);
    assert_eq!(pixel.index(), 0x3f);
    assert_eq!(pixel.emphasis(), 0b101);
    assert_eq!(Pixel::new(0xff, 0xff), Pixel::new(0x3f, 0b111));
}

// ---------------------------------------------------------------------------
// Access constraints
// ---------------------------------------------------------------------------

#[test]
fn the_register_block_takes_byte_accesses_only() {
    let (ppu, _, _) = new_ppu();
    let port = ppu.port();
    let mut wide = [0u8; 2];
    assert!(port.read(0, &mut wide, MemAttrs::DEFAULT).is_err());
    assert!(port.write(0, &[0, 0], MemAttrs::DEFAULT).is_err());
    assert_eq!(port.constraints().max, Width::U8);
}

#[test]
fn a_debug_write_is_refused_rather_than_guessed_at() {
    let (ppu, _, _) = new_ppu();
    let port = ppu.port();
    assert!(port.write(0, &[0xff], MemAttrs::DEBUG).is_err());
    assert_eq!(ppu.with_engine(|e| e.ctrl), 0);
}