summaryrefslogtreecommitdiff
path: root/mknes_memory.c
blob: 7280f816e63fd1aac301314eba569bb9677ed591 (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

__attribute__((hot))
static inline uint8_t memory_read(struct nes_state *state, uint32_t offset) {
	if(offset >= 0x10000) __builtin_unreachable();

	state->cpu.cycles++;
	apu_tick(state);
	ppu_tick(state);

	uint8_t result = 0;

	if(offset <= 0x1fff) {
		result = state->ram[offset & 0x07ff];

	} else if(offset >= 0x8000) {
		result = state->mapper_function.prg_rom_read(state, offset);

	} else if(offset >= 0x2000 && offset <= 0x3fff) {
		result = ppu_read(state, offset);

	} else if(offset == 0x4015) {
		result = apu_read4015(state);

	} else if(offset >= 0x4016 && offset <= 0x4017) {
		uint32_t index = offset & 1;
		uint8_t value = (state->ppu.input_latch[index] >> state->ppu.input_bit[index]) & 1;
		state->ppu.input_bit[index]++;
		result = value | 0x40;	// Bit 6 open bus high, bit 7 low

	} else if(offset >= 0x6000 && offset <= 0x7fff) {
		result = state->mapper_function.prg_ram_read(state, offset);
	}

	return result;
}

__attribute__((always_inline, hot))
static inline uint8_t memory_read_dummy(struct nes_state *state, uint32_t offset) {
	state->cpu.cycles++;
	apu_tick(state);
	ppu_tick(state);

	uint8_t result = 0;

	if(offset >= 0x2000 && offset < 0x4000) {
		result = ppu_read(state, offset);
	}
	return result;
}

__attribute__((hot))
static inline void memory_write(struct nes_state *state, uint32_t offset, uint8_t value) {
	if(offset >= 0x10000) __builtin_unreachable();

	state->cpu.cycles++;
	apu_tick(state);
	ppu_tick(state);


	if(offset <= 0x1fff) {
		state->ram[offset & 0x07ff] = value;

	} else if(offset >= 0x8000) {
		state->mapper_function.prg_rom_write(state, offset, value);

	} else if(offset >= 0x2000 && offset <= 0x3fff) {
		ppu_write(state, offset, value);

	} else if(offset == 0x4014) {
		ppu_dma_4014(state, value);

	} else if(offset == 0x4016) {
		// joypad strobe
		uint8_t s = value & 1;

		// if(s) {
			uint8_t prev = state->ppu.input_strobe;
			state->ppu.input_strobe = s;

			if(prev == 1 && (s) == 0) {
				// state->ppu.input[0] = tas_input[tas_frame_count];

				state->ppu.input_latch[0] = state->ppu.input[0];
				state->ppu.input_latch[1] = state->ppu.input[1];
				state->ppu.input_bit[0] = 0;
				state->ppu.input_bit[1] = 0;
			}
		// }

	} else if(offset >= 0x4000 && offset <= 0x4017) {
		apu_write(state, offset, value);

	} else if(offset >= 0x6000 && offset <= 0x7fff) {
		state->mapper_function.prg_ram_write(state, offset, value);

	}
}