PlayerManager

Chunk watch manager: streams S21 chunk data, S22 multi-block deltas and S26 bulk loads to watching players.

net/minecraft/server/management/PlayerManager.java

Updated 2026-09-12

Deep Analysis

Chunk-subscription manager mapping players to PlayerInstance watchers. Fans out block deltas only to watchers of that chunk. Uses playerViewRadius 3-32 for subscription square. Batches changes per tick into single, multi, or full-chunk packets.

Key Methods in Depth (8)

markBlockForUpdate

Flag single block coordinate for next tick flush.

This method maps a world BlockPos to its chunk watcher and queues a delta. It derives chunk X and Z by arithmetic right shift 4 on block X and Z. It looks up the PlayerInstance with getPlayerInstance without creation, so unloaded chunks get no queue. If the instance exists it calls flagChunkForUpdate with local coordinates using bitwise and 15 for X and Z plus full Y. That call records the packed short and sets Y section flags for later S21 use. No S23 S22 or S21 packet is built here. The eventual choice depends on accumulated count: one becomes S23, two to sixty three become S22, sixty four becomes S21. This defers networking to PlayerInstance.onUpdate on the next tick. Chunk-scoped fan-out replaces any global radius broadcast.

    public void markBlockForUpdate(BlockPos pos)
    {
        int i = pos.getX() >> 4;
        int j = pos.getZ() >> 4;
        PlayerManager.PlayerInstance playermanager$playerinstance = this.getPlayerInstance(i, j, false);

        if (playermanager$playerinstance != null)
        {
            playermanager$playerinstance.flagChunkForUpdate(pos.getX() & 15, pos.getY(), pos.getZ() & 15);
        }
    }

The signature takes BlockPos to flag. The shift lines convert block to chunk coordinates. The getPlayerInstance call uses false to avoid creating watchers. The null check ensures only watched chunks queue. The flagChunkForUpdate line passes local x y z for packing. Packet selection is deferred to onUpdate batching.

PlayerInstance.onUpdate

Flush accumulated block changes to chunk watchers.

