-
Notifications
You must be signed in to change notification settings - Fork 0
/
Timer.java
200 lines (157 loc) · 2.47 KB
/
Timer.java
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
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
import littlecube.bitutil.*;
import littlecube.unsigned.*;
public class Timer
{
UnsignedShort div;
UnsignedByte tima;
UnsignedByte tma;
UnsignedByte tac;
static final int DIV = 0xFF04;
static final int TIMA = 0xFF05;
static final int TMA = 0xFF06;
static final int TAC = 0xFF07;
int lastAND;
int lastTIMA;
int clocks;
int waitClocks;
public Timer()
{
init();
}
public void init()
{
div = new UnsignedShort();
tima = new UnsignedByte();
tma = new UnsignedByte();
tac = new UnsignedByte();
lastAND = -1;
lastTIMA = -1;
clocks = 0;
waitClocks = -1;
}
public void clock(int newClocks)
{
clocks += newClocks;
readDIV();
readTIMA();
readTMA();
readTAC();
if (waitClocks == -1)
{
while (clocks > 0)
{
div.add(1);
writeDIV();
int andResult = tac.getBit(2) & div.getBit(TACVal());
if ((lastAND == 1) && ((lastAND = andResult) == 0))
{
if ((tima.get() + 1) > 0xFF)
{
overflow();
waitClocks();
if (clocks > 0)
{
continue;
}
else
{
return;
}
}
tima.add(1);
writeTIMA();
}
clocks--;
}
}
else if (waitClocks == 0)
{
GB.cpu.mmu.writeBit(CPU.IF, 2, 1);
tima.set(tma.get());
writeTIMA();
waitClocks = -1;
}
else if (waitClocks > 0)
{
waitClocks();
if (clocks > 0)
{
clock(0);
}
}
else
{
System.out.println("E: Broken waitClocks.");
}
}
void overflow()
{
waitClocks = 4;
tima.set(0x00);
writeTIMA();
}
void waitClocks()
{
while (waitClocks > 0 && clocks > 0)
{
div.add(1);
writeDIV();
waitClocks--;
clocks--;
}
}
void readDIV()
{
div.set(GB.cpu.memory[0xFF04].get());
}
void writeDIV()
{
GB.cpu.mmu.write(0xFF04, div.subByte(1));
}
void readTIMA()
{
tima.set(GB.cpu.memory[0xFF05].get());
}
void writeTIMA()
{
GB.cpu.mmu.write(0xFF05, tima.get());
}
void readTMA()
{
tma.set(GB.cpu.memory[0xFF06].get());
}
void readTAC()
{
tac.set(GB.cpu.memory[0xFF07].get());
}
int TACVal()
{
UnsignedByte tacval = new UnsignedByte();
tacval.set(tac.get() & 0x03);
int retPos = 0;
switch (tacval.get())
{
case 0:
{
retPos = 9;
break;
}
case 1:
{
retPos = 3;
break;
}
case 2:
{
retPos = 5;
break;
}
case 3:
{
retPos = 7;
break;
}
}
return retPos;
}
}