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
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
//! PPU (Picture Processing Unit) functions and structures.
//!
//! The Game Boy's Picture Processing Unit (PPU) is responsible for rendering
//! graphics on the handheld's screen. It handles the drawing of sprites and
//! backgrounds using tile-based graphics.
use core::fmt;
use std::{
borrow::BorrowMut,
cmp::max,
convert::TryInto,
fmt::{Display, Formatter},
io::Cursor,
sync::{Arc, Mutex},
};
use boytacean_common::{
data::{read_into, read_u16, read_u8, write_bytes, write_u16, write_u8},
error::Error,
util::SharedThread,
};
#[cfg(feature = "wasm")]
use wasm_bindgen::prelude::*;
use crate::{
assert_pedantic_gb,
color::{
rgb555_to_rgb888, rgb888_to_rgb1555_array, rgb888_to_rgb1555_u16, rgb888_to_rgb565,
rgb888_to_rgb565_u16, Pixel, PixelAlpha, RGB1555_SIZE, RGB565_SIZE, RGB888_SIZE, RGBA_SIZE,
RGB_SIZE, XRGB8888_SIZE,
},
consts::{
BGP_ADDR, LCDC_ADDR, LYC_ADDR, LY_ADDR, OBP0_ADDR, OBP1_ADDR, SCX_ADDR, SCY_ADDR,
STAT_ADDR, WX_ADDR, WY_ADDR,
},
gb::{GameBoyConfig, GameBoyMode},
mmu::BusComponent,
panic_gb,
state::{StateComponent, StateFormat},
warnln,
};
pub const VRAM_SIZE_DMG: usize = 8192;
pub const VRAM_SIZE_CGB: usize = 16384;
pub const VRAM_SIZE: usize = VRAM_SIZE_CGB;
pub const HRAM_SIZE: usize = 128;
pub const OAM_SIZE: usize = 160;
pub const PALETTE_SIZE: usize = 4;
pub const TILE_WIDTH: usize = 8;
pub const TILE_HEIGHT: usize = 8;
pub const TILE_WIDTH_I: usize = 7;
pub const TILE_HEIGHT_I: usize = 7;
pub const TILE_DOUBLE_HEIGHT: usize = 16;
pub const TILE_COUNT_DMG: usize = 384;
pub const TILE_COUNT_CGB: usize = 768;
/// The number of tiles that can be store in Game Boy's
/// VRAM memory according to specifications.
pub const TILE_COUNT: usize = TILE_COUNT_CGB;
/// The number of objects/sprites that can be handled at
/// the same time by the Game Boy.
pub const OBJ_COUNT: usize = 40;
/// The width of the Game Boy screen in pixels.
pub const DISPLAY_WIDTH: usize = 160;
/// The height of the Game Boy screen in pixels.
pub const DISPLAY_HEIGHT: usize = 144;
/// The size in pixels of the display.
pub const DISPLAY_SIZE: usize = DISPLAY_WIDTH * DISPLAY_HEIGHT;
/// The size to be used by the buffer of color ids
/// for the Game Boy screen, the values there should
/// range from 0 to 3.
pub const COLOR_BUFFER_SIZE: usize = DISPLAY_SIZE;
/// The size of the buffer that will hold the concrete shade
/// index (0 to 3) for each of the pixel in the screen, so that
/// it is possible to rebuild the pixel buffer from scratch.
pub const SHADE_BUFFER_SIZE: usize = DISPLAY_SIZE;
/// The size of the RGB frame buffer in bytes.
pub const FRAME_BUFFER_SIZE: usize = DISPLAY_SIZE * RGB_SIZE;
/// The size of the RGB888 frame buffer in bytes.
pub const FRAME_BUFFER_RGB888_SIZE: usize = DISPLAY_SIZE * RGB888_SIZE;
/// The size of the XRGB8888 frame buffer in bytes.
pub const FRAME_BUFFER_XRGB8888_SIZE: usize = DISPLAY_SIZE * XRGB8888_SIZE;
/// The size of the RGB1555 frame buffer in bytes.
pub const FRAME_BUFFER_RGB1555_SIZE: usize = DISPLAY_SIZE * RGB1555_SIZE;
/// The size of the RGB565 frame buffer in bytes.
pub const FRAME_BUFFER_RGB565_SIZE: usize = DISPLAY_SIZE * RGB565_SIZE;
/// The size of the RGBA frame buffer in bytes.
pub const FRAME_BUFFER_RGBA_SIZE: usize = DISPLAY_SIZE * RGBA_SIZE;
/// The base colors to be used to populate the
/// custom palettes of the Game Boy.
pub const PALETTE_COLORS: Palette = [[255, 255, 255], [192, 192, 192], [96, 96, 96], [0, 0, 0]];
/// Default tile data to be used in the DMG compatibility
/// mode of tile processing (avoids algorithmic forking).
pub const DEFAULT_TILE_ATTR: TileData = TileData {
palette: 0,
vram_bank: 0,
xflip: false,
yflip: false,
priority: false,
};
/// A basic palette for DMG with the typical high contrast
/// color characteristic of the Game Boy.
pub const BASIC_PALETTE: Palette = [
[0xff, 0xff, 0xff],
[0xc0, 0xc0, 0xc0],
[0x60, 0x60, 0x60],
[0x00, 0x00, 0x00],
];
/// Defines a type that represents a color palette
/// within the Game Boy context.
pub type Palette = [Pixel; PALETTE_SIZE];
/// Defines a type that represents a color palette
/// with alpha within the Game Boy context.
pub type PaletteAlpha = [PixelAlpha; PALETTE_SIZE];
/// Represents a palette together with the metadata
/// that is associated with it.
#[cfg_attr(feature = "wasm", wasm_bindgen)]
#[derive(Clone, PartialEq, Eq)]
pub struct PaletteInfo {
name: String,
colors: Palette,
}
impl PaletteInfo {
pub fn new(name: &str, colors: Palette) -> Self {
Self {
name: String::from(name),
colors,
}
}
pub fn from_colors_hex(name: &str, colors_hex: &str) -> Self {
let colors = Self::parse_colors_hex(colors_hex);
Self::new(name, colors)
}
pub fn parse_colors_hex(colors_hex: &str) -> Palette {
let mut colors = [[0u8; RGB_SIZE]; PALETTE_SIZE];
for (index, color) in colors_hex.split(',').enumerate() {
let color = color.trim();
let color = u32::from_str_radix(color, 16).unwrap_or(0);
let r = ((color >> 16) & 0xff) as u8;
let g = ((color >> 8) & 0xff) as u8;
let b = (color & 0xff) as u8;
colors[index] = [r, g, b];
}
colors
}
pub fn name(&self) -> &String {
&self.name
}
/// Returns the colors in RGB format.
pub fn colors(&self) -> &Palette {
&self.colors
}
/// Returns the colors in hex format, separated by comma.
pub fn colors_hex(&self) -> String {
let mut buffer = String::new();
let mut is_first = true;
for color in self.colors.iter() {
let r = color[0];
let g = color[1];
let b = color[2];
let color = ((r as u32) << 16) | ((g as u32) << 8) | b as u32;
if is_first {
is_first = false;
} else {
buffer.push(',');
}
buffer.push_str(format!("{color:06x}").as_str());
}
buffer
}
}
/// Represents a tile within the Game Boy context,
/// should contain the pixel buffer of the tile.
/// The tiles are always 8x8 pixels in size.
#[cfg_attr(feature = "wasm", wasm_bindgen)]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Tile {
/// The buffer for the tile, should contain a byte
/// per each pixel of the tile with values ranging
/// from 0 to 3 (4 colors).
buffer: [u8; 64],
}
#[cfg_attr(feature = "wasm", wasm_bindgen)]
impl Tile {
pub fn new() -> Self {
Self { buffer: [0u8; 64] }
}
pub fn get(&self, x: usize, y: usize) -> u8 {
self.buffer[y * TILE_WIDTH + x]
}
pub fn get_flipped(&self, x: usize, y: usize, xflip: bool, yflip: bool) -> u8 {
let x: usize = if xflip { TILE_WIDTH_I - x } else { x };
let y = if yflip { TILE_HEIGHT_I - y } else { y };
self.buffer[y * TILE_WIDTH + x]
}
pub fn set(&mut self, x: usize, y: usize, value: u8) {
self.buffer[y * TILE_WIDTH + x] = value;
}
pub fn buffer(&self) -> Vec<u8> {
self.buffer.to_vec()
}
}
impl Tile {
pub fn get_row(&self, y: usize) -> &[u8] {
&self.buffer[y * TILE_WIDTH..(y + 1) * TILE_WIDTH]
}
pub fn palette_buffer(&self, palette: Palette) -> Vec<u8> {
self.buffer
.iter()
.flat_map(|p| palette[*p as usize])
.collect()
}
}
impl Default for Tile {
fn default() -> Self {
Self::new()
}
}
impl Display for Tile {
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
let mut buffer = String::new();
for y in 0..8 {
for x in 0..8 {
buffer.push_str(format!("{}", self.get(x, y)).as_str());
}
buffer.push('\n');
}
write!(f, "{buffer}")
}
}
impl From<&[u8]> for Tile {
fn from(value: &[u8]) -> Self {
let mut object = Tile::new();
object.buffer.copy_from_slice(value);
object
}
}
impl From<Tile> for Vec<u8> {
fn from(value: Tile) -> Self {
let mut buffer = Vec::with_capacity(64);
buffer.extend_from_slice(&value.buffer);
buffer
}
}
#[cfg_attr(feature = "wasm", wasm_bindgen)]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct ObjectData {
x: i16,
y: i16,
tile: u8,
palette_cgb: u8,
tile_bank: u8,
palette: u8,
xflip: bool,
yflip: bool,
bg_over: bool,
index: u8,
}
impl ObjectData {
pub fn new() -> Self {
Self {
x: 0,
y: 0,
tile: 0,
palette_cgb: 0,
tile_bank: 0,
palette: 0,
xflip: false,
yflip: false,
bg_over: false,
index: 0,
}
}
}
impl Default for ObjectData {
fn default() -> Self {
Self::new()
}
}
impl Display for ObjectData {
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
write!(
f,
"Index: {}, X: {}, Y: {}, Tile: {}",
self.index, self.x, self.y, self.tile
)
}
}
impl From<&[u8]> for ObjectData {
fn from(value: &[u8]) -> Self {
let mut object = ObjectData::new();
object.x = i16::from_le_bytes([value[0], value[1]]);
object.y = i16::from_le_bytes([value[2], value[3]]);
object.tile = value[4];
object.palette_cgb = value[5];
object.tile_bank = value[6];
object.palette = value[7];
object.xflip = value[8] != 0;
object.yflip = value[9] != 0;
object.bg_over = value[10] != 0;
object.index = value[11];
object
}
}
impl From<ObjectData> for Vec<u8> {
fn from(value: ObjectData) -> Self {
let mut buffer = Vec::with_capacity(12);
buffer.extend_from_slice(&value.x.to_le_bytes());
buffer.extend_from_slice(&value.y.to_le_bytes());
buffer.push(value.tile);
buffer.push(value.palette_cgb);
buffer.push(value.tile_bank);
buffer.push(value.palette);
buffer.push(if value.xflip { 1 } else { 0 });
buffer.push(if value.yflip { 1 } else { 0 });
buffer.push(if value.bg_over { 1 } else { 0 });
buffer.push(value.index);
buffer
}
}
#[cfg_attr(feature = "wasm", wasm_bindgen)]
#[derive(Clone, Copy, PartialEq, Eq)]
pub struct TileData {
palette: u8,
vram_bank: u8,
xflip: bool,
yflip: bool,
priority: bool,
}
impl TileData {
pub fn new() -> Self {
Self {
palette: 0,
vram_bank: 0,
xflip: false,
yflip: false,
priority: false,
}
}
}
impl Default for TileData {
fn default() -> Self {
Self::new()
}
}
impl Display for TileData {
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
write!(
f,
"Palette: {}, VRAM Bank: {}, X Flip: {}, Y Flip: {}",
self.palette, self.vram_bank, self.xflip, self.yflip
)
}
}
impl From<&[u8]> for TileData {
fn from(value: &[u8]) -> Self {
let mut object = TileData::new();
object.palette = value[0];
object.vram_bank = value[1];
object.xflip = value[2] != 0;
object.yflip = value[3] != 0;
object.priority = value[4] != 0;
object
}
}
impl From<TileData> for Vec<u8> {
fn from(value: TileData) -> Self {
let mut buffer = Vec::with_capacity(5);
buffer.push(value.palette);
buffer.push(value.vram_bank);
buffer.push(if value.xflip { 1 } else { 0 });
buffer.push(if value.yflip { 1 } else { 0 });
buffer.push(if value.priority { 1 } else { 0 });
buffer
}
}
pub struct PpuRegisters {
pub scy: u8,
pub scx: u8,
pub wy: u8,
pub wx: u8,
pub ly: u8,
pub lyc: u8,
}
/// Represents the Game Boy PPU (Pixel Processing Unit) and controls
/// all of the logic behind the graphics processing and presentation.
/// The PPU is responsible for the rendering of the screen and the
/// management of the video memory.
///
/// Should store both the VRAM and HRAM together with the internal
/// graphic related registers. Outputs the screen as an 8 bit RGB
/// frame buffer.
///
/// Current implementation is compatible with both DMG and CGB.
///
/// # Basic usage
///
/// ```rust
/// use boytacean::ppu::Ppu;
/// let mut ppu = Ppu::default();
/// ppu.clock(8);
/// ```
pub struct Ppu {
/// The color buffer that is going to store the colors
/// (from 0 to 3) for all the pixels in the screen.
pub color_buffer: Box<[u8; COLOR_BUFFER_SIZE]>,
/// The shades buffer that is going to store the shade
/// tone value (0 to 3) for all the pixels in the screen (DMG only).
pub shade_buffer: Box<[u8; SHADE_BUFFER_SIZE]>,
/// The 8 bit based RGB frame buffer with the processed
/// set of pixels ready to be displayed on screen.
/// This value may be lazy computed in case the DMG mode
/// is in use, the lazy evaluation is controlled by
/// the `frame_buffer_index` value.
frame_buffer: Box<[u8; FRAME_BUFFER_SIZE]>,
/// The buffer that will control the background to OAM
/// priority, allowing the background to be drawn over
/// the sprites/objects if necessary.
priority_buffer: Box<[bool; COLOR_BUFFER_SIZE]>,
/// Video dedicated memory (VRAM) where both the tiles and
/// the sprites/objects are going to be stored.
vram: [u8; VRAM_SIZE],
/// High RAM memory that should provide extra speed for regular
/// operations.
hram: [u8; HRAM_SIZE],
/// OAM RAM (Sprite Attribute Table ) used for the storage of the
/// sprite attributes for each of the 40 sprites of the Game Boy.
oam: [u8; OAM_SIZE],
/// The VRAM bank to be used in the read and write operation of
/// the 0x8000-0x9FFF memory range (CGB only).
vram_bank: u8,
/// The offset to be used in the read and write operation of
/// the VRAM, this value should be consistent with the VRAM bank
/// that is currently selected (CGB only).
vram_offset: u16,
/// The current set of processed tiles that are stored in the
/// PPU related structures.
tiles: [Tile; TILE_COUNT],
/// The meta information about the sprites/objects that are going
/// to be drawn to the screen,
obj_data: [ObjectData; OBJ_COUNT],
/// The base colors that are going to be used in the registration
/// of the concrete palettes, this value basically controls the
/// colors that are going to be shown for each of the four base
/// values - 0x00, 0x01, 0x02, and 0x03.
palette_colors: Palette,
/// The palette of colors that is currently loaded in Game Boy
/// and used for background (tiles) and window. The value of
/// thi field can be computed value from [`Self::palettes[0]`].
palette_bg: Palette,
/// The palette that is going to be used for sprites/objects #0.
/// The value of this field can be computed value from [`Self::palettes[1]`].
palette_obj_0: Palette,
/// The palette that is going to be used for sprites/objects #1.
/// The value of this field can be computed value from [`Self::palettes[2]`].
palette_obj_1: Palette,
/// The complete set of background palettes that are going to be
/// used in CGB emulation to provide the full set of colors (CGB only).
/// The value of this field can be computed value from [`Self::palettes_color[0]`].
palettes_color_bg: [Palette; 8],
/// The complete set of object/sprite palettes that are going to be
/// used in CGB emulation to provide the full set of colors (CGB only).
/// The value of this field can be computed value from [`Self::palettes_color[1]`].
palettes_color_obj: [Palette; 8],
/// The complete set of palettes in raw binary data so that they can
/// be re-read if required by the system.
/// This field contains the values required to recompute [`Self::palette_bg`],
/// [`Self::palette_obj_0`] and [`Self::palette_obj_1`].
palettes: [u8; 3],
/// The raw binary information (64 bytes) for the color palettes,
/// contains binary information for both the background and
/// the objects palettes (CGB only).
/// This field contains the values required to recompute [`Self::palettes_color_bg`],
/// and [`Self::palettes_color_obj`] .
palettes_color: [[u8; 64]; 2],
/// The complete list of attributes for the first background
/// map that is located in 0x9800-0x9BFF (CGB only).
bg_map_attrs_0: [TileData; 1024],
/// The complete list of attributes for the second background
/// map that is located in 0x9C00-0x9FFF (CGB only).
bg_map_attrs_1: [TileData; 1024],
/// The flag that controls if the object/sprite priority
/// if set means that the priority mode to be used is the
/// X coordinate otherwise the normal CGB OAM memory mode
/// mode is used, the value of this flag is controlled by
/// the OPRI register (CGB only)
obj_priority: bool,
/// The scroll Y register that controls the Y offset
/// of the background.
scy: u8,
/// The scroll X register that controls the X offset
/// of the background.
scx: u8,
/// The top most Y coordinate of the window,
/// going to be used while drawing the window.
wy: u8,
/// The top most X coordinate of the window plus 7,
/// going to be used while drawing the window.
wx: u8,
/// The current scan line in processing, should
/// range between 0 (0x00) and 153 (0x99), representing
/// the 154 lines plus 10 extra V-Blank lines.
ly: u8,
/// The line compare register that is going to be used
/// in the STATE and associated interrupts.
lyc: u8,
/// The current execution mode of the PPU, should change
/// between states over the drawing of a frame.
mode: PpuMode,
/// Internal clock counter used to control the time in ticks
/// spent in each of the PPU modes.
mode_clock: u16,
/// Controls if the background is going to be drawn to screen.
/// In CGB mode this flag controls the master priority instead
/// enabling or disabling complex priority rules.
switch_bg: bool,
/// Controls if the sprites/objects are going to be drawn to screen.
switch_obj: bool,
/// Defines the size in pixels of the object (false=8x8, true=8x16).
obj_size: bool,
/// Controls the map that is going to be drawn to screen, the
/// offset in VRAM will be adjusted according to this
/// (false=0x9800, true=0x9c000).
bg_map: bool,
/// If the background tile set is active meaning that the
/// negative based indexes are going to be used.
bg_tile: bool,
/// Controls if the window is meant to be drawn.
switch_window: bool,
/// Controls the offset of the map that is going to be drawn
/// for the window section of the screen.
window_map: bool,
/// Flag that controls if the LCD screen is ON and displaying
/// content.
switch_lcd: bool,
// Internal window counter value used to control the lines that
// were effectively rendered as part of the window tile drawing process.
// A line is only considered rendered when the WX and WY registers
// are within the valid screen range and the window switch register
// is valid.
window_counter: u8,
/// If the auto increment of the background color palette is enabled
/// so that the next address is going to be set on every write.
auto_increment_bg: bool,
/// The current address in usage for the background color palettes.
palette_address_bg: u8,
/// If the auto increment of the object/sprite color palette is enabled
/// so that the next address is going to be set on every write.
auto_increment_obj: bool,
/// The current address in usage for the object/sprite color palettes.
palette_address_obj: u8,
/// Flag that controls if the frame currently in rendering is the
/// first one, preventing actions.
first_frame: bool,
/// Almost unique identifier of the frame that can be used to debug
/// and uniquely identify the frame that is currently ind drawing,
/// the identifier wraps on the u16 edges.
frame_index: u16,
/// Index of the last frame that was rendered, this value is used
/// to control the deferred rendering of the frame buffer and should
/// prevent unnecessary resource usage.
frame_buffer_index: u16,
stat_hblank: bool,
stat_vblank: bool,
stat_oam: bool,
stat_lyc: bool,
/// Boolean value set when the V-Blank interrupt should be handled
/// by the next CPU clock operation.
int_vblank: bool,
/// Boolean value when the LCD STAT interrupt should be handled by
/// the next CPU clock operation.
int_stat: bool,
/// Previous level of the internal LCD STAT line, used for edge detection
/// so that the LCD STAT interrupt is only triggered on rising edges (0 to 1).
int_stat_prev: bool,
/// Flag that controls if the DMG compatibility mode is
/// enabled meaning that some of the PPU decisions will
/// be made differently to address this special situation
/// (CGB only).
dmg_compat: bool,
/// The current running mode of the emulator, this
/// may affect many aspects of the emulation.
gb_mode: GameBoyMode,
/// The pointer to the parent configuration of the running
/// Game Boy emulator, that can be used to control the behaviour
/// of Game Boy emulation.
gbc: SharedThread<GameBoyConfig>,
}
#[cfg_attr(feature = "wasm", wasm_bindgen)]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum PpuMode {
HBlank = 0,
VBlank = 1,
OamRead = 2,
VramRead = 3,
}
impl From<u8> for PpuMode {
fn from(value: u8) -> Self {
match value {
0 => PpuMode::HBlank,
1 => PpuMode::VBlank,
2 => PpuMode::OamRead,
3 => PpuMode::VramRead,
_ => PpuMode::HBlank,
}
}
}
impl From<PpuMode> for u8 {
fn from(value: PpuMode) -> Self {
value as u8
}
}
impl Ppu {
pub fn new(mode: GameBoyMode, gbc: SharedThread<GameBoyConfig>) -> Self {
Self {
color_buffer: Box::new([0u8; COLOR_BUFFER_SIZE]),
shade_buffer: Box::new([0u8; SHADE_BUFFER_SIZE]),
frame_buffer: Box::new([0u8; FRAME_BUFFER_SIZE]),
priority_buffer: Box::new([false; COLOR_BUFFER_SIZE]),
vram: [0u8; VRAM_SIZE],
hram: [0u8; HRAM_SIZE],
oam: [0u8; OAM_SIZE],
vram_bank: 0x0,
vram_offset: 0x0000,
tiles: [Tile { buffer: [0u8; 64] }; TILE_COUNT],
obj_data: [ObjectData::default(); OBJ_COUNT],
palette_colors: PALETTE_COLORS,
palette_bg: [[0u8; RGB_SIZE]; PALETTE_SIZE],
palette_obj_0: [[0u8; RGB_SIZE]; PALETTE_SIZE],
palette_obj_1: [[0u8; RGB_SIZE]; PALETTE_SIZE],
palettes_color_bg: [[[0u8; RGB_SIZE]; PALETTE_SIZE]; 8],
palettes_color_obj: [[[0u8; RGB_SIZE]; PALETTE_SIZE]; 8],
palettes: [0u8; 3],
palettes_color: [[0u8; 64]; 2],
bg_map_attrs_0: [TileData::default(); 1024],
bg_map_attrs_1: [TileData::default(); 1024],
obj_priority: false,
scy: 0x0,
scx: 0x0,
wy: 0x0,
wx: 0x0,
ly: 0x0,
lyc: 0x0,
mode: PpuMode::OamRead,
mode_clock: 0,
switch_bg: false,
switch_obj: false,
obj_size: false,
bg_map: false,
bg_tile: false,
switch_window: false,
window_map: false,
switch_lcd: false,
window_counter: 0x0,
auto_increment_bg: false,
palette_address_bg: 0x0,
auto_increment_obj: false,
palette_address_obj: 0x0,
first_frame: false,
frame_index: 0,
frame_buffer_index: u16::MAX,
stat_hblank: false,
stat_vblank: false,
stat_oam: false,
stat_lyc: false,
int_vblank: false,
int_stat: false,
int_stat_prev: false,
dmg_compat: false,
gb_mode: mode,
gbc,
}
}
pub fn reset(&mut self) {
*self.color_buffer = [0u8; COLOR_BUFFER_SIZE];
*self.shade_buffer = [0u8; SHADE_BUFFER_SIZE];
*self.frame_buffer = [0u8; FRAME_BUFFER_SIZE];
*self.priority_buffer = [false; COLOR_BUFFER_SIZE];
self.vram = [0u8; VRAM_SIZE_CGB];
self.hram = [0u8; HRAM_SIZE];
self.vram_bank = 0x0;
self.vram_offset = 0x0000;
self.tiles = [Tile { buffer: [0u8; 64] }; TILE_COUNT];
self.obj_data = [ObjectData::default(); OBJ_COUNT];
self.palette_bg = [[0u8; RGB_SIZE]; PALETTE_SIZE];
self.palette_obj_0 = [[0u8; RGB_SIZE]; PALETTE_SIZE];
self.palette_obj_1 = [[0u8; RGB_SIZE]; PALETTE_SIZE];
self.palettes_color_bg = [[[0u8; RGB_SIZE]; PALETTE_SIZE]; 8];
self.palettes_color_obj = [[[0u8; RGB_SIZE]; PALETTE_SIZE]; 8];
self.palettes = [0u8; 3];
self.palettes_color = [[0u8; 64]; 2];
self.bg_map_attrs_0 = [TileData::default(); 1024];
self.bg_map_attrs_1 = [TileData::default(); 1024];
self.obj_priority = false;
self.scy = 0x0;
self.scx = 0x0;
self.ly = 0x0;
self.lyc = 0x0;
self.mode = PpuMode::OamRead;
self.mode_clock = 0;
self.switch_bg = false;
self.switch_obj = false;
self.obj_size = false;
self.bg_map = false;
self.bg_tile = false;
self.switch_window = false;
self.window_map = false;
self.switch_lcd = false;
self.window_counter = 0;
self.auto_increment_bg = false;
self.palette_address_bg = 0x0;
self.auto_increment_obj = false;
self.palette_address_obj = 0x0;
self.first_frame = false;
self.frame_index = 0;
self.frame_buffer_index = u16::MAX;
self.stat_hblank = false;
self.stat_vblank = false;
self.stat_oam = false;
self.stat_lyc = false;
self.int_vblank = false;
self.int_stat = false;
self.int_stat_prev = false;
self.dmg_compat = false;
}
/// Clears the screen and resets the PPU's mode, mode clock, LY registers
/// and VBlank interrupt flag.
///
/// The optional `hard` parameter is used to clear the internal frame
/// buffer, considered to be an expensive operation.
pub fn clear_screen(&mut self, hard: bool) {
self.mode = PpuMode::HBlank;
self.mode_clock = 0;
self.ly = 0;
self.int_vblank = false;
self.int_stat = false;
self.int_stat_prev = false;
self.window_counter = 0;
if hard {
self.first_frame = true;
self.clear_frame_buffer();
}
}
pub fn clock(&mut self, cycles: u16) {
// in case the LCD is currently off then we skip the current
// clock operation the PPU should not work
if !self.switch_lcd {
return;
}
// runs a series of pre-emptive PPU state validations to ensure
// that no core invariants are being violated, this is a pedantic
// only check, proper features must be set
assert_pedantic_gb!(cycles < 80, "Invalid number of cycles in PPU: {}", cycles);
assert_pedantic_gb!(
self.mode_clock < 600,
"Invalid mode clock: {}",
self.mode_clock
);
assert_pedantic_gb!(self.ly < 154, "Invalid LY value: {}", self.ly);
// increments the current mode clock by the provided amount
// of CPU cycles (probably coming from a previous CPU clock)
self.mode_clock += cycles;
match self.mode {
PpuMode::OamRead => {
if self.mode_clock >= 80 {
self.mode = PpuMode::VramRead;
self.mode_clock -= 80;
self.update_stat()
}
}
PpuMode::VramRead => {
if self.mode_clock >= 172 {
self.render_line();
self.mode = PpuMode::HBlank;
self.mode_clock -= 172;
self.update_stat()
}
}
PpuMode::HBlank => {
if self.mode_clock >= 204 {
// increments the window counter making sure that the
// valid is only incremented when both the WX and WY
// registers make sense (are within range), the window
// switch is on and the line in drawing is above WY
if self.switch_window
&& self.wx as i16 - 7 < DISPLAY_WIDTH as i16
&& self.wy < DISPLAY_HEIGHT as u8
&& self.ly >= self.wy
{
self.window_counter += 1;
}
// increments the register that holds the
// information about the current line in drawing
self.ly += 1;
// in case we've reached the end of the
// screen we're now entering the V-Blank
if self.ly == 144 {
self.int_vblank = true;
self.mode = PpuMode::VBlank;
} else {
self.mode = PpuMode::OamRead;
}
self.mode_clock -= 204;
self.update_stat()
}
}
PpuMode::VBlank => {
if self.mode_clock >= 456 {
// increments the register that controls the line count,
// notice that these represent the extra 10 horizontal
// scanlines that are virtual and not real (off-screen)
self.ly += 1;
// in case the end of V-Blank has been reached then
// we must jump again to the OAM read mode and reset
// the scan line counter to the zero value
if self.ly == 154 {
self.mode = PpuMode::OamRead;
self.ly = 0;
self.window_counter = 0;
self.first_frame = false;
self.frame_index = self.frame_index.wrapping_add(1);
}
self.mode_clock -= 456;
self.update_stat()
}
}
}
}
pub fn read(&self, addr: u16) -> u8 {
match addr {
// 0x8000-0x9FFF - Graphics: VRAM (8 KB)
0x8000..=0x9fff => self.vram[(self.vram_offset + (addr & 0x1fff)) as usize],
// 0xFE00-0xFE9F - Object attribute memory (OAM)
0xfe00..=0xfe9f => self.oam[(addr & 0x00ff) as usize],
// 0xFEA0-0xFEFF - Not Usable
0xfea0..=0xfeff => 0xff,
// 0xFF80-0xFFFE - High RAM (HRAM)
0xff80..=0xfffe => self.hram[(addr & 0x007f) as usize],
LCDC_ADDR =>
{
#[allow(clippy::bool_to_int_with_if)]
(if self.switch_bg { 0x01 } else { 0x00 }
| if self.switch_obj { 0x02 } else { 0x00 }
| if self.obj_size { 0x04 } else { 0x00 }
| if self.bg_map { 0x08 } else { 0x00 }
| if self.bg_tile { 0x10 } else { 0x00 }
| if self.switch_window { 0x20 } else { 0x00 }
| if self.window_map { 0x40 } else { 0x00 }
| if self.switch_lcd { 0x80 } else { 0x00 })
}
STAT_ADDR => {
(if self.stat_hblank { 0x08 } else { 0x00 }
| if self.stat_vblank { 0x10 } else { 0x00 }
| if self.stat_oam { 0x20 } else { 0x00 }
| if self.stat_lyc { 0x40 } else { 0x00 }
| if self.lyc == self.ly { 0x04 } else { 0x00 }
| (self.mode as u8 & 0x03)
| 0x80)
}
// 0xFF42 — SCY: Background Y position
SCY_ADDR => self.scy,
// 0xFF43 — SCX: Background X position
SCX_ADDR => self.scx,
// 0xFF44 — LY: LCD Y coordinate
LY_ADDR => self.ly,
// 0xFF45 — LYC: LY compare
LYC_ADDR => self.lyc,
// 0xFF47 — BGP (Non-CGB Mode only)
BGP_ADDR => self.palettes[0],
// 0xFF48 — OBP0 (Non-CGB Mode only)
OBP0_ADDR => self.palettes[1],
// 0xFF49 — OBP1 (Non-CGB Mode only)
OBP1_ADDR => self.palettes[2],
// 0xFF4A — WY
WY_ADDR => self.wy,
// 0xFF4B — WX
WX_ADDR => self.wx,
// 0xFF4F — VBK (CGB only)
0xff4f => self.vram_bank | 0xfe,
// 0xFF68 — BCPS/BGPI (CGB only)
0xff68 => self.palette_address_bg | if self.auto_increment_bg { 0x80 } else { 0x00 },
// 0xFF69 — BCPD/BGPD (CGB only)
0xff69 => self.palettes_color[0][self.palette_address_bg as usize],
// 0xFF6A — OCPS/OBPI (CGB only)
0xff6a => self.palette_address_obj | if self.auto_increment_obj { 0x80 } else { 0x00 },
// 0xFF6B — OCPD/OBPD (CGB only)
0xff6b => self.palettes_color[1][self.palette_address_obj as usize],
// 0xFF6C — OPRI (CGB only)
0xff6c => (if self.obj_priority { 0x01 } else { 0x00 }) | 0xfe,
_ => {
warnln!("Reading from unknown PPU location 0x{:04x}", addr);
#[allow(unreachable_code)]
0xff
}
}
}
pub fn write(&mut self, addr: u16, value: u8) {
match addr {
// 0x8000-0x9FFF - Graphics: VRAM (8 KB)
0x8000..=0x9fff => {
self.vram[(self.vram_offset + (addr & 0x1fff)) as usize] = value;
if addr < 0x9800 {
self.update_tile(addr, value);
} else if self.vram_bank == 0x1 {
self.update_bg_map_attrs(addr, value);
}
}
// 0xFE00-0xFE9F - Object attribute memory (OAM)
0xfe00..=0xfe9f => {
self.oam[(addr & 0x00ff) as usize] = value;
self.update_object(addr, value);
}
// 0xFEA0-0xFEFF - Not Usable
0xfea0..=0xfeff => (),
// 0xFF80-0xFFFE - High RAM (HRAM)
0xff80..=0xfffe => self.hram[(addr & 0x007f) as usize] = value,
LCDC_ADDR => {
self.switch_bg = value & 0x01 == 0x01;
self.switch_obj = value & 0x02 == 0x02;
self.obj_size = value & 0x04 == 0x04;
self.bg_map = value & 0x08 == 0x08;
self.bg_tile = value & 0x10 == 0x10;
self.switch_window = value & 0x20 == 0x20;
self.window_map = value & 0x40 == 0x40;
self.switch_lcd = value & 0x80 == 0x80;
// in case the LCD is off takes the opportunity
// to clear the screen, this is the expected
// behaviour for this specific situation
if !self.switch_lcd {
self.clear_screen(true)
}
}
STAT_ADDR => {
self.stat_hblank = value & 0x08 == 0x08;
self.stat_vblank = value & 0x10 == 0x10;
self.stat_oam = value & 0x20 == 0x20;
self.stat_lyc = value & 0x40 == 0x40;
if self.switch_lcd {
// DMG STAT bug: writing to STAT momentarily glitches
// the internal STAT line low, so we force a rising-edge
// re-evaluation which may trigger a spurious interrupt
if self.gb_mode == GameBoyMode::Dmg {
self.int_stat_prev = false;
}
// re-evaluate STAT line after changing the enable flags,
// a new condition may now be met causing a rising edge
self.update_stat();
}
}
// 0xFF42 — SCY: Background Y position
SCY_ADDR => self.scy = value,
// 0xFF43 — SCX: Background X position
SCX_ADDR => self.scx = value,
// 0xFF45 — LYC: LY compare
LYC_ADDR => {
self.lyc = value;
self.update_stat();
}
// 0xFF47 — BGP (Non-CGB Mode only)
BGP_ADDR => {
if value == self.palettes[0] {
return;
}
if self.dmg_compat {
Self::compute_palette(&mut self.palette_bg, &self.palettes_color_bg[0], value);
} else {
Self::compute_palette(&mut self.palette_bg, &self.palette_colors, value);
}
self.palettes[0] = value;
}
// 0xFF48 — OBP0 (Non-CGB Mode only)
OBP0_ADDR => {
if value == self.palettes[1] {
return;
}
if self.dmg_compat {
Self::compute_palette(
&mut self.palette_obj_0,
&self.palettes_color_obj[0],
value,
);
} else {
Self::compute_palette(&mut self.palette_obj_0, &self.palette_colors, value);
}
self.palettes[1] = value;
}
// 0xFF49 — OBP0 (Non-CGB Mode only)
OBP1_ADDR => {
if value == self.palettes[2] {
return;
}
if self.dmg_compat {
Self::compute_palette(
&mut self.palette_obj_1,
&self.palettes_color_obj[1],
value,
);
} else {
Self::compute_palette(&mut self.palette_obj_1, &self.palette_colors, value);
}
self.palettes[2] = value;
}
// 0xFF4A — WY
WY_ADDR => self.wy = value,
// 0xFF4B — WX
WX_ADDR => self.wx = value,
// 0xFF4F — VBK (CGB only)
0xff4f => {
self.vram_bank = value & 0x01;
self.vram_offset = self.vram_bank as u16 * 0x2000;
}
// 0xFF68 — BCPS/BGPI (CGB only)
0xff68 => {
self.palette_address_bg = value & 0x3f;
self.auto_increment_bg = value & 0x80 == 0x80;
}
// 0xFF69 — BCPD/BGPD (CGB only)
0xff69 => {
let palette_index = self.palette_address_bg / 8;
let color_index = (self.palette_address_bg % 8) / 2;
let palette_color = &mut self.palettes_color[0];
palette_color[self.palette_address_bg as usize] = value;
let palette = &mut self.palettes_color_bg[palette_index as usize];
Self::compute_palette_color(palette, palette_color, palette_index, color_index);
if self.auto_increment_bg {
self.palette_address_bg = (self.palette_address_bg + 1) & 0x3f;
}
}
// 0xFF6A — OCPS/OBPI (CGB only)
0xff6a => {
self.palette_address_obj = value & 0x3f;
self.auto_increment_obj = value & 0x80 == 0x80;
}
// 0xFF6B — OCPD/OBPD (CGB only)
0xff6b => {
let palette_index = self.palette_address_obj / 8;
let color_index = (self.palette_address_obj % 8) / 2;
let palette_color = &mut self.palettes_color[1];
palette_color[self.palette_address_obj as usize] = value;
let palette = &mut self.palettes_color_obj[palette_index as usize];
Self::compute_palette_color(palette, palette_color, palette_index, color_index);
if self.auto_increment_obj {
self.palette_address_obj = (self.palette_address_obj + 1) & 0x3f;
}
}
// 0xFF6C — OPRI (CGB only)
0xff6c => self.obj_priority = value & 0x01 == 0x01,
0xff7f => (),
_ => warnln!("Writing in unknown PPU location 0x{:04x}", addr),
}
}
pub fn frame_buffer(&mut self) -> &[u8; FRAME_BUFFER_SIZE] {
if self.gb_mode != GameBoyMode::Dmg {
return &self.frame_buffer;
}
if self.frame_index == self.frame_buffer_index {
return &self.frame_buffer;
}
for (index, pixel) in self.frame_buffer.chunks_mut(RGB_SIZE).enumerate() {
let shade_index = self.shade_buffer[index];
let color = &self.palette_colors[shade_index as usize];
pixel[0] = color[0];
pixel[1] = color[1];
pixel[2] = color[2];
}
self.frame_buffer_index = self.frame_index;
&self.frame_buffer
}
pub fn frame_buffer_xrgb8888(&mut self) -> [u8; FRAME_BUFFER_XRGB8888_SIZE] {
let frame_buffer = self.frame_buffer();
let mut buffer = [0u8; FRAME_BUFFER_XRGB8888_SIZE];
for index in 0..DISPLAY_SIZE {
let (r, g, b) = (
frame_buffer[index * RGB_SIZE],
frame_buffer[index * RGB_SIZE + 1],
frame_buffer[index * RGB_SIZE + 2],
);
buffer[index * XRGB8888_SIZE] = b;
buffer[index * XRGB8888_SIZE + 1] = g;
buffer[index * XRGB8888_SIZE + 2] = r;
buffer[index * XRGB8888_SIZE + 3] = 0xff;
}
buffer
}
pub fn frame_buffer_xrgb8888_u32(&mut self) -> [u32; FRAME_BUFFER_SIZE] {
let frame_buffer = self.frame_buffer();
let mut buffer = [0u32; FRAME_BUFFER_SIZE];
for (index, pixel) in buffer.iter_mut().enumerate().take(DISPLAY_SIZE) {
let (r, g, b) = (
frame_buffer[index * RGB_SIZE],
frame_buffer[index * RGB_SIZE + 1],
frame_buffer[index * RGB_SIZE + 2],
);
*pixel = ((r as u32) << 16) | ((g as u32) << 8) | b as u32;
}
buffer
}
pub fn frame_buffer_rgb1555(&mut self) -> [u8; FRAME_BUFFER_RGB1555_SIZE] {
let frame_buffer = self.frame_buffer();
let mut buffer = [0u8; FRAME_BUFFER_RGB1555_SIZE];
rgb888_to_rgb1555_array(frame_buffer, &mut buffer);
buffer
}
pub fn frame_buffer_rgb1555_u16(&mut self) -> [u16; FRAME_BUFFER_SIZE] {
let frame_buffer = self.frame_buffer();
let mut buffer = [0u16; FRAME_BUFFER_SIZE];
for (index, pixel) in buffer.iter_mut().enumerate().take(DISPLAY_SIZE) {
let (r, g, b) = (
frame_buffer[index * RGB_SIZE],
frame_buffer[index * RGB_SIZE + 1],
frame_buffer[index * RGB_SIZE + 2],
);
*pixel = rgb888_to_rgb1555_u16(r, g, b);
}
buffer
}
pub fn frame_buffer_rgb565(&mut self) -> [u8; FRAME_BUFFER_RGB565_SIZE] {
let frame_buffer = self.frame_buffer();
let mut buffer = [0u8; FRAME_BUFFER_RGB565_SIZE];
for index in 0..DISPLAY_SIZE {
let (r, g, b) = (
frame_buffer[index * RGB_SIZE],
frame_buffer[index * RGB_SIZE + 1],
frame_buffer[index * RGB_SIZE + 2],
);
let rgb565 = rgb888_to_rgb565(r, g, b);
buffer[index * RGB565_SIZE] = rgb565[0];
buffer[index * RGB565_SIZE + 1] = rgb565[1];
}
buffer
}
pub fn frame_buffer_rgb565_u16(&mut self) -> [u16; FRAME_BUFFER_SIZE] {
let frame_buffer = self.frame_buffer();
let mut buffer = [0u16; FRAME_BUFFER_SIZE];
for (index, pixel) in buffer.iter_mut().enumerate().take(DISPLAY_SIZE) {
let (r, g, b) = (
frame_buffer[index * RGB_SIZE],
frame_buffer[index * RGB_SIZE + 1],
frame_buffer[index * RGB_SIZE + 2],
);
*pixel = rgb888_to_rgb565_u16(r, g, b);
}
buffer
}
pub fn frame_buffer_rgba(&mut self) -> [u8; FRAME_BUFFER_RGBA_SIZE] {
let frame_buffer = self.frame_buffer();
let mut buffer = [0u8; FRAME_BUFFER_RGBA_SIZE];
for index in 0..DISPLAY_SIZE {
let (r, g, b) = (
frame_buffer[index * RGB_SIZE],
frame_buffer[index * RGB_SIZE + 1],
frame_buffer[index * RGB_SIZE + 2],
);
buffer[index * RGBA_SIZE] = r;
buffer[index * RGBA_SIZE + 1] = g;
buffer[index * RGBA_SIZE + 2] = b;
buffer[index * RGBA_SIZE + 3] = 0xff;
}
buffer
}
/// Obtains the "raw" version of the frame buffer any custom
/// color palette operation applied to it. This is can be an
/// extremely slow operation (in DMG devices) and because of
/// that should be used carefully.
pub fn frame_buffer_raw(&self) -> [u8; FRAME_BUFFER_SIZE] {
self.frame_buffer_palette(&BASIC_PALETTE)
}
/// Obtains the frame buffer with the colors mapped according
/// to the provided palette of colors.
/// This method is very slow and only useful for the DMG mode
/// which can have its simple colors mapped to palettes.
pub fn frame_buffer_palette(&self, palette_colors: &Palette) -> [u8; FRAME_BUFFER_SIZE] {
if self.gb_mode == GameBoyMode::Dmg {
let mut buffer = [0u8; FRAME_BUFFER_SIZE];
for (index, pixel) in buffer.chunks_mut(RGB_SIZE).enumerate() {
let shade_index = self.shade_buffer[index];
let color = &palette_colors[shade_index as usize];
pixel[0] = color[0];
pixel[1] = color[1];
pixel[2] = color[2];
}
buffer
} else {
*self.frame_buffer.clone()
}
}
pub fn vram(&self) -> &[u8; VRAM_SIZE] {
&self.vram
}
pub fn vram_dmg(&self) -> &[u8] {
&self.vram[0..VRAM_SIZE_DMG]
}
pub fn vram_cgb(&self) -> &[u8] {
&self.vram[0..VRAM_SIZE_CGB]
}
pub fn vram_device(&self) -> &[u8] {
match self.gb_mode {
GameBoyMode::Dmg => self.vram_dmg(),
GameBoyMode::Cgb => self.vram_cgb(),
GameBoyMode::Sgb => self.vram_dmg(),
}
}
pub fn set_vram(&mut self, value: &[u8]) {
self.vram[0..value.len()].copy_from_slice(value);
self.update_vram();
}
pub fn oam(&self) -> &[u8; OAM_SIZE] {
&self.oam
}
pub fn set_oam(&mut self, value: &[u8]) {
self.oam[0..value.len()].copy_from_slice(value);
self.update_oam();
}
pub fn hram(&self) -> &[u8; HRAM_SIZE] {
&self.hram
}
pub fn set_hram(&mut self, value: &[u8]) {
self.hram[0..value.len()].copy_from_slice(value);
}
pub fn tiles(&self) -> &[Tile; TILE_COUNT] {
&self.tiles
}
pub fn set_palette_colors(&mut self, value: &Palette) {
self.palette_colors = *value;
self.compute_palettes()
}
pub fn palette_bg(&self) -> Palette {
self.palette_bg
}
pub fn palette_obj_0(&self) -> Palette {
self.palette_obj_0
}
pub fn palette_obj_1(&self) -> Palette {
self.palette_obj_1
}
pub fn palettes_color(&self) -> &[[u8; 64]; 2] {
&self.palettes_color
}
pub fn set_palettes_color(&mut self, palettes_color: [[u8; 64]; 2]) {
self.palettes_color = palettes_color;
Self::compute_palettes_color(
&mut [&mut self.palettes_color_bg, &mut self.palettes_color_obj],
&self.palettes_color,
);
}
pub fn ly(&self) -> u8 {
self.ly
}
pub fn mode(&self) -> PpuMode {
self.mode
}
pub fn frame_index(&self) -> u16 {
self.frame_index
}
#[inline(always)]
pub fn int_vblank(&self) -> bool {
self.int_vblank
}
#[inline(always)]
pub fn set_int_vblank(&mut self, value: bool) {
self.int_vblank = value;
}
#[inline(always)]
pub fn ack_vblank(&mut self) {
self.set_int_vblank(false);
}
#[inline(always)]
pub fn int_stat(&self) -> bool {
self.int_stat
}
#[inline(always)]
pub fn set_int_stat(&mut self, value: bool) {
self.int_stat = value;
}
#[inline(always)]
pub fn int_stat_prev(&self) -> bool {
self.int_stat_prev
}
#[inline(always)]
pub fn set_int_stat_prev(&mut self, value: bool) {
self.int_stat_prev = value;
}
#[inline(always)]
pub fn ack_stat(&mut self) {
self.set_int_stat(false);
}
pub fn dmg_compat(&self) -> bool {
self.dmg_compat
}
pub fn set_dmg_compat(&mut self, value: bool) {
self.dmg_compat = value;
// if we're switching to the DMG compat mode
// then we need to recompute the palettes so
// that the colors are correct according to
// the compat palettes set by the Boot ROM
if value {
self.compute_palettes();
}
}
pub fn gb_mode(&self) -> GameBoyMode {
self.gb_mode
}
pub fn set_gb_mode(&mut self, value: GameBoyMode) {
self.gb_mode = value;
}
pub fn set_gbc(&mut self, value: SharedThread<GameBoyConfig>) {
self.gbc = value;
}
/// Fills the frame buffer with pixels of the provided color,
/// this method should represent the fastest way of achieving
/// the fill background with color operation.
pub fn fill_frame_buffer(&mut self, shade_index: u8) {
let color = &self.palette_colors[shade_index as usize];
self.color_buffer.fill(0);
self.shade_buffer.fill(shade_index);
self.frame_buffer_index = u16::MAX;
for pixel in self.frame_buffer.chunks_mut(RGB_SIZE) {
pixel[0] = color[0];
pixel[1] = color[1];
pixel[2] = color[2];
}
}
/// Clears the current frame buffer, setting the background color
/// for all the pixels in the frame buffer.
pub fn clear_frame_buffer(&mut self) {
self.fill_frame_buffer(0);
}
/// Prints the tile data information to the stdout, this is
/// useful for debugging purposes.
pub fn print_tile_stdout(&self, tile_index: usize) {
println!("{}", self.tiles[tile_index]);
}
/// Updates the internal PPU state (calculated values) according
/// to the VRAM values, this should be called whenever the VRAM
/// data is replaced (eg: state loading).
pub fn update_vram(&mut self) {
// "saves" the old values of the VRAM bank and offset
// as they are going to be needed later, this is required
// as we're going to trick the PPU into switching banks
// over the update of the calculated values for the new VRAM,
// essentially required for the `update_tile()` method
let (vram_bank_old, vram_offset_old) = (self.vram_bank, self.vram_offset);
// determines the number of VRAM banks available according
// to the running Game Boy running mode (CGB vs DMG)
let vram_banks = if self.gb_mode == GameBoyMode::Cgb {
2u8
} else {
1u8
};
// goes over all the VRAM banks, and over all the VRAM addresses
// in those banks to update the internal tiles and background map
// attributes structures accordingly
for vram_bank in 0..vram_banks {
self.vram_bank = vram_bank;
self.vram_offset = self.vram_bank as u16 * 0x2000;
for addr in 0x8000..=0x9fff {
let value = self.vram[(self.vram_offset + (addr & 0x1fff)) as usize];
if addr < 0x9800 {
self.update_tile(addr, value);
} else if self.vram_bank == 0x1 {
self.update_bg_map_attrs(addr, value);
}
}
}
// restores the "old" values for VRAM bank and offset
(self.vram_bank, self.vram_offset) = (vram_bank_old, vram_offset_old);
}
/// Updates the internal PPU state (calculated values) according
/// to the OAM values, this should be called whenever the OAM
/// data is replaced (eg: state loading).
fn update_oam(&mut self) {
for addr in 0xfe00..=0xfe9f {
let value = self.oam[(addr & 0x00ff) as usize];
self.update_object(addr, value);
}
}
/// Updates the tile structure with the value that has
/// just been written to a location on the VRAM associated
/// with tiles.
fn update_tile(&mut self, addr: u16, _value: u8) {
let addr = (self.vram_offset + (addr & 0x1ffe)) as usize;
let tile_index = ((addr >> 4) & 0x01ff) + (self.vram_bank as usize * TILE_COUNT_DMG);
let tile = self.tiles[tile_index].borrow_mut();
let y = (addr >> 1) & 0x0007;
let mut mask;
for x in 0..TILE_WIDTH {
mask = 1 << (TILE_WIDTH_I - x);
#[allow(clippy::bool_to_int_with_if)]
tile.set(
x,
y,
if self.vram[addr] & mask > 0 { 0x1 } else { 0x0 }
| if self.vram[addr + 1] & mask > 0 {
0x2
} else {
0x0
},
);
}
}
fn update_object(&mut self, addr: u16, value: u8) {
let addr = (addr & 0x01ff) as usize;
let obj_index = addr >> 2;
if obj_index >= OBJ_COUNT {
return;
}
let obj = self.obj_data[obj_index].borrow_mut();
match addr & 0x03 {
0x00 => obj.y = value as i16 - 16,
0x01 => obj.x = value as i16 - 8,
0x02 => obj.tile = value,
0x03 => {
obj.palette_cgb = value & 0x07;
obj.tile_bank = (value & 0x08 == 0x08) as u8;
obj.palette = (value & 0x10 == 0x10) as u8;
obj.xflip = value & 0x20 == 0x20;
obj.yflip = value & 0x40 == 0x40;
obj.bg_over = value & 0x80 == 0x80;
obj.index = obj_index as u8;
}
_ => (),
}
}
fn update_bg_map_attrs(&mut self, addr: u16, value: u8) {
let bg_map = addr >= 0x9c00;
let tile_index = if bg_map { addr - 0x9c00 } else { addr - 0x9800 };
let bg_map_attrs = if bg_map {
&mut self.bg_map_attrs_1
} else {
&mut self.bg_map_attrs_0
};
let tile_data: &mut TileData = bg_map_attrs[tile_index as usize].borrow_mut();
tile_data.palette = value & 0x07;
tile_data.vram_bank = (value & 0x08 == 0x08) as u8;
tile_data.xflip = value & 0x20 == 0x20;
tile_data.yflip = value & 0x40 == 0x40;
tile_data.priority = value & 0x80 == 0x80;
}
pub fn registers(&self) -> PpuRegisters {
PpuRegisters {
scy: self.scy,
scx: self.scx,
wy: self.wy,
wx: self.wx,
ly: self.ly,
lyc: self.lyc,
}
}
fn render_line(&mut self) {
if self.gb_mode == GameBoyMode::Dmg {
self.render_line_dmg();
} else {
self.render_line_cgb();
}
}
fn render_line_dmg(&mut self) {
if self.first_frame {
return;
}
if self.switch_bg {
self.render_map_dmg(self.bg_map, self.scx, self.scy, 0, 0, self.ly);
}
if self.switch_bg && self.switch_window {
self.render_map_dmg(self.window_map, 0, 0, self.wx, self.wy, self.window_counter);
}
if self.switch_obj {
self.render_objects();
}
}
fn render_line_cgb(&mut self) {
if self.first_frame {
return;
}
let switch_bg_window = (self.gb_mode.is_cgb() && !self.dmg_compat) || self.switch_bg;
if switch_bg_window {
self.render_map(self.bg_map, self.scx, self.scy, 0, 0, self.ly);
}
if switch_bg_window && self.switch_window {
self.render_map(self.window_map, 0, 0, self.wx, self.wy, self.window_counter);
}
if self.switch_obj {
self.render_objects();
}
}
fn render_map(&mut self, map: bool, scx: u8, scy: u8, wx: u8, wy: u8, ld: u8) {
// in case the target window Y position has not yet been reached
// then there's nothing to be done, returns control flow immediately
if self.ly < wy {
return;
}
// selects the correct background attributes map based on the bg map flag
// because the attributes are separated according to the map they represent
// this is only relevant for CGB mode
let bg_map_attrs = if map {
self.bg_map_attrs_1
} else {
self.bg_map_attrs_0
};
// obtains the base address of the background map using the bg map flag
// that control which background map is going to be used
let map_offset: usize = if map { 0x1c00 } else { 0x1800 };
// calculates the map row index for the tile by using the current line
// index and the DY (scroll Y) divided by 8 (as the tiles are 8x8 pixels),
// on top of that ensures that the result is modulus 32 meaning that the
// drawing wraps around the Y axis
let row_index = (((ld as usize + scy as usize) & 0xff) >> 3) % 32;
// calculates the map offset by the row offset multiplied by the number
// of tiles in each row (32)
let row_offset = row_index * 32;
// calculates the sprite line offset by using the SCX register
// shifted by 3 meaning that the tiles are 8x8
let mut line_offset = (scx >> 3) as usize;
// calculates the index of the initial tile in drawing,
// if the tile data set in use is #1, the indexes are
// signed, then calculates a real tile offset
let mut tile_index = self.vram[map_offset + row_offset + line_offset] as usize;
if !self.bg_tile && tile_index < 128 {
tile_index += 256;
}
// obtains the reference to the attributes of the new tile in
// drawing for meta processing (CGB only)
let mut tile_attr = if self.dmg_compat {
&DEFAULT_TILE_ATTR
} else {
&bg_map_attrs[row_offset + line_offset]
};
// retrieves the proper palette for the current tile in drawing
// taking into consideration if we're running in CGB mode or not
let mut palette = if self.gb_mode == GameBoyMode::Cgb {
if self.dmg_compat {
&self.palette_bg
} else {
&self.palettes_color_bg[tile_attr.palette as usize]
}
} else {
&self.palette_bg
};
// obtains the current integer value (raw) for the background palette
// this is going to be used for shade index value computation (DMG only)
let palette_v = self.palettes[0];
// obtains the values of both X and Y flips for the current tile
// they will be applied by the get tile pixel method
let mut xflip = tile_attr.xflip;
let mut yflip = tile_attr.yflip;
// obtains the value the BG-to-OAM priority to be used in the computation
// of the final pixel value (CGB only)
let mut priority = tile_attr.priority;
// increments the tile index value by the required offset for the VRAM
// bank in which the tile is stored, this is only required for CGB mode
tile_index += tile_attr.vram_bank as usize * TILE_COUNT_DMG;
// obtains the reference to the tile that is going to be drawn
let mut tile = &self.tiles[tile_index];
// calculates the offset that is going to be used in the update of the color buffer
// which stores Game Boy colors from 0 to 3
let mut color_offset = self.ly as usize * DISPLAY_WIDTH;
// calculates the frame buffer offset position assuming the proper
// Game Boy screen width and RGB pixel (3 bytes) size
let mut frame_offset = self.ly as usize * DISPLAY_WIDTH * RGB_SIZE;
// calculates both the current Y and X positions within the tiles
// using the bitwise and operation as an effective modulus 8
let y = (ld as usize + scy as usize) & 0x07;
let mut x = (scx & 0x07) as usize;
// calculates the initial tile X position in drawing, doing this
// allows us to position the background map properly in the display
let initial_index = max(wx as i16 - 7, 0) as usize;
color_offset += initial_index;
frame_offset += initial_index * RGB_SIZE;
// iterates over all the pixels in the current line of the display
// to draw the background map, note that the initial index is used
// to skip the drawing of the tiles that are not visible (WX)
for _ in initial_index..DISPLAY_WIDTH {
// obtains the current pixel data from the tile
let pixel = tile.get_flipped(x, y, xflip, yflip);
// updates the pixel in the color buffer, which stores
// the raw pixel color information (unmapped) and then
// updates the shade buffer with the shade index
self.color_buffer[color_offset] = pixel;
self.shade_buffer[color_offset] = (palette_v >> (pixel * 2)) & 3;
// re-maps the pixel according to the current palette
// and sets the color pixel in the frame buffer
let color = &palette[pixel as usize];
self.frame_buffer[frame_offset] = color[0];
self.frame_buffer[frame_offset + 1] = color[1];
self.frame_buffer[frame_offset + 2] = color[2];
// updates the priority buffer with the current pixel
// the priority is only set in case the priority of
// the background (over OAM) is set in the attributes
// and the pixel is not transparent
self.priority_buffer[color_offset] = priority && pixel != 0;
// increments the current tile X position in drawing
x += 1;
// in case the end of tile width has been reached then
// a new tile must be retrieved for rendering
if x == TILE_WIDTH {
// resets the tile X position to the base value
// as a new tile is going to be drawn
x = 0;
// calculates the new line tile offset making sure that
// the maximum of 32 is not overflown
line_offset = (line_offset + 1) % 32;
// calculates the tile index and makes sure the value
// takes into consideration the bg tile value
tile_index = self.vram[map_offset + row_offset + line_offset] as usize;
if !self.bg_tile && tile_index < 128 {
tile_index += 256;
}
// in case the current mode is CGB and the DMG compatibility
// flag is not set then a series of tile values must be
// updated according to the tile attributes field
if self.gb_mode == GameBoyMode::Cgb && !self.dmg_compat {
tile_attr = &bg_map_attrs[row_offset + line_offset];
palette = &self.palettes_color_bg[tile_attr.palette as usize];
xflip = tile_attr.xflip;
yflip = tile_attr.yflip;
priority = tile_attr.priority;
tile_index += tile_attr.vram_bank as usize * TILE_COUNT_DMG;
}
// obtains the reference to the new tile in drawing
tile = &self.tiles[tile_index];
}
// increments the color offset by one, representing
// the drawing of one pixel
color_offset += 1;
// increments the offset of the frame buffer by the
// size of an RGB pixel (which is 3 bytes)
frame_offset += RGB_SIZE;
}
}
fn render_map_dmg(&mut self, map: bool, scx: u8, scy: u8, wx: u8, wy: u8, ld: u8) {
// in case the target window Y position has not yet been reached
// then there's nothing to be done, returns control flow immediately
if self.ly < wy {
return;
}
// obtains the base address of the background map using the bg map flag
// that control which background map is going to be used
let map_offset: usize = if map { 0x1c00 } else { 0x1800 };
// calculates the map row index for the tile by using the current line
// index and the DY (scroll Y) divided by 8 (as the tiles are 8x8 pixels),
// on top of that ensures that the result is modulus 32 meaning that the
// drawing wraps around the Y axis
let row_index = (((ld as usize + scy as usize) & 0xff) >> 3) % 32;
// calculates the map offset by the row offset multiplied by the number
// of tiles in each row (32)
let row_offset = row_index * 32;
// calculates the sprite line offset by using the SCX register
// shifted by 3 meaning that the tiles are 8x8
let mut line_offset = (scx >> 3) as usize;
// calculates the index of the initial tile in drawing,
// if the tile data set in use is #1, the indexes are
// signed, then calculates a real tile offset
let mut tile_index = self.vram[map_offset + row_offset + line_offset] as usize;
if !self.bg_tile && tile_index < 128 {
tile_index += 256;
}
// obtains the reference to the tile that is going to be drawn
let mut tile = &self.tiles[tile_index];
// calculates the offset that is going to be used in the update of the color buffer
// which stores Game Boy colors from 0 to 3
let mut color_offset = self.ly as usize * DISPLAY_WIDTH;
// obtains the current integer value (raw) for the background palette
// this is going to be used for shade index value computation (DMG only)
let palette_v = self.palettes[0];
// calculates both the current Y and X positions within the tiles
// using the bitwise and operation as an effective modulus 8
let y = (ld as usize + scy as usize) & 0x07;
let mut x = (scx & 0x07) as usize;
// calculates the initial tile X position in drawing, doing this
// allows us to position the background map properly in the display
let initial_index = max(wx as i16 - 7, 0) as usize;
color_offset += initial_index;
// iterates over all the pixels in the current line of the display
// to draw the background map, note that the initial index is used
// to skip the drawing of the tiles that are not visible (WX)
for _ in initial_index..DISPLAY_WIDTH {
// obtains the current pixel data from the tile
let pixel = tile.get(x, y);
// updates the pixel in the color buffer, which stores
// the raw pixel color information (unmapped) and then
// updates the shade buffer with the shade index
self.color_buffer[color_offset] = pixel;
self.shade_buffer[color_offset] = (palette_v >> (pixel * 2)) & 3;
// increments the current tile X position in drawing
x += 1;
// in case the end of tile width has been reached then
// a new tile must be retrieved for rendering
if x == TILE_WIDTH {
// resets the tile X position to the base value
// as a new tile is going to be drawn
x = 0;
// calculates the new line tile offset making sure that
// the maximum of 32 is not overflown
line_offset = (line_offset + 1) % 32;
// calculates the tile index and makes sure the value
// takes into consideration the bg tile value
tile_index = self.vram[map_offset + row_offset + line_offset] as usize;
if !self.bg_tile && tile_index < 128 {
tile_index += 256;
}
// obtains the reference to the new tile in drawing
tile = &self.tiles[tile_index];
}
// increments the color offset by one, representing
// the drawing of one pixel
color_offset += 1;
}
}
fn render_objects(&mut self) {
// the mode in which the object priority should be computed
// if true this means that the X coordinate priority mode will
// be used otherwise the object priority will be defined according
// to the object's index in the OAM memory, notice that this
// control of priority is only present in the CGB and to be able
// to offer retro-compatibility with DMG
let obj_priority_mode = self.gb_mode != GameBoyMode::Cgb || self.obj_priority;
// creates a local counter object to count the total number
// of object that were drawn in the current line, this will
// be used for instance to limit the total number of objects
// to 10 per line (Game Boy limitation)
let mut draw_count = 0u8;
// allocates the buffer that is going to be used to determine
// drawing priority for overlapping pixels between different
// objects, in MBR mode the object that has the smallest X
// coordinate takes priority in drawing the pixel
let mut index_buffer = [-256i16; DISPLAY_WIDTH];
// determines if the object should always be placed over the
// possible background, this is only required for CGB mode
let always_over = if self.gb_mode == GameBoyMode::Cgb && !self.dmg_compat {
!self.switch_bg
} else {
false
};
// iterates over the complete set of available object to check
// the ones that require drawing and draws them
for index in 0..OBJ_COUNT {
// in case the limit on the number of objects to be draw per
// line has been reached breaks the loop avoiding more draws
if draw_count == 10 {
break;
}
// obtains the meta data of the object that is currently
// under iteration to be checked for drawing
let obj = &self.obj_data[index];
let obj_height = if self.obj_size {
TILE_DOUBLE_HEIGHT
} else {
TILE_HEIGHT
};
// verifies if the sprite is currently located at the
// current line that is going to be drawn and skips it
// in case it's not
let is_contained =
(obj.y <= self.ly as i16) && ((obj.y + obj_height as i16) > self.ly as i16);
if !is_contained {
continue;
}
let (palette, palette_index) = if self.gb_mode == GameBoyMode::Cgb {
if self.dmg_compat {
if obj.palette == 0 {
(&self.palette_obj_0, 0_u8)
} else if obj.palette == 1 {
(&self.palette_obj_1, 0_u8)
} else {
panic_gb!("Invalid object palette: {:02x}", obj.palette);
}
} else {
(&self.palettes_color_obj[obj.palette_cgb as usize], 0_u8)
}
} else if obj.palette == 0 {
(&self.palette_obj_0, 1_u8)
} else if obj.palette == 1 {
(&self.palette_obj_1, 2_u8)
} else {
panic_gb!("Invalid object palette: {:02x}", obj.palette);
};
// obtains the current integer value (raw) for the palette in use
// this is going to be used for shade index value computation (DMG only)
let palette_v = self.palettes[palette_index as usize];
// calculates the base offset in the color buffer (raw color
// information from 0 to 3) for the sprite that is going to be
// drawn, each tile pixel adds to this base to get the final offset
let color_base = self.ly as i32 * DISPLAY_WIDTH as i32 + obj.x as i32;
// calculates the base offset in the frame buffer for the sprite
// that is going to be drawn, each tile pixel adds to this base
// (scaled by RGB_SIZE) to get the final frame buffer position
let frame_base =
(self.ly as i32 * DISPLAY_WIDTH as i32 + obj.x as i32) * RGB_SIZE as i32;
// the relative title offset should range from 0 to 7 in 8x8
// objects and from 0 to 15 in 8x16 objects
let mut tile_offset = self.ly as i16 - obj.y;
// in case we're flipping the object we must recompute the
// tile offset as an inverted value using the object's height
if obj.yflip {
tile_offset = obj_height as i16 - tile_offset - 1;
}
// saves some space for the reference to the tile that
// is going to be used in the current operation
let tile: &Tile;
// "calculates" the index offset that is going to be applied
// to the tile index to retrieve the proper tile taking into
// consideration the VRAM in which the tile is stored
let tile_bank_offset = if self.dmg_compat {
0
} else {
obj.tile_bank as usize * TILE_COUNT_DMG
};
// in case we're facing a 8x16 object then we must
// differentiate between the handling of the top tile
// and the bottom tile through bitwise manipulation
// of the tile index
if self.obj_size {
if tile_offset < 8 {
let tile_index = (obj.tile as usize & 0xfe) + tile_bank_offset;
tile = &self.tiles[tile_index];
} else {
let tile_index = (obj.tile as usize | 0x01) + tile_bank_offset;
tile = &self.tiles[tile_index];
tile_offset -= 8;
}
}
// otherwise we're facing a 8x8 sprite and we should grab
// the tile directly from the object's tile index
else {
let tile_index = obj.tile as usize + tile_bank_offset;
tile = &self.tiles[tile_index];
}
let tile_row = tile.get_row(tile_offset as usize);
// determines if the object should always be placed over the
// previously placed background or window pixels
let obj_over = always_over || !obj.bg_over;
for tile_x in 0..TILE_WIDTH {
// calculates the color buffer offset for the current pixel in iteration,
// this is going to be used to update the color buffer and the shade buffer
let color_offset = color_base + tile_x as i32;
let frame_offset = frame_base + tile_x as i32 * RGB_SIZE as i32;
let x = obj.x + tile_x as i16;
let is_contained = (x >= 0) && (x < DISPLAY_WIDTH as i16);
if is_contained {
// the object is only considered visible if no background or
// window should be drawn over or if the underlying pixel
// is transparent (zero value) meaning there's no background
// or window for the provided pixel
let mut is_visible = obj_over || self.color_buffer[color_offset as usize] == 0;
// additionally (in CCG mode) the object is only considered to
// be visible if the priority buffer is not set for the current
// pixel, this means that the background is capturing priority
// by having the BG-to-OAM priority bit set in the bg map attributes
is_visible &= always_over || !self.priority_buffer[color_offset as usize];
// determines if the current pixel has priority over a possible
// one that has been drawn by a previous object, this happens
// in case the current object has a small X coordinate according
// to the MBR algorithm
let has_priority = index_buffer[x as usize] == -256
|| (obj_priority_mode && obj.x < index_buffer[x as usize]);
let pixel = tile_row[if obj.xflip {
TILE_WIDTH_I - tile_x
} else {
tile_x
}];
if is_visible && has_priority && pixel != 0 {
// marks the current pixel in iteration as "owned"
// by the object with the defined X base position,
// to be used in priority calculus
index_buffer[x as usize] = obj.x;
// updates the pixel in the color buffer, which stores
// the raw pixel color information (unmapped) and then
// updates the shade buffer with the shade index
self.color_buffer[color_offset as usize] = pixel;
self.shade_buffer[color_offset as usize] = (palette_v >> (pixel * 2)) & 3;
// re-maps the pixel according to the object palette
// and then sets the color pixel in the frame buffer
let color = &palette[pixel as usize];
self.frame_buffer[frame_offset as usize] = color[0];
self.frame_buffer[frame_offset as usize + 1] = color[1];
self.frame_buffer[frame_offset as usize + 2] = color[2];
}
}
}
// increments the counter so that we're able to keep
// track on the number of object drawn
draw_count += 1;
}
}
/// Runs an update operation on the LCD STAT interrupt using
/// rising-edge detection on the internal STAT line.
///
/// The LCD STAT interrupt is only triggered on the 0 to 1 transition
/// of the combined STAT conditions, matching the real hardware
/// behaviour where the IF bit is set on the rising edge and
/// remains set until the CPU acknowledges it.
fn update_stat(&mut self) {
let level = self.stat_level();
if level && !self.int_stat_prev {
self.int_stat = true;
}
self.int_stat_prev = level;
}
/// Obtains the current level of the LCD STAT interrupt by
/// checking the current PPU state in various sections.
fn stat_level(&self) -> bool {
self.stat_lyc && self.lyc == self.ly
|| self.stat_oam && self.mode == PpuMode::OamRead
|| self.stat_vblank && self.mode == PpuMode::VBlank
|| self.stat_hblank && self.mode == PpuMode::HBlank
}
/// Computes the values for all of the palettes, this method
/// is useful to "flush" color computation whenever the base
/// palette colors are changed.
///
/// Notice that this is only applicable to the DMG running mode -
/// either in the original DMG or in CGB with DMG compatibility.
fn compute_palettes(&mut self) {
if self.dmg_compat {
Self::compute_palette(
&mut self.palette_bg,
&self.palettes_color_bg[0],
self.palettes[0],
);
Self::compute_palette(
&mut self.palette_obj_0,
&self.palettes_color_obj[0],
self.palettes[1],
);
Self::compute_palette(
&mut self.palette_obj_1,
&self.palettes_color_obj[1],
self.palettes[2],
);
} else {
// re-computes the complete set of palettes according to
// the currently set palette colors (that may have changed)
Self::compute_palette(&mut self.palette_bg, &self.palette_colors, self.palettes[0]);
Self::compute_palette(
&mut self.palette_obj_0,
&self.palette_colors,
self.palettes[1],
);
Self::compute_palette(
&mut self.palette_obj_1,
&self.palette_colors,
self.palettes[2],
);
}
// clears the frame buffer to allow the new background
// color to be used
self.clear_frame_buffer();
}
/// Static method used for the base logic of computation of RGB
/// based palettes from the internal Game Boy color indexes.
///
/// This method should be called whenever the palette indexes
/// are changed.
fn compute_palette(palette: &mut Palette, palette_colors: &Palette, value: u8) {
for (index, palette_item) in palette.iter_mut().enumerate() {
let color_index: usize = (value as usize >> (index * 2)) & 3;
match color_index {
0..=3 => *palette_item = palette_colors[color_index],
color_index => panic_gb!("Invalid palette color index {:04x}", color_index),
}
}
}
/// Static method that computes an RGB888 color palette ready to
/// be used for frame buffer operations from 4 (colors) x 2 bytes (RGB555)
/// that represent an RGB555 set of colors. This method should be
/// used for CGB mode where colors are represented using RGB555.
fn compute_palette_color(
palette: &mut Palette,
palette_color: &[u8; 64],
palette_index: u8,
color_index: u8,
) {
let palette_offset = (palette_index * 4 * 2) as usize;
let color_offset = (color_index * 2) as usize;
palette[color_index as usize] = rgb555_to_rgb888(
palette_color[palette_offset + color_offset],
palette_color[palette_offset + color_offset + 1],
);
}
/// Re-computes the complete set of CGB only color palettes using the
/// raw `palettes_color` information and computing the `Palette` structure
/// for both background and objects palettes.
fn compute_palettes_color(
palettes: &mut [&mut [Palette; 8]; 2],
palettes_color: &[[u8; 64]; 2],
) {
for index in 0..2 {
let palette = &mut palettes[index];
let palette_color = &palettes_color[index];
for palette_index in 0..palette.len() {
Self::compute_color_palette(
&mut palette[palette_index],
&palette_color[palette_index * 8..(palette_index + 1) * 8]
.try_into()
.unwrap(),
);
}
}
}
/// Computes an individual structured CGB color palette from 8 raw bytes
/// coming from the raw `palette_color` information, this 8 bytes should
/// represent the 4 colors of the palette in the RGB555 format.
fn compute_color_palette(palette: &mut Palette, palette_color: &[u8; 8]) {
for color_index in 0..palette.len() {
palette[color_index] = rgb555_to_rgb888(
palette_color[color_index * 2],
palette_color[color_index * 2 + 1],
);
}
}
}
impl BusComponent for Ppu {
fn read(&self, addr: u16) -> u8 {
self.read(addr)
}
fn write(&mut self, addr: u16, value: u8) {
self.write(addr, value);
}
}
impl StateComponent for Ppu {
fn state(&self, format: Option<StateFormat>) -> Result<Vec<u8>, Error> {
let format = format.unwrap_or(StateFormat::Minimal);
let mut cursor = Cursor::new(vec![]);
if format == StateFormat::Full {
write_bytes(&mut cursor, &self.color_buffer[..])?;
write_bytes(&mut cursor, &self.shade_buffer[..])?;
write_bytes(&mut cursor, &self.frame_buffer[..])?;
write_bytes(
&mut cursor,
&self
.priority_buffer
.iter()
.map(|&b| if b { 1 } else { 0 })
.collect::<Vec<u8>>(),
)?;
write_bytes(&mut cursor, &self.vram)?;
write_bytes(&mut cursor, &self.hram)?;
write_bytes(&mut cursor, &self.oam)?;
}
write_u8(&mut cursor, self.vram_bank)?;
write_u16(&mut cursor, self.vram_offset)?;
if format == StateFormat::Full {
for tile in &self.tiles {
let tile = &Into::<Vec<u8>>::into(*tile)[..];
write_bytes(&mut cursor, tile)?;
}
for obj_data in &self.obj_data {
let obj_data = &Into::<Vec<u8>>::into(*obj_data)[..];
write_bytes(&mut cursor, obj_data)?;
}
write_bytes(&mut cursor, &self.palettes)?;
for palette_color in &self.palettes_color {
write_bytes(&mut cursor, palette_color)?;
}
}
write_u8(&mut cursor, self.obj_priority as u8)?;
write_u8(&mut cursor, self.scy)?;
write_u8(&mut cursor, self.scx)?;
write_u8(&mut cursor, self.wy)?;
write_u8(&mut cursor, self.wx)?;
write_u8(&mut cursor, self.ly)?;
write_u8(&mut cursor, self.lyc)?;
write_u8(&mut cursor, self.mode as u8)?;
write_u16(&mut cursor, self.mode_clock)?;
write_u8(&mut cursor, self.switch_bg as u8)?;
write_u8(&mut cursor, self.switch_obj as u8)?;
write_u8(&mut cursor, self.obj_size as u8)?;
write_u8(&mut cursor, self.bg_map as u8)?;
write_u8(&mut cursor, self.bg_tile as u8)?;
write_u8(&mut cursor, self.switch_window as u8)?;
write_u8(&mut cursor, self.window_map as u8)?;
write_u8(&mut cursor, self.switch_lcd as u8)?;
write_u8(&mut cursor, self.window_counter)?;
write_u8(&mut cursor, self.auto_increment_bg as u8)?;
write_u8(&mut cursor, self.palette_address_bg)?;
write_u8(&mut cursor, self.auto_increment_obj as u8)?;
write_u8(&mut cursor, self.palette_address_obj)?;
write_u8(&mut cursor, self.first_frame as u8)?;
write_u16(&mut cursor, self.frame_index)?;
write_u16(&mut cursor, self.frame_buffer_index)?;
write_u8(&mut cursor, self.stat_hblank as u8)?;
write_u8(&mut cursor, self.stat_vblank as u8)?;
write_u8(&mut cursor, self.stat_oam as u8)?;
write_u8(&mut cursor, self.stat_lyc as u8)?;
write_u8(&mut cursor, self.int_vblank as u8)?;
write_u8(&mut cursor, self.int_stat as u8)?;
write_u8(&mut cursor, self.int_stat_prev as u8)?;
write_u8(&mut cursor, self.dmg_compat as u8)?;
write_u8(&mut cursor, self.gb_mode as u8)?;
Ok(cursor.into_inner())
}
fn set_state(&mut self, data: &[u8], format: Option<StateFormat>) -> Result<(), Error> {
let format: StateFormat = format.unwrap_or(StateFormat::Minimal);
let mut cursor: Cursor<&[u8]> = Cursor::new(data);
if format == StateFormat::Full {
let mut priority_buffer = [0u8; COLOR_BUFFER_SIZE];
read_into(&mut cursor, &mut self.color_buffer[..])?;
read_into(&mut cursor, &mut self.shade_buffer[..])?;
read_into(&mut cursor, &mut self.frame_buffer[..])?;
read_into(&mut cursor, &mut priority_buffer)?;
self.priority_buffer.copy_from_slice(
&priority_buffer
.iter()
.map(|&b| b != 0)
.collect::<Vec<bool>>(),
);
read_into(&mut cursor, &mut self.vram[..])?;
read_into(&mut cursor, &mut self.hram[..])?;
read_into(&mut cursor, &mut self.oam[..])?;
}
self.vram_bank = read_u8(&mut cursor)?;
self.vram_offset = read_u16(&mut cursor)?;
if format == StateFormat::Full {
for index in 0..TILE_COUNT {
let mut tile = [0u8; 64];
read_into(&mut cursor, &mut tile)?;
self.tiles[index] = (&tile[..]).into();
}
for index in 0..OBJ_COUNT {
let mut obj_data = [0u8; 12];
read_into(&mut cursor, &mut obj_data)?;
self.obj_data[index] = (&obj_data[..]).into();
}
read_into(&mut cursor, &mut self.palettes)?;
for index in 0..2 {
let mut palette_color = [0u8; 64];
read_into(&mut cursor, &mut palette_color)?;
self.palettes_color[index] = palette_color;
}
}
self.obj_priority = read_u8(&mut cursor)? != 0;
self.scy = read_u8(&mut cursor)?;
self.scx = read_u8(&mut cursor)?;
self.wy = read_u8(&mut cursor)?;
self.wx = read_u8(&mut cursor)?;
self.ly = read_u8(&mut cursor)?;
self.lyc = read_u8(&mut cursor)?;
self.mode = read_u8(&mut cursor)?.into();
self.mode_clock = read_u16(&mut cursor)?;
self.switch_bg = read_u8(&mut cursor)? != 0;
self.switch_obj = read_u8(&mut cursor)? != 0;
self.obj_size = read_u8(&mut cursor)? != 0;
self.bg_map = read_u8(&mut cursor)? != 0;
self.bg_tile = read_u8(&mut cursor)? != 0;
self.switch_window = read_u8(&mut cursor)? != 0;
self.window_map = read_u8(&mut cursor)? != 0;
self.switch_lcd = read_u8(&mut cursor)? != 0;
self.window_counter = read_u8(&mut cursor)?;
self.auto_increment_bg = read_u8(&mut cursor)? != 0;
self.palette_address_bg = read_u8(&mut cursor)?;
self.auto_increment_obj = read_u8(&mut cursor)? != 0;
self.palette_address_obj = read_u8(&mut cursor)?;
self.first_frame = read_u8(&mut cursor)? != 0;
self.frame_index = read_u16(&mut cursor)?;
self.frame_buffer_index = read_u16(&mut cursor)?;
self.stat_hblank = read_u8(&mut cursor)? != 0;
self.stat_vblank = read_u8(&mut cursor)? != 0;
self.stat_oam = read_u8(&mut cursor)? != 0;
self.stat_lyc = read_u8(&mut cursor)? != 0;
self.int_vblank = read_u8(&mut cursor)? != 0;
self.int_stat = read_u8(&mut cursor)? != 0;
self.int_stat_prev = read_u8(&mut cursor)? != 0;
self.dmg_compat = read_u8(&mut cursor)? != 0;
self.gb_mode = read_u8(&mut cursor)?.into();
Ok(())
}
}
impl Default for Ppu {
fn default() -> Self {
Self::new(
GameBoyMode::Dmg,
Arc::new(Mutex::new(GameBoyConfig::default())),
)
}
}
#[cfg(test)]
mod tests {
use super::{
ObjectData, Ppu, PpuMode, Tile, COLOR_BUFFER_SIZE, FRAME_BUFFER_SIZE, HRAM_SIZE, OAM_SIZE,
OBJ_COUNT, SHADE_BUFFER_SIZE, TILE_COUNT, VRAM_SIZE,
};
use crate::{
gb::GameBoyMode,
state::{StateComponent, StateFormat},
};
#[test]
fn test_update_tile_simple() {
let mut ppu = Ppu::default();
ppu.vram[0x0000] = 0xff;
ppu.vram[0x0001] = 0xff;
let result = ppu.tiles()[0].get(0, 0);
assert_eq!(result, 0);
ppu.update_tile(0x8000, 0x00);
let result = ppu.tiles()[0].get(0, 0);
assert_eq!(result, 3);
}
#[test]
fn test_update_tile_upper() {
let mut ppu = Ppu::default();
ppu.vram[0x1000] = 0xff;
ppu.vram[0x1001] = 0xff;
let result = ppu.tiles()[256].get(0, 0);
assert_eq!(result, 0);
ppu.update_tile(0x9000, 0x00);
let result = ppu.tiles()[256].get(0, 0);
assert_eq!(result, 3);
}
#[test]
fn test_state_and_set_state() {
let ppu = Ppu {
color_buffer: Box::new([0x01; COLOR_BUFFER_SIZE]),
shade_buffer: Box::new([0x02; SHADE_BUFFER_SIZE]),
frame_buffer: Box::new([0x03; FRAME_BUFFER_SIZE]),
priority_buffer: Box::new([true; COLOR_BUFFER_SIZE]),
vram: [0x04; VRAM_SIZE],
hram: [0x05; HRAM_SIZE],
oam: [0x06; OAM_SIZE],
vram_bank: 0x07,
vram_offset: 0x08,
tiles: [Tile::new(); TILE_COUNT],
obj_data: [ObjectData::new(); OBJ_COUNT],
palettes: [0x09; 3],
palettes_color: [[0x0a; 64]; 2],
obj_priority: true,
scy: 0x0b,
scx: 0x0c,
wy: 0x0d,
wx: 0x0e,
ly: 0x0f,
lyc: 0x10,
mode: PpuMode::OamRead,
mode_clock: 0x12,
switch_bg: true,
switch_obj: true,
obj_size: true,
bg_map: true,
bg_tile: true,
switch_window: true,
window_map: true,
switch_lcd: true,
window_counter: 0x13,
auto_increment_bg: true,
palette_address_bg: 0x14,
auto_increment_obj: true,
palette_address_obj: 0x15,
first_frame: true,
frame_index: 0x16,
frame_buffer_index: 0x17,
stat_hblank: true,
stat_vblank: true,
stat_oam: true,
stat_lyc: true,
int_vblank: true,
int_stat: true,
int_stat_prev: true,
dmg_compat: true,
gb_mode: GameBoyMode::Dmg,
..Default::default()
};
let state = ppu.state(Some(StateFormat::Full)).unwrap();
assert_eq!(state.len(), 204715);
let mut new_ppu = Ppu::default();
new_ppu.set_state(&state, Some(StateFormat::Full)).unwrap();
assert_eq!(new_ppu.color_buffer, Box::new([0x01; COLOR_BUFFER_SIZE]));
assert_eq!(new_ppu.shade_buffer, Box::new([0x02; SHADE_BUFFER_SIZE]));
assert_eq!(new_ppu.frame_buffer, Box::new([0x03; FRAME_BUFFER_SIZE]));
assert_eq!(new_ppu.priority_buffer, Box::new([true; COLOR_BUFFER_SIZE]));
assert_eq!(new_ppu.vram, [0x04; VRAM_SIZE]);
assert_eq!(new_ppu.hram, [0x05; HRAM_SIZE]);
assert_eq!(new_ppu.oam, [0x06; OAM_SIZE]);
assert_eq!(new_ppu.vram_bank, 0x07);
assert_eq!(new_ppu.vram_offset, 0x08);
assert_eq!(new_ppu.tiles, [Tile::new(); TILE_COUNT]);
assert_eq!(new_ppu.obj_data, [ObjectData::new(); OBJ_COUNT]);
assert_eq!(new_ppu.palettes, [0x09; 3]);
assert_eq!(new_ppu.palettes_color, [[0x0a; 64]; 2]);
assert!(new_ppu.obj_priority);
assert_eq!(new_ppu.scy, 0x0b);
assert_eq!(new_ppu.scx, 0x0c);
assert_eq!(new_ppu.wy, 0x0d);
assert_eq!(new_ppu.wx, 0x0e);
assert_eq!(new_ppu.ly, 0x0f);
assert_eq!(new_ppu.lyc, 0x10);
assert_eq!(new_ppu.mode, PpuMode::OamRead);
assert_eq!(new_ppu.mode_clock, 0x12);
assert!(new_ppu.switch_bg);
assert!(new_ppu.switch_obj);
assert!(new_ppu.obj_size);
assert!(new_ppu.bg_map);
assert!(new_ppu.bg_tile);
assert!(new_ppu.switch_window);
assert!(new_ppu.window_map);
assert!(new_ppu.switch_lcd);
assert_eq!(new_ppu.window_counter, 0x13);
assert!(new_ppu.auto_increment_bg);
assert_eq!(new_ppu.palette_address_bg, 0x14);
assert!(new_ppu.auto_increment_obj);
assert_eq!(new_ppu.palette_address_obj, 0x15);
assert!(new_ppu.first_frame);
assert_eq!(new_ppu.frame_index, 0x16);
assert_eq!(new_ppu.frame_buffer_index, 0x17);
assert!(new_ppu.stat_hblank);
assert!(new_ppu.stat_vblank);
assert!(new_ppu.stat_oam);
assert!(new_ppu.stat_lyc);
assert!(new_ppu.int_vblank);
assert!(new_ppu.int_stat);
assert!(new_ppu.int_stat_prev);
assert!(new_ppu.dmg_compat);
assert_eq!(new_ppu.gb_mode, GameBoyMode::Dmg);
}
#[test]
fn test_state_and_set_state_minimal() {
let ppu = Ppu {
vram_bank: 0x07,
vram_offset: 0x08,
obj_priority: true,
scy: 0x0b,
scx: 0x0c,
wy: 0x0d,
wx: 0x0e,
ly: 0x0f,
lyc: 0x10,
mode: PpuMode::OamRead,
mode_clock: 0x12,
switch_bg: true,
switch_obj: true,
obj_size: true,
bg_map: true,
bg_tile: true,
switch_window: true,
window_map: true,
switch_lcd: true,
window_counter: 0x13,
auto_increment_bg: true,
palette_address_bg: 0x14,
auto_increment_obj: true,
palette_address_obj: 0x15,
first_frame: true,
frame_index: 0x16,
frame_buffer_index: 0x17,
stat_hblank: true,
stat_vblank: true,
stat_oam: true,
stat_lyc: true,
int_vblank: true,
int_stat: true,
int_stat_prev: true,
dmg_compat: true,
gb_mode: GameBoyMode::Dmg,
..Default::default()
};
let state = ppu.state(Some(StateFormat::Minimal)).unwrap();
assert_eq!(state.len(), 40);
let mut new_ppu = Ppu::default();
new_ppu
.set_state(&state, Some(StateFormat::Minimal))
.unwrap();
assert_eq!(new_ppu.vram_bank, 0x07);
assert_eq!(new_ppu.vram_offset, 0x08);
assert!(new_ppu.obj_priority);
assert_eq!(new_ppu.scy, 0x0b);
assert_eq!(new_ppu.scx, 0x0c);
assert_eq!(new_ppu.wy, 0x0d);
assert_eq!(new_ppu.wx, 0x0e);
assert_eq!(new_ppu.ly, 0x0f);
assert_eq!(new_ppu.lyc, 0x10);
assert_eq!(new_ppu.mode, PpuMode::OamRead);
assert_eq!(new_ppu.mode_clock, 0x12);
assert!(new_ppu.switch_bg);
assert!(new_ppu.switch_obj);
assert!(new_ppu.obj_size);
assert!(new_ppu.bg_map);
assert!(new_ppu.bg_tile);
assert!(new_ppu.switch_window);
assert!(new_ppu.window_map);
assert!(new_ppu.switch_lcd);
assert_eq!(new_ppu.window_counter, 0x13);
assert!(new_ppu.auto_increment_bg);
assert_eq!(new_ppu.palette_address_bg, 0x14);
assert!(new_ppu.auto_increment_obj);
assert_eq!(new_ppu.palette_address_obj, 0x15);
assert!(new_ppu.first_frame);
assert_eq!(new_ppu.frame_index, 0x16);
assert_eq!(new_ppu.frame_buffer_index, 0x17);
assert!(new_ppu.stat_hblank);
assert!(new_ppu.stat_vblank);
assert!(new_ppu.stat_oam);
assert!(new_ppu.stat_lyc);
assert!(new_ppu.int_vblank);
assert!(new_ppu.int_stat);
assert!(new_ppu.int_stat_prev);
assert!(new_ppu.dmg_compat);
assert_eq!(new_ppu.gb_mode, GameBoyMode::Dmg);
}
}