aboutsummaryrefslogtreecommitdiffhomepage
path: root/patches/server/0429-Use-distance-map-to-optimise-entity-tracker.patch
blob: ef2dfbe2462dcd0d245f944d23436be213b32077 (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
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
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
From: Spottedleaf <Spottedleaf@users.noreply.github.com>
Date: Tue, 5 May 2020 20:18:05 -0700
Subject: [PATCH] Use distance map to optimise entity tracker

Use the distance map to find candidate players for tracking.

diff --git a/src/main/java/net/minecraft/server/level/ChunkMap.java b/src/main/java/net/minecraft/server/level/ChunkMap.java
index 80018a94c12b7963c87b3960b71d88d8ac50ff09..2ff9c1f1c41494c282b43eafeb719172f664414b 100644
--- a/src/main/java/net/minecraft/server/level/ChunkMap.java
+++ b/src/main/java/net/minecraft/server/level/ChunkMap.java
@@ -70,6 +70,7 @@ import net.minecraft.network.protocol.game.ClientboundSetEntityLinkPacket;
 import net.minecraft.network.protocol.game.ClientboundSetPassengersPacket;
 import net.minecraft.network.protocol.game.DebugPackets;
 import net.minecraft.server.MCUtil;
+import net.minecraft.server.MinecraftServer;
 import net.minecraft.server.level.progress.ChunkProgressListener;
 import net.minecraft.server.network.ServerPlayerConnection;
 import net.minecraft.util.CsvOutput;
@@ -192,10 +193,35 @@ public class ChunkMap extends ChunkStorage implements ChunkHolder.PlayerProvider
     public final com.destroystokyo.paper.util.misc.PlayerAreaMap playerMobSpawnMap; // this map is absent from updateMaps since it's controlled at the start of the chunkproviderserver tick
     public final com.destroystokyo.paper.util.misc.PlayerAreaMap playerChunkTickRangeMap;
     // Paper end - optimise ChunkMap#anyPlayerCloseEnoughForSpawning
+    // Paper start - use distance map to optimise tracker
+    public static boolean isLegacyTrackingEntity(Entity entity) {
+        return entity.isLegacyTrackingEntity;
+    }
+
+    // inlined EnumMap, TrackingRange.TrackingRangeType
+    static final org.spigotmc.TrackingRange.TrackingRangeType[] TRACKING_RANGE_TYPES = org.spigotmc.TrackingRange.TrackingRangeType.values();
+    public final com.destroystokyo.paper.util.misc.PlayerAreaMap[] playerEntityTrackerTrackMaps;
+    final int[] entityTrackerTrackRanges;
+    public final int getEntityTrackerRange(final int ordinal) {
+        return this.entityTrackerTrackRanges[ordinal];
+    }
+
+    private int convertSpigotRangeToVanilla(final int vanilla) {
+        return MinecraftServer.getServer().getScaledTrackingDistance(vanilla);
+    }
+    // Paper end - use distance map to optimise tracker
 
     void addPlayerToDistanceMaps(ServerPlayer player) {
         int chunkX = MCUtil.getChunkCoordinate(player.getX());
         int chunkZ = MCUtil.getChunkCoordinate(player.getZ());
+        // Paper start - use distance map to optimise entity tracker
+        for (int i = 0, len = TRACKING_RANGE_TYPES.length; i < len; ++i) {
+            com.destroystokyo.paper.util.misc.PlayerAreaMap trackMap = this.playerEntityTrackerTrackMaps[i];
+            int trackRange = this.entityTrackerTrackRanges[i];
+
+            trackMap.add(player, chunkX, chunkZ, Math.min(trackRange, this.getEffectiveViewDistance()));
+        }
+        // Paper end - use distance map to optimise entity tracker
         // Note: players need to be explicitly added to distance maps before they can be updated
         this.playerChunkTickRangeMap.add(player, chunkX, chunkZ, DistanceManager.MOB_SPAWN_RANGE); // Paper - optimise ChunkMap#anyPlayerCloseEnoughForSpawning
         // Paper start - per player mob spawning
@@ -207,6 +233,11 @@ public class ChunkMap extends ChunkStorage implements ChunkHolder.PlayerProvider
 
     void removePlayerFromDistanceMaps(ServerPlayer player) {
 
+        // Paper start - use distance map to optimise tracker
+        for (int i = 0, len = TRACKING_RANGE_TYPES.length; i < len; ++i) {
+            this.playerEntityTrackerTrackMaps[i].remove(player);
+        }
+        // Paper end - use distance map to optimise tracker
         // Paper start - optimise ChunkMap#anyPlayerCloseEnoughForSpawning
         this.playerMobSpawnMap.remove(player);
         this.playerChunkTickRangeMap.remove(player);
@@ -222,6 +253,14 @@ public class ChunkMap extends ChunkStorage implements ChunkHolder.PlayerProvider
         int chunkX = MCUtil.getChunkCoordinate(player.getX());
         int chunkZ = MCUtil.getChunkCoordinate(player.getZ());
         // Note: players need to be explicitly added to distance maps before they can be updated
+        // Paper start - use distance map to optimise entity tracker
+        for (int i = 0, len = TRACKING_RANGE_TYPES.length; i < len; ++i) {
+            com.destroystokyo.paper.util.misc.PlayerAreaMap trackMap = this.playerEntityTrackerTrackMaps[i];
+            int trackRange = this.entityTrackerTrackRanges[i];
+
+            trackMap.update(player, chunkX, chunkZ, Math.min(trackRange, this.getEffectiveViewDistance()));
+        }
+        // Paper end - use distance map to optimise entity tracker
         this.playerChunkTickRangeMap.update(player, chunkX, chunkZ, DistanceManager.MOB_SPAWN_RANGE); // Paper - optimise ChunkMap#anyPlayerCloseEnoughForSpawning
         // Paper start - per player mob spawning
         if (this.playerMobDistanceMap != null) {
@@ -303,6 +342,45 @@ public class ChunkMap extends ChunkStorage implements ChunkHolder.PlayerProvider
         this.regionManagers.add(this.dataRegionManager);
         // Paper end
         this.playerMobDistanceMap = this.level.paperConfig.perPlayerMobSpawns ? new com.destroystokyo.paper.util.misc.PlayerAreaMap(this.pooledLinkedPlayerHashSets) : null; // Paper
+        // Paper start - use distance map to optimise entity tracker
+        this.playerEntityTrackerTrackMaps = new com.destroystokyo.paper.util.misc.PlayerAreaMap[TRACKING_RANGE_TYPES.length];
+        this.entityTrackerTrackRanges = new int[TRACKING_RANGE_TYPES.length];
+
+        org.spigotmc.SpigotWorldConfig spigotWorldConfig = this.level.spigotConfig;
+
+        for (int ordinal = 0, len = TRACKING_RANGE_TYPES.length; ordinal < len; ++ordinal) {
+            org.spigotmc.TrackingRange.TrackingRangeType trackingRangeType = TRACKING_RANGE_TYPES[ordinal];
+            int configuredSpigotValue;
+            switch (trackingRangeType) {
+                case PLAYER:
+                    configuredSpigotValue = spigotWorldConfig.playerTrackingRange;
+                    break;
+                case ANIMAL:
+                    configuredSpigotValue = spigotWorldConfig.animalTrackingRange;
+                    break;
+                case MONSTER:
+                    configuredSpigotValue = spigotWorldConfig.monsterTrackingRange;
+                    break;
+                case MISC:
+                    configuredSpigotValue = spigotWorldConfig.miscTrackingRange;
+                    break;
+                case OTHER:
+                    configuredSpigotValue = spigotWorldConfig.otherTrackingRange;
+                    break;
+                case ENDERDRAGON:
+                    configuredSpigotValue = EntityType.ENDER_DRAGON.clientTrackingRange() * 16;
+                    break;
+                default:
+                    throw new IllegalStateException("Missing case for enum " + trackingRangeType);
+            }
+            configuredSpigotValue = convertSpigotRangeToVanilla(configuredSpigotValue);
+
+            int trackRange = (configuredSpigotValue >>> 4) + ((configuredSpigotValue & 15) != 0 ? 1 : 0);
+            this.entityTrackerTrackRanges[ordinal] = trackRange;
+
+            this.playerEntityTrackerTrackMaps[ordinal] = new com.destroystokyo.paper.util.misc.PlayerAreaMap(this.pooledLinkedPlayerHashSets);
+        }
+        // Paper end - use distance map to optimise entity tracker
         // Paper start - optimise ChunkMap#anyPlayerCloseEnoughForSpawning
         this.playerChunkTickRangeMap = new com.destroystokyo.paper.util.misc.PlayerAreaMap(this.pooledLinkedPlayerHashSets,
             (ServerPlayer player, int rangeX, int rangeZ, int currPosX, int currPosZ, int prevPosX, int prevPosZ,
@@ -1558,17 +1636,7 @@ public class ChunkMap extends ChunkStorage implements ChunkHolder.PlayerProvider
     }
 
     public void move(ServerPlayer player) {
-        ObjectIterator objectiterator = this.entityMap.values().iterator();
-
-        while (objectiterator.hasNext()) {
-            ChunkMap.TrackedEntity playerchunkmap_entitytracker = (ChunkMap.TrackedEntity) objectiterator.next();
-
-            if (playerchunkmap_entitytracker.entity == player) {
-                playerchunkmap_entitytracker.updatePlayers(this.level.players());
-            } else {
-                playerchunkmap_entitytracker.updatePlayer(player);
-            }
-        }
+        // Paper - delay this logic for the entity tracker tick, no need to duplicate it
 
         int i = SectionPos.blockToSectionCoord(player.getBlockX());
         int j = SectionPos.blockToSectionCoord(player.getBlockZ());
@@ -1695,7 +1763,7 @@ public class ChunkMap extends ChunkStorage implements ChunkHolder.PlayerProvider
 
                     entity.tracker = playerchunkmap_entitytracker; // Paper - Fast access to tracker
                     this.entityMap.put(entity.getId(), playerchunkmap_entitytracker);
-                    playerchunkmap_entitytracker.updatePlayers(this.level.players());
+                    playerchunkmap_entitytracker.updatePlayers(entity.getPlayersInTrackRange()); // Paper - don't search all players
                     if (entity instanceof ServerPlayer) {
                         ServerPlayer entityplayer = (ServerPlayer) entity;
 
@@ -1739,7 +1807,37 @@ public class ChunkMap extends ChunkStorage implements ChunkHolder.PlayerProvider
         entity.tracker = null; // Paper - We're no longer tracked
     }
 
+    // Paper start - optimised tracker
+    private final void processTrackQueue() {
+        this.level.timings.tracker1.startTiming();
+        try {
+            for (TrackedEntity tracker : this.entityMap.values()) {
+                // update tracker entry
+                tracker.updatePlayers(tracker.entity.getPlayersInTrackRange());
+            }
+        } finally {
+            this.level.timings.tracker1.stopTiming();
+        }
+
+
+        this.level.timings.tracker2.startTiming();
+        try {
+            for (TrackedEntity tracker : this.entityMap.values()) {
+                tracker.serverEntity.sendChanges();
+            }
+        } finally {
+            this.level.timings.tracker2.stopTiming();
+        }
+    }
+    // Paper end - optimised tracker
+
     protected void tick() {
+        // Paper start - optimized tracker
+        if (true) {
+            this.processTrackQueue();
+            return;
+        }
+        // Paper end - optimized tracker
         List<ServerPlayer> list = Lists.newArrayList();
         List<ServerPlayer> list1 = this.level.players();
         ObjectIterator objectiterator = this.entityMap.values().iterator();
@@ -1815,23 +1913,31 @@ public class ChunkMap extends ChunkStorage implements ChunkHolder.PlayerProvider
         DebugPackets.sendPoiPacketsForChunk(this.level, chunk.getPos());
         List<Entity> list = Lists.newArrayList();
         List<Entity> list1 = Lists.newArrayList();
-        ObjectIterator objectiterator = this.entityMap.values().iterator();
+        // Paper start - optimise entity tracker
+        // use the chunk entity list, not the whole trackedEntities map...
+        Entity[] entities = chunk.entities.getRawData();
+        for (int i = 0, size = chunk.entities.size(); i < size; ++i) {
+            Entity entity = entities[i];
+            if (entity == player) {
+                continue;
+            }
+            ChunkMap.TrackedEntity tracker = this.entityMap.get(entity.getId());
+            if (tracker != null) { // dumb plugins... move on...
+                tracker.updatePlayer(player);
+            }
 
-        while (objectiterator.hasNext()) {
-            ChunkMap.TrackedEntity playerchunkmap_entitytracker = (ChunkMap.TrackedEntity) objectiterator.next();
-            Entity entity = playerchunkmap_entitytracker.entity;
+            // keep the vanilla logic here - this is REQUIRED or else passengers and their vehicles disappear!
+            // (and god knows what the leash thing is)
 
-            if (entity != player && entity.chunkPosition().equals(chunk.getPos())) {
-                playerchunkmap_entitytracker.updatePlayer(player);
-                if (entity instanceof Mob && ((Mob) entity).getLeashHolder() != null) {
-                    list.add(entity);
-                }
+            if (entity instanceof Mob && ((Mob)entity).getLeashHolder() != null) {
+                list.add(entity);
+            }
 
-                if (!entity.getPassengers().isEmpty()) {
-                    list1.add(entity);
-                }
+            if (!entity.getPassengers().isEmpty()) {
+                list1.add(entity);
             }
         }
+        // Paper end - optimise entity tracker
 
         Iterator iterator;
         Entity entity1;
@@ -1907,6 +2013,42 @@ public class ChunkMap extends ChunkStorage implements ChunkHolder.PlayerProvider
             this.lastSectionPos = SectionPos.of(entity);
         }
 
+        // Paper start - use distance map to optimise tracker
+        com.destroystokyo.paper.util.misc.PooledLinkedHashSets.PooledObjectLinkedOpenHashSet<ServerPlayer> lastTrackerCandidates;
+
+        final void updatePlayers(com.destroystokyo.paper.util.misc.PooledLinkedHashSets.PooledObjectLinkedOpenHashSet<ServerPlayer> newTrackerCandidates) {
+            com.destroystokyo.paper.util.misc.PooledLinkedHashSets.PooledObjectLinkedOpenHashSet<ServerPlayer> oldTrackerCandidates = this.lastTrackerCandidates;
+            this.lastTrackerCandidates = newTrackerCandidates;
+
+            if (newTrackerCandidates != null) {
+                Object[] rawData = newTrackerCandidates.getBackingSet();
+                for (int i = 0, len = rawData.length; i < len; ++i) {
+                    Object raw = rawData[i];
+                    if (!(raw instanceof ServerPlayer)) {
+                        continue;
+                    }
+                    ServerPlayer player = (ServerPlayer)raw;
+                    this.updatePlayer(player);
+                }
+            }
+
+            if (oldTrackerCandidates == newTrackerCandidates) {
+                // this is likely the case.
+                // means there has been no range changes, so we can just use the above for tracking.
+                return;
+            }
+
+            // stuff could have been removed, so we need to check the trackedPlayers set
+            // for players that were removed
+
+            for (ServerPlayerConnection conn : this.seenBy.toArray(new ServerPlayerConnection[0])) { // avoid CME
+                if (newTrackerCandidates == null || !newTrackerCandidates.contains(conn.getPlayer())) {
+                    this.updatePlayer(conn.getPlayer());
+                }
+            }
+        }
+        // Paper end - use distance map to optimise tracker
+
         public boolean equals(Object object) {
             return object instanceof ChunkMap.TrackedEntity ? ((ChunkMap.TrackedEntity) object).entity.getId() == this.entity.getId() : false;
         }
diff --git a/src/main/java/net/minecraft/world/entity/Entity.java b/src/main/java/net/minecraft/world/entity/Entity.java
index 53c8583b8438571dd6fcec26c79a6594a4a6f786..a99d0dfeece57204e94b349b385e315a83869bca 100644
--- a/src/main/java/net/minecraft/world/entity/Entity.java
+++ b/src/main/java/net/minecraft/world/entity/Entity.java
@@ -54,6 +54,7 @@ import net.minecraft.network.syncher.EntityDataSerializers;
 import net.minecraft.network.syncher.SynchedEntityData;
 import net.minecraft.resources.ResourceKey;
 import net.minecraft.resources.ResourceLocation;
+import net.minecraft.server.MCUtil;
 import net.minecraft.server.MinecraftServer;
 import net.minecraft.server.level.ServerLevel;
 import net.minecraft.server.level.ServerPlayer;
@@ -362,6 +363,39 @@ public abstract class Entity implements Nameable, EntityAccess, CommandSource, i
     }
     // Paper end
 
+    // Paper start - optimise entity tracking
+    final org.spigotmc.TrackingRange.TrackingRangeType trackingRangeType = org.spigotmc.TrackingRange.getTrackingRangeType(this);
+
+    public boolean isLegacyTrackingEntity = false;
+
+    public final void setLegacyTrackingEntity(final boolean isLegacyTrackingEntity) {
+        this.isLegacyTrackingEntity = isLegacyTrackingEntity;
+    }
+
+    public final com.destroystokyo.paper.util.misc.PooledLinkedHashSets.PooledObjectLinkedOpenHashSet<ServerPlayer> getPlayersInTrackRange() {
+        // determine highest range of passengers
+        if (this.passengers.isEmpty()) {
+            return ((ServerLevel)this.level).getChunkSource().chunkMap.playerEntityTrackerTrackMaps[this.trackingRangeType.ordinal()]
+                .getObjectsInRange(MCUtil.getCoordinateKey(this));
+        }
+        Iterable<Entity> passengers = this.getIndirectPassengers();
+        net.minecraft.server.level.ChunkMap chunkMap = ((ServerLevel)this.level).getChunkSource().chunkMap;
+        org.spigotmc.TrackingRange.TrackingRangeType type = this.trackingRangeType;
+        int range = chunkMap.getEntityTrackerRange(type.ordinal());
+
+        for (Entity passenger : passengers) {
+            org.spigotmc.TrackingRange.TrackingRangeType passengerType = passenger.trackingRangeType;
+            int passengerRange = chunkMap.getEntityTrackerRange(passengerType.ordinal());
+            if (passengerRange > range) {
+                type = passengerType;
+                range = passengerRange;
+            }
+        }
+
+        return chunkMap.playerEntityTrackerTrackMaps[type.ordinal()].getObjectsInRange(MCUtil.getCoordinateKey(this));
+    }
+    // Paper end - optimise entity tracking
+
     public Entity(EntityType<?> type, Level world) {
         this.id = Entity.ENTITY_COUNTER.incrementAndGet();
         this.passengers = ImmutableList.of();
diff --git a/src/main/java/org/spigotmc/TrackingRange.java b/src/main/java/org/spigotmc/TrackingRange.java
index 55ce69b5fe097841d00ef5c241459dce9bb0d4db..e5bcbfe175a697e04886d04543e1278b7e83a184 100644
--- a/src/main/java/org/spigotmc/TrackingRange.java
+++ b/src/main/java/org/spigotmc/TrackingRange.java
@@ -24,6 +24,7 @@ public class TrackingRange
         {
             return defaultRange;
         }
+        if (entity instanceof net.minecraft.world.entity.boss.enderdragon.EnderDragon) return defaultRange; // Paper - enderdragon is exempt
         SpigotWorldConfig config = entity.level.spigotConfig;
         if ( entity instanceof ServerPlayer )
         {
@@ -47,8 +48,48 @@ public class TrackingRange
             return config.miscTrackingRange;
         } else
         {
-            if (entity instanceof net.minecraft.world.entity.boss.enderdragon.EnderDragon) return ((net.minecraft.server.level.ServerLevel)(entity.getCommandSenderWorld())).getChunkSource().chunkMap.getEffectiveViewDistance(); // Paper - enderdragon is exempt
             return config.otherTrackingRange;
         }
     }
+
+    // Paper start - optimise entity tracking
+    // copied from above, TODO check on update
+    public static TrackingRangeType getTrackingRangeType(Entity entity)
+    {
+        if (entity instanceof net.minecraft.world.entity.boss.enderdragon.EnderDragon) return TrackingRangeType.ENDERDRAGON; // Paper - enderdragon is exempt
+        if ( entity instanceof ServerPlayer )
+        {
+            return TrackingRangeType.PLAYER;
+            // Paper start - Simplify and set water mobs to animal tracking range
+        }
+        switch (entity.activationType) {
+            case RAIDER:
+            case MONSTER:
+            case FLYING_MONSTER:
+                return TrackingRangeType.MONSTER;
+            case WATER:
+            case VILLAGER:
+            case ANIMAL:
+                return TrackingRangeType.ANIMAL;
+            case MISC:
+        }
+        if ( entity instanceof ItemFrame || entity instanceof Painting || entity instanceof ItemEntity || entity instanceof ExperienceOrb )
+        // Paper end
+        {
+            return TrackingRangeType.MISC;
+        } else
+        {
+            return TrackingRangeType.OTHER;
+        }
+    }
+
+    public static enum TrackingRangeType {
+        PLAYER,
+        ANIMAL,
+        MONSTER,
+        MISC,
+        OTHER,
+        ENDERDRAGON;
+    }
+    // Paper end - optimise entity tracking
 }