-
-
Notifications
You must be signed in to change notification settings - Fork 44
/
TickManager.java
352 lines (323 loc) · 11.6 KB
/
TickManager.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
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
package me.nallar.tickthreading.minecraft;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.SortedMap;
import java.util.TreeMap;
import me.nallar.tickthreading.Log;
import me.nallar.tickthreading.collections.ConcurrentIterableArrayList;
import me.nallar.tickthreading.minecraft.profiling.EntityTickProfiler;
import me.nallar.tickthreading.minecraft.tickregion.EntityTickRegion;
import me.nallar.tickthreading.minecraft.tickregion.TickRegion;
import me.nallar.tickthreading.minecraft.tickregion.TileEntityTickRegion;
import me.nallar.tickthreading.util.TableFormatter;
import me.nallar.unsafe.UnsafeUtil;
import net.minecraft.entity.Entity;
import net.minecraft.server.MinecraftServer;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.world.World;
import net.minecraft.world.WorldServer;
public final class TickManager {
public final int regionSize;
public boolean variableTickRate;
public boolean profilingEnabled = false;
public double averageTickLength = 0;
public long lastTickLength = 0;
public long lastStartTime = 0;
private static final int shuffleInterval = 800;
private int shuffleCount;
private final boolean waitForCompletion;
public final EntityTickProfiler entityTickProfiler = new EntityTickProfiler();
public final World world;
public final List<TileEntity> tileEntityList = new ArrayList<TileEntity>();
public final List<Entity> entityList = new ArrayList<Entity>();
public Object tileEntityLock = new Object();
public Object entityLock = new Object();
private final Map<Integer, TileEntityTickRegion> tileEntityCallables = new HashMap<Integer, TileEntityTickRegion>();
private final Map<Integer, EntityTickRegion> entityCallables = new HashMap<Integer, EntityTickRegion>();
private final ConcurrentIterableArrayList<TickRegion> tickRegions = new ConcurrentIterableArrayList<TickRegion>();
private final ThreadManager threadManager;
private final Map<Class<?>, Integer> entityClassToCountMap = new HashMap<Class<?>, Integer>();
public TickManager(World world, int regionSize, int threads, boolean waitForCompletion) {
this.waitForCompletion = waitForCompletion;
threadManager = new ThreadManager(threads, "Tile/Entity Tick for " + Log.name(world));
this.world = world;
this.regionSize = regionSize;
shuffleCount = world.rand.nextInt(shuffleInterval);
}
public void setVariableTickRate(boolean variableTickRate) {
this.variableTickRate = variableTickRate;
}
public TickRegion getTileEntityCallable(int hashCode) {
return tileEntityCallables.get(hashCode);
}
@SuppressWarnings ("NumericCastThatLosesPrecision")
private TileEntityTickRegion getOrCreateCallable(TileEntity tileEntity) {
int hashCode = getHashCode(tileEntity);
TileEntityTickRegion callable = tileEntityCallables.get(hashCode);
if (callable == null) {
synchronized (tickRegions) {
callable = tileEntityCallables.get(hashCode);
if (callable == null) {
callable = new TileEntityTickRegion(world, this, tileEntity.xCoord / regionSize, tileEntity.zCoord / regionSize);
tileEntityCallables.put(hashCode, callable);
tickRegions.add(callable);
}
}
}
return callable;
}
public TickRegion getEntityCallable(int hashCode) {
return entityCallables.get(hashCode);
}
@SuppressWarnings ("NumericCastThatLosesPrecision")
private EntityTickRegion getOrCreateCallable(Entity entity) {
int regionX = (int) entity.posX / regionSize;
int regionZ = (int) entity.posZ / regionSize;
int hashCode = getHashCodeFromRegionCoords(regionX, regionZ);
EntityTickRegion callable = entityCallables.get(hashCode);
if (callable == null) {
synchronized (tickRegions) {
callable = entityCallables.get(hashCode);
if (callable == null) {
callable = new EntityTickRegion(world, this, regionX, regionZ);
entityCallables.put(hashCode, callable);
tickRegions.add(callable);
}
}
}
return callable;
}
public int getHashCode(TileEntity tileEntity) {
return getHashCode(tileEntity.xCoord, tileEntity.zCoord);
}
@SuppressWarnings ("NumericCastThatLosesPrecision")
public int getHashCode(Entity entity) {
return getHashCode((int) entity.posX, (int) entity.posZ);
}
public int getHashCode(int x, int z) {
return getHashCodeFromRegionCoords(x / regionSize, z / regionSize);
}
public static int getHashCodeFromRegionCoords(int x, int z) {
return x + (z << 16);
}
private void processChanges() {
try {
synchronized (tickRegions) {
Iterator<TickRegion> iterator = tickRegions.iterator();
while (iterator.hasNext()) {
TickRegion tickRegion = iterator.next();
tickRegion.processChanges();
if (tickRegion.isEmpty()) {
iterator.remove();
if (tickRegion instanceof EntityTickRegion) {
entityCallables.remove(tickRegion.hashCode);
} else {
tileEntityCallables.remove(tickRegion.hashCode);
}
tickRegion.die();
}
}
if (shuffleCount++ % shuffleInterval == 0) {
Collections.shuffle(tickRegions);
}
}
} catch (Exception e) {
Log.severe("Exception occurred while processing entity changes: ", e);
}
}
public void add(TileEntity tileEntity) {
getOrCreateCallable(tileEntity).add(tileEntity);
synchronized (tileEntityLock) {
if (!tileEntityList.contains(tileEntity)) {
tileEntityList.add(tileEntity);
}
}
}
public void add(Entity entity) {
getOrCreateCallable(entity).add(entity);
boolean added;
synchronized (entityLock) {
if (added = !entityList.contains(entity)) {
entityList.add(entity);
}
}
if (added) {
synchronized (entityClassToCountMap) {
Class entityClass = entity.getClass();
Integer count = entityClassToCountMap.get(entityClass);
if (count == null) {
count = 0;
}
entityClassToCountMap.put(entityClass, count + 1);
}
}
}
public void remove(TileEntity tileEntity) {
getOrCreateCallable(tileEntity).remove(tileEntity);
removed(tileEntity);
}
public void remove(Entity entity) {
getOrCreateCallable(entity).remove(entity);
removed(entity);
}
public void removed(TileEntity tileEntity) {
synchronized (tileEntityLock) {
tileEntityList.remove(tileEntity);
}
}
public void removed(Entity entity) {
boolean removed;
synchronized (entityLock) {
removed = entityList.remove(entity);
}
if (removed) {
synchronized (entityClassToCountMap) {
Class entityClass = entity.getClass();
Integer count = entityClassToCountMap.get(entityClass);
if (count == null) {
throw new IllegalStateException("Removed an entity which should not have been in the entityList");
}
entityClassToCountMap.put(entityClass, count - 1);
}
}
}
public void doTick() {
boolean previousProfiling = world.theProfiler.profilingEnabled;
lastStartTime = DeadLockDetector.tick("TickManager.doTick: " + Log.name(world));
threadManager.waitForCompletion();
if (previousProfiling) {
world.theProfiler.profilingEnabled = false;
}
threadManager.runList(tickRegions);
if (previousProfiling || waitForCompletion) {
lastTickLength = (threadManager.waitForCompletion() - lastStartTime);
averageTickLength = ((averageTickLength * 127) + lastTickLength) / 128;
threadManager.run(new Runnable() {
@Override
public void run() {
processChanges();
}
});
}
if (previousProfiling) {
world.theProfiler.profilingEnabled = true;
}
if (profilingEnabled) {
entityTickProfiler.tick();
}
}
public void tickEnd() {
if (!waitForCompletion) {
lastTickLength = (threadManager.waitForCompletion() - lastStartTime);
averageTickLength = ((averageTickLength * 127) + lastTickLength) / 128;
threadManager.run(new Runnable() {
@Override
public void run() {
processChanges();
}
});
}
}
public void unload() {
threadManager.stop();
for (TickRegion tickRegion : tickRegions) {
tickRegion.die();
}
tickRegions.clear();
entityList.clear();
entityClassToCountMap.clear();
UnsafeUtil.clean(this);
}
public void writeStats(TableFormatter tf) {
long timeTotal = 0;
long[] tickTimes = MinecraftServer.getServer().worldTickTimes.get(world.provider.dimensionId);
for (long tick : tickTimes) {
timeTotal += tick;
}
double time = (timeTotal) / (double) tickTimes.length;
if (time == 0) {
time = 0.1;
}
tf
.row(Log.name(world))
.row(Math.min(1000000000 / time, MinecraftServer.getTargetTPS()))
.row(String.valueOf(entityList.size()))
.row(String.valueOf(tileEntityList.size()))
.row(world instanceof WorldServer ? String.valueOf(((WorldServer) world).theChunkProviderServer.getLoadedChunkCount()) : "0")
.row(TableFormatter.formatDoubleWithPrecision((time * 100f) / MinecraftServer.getTargetTickTime(), 3) + '%');
}
public TableFormatter writeDetailedStats(TableFormatter tf) {
@SuppressWarnings ("MismatchedQueryAndUpdateOfStringBuilder")
StringBuilder stats = tf.sb;
stats.append("World: ").append(Log.name(world)).append('\n');
stats.append("---- Slowest tick regions ----").append('\n');
// TODO: Rewrite this
float averageAverageTickTime = 0;
float maxTickTime = 0;
SortedMap<Float, TickRegion> sortedTickCallables = new TreeMap<Float, TickRegion>();
synchronized (tickRegions) {
for (TickRegion tickRegion : tickRegions) {
float averageTickTime = tickRegion.getAverageTickTime();
averageAverageTickTime += averageTickTime;
sortedTickCallables.put(averageTickTime, tickRegion);
if (averageTickTime > maxTickTime) {
maxTickTime = averageTickTime;
}
}
Collection<TickRegion> var = sortedTickCallables.values();
TickRegion[] sortedTickCallablesArray = var.toArray(new TickRegion[var.size()]);
for (int i = sortedTickCallablesArray.length - 1; i >= sortedTickCallablesArray.length - 6; i--) {
if (i >= 0 && sortedTickCallablesArray[i].getAverageTickTime() > 1.5) {
stats.append(sortedTickCallablesArray[i].getStats()).append('\n');
}
}
averageAverageTickTime /= tickRegions.size();
stats.append("---- World stats ----");
stats.append("\nAverage tick time: ").append(averageAverageTickTime).append("ms");
stats.append("\nMax tick time: ").append(maxTickTime).append("ms");
stats.append("\nEffective tick time: ").append(lastTickLength / 1000000f).append("ms");
stats.append("\nAverage effective tick time: ").append((float) averageTickLength / 1000000).append("ms");
}
return tf;
}
public TableFormatter writeEntityStats(TableFormatter tf) {
tf
.heading("Main")
.heading("Map")
.heading("Region");
tf
.row(entityList.size())
.row(getTotalEntityCountFromMap())
.row(getTotalEntityCountFromRegions());
tf.finishTable();
return tf;
}
private int getTotalEntityCountFromRegions() {
int count = 0;
for (EntityTickRegion entityTickRegion : entityCallables.values()) {
count += entityTickRegion.size();
}
return count;
}
private int getTotalEntityCountFromMap() {
int count = 0;
for (Map.Entry<Class<?>, Integer> entry : entityClassToCountMap.entrySet()) {
count += entry.getValue();
}
return count;
}
public int getEntityCount(Class<?> clazz) {
int count = 0;
for (Map.Entry<Class<?>, Integer> entry : entityClassToCountMap.entrySet()) {
if (clazz.isAssignableFrom(entry.getKey())) {
count += entry.getValue();
}
}
return count;
}
}