oboy/src/cpu.ml

69 lines
1.7 KiB
OCaml

open Printf
(** http://bgb.bircd.org/pandocs.htm#cpuregistersandflags
http://gameboy.mongenel.com/dmg/lesson1.html *)
type registers = {
mutable a : char; (* accumulator *)
mutable f : char; (* flags *)
mutable b : char;
mutable c : char;
mutable d : char;
mutable e : char;
mutable h : char;
mutable l : char;
mutable sp : int; (* stack pointer *)
mutable pc : int; (* program counter *)
}
(* type flags = {
z : bool; (* zero *)
n : bool; (* substraction *)
h : bool; (* half-carry *)
cy : bool; (* carry *)
} *)
type t = {
reg : registers;
mutable cycles : int;
}
(** http://bgb.bircd.org/pandocs.htm#powerupsequence *)
let init_registers =
{
a = '\x00';
f = '\x00';
b = '\x00';
c = '\x00';
d = '\x00';
e = '\x00';
h = '\x00';
l = '\x00';
sp = 0xFFFE;
pc = 0x0100;
}
let init_cpu =
{ reg = init_registers; cycles = 0 }
let inc_pc cpu count =
cpu.reg.pc <- cpu.reg.pc + count
let inc_cycles cpu count =
cpu.cycles <- cpu.cycles + count
let read_2B b addr =
let low = Bytes.get b addr in
let high = Bytes.get b (addr + 1) in
(int_of_char high) * 256 + (int_of_char low)
(** http://imrannazar.com/GameBoy-Z80-Opcode-Map *)
let run cpu (cartridge: Cartridge.t) =
(* Hexa.print_slice cartridge.full_rom cpu.reg.pc (cpu.reg.pc + 7) ~width:16; *)
match Bytes.get cartridge.full_rom cpu.reg.pc with
| '\x00' -> printf " nop\n"; inc_pc cpu 1; inc_cycles cpu 4
| '\xC3' -> let addr = read_2B cartridge.full_rom (cpu.reg.pc + 1) in
printf " jp 0x%02x\n" addr; cpu.reg.pc <- addr; inc_cycles cpu 16
| _ as x -> eprintf "OpCode %02X\n" (int_of_char x); failwith "Unimplemented opcode."