From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
From: Aikar <aikar@aikar.co>
Date: Fri, 28 Sep 2018 21:49:53 -0400
Subject: [PATCH] Fix issues with entity loss due to unloaded chunks

Vanilla has risk of losing entities by causing them to be
removed from all chunks if they try to move into an unloaded chunk.

This pretty much means high chance this entity will be lost in this
scenario.

There is another case that adding an entity to the world can fail if
the chunk isn't loaded.

Lots of the server is designed around addEntity never expecting to fail
for these reasons, nor is it really logical.

This change ensures the chunks are always loaded when entities are
added to the world, or a valid entity moves between chunks.

diff --git a/src/main/java/net/minecraft/server/level/ServerLevel.java b/src/main/java/net/minecraft/server/level/ServerLevel.java
index d03b4f97102dfb88927a94ee5a5d397ac493eaa1..99883c83c126405fc93becefed8a1d0727b94aa7 100644
--- a/src/main/java/net/minecraft/server/level/ServerLevel.java
+++ b/src/main/java/net/minecraft/server/level/ServerLevel.java
@@ -848,11 +848,18 @@ public class ServerLevel extends net.minecraft.world.level.Level implements Worl
             int k = Mth.floor(entity.getZ() / 16.0D);
 
             if (!entity.inChunk || entity.xChunk != i || entity.yChunk != j || entity.zChunk != k) {
+                // Paper start - remove entity if its in a chunk more correctly.
+                LevelChunk currentChunk = entity.getCurrentChunk();
+                if (currentChunk != null) {
+                    currentChunk.removeEntity(entity);
+                }
+                // Paper end
+
                 if (entity.inChunk && this.hasChunk(entity.xChunk, entity.zChunk)) {
                     this.getChunk(entity.xChunk, entity.zChunk).removeEntity(entity, entity.yChunk);
                 }
 
-                if (!entity.checkAndResetForcedChunkAdditionFlag() && !this.hasChunk(i, k)) {
+                if (!entity.valid && !entity.checkAndResetForcedChunkAdditionFlag() && !this.hasChunk(i, k)) { // Paper - always load chunks to register valid entities location
                     if (entity.inChunk) {
                         ServerLevel.LOGGER.warn("Entity {} left loaded chunk area", entity);
                     }
@@ -1067,7 +1074,7 @@ public class ServerLevel extends net.minecraft.world.level.Level implements Worl
                 return false;
             }
             // CraftBukkit end
-            ChunkAccess ichunkaccess = this.getChunk(Mth.floor(entity.getX() / 16.0D), Mth.floor(entity.getZ() / 16.0D), ChunkStatus.FULL, entity.forcedLoading);
+            ChunkAccess ichunkaccess = this.getChunk(Mth.floor(entity.getX() / 16.0D), Mth.floor(entity.getZ() / 16.0D), ChunkStatus.FULL, true); // Paper - always load chunks for entity adds
 
             if (!(ichunkaccess instanceof LevelChunk)) {
                 return false;
