gb-emu/src/main.rs
2023-02-07 09:12:39 +11:00

247 lines
5.6 KiB
Rust

#![feature(exclusive_range_pattern)]
mod processor;
use clap::{ArgGroup, Parser};
use minifb::{Window, WindowOptions};
use processor::{
memory::{Memory, ROM},
Registers, CPU,
};
use std::{
fs,
io::{self, stdout, Write},
sync::RwLock,
};
#[macro_export]
macro_rules! verbose_println {
($($tts:tt)*) => {
if crate::is_verbose() {
println!($($tts)*);
}
};
}
#[macro_export]
macro_rules! verbose_print {
($($tts:tt)*) => {
if crate::is_verbose() {
print!($($tts)*);
}
};
}
/// Simple program to greet a person
#[derive(Parser, Debug)]
#[command(author, version, about, long_about = None)]
#[command(group(ArgGroup::new("prints").args(["verbose","cycle_count"])))]
struct Args {
/// ROM path
#[arg(short, long)]
rom: String,
/// BootROM path
#[arg(short, long)]
bootrom: String,
/// Just run BootROM
#[arg(long)]
run_bootrom: bool,
/// Verbose print
#[arg(short, long)]
verbose: bool,
/// Show cycle count
#[arg(short, long)]
cycle_count: bool,
/// Step emulation by...
#[arg(long)]
step_by: Option<usize>,
}
fn cpu_ram_init(cpu: &mut CPU) {
cpu.memory.set(0xFF10, 0x80);
cpu.memory.set(0xFF11, 0xBF);
cpu.memory.set(0xFF12, 0xF3);
cpu.memory.set(0xFF14, 0xBF);
cpu.memory.set(0xFF16, 0x3F);
cpu.memory.set(0xFF19, 0xBF);
cpu.memory.set(0xFF1A, 0x7F);
cpu.memory.set(0xFF1B, 0xFF);
cpu.memory.set(0xFF1C, 0x9F);
cpu.memory.set(0xFF1E, 0xBF);
cpu.memory.set(0xFF20, 0xFF);
cpu.memory.set(0xFF23, 0xBF);
cpu.memory.set(0xFF24, 0x77);
cpu.memory.set(0xFF25, 0xF3);
cpu.memory.set(0xFF26, 0xF1);
cpu.memory.set(0xFF40, 0x91);
cpu.memory.set(0xFF47, 0xFC);
cpu.memory.set(0xFF48, 0xFF);
cpu.memory.set(0xFF49, 0xFF);
}
#[allow(dead_code)]
fn swap_rom_endian(rom: &ROM) -> ROM {
rom.chunks(2)
.map(|l| {
let mut m = l.to_owned();
m.reverse();
m
})
.flatten()
.collect()
}
static mut PAUSE_ENABLED: bool = false;
static mut PAUSE_QUEUED: bool = false;
// static mut VERBOSE: bool = false;
static VERBOSE: RwLock<bool> = RwLock::new(false);
const WIDTH: usize = 160;
const HEIGHT: usize = 144;
const FACTOR: usize = 3;
fn main() {
let args = Args::parse();
{
let mut v = VERBOSE.write().unwrap();
*v = args.verbose;
}
let mut window = Window::new(
"Gameboy",
WIDTH * FACTOR,
HEIGHT * FACTOR,
WindowOptions::default(),
)
.unwrap_or_else(|e| {
panic!("{}", e);
});
window.set_position(500, 50);
window.topmost(true);
let rom: ROM = fs::read(args.rom).expect("Could not load ROM");
let bootrom: ROM = fs::read(args.bootrom).expect("Could not load BootROM");
let mut cpu = CPU::new(Memory::init(bootrom, args.run_bootrom, rom), window);
if !args.run_bootrom {
cpu.reg.pc = 0x0100;
cpu_ram_init(&mut cpu);
}
let mut cycle_num = 0;
let mut instructions_seen = vec![];
let mut last_state = cpu.reg.clone();
let mut next_state = last_state;
verbose_println!("\n\n Begin execution...\n");
match args.step_by {
Some(step_size) => loop {
for _ in 0..step_size {
cycle_num += 1;
if args.cycle_count {
print_cycles(&cycle_num);
}
run_cycle(
&mut cpu,
&mut next_state,
&mut last_state,
&mut instructions_seen,
);
}
print!(
" ...{} cycles - press enter to continue\r",
cycle_num
);
stdout().flush().unwrap();
pause_once();
},
None => loop {
cycle_num += 1;
if args.cycle_count {
print_cycles(&cycle_num);
}
run_cycle(
&mut cpu,
&mut next_state,
&mut last_state,
&mut instructions_seen,
);
},
}
}
fn run_cycle(
cpu: &mut CPU,
next_state: &mut Registers,
last_state: &mut Registers,
instructions_seen: &mut Vec<u8>,
) {
let will_pause;
unsafe {
will_pause = PAUSE_QUEUED.clone();
}
cpu.exec_next();
unsafe {
*next_state = cpu.reg;
if !PAUSE_ENABLED {
if next_state.pc >= 0x100 {
PAUSE_ENABLED = true;
}
}
*last_state = *next_state;
if will_pause {
pause();
}
}
match instructions_seen.contains(&cpu.last_instruction) {
true => {}
false => {
// println!("new instruction enountered: {:#X}", cpu.last_instruction);
instructions_seen.push(cpu.last_instruction);
}
}
}
fn pause() {
unsafe {
if PAUSE_ENABLED {
let line = &mut String::new();
io::stdin().read_line(line).unwrap();
PAUSE_QUEUED = !line.contains("continue");
}
}
}
fn pause_once() {
println!("paused...");
io::stdin().read_line(&mut String::new()).unwrap();
}
fn print_cycles(cycles: &i32) {
if *cycles % 45678 != 0 {
return;
}
let instructions_per_second = 400000;
print!(
"cycle {} - approx {} seconds on real hardware\r",
cycles,
cycles / instructions_per_second
);
stdout().flush().unwrap();
}
fn is_verbose() -> bool {
match VERBOSE.read() {
Ok(v) => *v,
Err(_) => false,
}
}