--- a/net/minecraft/server/level/EntityPlayer.java
+++ b/net/minecraft/server/level/EntityPlayer.java
@@ -157,6 +157,38 @@
 import net.minecraft.world.scores.criteria.IScoreboardCriteria;
 import org.slf4j.Logger;
 
+// CraftBukkit start
+import net.minecraft.nbt.NBTBase;
+import net.minecraft.world.damagesource.CombatTracker;
+import net.minecraft.world.food.FoodMetaData;
+import net.minecraft.world.item.enchantment.EnchantmentManager;
+import net.minecraft.world.level.block.BlockChest;
+import net.minecraft.world.level.dimension.WorldDimension;
+import net.minecraft.world.scores.Scoreboard;
+import org.bukkit.Bukkit;
+import org.bukkit.Location;
+import org.bukkit.WeatherType;
+import org.bukkit.craftbukkit.CraftWorld;
+import org.bukkit.craftbukkit.CraftWorldBorder;
+import org.bukkit.craftbukkit.entity.CraftPlayer;
+import org.bukkit.craftbukkit.event.CraftEventFactory;
+import org.bukkit.craftbukkit.event.CraftPortalEvent;
+import org.bukkit.craftbukkit.inventory.CraftItemStack;
+import org.bukkit.craftbukkit.util.CraftDimensionUtil;
+import org.bukkit.craftbukkit.util.CraftLocation;
+import org.bukkit.event.entity.EntityExhaustionEvent;
+import org.bukkit.event.player.PlayerBedLeaveEvent;
+import org.bukkit.event.player.PlayerChangedMainHandEvent;
+import org.bukkit.event.player.PlayerChangedWorldEvent;
+import org.bukkit.event.player.PlayerLocaleChangeEvent;
+import org.bukkit.event.player.PlayerPortalEvent;
+import org.bukkit.event.player.PlayerSpawnChangeEvent;
+import org.bukkit.event.player.PlayerTeleportEvent;
+import org.bukkit.event.player.PlayerTeleportEvent.TeleportCause;
+import org.bukkit.event.player.PlayerToggleSneakEvent;
+import org.bukkit.inventory.MainHand;
+// CraftBukkit end
+
 public class EntityPlayer extends EntityHuman {
 
     private static final Logger LOGGER = LogUtils.getLogger();
@@ -192,7 +224,7 @@
     private int levitationStartTime;
     private boolean disconnected;
     private int requestedViewDistance;
-    public String language;
+    public String language = "en_us"; // CraftBukkit - default
     @Nullable
     private Vec3D startingToFallPosition;
     @Nullable
@@ -217,6 +249,20 @@
     private int containerCounter;
     public boolean wonGame;
 
+    // CraftBukkit start
+    public String displayName;
+    public IChatBaseComponent listName;
+    public org.bukkit.Location compassTarget;
+    public int newExp = 0;
+    public int newLevel = 0;
+    public int newTotalExp = 0;
+    public boolean keepLevel = false;
+    public double maxHealthCache;
+    public boolean joining = true;
+    public boolean sentListPacket = false;
+    public String kickLeaveMessage = null; // SPIGOT-3034: Forward leave message to PlayerQuitEvent
+    // CraftBukkit end
+
     public EntityPlayer(MinecraftServer minecraftserver, WorldServer worldserver, GameProfile gameprofile, ClientInformation clientinformation) {
         super(worldserver, worldserver.getSharedSpawnPos(), worldserver.getSharedSpawnAngle(), gameprofile);
         this.chatVisibility = EnumChatVisibility.FULL;
@@ -283,12 +329,56 @@
         this.setMaxUpStep(1.0F);
         this.fudgeSpawnLocation(worldserver);
         this.updateOptions(clientinformation);
+
+        // CraftBukkit start
+        this.displayName = this.getScoreboardName();
+        this.bukkitPickUpLoot = true;
+        this.maxHealthCache = this.getMaxHealth();
+    }
+
+    // Yes, this doesn't match Vanilla, but it's the best we can do for now.
+    // If this is an issue, PRs are welcome
+    public final BlockPosition getSpawnPoint(WorldServer worldserver) {
+        BlockPosition blockposition = worldserver.getSharedSpawnPos();
+
+        if (worldserver.dimensionType().hasSkyLight() && worldserver.serverLevelData.getGameType() != EnumGamemode.ADVENTURE) {
+            int i = Math.max(0, this.server.getSpawnRadius(worldserver));
+            int j = MathHelper.floor(worldserver.getWorldBorder().getDistanceToBorder((double) blockposition.getX(), (double) blockposition.getZ()));
+
+            if (j < i) {
+                i = j;
+            }
+
+            if (j <= 1) {
+                i = 1;
+            }
+
+            long k = (long) (i * 2 + 1);
+            long l = k * k;
+            int i1 = l > 2147483647L ? Integer.MAX_VALUE : (int) l;
+            int j1 = this.getCoprime(i1);
+            int k1 = RandomSource.create().nextInt(i1);
+
+            for (int l1 = 0; l1 < i1; ++l1) {
+                int i2 = (k1 + j1 * l1) % i1;
+                int j2 = i2 % (i * 2 + 1);
+                int k2 = i2 / (i * 2 + 1);
+                BlockPosition blockposition1 = WorldProviderNormal.getOverworldRespawnPos(worldserver, blockposition.getX() + j2 - i, blockposition.getZ() + k2 - i);
+
+                if (blockposition1 != null) {
+                    return blockposition1;
+                }
+            }
+        }
+
+        return blockposition;
     }
+    // CraftBukkit end
 
     private void fudgeSpawnLocation(WorldServer worldserver) {
         BlockPosition blockposition = worldserver.getSharedSpawnPos();
 
-        if (worldserver.dimensionType().hasSkyLight() && worldserver.getServer().getWorldData().getGameType() != EnumGamemode.ADVENTURE) {
+        if (worldserver.dimensionType().hasSkyLight() && worldserver.serverLevelData.getGameType() != EnumGamemode.ADVENTURE) { // CraftBukkit
             int i = Math.max(0, this.server.getSpawnRadius(worldserver));
             int j = MathHelper.floor(worldserver.getWorldBorder().getDistanceToBorder((double) blockposition.getX(), (double) blockposition.getZ()));
 
@@ -337,7 +427,7 @@
     public void readAdditionalSaveData(NBTTagCompound nbttagcompound) {
         super.readAdditionalSaveData(nbttagcompound);
         if (nbttagcompound.contains("warden_spawn_tracker", 10)) {
-            DataResult dataresult = WardenSpawnTracker.CODEC.parse(new Dynamic(DynamicOpsNBT.INSTANCE, nbttagcompound.get("warden_spawn_tracker")));
+            DataResult<WardenSpawnTracker> dataresult = WardenSpawnTracker.CODEC.parse(new Dynamic(DynamicOpsNBT.INSTANCE, nbttagcompound.get("warden_spawn_tracker"))); // CraftBukkit - decompile error
             Logger logger = EntityPlayer.LOGGER;
 
             Objects.requireNonNull(logger);
@@ -356,17 +446,26 @@
         if (nbttagcompound.contains("recipeBook", 10)) {
             this.recipeBook.fromNbt(nbttagcompound.getCompound("recipeBook"), this.server.getRecipeManager());
         }
+        this.getBukkitEntity().readExtraData(nbttagcompound); // CraftBukkit
 
         if (this.isSleeping()) {
             this.stopSleeping();
         }
 
+        // CraftBukkit start
+        String spawnWorld = nbttagcompound.getString("SpawnWorld");
+        CraftWorld oldWorld = (CraftWorld) Bukkit.getWorld(spawnWorld);
+        if (oldWorld != null) {
+            this.respawnDimension = oldWorld.getHandle().dimension();
+        }
+        // CraftBukkit end
+
         if (nbttagcompound.contains("SpawnX", 99) && nbttagcompound.contains("SpawnY", 99) && nbttagcompound.contains("SpawnZ", 99)) {
             this.respawnPosition = new BlockPosition(nbttagcompound.getInt("SpawnX"), nbttagcompound.getInt("SpawnY"), nbttagcompound.getInt("SpawnZ"));
             this.respawnForced = nbttagcompound.getBoolean("SpawnForced");
             this.respawnAngle = nbttagcompound.getFloat("SpawnAngle");
             if (nbttagcompound.contains("SpawnDimension")) {
-                DataResult dataresult1 = World.RESOURCE_KEY_CODEC.parse(DynamicOpsNBT.INSTANCE, nbttagcompound.get("SpawnDimension"));
+                DataResult<ResourceKey<World>> dataresult1 = World.RESOURCE_KEY_CODEC.parse(DynamicOpsNBT.INSTANCE, nbttagcompound.get("SpawnDimension")); // CraftBukkit - decompile error
                 Logger logger1 = EntityPlayer.LOGGER;
 
                 Objects.requireNonNull(logger1);
@@ -379,7 +478,7 @@
     @Override
     public void addAdditionalSaveData(NBTTagCompound nbttagcompound) {
         super.addAdditionalSaveData(nbttagcompound);
-        DataResult dataresult = WardenSpawnTracker.CODEC.encodeStart(DynamicOpsNBT.INSTANCE, this.wardenSpawnTracker);
+        DataResult<NBTBase> dataresult = WardenSpawnTracker.CODEC.encodeStart(DynamicOpsNBT.INSTANCE, this.wardenSpawnTracker); // CraftBukkit - decompile error
         Logger logger = EntityPlayer.LOGGER;
 
         Objects.requireNonNull(logger);
@@ -400,7 +499,20 @@
         Entity entity = this.getRootVehicle();
         Entity entity1 = this.getVehicle();
 
-        if (entity1 != null && entity != this && entity.hasExactlyOnePlayerPassenger()) {
+        // CraftBukkit start - handle non-persistent vehicles
+        boolean persistVehicle = true;
+        if (entity1 != null) {
+            Entity vehicle;
+            for (vehicle = entity1; vehicle != null; vehicle = vehicle.getVehicle()) {
+                if (!vehicle.persist) {
+                    persistVehicle = false;
+                    break;
+                }
+            }
+        }
+
+        if (persistVehicle && entity1 != null && entity != this && entity.hasExactlyOnePlayerPassenger()) {
+            // CraftBukkit end
             NBTTagCompound nbttagcompound2 = new NBTTagCompound();
             NBTTagCompound nbttagcompound3 = new NBTTagCompound();
 
@@ -425,8 +537,32 @@
                 nbttagcompound.put("SpawnDimension", nbtbase);
             });
         }
+        this.getBukkitEntity().setExtraData(nbttagcompound); // CraftBukkit
+
+    }
 
+    // CraftBukkit start - World fallback code, either respawn location or global spawn
+    public void spawnIn(World world) {
+        this.setLevel(world);
+        if (world == null) {
+            this.unsetRemoved();
+            Vec3D position = null;
+            if (this.respawnDimension != null) {
+                world = this.server.getLevel(this.respawnDimension);
+                if (world != null && this.getRespawnPosition() != null) {
+                    position = EntityHuman.findRespawnPositionAndUseSpawnBlock((WorldServer) world, this.getRespawnPosition(), this.getRespawnAngle(), false, false).orElse(null);
+                }
+            }
+            if (world == null || position == null) {
+                world = ((CraftWorld) Bukkit.getServer().getWorlds().get(0)).getHandle();
+                position = Vec3D.atCenterOf(world.getSharedSpawnPos());
+            }
+            this.setLevel(world);
+            this.setPos(position);
+        }
+        this.gameMode.setLevel((WorldServer) world);
     }
+    // CraftBukkit end
 
     public void setExperiencePoints(int i) {
         float f = (float) this.getXpNeededForNextLevel();
@@ -486,6 +622,11 @@
 
     @Override
     public void tick() {
+        // CraftBukkit start
+        if (this.joining) {
+            this.joining = false;
+        }
+        // CraftBukkit end
         this.gameMode.tick();
         this.wardenSpawnTracker.tick();
         --this.spawnInvulnerableTime;
@@ -542,7 +683,7 @@
             }
 
             if (this.getHealth() != this.lastSentHealth || this.lastSentFood != this.foodData.getFoodLevel() || this.foodData.getSaturationLevel() == 0.0F != this.lastFoodSaturationZero) {
-                this.connection.send(new PacketPlayOutUpdateHealth(this.getHealth(), this.foodData.getFoodLevel(), this.foodData.getSaturationLevel()));
+                this.connection.send(new PacketPlayOutUpdateHealth(this.getBukkitEntity().getScaledHealth(), this.foodData.getFoodLevel(), this.foodData.getSaturationLevel())); // CraftBukkit
                 this.lastSentHealth = this.getHealth();
                 this.lastSentFood = this.foodData.getFoodLevel();
                 this.lastFoodSaturationZero = this.foodData.getSaturationLevel() == 0.0F;
@@ -573,6 +714,12 @@
                 this.updateScoreForCriteria(IScoreboardCriteria.EXPERIENCE, MathHelper.ceil((float) this.lastRecordedExperience));
             }
 
+            // CraftBukkit start - Force max health updates
+            if (this.maxHealthCache != this.getMaxHealth()) {
+                this.getBukkitEntity().updateScaledHealth();
+            }
+            // CraftBukkit end
+
             if (this.experienceLevel != this.lastRecordedLevel) {
                 this.lastRecordedLevel = this.experienceLevel;
                 this.updateScoreForCriteria(IScoreboardCriteria.LEVEL, MathHelper.ceil((float) this.lastRecordedLevel));
@@ -587,6 +734,20 @@
                 CriterionTriggers.LOCATION.trigger(this);
             }
 
+            // CraftBukkit start - initialize oldLevel, fire PlayerLevelChangeEvent, and tick client-sided world border
+            if (this.oldLevel == -1) {
+                this.oldLevel = this.experienceLevel;
+            }
+
+            if (this.oldLevel != this.experienceLevel) {
+                CraftEventFactory.callPlayerLevelChangeEvent(this.getBukkitEntity(), this.oldLevel, this.experienceLevel);
+                this.oldLevel = this.experienceLevel;
+            }
+
+            if (this.getBukkitEntity().hasClientWorldBorder()) {
+                ((CraftWorldBorder) this.getBukkitEntity().getWorldBorder()).getHandle().tick();
+            }
+            // CraftBukkit end
         } catch (Throwable throwable) {
             CrashReport crashreport = CrashReport.forThrowable(throwable, "Ticking player");
             CrashReportSystemDetails crashreportsystemdetails = crashreport.addCategory("Player being ticked");
@@ -629,7 +790,8 @@
     }
 
     private void updateScoreForCriteria(IScoreboardCriteria iscoreboardcriteria, int i) {
-        this.getScoreboard().forAllObjectives(iscoreboardcriteria, this, (scoreaccess) -> {
+        // CraftBukkit - Use our scores instead
+        this.level().getCraftServer().getScoreboardManager().forAllObjectives(iscoreboardcriteria, this, (scoreaccess) -> {
             scoreaccess.set(i);
         });
     }
@@ -638,9 +800,47 @@
     public void die(DamageSource damagesource) {
         this.gameEvent(GameEvent.ENTITY_DIE);
         boolean flag = this.level().getGameRules().getBoolean(GameRules.RULE_SHOWDEATHMESSAGES);
+        // CraftBukkit start - fire PlayerDeathEvent
+        if (this.isRemoved()) {
+            return;
+        }
+        java.util.List<org.bukkit.inventory.ItemStack> loot = new java.util.ArrayList<org.bukkit.inventory.ItemStack>(this.getInventory().getContainerSize());
+        boolean keepInventory = this.level().getGameRules().getBoolean(GameRules.RULE_KEEPINVENTORY) || this.isSpectator();
 
-        if (flag) {
-            IChatBaseComponent ichatbasecomponent = this.getCombatTracker().getDeathMessage();
+        if (!keepInventory) {
+            for (ItemStack item : this.getInventory().getContents()) {
+                if (!item.isEmpty() && !EnchantmentManager.hasVanishingCurse(item)) {
+                    loot.add(CraftItemStack.asCraftMirror(item));
+                }
+            }
+        }
+        // SPIGOT-5071: manually add player loot tables (SPIGOT-5195 - ignores keepInventory rule)
+        this.dropFromLootTable(damagesource, this.lastHurtByPlayerTime > 0);
+        for (org.bukkit.inventory.ItemStack item : this.drops) {
+            loot.add(item);
+        }
+        this.drops.clear(); // SPIGOT-5188: make sure to clear
+
+        IChatBaseComponent defaultMessage = this.getCombatTracker().getDeathMessage();
+
+        String deathmessage = defaultMessage.getString();
+        keepLevel = keepInventory; // SPIGOT-2222: pre-set keepLevel
+        org.bukkit.event.entity.PlayerDeathEvent event = CraftEventFactory.callPlayerDeathEvent(this, loot, deathmessage, keepInventory);
+
+        // SPIGOT-943 - only call if they have an inventory open
+        if (this.containerMenu != this.inventoryMenu) {
+            this.closeContainer();
+        }
+
+        String deathMessage = event.getDeathMessage();
+
+        if (deathMessage != null && deathMessage.length() > 0 && flag) { // TODO: allow plugins to override?
+            IChatBaseComponent ichatbasecomponent;
+            if (deathMessage.equals(deathmessage)) {
+                ichatbasecomponent = this.getCombatTracker().getDeathMessage();
+            } else {
+                ichatbasecomponent = org.bukkit.craftbukkit.util.CraftChatMessage.fromStringOrNull(deathMessage);
+            }
 
             this.connection.send(new ClientboundPlayerCombatKillPacket(this.getId(), ichatbasecomponent), PacketSendListener.exceptionallySend(() -> {
                 boolean flag1 = true;
@@ -671,12 +871,18 @@
         if (this.level().getGameRules().getBoolean(GameRules.RULE_FORGIVE_DEAD_PLAYERS)) {
             this.tellNeutralMobsThatIDied();
         }
-
-        if (!this.isSpectator()) {
-            this.dropAllDeathLoot(damagesource);
+        // SPIGOT-5478 must be called manually now
+        this.dropExperience();
+        // we clean the player's inventory after the EntityDeathEvent is called so plugins can get the exact state of the inventory.
+        if (!event.getKeepInventory()) {
+            this.getInventory().clearContent();
         }
 
-        this.getScoreboard().forAllObjectives(IScoreboardCriteria.DEATH_COUNT, this, ScoreAccess::increment);
+        this.setCamera(this); // Remove spectated target
+        // CraftBukkit end
+
+        // CraftBukkit - Get our scores instead
+        this.level().getCraftServer().getScoreboardManager().forAllObjectives(IScoreboardCriteria.DEATH_COUNT, this, ScoreAccess::increment);
         EntityLiving entityliving = this.getKillCredit();
 
         if (entityliving != null) {
@@ -711,10 +917,12 @@
         if (entity != this) {
             super.awardKillScore(entity, i, damagesource);
             this.increaseScore(i);
-            this.getScoreboard().forAllObjectives(IScoreboardCriteria.KILL_COUNT_ALL, this, ScoreAccess::increment);
+            // CraftBukkit - Get our scores instead
+            this.level().getCraftServer().getScoreboardManager().forAllObjectives(IScoreboardCriteria.KILL_COUNT_ALL, this, ScoreAccess::increment);
             if (entity instanceof EntityHuman) {
                 this.awardStat(StatisticList.PLAYER_KILLS);
-                this.getScoreboard().forAllObjectives(IScoreboardCriteria.KILL_COUNT_PLAYERS, this, ScoreAccess::increment);
+                // CraftBukkit - Get our scores instead
+                this.level().getCraftServer().getScoreboardManager().forAllObjectives(IScoreboardCriteria.KILL_COUNT_PLAYERS, this, ScoreAccess::increment);
             } else {
                 this.awardStat(StatisticList.MOB_KILLS);
             }
@@ -732,7 +940,8 @@
             int i = scoreboardteam.getColor().getId();
 
             if (i >= 0 && i < aiscoreboardcriteria.length) {
-                this.getScoreboard().forAllObjectives(aiscoreboardcriteria[i], scoreholder, ScoreAccess::increment);
+                // CraftBukkit - Get our scores instead
+                this.level().getCraftServer().getScoreboardManager().forAllObjectives(aiscoreboardcriteria[i], scoreholder, ScoreAccess::increment);
             }
         }
 
@@ -782,18 +991,20 @@
     }
 
     private boolean isPvpAllowed() {
-        return this.server.isPvpAllowed();
+        // CraftBukkit - this.server.isPvpAllowed() -> this.world.pvpMode
+        return this.level().pvpMode;
     }
 
     @Nullable
     @Override
     protected ShapeDetectorShape findDimensionEntryPoint(WorldServer worldserver) {
         ShapeDetectorShape shapedetectorshape = super.findDimensionEntryPoint(worldserver);
+        worldserver = (shapedetectorshape == null) ? worldserver : shapedetectorshape.world; // CraftBukkit
 
-        if (shapedetectorshape != null && this.level().dimension() == World.OVERWORLD && worldserver.dimension() == World.END) {
+        if (shapedetectorshape != null && this.level().getTypeKey() == WorldDimension.OVERWORLD && worldserver != null && worldserver.getTypeKey() == WorldDimension.END) { // CraftBukkit
             Vec3D vec3d = shapedetectorshape.pos.add(0.0D, -1.0D, 0.0D);
 
-            return new ShapeDetectorShape(vec3d, Vec3D.ZERO, 90.0F, 0.0F);
+            return new ShapeDetectorShape(vec3d, Vec3D.ZERO, 90.0F, 0.0F, worldserver, shapedetectorshape.portalEventInfo); // CraftBukkit
         } else {
             return shapedetectorshape;
         }
@@ -802,11 +1013,20 @@
     @Nullable
     @Override
     public Entity changeDimension(WorldServer worldserver) {
-        this.isChangingDimension = true;
+        // CraftBukkit start
+        return changeDimension(worldserver, TeleportCause.UNKNOWN);
+    }
+
+    @Nullable
+    public Entity changeDimension(WorldServer worldserver, PlayerTeleportEvent.TeleportCause cause) {
+        // CraftBukkit end
+        if (this.isSleeping()) return this; // CraftBukkit - SPIGOT-3154
+        // this.isChangingDimension = true; // CraftBukkit - Moved down and into PlayerList#changeDimension
         WorldServer worldserver1 = this.serverLevel();
-        ResourceKey<World> resourcekey = worldserver1.dimension();
+        ResourceKey<WorldDimension> resourcekey = worldserver1.getTypeKey(); // CraftBukkit
 
-        if (resourcekey == World.END && worldserver.dimension() == World.OVERWORLD) {
+        if (resourcekey == WorldDimension.END && worldserver != null && worldserver.getTypeKey() == WorldDimension.OVERWORLD) { // CraftBukkit
+            this.isChangingDimension = true; // CraftBukkit - Moved down from above
             this.unRide();
             this.serverLevel().removePlayerImmediately(this, Entity.RemovalReason.CHANGED_DIMENSION);
             if (!this.wonGame) {
@@ -817,6 +1037,8 @@
 
             return this;
         } else {
+            // CraftBukkit start
+            /*
             WorldData worlddata = worldserver.getLevelData();
 
             this.connection.send(new PacketPlayOutRespawn(this.createCommonSpawnInfo(worldserver), (byte) 3));
@@ -826,20 +1048,50 @@
             playerlist.sendPlayerPermissionLevel(this);
             worldserver1.removePlayerImmediately(this, Entity.RemovalReason.CHANGED_DIMENSION);
             this.unsetRemoved();
+            */
+            // CraftBukkit end
             ShapeDetectorShape shapedetectorshape = this.findDimensionEntryPoint(worldserver);
 
             if (shapedetectorshape != null) {
                 worldserver1.getProfiler().push("moving");
-                if (resourcekey == World.OVERWORLD && worldserver.dimension() == World.NETHER) {
+                worldserver = shapedetectorshape.world; // CraftBukkit
+                if (worldserver == null) { } else // CraftBukkit - empty to fall through to null to event
+                if (resourcekey == WorldDimension.OVERWORLD && worldserver.getTypeKey() == WorldDimension.NETHER) { // CraftBukkit
                     this.enteredNetherPosition = this.position();
-                } else if (worldserver.dimension() == World.END) {
+                } else if (worldserver.getTypeKey() == WorldDimension.END && shapedetectorshape.portalEventInfo != null && shapedetectorshape.portalEventInfo.getCanCreatePortal()) { // CraftBukkit
                     this.createEndPlatform(worldserver, BlockPosition.containing(shapedetectorshape.pos));
                 }
+                // CraftBukkit start
+            } else {
+                return null;
+            }
+            Location enter = this.getBukkitEntity().getLocation();
+            Location exit = (worldserver == null) ? null : CraftLocation.toBukkit(shapedetectorshape.pos, worldserver.getWorld(), shapedetectorshape.yRot, shapedetectorshape.xRot);
+            PlayerTeleportEvent tpEvent = new PlayerTeleportEvent(this.getBukkitEntity(), enter, exit, cause);
+            Bukkit.getServer().getPluginManager().callEvent(tpEvent);
+            if (tpEvent.isCancelled() || tpEvent.getTo() == null) {
+                return null;
+            }
+            exit = tpEvent.getTo();
+            worldserver = ((CraftWorld) exit.getWorld()).getHandle();
+            // CraftBukkit end
 
-                worldserver1.getProfiler().pop();
-                worldserver1.getProfiler().push("placing");
+            worldserver1.getProfiler().pop();
+            worldserver1.getProfiler().push("placing");
+            if (true) { // CraftBukkit
+                this.isChangingDimension = true; // CraftBukkit - Set teleport invulnerability only if player changing worlds
+
+                this.connection.send(new PacketPlayOutRespawn(this.createCommonSpawnInfo(worldserver), (byte) 3));
+                this.connection.send(new PacketPlayOutServerDifficulty(this.level().getDifficulty(), this.level().getLevelData().isDifficultyLocked()));
+                PlayerList playerlist = this.server.getPlayerList();
+
+                playerlist.sendPlayerPermissionLevel(this);
+                worldserver1.removePlayerImmediately(this, Entity.RemovalReason.CHANGED_DIMENSION);
+                this.unsetRemoved();
+
+                // CraftBukkit end
                 this.setServerLevel(worldserver);
-                this.connection.teleport(shapedetectorshape.pos.x, shapedetectorshape.pos.y, shapedetectorshape.pos.z, shapedetectorshape.yRot, shapedetectorshape.xRot);
+                this.connection.teleport(exit); // CraftBukkit - use internal teleport without event
                 this.connection.resetPosition();
                 worldserver.addDuringPortalTeleport(this);
                 worldserver1.getProfiler().pop();
@@ -859,39 +1111,66 @@
                 this.lastSentExp = -1;
                 this.lastSentHealth = -1.0F;
                 this.lastSentFood = -1;
+
+                // CraftBukkit start
+                PlayerChangedWorldEvent changeEvent = new PlayerChangedWorldEvent(this.getBukkitEntity(), worldserver1.getWorld());
+                this.level().getCraftServer().getPluginManager().callEvent(changeEvent);
+                // CraftBukkit end
             }
 
             return this;
         }
     }
 
+    // CraftBukkit start
+    @Override
+    protected CraftPortalEvent callPortalEvent(Entity entity, WorldServer exitWorldServer, Vec3D exitPosition, TeleportCause cause, int searchRadius, int creationRadius) {
+        Location enter = this.getBukkitEntity().getLocation();
+        Location exit = CraftLocation.toBukkit(exitPosition, exitWorldServer.getWorld(), getYRot(), getXRot());
+        PlayerPortalEvent event = new PlayerPortalEvent(this.getBukkitEntity(), enter, exit, cause, searchRadius, true, creationRadius);
+        Bukkit.getServer().getPluginManager().callEvent(event);
+        if (event.isCancelled() || event.getTo() == null || event.getTo().getWorld() == null) {
+            return null;
+        }
+        return new CraftPortalEvent(event);
+    }
+    // CraftBukkit end
+
     private void createEndPlatform(WorldServer worldserver, BlockPosition blockposition) {
         BlockPosition.MutableBlockPosition blockposition_mutableblockposition = blockposition.mutable();
+        org.bukkit.craftbukkit.util.BlockStateListPopulator blockList = new org.bukkit.craftbukkit.util.BlockStateListPopulator(worldserver); // CraftBukkit
 
         for (int i = -2; i <= 2; ++i) {
             for (int j = -2; j <= 2; ++j) {
                 for (int k = -1; k < 3; ++k) {
                     IBlockData iblockdata = k == -1 ? Blocks.OBSIDIAN.defaultBlockState() : Blocks.AIR.defaultBlockState();
 
-                    worldserver.setBlockAndUpdate(blockposition_mutableblockposition.set(blockposition).move(j, k, i), iblockdata);
+                    blockList.setBlock(blockposition_mutableblockposition.set(blockposition).move(j, k, i), iblockdata, 3); // CraftBukkit
                 }
             }
         }
+        // CraftBukkit start - call portal event
+        org.bukkit.event.world.PortalCreateEvent portalEvent = new org.bukkit.event.world.PortalCreateEvent((List<org.bukkit.block.BlockState>) (List) blockList.getList(), worldserver.getWorld(), this.getBukkitEntity(), org.bukkit.event.world.PortalCreateEvent.CreateReason.END_PLATFORM);
+        worldserver.getCraftServer().getPluginManager().callEvent(portalEvent);
+        if (!portalEvent.isCancelled()) {
+            blockList.updateList();
+        }
+        // CraftBukkit end
 
     }
 
     @Override
-    protected Optional<BlockUtil.Rectangle> getExitPortal(WorldServer worldserver, BlockPosition blockposition, boolean flag, WorldBorder worldborder) {
-        Optional<BlockUtil.Rectangle> optional = super.getExitPortal(worldserver, blockposition, flag, worldborder);
+    protected Optional<BlockUtil.Rectangle> getExitPortal(WorldServer worldserver, BlockPosition blockposition, boolean flag, WorldBorder worldborder, int searchRadius, boolean canCreatePortal, int createRadius) { // CraftBukkit
+        Optional<BlockUtil.Rectangle> optional = super.getExitPortal(worldserver, blockposition, flag, worldborder, searchRadius, canCreatePortal, createRadius); // CraftBukkit
 
-        if (optional.isPresent()) {
+        if (optional.isPresent() || !canCreatePortal) { // CraftBukkit
             return optional;
         } else {
             EnumDirection.EnumAxis enumdirection_enumaxis = (EnumDirection.EnumAxis) this.level().getBlockState(this.portalEntrancePos).getOptionalValue(BlockPortal.AXIS).orElse(EnumDirection.EnumAxis.X);
-            Optional<BlockUtil.Rectangle> optional1 = worldserver.getPortalForcer().createPortal(blockposition, enumdirection_enumaxis);
+            Optional<BlockUtil.Rectangle> optional1 = worldserver.getPortalForcer().createPortal(blockposition, enumdirection_enumaxis, this, createRadius); // CraftBukkit
 
             if (optional1.isEmpty()) {
-                EntityPlayer.LOGGER.error("Unable to create a portal, likely target out of worldborder");
+                // EntityPlayer.LOGGER.error("Unable to create a portal, likely target out of worldborder"); // CraftBukkit
             }
 
             return optional1;
@@ -901,13 +1180,21 @@
     public void triggerDimensionChangeTriggers(WorldServer worldserver) {
         ResourceKey<World> resourcekey = worldserver.dimension();
         ResourceKey<World> resourcekey1 = this.level().dimension();
+        // CraftBukkit start
+        ResourceKey<World> maindimensionkey = CraftDimensionUtil.getMainDimensionKey(worldserver);
+        ResourceKey<World> maindimensionkey1 = CraftDimensionUtil.getMainDimensionKey(this.level());
 
-        CriterionTriggers.CHANGED_DIMENSION.trigger(this, resourcekey, resourcekey1);
-        if (resourcekey == World.NETHER && resourcekey1 == World.OVERWORLD && this.enteredNetherPosition != null) {
+        CriterionTriggers.CHANGED_DIMENSION.trigger(this, maindimensionkey, maindimensionkey1);
+        if (maindimensionkey != resourcekey || maindimensionkey1 != resourcekey1) {
+            CriterionTriggers.CHANGED_DIMENSION.trigger(this, resourcekey, resourcekey1);
+        }
+
+        if (maindimensionkey == World.NETHER && maindimensionkey1 == World.OVERWORLD && this.enteredNetherPosition != null) {
+            // CraftBukkit end
             CriterionTriggers.NETHER_TRAVEL.trigger(this, this.enteredNetherPosition);
         }
 
-        if (resourcekey1 != World.NETHER) {
+        if (maindimensionkey1 != World.NETHER) { // CraftBukkit
             this.enteredNetherPosition = null;
         }
 
@@ -924,19 +1211,17 @@
         this.containerMenu.broadcastChanges();
     }
 
-    @Override
-    public Either<EntityHuman.EnumBedResult, Unit> startSleepInBed(BlockPosition blockposition) {
-        EnumDirection enumdirection = (EnumDirection) this.level().getBlockState(blockposition).getValue(BlockFacingHorizontal.FACING);
-
+    // CraftBukkit start - moved bed result checks from below into separate method
+    private Either<EntityHuman.EnumBedResult, Unit> getBedResult(BlockPosition blockposition, EnumDirection enumdirection) {
         if (!this.isSleeping() && this.isAlive()) {
-            if (!this.level().dimensionType().natural()) {
+            if (!this.level().dimensionType().natural() || !this.level().dimensionType().bedWorks()) {
                 return Either.left(EntityHuman.EnumBedResult.NOT_POSSIBLE_HERE);
             } else if (!this.bedInRange(blockposition, enumdirection)) {
                 return Either.left(EntityHuman.EnumBedResult.TOO_FAR_AWAY);
             } else if (this.bedBlocked(blockposition, enumdirection)) {
                 return Either.left(EntityHuman.EnumBedResult.OBSTRUCTED);
             } else {
-                this.setRespawnPosition(this.level().dimension(), blockposition, this.getYRot(), false, true);
+                this.setRespawnPosition(this.level().dimension(), blockposition, this.getYRot(), false, true, PlayerSpawnChangeEvent.Cause.BED); // CraftBukkit
                 if (this.level().isDay()) {
                     return Either.left(EntityHuman.EnumBedResult.NOT_POSSIBLE_NOW);
                 } else {
@@ -953,7 +1238,36 @@
                         }
                     }
 
-                    Either<EntityHuman.EnumBedResult, Unit> either = super.startSleepInBed(blockposition).ifRight((unit) -> {
+                    return Either.right(Unit.INSTANCE);
+                }
+            }
+        } else {
+            return Either.left(EntityHuman.EnumBedResult.OTHER_PROBLEM);
+        }
+    }
+
+    @Override
+    public Either<EntityHuman.EnumBedResult, Unit> startSleepInBed(BlockPosition blockposition, boolean force) {
+        EnumDirection enumdirection = (EnumDirection) this.level().getBlockState(blockposition).getValue(BlockFacingHorizontal.FACING);
+        Either<EntityHuman.EnumBedResult, Unit> bedResult = this.getBedResult(blockposition, enumdirection);
+
+        if (bedResult.left().orElse(null) == EntityHuman.EnumBedResult.OTHER_PROBLEM) {
+            return bedResult; // return immediately if the result is not bypassable by plugins
+        }
+
+        if (force) {
+            bedResult = Either.right(Unit.INSTANCE);
+        }
+
+        bedResult = org.bukkit.craftbukkit.event.CraftEventFactory.callPlayerBedEnterEvent(this, blockposition, bedResult);
+        if (bedResult.left().isPresent()) {
+            return bedResult;
+        }
+
+        {
+            {
+                {
+                    Either<EntityHuman.EnumBedResult, Unit> either = super.startSleepInBed(blockposition, force).ifRight((unit) -> {
                         this.awardStat(StatisticList.SLEEP_IN_BED);
                         CriterionTriggers.SLEPT_IN_BED.trigger(this);
                     });
@@ -966,9 +1280,8 @@
                     return either;
                 }
             }
-        } else {
-            return Either.left(EntityHuman.EnumBedResult.OTHER_PROBLEM);
         }
+        // CraftBukkit end
     }
 
     @Override
@@ -995,13 +1308,31 @@
 
     @Override
     public void stopSleepInBed(boolean flag, boolean flag1) {
+        if (!this.isSleeping()) return; // CraftBukkit - Can't leave bed if not in one!
+        // CraftBukkit start - fire PlayerBedLeaveEvent
+        CraftPlayer player = this.getBukkitEntity();
+        BlockPosition bedPosition = this.getSleepingPos().orElse(null);
+
+        org.bukkit.block.Block bed;
+        if (bedPosition != null) {
+            bed = this.level().getWorld().getBlockAt(bedPosition.getX(), bedPosition.getY(), bedPosition.getZ());
+        } else {
+            bed = this.level().getWorld().getBlockAt(player.getLocation());
+        }
+
+        PlayerBedLeaveEvent event = new PlayerBedLeaveEvent(player, bed, true);
+        this.level().getCraftServer().getPluginManager().callEvent(event);
+        if (event.isCancelled()) {
+            return;
+        }
+        // CraftBukkit end
         if (this.isSleeping()) {
             this.serverLevel().getChunkSource().broadcastAndSend(this, new PacketPlayOutAnimation(this, 2));
         }
 
         super.stopSleepInBed(flag, flag1);
         if (this.connection != null) {
-            this.connection.teleport(this.getX(), this.getY(), this.getZ(), this.getYRot(), this.getXRot());
+            this.connection.teleport(this.getX(), this.getY(), this.getZ(), this.getYRot(), this.getXRot(), TeleportCause.EXIT_BED); // CraftBukkit
         }
 
     }
@@ -1051,8 +1382,9 @@
         this.connection.send(new PacketPlayOutOpenSignEditor(tileentitysign.getBlockPos(), flag));
     }
 
-    public void nextContainerCounter() {
+    public int nextContainerCounter() { // CraftBukkit - void -> int
         this.containerCounter = this.containerCounter % 100 + 1;
+        return containerCounter; // CraftBukkit
     }
 
     @Override
@@ -1060,13 +1392,35 @@
         if (itileinventory == null) {
             return OptionalInt.empty();
         } else {
+            // CraftBukkit start - SPIGOT-6552: Handle inventory closing in CraftEventFactory#callInventoryOpenEvent(...)
+            /*
             if (this.containerMenu != this.inventoryMenu) {
                 this.closeContainer();
             }
+            */
+            // CraftBukkit end
 
             this.nextContainerCounter();
             Container container = itileinventory.createMenu(this.containerCounter, this.getInventory(), this);
 
+            // CraftBukkit start - Inventory open hook
+            if (container != null) {
+                container.setTitle(itileinventory.getDisplayName());
+
+                boolean cancelled = false;
+                container = CraftEventFactory.callInventoryOpenEvent(this, container, cancelled);
+                if (container == null && !cancelled) { // Let pre-cancelled events fall through
+                    // SPIGOT-5263 - close chest if cancelled
+                    if (itileinventory instanceof IInventory) {
+                        ((IInventory) itileinventory).stopOpen(this);
+                    } else if (itileinventory instanceof BlockChest.DoubleInventory) {
+                        // SPIGOT-5355 - double chests too :(
+                        ((BlockChest.DoubleInventory) itileinventory).inventorylargechest.stopOpen(this);
+                    }
+                    return OptionalInt.empty();
+                }
+            }
+            // CraftBukkit end
             if (container == null) {
                 if (this.isSpectator()) {
                     this.displayClientMessage(IChatBaseComponent.translatable("container.spectatorCantOpen").withStyle(EnumChatFormat.RED), true);
@@ -1074,9 +1428,11 @@
 
                 return OptionalInt.empty();
             } else {
-                this.connection.send(new PacketPlayOutOpenWindow(container.containerId, container.getType(), itileinventory.getDisplayName()));
-                this.initMenu(container);
+                // CraftBukkit start
                 this.containerMenu = container;
+                this.connection.send(new PacketPlayOutOpenWindow(container.containerId, container.getType(), container.getTitle()));
+                // CraftBukkit end
+                this.initMenu(container);
                 return OptionalInt.of(this.containerCounter);
             }
         }
@@ -1089,13 +1445,24 @@
 
     @Override
     public void openHorseInventory(EntityHorseAbstract entityhorseabstract, IInventory iinventory) {
+        // CraftBukkit start - Inventory open hook
+        this.nextContainerCounter();
+        Container container = new ContainerHorse(this.containerCounter, this.getInventory(), iinventory, entityhorseabstract);
+        container.setTitle(entityhorseabstract.getDisplayName());
+        container = CraftEventFactory.callInventoryOpenEvent(this, container);
+
+        if (container == null) {
+            iinventory.stopOpen(this);
+            return;
+        }
+        // CraftBukkit end
         if (this.containerMenu != this.inventoryMenu) {
             this.closeContainer();
         }
 
-        this.nextContainerCounter();
+        // this.nextContainerCounter(); // CraftBukkit - moved up
         this.connection.send(new PacketPlayOutOpenWindowHorse(this.containerCounter, iinventory.getContainerSize(), entityhorseabstract.getId()));
-        this.containerMenu = new ContainerHorse(this.containerCounter, this.getInventory(), iinventory, entityhorseabstract);
+        this.containerMenu = container; // CraftBukkit
         this.initMenu(this.containerMenu);
     }
 
@@ -1118,6 +1485,7 @@
 
     @Override
     public void closeContainer() {
+        CraftEventFactory.handleInventoryCloseEvent(this); // CraftBukkit
         this.connection.send(new PacketPlayOutCloseWindow(this.containerMenu.containerId));
         this.doCloseContainer();
     }
@@ -1140,6 +1508,16 @@
             }
 
             this.jumping = flag;
+            // CraftBukkit start
+            if (flag1 != this.isShiftKeyDown()) {
+                PlayerToggleSneakEvent event = new PlayerToggleSneakEvent(this.getBukkitEntity(), flag1);
+                this.server.server.getPluginManager().callEvent(event);
+
+                if (event.isCancelled()) {
+                    return;
+                }
+            }
+            // CraftBukkit end
             this.setShiftKeyDown(flag1);
         }
 
@@ -1173,19 +1551,19 @@
                 i = Math.round((float) Math.sqrt(d0 * d0 + d1 * d1 + d2 * d2) * 100.0F);
                 if (i > 0) {
                     this.awardStat(StatisticList.SWIM_ONE_CM, i);
-                    this.causeFoodExhaustion(0.01F * (float) i * 0.01F);
+                    this.causeFoodExhaustion(0.01F * (float) i * 0.01F, EntityExhaustionEvent.ExhaustionReason.SWIM); // CraftBukkit - EntityExhaustionEvent
                 }
             } else if (this.isEyeInFluid(TagsFluid.WATER)) {
                 i = Math.round((float) Math.sqrt(d0 * d0 + d1 * d1 + d2 * d2) * 100.0F);
                 if (i > 0) {
                     this.awardStat(StatisticList.WALK_UNDER_WATER_ONE_CM, i);
-                    this.causeFoodExhaustion(0.01F * (float) i * 0.01F);
+                    this.causeFoodExhaustion(0.01F * (float) i * 0.01F, EntityExhaustionEvent.ExhaustionReason.WALK_UNDERWATER); // CraftBukkit - EntityExhaustionEvent
                 }
             } else if (this.isInWater()) {
                 i = Math.round((float) Math.sqrt(d0 * d0 + d2 * d2) * 100.0F);
                 if (i > 0) {
                     this.awardStat(StatisticList.WALK_ON_WATER_ONE_CM, i);
-                    this.causeFoodExhaustion(0.01F * (float) i * 0.01F);
+                    this.causeFoodExhaustion(0.01F * (float) i * 0.01F, EntityExhaustionEvent.ExhaustionReason.WALK_ON_WATER); // CraftBukkit - EntityExhaustionEvent
                 }
             } else if (this.onClimbable()) {
                 if (d1 > 0.0D) {
@@ -1196,13 +1574,13 @@
                 if (i > 0) {
                     if (this.isSprinting()) {
                         this.awardStat(StatisticList.SPRINT_ONE_CM, i);
-                        this.causeFoodExhaustion(0.1F * (float) i * 0.01F);
+                        this.causeFoodExhaustion(0.1F * (float) i * 0.01F, EntityExhaustionEvent.ExhaustionReason.SPRINT); // CraftBukkit - EntityExhaustionEvent
                     } else if (this.isCrouching()) {
                         this.awardStat(StatisticList.CROUCH_ONE_CM, i);
-                        this.causeFoodExhaustion(0.0F * (float) i * 0.01F);
+                        this.causeFoodExhaustion(0.0F * (float) i * 0.01F, EntityExhaustionEvent.ExhaustionReason.CROUCH); // CraftBukkit - EntityExhaustionEvent
                     } else {
                         this.awardStat(StatisticList.WALK_ONE_CM, i);
-                        this.causeFoodExhaustion(0.0F * (float) i * 0.01F);
+                        this.causeFoodExhaustion(0.0F * (float) i * 0.01F, EntityExhaustionEvent.ExhaustionReason.WALK); // CraftBukkit - EntityExhaustionEvent
                     }
                 }
             } else if (this.isFallFlying()) {
@@ -1245,7 +1623,7 @@
     @Override
     public void awardStat(Statistic<?> statistic, int i) {
         this.stats.increment(this, statistic, i);
-        this.getScoreboard().forAllObjectives(statistic, this, (scoreaccess) -> {
+        this.level().getCraftServer().getScoreboardManager().forAllObjectives(statistic, this, (scoreaccess) -> {
             scoreaccess.add(i);
         });
     }
@@ -1253,7 +1631,7 @@
     @Override
     public void resetStat(Statistic<?> statistic) {
         this.stats.setValue(this, statistic, 0);
-        this.getScoreboard().forAllObjectives(statistic, this, ScoreAccess::reset);
+        this.level().getCraftServer().getScoreboardManager().forAllObjectives(statistic, this, ScoreAccess::reset); // CraftBukkit - Get our scores instead
     }
 
     @Override
@@ -1301,6 +1679,7 @@
 
     public void resetSentInfo() {
         this.lastSentHealth = -1.0E8F;
+        this.lastSentExp = -1; // CraftBukkit - Added to reset
     }
 
     @Override
@@ -1358,7 +1737,7 @@
         this.lastSentExp = -1;
         this.lastSentHealth = -1.0F;
         this.lastSentFood = -1;
-        this.recipeBook.copyOverData(entityplayer.recipeBook);
+        // this.recipeBook.copyOverData(entityplayer.recipeBook); // CraftBukkit
         this.seenCredits = entityplayer.seenCredits;
         this.enteredNetherPosition = entityplayer.enteredNetherPosition;
         this.chunkTrackingView = entityplayer.chunkTrackingView;
@@ -1409,6 +1788,12 @@
 
     @Override
     public boolean teleportTo(WorldServer worldserver, double d0, double d1, double d2, Set<RelativeMovement> set, float f, float f1) {
+        // CraftBukkit start
+        return teleportTo(worldserver, d0, d1, d2, set, f, f1, TeleportCause.UNKNOWN);
+    }
+
+    public boolean teleportTo(WorldServer worldserver, double d0, double d1, double d2, Set<RelativeMovement> set, float f, float f1, TeleportCause cause) {
+        // CraftBukkit end
         ChunkCoordIntPair chunkcoordintpair = new ChunkCoordIntPair(BlockPosition.containing(d0, d1, d2));
 
         worldserver.getChunkSource().addRegionTicket(TicketType.POST_TELEPORT, chunkcoordintpair, 1, this.getId());
@@ -1418,9 +1803,9 @@
         }
 
         if (worldserver == this.level()) {
-            this.connection.teleport(d0, d1, d2, f, f1, set);
+            this.connection.teleport(d0, d1, d2, f, f1, set, cause); // CraftBukkit
         } else {
-            this.teleportTo(worldserver, d0, d1, d2, f, f1);
+            this.teleportTo(worldserver, d0, d1, d2, f, f1, cause); // CraftBukkit
         }
 
         this.setYHeadRot(f);
@@ -1524,6 +1909,16 @@
     }
 
     public void updateOptions(ClientInformation clientinformation) {
+        // CraftBukkit start
+        if (getMainArm() != clientinformation.mainHand()) {
+            PlayerChangedMainHandEvent event = new PlayerChangedMainHandEvent(getBukkitEntity(), getMainArm() == EnumMainHand.LEFT ? MainHand.LEFT : MainHand.RIGHT);
+            this.server.server.getPluginManager().callEvent(event);
+        }
+        if (!this.language.equals(clientinformation.language())) {
+            PlayerLocaleChangeEvent event = new PlayerLocaleChangeEvent(getBukkitEntity(), clientinformation.language());
+            this.server.server.getPluginManager().callEvent(event);
+        }
+        // CraftBukkit end
         this.language = clientinformation.language();
         this.requestedViewDistance = clientinformation.viewDistance();
         this.chatVisibility = clientinformation.chatVisibility();
@@ -1607,7 +2002,7 @@
             if (world instanceof WorldServer) {
                 WorldServer worldserver = (WorldServer) world;
 
-                this.teleportTo(worldserver, this.camera.getX(), this.camera.getY(), this.camera.getZ(), Set.of(), this.getYRot(), this.getXRot());
+                this.teleportTo(worldserver, this.camera.getX(), this.camera.getY(), this.camera.getZ(), Set.of(), this.getYRot(), this.getXRot(), TeleportCause.SPECTATE); // CraftBukkit
             }
 
             if (entity != null) {
@@ -1644,7 +2039,7 @@
 
     @Nullable
     public IChatBaseComponent getTabListDisplayName() {
-        return null;
+        return listName; // CraftBukkit
     }
 
     @Override
@@ -1665,9 +2060,16 @@
         return this.advancements;
     }
 
+    // CraftBukkit start
     public void teleportTo(WorldServer worldserver, double d0, double d1, double d2, float f, float f1) {
+        this.teleportTo(worldserver, d0, d1, d2, f, f1, org.bukkit.event.player.PlayerTeleportEvent.TeleportCause.UNKNOWN);
+    }
+
+    public void teleportTo(WorldServer worldserver, double d0, double d1, double d2, float f, float f1, org.bukkit.event.player.PlayerTeleportEvent.TeleportCause cause) {
+        // CraftBukkit end
         this.setCamera(this);
         this.stopRiding();
+        /* CraftBukkit start - replace with bukkit handling for multi-world
         if (worldserver == this.level()) {
             this.connection.teleport(d0, d1, d2, f, f1);
         } else {
@@ -1687,6 +2089,9 @@
             this.server.getPlayerList().sendLevelInfo(this, worldserver);
             this.server.getPlayerList().sendAllPlayerInfo(this);
         }
+        */
+        this.getBukkitEntity().teleport(new Location(worldserver.getWorld(), d0, d1, d2, f, f1), cause);
+        // CraftBukkit end
 
     }
 
@@ -1708,6 +2113,32 @@
     }
 
     public void setRespawnPosition(ResourceKey<World> resourcekey, @Nullable BlockPosition blockposition, float f, boolean flag, boolean flag1) {
+        // CraftBukkit start
+        this.setRespawnPosition(resourcekey, blockposition, f, flag, flag1, PlayerSpawnChangeEvent.Cause.UNKNOWN);
+    }
+
+    public void setRespawnPosition(ResourceKey<World> resourcekey, @Nullable BlockPosition blockposition, float f, boolean flag, boolean flag1, PlayerSpawnChangeEvent.Cause cause) {
+        WorldServer newWorld = this.server.getLevel(resourcekey);
+        Location newSpawn = (blockposition != null) ? CraftLocation.toBukkit(blockposition, newWorld.getWorld(), f, 0) : null;
+
+        PlayerSpawnChangeEvent event = new PlayerSpawnChangeEvent(this.getBukkitEntity(), newSpawn, flag, cause);
+        Bukkit.getServer().getPluginManager().callEvent(event);
+        if (event.isCancelled()) {
+            return;
+        }
+        newSpawn = event.getNewSpawn();
+        flag = event.isForced();
+
+        if (newSpawn != null) {
+            resourcekey = ((CraftWorld) newSpawn.getWorld()).getHandle().dimension();
+            blockposition = BlockPosition.containing(newSpawn.getX(), newSpawn.getY(), newSpawn.getZ());
+            f = newSpawn.getYaw();
+        } else {
+            resourcekey = World.OVERWORLD;
+            blockposition = null;
+            f = 0.0F;
+        }
+        // CraftBukkit end
         if (blockposition != null) {
             boolean flag2 = blockposition.equals(this.respawnPosition) && resourcekey.equals(this.respawnDimension);
 
@@ -1913,4 +2344,146 @@
     public CommonPlayerSpawnInfo createCommonSpawnInfo(WorldServer worldserver) {
         return new CommonPlayerSpawnInfo(worldserver.dimensionTypeId(), worldserver.dimension(), BiomeManager.obfuscateSeed(worldserver.getSeed()), this.gameMode.getGameModeForPlayer(), this.gameMode.getPreviousGameModeForPlayer(), worldserver.isDebug(), worldserver.isFlat(), this.getLastDeathLocation(), this.getPortalCooldown());
     }
+
+    // CraftBukkit start - Add per-player time and weather.
+    public long timeOffset = 0;
+    public boolean relativeTime = true;
+
+    public long getPlayerTime() {
+        if (this.relativeTime) {
+            // Adds timeOffset to the current server time.
+            return this.level().getDayTime() + this.timeOffset;
+        } else {
+            // Adds timeOffset to the beginning of this day.
+            return this.level().getDayTime() - (this.level().getDayTime() % 24000) + this.timeOffset;
+        }
+    }
+
+    public WeatherType weather = null;
+
+    public WeatherType getPlayerWeather() {
+        return this.weather;
+    }
+
+    public void setPlayerWeather(WeatherType type, boolean plugin) {
+        if (!plugin && this.weather != null) {
+            return;
+        }
+
+        if (plugin) {
+            this.weather = type;
+        }
+
+        if (type == WeatherType.DOWNFALL) {
+            this.connection.send(new PacketPlayOutGameStateChange(PacketPlayOutGameStateChange.STOP_RAINING, 0));
+        } else {
+            this.connection.send(new PacketPlayOutGameStateChange(PacketPlayOutGameStateChange.START_RAINING, 0));
+        }
+    }
+
+    private float pluginRainPosition;
+    private float pluginRainPositionPrevious;
+
+    public void updateWeather(float oldRain, float newRain, float oldThunder, float newThunder) {
+        if (this.weather == null) {
+            // Vanilla
+            if (oldRain != newRain) {
+                this.connection.send(new PacketPlayOutGameStateChange(PacketPlayOutGameStateChange.RAIN_LEVEL_CHANGE, newRain));
+            }
+        } else {
+            // Plugin
+            if (pluginRainPositionPrevious != pluginRainPosition) {
+                this.connection.send(new PacketPlayOutGameStateChange(PacketPlayOutGameStateChange.RAIN_LEVEL_CHANGE, pluginRainPosition));
+            }
+        }
+
+        if (oldThunder != newThunder) {
+            if (weather == WeatherType.DOWNFALL || weather == null) {
+                this.connection.send(new PacketPlayOutGameStateChange(PacketPlayOutGameStateChange.THUNDER_LEVEL_CHANGE, newThunder));
+            } else {
+                this.connection.send(new PacketPlayOutGameStateChange(PacketPlayOutGameStateChange.THUNDER_LEVEL_CHANGE, 0));
+            }
+        }
+    }
+
+    public void tickWeather() {
+        if (this.weather == null) return;
+
+        pluginRainPositionPrevious = pluginRainPosition;
+        if (weather == WeatherType.DOWNFALL) {
+            pluginRainPosition += 0.01;
+        } else {
+            pluginRainPosition -= 0.01;
+        }
+
+        pluginRainPosition = MathHelper.clamp(pluginRainPosition, 0.0F, 1.0F);
+    }
+
+    public void resetPlayerWeather() {
+        this.weather = null;
+        this.setPlayerWeather(this.level().getLevelData().isRaining() ? WeatherType.DOWNFALL : WeatherType.CLEAR, false);
+    }
+
+    @Override
+    public String toString() {
+        return super.toString() + "(" + this.getScoreboardName() + " at " + this.getX() + "," + this.getY() + "," + this.getZ() + ")";
+    }
+
+    // SPIGOT-1903, MC-98153
+    public void forceSetPositionRotation(double x, double y, double z, float yaw, float pitch) {
+        this.moveTo(x, y, z, yaw, pitch);
+        this.connection.resetPosition();
+    }
+
+    @Override
+    public boolean isImmobile() {
+        return super.isImmobile() || !getBukkitEntity().isOnline();
+    }
+
+    @Override
+    public Scoreboard getScoreboard() {
+        return getBukkitEntity().getScoreboard().getHandle();
+    }
+
+    public void reset() {
+        float exp = 0;
+        boolean keepInventory = this.level().getGameRules().getBoolean(GameRules.RULE_KEEPINVENTORY);
+
+        if (this.keepLevel) { // CraftBukkit - SPIGOT-6687: Only use keepLevel (was pre-set with RULE_KEEPINVENTORY value in PlayerDeathEvent)
+            exp = this.experienceProgress;
+            this.newTotalExp = this.totalExperience;
+            this.newLevel = this.experienceLevel;
+        }
+
+        this.setHealth(this.getMaxHealth());
+        this.stopUsingItem(); // CraftBukkit - SPIGOT-6682: Clear active item on reset
+        this.setRemainingFireTicks(0);
+        this.fallDistance = 0;
+        this.foodData = new FoodMetaData(this);
+        this.experienceLevel = this.newLevel;
+        this.totalExperience = this.newTotalExp;
+        this.experienceProgress = 0;
+        this.deathTime = 0;
+        this.setArrowCount(0, true); // CraftBukkit - ArrowBodyCountChangeEvent
+        this.removeAllEffects(org.bukkit.event.entity.EntityPotionEffectEvent.Cause.DEATH);
+        this.effectsDirty = true;
+        this.containerMenu = this.inventoryMenu;
+        this.lastHurtByPlayer = null;
+        this.lastHurtByMob = null;
+        this.combatTracker = new CombatTracker(this);
+        this.lastSentExp = -1;
+        if (this.keepLevel) { // CraftBukkit - SPIGOT-6687: Only use keepLevel (was pre-set with RULE_KEEPINVENTORY value in PlayerDeathEvent)
+            this.experienceProgress = exp;
+        } else {
+            this.giveExperiencePoints(this.newExp);
+        }
+        this.keepLevel = false;
+        this.setDeltaMovement(0, 0, 0); // CraftBukkit - SPIGOT-6948: Reset velocity on death
+    }
+
+    @Override
+    public CraftPlayer getBukkitEntity() {
+        return (CraftPlayer) super.getBukkitEntity();
+    }
+    // CraftBukkit end
 }
