-
-
Notifications
You must be signed in to change notification settings - Fork 645
/
nesemu1.cc
1866 lines (1734 loc) · 58.3 KB
/
nesemu1.cc
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
/* NESEMU1 :: EMULATOR FOR THE NINTENDO ENTERTAINMENT SYSTEM (R) ARCHITECTURE */
/* WRITTEN BY AND COPYRIGHT 2011 JOEL YLILUOMA ── SEE: http://iki.fi/bisqwit/ */
/* PORTED TO TELETYPEWRITERS IN YEAR 2020 BY JUSTINE ALEXANDRA ROBERTS TUNNEY */
/* TRADEMARKS ARE OWNED BY THEIR RESPECTIVE OWNERS LAWYERCATS LUV TAUTOLOGIES */
/* https://bisqwit.iki.fi/jutut/kuvat/programming_examples/nesemu1/nesemu1.cc */
#include "dsp/core/core.h"
#include "dsp/core/half.h"
#include "dsp/core/illumination.h"
#include "dsp/scale/scale.h"
#include "dsp/tty/itoa8.h"
#include "dsp/tty/quant.h"
#include "dsp/tty/tty.h"
#include "libc/alg/arraylist2.internal.h"
#include "libc/assert.h"
#include "libc/bits/bits.h"
#include "libc/bits/safemacros.h"
#include "libc/calls/calls.h"
#include "libc/calls/struct/itimerval.h"
#include "libc/calls/struct/winsize.h"
#include "libc/errno.h"
#include "libc/fmt/conv.h"
#include "libc/fmt/fmt.h"
#include "libc/inttypes.h"
#include "libc/log/check.h"
#include "libc/log/log.h"
#include "libc/macros.h"
#include "libc/math.h"
#include "libc/mem/mem.h"
#include "libc/ohmyplus/vector.h"
#include "libc/runtime/gc.h"
#include "libc/runtime/runtime.h"
#include "libc/sock/sock.h"
#include "libc/stdio/stdio.h"
#include "libc/str/str.h"
#include "libc/sysv/consts/ex.h"
#include "libc/sysv/consts/exit.h"
#include "libc/sysv/consts/fileno.h"
#include "libc/sysv/consts/itimer.h"
#include "libc/sysv/consts/o.h"
#include "libc/sysv/consts/poll.h"
#include "libc/sysv/consts/sig.h"
#include "libc/time/time.h"
#include "libc/x/x.h"
#include "libc/zip.h"
#include "libc/zipos/zipos.internal.h"
#include "third_party/getopt/getopt.h"
#include "tool/viz/lib/knobs.h"
STATIC_YOINK("zip_uri_support");
#define USAGE \
" [ROM] [FMV]\n\
\n\
SYNOPSIS\n\
\n\
Emulates NES Video Games in Terminal\n\
\n\
FLAGS\n\
\n\
-A ansi color mode\n\
-t normal color mode\n\
-x xterm256 color mode\n\
-4 unicode character set\n\
-3 ibm cp437 character set\n\
-1 ntsc crt artifact emulation\n\
-h\n\
-? shows this information\n\
\n\
KEYBOARD\n\
\n\
We support Emacs / Mac OS X control key bindings. We also support\n\
Vim. We support arrow keys. We also support WASD QWERTY & Dvorak.\n\
The 'A' button is mapped to SPACE. The 'B' button is mapped to b.\n\
Lastly TAB is SELECT and ENTER is START.\n\
\n\
Teletypewriters are naturally limited in terms of keyboard input.\n\
They don't exactly have n-key rollover. More like 1-key rollover.\n\
\n\
Try tapping rather than holding keys. You can tune the activation\n\
duration by pressing '8' and '9'. You can also adjust the keyboard\n\
repeat delay in your operating system settings to make it shorter.\n\
\n\
Ideally we should send patches to all the terms that introduces a\n\
new ANSI escape sequences for key down / key up events. It'd also\n\
be great to have inband audio with terminals too.\n\
\n\
GRAPHICS\n\
\n\
The '1' key toggles CRT monitor artifact emulation, which can make\n\
some games like Zelda II look better. The '3' and '4' keys toggle\n\
the selection of UNICODE block characters.\n\
\n\
ZIP\n\
\n\
This executable is also a ZIP archive. If you change the extension\n\
then you can modify its inner structure, to place roms inside it.\n\
\n\
AUTHORS\n\
\n\
Joel Yliluoma <http://iki.fi/bisqwit/>\n\
Justine Tunney <jtunney@gmail.com/>\n\
\n\
\n"
#define DYN 240
#define DXN 256
#define FPS 60.0988
#define HZ 1789773
#define GAMMA 2.2
#define CTRL(C) ((C) ^ 0100)
#define ALT(C) ((033 << 010) | (C))
typedef int8_t s8;
typedef uint8_t u8;
typedef uint16_t u16;
typedef uint32_t u32;
static const struct itimerval kNesFps = {
{0, 1. / FPS * 1e6},
{0, 1. / FPS * 1e6},
};
struct Frame {
char *p, *w, *mem;
};
struct Action {
int code;
int wait;
};
struct Audio {
size_t i;
int16_t p[FRAMESIZE];
};
struct Status {
int wait;
char text[80];
};
struct ZipGames {
size_t i, n;
char** p;
};
static int frame_;
static int drain_;
static int playfd_;
static int playpid_;
static bool exited_;
static bool timeout_;
static bool resized_;
static size_t vtsize_;
static bool artifacts_;
static long tyn_, txn_;
static struct Frame vf_[2];
static struct Audio audio_;
static const char* inputfn_;
static struct Status status_;
static struct TtyRgb* ttyrgb_;
static unsigned char *R, *G, *B;
static struct ZipGames zipgames_;
static struct Action arrow_, button_;
static struct SamplingSolution* asx_;
static struct SamplingSolution* ssy_;
static struct SamplingSolution* ssx_;
static unsigned char pixels_[3][DYN][DXN];
static unsigned char palette_[3][64][512][3];
static int joy_current_[2], joy_next_[2], joypos_[2];
static int keyframes_ = 10;
static enum TtyBlocksSelection blocks_ = kTtyBlocksUnicode;
static enum TtyQuantizationAlgorithm quant_ = kTtyQuantTrue;
static int Clamp(int v) {
return MAX(0, MIN(255, v));
}
static double FixGamma(double x) {
return tv2pcgamma(x, GAMMA);
}
void InitPalette(void) {
// The input value is a NES color index (with de-emphasis bits).
// See http://wiki.nesdev.com/w/index.php/NTSC_video for magic numbers
// We need RGB values. To produce a RGB value, we emulate the NTSC circuitry.
double A[3] = {-1.109, -.275, .947};
double B[3] = {1.709, -.636, .624};
double rgbc[3], lightbulb[3][3], rgbd65[3], sc[2];
int o, u, r, c, b, p, y, i, l, q, e, p0, p1, pixel;
signed char volt[] = "\372\273\32\305\35\311I\330D\357\175\13D!}N";
GetChromaticAdaptationMatrix(lightbulb, kIlluminantC, kIlluminantD65);
for (o = 0; o < 3; ++o) {
for (p0 = 0; p0 < 512; ++p0) {
for (p1 = 0; p1 < 64; ++p1) {
for (u = 0; u < 3; ++u) {
// Calculate the luma and chroma by emulating the relevant circuits:
y = i = q = 0;
// 12 samples of NTSC signal constitute a color.
for (p = 0; p < 12; ++p) {
// Sample either the previous or the current pixel.
r = (p + o * 4) % 12;
// Decode the color index.
if (artifacts_) {
pixel = r < 8 - u * 2 ? p0 : p1;
} else {
pixel = p0;
}
c = pixel % 16;
l = c < 0xE ? pixel / 4 & 12 : 4;
e = p0 / 64;
// NES NTSC modulator
// square wave between up to four voltage levels
b = 40 + volt[(c > 12 * ((c + 8 + p) % 12 < 6)) +
2 * !(0451326 >> p / 2 * 3 & e) + l];
// Ideal TV NTSC demodulator?
sincos(M_PI * p / 6, &sc[0], &sc[1]);
y += b;
i += b * sc[1] * 5909;
q += b * sc[0] * 5909;
}
// Converts YIQ to RGB
// Store color at subpixel precision
rgbc[u] = FixGamma(y / 1980. + i * A[u] / 9e6 + q * B[u] / 9e6);
}
matvmul3(rgbd65, lightbulb, rgbc);
for (u = 0; u < 3; ++u) {
palette_[o][p1][p0][u] = Clamp(rgbd65[u] * 255);
}
}
}
}
}
static void WriteStringNow(const char* s) {
ttywrite(STDOUT_FILENO, s, strlen(s));
}
void Exit(int rc) {
WriteStringNow("\r\n\e[0m\e[J");
if (rc && errno) {
fprintf(stderr, "%s%s\r\n", "error: ", strerror(errno));
}
exit(rc);
}
void Cleanup(void) {
ttyraw((enum TtyRawFlags)(-1u));
ttyshowcursor(STDOUT_FILENO);
if (playpid_) kill(playpid_, SIGTERM), sched_yield();
}
void OnTimer(void) {
timeout_ = true; // also sends EINTR to poll()
}
void OnResize(void) {
resized_ = true;
}
void OnPiped(void) {
exited_ = true;
}
void OnCtrlC(void) {
drain_ = exited_ = true;
}
void OnSigChld(void) {
exited_ = true, playpid_ = 0;
}
void InitFrame(struct Frame* f) {
f->p = f->w = f->mem = (char*)realloc(f->mem, vtsize_);
}
long ChopAxis(long dn, long sn) {
while (HALF(sn) > dn) {
sn = HALF(sn);
}
return sn;
}
void GetTermSize(void) {
struct winsize wsize_;
wsize_.ws_row = 25;
wsize_.ws_col = 80;
getttysize(STDIN_FILENO, &wsize_);
FreeSamplingSolution(ssy_);
FreeSamplingSolution(ssx_);
tyn_ = wsize_.ws_row * 2;
txn_ = wsize_.ws_col * 2;
ssy_ = ComputeSamplingSolution(tyn_, ChopAxis(tyn_, DYN), 0, 0, 2);
ssx_ = ComputeSamplingSolution(txn_, ChopAxis(txn_, DXN), 0, 0, 0);
R = (unsigned char*)realloc(R, tyn_ * txn_);
G = (unsigned char*)realloc(G, tyn_ * txn_);
B = (unsigned char*)realloc(B, tyn_ * txn_);
ttyrgb_ = (struct TtyRgb*)realloc(ttyrgb_, tyn_ * txn_ * 4);
vtsize_ = ((tyn_ * txn_ * strlen("\e[48;2;255;48;2;255m▄")) +
(tyn_ * strlen("\e[0m\r\n")) + 128);
frame_ = 0;
InitFrame(&vf_[0]);
InitFrame(&vf_[1]);
WriteStringNow("\e[0m\e[H\e[J");
}
void IoInit(void) {
GetTermSize();
xsigaction(SIGINT, (void*)OnCtrlC, 0, 0, NULL);
xsigaction(SIGPIPE, (void*)OnPiped, 0, 0, NULL);
xsigaction(SIGWINCH, (void*)OnResize, 0, 0, NULL);
xsigaction(SIGALRM, (void*)OnTimer, 0, 0, NULL);
xsigaction(SIGCHLD, (void*)OnSigChld, 0, 0, NULL);
setitimer(ITIMER_REAL, &kNesFps, NULL);
ttyhidecursor(STDOUT_FILENO);
ttyraw(kTtySigs);
ttyquantsetup(quant_, kTtyQuantRgb, blocks_);
atexit(Cleanup);
}
void SetStatus(const char* fmt, ...) {
va_list va;
va_start(va, fmt);
vsnprintf(status_.text, sizeof(status_.text), fmt, va);
va_end(va);
status_.wait = FPS / 2;
}
void ReadKeyboard(void) {
int ch;
char b[20];
ssize_t i, rc;
memset(b, -1, sizeof(b));
if ((rc = read(STDIN_FILENO, b, 16)) != -1) {
if (!rc) exited_ = true;
for (i = 0; i < rc; ++i) {
ch = b[i];
if (b[i] == '\e') {
++i;
if (b[i] == '[') {
++i;
switch (b[i]) {
case 'A':
ch = CTRL('P'); // up arrow
break;
case 'B':
ch = CTRL('N'); // down arrow
break;
case 'C':
ch = CTRL('F'); // right arrow
break;
case 'D':
ch = CTRL('B'); // left arrow
break;
default:
break;
}
}
}
switch (ch) {
case ' ':
button_.code = 0b00100000; // A
button_.wait = keyframes_;
break;
case 'b':
button_.code = 0b00010000; // B
button_.wait = keyframes_;
break;
case '\r': // enter
button_.code = 0b10000000; // START
button_.wait = keyframes_;
break;
case '\t': // tab
button_.code = 0b01000000; // SELECT
button_.wait = keyframes_;
break;
case 'k': // vim
case 'w': // wasd qwerty
case ',': // wasd dvorak
case CTRL('P'): // emacs
arrow_.code = 0b00000100; // UP
arrow_.wait = keyframes_;
break;
case 'j': // vim
case 's': // wasd qwerty
case 'o': // wasd dvorak
case CTRL('N'): // emacs
arrow_.code = 0b00001000; // DOWN
arrow_.wait = keyframes_;
break;
case 'h': // vim
case 'a': // wasd qwerty & dvorak
case CTRL('B'): // emacs
arrow_.code = 0b00000010; // LEFT
arrow_.wait = keyframes_;
break;
case 'l': // vim
case 'd': // wasd qwerty
case 'e': // wasd dvorak
case CTRL('F'): // emacs
arrow_.code = 0b00000001; // RIGHT
arrow_.wait = keyframes_;
break;
case 'A': // ansi 4-bit color mode
quant_ = kTtyQuantAnsi;
ttyquantsetup(quant_, kTtyQuantRgb, blocks_);
SetStatus("ansi color");
break;
case 'x': // xterm256 color mode
quant_ = kTtyQuantXterm256;
ttyquantsetup(quant_, kTtyQuantRgb, blocks_);
SetStatus("xterm256 color");
break;
case 't': // ansi 24bit color mode
quant_ = kTtyQuantTrue;
ttyquantsetup(quant_, kTtyQuantRgb, blocks_);
SetStatus("24-bit color");
break;
case '1':
artifacts_ = !artifacts_;
InitPalette();
SetStatus("artifacts %s", artifacts_ ? "on" : "off");
break;
case '3': // oldskool ibm unicode rasterization
blocks_ = kTtyBlocksCp437;
ttyquantsetup(quant_, kTtyQuantRgb, blocks_);
SetStatus("IBM CP437");
break;
case '4': // newskool unicode rasterization
blocks_ = kTtyBlocksUnicode;
ttyquantsetup(quant_, kTtyQuantRgb, blocks_);
SetStatus("UNICODE");
break;
case '8':
keyframes_ = MAX(1, keyframes_ - 1);
SetStatus("%d key frames", keyframes_);
break;
case '9':
keyframes_ = keyframes_ + 1;
SetStatus("%d key frames", keyframes_);
break;
default:
break;
}
}
}
}
bool HasVideo(struct Frame* f) {
return f->w < f->p;
}
bool HasPendingVideo(void) {
return HasVideo(&vf_[0]) || HasVideo(&vf_[1]);
}
bool HasPendingAudio(void) {
return playpid_ && audio_.i;
}
struct Frame* FlipFrameBuffer(void) {
frame_ = !frame_;
return &vf_[frame_];
}
void TransmitVideo(void) {
ssize_t rc;
struct Frame* f;
f = &vf_[frame_];
if (!HasVideo(f)) f = FlipFrameBuffer();
if ((rc = write(STDOUT_FILENO, f->w, f->p - f->w)) != -1) {
f->w += rc;
} else if (errno == EPIPE) {
Exit(0);
} else if (errno != EINTR) {
Exit(1);
}
}
void TransmitAudio(void) {
ssize_t rc;
if (!audio_.i) return;
if ((rc = write(playfd_, audio_.p, audio_.i * sizeof(short))) != -1) {
rc /= sizeof(short);
memmove(audio_.p, audio_.p + rc, (audio_.i - rc) * sizeof(short));
audio_.i -= rc;
} else if (errno == EPIPE) {
Exit(0);
} else if (errno != EINTR) {
Exit(1);
}
}
void ScaleVideoFrameToTeletypewriter(void) {
long y, x, yn, xn;
yn = DYN, xn = DXN;
while (HALF(yn) > tyn_ || HALF(xn) > txn_) {
if (HALF(xn) > txn_) {
Magikarp2xX(DYN, DXN, pixels_[0], yn, xn);
Magikarp2xX(DYN, DXN, pixels_[1], yn, xn);
Magikarp2xX(DYN, DXN, pixels_[2], yn, xn);
xn = HALF(xn);
}
if (HALF(yn) > tyn_) {
Magikarp2xY(DYN, DXN, pixels_[0], yn, xn);
Magikarp2xY(DYN, DXN, pixels_[1], yn, xn);
Magikarp2xY(DYN, DXN, pixels_[2], yn, xn);
yn = HALF(yn);
}
}
GyaradosUint8(tyn_, txn_, R, DYN, DXN, pixels_[0], tyn_, txn_, yn, xn, 0, 255,
ssy_, ssx_, true);
GyaradosUint8(tyn_, txn_, G, DYN, DXN, pixels_[1], tyn_, txn_, yn, xn, 0, 255,
ssy_, ssx_, true);
GyaradosUint8(tyn_, txn_, B, DYN, DXN, pixels_[2], tyn_, txn_, yn, xn, 0, 255,
ssy_, ssx_, true);
for (y = 0; y < tyn_; ++y) {
for (x = 0; x < txn_; ++x) {
ttyrgb_[y * txn_ + x] =
rgb2tty(R[y * txn_ + x], G[y * txn_ + x], B[y * txn_ + x]);
}
}
}
void KeyCountdown(struct Action* a) {
if (a->wait <= 1) {
a->code = 0;
} else {
a->wait--;
}
}
void PollAndSynchronize(void) {
struct pollfd fds[3];
do {
errno = 0;
fds[0].fd = STDIN_FILENO;
fds[0].events = POLLIN;
fds[1].fd = HasPendingVideo() ? STDOUT_FILENO : -1;
fds[1].events = POLLOUT;
fds[2].fd = HasPendingAudio() ? playfd_ : -1;
fds[2].events = POLLOUT;
if (poll(fds, ARRAYLEN(fds), 1. / FPS * 1e3) != -1) {
if (fds[0].revents & (POLLIN | POLLERR)) ReadKeyboard();
if (fds[1].revents & (POLLOUT | POLLERR)) TransmitVideo();
if (fds[2].revents & (POLLOUT | POLLERR)) TransmitAudio();
} else if (errno != EINTR) {
Exit(1);
}
if (exited_) {
if (drain_) {
while (HasPendingVideo()) {
TransmitVideo();
}
}
Exit(0);
}
if (resized_) {
resized_ = false;
GetTermSize();
break;
}
} while (!timeout_);
timeout_ = false;
KeyCountdown(&arrow_);
KeyCountdown(&button_);
joy_next_[0] = arrow_.code | button_.code;
joy_next_[1] = arrow_.code | button_.code;
}
void Raster(void) {
struct Frame* f;
struct TtyRgb bg = {0x12, 0x34, 0x56, 0};
struct TtyRgb fg = {0x12, 0x34, 0x56, 0};
ScaleVideoFrameToTeletypewriter();
f = &vf_[!frame_];
f->p = f->w = f->mem;
f->p = stpcpy(f->p, "\e[0m\e[H");
f->p = ttyraster(f->p, ttyrgb_, tyn_, txn_, bg, fg);
if (status_.wait) {
status_.wait--;
f->p = stpcpy(f->p, "\e[0m\e[H");
f->p = stpcpy(f->p, status_.text);
}
CHECK_LT(f->p - f->mem, vtsize_);
PollAndSynchronize();
}
void FlushScanline(unsigned py) {
if (py == DYN - 1) {
if (!timeout_) {
Raster();
}
timeout_ = false;
}
}
static void PutPixel(unsigned px, unsigned py, unsigned pixel, int offset) {
unsigned rgb;
static unsigned prev;
pixels_[0][py][px] = palette_[offset][prev % 64][pixel][2];
pixels_[1][py][px] = palette_[offset][prev % 64][pixel][1];
pixels_[2][py][px] = palette_[offset][prev % 64][pixel][0];
prev = pixel;
}
static void JoyStrobe(unsigned v) {
if (v) {
joy_current_[0] = joy_next_[0];
joypos_[0] = 0;
}
if (v) {
joy_current_[1] = joy_next_[1];
joypos_[1] = 0;
}
}
static u8 JoyRead(unsigned idx) {
// http://tasvideos.org/EmulatorResources/Famtasia/FMV.html
static const u8 masks[8] = {
0b00100000, // A
0b00010000, // B
0b01000000, // SELECT
0b10000000, // START
0b00000100, // UP
0b00001000, // DOWN
0b00000010, // LEFT
0b00000001, // RIGHT
};
return (joy_current_[idx] & masks[joypos_[idx]++ & 7]) ? 1 : 0;
}
template <unsigned bitno, unsigned nbits = 1, typename T = u8>
struct RegBit {
T data;
enum { mask = (1u << nbits) - 1u };
template <typename T2>
RegBit& operator=(T2 v) {
data = (data & ~(mask << bitno)) | ((nbits > 1 ? v & mask : !!v) << bitno);
return *this;
}
operator unsigned() const {
return (data >> bitno) & mask;
}
RegBit& operator++() {
return *this = *this + 1;
}
unsigned operator++(int) {
unsigned r = *this;
++*this;
return r;
}
};
namespace GamePak {
const unsigned VRomGranularity = 0x0400;
const unsigned VRomPages = 0x2000 / VRomGranularity;
const unsigned RomGranularity = 0x2000;
const unsigned RomPages = 0x10000 / RomGranularity;
std::vector<u8> ROM;
std::vector<u8> VRAM(0x2000);
unsigned mappernum;
unsigned char NRAM[0x1000];
unsigned char PRAM[0x2000];
unsigned char* banks[RomPages] = {};
unsigned char* Vbanks[VRomPages] = {};
unsigned char* Nta[4] = {NRAM + 0x0000, NRAM + 0x0400, NRAM + 0x0000,
NRAM + 0x0400};
template <unsigned npages, unsigned char* (&b)[npages], std::vector<u8>& r,
unsigned granu>
static void SetPages(unsigned size, unsigned baseaddr, unsigned index) {
for (unsigned v = r.size() + index * size, p = baseaddr / granu;
p < (baseaddr + size) / granu && p < npages; ++p, v += granu) {
b[p] = &r[v % r.size()];
}
}
auto& SetROM = SetPages<RomPages, banks, ROM, RomGranularity>;
auto& SetVROM = SetPages<VRomPages, Vbanks, VRAM, VRomGranularity>;
u8 Access(unsigned addr, u8 value, bool write) {
if (write && addr >= 0x8000 && mappernum == 7) { // e.g. Rare games
SetROM(0x8000, 0x8000, (value & 7));
Nta[0] = Nta[1] = Nta[2] = Nta[3] = &NRAM[0x400 * ((value >> 4) & 1)];
}
if (write && addr >= 0x8000 && mappernum == 2) { // e.g. Rockman, Castlevania
SetROM(0x4000, 0x8000, value);
}
if (write && addr >= 0x8000 && mappernum == 3) { // e.g. Kage, Solomon's Key
value &= Access(addr, 0, false); // Simulate bus conflict
SetVROM(0x2000, 0x0000, (value & 3));
}
if (write && addr >= 0x8000 &&
mappernum == 1) { // e.g. Rockman 2, Simon's Quest
static u8 regs[4] = {0x0C, 0, 0, 0}, counter = 0, cache = 0;
if (value & 0x80) {
regs[0] = 0x0C;
goto configure;
}
cache |= (value & 1) << counter;
if (++counter == 5) {
regs[(addr >> 13) & 3] = value = cache;
configure:
cache = counter = 0;
static const u8 sel[4][4] = {
{0, 0, 0, 0}, {1, 1, 1, 1}, {0, 1, 0, 1}, {0, 0, 1, 1}};
for (unsigned m = 0; m < 4; ++m)
Nta[m] = &NRAM[0x400 * sel[regs[0] & 3][m]];
SetVROM(0x1000, 0x0000,
((regs[0] & 16) ? regs[1] : ((regs[1] & ~1) + 0)));
SetVROM(0x1000, 0x1000,
((regs[0] & 16) ? regs[2] : ((regs[1] & ~1) + 1)));
switch ((regs[0] >> 2) & 3) {
case 0:
case 1:
SetROM(0x8000, 0x8000, (regs[3] & 0xE) / 2);
break;
case 2:
SetROM(0x4000, 0x8000, 0);
SetROM(0x4000, 0xC000, (regs[3] & 0xF));
break;
case 3:
SetROM(0x4000, 0x8000, (regs[3] & 0xF));
SetROM(0x4000, 0xC000, ~0);
break;
}
}
}
if ((addr >> 13) == 3) return PRAM[addr & 0x1FFF];
return banks[(addr / RomGranularity) % RomPages][addr % RomGranularity];
}
void Init() {
unsigned v;
SetVROM(0x2000, 0x0000, 0);
for (v = 0; v < 4; ++v) {
SetROM(0x4000, v * 0x4000, v == 3 ? -1 : 0);
}
}
} // namespace GamePak
/* CPU: Ricoh RP2A03 (based on MOS6502, almost the same as in Commodore 64) */
namespace CPU {
u8 RAM[0x800];
bool reset = true;
bool nmi = false;
bool nmi_edge_detected = false;
bool intr = false;
template <bool write>
u8 MemAccess(u16 addr, u8 v = 0);
u8 RB(u16 addr) {
return MemAccess<0>(addr);
}
u8 WB(u16 addr, u8 v) {
return MemAccess<1>(addr, v);
}
void Tick();
} // namespace CPU
namespace PPU { /* Picture Processing Unit */
union regtype { // PPU register file
u32 value;
/* clang-format off */
// Reg0 (write) // Reg1 (write) // Reg2 (read)
RegBit<0,8,u32> sysctrl; RegBit< 8,8,u32> dispctrl; RegBit<16,8,u32> status;
RegBit<0,2,u32> BaseNTA; RegBit< 8,1,u32> Grayscale; RegBit<21,1,u32> SPoverflow;
RegBit<2,1,u32> Inc; RegBit< 9,1,u32> ShowBG8; RegBit<22,1,u32> SP0hit;
RegBit<3,1,u32> SPaddr; RegBit<10,1,u32> ShowSP8; RegBit<23,1,u32> InVBlank;
RegBit<4,1,u32> BGaddr; RegBit<11,1,u32> ShowBG; // Reg3 (write)
RegBit<5,1,u32> SPsize; RegBit<12,1,u32> ShowSP; RegBit<24,8,u32> OAMaddr;
RegBit<6,1,u32> SlaveFlag; RegBit<11,2,u32> ShowBGSP; RegBit<24,2,u32> OAMdata;
RegBit<7,1,u32> NMIenabled; RegBit<13,3,u32> EmpRGB; RegBit<26,6,u32> OAMindex;
/* clang-format on */
} reg;
// Raw memory data as read&written by the game
u8 palette[32];
u8 OAM[256];
// Decoded sprite information, used & changed during each scanline
struct {
u8 sprindex, y, index, attr, x_;
u16 pattern;
} OAM2[8], OAM3[8];
union scrolltype {
RegBit<3, 16, u32> raw; // raw VRAM address (16-bit)
RegBit<0, 8, u32> xscroll; // low 8 bits of first write to 2005
RegBit<0, 3, u32> xfine; // low 3 bits of first write to 2005
RegBit<3, 5, u32> xcoarse; // high 5 bits of first write to 2005
RegBit<8, 5, u32> ycoarse; // high 5 bits of second write to 2005
RegBit<13, 2, u32> basenta; // nametable index (copied from 2000)
RegBit<13, 1, u32> basenta_h; // horizontal nametable index
RegBit<14, 1, u32> basenta_v; // vertical nametable index
RegBit<15, 3, u32> yfine; // low 3 bits of second write to 2005
RegBit<11, 8, u32> vaddrhi; // first write to 2006 w/ high 2 bits set to 0
RegBit<3, 8, u32> vaddrlo; // second write to 2006
} scroll, vaddr;
unsigned pat_addr, sprinpos, sproutpos, sprrenpos, sprtmp;
u16 tileattr, tilepat, ioaddr;
u32 bg_shift_pat, bg_shift_attr;
int x_ = 0;
int scanline = 241;
int scanline_end = 341;
int VBlankState = 0;
int cycle_counter = 0;
int read_buffer = 0;
int open_bus = 0;
int open_bus_decay_timer = 0;
bool even_odd_toggle = false;
bool offset_toggle = false;
/* Memory mapping: Convert PPU memory address into reference to relevant data */
u8& NesMmap(int i) {
i &= 0x3FFF;
if (i >= 0x3F00) {
if (i % 4 == 0) i &= 0x0F;
return palette[i & 0x1F];
}
if (i < 0x2000) {
return GamePak::Vbanks[(i / GamePak::VRomGranularity) % GamePak::VRomPages]
[i % GamePak::VRomGranularity];
}
return GamePak::Nta[(i >> 10) & 3][i & 0x3FF];
}
// External I/O: read or write
u8 PpuAccess(u16 index, u8 v, bool write) {
auto RefreshOpenBus = [&](u8 v) {
return open_bus_decay_timer = 77777, open_bus = v;
};
u8 res = open_bus;
if (write) RefreshOpenBus(v);
switch (index) { // Which port from $200x?
case 0:
if (write) {
reg.sysctrl = v;
scroll.basenta = reg.BaseNTA;
}
break;
case 1:
if (write) {
reg.dispctrl = v;
}
break;
case 2:
if (write) break;
res = reg.status | (open_bus & 0x1F);
reg.InVBlank = false; // Reading $2002 clears the vblank flag.
offset_toggle = false; // Also resets the toggle for address updates.
if (VBlankState != -5) {
VBlankState = 0; // This also may cancel the setting of InVBlank.
}
break;
case 3:
if (write) reg.OAMaddr = v;
break; // Index into Object Attribute Memory
case 4:
if (write) {
OAM[reg.OAMaddr++] = v; // Write or read the OAM (sprites).
} else {
res =
RefreshOpenBus(OAM[reg.OAMaddr] & (reg.OAMdata == 2 ? 0xE3 : 0xFF));
}
break;
case 5:
if (!write) break; // Set background scrolling offset
if (offset_toggle) {
scroll.yfine = v & 7;
scroll.ycoarse = v >> 3;
} else {
scroll.xscroll = v;
}
offset_toggle = !offset_toggle;
break;
case 6:
if (!write) break; // Set video memory position for reads/writes
if (offset_toggle) {
scroll.vaddrlo = v;
vaddr.raw = (unsigned)scroll.raw;
} else {
scroll.vaddrhi = v & 0x3F;
}
offset_toggle = !offset_toggle;
break;
case 7:
res = read_buffer;
u8& t = NesMmap(vaddr.raw); // Access the video memory.
if (write) {
res = t = v;
} else {
if ((vaddr.raw & 0x3F00) == 0x3F00) { // palette?
res = read_buffer = (open_bus & 0xC0) | (t & 0x3F);
}
read_buffer = t;
}
RefreshOpenBus(res);
vaddr.raw = vaddr.raw +
(reg.Inc ? 32 : 1); // The address is automatically updated.
break;
}
return res;
}
void RenderingTick() {
int y1, y2;
bool tile_decode_mode =
0x10FFFF & (1u << (x_ / 16)); // When x_ is 0..255, 320..335
// Each action happens in two steps: 1) select memory address; 2) receive data
// and react on it.
switch (x_ % 8) {
case 2: // Point to attribute table
ioaddr = 0x23C0 + 0x400 * vaddr.basenta + 8 * (vaddr.ycoarse / 4) +
(vaddr.xcoarse / 4);
if (tile_decode_mode) break; // Or nametable, with sprites.
case 0: // Point to nametable
ioaddr = 0x2000 + (vaddr.raw & 0xFFF);
// Reset sprite data
if (x_ == 0) {
sprinpos = sproutpos = 0;
if (reg.ShowSP) reg.OAMaddr = 0;
}
if (!reg.ShowBG) break;
// Reset scrolling (vertical once, horizontal each scanline)
if (x_ == 304 && scanline == -1) vaddr.raw = (unsigned)scroll.raw;
if (x_ == 256) {
vaddr.xcoarse = (unsigned)scroll.xcoarse;
vaddr.basenta_h = (unsigned)scroll.basenta_h;
sprrenpos = 0;
}
break;
case 1:
if (x_ == 337 && scanline == -1 && even_odd_toggle && reg.ShowBG) {
scanline_end = 340;
}
// Name table access
pat_addr = 0x1000 * reg.BGaddr + 16 * NesMmap(ioaddr) + vaddr.yfine;
if (!tile_decode_mode) break;
// Push the current tile into shift registers.
// The bitmap pattern is 16 bits, while the attribute is 2 bits, repeated
// 8 times.
bg_shift_pat = (bg_shift_pat >> 16) + 0x00010000 * tilepat;
bg_shift_attr = (bg_shift_attr >> 16) + 0x55550000 * tileattr;
break;
case 3:
// Attribute table access
if (tile_decode_mode) {
tileattr = (NesMmap(ioaddr) >>
((vaddr.xcoarse & 2) + 2 * (vaddr.ycoarse & 2))) &
3;
// Go to the next tile horizontally (and switch nametable if it wraps)
if (!++vaddr.xcoarse) {
vaddr.basenta_h = 1 - vaddr.basenta_h;
}
// At the edge of the screen, do the same but vertically
if (x_ == 251 && !++vaddr.yfine && ++vaddr.ycoarse == 30) {
vaddr.ycoarse = 0;
vaddr.basenta_v = 1 - vaddr.basenta_v;
}
} else if (sprrenpos < sproutpos) {
// Select sprite pattern instead of background pattern
auto& o = OAM3[sprrenpos]; // Sprite to render on next scanline
memcpy(&o, &OAM2[sprrenpos], sizeof(o));
unsigned y = (scanline)-o.y;
if (o.attr & 0x80) y ^= (reg.SPsize ? 15 : 7);
pat_addr = 0x1000 * (reg.SPsize ? (o.index & 0x01) : reg.SPaddr);
pat_addr += 0x10 * (reg.SPsize ? (o.index & 0xFE) : (o.index & 0xFF));
pat_addr += (y & 7) + (y & 8) * 2;
}
break;
// Pattern table bytes
case 5:
tilepat = NesMmap(pat_addr | 0);
break;
case 7: // Interleave the bits of the two pattern bytes
unsigned p = tilepat | (NesMmap(pat_addr | 8) << 8);
p = (p & 0xF00F) | ((p & 0x0F00) >> 4) | ((p & 0x00F0) << 4);
p = (p & 0xC3C3) | ((p & 0x3030) >> 2) | ((p & 0x0C0C) << 2);
p = (p & 0x9999) | ((p & 0x4444) >> 1) | ((p & 0x2222) << 1);
tilepat = p;
// When decoding sprites, save the sprite graphics and move to next sprite
if (!tile_decode_mode && sprrenpos < sproutpos) {
OAM3[sprrenpos++].pattern = tilepat;
}
break;
}
// Find which sprites are visible on next scanline (TODO: implement crazy
// 9-sprite malfunction)
switch (x_ >= 64 && x_ < 256 && x_ % 2 ? (reg.OAMaddr++ & 3) : 4) {
default: