-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathchip8.rs
1029 lines (862 loc) · 32.1 KB
/
chip8.rs
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
#![allow(non_snake_case)]
#![allow(unused_parens)]
#![allow(dead_code)]
use rand::Rng;
use std::{convert::TryFrom, ops::ShlAssign};
use std::fs::File;
use std::io::prelude::*;
use std::convert::TryInto;
use std::path::PathBuf;
use std::ops::ShrAssign;
use std::{thread, time};
use function_name::named;
/// General chip 8 struct
pub struct Chip8 {
registers: [u8; 16],
memory: [u8; 4096],
index_register: u16,
program_counter: u16,
stack: [u16; 16],
stack_pointer: u8,
delay_timer: u8,
sound_timer: u8,
keypad: [u8; 16],
pub video: [u32; 64 * 32],
op_code: u16,
table: [fn(&mut Chip8); 0xF+1],
table0: [fn(&mut Chip8); 0xE+1],
table8: [fn(&mut Chip8); 0xE+1],
tableE: [fn(&mut Chip8); 0xE+1],
tableF: [fn(&mut Chip8); 0x65+1],
debug_mode: bool,
}
impl Chip8 {
/// Create a new chip8 instance with an empty `rom`, ready for use
///
/// # Example:
///
/// ```
/// let mut chip8: Chip8 = Chip8::new();
///
/// chip.load_rom(path);
///
/// let rom: PathBuf = '...';
/// let speed: u64 = 30;
///
/// loop {
///
/// chip8.Cycle();
/// chip8.pretty_print_video(rom);
/// thread::sleep(time::Duration::from_millis(speed);
/// }
/// ```
///
/// ## Values
///
/// * `registers`: all zeroes
/// * `memory`/`rom`: all zeroes
/// * `index_register`: 0
/// * `program_counter`: 0x200
/// * `stack`: all zeroes
/// * `stack_poionter`: 0
/// * `delay_timer`: 0
/// * `sound_timer`: 0
/// * `keypad`: all zeroes
/// * `video`: all zeroes
/// * `op_code`: 0
/// * `fontset_size`: 80
pub fn new() -> Self {
let mut chip8: Chip8 = Chip8 {
registers: [0; 16],
memory: [0; 4096],
index_register: 0,
program_counter: 0x200,
stack: [0; 16],
stack_pointer: 0,
delay_timer: 0,
sound_timer: 0,
keypad: [0; 16],
video: [0; 2048],
op_code: 0,
table: [Chip8::OP_ERR; 0xF+1],
table0: [Chip8::OP_ERR; 0xE+1],
table8: [Chip8::OP_ERR; 0xE+1],
tableE: [Chip8::OP_ERR; 0xE+1],
tableF: [Chip8::OP_ERR; 0x65+1],
debug_mode: false,
};
chip8.load_fonts();
chip8.add_table();
return chip8;
}
/// Runs the CHIP8 Machine forever with the currently loaded ROM.
/// The clock speed is determined by the passed in `speed` parameter.
///
/// ```
/// loop {
/// self.Cycle();
/// self.pretty_print_video();
/// thread::sleep(cycle_wait_time);
/// }
/// ```
pub fn play(&mut self, speed: u64) {
let cycle_wait_time = time::Duration::from_millis(speed);
loop {
self.Cycle();
self.pretty_print_video();
thread::sleep(cycle_wait_time);
}
}
/// Adds the correct function pointer tables to the newly created Chip8 object
pub fn add_table(&mut self) {
if (self.debug_mode) {
eprintln!("Loading tables");
}
let table: [fn(&mut Chip8); 0xF+1] = [
Chip8::Table0,
Chip8::OP_1nnn,
Chip8::OP_2nnn,
Chip8::OP_3xkk,
Chip8::OP_4xkk,
Chip8::OP_5xy0,
Chip8::OP_6xkk,
Chip8::OP_7xkk,
Chip8::Table8,
Chip8::OP_9xy0,
Chip8::OP_Annn,
Chip8::OP_Bnnn,
Chip8::OP_Cxkk,
Chip8::OP_Dxyn,
Chip8::TableE,
Chip8::TableF
];
// Chip8::OP_ERR here is just a placeholder, technically the array is already filled with
// OP_ERR
let mut table0: [fn(&mut Chip8); 0xE+1] = [Chip8::OP_ERR; 0xE+1];
let mut table8: [fn(&mut Chip8); 0xE+1] = [Chip8::OP_ERR; 0xE+1];
let mut tableE: [fn(&mut Chip8); 0xE+1] = [Chip8::OP_ERR; 0xE+1];
let mut tableF: [fn(&mut Chip8); 0x65+1] = [Chip8::OP_ERR; 0x65+1];
table0[0x0] = Chip8::OP_00E0;
table0[0xE] = Chip8::OP_00EE;
table8[0x0] = Chip8::OP_8xy0;
table8[0x1] = Chip8::OP_8xy1;
table8[0x2] = Chip8::OP_8xy2;
table8[0x3] = Chip8::OP_8xy3;
table8[0x4] = Chip8::OP_8xy4;
table8[0x5] = Chip8::OP_8xy5;
table8[0x6] = Chip8::OP_8xy6;
table8[0x7] = Chip8::OP_8xy7;
table8[0xE] = Chip8::OP_8xyE;
tableE[0x1] = Chip8::OP_ExA1;
tableE[0xE] = Chip8::OP_Ex9E;
tableF[0x07] = Chip8::OP_Fx07;
tableF[0x0A] = Chip8::OP_Fx0A;
tableF[0x15] = Chip8::OP_Fx15;
tableF[0x18] = Chip8::OP_Fx18;
tableF[0x1E] = Chip8::OP_Fx1E;
tableF[0x29] = Chip8::OP_Fx29;
tableF[0x33] = Chip8::OP_Fx33;
tableF[0x55] = Chip8::OP_Fx55;
tableF[0x65] = Chip8::OP_Fx65;
// Apply the newly generated tables
self.table = table;
self.table0 = table0;
self.table8 = table8;
self.tableE = tableE;
self.tableF = tableF;
if (self.debug_mode) {
eprintln!("Tables loaded");
}
}
/// Toggle debug mode for current chip8 instance
pub fn debug(&mut self) {
// bitwise xor
self.debug_mode ^= true;
eprintln!("Debug mode activated");
}
/// Loads a given rom into memory, starting from memory address 0x200
pub fn load_rom(&mut self, path: PathBuf) {
if (self.debug_mode) {
eprintln!("Loading ROM: {:?}", &path);
}
// memory addres before this are reserved
let start_address = 0x200;
// open rom file
let file: File = File::open(path).expect("Error opening rom file");
// buffer to store bytes in
let mut buf: Vec<u8> = Vec::new();
// read the bytes from file
for byte in file.bytes() {
let byte = match byte {
Ok(byte) => byte,
Err(error) => panic!("Provided rom is not a valid binary. {:?}", error),
};
buf.push(byte);
}
// println!("{:x?}", buf);
// load the buffer into the chip 8 memory
for i in 0..buf.len() {
self.memory[start_address + i] = buf[i];
}
if (self.debug_mode) {
eprintln!("ROM Loaded");
}
}
/// Returns `byte_number` amount of bytes after the `pointer` in rom
pub fn dump_rom(&self, start_address: usize, byte_number: usize) -> Vec<u8> {
let mut rom: Vec<u8> = Vec::new();
// for each memory address after the pointer add that address to the buffer, then return the buffer
for i in start_address..start_address + byte_number {
rom.push(self.memory[i]);
}
return rom;
}
pub fn dump_video(&mut self) -> Vec<u32> {
let mut buf: Vec<u32> = Vec::new();
for i in 0..self.video.len() {
buf.push(self.video[i]);
}
return buf;
}
pub fn pretty_print_video(&mut self) {
// █ &(0xFFFFFFFF as u32)
//print!("\x1B[2J\x1B[1;1H");
print!("\x1B[2J\x1B[1;1H");
let mut new_vec = self.video.iter().peekable();
let mut rows: Vec<Vec<_>> = vec![];
while new_vec.peek().is_some() {
let chunk: Vec<_> = new_vec.by_ref().take(64).collect();
rows.push(chunk);
}
for row in rows {
let mut current_row = "".to_string();
for pixel in row {
if (pixel == &(0xFFFFFFFF as u32)) {
current_row.push('█');
} else {
current_row.push(' ');
}
}
println!("{}", current_row);
}
}
/// Load the fontset into memory
fn load_fonts(&mut self) {
let fontset: [u8; 80] = [
0xF0, 0x90, 0x90, 0x90, 0xF0, // 0
0x20, 0x60, 0x20, 0x20, 0x70, // 1
0xF0, 0x10, 0xF0, 0x80, 0xF0, // 2
0xF0, 0x10, 0xF0, 0x10, 0xF0, // 3
0x90, 0x90, 0xF0, 0x10, 0x10, // 4
0xF0, 0x80, 0xF0, 0x10, 0xF0, // 5
0xF0, 0x80, 0xF0, 0x90, 0xF0, // 6
0xF0, 0x10, 0x20, 0x40, 0x40, // 7
0xF0, 0x90, 0xF0, 0x90, 0xF0, // 8
0xF0, 0x90, 0xF0, 0x10, 0xF0, // 9
0xF0, 0x90, 0xF0, 0x90, 0x90, // A
0xE0, 0x90, 0xE0, 0x90, 0xE0, // B
0xF0, 0x80, 0x80, 0x80, 0xF0, // C
0xE0, 0x90, 0x90, 0x90, 0xE0, // D
0xF0, 0x80, 0xF0, 0x80, 0xF0, // E
0xF0, 0x80, 0xF0, 0x80, 0x80, // F];
];
let fontset_start_address = 0x50;
if (self.debug_mode) {
eprintln!("Loading fontset");
}
for i in 0..fontset.len() {
self.memory[fontset_start_address + i as usize] = fontset[i as usize];
}
if (self.debug_mode) {
eprintln!("Fontset loaded");
}
}
/// Generate a random byte(0, 255)
pub fn rand_byte(&self) -> u8 {
let mut rng = rand::thread_rng();
return rng.gen_range(0, 255);
}
//
//
// From Now On I will define all `opcodes`, taken from here:
//
// https://austinmorlan.com/posts/chip8_emulator/
//
//
/// OPCODE 00E0 - Clear Screen
#[named]
pub fn OP_00E0(&mut self) {
// set video buffer to zero
self.video = [0; 2048];
if self.debug_mode {
eprintln!("Ran opcode: {}", function_name!());
}
}
/// OPCODE 00EE - Return from subroutine
#[named]
fn OP_00EE(&mut self) {
self.stack_pointer = self.stack_pointer - 1;
self.program_counter = self.stack[self.stack_pointer as usize];
if self.debug_mode {
eprintln!("Ran opcode: {}", function_name!());
}
}
/// OPCODE 1NNN - Jump to location NNN(set program counter to nnn)
#[named]
fn OP_1nnn(&mut self) {
// using 0x0FFF I can take the NNN from the opcode while leaving the one
let address: u16 = self.op_code & 0x0FFF;
self.program_counter = address;
if self.debug_mode {
eprintln!("Ran opcode: {}", function_name!());
}
}
/// OPCODE 2NNN - Call subroutine at location NNN
#[named]
fn OP_2nnn(&mut self) {
let address: u16 = self.op_code & 0x0FFF;
self.stack[self.stack_pointer as usize] = self.program_counter;
self.stack_pointer = self.stack_pointer + 1;
self.program_counter = address;
if self.debug_mode {
eprintln!("Ran opcode: {}", function_name!());
}
}
/// OPCODE 3XKK - Skip next instruction if Vx = kk
/// Since our PC has already been incremented by 2 in Cycle(), we can just increment by 2 again to skip the next instruction.
#[named]
fn OP_3xkk(&mut self) {
let Vx: u8 = (self.op_code & 0x0F00).checked_shr(8).unwrap_or(0).try_into().unwrap();
let byte: u16 = self.op_code & 0x00FF;
let byte: u8 = match u8::try_from(byte) {
Ok(number) => number,
Err(error) => panic!(
"Could not turn u16 into u8 in OPCODE: 3XKK. Error: {}",
error
),
};
if self.registers[Vx as usize] == byte {
self.program_counter += 2;
}
if self.debug_mode {
eprintln!("Ran opcode: {}", function_name!());
}
}
/// OPCODE 4XKK - Skip next instruction if Vx != kk
#[named]
fn OP_4xkk(&mut self) {
let Vx: u8 = (self.op_code & 0x0F00).checked_shr(8).unwrap_or(0).try_into().unwrap();
let byte: u16 = self.op_code & 0x00FF;
let byte: u8 = match u8::try_from(byte) {
Ok(number) => number,
Err(error) => panic!(
"Could not turn u16 into u8 in OPCODE: 3XKK. Error: {}",
error
),
};
// this != is the onlh difference from the function above
if self.registers[Vx as usize] != byte {
self.program_counter += 2;
}
if self.debug_mode {
eprintln!("Ran opcode: {}", function_name!());
}
}
/// OPCODE 5XY0 - Skip next instruction if Vx = Vy.
#[named]
fn OP_5xy0(&mut self) {
let Vx: u8 = (self.op_code & 0x0F00).checked_shr(8).unwrap_or(0).try_into().unwrap();
let Vy: u16 = (self.op_code & 0x00F0).checked_shr(4).unwrap_or(0);
if self.registers[Vx as usize] == self.registers[Vy as usize] {
self.program_counter += 2;
}
if self.debug_mode {
eprintln!("Ran opcode: {}", function_name!());
}
}
/// OPCODE 6XKK - Set Vx = kk.
#[named]
fn OP_6xkk(&mut self) {
let Vx: u8 = (self.op_code & 0x0F00).checked_shr(8).unwrap_or(0).try_into().unwrap();
let byte: u16 = self.op_code & 0x00FF;
let byte: u8 = match u8::try_from(byte) {
Ok(number) => number,
Err(error) => panic!(
"Could not turn u16 into u8 in OPCODE 6XKK. Error: {}",
error
),
};
self.registers[Vx as usize] = byte;
if self.debug_mode {
eprintln!("Ran opcode: {}", function_name!());
}
}
/// OPCODE 7XKK - Set Vx = Vx + kk.
#[named]
fn OP_7xkk(&mut self) {
let Vx: u8 = (self.op_code & 0x0F00).checked_shr(8).unwrap_or(0).try_into().unwrap();
let byte: u8 = (self.op_code as u8) & 0x00FF;
self.registers[Vx as usize] = (((self.registers[Vx as usize] as u16) + byte as u16) % 256) as u8;
if self.debug_mode {
eprintln!("Ran opcode: {}", function_name!());
}
}
/// OPCODE 8XY0 - Set Vx = Vy.
#[named]
fn OP_8xy0(&mut self) {
let Vx: u8 = (self.op_code & 0x0F00).checked_shr(8).unwrap_or(0).try_into().unwrap();
let Vy: u16 = (self.op_code & 0x00F0).checked_shr(4).unwrap_or(0);
self.registers[Vx as usize] = self.registers[Vy as usize];
if self.debug_mode {
eprintln!("Ran opcode: {}", function_name!());
}
}
/// OPCODE 8XY1 - Set Vx = Vx OR Vy.
#[named]
fn OP_8xy1(&mut self) {
let Vx: u8 = (self.op_code & 0x0F00).checked_shr(8).unwrap_or(0).try_into().unwrap();
let Vy: u16 = (self.op_code & 0x00F0).checked_shr(4).unwrap_or(0);
self.registers[Vx as usize] |= self.registers[Vy as usize];
if self.debug_mode {
eprintln!("Ran opcode: {}", function_name!());
}
}
/// OPCODE 8XY2 - Set Vx = Vx AND Vy
#[named]
fn OP_8xy2(&mut self) {
let Vx: u8 = (self.op_code & 0x0F00).checked_shr(8).unwrap_or(0).try_into().unwrap();
let Vy: u16 = (self.op_code & 0x00F0).checked_shr(4).unwrap_or(0);
self.registers[Vx as usize] &= self.registers[Vy as usize];
if self.debug_mode {
eprintln!("Ran opcode: {}", function_name!());
}
}
/// OPCODE 8XY3 - Set Vx = Vx XOR Vy
#[named]
fn OP_8xy3(&mut self) {
let Vx: u8 = (self.op_code & 0x0F00).checked_shr(8).unwrap_or(0).try_into().unwrap();
let Vy: u16 = (self.op_code & 0x00F0).checked_shr(4).unwrap_or(0);
self.registers[Vx as usize] ^= self.registers[Vy as usize];
if self.debug_mode {
eprintln!("Ran opcode: {}", function_name!());
}
}
/// OPCODE 8XY4 - Set Vx = Vx + Vy, set VF = carry.
/// The values of Vx and Vy are added together. If the result is greater than 8 bits (i.e., > 255,) VF is set to 1, otherwise 0. Only the lowest 8 bits of the result are kept, and stored in Vx.
#[named]
fn OP_8xy4(&mut self) {
let Vx: u8 = (self.op_code & 0x0F00).checked_shr(8).unwrap_or(0).try_into().unwrap();
let Vy: u16 = (self.op_code & 0x00F0).checked_shr(4).unwrap_or(0);
let sum: u16 = self.registers[Vx as usize] as u16 + self.registers[Vy as usize] as u16;
if sum > 255 {
self.registers[0xF] = 1;
} else {
self.registers[0xF] = 0;
}
self.registers[Vx as usize] = (sum & 0xFF) as u8;
if self.debug_mode {
eprintln!("Ran opcode: {}", function_name!());
}
}
/// OPCODE 8XY5 - Set Vx = Vx - Vy, set VF = NOT borrow.
/// If Vx > Vy, then VF is set to 1, otherwise 0. Then Vy is subtracted from Vx, and the results stored in Vx.
#[named]
fn OP_8xy5(&mut self) {
let Vx: u8 = (self.op_code & 0x0F00).checked_shr(8).unwrap_or(0).try_into().unwrap();
let Vy: u16 = (self.op_code & 0x00F0).checked_shr(4).unwrap_or(0);
if self.registers[Vx as usize] > self.registers[Vy as usize] {
self.registers[0xF] = 1;
} else {
self.registers[0xF] = 0;
}
self.registers[Vx as usize] = self.registers[Vx as usize].wrapping_sub(self.registers[Vy as usize]);
if self.debug_mode {
eprintln!("Ran opcode: {}", function_name!());
}
}
/// OPCODE 8XY6 - Set Vx = Vx SHR 1.
/// If the least-significant bit of Vx is 1, then VF is set to 1, otherwise 0. Then Vx is divided by 2.
#[named]
fn OP_8xy6(&mut self) {
let Vx: u8 = (self.op_code & 0x0F00).checked_shr(8).unwrap_or(0).try_into().unwrap();
// Save LSB in VF
self.registers[0xF] = self.registers[Vx as usize] & 0x1;
self.registers[Vx as usize].shr_assign(1);
if self.debug_mode {
eprintln!("Ran opcode: {}", function_name!());
}
}
/// OPCODE 8XY7 - SUBN Vx, Vy
/// If Vy > Vx, then VF is set to 1, otherwise 0. Then Vx is subtracted from Vy, and the results stored in Vx.
#[named]
fn OP_8xy7(&mut self) {
let Vx: u8 = (self.op_code & 0x0F00).checked_shr(8).unwrap_or(0).try_into().unwrap();
let Vy: u16 = (self.op_code & 0x00F0).checked_shr(4).unwrap_or(0);
if self.registers[Vy as usize] > self.registers[Vx as usize] {
self.registers[0xF] = 1;
} else {
self.registers[0xF] = 0;
}
//self.registers[Vx as usize] = self.registers[Vy as usize] - self.registers[Vx as usize];
self.registers[Vx as usize] = self.registers[Vy as usize].wrapping_sub(self.registers[Vx as usize]);
if self.debug_mode {
eprintln!("Ran opcode: {}", function_name!());
}
}
/// OPCODE 8XYE - Set Vx = Vx SHL 1.
/// If the most-significant bit of Vx is 1, then VF is set to 1, otherwise to 0. Then Vx is multiplied by 2.
#[named]
fn OP_8xyE(&mut self) {
let Vx: u8 = (self.op_code & 0x0F00).checked_shr(8).unwrap_or(0).try_into().unwrap();
// save MSB in VF
self.registers[0xF] = (self.registers[Vx as usize] & 0x80).checked_shr(7).unwrap_or(0);
self.registers[Vx as usize].shl_assign(1);
if self.debug_mode {
eprintln!("Ran opcode: {}", function_name!());
}
}
/// OPCODE 9XY0 - Skip next instruction if Vx != Vy
#[named]
fn OP_9xy0(&mut self) {
let Vx: u8 = (self.op_code & 0x0F00).checked_shr(8).unwrap_or(0).try_into().unwrap();
let Vy: u16 = (self.op_code & 0x00F0).checked_shr(4).unwrap_or(0);
if self.registers[Vx as usize] != self.registers[Vy as usize] {
self.program_counter += 2;
}
if self.debug_mode {
eprintln!("Ran opcode: {}", function_name!());
}
}
/// OPCODE ANNN - set I = nnn
#[named]
fn OP_Annn(&mut self) {
let address: u16 = self.op_code & 0x0FFF;
self.index_register = address;
if self.debug_mode {
eprintln!("Ran opcode: {}", function_name!());
}
}
/// OPCODE BNNN - Jump to location nnn + V0
#[named]
fn OP_Bnnn(&mut self) {
let address: u16 = self.op_code & 0x0FFF;
self.program_counter = self.registers[0] as u16 + address;
if self.debug_mode {
eprintln!("Ran opcode: {}", function_name!());
}
}
/// OPCODE CXKK - Set Vx = random byte AND kk.
#[named]
fn OP_Cxkk(&mut self) {
let Vx: u8 = (self.op_code & 0x0F00).checked_shr(8).unwrap_or(0).try_into().unwrap();
let byte: u16 = self.op_code & 0x00FF;
let byte: u8 = match u8::try_from(byte) {
Ok(number) => number,
Err(error) => panic!(
"Could not turn u16 into u8 in OPCODE CXKK. Error: {}",
error
),
};
self.registers[Vx as usize] = self.rand_byte() & byte;
if self.debug_mode {
eprintln!("Ran opcode: {}", function_name!());
}
}
/// OPCODE DXYN - Display n-byte sprite starting at memory location I at (Vx, Vy), set VF = collision.
#[named]
fn OP_Dxyn(&mut self) {
let Vx: u8 = (self.op_code & 0x0F00).checked_shr(8).unwrap_or(0).try_into().unwrap();
let Vy = (self.op_code & 0x00F0).checked_shr(4).unwrap_or(0);
let height = self.op_code & 0x000F;
let VIDEO_WIDTH: u8 = 64;
let VIDEO_HEIGHT: u8 = 32;
// wrap if going over boundaries
let x_pos: u8 = self.registers[Vx as usize] % VIDEO_WIDTH;
let y_pos: u8 = self.registers[Vy as usize] % VIDEO_HEIGHT;
self.registers[0xF] = 0;
for row in 0..height {
let sprite_byte: u8 = self.memory[(self.index_register + row) as usize];
for col in 0..8 {
let sprite_pixel = sprite_byte & ((0x80 as u16).checked_shr(col as u32).unwrap_or(0) as u8);
// casting without error checking here is fine because col and raw wil alwyays be lower than 255(they are 64 and 32)
//let mut screen_pixel = self.video[(((y_pos as u16 + row) * (VIDEO_WIDTH as u16) + (x_pos as u16) + col)) as usize];
// old:
//
// ```
// let video_index = ((y_pos as u16 + row) * (VIDEO_WIDTH as u16) + (x_pos as u16) + col) as usize;
// ```
//
// new:
let video_index = ((y_pos as u16).wrapping_add(row) * (VIDEO_WIDTH as u16))
.wrapping_add(x_pos as u16)
.wrapping_add(col) as usize;
// sprite pixel is on
if sprite_pixel != 0 {
// screen pixel also on - collision
if self.video[video_index] == 0xFFFFFFFF {
self.registers[0xF] = 1;
}
// Effectively XOR with the sprite pixel
self.video[video_index] ^= 0xFFFFFFFF;
}
}
}
if self.debug_mode {
eprintln!("Ran opcode: {}", function_name!());
}
}
/// OPCODE EX9E - Skip next instruction if key with the value of Vx is pressed.
#[named]
fn OP_Ex9E(&mut self) {
let Vx: u8 = (self.op_code & 0x0F00).checked_shr(8).unwrap_or(0).try_into().unwrap();
let key: u8 = self.registers[Vx as usize];
if self.keypad[key as usize] != 0 {
self.program_counter += 2;
}
if self.debug_mode {
eprintln!("Ran opcode: {}", function_name!());
}
}
/// OPCODE EXA1 - Skip next instruction if key with the value of Vx is not pressed
#[named]
fn OP_ExA1(&mut self) {
let Vx: u8 = (self.op_code & 0x0F00).checked_shr(8).unwrap_or(0).try_into().unwrap();
let key: u8 = self.registers[Vx as usize];
if self.keypad[key as usize] == 0 {
self.program_counter += 2;
}
if self.debug_mode {
eprintln!("Ran opcode: {}", function_name!());
}
}
/// OPCODE FX07 - Set Vx = delay timer value
#[named]
fn OP_Fx07(&mut self) {
let Vx: u8 = (self.op_code & 0x0F00).checked_shr(8).unwrap_or(0).try_into().unwrap();
self.registers[Vx as usize] = self.delay_timer;
if self.debug_mode {
eprintln!("Ran opcode: {}", function_name!());
}
}
/// OPCODE FX0A - Wait for a key press, store the value of the key in Vx.
#[named]
fn OP_Fx0A(&mut self) {
let Vx: u8 = (self.op_code & 0x0F00).checked_shr(8).unwrap_or(0).try_into().unwrap();
if self.keypad[0] != 0 {
self.registers[Vx as usize] = 0;
} else if self.keypad[1] != 0 {
self.registers[Vx as usize] = 1;
} else if self.keypad[2] != 0 {
self.registers[Vx as usize] = 2;
} else if self.keypad[3] != 0 {
self.registers[Vx as usize] = 3;
} else if self.keypad[4] != 0 {
self.registers[Vx as usize] = 4;
} else if self.keypad[5] != 0 {
self.registers[Vx as usize] = 5;
} else if self.keypad[6] != 0 {
self.registers[Vx as usize] = 6;
} else if self.keypad[7] != 0 {
self.registers[Vx as usize] = 7;
} else if self.keypad[8] != 0 {
self.registers[Vx as usize] = 8;
} else if self.keypad[9] != 0 {
self.registers[Vx as usize] = 9;
} else if self.keypad[10] != 0 {
self.registers[Vx as usize] = 10;
} else if self.keypad[11] != 0 {
self.registers[Vx as usize] = 11;
} else if self.keypad[12] != 0 {
self.registers[Vx as usize] = 12;
} else if self.keypad[13] != 0 {
self.registers[Vx as usize] = 13;
} else if self.keypad[14] != 0 {
self.registers[Vx as usize] = 14;
} else if self.keypad[15] != 0 {
self.registers[Vx as usize] = 15;
} else {
self.program_counter -= 2;
}
if self.debug_mode {
eprintln!("Ran opcode: {}", function_name!());
}
}
/// OPCODE FX15 - Set delay timer = Vx.
#[named]
fn OP_Fx15(&mut self) {
let Vx: u8 = (self.op_code & 0x0F00).checked_shr(8).unwrap_or(0).try_into().unwrap();
self.delay_timer = self.registers[Vx as usize];
if self.debug_mode {
eprintln!("Ran opcode: {}", function_name!());
}
}
/// OPCODE FX18 - Set sound timer = Vx.
#[named]
fn OP_Fx18(&mut self) {
let Vx: u8 = (self.op_code & 0x0F00).checked_shr(8).unwrap_or(0).try_into().unwrap();
self.sound_timer = self.registers[Vx as usize];
if self.debug_mode {
eprintln!("Ran opcode: {}", function_name!());
}
}
/// OPCODE FX1E - Set I = I + Vx.
#[named]
fn OP_Fx1E(&mut self) {
let Vx: u8 = (self.op_code & 0x0F00).checked_shr(8).unwrap_or(0).try_into().unwrap();
self.index_register += self.registers[Vx as usize] as u16;
if self.debug_mode {
eprintln!("Ran opcode: {}", function_name!());
}
}
/// OPCODE FX29 - Set I = location of sprite for digit Vx.
#[named]
fn OP_Fx29(&mut self) {
// TODO this Vx has to stay u16 bc I have to cast it either way back into index register
let Vx: u16 = (self.op_code & 0x0F00).checked_shr(8).unwrap_or(0);
let digit = self.registers[Vx as usize];
let fontset_start_address = 0x50;
self.index_register = (fontset_start_address + (5*digit)) as u16;
if self.debug_mode {
eprintln!("Ran opcode: {}", function_name!());
}
}
/// OPCODE FX33 - Store BCD representation of Vx in memory locations I, I+1, and I+2.
/// The interpreter takes the decimal value of Vx, and places the hundreds digit in memory at location in I, the tens digit at location I+1, and the ones digit at location I+2.
#[named]
fn OP_Fx33(&mut self) {
let Vx: u8 = (self.op_code & 0x0F00).checked_shr(8).unwrap_or(0).try_into().unwrap();
let mut value: u8 = self.registers[Vx as usize];
// ones place
self.memory[(self.index_register + 2) as usize] = value % 10;
value /= 10;
// tens place
self.memory[(self.index_register + 1) as usize] = value % 10;
value /= 10;
// hundreds place
self.memory[self.index_register as usize] = value % 10;
if self.debug_mode {
eprintln!("Ran opcode: {}", function_name!());
}
}
/// OPCODE FX55 -- Store registers V0 to VX in memory starting at location X
#[named]
fn OP_Fx55(&mut self) {
// TODO: this has to stay a u16 bc it needs to get added into index register
let Vx: u16 = (self.op_code & 0x0F00).checked_shr(8).unwrap_or(0);
for i in 0..(Vx +1) {
self.memory[(self.index_register + i) as usize] = self.registers[i as usize];
}
if self.debug_mode {
eprintln!("Ran opcode: {}", function_name!());
}
}
/// OPCODE FX65 - Read registers V0 through Vx from memory starting at location I.
#[named]
fn OP_Fx65(&mut self) {
// TODO: has to stay u16, bc we need to recast it anyways
let Vx: u16 = (self.op_code & 0x0F00).checked_shr(8).unwrap_or(0).try_into().unwrap();
for i in 0..(Vx +1) {
self.registers[i as usize] = self.memory[(self.index_register + i) as usize];
}
if self.debug_mode {
eprintln!("Ran opcode: {}", function_name!());
}
}
/// Fallback OPCODE
#[named]
fn OP_ERR(&mut self) {
eprintln!("[ERROR]: Opcode {} not valid", self.op_code);
if self.debug_mode {
eprintln!("Ran opcode: {}", function_name!());
}
}
#[named]
fn Table0(&mut self) {
if self.debug_mode {
eprintln!("Running table: {}", function_name!());
}
self.table0[(self.op_code & 0x000F) as usize](self);
}
#[named]
fn Table8(&mut self) {
if self.debug_mode {
eprintln!("Running table: {}", function_name!());
}
self.table8[(self.op_code & 0x000F) as usize](self);
}
#[named]
fn TableE(&mut self) {
if self.debug_mode {
eprintln!("Running table: {}", function_name!());
}
self.tableE[(self.op_code & 0x000F) as usize](self);
}
#[named]
fn TableF(&mut self) {
if self.debug_mode {
eprintln!("Running table: {}", function_name!());
}
self.tableF[(self.op_code & 0x00FF) as usize](self);
}
// the opcodes are stored in memory starting from index 512, i need to decode them and map each opcode to one of my functions
// The CHIP-8 Architecture uses big-endian (0x00 0xe0 -> 0x00e0)
pub fn Cycle(&mut self) {
// Fetch opcode
//let _: () = self.memory[self.program_counter as usize].checked_shl(8).unwrap_or(0);
self.op_code = ((self.memory[self.program_counter as usize] as u16).checked_shl(8).unwrap_or(0)) | self.memory[(self.program_counter + 1) as usize] as u16;
if (self.debug_mode) {
eprintln!("Opcode: {}", &self.op_code);
}
// increment pc before we do anything
self.program_counter += 2;
// decode and execute
self.table[((self.op_code & 0xF000).checked_shr(12).unwrap_or(0)) as usize](self);
// Decrement delay timer if it exists
if (self.delay_timer > 0) {
self.delay_timer -= 1;
}
// Decrement sound timer if it exists
if (self.sound_timer > 0) {
self.sound_timer -= 1;
}
}
}
/*
*
* UNIT TESTS
*
*/
#[cfg(test)]
mod tests {
use crate::Chip8;
#[test]
fn add_two() {
assert_eq!(2, 1 +1);
}
#[test]
fn check_fontset() {