From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
From: Aikar <aikar@aikar.co>
Date: Thu, 26 Jul 2018 00:11:12 -0400
Subject: [PATCH] Prevent Saving Bad entities to chunks

See https://github.com/PaperMC/Paper/issues/1223

Minecraft is saving invalid entities to the chunk files.

Avoid saving bad data, and also make improvements to handle
loading these chunks. Any invalid entity will be instant killed,
so lets avoid adding it to the world...

This lets us be safer about the dupe UUID resolver too, as now
we can ignore instant killed entities and avoid risk of duplicating
an invalid entity.

This should reduce log occurrences of dupe uuid messages.

1.17, not a concern anymore

diff --git a/src/main/java/net/minecraft/server/level/ServerLevel.java b/src/main/java/net/minecraft/server/level/ServerLevel.java
index a5d7781b13a6d61238d026f064512f7162e1e868..8e8e5f30c512ed7d8ee987550c22d3e9df845043 100644
--- a/src/main/java/net/minecraft/server/level/ServerLevel.java
+++ b/src/main/java/net/minecraft/server/level/ServerLevel.java
@@ -1151,6 +1151,7 @@ public class ServerLevel extends net.minecraft.world.level.Level implements Worl
         List[] aentityslice = chunk.getEntitySlices(); // Spigot
         int i = aentityslice.length;
 
+        java.util.List<Entity> toMoveChunks = new java.util.ArrayList<>(); // Paper
         for (int j = 0; j < i; ++j) {
             List<Entity> entityslice = aentityslice[j]; // Spigot
             Iterator iterator = entityslice.iterator();
@@ -1163,11 +1164,25 @@ public class ServerLevel extends net.minecraft.world.level.Level implements Worl
                         throw (IllegalStateException) Util.pauseInIde((Throwable) (new IllegalStateException("Removing entity while ticking!")));
                     }
 
+                    // Paper start - move out entities that shouldn't be in this chunk before it unloads
+                    if (!entity.removed && (int) Math.floor(entity.getX()) >> 4 != chunk.getPos().x || (int) Math.floor(entity.getZ()) >> 4 != chunk.getPos().z) {
+                        toMoveChunks.add(entity);
+                        continue;
+                    }
+                    // Paper end
+
                     this.entitiesById.remove(entity.getId());
                     this.onEntityRemoved(entity);
+
+                    if (entity.removed) iterator.remove(); // Paper - don't save dead entities during unload
                 }
             }
         }
+        // Paper start - move out entities that shouldn't be in this chunk before it unloads
+        for (Entity entity : toMoveChunks) {
+            this.updateChunkPos(entity);
+        }
+        // Paper end
 
     }
 
diff --git a/src/main/java/net/minecraft/world/level/chunk/storage/ChunkSerializer.java b/src/main/java/net/minecraft/world/level/chunk/storage/ChunkSerializer.java
index 0efaf4d0f58bcf38b427e76bf09b96e354294159..542d6f322df5f44ad9f504c8e14c88e3fa540657 100644
--- a/src/main/java/net/minecraft/world/level/chunk/storage/ChunkSerializer.java
+++ b/src/main/java/net/minecraft/world/level/chunk/storage/ChunkSerializer.java
@@ -27,6 +27,7 @@ import net.minecraft.nbt.LongArrayTag;
 import net.minecraft.nbt.ShortTag;
 import net.minecraft.server.level.ServerChunkCache;
 import net.minecraft.server.level.ServerLevel;
+import net.minecraft.server.level.ServerPlayer;
 import net.minecraft.server.level.ThreadedLevelLightEngine;
 import net.minecraft.world.entity.Entity;
 import net.minecraft.world.entity.EntityType;
@@ -349,6 +350,7 @@ public class ChunkSerializer {
         nbttagcompound1.put("TileEntities", nbttaglist1);
         ListTag nbttaglist2 = new ListTag();
 
+        java.util.List<Entity> toUpdate = new java.util.ArrayList<>(); // Paper
         if (chunk.getStatus().getChunkType() == ChunkStatus.ChunkType.LEVELCHUNK) {
             LevelChunk chunk1 = (LevelChunk) chunk;
 
@@ -366,13 +368,28 @@ public class ChunkSerializer {
                 while (iterator1.hasNext()) {
                     Entity entity = (Entity) iterator1.next();
                     CompoundTag nbttagcompound4 = new CompoundTag();
-
+                    // Paper start
+                    if ((int) Math.floor(entity.getX()) >> 4 != chunk1.getPos().x || (int) Math.floor(entity.getZ()) >> 4 != chunk1.getPos().z) {
+                        toUpdate.add(entity);
+                        continue;
+                    }
+                    if (entity.removed || hasPlayerPassenger(entity)) {
+                        continue;
+                    }
+                    // Paper end
                     if (entity.save(nbttagcompound4)) {
                         chunk1.setLastSaveHadEntities(true);
                         nbttaglist2.add(nbttagcompound4);
                     }
                 }
             }
+
+            // Paper start - move entities to the correct chunk
+            for (Entity entity : toUpdate) {
+                world.updateChunkPos(entity);
+            }
+            // Paper end
+
         } else {
             ProtoChunk protochunk = (ProtoChunk) chunk;
 
@@ -431,6 +448,19 @@ public class ChunkSerializer {
         nbttagcompound1.put("Structures", packStructureData(chunkcoordintpair, chunk.getAllStarts(), chunk.getAllReferences()));
         return nbttagcompound;
     }
+    // Paper start - this is saved with the player
+    private static boolean hasPlayerPassenger(Entity entity) {
+        for (Entity passenger : entity.passengers) {
+            if (passenger instanceof ServerPlayer) {
+                return true;
+            }
+            if (hasPlayerPassenger(passenger)) {
+                return true;
+            }
+        }
+        return false;
+    }
+    // Paper end
 
     public static ChunkStatus.ChunkType getChunkTypeFromTag(@Nullable CompoundTag tag) {
         if (tag != null) {