This is the per-tick flush that converts accumulated block edits into minimal packets. If numBlocksToUpdate is zero it does nothing and returns without networking. If count equals one it decodes the single packed short into world x y z and sends S23PacketBlockChange to chunk watchers. It also sends the tile entity description packet if that block has a tile entity. If count equals sixty four it sends S21PacketChunkData with flagsYAreasToUpdate mask for full chunk resend plus tile entities per dirty section. Otherwise for two to sixty three it sends S22PacketMultiBlockChange with count, short array, and chunk reference plus per-block tile packets. After any branch it resets numBlocksToUpdate and flagsYAreasToUpdate to zero. This 1 versus 2 to 63 versus 64 batching rule minimizes bandwidth. Only players in playersWatchingChunk receive the chosen packet.

        public void onUpdate()
        {
            if (this.numBlocksToUpdate != 0)
            {
                if (this.numBlocksToUpdate == 1)
                {
                    int i = (this.locationOfBlockChange[0] >> 12 & 15) + this.chunkCoords.chunkXPos * 16;
                    int j = this.locationOfBlockChange[0] & 255;
                    int k = (this.locationOfBlockChange[0] >> 8 & 15) + this.chunkCoords.chunkZPos * 16;
                    BlockPos blockpos = new BlockPos(i, j, k);
                    this.sendToAllPlayersWatchingChunk(new S23PacketBlockChange(PlayerManager.this.theWorldServer, blockpos));

                    if (PlayerManager.this.theWorldServer.getBlockState(blockpos).getBlock().hasTileEntity())
                    {
                        this.sendTileToAllPlayersWatchingChunk(PlayerManager.this.theWorldServer.getTileEntity(blockpos));
                    }
                }
                else if (this.numBlocksToUpdate == 64)
                {
                    int i1 = this.chunkCoords.chunkXPos * 16;
                    int k1 = this.chunkCoords.chunkZPos * 16;
                    this.sendToAllPlayersWatchingChunk(new S21PacketChunkData(PlayerManager.this.theWorldServer.getChunkFromChunkCoords(this.chunkCoords.chunkXPos, this.chunkCoords.chunkZPos), false, this.flagsYAreasToUpdate));

                    for (int i2 = 0; i2 < 16; ++i2)
                    {
                        if ((this.flagsYAreasToUpdate & 1 << i2) != 0)
                        {
                            int k2 = i2 << 4;
                            List<TileEntity> list = PlayerManager.this.theWorldServer.getTileEntitiesIn(i1, k2, k1, i1 + 16, k2 + 16, k1 + 16);
                        }
                    }
                }

The method checks numBlocksToUpdate nonzero before branching. The equals one branch decodes packed shorts to world coords and builds S23PacketBlockChange. The tile check adds description packets for containers. The equals 64 branch builds S21PacketChunkData with Y mask for full resend. The loop over 16 sections gathers tile entities per dirty slice. The missing tail handles 2 to 63 via S22 multi change.

PlayerInstance.sendToAllPlayersWatchingChunk

Chunk-scoped fan-out excluding fully loaded senders.

This helper implements chunk-scoped fan-out for all block delta packets. It iterates playersWatchingChunk by index for the owning PlayerInstance. For each EntityPlayerMP it checks whether loadedChunks contains the chunkCoords. If the player already fully loaded the chunk via the load queue, the packet is skipped to avoid duplicate S21 or delta spam. Otherwise it sends the supplied Packet directly via playerNetServerHandler.sendPacket. No distance math with 16.0D or 1024.0D is performed because subscription implies proximity. The same Packet instance is reused across recipients, whether S23 single, S22 multi, or S21 chunk. This exclusion of fully loaded senders prevents echo during initial chunk burst. All networking for onUpdate flows through this single choke point.

        public void sendToAllPlayersWatchingChunk(Packet thePacket)
        {
            for (int i = 0; i < this.playersWatchingChunk.size(); ++i)
            {
                EntityPlayerMP entityplayermp = (EntityPlayerMP)this.playersWatchingChunk.get(i);

                if (!entityplayermp.loadedChunks.contains(this.chunkCoords))
                {
                    entityplayermp.playerNetServerHandler.sendPacket(thePacket);
                }
            }
        }

The signature takes a generic Packet to share. The for loop walks playersWatchingChunk for this chunk. The loadedChunks contains check skips players still in initial burst. The sendPacket line delivers the same S23 S22 or S21 instance to qualifiers. No radius or dimension check appears. This is pure subscription-based fan-out.

addPlayer

Subscribe player to all chunk instances in view square.

This method subscribes a joining or teleporting player to all nearby chunk watchers. It computes central chunk XZ from posX and posZ with right shift 4. It stores managedPosX and managedPosZ as the subscription origin for later movement diffs. It then loops a square from center minus playerViewRadius to center plus radius in both axes. For each coordinate it calls getPlayerInstance with true to create the instance if absent, which also loads the chunk. It then calls addPlayer on that instance to add the player to playersWatchingChunk and loadedChunks queue. After the square it adds the player to the global players list. It finally calls filterChunkLoadQueue to order pending S21 chunk data sends in spiral priority. The radius is clamped 3 to 32 elsewhere.

    public void addPlayer(EntityPlayerMP player)
    {
        int i = (int)player.posX >> 4;
        int j = (int)player.posZ >> 4;
        player.managedPosX = player.posX;
        player.managedPosZ = player.posZ;

        for (int k = i - this.playerViewRadius; k <= i + this.playerViewRadius; ++k)
        {
            for (int l = j - this.playerViewRadius; l <= j + this.playerViewRadius; ++l)
            {
                this.getPlayerInstance(k, l, true).addPlayer(player);
            }
        }

        this.players.add(player);
        this.filterChunkLoadQueue(player);
    }

The signature takes the joining EntityPlayerMP. The shift lines derive central chunk XZ. The managedPos lines snapshot origin for movement checks. The nested loops cover the view radius square and force-create instances. The addPlayer call subscribes to each chunk watcher. The final lines register globally and reorder load queue for S21 sends.

removePlayer

Unsubscribe player and unload empty chunks.

This method unsubscribes a leaving player and unloads now-empty chunks. It derives the origin chunk from managedPosX and managedPosZ, not live pos, to cover the subscribed square. It loops the same view radius square around that managed origin. For each coordinate it fetches the PlayerInstance without creation. If non-null it calls removePlayer on the instance to drop the player from watchers and loadedChunks. When an instance becomes empty, that inner method sends S21PacketChunkData unload, drops the chunk, and removes the instance maps. After the loops it removes the player from the global players list. This ensures no ghost watchers remain after logout or dimension change. The S21 unload packet tells the client to discard chunk data.

    public void removePlayer(EntityPlayerMP player)
    {
        int i = (int)player.managedPosX >> 4;
        int j = (int)player.managedPosZ >> 4;

        for (int k = i - this.playerViewRadius; k <= i + this.playerViewRadius; ++k)
        {
            for (int l = j - this.playerViewRadius; l <= j + this.playerViewRadius; ++l)
            {
                PlayerManager.PlayerInstance playermanager$playerinstance = this.getPlayerInstance(k, l, false);

                if (playermanager$playerinstance != null)
                {
                    playermanager$playerinstance.removePlayer(player);
                }
            }
        }

        this.players.remove(player);
    }

The signature takes the departing EntityPlayerMP. The managedPos shift lines recover the subscribed center. The nested loops visit every watcher in the square without creating new ones. The null check plus removePlayer call handles unsubscribe and empty-chunk S21 unload. The final remove drops the global reference. This mirrors addPlayer subscription logic.

updatePlayerInstances

Tick dirty chunk instances each server tick.

This per-tick driver flushes dirty chunk instances for block deltas. It reads total world time and compares to previousTotalWorldTime. If more than 8000 ticks elapsed it does a full pass over playerInstanceList calling onUpdate plus processChunk for inhabited time. Otherwise it only iterates playerInstancesToUpdate, which holds instances flagged by markBlockForUpdate. After either path it clears playerInstancesToUpdate to reset dirty state. If the players list is empty and the provider cannot respawn here, it unloads all chunks to save memory. This method is called from WorldServer.tick chunkMap section. It is the indirect source of S23 for one change, S22 for two to sixty three, and S21 for sixty four. No radius check occurs because watchers define recipients.

    public void updatePlayerInstances()
    {
        long i = this.theWorldServer.getTotalWorldTime();

        if (i - this.previousTotalWorldTime > 8000L)
        {
            this.previousTotalWorldTime = i;

            for (int j = 0; j < this.playerInstanceList.size(); ++j)
            {
                PlayerManager.PlayerInstance playermanager$playerinstance = (PlayerManager.PlayerInstance)this.playerInstanceList.get(j);
                playermanager$playerinstance.onUpdate();
                playermanager$playerinstance.processChunk();
            }
        }
        else
        {
            for (int k = 0; k < this.playerInstancesToUpdate.size(); ++k)
            {
                PlayerManager.PlayerInstance playermanager$playerinstance1 = (PlayerManager.PlayerInstance)this.playerInstancesToUpdate.get(k);
                playermanager$playerinstance1.onUpdate();
            }
        }

        this.playerInstancesToUpdate.clear();

        if (this.players.isEmpty())
        {
            WorldProvider worldprovider = this.theWorldServer.provider;
        }

The signature takes no args and reads world time. The greater than 8000L branch does full onUpdate plus inhabited time. The else branch flushes only dirty instances queued for S23 S22 S21. The clear call resets the dirty list each tick. The trailing players empty check leads to unload when no viewers remain. This shows tick-driven batched flushing.

updateMountedMovingPlayer

Update subscriptions after fast vehicle movement.

This method updates chunk subscriptions after fast vehicle movement like boats or minecarts. It computes current chunk XZ from live posX posZ and the delta from managedPosX managedPosZ. It calculates squared movement d2 and only proceeds if at least 64.0D, which equals 8 blocks. It then derives old managed chunk and view radius plus delta in chunks j1 k1. If no chunk changed it returns without networking. Otherwise it loops the new view square, adding the player to instances not overlapping the old square. It also loops to remove from old instances not overlapping the new square. It finally calls filterChunkLoadQueue and snaps managedPos to live pos. This diff avoids resubscribing the entire square on small moves. New chunks trigger S21 loads while stale ones trigger S21 unloads.

    public void updateMountedMovingPlayer(EntityPlayerMP player)
    {
        int i = (int)player.posX >> 4;
        int j = (int)player.posZ >> 4;
        double d0 = player.managedPosX - player.posX;
        double d1 = player.managedPosZ - player.posZ;
        double d2 = d0 * d0 + d1 * d1;

        if (d2 >= 64.0D)
        {
            int k = (int)player.managedPosX >> 4;
            int l = (int)player.managedPosZ >> 4;
            int i1 = this.playerViewRadius;
            int j1 = i - k;
            int k1 = j - l;

            if (j1 != 0 || k1 != 0)
            {
                for (int l1 = i - i1; l1 <= i + i1; ++l1)
                {
                    for (int i2 = j - i1; i2 <= j + i1; ++i2)
                    {
                        if (!this.overlaps(l1, i2, k, l, i1))
                        {
                            this.getPlayerInstance(l1, i2, true).addPlayer(player);
                        }

                        if (!this.overlaps(l1 - j1, i2 - k1, i, j, i1))
                        {
                            PlayerManager.PlayerInstance playermanager$playerinstance = this.getPlayerInstance(l1 - j1, i2 - k1, false);

                            if (playermanager$playerinstance != null)
                            {
                                playermanager$playerinstance.removePlayer(player);
                            }
                        }
                    }
                }
            }
        }

The signature takes the mounted EntityPlayerMP. The chunk and delta lines compute movement squared. The greater than equals 64.0D gate equals 8 blocks before work. The j1 k1 check ensures a chunk boundary crossed. The nested loops add new watchers and remove stale ones via overlaps tests. Later lines reorder load queue and snap managedPos. This is differential S21 subscription update.

filterChunkLoadQueue

Reorder pending chunk loads in spiral around player.

This method reorders a player pending chunk load queue into spiral priority around the player. It copies loadedChunks to a temp list then clears the live queue. It computes view radius, central chunk XZ, and fetches the center PlayerInstance chunkCoords. If the old list contained the center it is added first for immediate S21 send. It then walks outward rings using xzDirectionsConst east south west north vectors with expanding step counts up to twice radius. Each visited coordinate is resolved to its PlayerInstance chunkCoords and re-added if previously queued. A final straight tail fills remaining edge chunks. This ordering makes closest chunks load first on login or teleport. The S21 chunk data sends later follow this queue order. No packets are built here, only queue order.

    public void filterChunkLoadQueue(EntityPlayerMP player)
    {
        List<ChunkCoordIntPair> list = Lists.newArrayList(player.loadedChunks);
        int i = 0;
        int j = this.playerViewRadius;
        int k = (int)player.posX >> 4;
        int l = (int)player.posZ >> 4;
        int i1 = 0;
        int j1 = 0;
        ChunkCoordIntPair chunkcoordintpair = this.getPlayerInstance(k, l, true).chunkCoords;
        player.loadedChunks.clear();

        if (list.contains(chunkcoordintpair))
        {
            player.loadedChunks.add(chunkcoordintpair);
        }

        for (int k1 = 1; k1 <= j * 2; ++k1)
        {
            for (int l1 = 0; l1 < 2; ++l1)
            {
                int[] aint = this.xzDirectionsConst[i++ % 4];

                for (int i2 = 0; i2 < k1; ++i2)
                {
                    i1 += aint[0];
                    j1 += aint[1];
                    chunkcoordintpair = this.getPlayerInstance(k + i1, l + j1, true).chunkCoords;

                    if (list.contains(chunkcoordintpair))
                    {
                        player.loadedChunks.add(chunkcoordintpair);
                    }
                }
            }
        }

The signature takes the player whose queue is rebuilt. The copy plus clear lines snapshot and reset pending chunks. The center fetch plus contains check prioritizes the standing chunk. The nested k1 l1 loops walk the xzDirectionsConst spiral outward. Each step resolves chunkCoords and re-adds if previously pending. This controls S21 send order without sending directly.

Packet Usage

PacketDirTrigger
S23sentonUpdate single block change to watchers
S22sentonUpdate 2-63 block changes to watchers
S21sentonUpdate 64 changes or chunk load/unload

Internal State

playerInstancesLongHashMap chunkKey to PlayerInstance watcher set
playersAll players managed in this dimension/world
playerViewRadiusClamped 3-32 subscription square radius in chunks
playerInstancesToUpdateDirty instances with pending block changes
theWorldServerOwning dimension for chunk provider access

Related Vanilla Internals

Full Source

PlayerManager.java539 lines · MCP 1.8.9 · verbatimOriginal ↗
1
package net.minecraft.server.management;
2
3
import com.google.common.collect.Lists;
4
import java.util.List;
5
import net.minecraft.entity.player.EntityPlayerMP;
6
import net.minecraft.network.Packet;
7
import net.minecraft.network.play.server.S21PacketChunkData;
8
import net.minecraft.network.play.server.S22PacketMultiBlockChange;
9
import net.minecraft.network.play.server.S23PacketBlockChange;
10
import net.minecraft.tileentity.TileEntity;
11
import net.minecraft.util.BlockPos;
12
import net.minecraft.util.LongHashMap;
13
import net.minecraft.util.MathHelper;
14
import net.minecraft.world.ChunkCoordIntPair;
15
import net.minecraft.world.WorldProvider;
16
import net.minecraft.world.WorldServer;
17
import net.minecraft.world.chunk.Chunk;
18
import org.apache.logging.log4j.LogManager;
19
import org.apache.logging.log4j.Logger;
20
21
public class PlayerManager
22
{
23
    private static final Logger pmLogger = LogManager.getLogger();
24
    private final WorldServer theWorldServer;
25
    private final List<EntityPlayerMP> players = Lists.<EntityPlayerMP>newArrayList();
26
    private final LongHashMap<PlayerManager.PlayerInstance> playerInstances = new LongHashMap();
27
    private final List<PlayerManager.PlayerInstance> playerInstancesToUpdate = Lists.<PlayerManager.PlayerInstance>newArrayList();
28
    private final List<PlayerManager.PlayerInstance> playerInstanceList = Lists.<PlayerManager.PlayerInstance>newArrayList();
29
30
    /**
31
     * Number of chunks the server sends to the client. Valid 3<=x<=15. In server.properties.
32
     */
33
    private int playerViewRadius;
34
35
    /** time what is using to check if InhabitedTime should be calculated */
36
    private long previousTotalWorldTime;
37
38
    /** x, z direction vectors: east, south, west, north */
39
    private final int[][] xzDirectionsConst = new int[][] {{1, 0}, {0, 1}, { -1, 0}, {0, -1}};
40
41
    public PlayerManager(WorldServer serverWorld)
42
    {
43
        this.theWorldServer = serverWorld;
44
        this.setPlayerViewRadius(serverWorld.getMinecraftServer().getConfigurationManager().getViewDistance());
45
    }
46
47
    /**
48
     * Returns the WorldServer associated with this PlayerManager
49
     */
50
    public WorldServer getWorldServer()
51
    {
52
        return this.theWorldServer;
53
    }
54
55
    /**
56
     * updates all the player instances that need to be updated
57
     */
58
    public void updatePlayerInstances()
59
    {
60
        long i = this.theWorldServer.getTotalWorldTime();
61
62
        if (i - this.previousTotalWorldTime > 8000L)
63
        {
64
            this.previousTotalWorldTime = i;
65
66
            for (int j = 0; j < this.playerInstanceList.size(); ++j)
67
            {
68
                PlayerManager.PlayerInstance playermanager$playerinstance = (PlayerManager.PlayerInstance)this.playerInstanceList.get(j);
69
                playermanager$playerinstance.onUpdate();
70
                playermanager$playerinstance.processChunk();
71
            }
72
        }
73
        else
74
        {
75
            for (int k = 0; k < this.playerInstancesToUpdate.size(); ++k)
76
            {
77
                PlayerManager.PlayerInstance playermanager$playerinstance1 = (PlayerManager.PlayerInstance)this.playerInstancesToUpdate.get(k);
78
                playermanager$playerinstance1.onUpdate();
79
            }
80
        }
81
82
        this.playerInstancesToUpdate.clear();
83
84
        if (this.players.isEmpty())
85
        {
86
            WorldProvider worldprovider = this.theWorldServer.provider;
87
88
            if (!worldprovider.canRespawnHere())
89
            {
90
                this.theWorldServer.theChunkProviderServer.unloadAllChunks();
91
            }
92
        }
93
    }
94
95
    public boolean hasPlayerInstance(int chunkX, int chunkZ)
96
    {
97
        long i = (long)chunkX + 2147483647L | (long)chunkZ + 2147483647L << 32;
98
        return this.playerInstances.getValueByKey(i) != null;
99
    }
100
101
    /**
102
     * passi n the chunk x and y and a flag as to whether or not the instance should be made if it doesnt exist
103
     */
104
    private PlayerManager.PlayerInstance getPlayerInstance(int chunkX, int chunkZ, boolean createIfAbsent)
105
    {
106
        long i = (long)chunkX + 2147483647L | (long)chunkZ + 2147483647L << 32;
107
        PlayerManager.PlayerInstance playermanager$playerinstance = (PlayerManager.PlayerInstance)this.playerInstances.getValueByKey(i);
108
109
        if (playermanager$playerinstance == null && createIfAbsent)
110
        {
111
            playermanager$playerinstance = new PlayerManager.PlayerInstance(chunkX, chunkZ);
112
            this.playerInstances.add(i, playermanager$playerinstance);
113
            this.playerInstanceList.add(playermanager$playerinstance);
114
        }
115
116
        return playermanager$playerinstance;
117
    }
118
119
    public void markBlockForUpdate(BlockPos pos)
120
    {
121
        int i = pos.getX() >> 4;
122
        int j = pos.getZ() >> 4;
123
        PlayerManager.PlayerInstance playermanager$playerinstance = this.getPlayerInstance(i, j, false);
124
125
        if (playermanager$playerinstance != null)
126
        {
127
            playermanager$playerinstance.flagChunkForUpdate(pos.getX() & 15, pos.getY(), pos.getZ() & 15);
128
        }
129
    }
130
131
    /**
132
     * Adds an EntityPlayerMP to the PlayerManager and to all player instances within player visibility
133
     */
134
    public void addPlayer(EntityPlayerMP player)
135
    {
136
        int i = (int)player.posX >> 4;
137
        int j = (int)player.posZ >> 4;
138
        player.managedPosX = player.posX;
139
        player.managedPosZ = player.posZ;
140
141
        for (int k = i - this.playerViewRadius; k <= i + this.playerViewRadius; ++k)
142
        {
143
            for (int l = j - this.playerViewRadius; l <= j + this.playerViewRadius; ++l)
144
            {
145
                this.getPlayerInstance(k, l, true).addPlayer(player);
146
            }
147
        }
148
149
        this.players.add(player);
150
        this.filterChunkLoadQueue(player);
151
    }
152
153
    /**
154
     * Removes all chunks from the given player's chunk load queue that are not in viewing range of the player.
155
     */
156
    public void filterChunkLoadQueue(EntityPlayerMP player)
157
    {
158
        List<ChunkCoordIntPair> list = Lists.newArrayList(player.loadedChunks);
159
        int i = 0;
160
        int j = this.playerViewRadius;
161
        int k = (int)player.posX >> 4;
162
        int l = (int)player.posZ >> 4;
163
        int i1 = 0;
164
        int j1 = 0;
165
        ChunkCoordIntPair chunkcoordintpair = this.getPlayerInstance(k, l, true).chunkCoords;
166
        player.loadedChunks.clear();
167
168
        if (list.contains(chunkcoordintpair))
169
        {
170
            player.loadedChunks.add(chunkcoordintpair);
171
        }
172
173
        for (int k1 = 1; k1 <= j * 2; ++k1)
174
        {
175
            for (int l1 = 0; l1 < 2; ++l1)
176
            {
177
                int[] aint = this.xzDirectionsConst[i++ % 4];
178
179
                for (int i2 = 0; i2 < k1; ++i2)
180
                {
181
                    i1 += aint[0];
182
                    j1 += aint[1];
183
                    chunkcoordintpair = this.getPlayerInstance(k + i1, l + j1, true).chunkCoords;
184
185
                    if (list.contains(chunkcoordintpair))
186
                    {
187
                        player.loadedChunks.add(chunkcoordintpair);
188
                    }
189
                }
190
            }
191
        }
192
193
        i = i % 4;
194
195
        for (int j2 = 0; j2 < j * 2; ++j2)
196
        {
197
            i1 += this.xzDirectionsConst[i][0];
198
            j1 += this.xzDirectionsConst[i][1];
199
            chunkcoordintpair = this.getPlayerInstance(k + i1, l + j1, true).chunkCoords;
200
201
            if (list.contains(chunkcoordintpair))
202
            {
203
                player.loadedChunks.add(chunkcoordintpair);
204
            }
205
        }
206
    }
207
208
    /**
209
     * Removes an EntityPlayerMP from the PlayerManager.
210
     */
211
    public void removePlayer(EntityPlayerMP player)
212
    {
213
        int i = (int)player.managedPosX >> 4;
214
        int j = (int)player.managedPosZ >> 4;
215
216
        for (int k = i - this.playerViewRadius; k <= i + this.playerViewRadius; ++k)
217
        {
218
            for (int l = j - this.playerViewRadius; l <= j + this.playerViewRadius; ++l)
219
            {
220
                PlayerManager.PlayerInstance playermanager$playerinstance = this.getPlayerInstance(k, l, false);
221
222
                if (playermanager$playerinstance != null)
223
                {
224
                    playermanager$playerinstance.removePlayer(player);
225
                }
226
            }
227
        }
228
229
        this.players.remove(player);
230
    }
231
232
    /**
233
     * Determine if two rectangles centered at the given points overlap for the provided radius. Arguments: x1, z1, x2,
234
     * z2, radius.
235
     */
236
    private boolean overlaps(int x1, int z1, int x2, int z2, int radius)
237
    {
238
        int i = x1 - x2;
239
        int j = z1 - z2;
240
        return i >= -radius && i <= radius ? j >= -radius && j <= radius : false;
241
    }
242
243
    /**
244
     * update chunks around a player being moved by server logic (e.g. cart, boat)
245
     */
246
    public void updateMountedMovingPlayer(EntityPlayerMP player)
247
    {
248
        int i = (int)player.posX >> 4;
249
        int j = (int)player.posZ >> 4;
250
        double d0 = player.managedPosX - player.posX;
251
        double d1 = player.managedPosZ - player.posZ;
252
        double d2 = d0 * d0 + d1 * d1;
253
254
        if (d2 >= 64.0D)
255
        {
256
            int k = (int)player.managedPosX >> 4;
257
            int l = (int)player.managedPosZ >> 4;
258
            int i1 = this.playerViewRadius;
259
            int j1 = i - k;
260
            int k1 = j - l;
261
262
            if (j1 != 0 || k1 != 0)
263
            {
264
                for (int l1 = i - i1; l1 <= i + i1; ++l1)
265
                {
266
                    for (int i2 = j - i1; i2 <= j + i1; ++i2)
267
                    {
268
                        if (!this.overlaps(l1, i2, k, l, i1))
269
                        {
270
                            this.getPlayerInstance(l1, i2, true).addPlayer(player);
271
                        }
272
273
                        if (!this.overlaps(l1 - j1, i2 - k1, i, j, i1))
274
                        {
275
                            PlayerManager.PlayerInstance playermanager$playerinstance = this.getPlayerInstance(l1 - j1, i2 - k1, false);
276
277
                            if (playermanager$playerinstance != null)
278
                            {
279
                                playermanager$playerinstance.removePlayer(player);
280
                            }
281
                        }
282
                    }
283
                }
284
285
                this.filterChunkLoadQueue(player);
286
                player.managedPosX = player.posX;
287
                player.managedPosZ = player.posZ;
288
            }
289
        }
290
    }
291
292
    public boolean isPlayerWatchingChunk(EntityPlayerMP player, int chunkX, int chunkZ)
293
    {
294
        PlayerManager.PlayerInstance playermanager$playerinstance = this.getPlayerInstance(chunkX, chunkZ, false);
295
        return playermanager$playerinstance != null && playermanager$playerinstance.playersWatchingChunk.contains(player) && !player.loadedChunks.contains(playermanager$playerinstance.chunkCoords);
296
    }
297
298
    public void setPlayerViewRadius(int radius)
299
    {
300
        radius = MathHelper.clamp_int(radius, 3, 32);
301
302
        if (radius != this.playerViewRadius)
303
        {
304
            int i = radius - this.playerViewRadius;
305
306
            for (EntityPlayerMP entityplayermp : Lists.newArrayList(this.players))
307
            {
308
                int j = (int)entityplayermp.posX >> 4;
309
                int k = (int)entityplayermp.posZ >> 4;
310
311
                if (i > 0)
312
                {
313
                    for (int j1 = j - radius; j1 <= j + radius; ++j1)
314
                    {
315
                        for (int k1 = k - radius; k1 <= k + radius; ++k1)
316
                        {
317
                            PlayerManager.PlayerInstance playermanager$playerinstance = this.getPlayerInstance(j1, k1, true);
318
319
                            if (!playermanager$playerinstance.playersWatchingChunk.contains(entityplayermp))
320
                            {
321
                                playermanager$playerinstance.addPlayer(entityplayermp);
322
                            }
323
                        }
324
                    }
325
                }
326
                else
327
                {
328
                    for (int l = j - this.playerViewRadius; l <= j + this.playerViewRadius; ++l)
329
                    {
330
                        for (int i1 = k - this.playerViewRadius; i1 <= k + this.playerViewRadius; ++i1)
331
                        {
332
                            if (!this.overlaps(l, i1, j, k, radius))
333
                            {
334
                                this.getPlayerInstance(l, i1, true).removePlayer(entityplayermp);
335
                            }
336
                        }
337
                    }
338
                }
339
            }
340
341
            this.playerViewRadius = radius;
342
        }
343
    }
344
345
    /**
346
     * Get the furthest viewable block given player's view distance
347
     */
348
    public static int getFurthestViewableBlock(int distance)
349
    {
350
        return distance * 16 - 16;
351
    }
352
353
    class PlayerInstance
354
    {
355
        private final List<EntityPlayerMP> playersWatchingChunk = Lists.<EntityPlayerMP>newArrayList();
356
        private final ChunkCoordIntPair chunkCoords;
357
        private short[] locationOfBlockChange = new short[64];
358
        private int numBlocksToUpdate;
359
        private int flagsYAreasToUpdate;
360
        private long previousWorldTime;
361
362
        public PlayerInstance(int chunkX, int chunkZ)
363
        {
364
            this.chunkCoords = new ChunkCoordIntPair(chunkX, chunkZ);
365
            PlayerManager.this.getWorldServer().theChunkProviderServer.loadChunk(chunkX, chunkZ);
366
        }
367
368
        public void addPlayer(EntityPlayerMP player)
369
        {
370
            if (this.playersWatchingChunk.contains(player))
371
            {
372
                PlayerManager.pmLogger.debug("Failed to add player. {} already is in chunk {}, {}", new Object[] {player, Integer.valueOf(this.chunkCoords.chunkXPos), Integer.valueOf(this.chunkCoords.chunkZPos)});
373
            }
374
            else
375
            {
376
                if (this.playersWatchingChunk.isEmpty())
377
                {
378
                    this.previousWorldTime = PlayerManager.this.theWorldServer.getTotalWorldTime();
379
                }
380
381
                this.playersWatchingChunk.add(player);
382
                player.loadedChunks.add(this.chunkCoords);
383
            }
384
        }
385
386
        public void removePlayer(EntityPlayerMP player)
387
        {
388
            if (this.playersWatchingChunk.contains(player))
389
            {
390
                Chunk chunk = PlayerManager.this.theWorldServer.getChunkFromChunkCoords(this.chunkCoords.chunkXPos, this.chunkCoords.chunkZPos);
391
392
                if (chunk.isPopulated())
393
                {
394
                    player.playerNetServerHandler.sendPacket(new S21PacketChunkData(chunk, true, 0));
395
                }
396
397
                this.playersWatchingChunk.remove(player);
398
                player.loadedChunks.remove(this.chunkCoords);
399
400
                if (this.playersWatchingChunk.isEmpty())
401
                {
402
                    long i = (long)this.chunkCoords.chunkXPos + 2147483647L | (long)this.chunkCoords.chunkZPos + 2147483647L << 32;
403
                    this.increaseInhabitedTime(chunk);
404
                    PlayerManager.this.playerInstances.remove(i);
405
                    PlayerManager.this.playerInstanceList.remove(this);
406
407
                    if (this.numBlocksToUpdate > 0)
408
                    {
409
                        PlayerManager.this.playerInstancesToUpdate.remove(this);
410
                    }
411
412
                    PlayerManager.this.getWorldServer().theChunkProviderServer.dropChunk(this.chunkCoords.chunkXPos, this.chunkCoords.chunkZPos);
413
                }
414
            }
415
        }
416
417
        public void processChunk()
418
        {
419
            this.increaseInhabitedTime(PlayerManager.this.theWorldServer.getChunkFromChunkCoords(this.chunkCoords.chunkXPos, this.chunkCoords.chunkZPos));
420
        }
421
422
        private void increaseInhabitedTime(Chunk theChunk)
423
        {
424
            theChunk.setInhabitedTime(theChunk.getInhabitedTime() + PlayerManager.this.theWorldServer.getTotalWorldTime() - this.previousWorldTime);
425
            this.previousWorldTime = PlayerManager.this.theWorldServer.getTotalWorldTime();
426
        }
427
428
        public void flagChunkForUpdate(int x, int y, int z)
429
        {
430
            if (this.numBlocksToUpdate == 0)
431
            {
432
                PlayerManager.this.playerInstancesToUpdate.add(this);
433
            }
434
435
            this.flagsYAreasToUpdate |= 1 << (y >> 4);
436
437
            if (this.numBlocksToUpdate < 64)
438
            {
439
                short short1 = (short)(x << 12 | z << 8 | y);
440
441
                for (int i = 0; i < this.numBlocksToUpdate; ++i)
442
                {
443
                    if (this.locationOfBlockChange[i] == short1)
444
                    {
445
                        return;
446
                    }
447
                }
448
449
                this.locationOfBlockChange[this.numBlocksToUpdate++] = short1;
450
            }
451
        }
452
453
        public void sendToAllPlayersWatchingChunk(Packet thePacket)
454
        {
455
            for (int i = 0; i < this.playersWatchingChunk.size(); ++i)
456
            {
457
                EntityPlayerMP entityplayermp = (EntityPlayerMP)this.playersWatchingChunk.get(i);
458
459
                if (!entityplayermp.loadedChunks.contains(this.chunkCoords))
460
                {
461
                    entityplayermp.playerNetServerHandler.sendPacket(thePacket);
462
                }
463
            }
464
        }
465
466
        public void onUpdate()
467
        {
468
            if (this.numBlocksToUpdate != 0)
469
            {
470
                if (this.numBlocksToUpdate == 1)
471
                {
472
                    int i = (this.locationOfBlockChange[0] >> 12 & 15) + this.chunkCoords.chunkXPos * 16;
473
                    int j = this.locationOfBlockChange[0] & 255;
474
                    int k = (this.locationOfBlockChange[0] >> 8 & 15) + this.chunkCoords.chunkZPos * 16;
475
                    BlockPos blockpos = new BlockPos(i, j, k);
476
                    this.sendToAllPlayersWatchingChunk(new S23PacketBlockChange(PlayerManager.this.theWorldServer, blockpos));
477
478
                    if (PlayerManager.this.theWorldServer.getBlockState(blockpos).getBlock().hasTileEntity())
479
                    {
480
                        this.sendTileToAllPlayersWatchingChunk(PlayerManager.this.theWorldServer.getTileEntity(blockpos));
481
                    }
482
                }
483
                else if (this.numBlocksToUpdate == 64)
484
                {
485
                    int i1 = this.chunkCoords.chunkXPos * 16;
486
                    int k1 = this.chunkCoords.chunkZPos * 16;
487
                    this.sendToAllPlayersWatchingChunk(new S21PacketChunkData(PlayerManager.this.theWorldServer.getChunkFromChunkCoords(this.chunkCoords.chunkXPos, this.chunkCoords.chunkZPos), false, this.flagsYAreasToUpdate));
488
489
                    for (int i2 = 0; i2 < 16; ++i2)
490
                    {
491
                        if ((this.flagsYAreasToUpdate & 1 << i2) != 0)
492
                        {
493
                            int k2 = i2 << 4;
494
                            List<TileEntity> list = PlayerManager.this.theWorldServer.getTileEntitiesIn(i1, k2, k1, i1 + 16, k2 + 16, k1 + 16);
495
496
                            for (int l = 0; l < list.size(); ++l)
497
                            {
498
                                this.sendTileToAllPlayersWatchingChunk((TileEntity)list.get(l));
499
                            }
500
                        }
501
                    }
502
                }
503
                else
504
                {
505
                    this.sendToAllPlayersWatchingChunk(new S22PacketMultiBlockChange(this.numBlocksToUpdate, this.locationOfBlockChange, PlayerManager.this.theWorldServer.getChunkFromChunkCoords(this.chunkCoords.chunkXPos, this.chunkCoords.chunkZPos)));
506
507
                    for (int j1 = 0; j1 < this.numBlocksToUpdate; ++j1)
508
                    {
509
                        int l1 = (this.locationOfBlockChange[j1] >> 12 & 15) + this.chunkCoords.chunkXPos * 16;
510
                        int j2 = this.locationOfBlockChange[j1] & 255;
511
                        int l2 = (this.locationOfBlockChange[j1] >> 8 & 15) + this.chunkCoords.chunkZPos * 16;
512
                        BlockPos blockpos1 = new BlockPos(l1, j2, l2);
513
514
                        if (PlayerManager.this.theWorldServer.getBlockState(blockpos1).getBlock().hasTileEntity())
515
                        {
516
                            this.sendTileToAllPlayersWatchingChunk(PlayerManager.this.theWorldServer.getTileEntity(blockpos1));
517
                        }
518
                    }
519
                }
520
521
                this.numBlocksToUpdate = 0;
522
                this.flagsYAreasToUpdate = 0;
523
            }
524
        }
525
526
        private void sendTileToAllPlayersWatchingChunk(TileEntity theTileEntity)
527
        {
528
            if (theTileEntity != null)
529
            {
530
                Packet packet = theTileEntity.getDescriptionPacket();
531
532
                if (packet != null)
533
                {
534
                    this.sendToAllPlayersWatchingChunk(packet);
535
                }
536
            }
537
        }
538
    }
539
}

Deobfuscated MCP 1.8.9 source of PlayerManager from Marcelektro/MavenMCP-1.8.9 (net/minecraft/server/management/PlayerManager.java), stored verbatim.