Skip to content

Commit d3364f1

Browse files
committed
chore: add Cycles to Ops, start to track cpu/ppu cycles
1 parent 108594d commit d3364f1

File tree

4 files changed

+318
-244
lines changed

4 files changed

+318
-244
lines changed

src/bus.rs

+11
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@ pub struct Bus {
1313
cpu_vram: [u8; 0x800], // 2048
1414
rom: Rom,
1515
ppu: Ppu,
16+
cycles: usize,
1617
}
1718

1819
impl Bus {
@@ -23,9 +24,19 @@ impl Bus {
2324
cpu_vram: [0; 0x800],
2425
rom,
2526
ppu,
27+
cycles: 0,
2628
}
2729
}
2830

31+
pub fn tick(&mut self, cycles: usize) {
32+
self.cycles += cycles;
33+
self.ppu.tick(cycles * 3);
34+
}
35+
36+
pub fn poll_nmi_status(&mut self) -> bool {
37+
self.ppu.is_nmi_interrupt_triggered()
38+
}
39+
2940
fn read_prg_rom(&self, addr: u16) -> u8 {
3041
let mut idx = addr - PRG_ROM_START;
3142

src/core.rs

+21-2
Original file line numberDiff line numberDiff line change
@@ -245,12 +245,24 @@ impl Cpu {
245245
F: FnMut(&mut Cpu),
246246
{
247247
loop {
248+
if self.bus.poll_nmi_status() {
249+
todo!("implement NMI interrupt");
250+
// self.interrupt_nmi();
251+
}
252+
248253
callback(self);
249254

250255
let opcode = self.mem_read(self.pc);
251256
self.pc += 1;
252257

253-
let (name, mode) = lookup_opcode(opcode);
258+
let (name, cycles, mode) = lookup_opcode(opcode);
259+
if cycles.0 == 0 {
260+
todo!(
261+
"cycles is mistakenly set to 0 for {} (0x{:02X}) ",
262+
name,
263+
opcode
264+
);
265+
}
254266
let size = addressing_mode_to_size(&mode);
255267

256268
let saved_pc = self.pc;
@@ -336,6 +348,13 @@ impl Cpu {
336348
OpName::RRA => self.rra(&mode),
337349
}
338350

351+
// TODO: Handle extra cycles behavior
352+
// (1) page wrapping behavior for some ops that adds +1 to the number of cycles
353+
// Memory page size is 256 bytes. For example, the range [0x0000 .. 0x00FF]- belongs to page 0, [0x0100 .. 0x01FF] belongs to page 1, etc.
354+
// It's enough to compare the upper byte of the addresses to see if they are on the same page.
355+
// (2) branching behavior that adds +1 or +2 to cycles
356+
self.bus.tick(cycles.0 as usize);
357+
339358
// some operations modify the pc, like JMP. We shouldn't override that.
340359
if self.pc == saved_pc {
341360
self.pc += size - 1;
@@ -836,7 +855,7 @@ impl Cpu {
836855
//// Address syntax by mode looks like:
837856

838857
let op = lookup_opcode(code);
839-
let (name, mode) = op;
858+
let (name, _, mode) = op;
840859
let size = addressing_mode_to_size(&mode);
841860

842861
let tla = format!("{}{}", if is_official(code) { "" } else { "*" }, name);

0 commit comments

Comments
 (0)