summaryrefslogtreecommitdiff
path: root/memory.c
blob: e0ed85af62831360a8c3e3be7078b3aff224ea9f (plain)
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



static uint8_t memory_read(struct nes_state *restrict state, uint32_t offset) {
	state->cycles++;
	ppu_tick(state); ppu_tick(state); ppu_tick(state);

	if(offset > 0xffff) {
		printf("%x\n", offset);
	}

	// state->ram[0x301] = 0x1;
	if(offset < 0x2000) {
		return state->ram[offset & 0x07ff];
	} else if(offset < 0x4000) {
		return ppu_read(state, offset);
		// switch(offset & 7) {
		// 	case 2: return ppu_read_2002(state);
		// 	case 4: return ppu_read_2004(state);
		// 	case 7: return ppu_read_2007(state);
		// 	default: return 0;
		// }
	} else if(offset < 0x4020) {
		// TODO: APU and I/O reads
		return 0;
	} else if(offset >= 0x6000) {
		return state->mapper.prg_read(state, offset);
	} else {
		return 0;
	}
}

static void memory_write(struct nes_state *restrict state, uint32_t offset, uint8_t value) {
	state->cycles++;
	ppu_tick(state); ppu_tick(state); ppu_tick(state);

	if(offset > 0xffff) {
		printf("%x\n", offset);
	}

	if(offset < 0x2000) {
		state->ram[offset & 0x07ff] = value;
	} else if(offset < 0x4000) {
		ppu_write(state, offset, value);
		// switch(offset & 7) {
		// 	case 0: ppu_write_2000(state, value); break;
		// 	case 1: ppu_write_2001(state, value); break;
		// 	case 3: ppu_write_2003(state, value); break;
		// 	case 4: ppu_write_2004(state, value); break;
		// 	case 5: ppu_write_2005(state, value); break;
		// 	case 6: ppu_write_2006(state, value); break;
		// 	case 7: ppu_write_2007(state, value); break;
		// 	default: break;
		// }
	} else if(offset == 0x4014) {
		ppu_dma_4014(state, value);
	} else if(offset < 0x4020) {
		// TODO: APU and I/O writes
	} else if(offset >= 0x6000) {
		state->mapper.prg_write(state, offset, value);
	}
}

static uint8_t memory_read_dma(struct nes_state *restrict state, uint32_t offset) {
	// Do not tick CPU/PPU/APU — caller handles timing
	if(offset < 0x2000) {
		return state->ram[offset & 0x07ff];
	} else if(offset < 0x4000) {
		// PPU register reads are ignored during DMA
		return 0;
	} else if(offset < 0x4020) {
		// APU and I/O — usually ignored or blocked during DMA
		return 0;
	} else if(offset >= 0x6000) {
		return state->mapper.prg_read(state, offset);
	} else {
		return 0;
	}
}

static uint8_t memory_read_dummy(struct nes_state *restrict state, uint32_t offset) {
	state->cycles++;
	ppu_tick(state); ppu_tick(state); ppu_tick(state);

	if(offset < 0x2000) {
		return 0;
	} else if(offset < 0x4000) {
		return ppu_read(state, offset);
	} else if(offset < 0x4020) {
		return 0;
	} else if(offset >= 0x6000) {
		return state->mapper.prg_read(state, offset);
	} else {
		return 0;
	}
}