forked from jsdf/little-virtual-computer
-
Notifications
You must be signed in to change notification settings - Fork 0
/
computer1.js
1726 lines (1562 loc) · 56.4 KB
/
computer1.js
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
// @flow
/*
Components: (do a ctrl-f find for them)
1.MEMORY
2.CPU
3.DISPLAY
4.INPUT
5.AUDIO
6.ASSEMBLER
7.SIMULATION CONTROL
8.BUILT-IN PROGRAMS
*/
// 1.MEMORY
const Memory = {
/*
We are going to use an array to simulate computer memory. We can store a number
value at each position in the array, and we will use a number value to access
each slot in the array (we'll call these array indexes 'memory addresses').
Real computers have memory which can be read and written as individual bytes,
and also in larger or smaller chunks. In real computers memory addresses and
values are usually shown as hexadecimal (base-16) form, due to the fact that
hexadecimal is a concise alternative to binary, which 'lines up' nicely with
binary: a 1 digit hexadecimal number can represent exactly all of the values
which a 4 digit binary number can. However, we are going to represent addresses
and values as base-10 numbers (the kind you're used to), so there's one less
thing you need know about at this point. If you like you can read more about
binary and hexidecimal numbers here (but it's not essential):
https://jamesfriend.com.au/how-do-binary-and-hexadecimal-numbers-work
*/
ram: [],
/*
Here we have the total amount of array slots (or memory addresses) we are
going to have at which to store data values.
The program code will also be loaded into these slots, and when the CPU starts
running, it will begin reading each instruction of the program from memory and
executing it. At the hardware level, program code is just another form of data
stored in memory.
We'll use the first 1000 (0 - 999) slots as working space for our code to use.
The next 1000 (1000 - 1999) we'll load our program code into, and that's where
it will be executed from.
The final 1000 slots will be used to communicate with the input and output (I/O)
devices.
2000 - 2003: the keycode of a key which is currently pressed, from most recently
to least recently started
2010, 2011: the x and y position of the mouse within the screen.
2012: the address of the pixel the mouse is currently on
2013: mouse button status (0 = up, 1 = down)
2050: a random number which changes before every instruction
2051 - 2099: unused
2100 - 2999: The content of the screen, specifically the color values of each
of the pixels of the 30x30 pixel screen, row by row, from the top left.
For example, the top row uses slots 2100 - 2129, and the bottom row uses
slots 2970 - 3000.
3000 - 3008: Memory addresses used to control 3 channels of audio output. This
computer is too simple to play recorded sounds, but can simple tones, which you
can control by setting the addresses for 'wavetype', frequency and volume of
each channel.
*/
TOTAL_MEMORY_SIZE: 3100,
WORKING_MEMORY_START: 0,
WORKING_MEMORY_END: 1000,
PROGRAM_MEMORY_START: 1000,
PROGRAM_MEMORY_END: 2000,
KEYCODE_0_ADDRESS: 2000,
KEYCODE_1_ADDRESS: 2001,
KEYCODE_2_ADDRESS: 2002,
MOUSE_X_ADDRESS: 2010,
MOUSE_Y_ADDRESS: 2011,
MOUSE_PIXEL_ADDRESS: 2012,
MOUSE_BUTTON_ADDRESS: 2013,
RANDOM_NUMBER_ADDRESS: 2050,
CURRENT_TIME_ADDRESS: 2051,
VIDEO_MEMORY_START: 2100,
VIDEO_MEMORY_END: 3000,
AUDIO_CH1_WAVETYPE_ADDRESS: 3000,
AUDIO_CH1_FREQUENCY_ADDRESS: 3001,
AUDIO_CH1_VOLUME_ADDRESS: 3002,
AUDIO_CH2_WAVETYPE_ADDRESS: 3003,
AUDIO_CH2_FREQUENCY_ADDRESS: 3004,
AUDIO_CH2_VOLUME_ADDRESS: 3005,
AUDIO_CH3_WAVETYPE_ADDRESS: 3006,
AUDIO_CH3_FREQUENCY_ADDRESS: 3007,
AUDIO_CH3_VOLUME_ADDRESS: 3008,
// The program will be loaded into the region of memory starting at this slot.
PROGRAM_START: 1000,
// Store a value at a certain address in memory
set(address, value) {
if (isNaN(value)) {
throw new Error(`tried to write to an invalid value at ${address}`);
}
if (address < 0 || address >= this.TOTAL_MEMORY_SIZE) {
throw new Error('tried to write to an invalid memory address');
}
this.ram[address] = value;
},
// Get the value which is stored at a certain address in memory
get(address) {
if (address < 0 || address >= this.TOTAL_MEMORY_SIZE) {
throw new Error('tried to read from an invalid memory address');
}
return this.ram[address];
},
};
// 2.CPU
const CPU = {
/*
These instructions represent the things the CPU can be told to do. We
implement them here with code, but a real CPU would have circuitry
implementing each one of these possible actions, which include things like
loading data from memory, comparing it, operating on and combining it, and
storing it back into Memory.
We assign numerical values called 'opcodes' to each of the instructions. When
our program is 'assembled' from the program code text, the version of the
program that we actually load into memory will use these numeric codes to refer
to the CPU instructions in place of the textual names as a numeric value is a
more efficient representation, especially as computers only directly understand
numbers, whereas text is an abstraction on top of number values.
We'll make the opcodes numbers starting at 9000 to make the values a bit more
distinctive when we see them in the memory viewer. We'll include some extra info
about each of the instructions so our simulator user interface can show it
alongside the 'disassembled' view of the program code in Memory.
There are a lot of these, so it's probably not worth reading the code for each one,
but they are grouped into sections of related instructions, so it might be worth
taking a look at a few in each section. When you're done you can skip ahead to the
next part which defines the 'programCounter'.
*/
instructions: {
// First, some instructions for copying values between places in memory.
// this instruction is typically called 'mov', short for 'move', as in 'move
// value at *this* address to *that* address', but this naming can be a bit
// confusing, because the operation doesn't remove the value at the source
// address, as 'move' might seem to imply, so for clarity we'll call it 'copy_to_from' instead.
copy_to_from: {
opcode: 9000,
description: 'set value at address to the value at the given address',
operands: [['destination', 'address'], ['source', 'address']],
execute(destination, sourceAddress) {
const sourceValue = Memory.get(sourceAddress);
Memory.set(destination, sourceValue);
},
},
copy_to_from_constant: {
opcode: 9001,
description: 'set value at address to the given constant value',
operands: [['destination', 'address'], ['source', 'constant']],
execute(address, sourceValue) {
Memory.set(address, sourceValue);
},
},
copy_to_from_ptr: {
opcode: 9002,
description: `set value at destination address to the value at the
address pointed to by the value at 'source' address`,
operands: [['destination', 'address'], ['source', 'pointer']],
execute(destinationAddress, sourcePointer) {
const sourceAddress = Memory.get(sourcePointer);
const sourceValue = Memory.get(sourceAddress);
Memory.set(destinationAddress, sourceValue);
},
},
copy_into_ptr_from: {
opcode: 9003,
description: `set value at the address pointed to by the value at
'destination' address to the value at the source address`,
operands: [['destination', 'pointer'], ['source', 'address']],
execute(destinationPointer, sourceAddress) {
const destinationAddress = Memory.get(destinationPointer);
const sourceValue = Memory.get(sourceAddress);
Memory.set(destinationAddress, sourceValue);
},
},
copy_address_of_label: {
opcode: 9004,
description: `set value at destination address to the address of the label
given`,
operands: [['destination', 'address'], ['source', 'label']],
execute(destinationAddress, labelAddress) {
Memory.set(destinationAddress, labelAddress);
},
},
// Next, some instructions for performing arithmetic
add: {
opcode: 9010,
description: `add the value at the 'a' address with the value at the 'b'
address and store the result at the 'result' address`,
operands: [['a', 'address'], ['b', 'address'], ['result', 'address']],
execute(aAddress, bAddress, resultAddress) {
const a = Memory.get(aAddress);
const b = Memory.get(bAddress);
const result = a + b;
Memory.set(resultAddress, result);
},
},
add_constant: {
opcode: 9011,
description: `add the value at the 'a' address with the constant value 'b' and store
the result at the 'result' address`,
operands: [['a', 'address'], ['b', 'constant'], ['result', 'address']],
execute(aAddress, b, resultAddress) {
const a = Memory.get(aAddress);
const result = a + b;
Memory.set(resultAddress, result);
},
},
subtract: {
opcode: 9020,
description: `from the value at the 'a' address, subtract the value at the
'b' address and store the result at the 'result' address`,
operands: [['a', 'address'], ['b', 'address'], ['result', 'address']],
execute(aAddress, bAddress, resultAddress) {
const a = Memory.get(aAddress);
const b = Memory.get(bAddress);
const result = a - b;
Memory.set(resultAddress, result);
},
},
subtract_constant: {
opcode: 9021,
description: `from the value at the 'a' address, subtract the constant value 'b' and
store the result at the 'result' address`,
operands: [['a', 'address'], ['b', 'constant'], ['result', 'address']],
execute(aAddress, b, resultAddress) {
const a = Memory.get(aAddress);
const result = a - b;
Memory.set(resultAddress, result);
},
},
multiply: {
opcode: 9030,
description: `multiply the value at the 'a' address and the value at the 'b'
address and store the result at the 'result' address`,
operands: [['a', 'address'], ['b', 'address'], ['result', 'address']],
execute(aAddress, bAddress, resultAddress) {
const a = Memory.get(aAddress);
const b = Memory.get(bAddress);
const result = a * b;
Memory.set(resultAddress, result);
},
},
multiply_constant: {
opcode: 9031,
description: `multiply the value at the 'a' address and the constant value 'b' and
store the result at the 'result' address`,
operands: [['a', 'address'], ['b', 'constant'], ['result', 'address']],
execute(aAddress, b, resultAddress) {
const a = Memory.get(aAddress);
const result = a * b;
Memory.set(resultAddress, result);
},
},
divide: {
opcode: 9040,
description: `integer divide the value at the 'a' address by the value at
the 'b' address and store the result at the 'result' address`,
operands: [['a', 'address'], ['b', 'address'], ['result', 'address']],
execute(aAddress, bAddress, resultAddress) {
const a = Memory.get(aAddress);
const b = Memory.get(bAddress);
if (b === 0) throw new Error('tried to divide by zero');
const result = Math.floor(a / b);
Memory.set(resultAddress, result);
},
},
divide_constant: {
opcode: 9041,
description: `integer divide the value at the 'a' address by the constant value 'b'
and store the result at the 'result' address`,
operands: [['a', 'address'], ['b', 'constant'], ['result', 'address']],
execute(aAddress, b, resultAddress) {
const a = Memory.get(aAddress);
if (b === 0) throw new Error('tried to divide by zero');
const result = Math.floor(a / b);
Memory.set(resultAddress, result);
},
},
modulo: {
opcode: 9050,
description: `get the value at the 'a' address modulo the value at the 'b'
address and store the result at the 'result' address`,
operands: [['a', 'address'], ['b', 'address'], ['result', 'address']],
execute(aAddress, bAddress, resultAddress) {
const a = Memory.get(aAddress);
const b = Memory.get(bAddress);
if (b === 0) throw new Error('tried to modulo by zero');
const result = a % b;
Memory.set(resultAddress, result);
},
},
modulo_constant: {
opcode: 9051,
description: `get the value at the 'a' address modulo the constant value 'b' and
store the result at the 'result' address`,
operands: [['a', 'address'], ['b', 'constant'], ['result', 'address']],
execute(aAddress, b, resultAddress) {
const a = Memory.get(aAddress);
const result = a % b;
if (b === 0) throw new Error('tried to modulo by zero');
Memory.set(resultAddress, result);
},
},
// some instructions for comparing values
compare: {
opcode: 9090,
description: `compare the value at the 'a' address and the value at the 'b'
address and store the result (-1 for a < b, 0 for a == b, 1 for a > b) at the
'result' address`,
operands: [['a', 'address'], ['b', 'address'], ['result', 'address']],
execute(aAddress, bAddress, resultAddress) {
const a = Memory.get(aAddress);
const b = Memory.get(bAddress);
let result = 0;
if (a < b) {
result = -1;
} else if (a > b) {
result = 1;
}
Memory.set(resultAddress, result);
},
},
compare_constant: {
opcode: 9091,
description: `compare the value at the 'a' address and the constant value
'b' and store the result (-1 for a < b, 0 for a == b, 1 for a > b) at the
'result' address`,
operands: [['a', 'address'], ['b', 'constant'], ['result', 'address']],
execute(aAddress, bAddress, resultAddress) {
const a = Memory.get(aAddress);
const b = bAddress;
let result = 0;
if (a < b) {
result = -1;
} else if (a > b) {
result = 1;
}
Memory.set(resultAddress, result);
},
},
// some instructions for controlling the flow of the program
'jump_to': {
opcode: 9100,
description: `set the program counter to the address of the label specified,
so the program continues from there`,
operands: [['destination', 'label']],
execute(labelAddress) {
CPU.programCounter = labelAddress;
},
},
'branch_if_equal': {
opcode: 9101,
description: `if the value at address 'a' is equal to the value at address
'b', set the program counter to the address of the label specified, so the
program continues from there`,
operands: [['a', 'address'], ['b', 'address'], ['destination', 'label']],
execute(aAddress, bAddress, labelAddress) {
const a = Memory.get(aAddress);
const b = Memory.get(bAddress);
if (a === b) {
CPU.programCounter = labelAddress;
}
},
},
'branch_if_equal_constant': {
opcode: 9102,
description: `if the value at address 'a' is equal to the constant value 'b', set the
program counter to the address of the label specified, so the program continues
from there`,
operands: [['a', 'address'], ['b', 'constant'], ['destination', 'label']],
execute(aAddress, b, labelAddress) {
const a = Memory.get(aAddress);
if (a === b) {
CPU.programCounter = labelAddress;
}
},
},
'branch_if_not_equal': {
opcode: 9103,
description: `if the value at address 'a' is not equal to the value at
address 'b', set the program counter to the address of the label specified, so
the program continues from there`,
operands: [['a', 'address'], ['b', 'address'], ['destination', 'label']],
execute(aAddress, bAddress, labelAddress) {
const a = Memory.get(aAddress);
const b = Memory.get(bAddress);
if (a !== b) {
CPU.programCounter = labelAddress;
}
},
},
'branch_if_not_equal_constant': {
opcode: 9104,
description: `if the value at address 'a' is not equal to the constant value 'b', set
the program counter to the address of the label specified, so the program
continues from there`,
operands: [['a', 'address'], ['b', 'constant'], ['destination', 'label']],
execute(aAddress, b, labelAddress) {
const a = Memory.get(aAddress);
if (a !== b) {
CPU.programCounter = labelAddress;
}
},
},
// some additional miscellanous instructions
'data': {
opcode: 9200,
description: `operands given will be included in the program when it is
compiled at the position that they appear in the code, so you can use a label to
get the address of the data and access it`,
operands: [],
execute() {
},
},
'break': {
opcode: 9998,
description: 'pause program execution, so it must be resumed via simulator UI',
operands: [],
execute() {
CPU.running = false;
},
},
'halt': {
opcode: 9999,
description: 'end program execution, requiring the simulator to be reset to start again',
operands: [],
execute() {
CPU.running = false;
CPU.halted = true;
},
},
},
/*
In a real computer, there are small pieces of memory inside the CPU called
'registers', which just hold one value at a time, but can be accessed
very quickly. These are used for a few different purposes, such as holding a
value that we are going to do some arithmetic operations with, before storing
it back to the main memory of the computer. For simplicity in this simulator
our CPU will just directly with the values in main memory instead.
However, there is one CPU register we do need to simulate: the 'program counter'.
As we move through our program, we need to keep track of where we are up to.
The program counter contains a memory address pointing to the location of the
program instruction we are currently executing.
*/
programCounter: Memory.PROGRAM_START,
/*
We also need to keep track of whether the CPU is running or not. The 'break'
instruction, which is like 'debugger' in Javascript, will be implemented by
setting this to false. This will cause the simulator to stop, but we can still
resume the program
The 'halt' instruction will tell the CPU that we are at the end of the program,
so it should stop executing instructions, and can't be resumed.
*/
running: false,
halted: false,
reset() {
this.programCounter = Memory.PROGRAM_START;
this.halted = false;
this.running = false;
},
/*
Move the program counter forward to the next memory address and return the
opcode or data at that location
*/
advanceProgramCounter() {
if (this.programCounter < Memory.PROGRAM_MEMORY_START || this.programCounter >= Memory.PROGRAM_MEMORY_END) {
throw new Error(`program counter outside valid program memory region at ${this.programCounter}`);
}
return Memory.get(this.programCounter++);
},
/*
We'll set up a mapping between our instruction names and the numerical values
we will turn them into when we assemble the program. It is these numerical
values ('opcodes') which will be interpreted by our simulated CPU as it runs the
program.
*/
instructionsToOpcodes: new Map(),
opcodesToInstructions: new Map(),
/*
Advances through the program by one instruction, getting input from the input
devices (keyboard, mouse), and then executing the instruction. After calling this,
we'll still need to handle writing output to the output devices (screen, audio).
*/
step() {
Input.updateInputs();
const opcode = this.advanceProgramCounter();
const instructionName = this.opcodesToInstructions.get(opcode);
if (!instructionName) {
throw new Error(`Unknown opcode '${opcode}'`);
}
// read as many values from memory as the instruction takes as operands and
// execute the instruction with those operands
const operands = this.instructions[instructionName].operands.map(() =>
this.advanceProgramCounter()
);
this.instructions[instructionName].execute.apply(null, operands);
},
init() {
// Init mapping between our instruction names and opcodes
Object.keys(this.instructions).forEach((instructionName, index) => {
const opcode = this.instructions[instructionName].opcode;
this.instructionsToOpcodes.set(instructionName, opcode);
this.opcodesToInstructions.set(opcode, instructionName);
});
},
};
// 3.DISPLAY
const Display = {
SCREEN_WIDTH: 30,
SCREEN_HEIGHT: 30,
SCREEN_PIXEL_SCALE: 20,
/*
To reduce the amount of memory required to contain the data for each pixel on
the screen, we're going to use a lookup table mapping color IDs to RGB colors.
This is sometimes called a 'color palette'.
This means that rather than having to store a red, green and blue value for each
color, in our simulated program we can just use the ID of the color we want to
use for each pixel, and when the simulated video hardware draws the screen it
can look up the actual RGB color values to use for each pixel rendered.
The drawback of approach is that the colors you can use are much more limited,
as you can only use a color if it's in the palette. It also means you can't
simply lighten or darken colors using math (unless you use a clever layout of
your palette).
*/
COLOR_PALETTE: {
'0': [ 0, 0, 0], // Black
'1': [255,255,255], // White
'2': [255, 0, 0], // Red
'3': [ 0,255, 0], // Lime
'4': [ 0, 0,255], // Blue
'5': [255,255, 0], // Yellow
'6': [ 0,255,255], // Cyan/Aqua
'7': [255, 0,255], // Magenta/Fuchsia
'8': [192,192,192], // Silver
'9': [128,128,128], // Gray
'10': [128, 0, 0], // Maroon
'11': [128,128, 0], // Olive
'12': [ 0,128, 0], // Green
'13': [128, 0,128], // Purple
'14': [ 0,128,128], // Teal
'15': [ 0, 0,128], // Navy
},
getColor(pixelColorId, address) {
const color = this.COLOR_PALETTE[pixelColorId];
if (!color) {
throw new Error(`Invalid color code ${pixelColorId} at address ${address}`);
}
return color;
},
imageData: (null/*: ?ImageData */),
canvasCtx: (null/*: ?CanvasRenderingContext2D */),
/*
Read the pixel values from video memory, look them up in our color palette, and
convert them to the format which the Canvas 2D API requires: an array of RGBA
values for each pixel. This format uses 4 consecutive array slots to represent
each pixel, one for each of the RGBA channels (red, green, blue, alpha).
We don't need to vary the alpha (opacity) values, so we'll just set them to 255
(full opacity) for every pixel.
*/
drawScreen() {
const imageData = notNull(this.imageData);
const videoMemoryLength = Memory.VIDEO_MEMORY_END - Memory.VIDEO_MEMORY_START;
const pixelsRGBA = imageData.data;
for (var i = 0; i < videoMemoryLength; i++) {
const pixelColorId = Memory.ram[Memory.VIDEO_MEMORY_START + i];
const colorRGB = this.getColor(pixelColorId || 0, Memory.VIDEO_MEMORY_START + i);
pixelsRGBA[i * 4] = colorRGB[0];
pixelsRGBA[i * 4 + 1] = colorRGB[1];
pixelsRGBA[i * 4 + 2] = colorRGB[2];
pixelsRGBA[i * 4 + 3] = 255; // full opacity
}
const canvasCtx = notNull(this.canvasCtx);
canvasCtx.putImageData(imageData, 0, 0);
},
init() {
const canvasCtx = notNull(SimulatorUI.getCanvas().getContext('2d'));
this.canvasCtx = canvasCtx;
this.imageData = canvasCtx.createImageData(Display.SCREEN_WIDTH, Display.SCREEN_HEIGHT);
},
};
// 4.INPUT
/*
We make mouse and keyboard input available to our simulated computer by setting
certain locations in memory the current keyboard and mouse states before each
CPU operation.
Because the browser provides an event-based API for input, we need to listen for
relevent keyboard and mouse events and keep track of their state and expose it
to the simulated computer.
*/
const Input = {
keysPressed: new Set(),
mouseDown: false,
mouseX: 0,
mouseY: 0,
init() {
if (!document.body) throw new Error('DOM not ready');
document.body.onkeydown = (event) => {
this.keysPressed.add(event.which);
};
document.body.onkeyup = (event) => {
this.keysPressed.delete(event.which);
};
document.body.onmousedown = () => {
this.mouseDown = true;
};
document.body.onmouseup = () => {
this.mouseDown = false;
};
const screenPageTop = SimulatorUI.getCanvas().getBoundingClientRect().top + window.scrollY;
const screenPageLeft = SimulatorUI.getCanvas().getBoundingClientRect().left + window.scrollX;
SimulatorUI.getCanvas().onmousemove = (event) => {
this.mouseX = Math.floor((event.pageX - screenPageTop) / Display.SCREEN_PIXEL_SCALE);
this.mouseY = Math.floor((event.pageY - screenPageLeft) / Display.SCREEN_PIXEL_SCALE);
};
},
updateInputs() {
const mostRecentKeys = Array.from(this.keysPressed.values()).reverse();
Memory.ram[Memory.KEYCODE_0_ADDRESS] = mostRecentKeys[0] || 0;
Memory.ram[Memory.KEYCODE_1_ADDRESS] = mostRecentKeys[1] || 0;
Memory.ram[Memory.KEYCODE_2_ADDRESS] = mostRecentKeys[2] || 0;
Memory.ram[Memory.MOUSE_BUTTON_ADDRESS] = this.mouseDown ? 1 : 0;
Memory.ram[Memory.MOUSE_X_ADDRESS] = this.mouseX;
Memory.ram[Memory.MOUSE_Y_ADDRESS] = this.mouseY;
Memory.ram[Memory.MOUSE_PIXEL_ADDRESS] = Memory.VIDEO_MEMORY_START + (Math.floor(this.mouseY)) * Display.SCREEN_WIDTH + Math.floor(this.mouseX);
Memory.ram[Memory.RANDOM_NUMBER_ADDRESS] = Math.floor(Math.random() * 255);
Memory.ram[Memory.CURRENT_TIME_ADDRESS] = Date.now();
},
};
// 5.AUDIO
const Audio = {
WAVETYPES: {
'0': 'square',
'1': 'sawtooth',
'2': 'triangle',
'3': 'sine',
},
MAX_GAIN: 0.15,
audioCtx: new AudioContext(),
audioChannels: [],
addAudioChannel(wavetypeAddr, freqAddr, volAddr) {
const oscillatorNode = this.audioCtx.createOscillator();
const gainNode = this.audioCtx.createGain();
oscillatorNode.connect(gainNode);
gainNode.connect(this.audioCtx.destination);
const state = {
gain: 0,
oscillatorType: 'square',
frequency: 440,
};
gainNode.gain.value = state.gain;
oscillatorNode.type = state.oscillatorType;
oscillatorNode.frequency.value = state.frequency;
oscillatorNode.start();
return this.audioChannels.push({
state,
wavetypeAddr,
freqAddr,
volAddr,
gainNode,
oscillatorNode,
});
},
updateAudio() {
this.audioChannels.forEach(channel => {
const frequency = (Memory.ram[channel.freqAddr] || 0) / 1000;
const gain = !CPU.running ? 0 : (Memory.ram[channel.volAddr] || 0) / 100 * this.MAX_GAIN;
const oscillatorType = this.WAVETYPES[Memory.ram[channel.wavetypeAddr] || 0];
const {state} = channel;
if (state.gain !== gain) {
channel.gainNode.gain.setValueAtTime(gain, this.audioCtx.currentTime);
state.gain = gain;
}
if (state.oscillatorType !== oscillatorType) {
channel.oscillatorNode.type = oscillatorType;
state.oscillatorType = oscillatorType;
}
if (state.frequency !== frequency) {
channel.oscillatorNode.frequency.setValueAtTime(frequency, this.audioCtx.currentTime);
state.frequency = frequency;
}
});
},
init() {
this.addAudioChannel(
Memory.AUDIO_CH1_WAVETYPE_ADDRESS,
Memory.AUDIO_CH1_FREQUENCY_ADDRESS,
Memory.AUDIO_CH1_VOLUME_ADDRESS
);
this.addAudioChannel(
Memory.AUDIO_CH2_WAVETYPE_ADDRESS,
Memory.AUDIO_CH2_FREQUENCY_ADDRESS,
Memory.AUDIO_CH2_VOLUME_ADDRESS
);
this.addAudioChannel(
Memory.AUDIO_CH3_WAVETYPE_ADDRESS,
Memory.AUDIO_CH3_FREQUENCY_ADDRESS,
Memory.AUDIO_CH3_VOLUME_ADDRESS
);
},
};
// 6.ASSEMBLER
/*
We use a simple text-based language to input our program. This is our 'assembly
language'. We need to convert it into a form which is made up of only numerical
values so we can load it into our computer's Memory. This is a two step process:
1. parse program text into an array of objects representing our instructions and
their operands.
2. convert the objects into numeric values to be interpreted by the CPU. This is
our 'machine code'.
We parse the program text into tokens by splitting the text into lines, then
splitting those lines into tokens (words), which gives us to an instruction name
and operands for that instruction, from each line.
*/
const Assembler = {
// we'll keep a map of instructions which take a label as an operand so we
// know when to substitute an operand for the corresponding label address
instructionsLabelOperands: new Map(),
initInstructionsLabelOperands() {
Object.keys(CPU.instructions).forEach(name => {
const labelOperandIndex = CPU.instructions[name].operands.findIndex(operand =>
operand[1] === 'label'
);
if (labelOperandIndex > -1) {
this.instructionsLabelOperands.set(name, labelOperandIndex);
}
});
},
parseProgramText(programText) {
const programInstructions = [];
const lines = programText.split('\n');
for (let line of lines) {
const instruction = {name: '', operands: []};
let tokens = line.replace(/;.*$/, '') // strip comments
.split(' ');
for (let token of tokens) {
// skip empty tokens
if (token == null || token == "") {
continue;
}
// first token
if (!instruction.name) {
// special case for labels
if (token.endsWith(':')) {
instruction.name = 'label';
instruction.operands.push(token.slice(0, token.length - 1));
break;
}
instruction.name = token; // instruction name token
} else {
// handle text operands
if (
(
// define name
instruction.name === 'define' &&
instruction.operands.length === 0
) || (
// label used as operand
this.instructionsLabelOperands.get(instruction.name) === instruction.operands.length
)
) {
instruction.operands.push(token);
continue;
}
// try to parse number operands
const number = parseInt(token, 10);
if (Number.isNaN(number)) {
instruction.operands.push(token);
} else {
instruction.operands.push(number);
}
}
}
// validate number of operands given
if (
instruction.name &&
instruction.name !== 'label' &&
instruction.name !== 'data' &&
instruction.name !== 'define'
) {
const expectedOperands = CPU.instructions[instruction.name].operands;
if (instruction.operands.length !== expectedOperands.length) {
throw new Error(`Wrong number of operands for instruction ${instruction.name}
got ${instruction.operands.length}, expected ${expectedOperands.length}
at line '${line}'`
);
}
}
// if instruction was found on this line, add it to the program
if (instruction.name) {
programInstructions.push(instruction);
}
}
programInstructions.push({name: 'halt', operands: []});
return programInstructions;
},
/*
Having parsed our program text into an array of objects containing instruction
name and the operands to the instruction, we need to turn those objects into
numeric values we can store in the computer's memory, and load them in there.
*/
assembleAndLoadProgram(programInstructions) {
// 'label' is a special case – it's not really an instruction which the CPU
// understands. Instead, it's a marker for the location of the next
// instruction, which we can substitute for the actual location once we know
// the memory locations in the assembled program which the labels refer to.
const labelAddresses = {};
let labelAddress = Memory.PROGRAM_START;
for (let instruction of programInstructions) {
if (instruction.name === 'label') {
const labelName = instruction.operands[0];
labelAddresses[labelName] = labelAddress;
} else if (instruction.name === 'define') {
continue;
} else {
// advance labelAddress by the length of the instruction and its operands
labelAddress += 1 + instruction.operands.length;
}
}
const defines = {};
// load instructions and operands into memory
let loadingAddress = Memory.PROGRAM_START;
for (let instruction of programInstructions) {
if (instruction.name === 'label') {
continue;
}
if (instruction.name === 'define') {
defines[instruction.operands[0]] = instruction.operands[1];
continue;
}
if (instruction.name === 'data') {
for (var i = 0; i < instruction.operands.length; i++) {
Memory.ram[loadingAddress++] = instruction.operands[i];
}
continue;
}
// for each instruction, we first write the relevant opcode to memory
const opcode = CPU.instructionsToOpcodes.get(instruction.name);
if (!opcode) {
throw new Error(`No opcode found for instruction '${instruction.name}'`);
}
Memory.ram[loadingAddress++] = opcode;
// then, we write the operands for instruction to memory
const operands = instruction.operands.slice(0);
// replace labels used as operands with actual memory address
if (this.instructionsLabelOperands.has(instruction.name)) {
const labelOperandIndex = this.instructionsLabelOperands.get(instruction.name);
if (typeof labelOperandIndex !== 'number') throw new Error('expected number');
const labelName = instruction.operands[labelOperandIndex];
const labelAddress = labelAddresses[labelName];
if (!labelAddress) {
throw new Error(`unknown label '${labelName}'`);
}
operands[labelOperandIndex] = labelAddress;
}
for (var i = 0; i < operands.length; i++) {
let value = null;
if (typeof operands[i] === 'string') {
if (operands[i] in defines) {
value = defines[operands[i]];
} else {
throw new Error(`'${operands[i]}' not defined`);
}
} else {
value = operands[i];
}
Memory.ram[loadingAddress++] = value;
}
}
},
init() {
this.initInstructionsLabelOperands();
}
};
// 7.SIMULATION CONTROL
const Simulation = {
CYCLES_PER_YIELD: 997,
delayBetweenCycles: 0,
loop() {
if (Simulation.delayBetweenCycles === 0) {
// running full speed, execute a bunch of instructions before yielding
// to the JS event loop, to achieve decent 'real time' execution speed
for (var i = 0; i < Simulation.CYCLES_PER_YIELD; i++) {
if (!CPU.running) {
Simulation.stop();
break;
}
CPU.step();
}
} else {
// run only one execution before yielding to the JS event loop so screen
// and UI changes can be shown, and new mouse and keyboard input taken
CPU.step();
SimulatorUI.updateUI();
}
Simulation.updateOutputs();
if (CPU.running) {
setTimeout(Simulation.loop, Simulation.delayBetweenCycles);
}
},
run() {
CPU.running = true;
SimulatorUI.updateUI();
SimulatorUI.updateSpeedUI();
this.loop();
},
stop() {
CPU.running = false;
SimulatorUI.updateUI();
SimulatorUI.updateSpeedUI();
},
updateOutputs() {