-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgameboy.html
3101 lines (2759 loc) · 106 KB
/
gameboy.html
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
<!--
https://github.com/juchi/gameboy.js
The MIT License (MIT)
Copyright (c) 2015 Julien Chichignoud
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
-->
<script>
function loadboot(p) {
var boot = [
0x31, 0xFE, 0xFF, 0xAF, 0x21, 0xFF, 0x9F, 0x32, 0xCB, 0x7C, 0x20, 0xFB, 0x21, 0x26, 0xFF, 0x0E,
0x11, 0x3E, 0x80, 0x32, 0xE2, 0x0C, 0x3E, 0xF3, 0xE2, 0x32, 0x3E, 0x77, 0x77, 0x3E, 0xFC, 0xE0,
0x47, 0x11, 0x04, 0x01, 0x21, 0x10, 0x80, 0x1A, 0xCD, 0x95, 0x00, 0xCD, 0x96, 0x00, 0x13, 0x7B,
0xFE, 0x34, 0x20, 0xF3, 0x11, 0xD8, 0x00, 0x06, 0x08, 0x1A, 0x13, 0x22, 0x23, 0x05, 0x20, 0xF9,
0x3E, 0x19, 0xEA, 0x10, 0x99, 0x21, 0x2F, 0x99, 0x0E, 0x0C, 0x3D, 0x28, 0x08, 0x32, 0x0D, 0x20,
0xF9, 0x2E, 0x0F, 0x18, 0xF3, 0x67, 0x3E, 0x64, 0x57, 0xE0, 0x42, 0x3E, 0x91, 0xE0, 0x40, 0x04,
0x1E, 0x02, 0x0E, 0x0C, 0xF0, 0x44, 0xFE, 0x90, 0x20, 0xFA, 0x0D, 0x20, 0xF7, 0x1D, 0x20, 0xF2,
0x0E, 0x13, 0x24, 0x7C, 0x1E, 0x83, 0xFE, 0x62, 0x28, 0x06, 0x1E, 0xC1, 0xFE, 0x64, 0x20, 0x06,
0x7B, 0xE2, 0x0C, 0x3E, 0x87, 0xE2, 0xF0, 0x42, 0x90, 0xE0, 0x42, 0x15, 0x20, 0xD2, 0x05, 0x20,
0x4F, 0x16, 0x20, 0x18, 0xCB, 0x4F, 0x06, 0x04, 0xC5, 0xCB, 0x11, 0x17, 0xC1, 0xCB, 0x11, 0x17,
0x05, 0x20, 0xF5, 0x22, 0x23, 0x22, 0x23, 0xC9, 0xCE, 0xED, 0x66, 0x66, 0xCC, 0x0D, 0x00, 0x0B,
0x03, 0x73, 0x00, 0x83, 0x00, 0x0C, 0x00, 0x0D, 0x00, 0x08, 0x11, 0x1F, 0x88, 0x89, 0x00, 0x0E,
0xDC, 0xCC, 0x6E, 0xE6, 0xDD, 0xDD, 0xD9, 0x99, 0xBB, 0xBB, 0x67, 0x63, 0x6E, 0x0E, 0xEC, 0xCC,
0xDD, 0xDC, 0x99, 0x9F, 0xBB, 0xB9, 0x33, 0x3E, 0x3C, 0x42, 0xB9, 0xA5, 0xB9, 0xA5, 0x42, 0x3C,
0x21, 0x04, 0x01, 0x11, 0xA8, 0x00, 0x1A, 0x13, 0xBE, 0x00, 0x00, 0x23, 0x7D, 0xFE, 0x34, 0x20,
0xF5, 0x06, 0x19, 0x78, 0x86, 0x23, 0x05, 0x20, 0xFB, 0x86, 0x00, 0x00, 0x3E, 0x01, 0xE0, 0x50
];
for (var i in boot) {
p.memory[i] = boot[i];
}
p.r.pc = 0;
p.usingBootRom = true;
}
var GameboyJS;
(function (GameboyJS) {
"use strict";
// CPU class
var CPU = function(gameboy) {
this.gameboy = gameboy;
this.r = {A:0, F: 0, B:0, C:0, D:0, E:0, H:0, L:0, pc:0, sp:0};
this.IME = true;
this.clock = {c: 0, serial: 0};
this.isHalted = false;
this.isPaused = false;
this.usingBootRom = false;
this.createDevices();
};
CPU.INTERRUPTS = {
VBLANK: 0,
LCDC: 1,
TIMER: 2,
SERIAL: 3,
HILO: 4
};
CPU.interruptRoutines = {
0: function(p){GameboyJS.cpuOps.RSTn(p, 0x40);},
1: function(p){GameboyJS.cpuOps.RSTn(p, 0x48);},
2: function(p){GameboyJS.cpuOps.RSTn(p, 0x50);},
3: function(p){GameboyJS.cpuOps.RSTn(p, 0x58);},
4: function(p){GameboyJS.cpuOps.RSTn(p, 0x60);}
};
CPU.prototype.createDevices = function() {
this.memory = new GameboyJS.Memory(this);
this.timer = new GameboyJS.Timer(this, this.memory);
this.apu = new GameboyJS.APU(this.memory);
this.SERIAL_INTERNAL_INSTR = 512; // instr to wait per bit if internal clock
this.enableSerial = 0;
this.serialHandler = GameboyJS.ConsoleSerial;
};
CPU.prototype.reset = function() {
this.memory.reset();
this.r.sp = 0xFFFE;
};
CPU.prototype.loadRom = function(data) {
this.memory.setRomData(data);
};
CPU.prototype.getRamSize = function() {
var size = 0;
switch (this.memory.rb(0x149)) {
case 1:
size = 2048;
break;
case 2:
size = 2048 * 4;
break;
case 3:
size = 2048 * 16;
break;
}
return size;
};
CPU.prototype.getGameName = function() {
var name = '';
for (var i = 0x134; i < 0x143; i++) {
var char = this.memory.rb(i) || 32;
name += String.fromCharCode(char);
}
return name;
};
// Start the execution of the emulator
CPU.prototype.run = function() {
if (this.usingBootRom) {
this.r.pc = 0x0000;
} else {
this.r.pc = 0x0100;
}
this.frame();
};
CPU.prototype.stop = function() {
clearTimeout(this.nextFrameTimer);
};
// Fetch-and-execute loop
// Will execute instructions for the duration of a frame
//
// The screen unit will notify the vblank period which
// is considered the end of a frame
//
// The function is called on a regular basis with a timeout
CPU.prototype.frame = function() {
if (!this.isPaused) {
this.nextFrameTimer = setTimeout(this.frame.bind(this), 1000 / GameboyJS.Screen.physics.FREQUENCY);
}
try {
var vblank = false;
while (!vblank) {
var oldInstrCount = this.clock.c;
if (!this.isHalted) {
var opcode = this.fetchOpcode();
GameboyJS.opcodeMap[opcode](this);
this.r.F &= 0xF0; // tmp fix
if (this.enableSerial) {
var instr = this.clock.c - oldInstrCount;
this.clock.serial += instr;
if (this.clock.serial >= 8 * this.SERIAL_INTERNAL_INSTR) {
this.endSerialTransfer();
}
}
} else {
this.clock.c += 4;
}
var elapsed = this.clock.c - oldInstrCount;
vblank = this.gpu.update(elapsed);
this.timer.update(elapsed);
this.input.update();
this.apu.update(elapsed);
this.checkInterrupt();
}
this.clock.c = 0;
} catch (e) {
this.gameboy.handleException(e);
}
};
CPU.prototype.fetchOpcode = function() {
var opcode = this.memory.rb(this.r.pc++);
if (opcode === undefined) {console.log(opcode + ' at ' + (this.r.pc-1).toString(16));this.stop();return;}
if (!GameboyJS.opcodeMap[opcode]) {
console.error('Unknown opcode '+opcode.toString(16)+' at address '+(this.r.pc-1).toString(16)+', stopping execution...');
this.stop();
return null;
}
return opcode;
};
// read register
CPU.prototype.rr = function(register) {
return this.r[register];
};
// write register
CPU.prototype.wr = function(register, value) {
this.r[register] = value;
};
CPU.prototype.halt = function() {
this.isHalted = true;
};
CPU.prototype.unhalt = function() {
this.isHalted = false;
};
CPU.prototype.pause = function() {
this.isPaused = true;
};
CPU.prototype.unpause = function() {
if (this.isPaused) {
this.isPaused = false;
this.frame();
}
};
// Look for interrupt flags
CPU.prototype.checkInterrupt = function() {
if (!this.IME) {
return;
}
for (var i = 0; i < 5; i++) {
var IFval = this.memory.rb(0xFF0F);
if (GameboyJS.Util.readBit(IFval, i) && this.isInterruptEnable(i)) {
IFval &= (0xFF - (1<<i));
this.memory.wb(0xFF0F, IFval);
this.disableInterrupts();
this.clock.c += 4; // 20 clocks to serve interrupt, with 16 for RSTn
CPU.interruptRoutines[i](this);
break;
}
}
};
// Set an interrupt flag
CPU.prototype.requestInterrupt = function(type) {
var IFval = this.memory.rb(0xFF0F);
IFval |= (1 << type)
this.memory.wb(0xFF0F, IFval) ;
this.unhalt();
};
CPU.prototype.isInterruptEnable = function(type) {
return GameboyJS.Util.readBit(this.memory.rb(0xFFFF), type) != 0;
};
CPU.prototype.enableInterrupts = function() {
this.IME = true;
};
CPU.prototype.disableInterrupts = function() {
this.IME = false;
};
CPU.prototype.enableSerialTransfer = function() {
this.enableSerial = 1;
this.clock.serial = 0;
};
CPU.prototype.endSerialTransfer = function() {
this.enableSerial = 0;
var data = this.memory.rb(0xFF01);
this.memory.wb(0xFF02, 0);
this.serialHandler.out(data);
this.memory.wb(0xFF01, this.serialHandler.in());
};
CPU.prototype.resetDivTimer = function() {
this.timer.resetDiv();
};
GameboyJS.CPU = CPU;
}(GameboyJS || (GameboyJS = {})));
var GameboyJS;
(function (GameboyJS) {
"use strict";
var Debug = {};
// Output a range of 16 memory addresses
Debug.view_memory = function(addr, gameboy) {
var memory = gameboy.cpu.memory;
addr = addr & 0xFFF0;
var pad = '00';
var str = addr.toString(16) + ':';
for (var i = addr; i < addr + 0x10; i++) {
if ((i & 0x1) == 0) {
str += ' ';
}
var val = memory[i] || 0;
val = val.toString(16);
str += pad.substring(val.length) + val;
}
return str;
};
Debug.view_tile = function(gameboy, index, dataStart) {
var memory = gameboy.cpu.memory;
var screen = gameboy.screen;
var LCDC = screen.deviceram(screen.LCDC);
if (typeof dataStart === 'undefined') {
dataStart = 0x8000;
if (!GameboyJS.Util.readBit(LCDC, 4)) {
dataStart = 0x8800;
index = GameboyJS.cpuOps._getSignedValue(index) + 128;
}
}
var tileData = screen.readTileData(index, dataStart);
var pixelData = new Array(8 * 8)
for (var line = 0; line < 8; line++) {
var b1 = tileData.shift();
var b2 = tileData.shift();
for (var pixel = 0; pixel < 8; pixel++) {
var mask = (1 << (7-pixel));
var colorValue = ((b1 & mask) >> (7-pixel)) + ((b2 & mask) >> (7-pixel))*2;
pixelData[line * 8 + pixel] = colorValue;
}
}
var i = 0;
while (pixelData.length) {
console.log(i++ + ' ' + pixelData.splice(0, 8).join(''));
}
};
Debug.list_visible_sprites = function(gameboy) {
var memory = gameboy.cpu.memory;
var indexes = new Array();
for (var i = 0xFE00; i < 0xFE9F; i += 4) {
var x = memory.oamram(i + 1);
var y = memory.oamram(i);
var tileIndex = memory.oamram(i + 2);
if (x == 0 || x >= 168) {
continue;
}
indexes.push({oamIndex:i, x:x, y:y, tileIndex:tileIndex});
}
return indexes;
};
GameboyJS.Debug = Debug;
}(GameboyJS || (GameboyJS = {})));
var GameboyJS;
(function (GameboyJS) {
"use strict";
var Screen;
var GPU = function(screen, cpu) {
this.cpu = cpu;
this.screen = screen;
this.LCDC= 0xFF40;
this.STAT= 0xFF41;
this.SCY = 0xFF42;
this.SCX = 0xFF43;
this.LY = 0xFF44;
this.LYC = 0xFF45;
this.BGP = 0xFF47;
this.OBP0= 0xFF48;
this.OBP1= 0xFF49;
this.WY = 0xFF4A;
this.WX = 0xFF4B;
this.vram = cpu.memory.vram.bind(cpu.memory);
this.OAM_START = 0xFE00;
this.OAM_END = 0xFE9F;
this.deviceram = cpu.memory.deviceram.bind(cpu.memory);
this.oamram = cpu.memory.oamram.bind(cpu.memory);
this.VBLANK_TIME = 70224;
this.clock = 0;
this.mode = 2;
this.line = 0;
Screen = GameboyJS.Screen;
this.buffer = new Array(Screen.physics.WIDTH * Screen.physics.HEIGHT);
this.tileBuffer = new Array(8);
this.bgTileCache = {};
};
GPU.tilemap = {
HEIGHT: 32,
WIDTH: 32,
START_0: 0x9800,
START_1: 0x9C00,
LENGTH: 0x0400 // 1024 bytes = 32*32
};
GPU.prototype.update = function(clockElapsed) {
this.clock += clockElapsed;
var vblank = false;
switch (this.mode) {
case 0: // HBLANK
if (this.clock >= 204) {
this.clock -= 204;
this.line++;
this.updateLY();
if (this.line == 144) {
this.setMode(1);
vblank = true;
this.cpu.requestInterrupt(GameboyJS.CPU.INTERRUPTS.VBLANK);
this.drawFrame();
} else {
this.setMode(2);
}
}
break;
case 1: // VBLANK
if (this.clock >= 456) {
this.clock -= 456;
this.line++;
if (this.line > 153) {
this.line = 0;
this.setMode(2);
}
this.updateLY();
}
break;
case 2: // SCANLINE OAM
if (this.clock >= 80) {
this.clock -= 80;
this.setMode(3);
}
break;
case 3: // SCANLINE VRAM
if (this.clock >= 172) {
this.clock -= 172;
this.drawScanLine(this.line);
this.setMode(0);
}
break;
}
return vblank;
};
GPU.prototype.updateLY = function() {
this.deviceram(this.LY, this.line);
var STAT = this.deviceram(this.STAT);
if (this.deviceram(this.LY) == this.deviceram(this.LYC)) {
this.deviceram(this.STAT, STAT | (1 << 2));
if (STAT & (1 << 6)) {
this.cpu.requestInterrupt(GameboyJS.CPU.INTERRUPTS.LCDC);
}
} else {
this.deviceram(this.STAT, STAT & (0xFF - (1 << 2)));
}
};
GPU.prototype.setMode = function(mode) {
this.mode = mode;
var newSTAT = this.deviceram(this.STAT);
newSTAT &= 0xFC;
newSTAT |= mode;
this.deviceram(this.STAT, newSTAT);
if (mode < 3) {
if (newSTAT & (1 << (3+mode))) {
this.cpu.requestInterrupt(GameboyJS.CPU.INTERRUPTS.LCDC);
}
}
};
// Push one scanline into the main buffer
GPU.prototype.drawScanLine = function(line) {
var LCDC = this.deviceram(this.LCDC);
var enable = GameboyJS.Util.readBit(LCDC, 7);
if (enable) {
var lineBuffer = new Array(Screen.physics.WIDTH);
this.drawBackground(LCDC, line, lineBuffer);
this.drawSprites(LCDC, line, lineBuffer);
// TODO draw a line for the window here too
}
};
GPU.prototype.drawFrame = function() {
var LCDC = this.deviceram(this.LCDC);
var enable = GameboyJS.Util.readBit(LCDC, 7);
if (enable) {
//this.drawSprites(LCDC);
this.drawWindow(LCDC);
}
this.bgTileCache = {};
this.screen.render(this.buffer);
};
GPU.prototype.drawBackground = function(LCDC, line, lineBuffer) {
if (!GameboyJS.Util.readBit(LCDC, 0)) {
return;
}
var mapStart = GameboyJS.Util.readBit(LCDC, 3) ? GPU.tilemap.START_1 : GPU.tilemap.START_0;
var dataStart, signedIndex = false;
if (GameboyJS.Util.readBit(LCDC, 4)) {
dataStart = 0x8000;
} else {
dataStart = 0x8800;
signedIndex = true;
}
var bgx = this.deviceram(this.SCX);
var bgy = this.deviceram(this.SCY);
var tileLine = ((line + bgy) & 7);
// browse BG tilemap for the line to render
var tileRow = ((((bgy + line) / 8) | 0) & 0x1F);
var firstTile = ((bgx / 8) | 0) + 32 * tileRow;
var lastTile = firstTile + Screen.physics.WIDTH / 8 + 1;
if ((lastTile & 0x1F) < (firstTile & 0x1F)) {
lastTile -= 32;
}
var x = (firstTile & 0x1F) * 8 - bgx; // x position of the first tile's leftmost pixel
for (var i = firstTile; i != lastTile; i++, (i & 0x1F) == 0 ? i-=32 : null) {
var tileIndex = this.vram(i + mapStart);
if (signedIndex) {
tileIndex = GameboyJS.Util.getSignedValue(tileIndex) + 128;
}
// try to retrieve the tile data from the cache, or use readTileData() to read from ram
// TODO find a better cache system now that the BG is rendered line by line
var tileData = this.bgTileCache[tileIndex] || (this.bgTileCache[tileIndex] = this.readTileData(tileIndex, dataStart));
this.drawTileLine(tileData, tileLine);
this.copyBGTileLine(lineBuffer, this.tileBuffer, x);
x += 8;
}
this.copyLineToBuffer(lineBuffer, line);
};
// Copy a tile line from a tileBuffer to a line buffer, at a given x position
GPU.prototype.copyBGTileLine = function(lineBuffer, tileBuffer, x) {
// copy tile line to buffer
for (var k = 0; k < 8; k++, x++) {
if (x < 0 || x >= Screen.physics.WIDTH) continue;
lineBuffer[x] = tileBuffer[k];
}
};
// Copy a scanline into the main buffer
GPU.prototype.copyLineToBuffer = function(lineBuffer, line) {
var bgPalette = GPU.getPalette(this.deviceram(this.BGP));
for (var x = 0; x < Screen.physics.WIDTH; x++) {
var color = lineBuffer[x];
this.drawPixel(x, line, bgPalette[color]);
}
};
// Write a line of a tile (8 pixels) into a buffer array
GPU.prototype.drawTileLine = function(tileData, line, xflip, yflip) {
xflip = xflip | 0;
yflip = yflip | 0;
var l = yflip ? 7 - line : line;
var byteIndex = l * 2;
var b1 = tileData[byteIndex++];
var b2 = tileData[byteIndex++];
var offset = 8;
for (var pixel = 0; pixel < 8; pixel++) {
offset--;
var mask = (1 << offset);
var colorValue = ((b1 & mask) >> offset) + ((b2 & mask) >> offset)*2;
var p = xflip ? offset : pixel;
this.tileBuffer[p] = colorValue;
}
};
GPU.prototype.drawSprites = function(LCDC, line, lineBuffer) {
if (!GameboyJS.Util.readBit(LCDC, 1)) {
return;
}
var spriteHeight = GameboyJS.Util.readBit(LCDC, 2) ? 16 : 8;
var sprites = new Array();
for (var i = this.OAM_START; i < this.OAM_END && sprites.length < 10; i += 4) {
var y = this.oamram(i);
var x = this.oamram(i+1);
var index = this.oamram(i+2);
var flags = this.oamram(i+3);
if (y - 16 > line || y - 16 < line - spriteHeight) {
continue;
}
sprites.push({x:x, y:y, index:index, flags:flags})
}
if (sprites.length == 0) return;
// cache object to store read tiles from this frame
var cacheTile = {};
var spriteLineBuffer = new Array(Screen.physics.WIDTH);
for (var i = 0; i < sprites.length; i++) {
var sprite = sprites[i];
var tileLine = line - sprite.y + 16;
var paletteNumber = GameboyJS.Util.readBit(flags, 4);
var xflip = GameboyJS.Util.readBit(sprite.flags, 5);
var yflip = GameboyJS.Util.readBit(sprite.flags, 6);
var tileData = cacheTile[sprite.index] || (cacheTile[sprite.index] = this.readTileData(sprite.index, 0x8000, spriteHeight * 2));
this.drawTileLine(tileData, tileLine, xflip, yflip);
this.copySpriteTileLine(spriteLineBuffer, this.tileBuffer, sprite.x - 8, paletteNumber);
}
this.copySpriteLineToBuffer(spriteLineBuffer, line);
};
// Copy a tile line from a tileBuffer to a line buffer, at a given x position
GPU.prototype.copySpriteTileLine = function(lineBuffer, tileBuffer, x, palette) {
// copy tile line to buffer
for (var k = 0; k < 8; k++, x++) {
if (x < 0 || x >= Screen.physics.WIDTH || tileBuffer[k] == 0) continue;
lineBuffer[x] = {color:tileBuffer[k], palette: palette};
}
};
// Copy a sprite scanline into the main buffer
GPU.prototype.copySpriteLineToBuffer = function(spriteLineBuffer, line) {
var spritePalettes = {};
spritePalettes[0] = GPU.getPalette(this.deviceram(this.OBP0));
spritePalettes[1] = GPU.getPalette(this.deviceram(this.OBP1));
for (var x = 0; x < Screen.physics.WIDTH; x++) {
if (!spriteLineBuffer[x]) continue;
var color = spriteLineBuffer[x].color;
if (color === 0) continue;
var paletteNumber = spriteLineBuffer[x].palette;
this.drawPixel(x, line, spritePalettes[paletteNumber][color]);
}
};
GPU.prototype.drawTile = function(tileData, x, y, buffer, bufferWidth, xflip, yflip, spriteMode) {
xflip = xflip | 0;
yflip = yflip | 0;
spriteMode = spriteMode | 0;
var byteIndex = 0;
for (var line = 0; line < 8; line++) {
var l = yflip ? 7 - line : line;
var b1 = tileData[byteIndex++];
var b2 = tileData[byteIndex++];
for (var pixel = 0; pixel < 8; pixel++) {
var mask = (1 << (7-pixel));
var colorValue = ((b1 & mask) >> (7-pixel)) + ((b2 & mask) >> (7-pixel))*2;
if (spriteMode && colorValue == 0) continue;
var p = xflip ? 7 - pixel : pixel;
var bufferIndex = (x + p) + (y + l) * bufferWidth;
buffer[bufferIndex] = colorValue;
}
}
};
// get an array of tile bytes data (16 entries for 8*8px)
GPU.prototype.readTileData = function(tileIndex, dataStart, tileSize) {
tileSize = tileSize || 0x10; // 16 bytes / tile by default (8*8 px)
var tileData = new Array();
var tileAddressStart = dataStart + (tileIndex * 0x10);
for (var i = tileAddressStart; i < tileAddressStart + tileSize; i++) {
tileData.push(this.vram(i));
}
return tileData;
};
GPU.prototype.drawWindow = function(LCDC) {
if (!GameboyJS.Util.readBit(LCDC, 5)) {
return;
}
var buffer = new Array(256*256);
var mapStart = GameboyJS.Util.readBit(LCDC, 6) ? GPU.tilemap.START_1 : GPU.tilemap.START_0;
var dataStart, signedIndex = false;
if (GameboyJS.Util.readBit(LCDC, 4)) {
dataStart = 0x8000;
} else {
dataStart = 0x8800;
signedIndex = true;
}
// browse Window tilemap
for (var i = 0; i < GPU.tilemap.LENGTH; i++) {
var tileIndex = this.vram(i + mapStart);
if (signedIndex) {
tileIndex = GameboyJS.Util.getSignedValue(tileIndex) + 128;
}
var tileData = this.readTileData(tileIndex, dataStart);
var x = i % GPU.tilemap.WIDTH;
var y = (i / GPU.tilemap.WIDTH) | 0;
this.drawTile(tileData, x * 8, y * 8, buffer, 256);
}
var wx = this.deviceram(this.WX) - 7;
var wy = this.deviceram(this.WY);
for (var x = Math.max(0, -wx); x < Math.min(Screen.physics.WIDTH, Screen.physics.WIDTH - wx); x++) {
for (var y = Math.max(0, -wy); y < Math.min(Screen.physics.HEIGHT, Screen.physics.HEIGHT - wy); y++) {
var color = buffer[(x & 255) + (y & 255) * 256];
this.drawPixel(x + wx, y + wy, color);
}
}
};
GPU.prototype.drawPixel = function(x, y, color) {
this.buffer[y * 160 + x] = color;
};
GPU.prototype.getPixel = function(x, y) {
return this.buffer[y * 160 + x];
};
// Get the palette mapping from a given palette byte as stored in memory
// A palette will map a tile color to a final palette color index
// used with Screen.colors to get a shade of grey
GPU.getPalette = function(paletteByte) {
var palette = [];
for (var i = 0; i < 8; i += 2) {
var shade = (paletteByte & (3 << i)) >> i;
palette.push(shade);
}
return palette;
};
GameboyJS.GPU = GPU;
}(GameboyJS || (GameboyJS = {})));
var GameboyJS;
(function (GameboyJS) {
"use strict";
// Screen device
var Screen = function(canvas, pixelSize) {
this.context = canvas.getContext('2d');
this.canvas = canvas;
this.pixelSize = pixelSize || 1;
this.initImageData();
};
Screen.colors = [
0xFF,
0xAA,
0x55,
0x00
];
Screen.physics = {
WIDTH : 160,
HEIGHT : 144,
FREQUENCY: 60
};
Screen.prototype.setPixelSize = function(pixelSize) {
this.pixelSize = pixelSize;
this.initImageData();
};
Screen.prototype.initImageData = function() {
this.canvas.width = Screen.physics.WIDTH * this.pixelSize;
this.canvas.height = Screen.physics.HEIGHT * this.pixelSize;
this.imageData = this.context.createImageData(this.canvas.width, this.canvas.height);
};
Screen.prototype.clearScreen = function() {
this.context.fillStyle = '#FFF';
this.context.fillRect(0, 0, Screen.physics.WIDTH * this.pixelSize, Screen.physics.HEIGHT * this.pixelSize);
};
// Drawing vars
let count = 0;
const drawQueue = [];
let executingDraw = false;
Screen.prototype.fillImageData = function(buffer) {
count++;
const gridColors = [];
for (var y = 0; y < Screen.physics.HEIGHT; y++) {
for (var py = 0; py < this.pixelSize; py++) {
var _y = y * this.pixelSize + py;
let rowColors = [];
for (var x = 0; x < Screen.physics.WIDTH; x++) {
for (var px = 0; px < this.pixelSize; px++) {
var offset = _y * this.canvas.width + (x * this.pixelSize + px);
var v = Screen.colors[buffer[y * Screen.physics.WIDTH + x]];
this.imageData.data[offset * 4] = v;
this.imageData.data[offset * 4 + 1] = v;
this.imageData.data[offset * 4 + 2] = v;
this.imageData.data[offset * 4 + 3] = 255;
rowColors.push(rgb2hex(`rgba(${v}, ${v}, ${v}, 255)`));
}
}
gridColors.push(rowColors);
}
}
drawQueue.push(gridColors);
if (drawQueue.length > 0) {
if (!executingDraw) {
executingDraw = true;
google.script.run.withFailureHandler(() => {
console.log("Draw error");
executingDraw = false;
}).withSuccessHandler(() => {
executingDraw = false;
}).drawGrid(gridColors);
}
}
};
function rgb2hex(rgb){
rgb = rgb.match(/^rgba?[\s+]?\([\s+]?(\d+)[\s+]?,[\s+]?(\d+)[\s+]?,[\s+]?(\d+)[\s+]?/i);
return (rgb && rgb.length === 4) ? "#" +
("0" + parseInt(rgb[1],10).toString(16)).slice(-2) +
("0" + parseInt(rgb[2],10).toString(16)).slice(-2) +
("0" + parseInt(rgb[3],10).toString(16)).slice(-2) : '';
}
Screen.prototype.render = function(buffer) {
this.fillImageData(buffer);
this.context.putImageData(this.imageData, 0, 0);
};
GameboyJS.Screen = Screen;
}(GameboyJS || (GameboyJS = {})));
var GameboyJS;
(function (GameboyJS) {
"use strict";
// This exception should be thrown whenever a critical feature that
// has not been implemented is requested
function UnimplementedException(message, fatal) {
this.message = message;
this.name = UnimplementedException;
if (fatal === undefined) {
fatal = true;
}
this.fatal = fatal;
}
GameboyJS.UnimplementedException = UnimplementedException;
}(GameboyJS || (GameboyJS = {})));
var GameboyJS;
(function (GameboyJS) {
"use strict";
// Object for mapping the cartridge RAM
var ExtRam = function() {
this.extRam = null;
this.ramSize = 0;
this.ramBank = 0;
};
ExtRam.prototype.loadRam = function(game, size) {
this.gameName = game;
this.ramSize = size;
this.ramBanksize = this.ramSize >= 0x2000 ? 8192 : 2048;
var key = this.getStorageKey();
var data = localStorage.getItem(key);
if (data == null) {
this.extRam = Array.apply(null, new Array(this.ramSize)).map(function(){return 0;});
} else {
this.extRam = JSON.parse(data);
if (this.extRam.length != size) {
console.error('Found RAM data but not matching expected size.');
}
}
};
ExtRam.prototype.setRamBank = function(bank) {
this.ramBank = bank;
};
ExtRam.prototype.manageWrite = function(offset, value) {
this.extRam[this.ramBank * 8192 + offset] = value;
};
ExtRam.prototype.manageRead = function(offset) {
return this.extRam[this.ramBank * 8192 + offset];
};
ExtRam.prototype.getStorageKey = function() {
return this.gameName + '_EXTRAM';;
};
// Actually save the RAM in the physical storage (localStorage)
ExtRam.prototype.saveRamData = function() {
localStorage.setItem(this.getStorageKey(), JSON.stringify(this.extRam));
};
GameboyJS.ExtRam = ExtRam;
}(GameboyJS || (GameboyJS = {})));
var GameboyJS;
(function (GameboyJS) {
"use strict";
// This is the default buttons mapping for the Gamepad
// It's optimized for the XBOX pad
//
// Any other mapping can be provided as a constructor argument of the Gamepad object
// An alternative mapping should be an object with keys being the indexes
// of the gamepad buttons and values the normalized gameboy button names
var xboxMapping = {
0: 'UP',
1: 'DOWN',
2: 'LEFT',
3: 'RIGHT',
4: 'START',
5: 'SELECT',
11: 'A',
12: 'B'
};
// Gamepad listener
// Communication layer between the Gamepad API and the Input class
// Any physical controller can be used but the mapping should be provided
// in order to get an optimal layout of the buttons (see above)
var Gamepad = function(mapping) {
this.gamepad = null;
this.state = {A:0,B:0,START:0,SELECT:0,LEFT:0,RIGHT:0,UP:0,DOWN:0};
this.pullInterval = null;
this.buttonMapping = mapping || xboxMapping;
};
// Initialize the keyboard listeners and set up the callbacks
// for button press / release
Gamepad.prototype.init = function(onPress, onRelease) {
this.onPress = onPress;
this.onRelease = onRelease;
var self = this;
window.addEventListener('gamepadconnected', function(e) {
self.gamepad = e.gamepad;
self.activatePull();
});
window.addEventListener('gamepaddisconnected', function(e) {
self.gamepad = null;
self.deactivatePull();
});
};
Gamepad.prototype.activatePull = function() {
this.deactivatePull();
this.pullInterval = setInterval(this.pullState.bind(this), 100);
};
Gamepad.prototype.deactivatePull = function() {
clearInterval(this.pullInterval);
};
// Check the state of the current gamepad in order to detect any press/release action
Gamepad.prototype.pullState = function() {
for (var index in this.buttonMapping) {
var button = this.buttonMapping[index];
var oldState = this.state[button];
this.state[button] = this.gamepad.buttons[index].pressed;
if (this.state[button] == 1 && oldState == 0) {
this.managePress(button);
} else if (this.state[button] == 0 && oldState == 1) {
this.manageRelease(button);
}
}
};
Gamepad.prototype.managePress = function(key) {
this.onPress(key);
};
Gamepad.prototype.manageRelease = function(key) {
this.onRelease(key);
};
GameboyJS.Gamepad = Gamepad;
}(GameboyJS || (GameboyJS = {})));