--- a/net/minecraft/world/entity/Entity.java
+++ b/net/minecraft/world/entity/Entity.java
@@ -139,8 +139,68 @@
 import net.minecraft.world.scores.ScoreboardTeamBase;
 import org.slf4j.Logger;
 
+// CraftBukkit start
+import net.minecraft.network.protocol.game.PacketPlayOutAttachEntity;
+import net.minecraft.network.protocol.game.PacketPlayOutEntityMetadata;
+import net.minecraft.world.level.GameRules;
+import org.bukkit.Bukkit;
+import org.bukkit.Location;
+import org.bukkit.Server;
+import org.bukkit.block.BlockFace;
+import org.bukkit.command.CommandSender;
+import org.bukkit.entity.Hanging;
+import org.bukkit.entity.LivingEntity;
+import org.bukkit.entity.Vehicle;
+import org.bukkit.event.entity.EntityCombustByEntityEvent;
+import org.bukkit.event.hanging.HangingBreakByEntityEvent;
+import org.bukkit.event.vehicle.VehicleBlockCollisionEvent;
+import org.bukkit.event.vehicle.VehicleEnterEvent;
+import org.bukkit.event.vehicle.VehicleExitEvent;
+import org.bukkit.craftbukkit.CraftWorld;
+import org.bukkit.craftbukkit.entity.CraftEntity;
+import org.bukkit.craftbukkit.entity.CraftPlayer;
+import org.bukkit.craftbukkit.event.CraftEventFactory;
+import org.bukkit.craftbukkit.event.CraftPortalEvent;
+import org.bukkit.craftbukkit.util.CraftLocation;
+import org.bukkit.entity.Pose;
+import org.bukkit.event.entity.EntityAirChangeEvent;
+import org.bukkit.event.entity.EntityCombustEvent;
+import org.bukkit.event.entity.EntityDismountEvent;
+import org.bukkit.event.entity.EntityDropItemEvent;
+import org.bukkit.event.entity.EntityMountEvent;
+import org.bukkit.event.entity.EntityPortalEvent;
+import org.bukkit.event.entity.EntityPoseChangeEvent;
+import org.bukkit.event.entity.EntityRemoveEvent;
+import org.bukkit.event.entity.EntityTeleportEvent;
+import org.bukkit.event.entity.EntityUnleashEvent;
+import org.bukkit.event.entity.EntityUnleashEvent.UnleashReason;
+import org.bukkit.event.player.PlayerTeleportEvent;
+import org.bukkit.plugin.PluginManager;
+// CraftBukkit end
+
 public abstract class Entity implements SyncedDataHolder, INamableTileEntity, EntityAccess, ScoreHolder {
 
+    // CraftBukkit start
+    private static final int CURRENT_LEVEL = 2;
+    static boolean isLevelAtLeast(NBTTagCompound tag, int level) {
+        return tag.contains("Bukkit.updateLevel") && tag.getInt("Bukkit.updateLevel") >= level;
+    }
+
+    private CraftEntity bukkitEntity;
+
+    public CraftEntity getBukkitEntity() {
+        if (bukkitEntity == null) {
+            bukkitEntity = CraftEntity.getEntity(level.getCraftServer(), this);
+        }
+        return bukkitEntity;
+    }
+
+    // CraftBukkit - SPIGOT-6907: re-implement LivingEntity#setMaximumAir()
+    public int getDefaultMaxAirSupply() {
+        return TOTAL_AIR_SUPPLY;
+    }
+    // CraftBukkit end
+
     private static final Logger LOGGER = LogUtils.getLogger();
     public static final String ID_TAG = "id";
     public static final String PASSENGERS_TAG = "Passengers";
@@ -253,6 +313,30 @@
     private final List<Entity.b> movementThisTick;
     private final Set<IBlockData> blocksInside;
     private final LongSet visitedBlocks;
+    // CraftBukkit start
+    public boolean forceDrops;
+    public boolean persist = true;
+    public boolean visibleByDefault = true;
+    public boolean valid;
+    public boolean inWorld = false;
+    public boolean generation;
+    public int maxAirTicks = getDefaultMaxAirSupply(); // CraftBukkit - SPIGOT-6907: re-implement LivingEntity#setMaximumAir()
+    public org.bukkit.projectiles.ProjectileSource projectileSource; // For projectiles only
+    public boolean lastDamageCancelled; // SPIGOT-5339, SPIGOT-6252, SPIGOT-6777: Keep track if the event was canceled
+    public boolean persistentInvisibility = false;
+    public BlockPosition lastLavaContact;
+    // Marks an entity, that it was removed by a plugin via Entity#remove
+    // Main use case currently is for SPIGOT-7487, preventing dropping of leash when leash is removed
+    public boolean pluginRemoved = false;
+
+    public float getBukkitYaw() {
+        return this.yRot;
+    }
+
+    public boolean isChunkLoaded() {
+        return level.hasChunk((int) Math.floor(this.getX()) >> 4, (int) Math.floor(this.getZ()) >> 4);
+    }
+    // CraftBukkit end
 
     public Entity(EntityTypes<?> entitytypes, World world) {
         this.id = Entity.ENTITY_COUNTER.incrementAndGet();
@@ -362,12 +446,18 @@
     }
 
     public void kill(WorldServer worldserver) {
-        this.remove(Entity.RemovalReason.KILLED);
+        this.remove(Entity.RemovalReason.KILLED, EntityRemoveEvent.Cause.DEATH); // CraftBukkit - add Bukkit remove cause
         this.gameEvent(GameEvent.ENTITY_DIE);
     }
 
     public final void discard() {
-        this.remove(Entity.RemovalReason.DISCARDED);
+        // CraftBukkit start - add Bukkit remove cause
+        this.discard(null);
+    }
+
+    public final void discard(EntityRemoveEvent.Cause cause) {
+        this.remove(Entity.RemovalReason.DISCARDED, cause);
+        // CraftBukkit end
     }
 
     protected abstract void defineSynchedData(DataWatcher.a datawatcher_a);
@@ -376,6 +466,16 @@
         return this.entityData;
     }
 
+    // CraftBukkit start
+    public void refreshEntityData(EntityPlayer to) {
+        List<DataWatcher.c<?>> list = this.getEntityData().getNonDefaultValues();
+
+        if (list != null) {
+            to.connection.send(new PacketPlayOutEntityMetadata(this.getId(), list));
+        }
+    }
+    // CraftBukkit end
+
     public boolean equals(Object object) {
         return object instanceof Entity ? ((Entity) object).id == this.id : false;
     }
@@ -385,7 +485,13 @@
     }
 
     public void remove(Entity.RemovalReason entity_removalreason) {
-        this.setRemoved(entity_removalreason);
+        // CraftBukkit start - add Bukkit remove cause
+        this.setRemoved(entity_removalreason, null);
+    }
+
+    public void remove(Entity.RemovalReason entity_removalreason, EntityRemoveEvent.Cause cause) {
+        this.setRemoved(entity_removalreason, cause);
+        // CraftBukkit end
     }
 
     public void onClientRemoval() {}
@@ -393,6 +499,12 @@
     public void onRemoval(Entity.RemovalReason entity_removalreason) {}
 
     public void setPose(EntityPose entitypose) {
+        // CraftBukkit start
+        if (entitypose == this.getPose()) {
+            return;
+        }
+        this.level.getCraftServer().getPluginManager().callEvent(new EntityPoseChangeEvent(this.getBukkitEntity(), Pose.values()[entitypose.ordinal()]));
+        // CraftBukkit end
         this.entityData.set(Entity.DATA_POSE, entitypose);
     }
 
@@ -417,6 +529,33 @@
     }
 
     protected void setRot(float f, float f1) {
+        // CraftBukkit start - yaw was sometimes set to NaN, so we need to set it back to 0
+        if (Float.isNaN(f)) {
+            f = 0;
+        }
+
+        if (f == Float.POSITIVE_INFINITY || f == Float.NEGATIVE_INFINITY) {
+            if (this instanceof EntityPlayer) {
+                this.level.getCraftServer().getLogger().warning(this.getScoreboardName() + " was caught trying to crash the server with an invalid yaw");
+                ((CraftPlayer) this.getBukkitEntity()).kickPlayer("Infinite yaw (Hacking?)");
+            }
+            f = 0;
+        }
+
+        // pitch was sometimes set to NaN, so we need to set it back to 0
+        if (Float.isNaN(f1)) {
+            f1 = 0;
+        }
+
+        if (f1 == Float.POSITIVE_INFINITY || f1 == Float.NEGATIVE_INFINITY) {
+            if (this instanceof EntityPlayer) {
+                this.level.getCraftServer().getLogger().warning(this.getScoreboardName() + " was caught trying to crash the server with an invalid pitch");
+                ((CraftPlayer) this.getBukkitEntity()).kickPlayer("Infinite pitch (Hacking?)");
+            }
+            f1 = 0;
+        }
+        // CraftBukkit end
+
         this.setYRot(f % 360.0F);
         this.setXRot(f1 % 360.0F);
     }
@@ -462,6 +601,15 @@
         this.baseTick();
     }
 
+    // CraftBukkit start
+    public void postTick() {
+        // No clean way to break out of ticking once the entity has been copied to a new world, so instead we move the portalling later in the tick cycle
+        if (!(this instanceof EntityPlayer)) {
+            this.handlePortal();
+        }
+    }
+    // CraftBukkit end
+
     public void baseTick() {
         GameProfilerFiller gameprofilerfiller = Profiler.get();
 
@@ -475,7 +623,7 @@
             --this.boardingCooldown;
         }
 
-        this.handlePortal();
+        if (this instanceof EntityPlayer) this.handlePortal(); // CraftBukkit - // Moved up to postTick
         if (this.canSpawnSprintParticle()) {
             this.spawnSprintParticle();
         }
@@ -514,6 +662,10 @@
         if (this.isInLava()) {
             this.lavaHurt();
             this.fallDistance *= 0.5F;
+            // CraftBukkit start
+        } else {
+            this.lastLavaContact = null;
+            // CraftBukkit end
         }
 
         this.checkBelowWorld();
@@ -525,7 +677,7 @@
         world = this.level();
         if (world instanceof WorldServer worldserver) {
             if (this instanceof Leashable) {
-                Leashable.tickLeash(worldserver, (Entity) ((Leashable) this));
+                Leashable.tickLeash(worldserver, (Entity & Leashable) this); // CraftBukkit - decompile error
             }
         }
 
@@ -568,15 +720,32 @@
 
     public void lavaHurt() {
         if (!this.fireImmune()) {
-            this.igniteForSeconds(15.0F);
+            // CraftBukkit start - Fallen in lava TODO: this event spams!
+            if (this instanceof EntityLiving && remainingFireTicks <= 0) {
+                // not on fire yet
+                org.bukkit.block.Block damager = (lastLavaContact == null) ? null : org.bukkit.craftbukkit.block.CraftBlock.at(level, lastLavaContact);
+                org.bukkit.entity.Entity damagee = this.getBukkitEntity();
+                EntityCombustEvent combustEvent = new org.bukkit.event.entity.EntityCombustByBlockEvent(damager, damagee, 15);
+                this.level.getCraftServer().getPluginManager().callEvent(combustEvent);
+
+                if (!combustEvent.isCancelled()) {
+                    this.igniteForSeconds(combustEvent.getDuration(), false);
+                }
+            } else {
+                // This will be called every single tick the entity is in lava, so don't throw an event
+                this.igniteForSeconds(15.0F, false);
+            }
+            // CraftBukkit end
             World world = this.level();
 
             if (world instanceof WorldServer) {
                 WorldServer worldserver = (WorldServer) world;
 
-                if (this.hurtServer(worldserver, this.damageSources().lava(), 4.0F) && this.shouldPlayLavaHurtSound() && !this.isSilent()) {
+                // CraftBukkit start
+                if (this.hurtServer(worldserver, this.damageSources().lava().directBlock(level, lastLavaContact), 4.0F) && this.shouldPlayLavaHurtSound() && !this.isSilent()) {
                     worldserver.playSound((EntityHuman) null, this.getX(), this.getY(), this.getZ(), SoundEffects.GENERIC_BURN, this.getSoundSource(), 0.4F, 2.0F + this.random.nextFloat() * 0.4F);
                 }
+                // CraftBukkit end - we also don't throw an event unless the object in lava is living, to save on some event calls
             }
 
         }
@@ -587,6 +756,22 @@
     }
 
     public final void igniteForSeconds(float f) {
+        // CraftBukkit start
+        this.igniteForSeconds(f, true);
+    }
+
+    public final void igniteForSeconds(float f, boolean callEvent) {
+        if (callEvent) {
+            EntityCombustEvent event = new EntityCombustEvent(this.getBukkitEntity(), f);
+            this.level.getCraftServer().getPluginManager().callEvent(event);
+
+            if (event.isCancelled()) {
+                return;
+            }
+
+            f = event.getDuration();
+        }
+        // CraftBukkit end
         this.igniteForTicks(MathHelper.floor(f * 20.0F));
     }
 
@@ -610,7 +795,7 @@
     }
 
     protected void onBelowWorld() {
-        this.discard();
+        this.discard(EntityRemoveEvent.Cause.OUT_OF_WORLD); // CraftBukkit - add Bukkit remove cause
     }
 
     public boolean isFree(double d0, double d1, double d2) {
@@ -750,6 +935,28 @@
                     }
                 }
 
+                // CraftBukkit start
+                if (horizontalCollision && getBukkitEntity() instanceof Vehicle) {
+                    Vehicle vehicle = (Vehicle) this.getBukkitEntity();
+                    org.bukkit.block.Block bl = this.level.getWorld().getBlockAt(MathHelper.floor(this.getX()), MathHelper.floor(this.getY()), MathHelper.floor(this.getZ()));
+
+                    if (vec3d.x > vec3d1.x) {
+                        bl = bl.getRelative(BlockFace.EAST);
+                    } else if (vec3d.x < vec3d1.x) {
+                        bl = bl.getRelative(BlockFace.WEST);
+                    } else if (vec3d.z > vec3d1.z) {
+                        bl = bl.getRelative(BlockFace.SOUTH);
+                    } else if (vec3d.z < vec3d1.z) {
+                        bl = bl.getRelative(BlockFace.NORTH);
+                    }
+
+                    if (!bl.getType().isAir()) {
+                        VehicleBlockCollisionEvent event = new VehicleBlockCollisionEvent(vehicle, bl);
+                        level.getCraftServer().getPluginManager().callEvent(event);
+                    }
+                }
+                // CraftBukkit end
+
                 if (!this.level().isClientSide() || this.isControlledByLocalInstance()) {
                     Entity.MovementEmission entity_movementemission = this.getMovementEmission();
 
@@ -1133,6 +1340,20 @@
         return SoundEffects.GENERIC_SPLASH;
     }
 
+    // CraftBukkit start - Add delegate methods
+    public SoundEffect getSwimSound0() {
+        return getSwimSound();
+    }
+
+    public SoundEffect getSwimSplashSound0() {
+        return getSwimSplashSound();
+    }
+
+    public SoundEffect getSwimHighSpeedSplashSound0() {
+        return getSwimHighSpeedSplashSound();
+    }
+    // CraftBukkit end
+
     public void recordMovementThroughBlocks(Vec3D vec3d, Vec3D vec3d1) {
         this.movementThisTick.add(new Entity.b(vec3d, vec3d1));
     }
@@ -1609,6 +1830,7 @@
         this.yo = d1;
         this.zo = d4;
         this.setPos(d3, d1, d4);
+        if (valid) level.getChunk((int) Math.floor(this.getX()) >> 4, (int) Math.floor(this.getZ()) >> 4); // CraftBukkit
     }
 
     public void moveTo(Vec3D vec3d) {
@@ -1861,6 +2083,12 @@
         return false;
     }
 
+    // CraftBukkit start - collidable API
+    public boolean canCollideWithBukkit(Entity entity) {
+        return isPushable();
+    }
+    // CraftBukkit end
+
     public void awardKillScore(Entity entity, DamageSource damagesource) {
         if (entity instanceof EntityPlayer) {
             CriterionTriggers.ENTITY_KILLED_PLAYER.trigger((EntityPlayer) entity, this, damagesource);
@@ -1889,16 +2117,22 @@
     }
 
     public boolean saveAsPassenger(NBTTagCompound nbttagcompound) {
+        // CraftBukkit start - allow excluding certain data when saving
+        return saveAsPassenger(nbttagcompound, true);
+    }
+
+    public boolean saveAsPassenger(NBTTagCompound nbttagcompound, boolean includeAll) {
+        // CraftBukkit end
         if (this.removalReason != null && !this.removalReason.shouldSave()) {
             return false;
         } else {
             String s = this.getEncodeId();
 
-            if (s == null) {
+            if (!this.persist || s == null) { // CraftBukkit - persist flag
                 return false;
             } else {
                 nbttagcompound.putString("id", s);
-                this.saveWithoutId(nbttagcompound);
+                this.saveWithoutId(nbttagcompound, includeAll); // CraftBukkit - pass on includeAll
                 return true;
             }
         }
@@ -1909,16 +2143,38 @@
     }
 
     public NBTTagCompound saveWithoutId(NBTTagCompound nbttagcompound) {
+        // CraftBukkit start - allow excluding certain data when saving
+        return saveWithoutId(nbttagcompound, true);
+    }
+
+    public NBTTagCompound saveWithoutId(NBTTagCompound nbttagcompound, boolean includeAll) {
+        // CraftBukkit end
         try {
-            if (this.vehicle != null) {
-                nbttagcompound.put("Pos", this.newDoubleList(this.vehicle.getX(), this.getY(), this.vehicle.getZ()));
-            } else {
-                nbttagcompound.put("Pos", this.newDoubleList(this.getX(), this.getY(), this.getZ()));
+            // CraftBukkit start - selectively save position
+            if (includeAll) {
+                if (this.vehicle != null) {
+                    nbttagcompound.put("Pos", this.newDoubleList(this.vehicle.getX(), this.getY(), this.vehicle.getZ()));
+                } else {
+                    nbttagcompound.put("Pos", this.newDoubleList(this.getX(), this.getY(), this.getZ()));
+                }
             }
+            // CraftBukkit end
 
             Vec3D vec3d = this.getDeltaMovement();
 
             nbttagcompound.put("Motion", this.newDoubleList(vec3d.x, vec3d.y, vec3d.z));
+
+            // CraftBukkit start - Checking for NaN pitch/yaw and resetting to zero
+            // TODO: make sure this is the best way to address this.
+            if (Float.isNaN(this.yRot)) {
+                this.yRot = 0;
+            }
+
+            if (Float.isNaN(this.xRot)) {
+                this.xRot = 0;
+            }
+            // CraftBukkit end
+
             nbttagcompound.put("Rotation", this.newFloatList(this.getYRot(), this.getXRot()));
             nbttagcompound.putFloat("FallDistance", this.fallDistance);
             nbttagcompound.putShort("Fire", (short) this.remainingFireTicks);
@@ -1926,7 +2182,28 @@
             nbttagcompound.putBoolean("OnGround", this.onGround());
             nbttagcompound.putBoolean("Invulnerable", this.invulnerable);
             nbttagcompound.putInt("PortalCooldown", this.portalCooldown);
-            nbttagcompound.putUUID("UUID", this.getUUID());
+            // CraftBukkit start - selectively save uuid and world
+            if (includeAll) {
+                nbttagcompound.putUUID("UUID", this.getUUID());
+                // PAIL: Check above UUID reads 1.8 properly, ie: UUIDMost / UUIDLeast
+                nbttagcompound.putLong("WorldUUIDLeast", ((WorldServer) this.level).getWorld().getUID().getLeastSignificantBits());
+                nbttagcompound.putLong("WorldUUIDMost", ((WorldServer) this.level).getWorld().getUID().getMostSignificantBits());
+            }
+            nbttagcompound.putInt("Bukkit.updateLevel", CURRENT_LEVEL);
+            if (!this.persist) {
+                nbttagcompound.putBoolean("Bukkit.persist", this.persist);
+            }
+            if (!this.visibleByDefault) {
+                nbttagcompound.putBoolean("Bukkit.visibleByDefault", this.visibleByDefault);
+            }
+            if (this.persistentInvisibility) {
+                nbttagcompound.putBoolean("Bukkit.invisible", this.persistentInvisibility);
+            }
+            // SPIGOT-6907: re-implement LivingEntity#setMaximumAir()
+            if (maxAirTicks != getDefaultMaxAirSupply()) {
+                nbttagcompound.putInt("Bukkit.MaxAirSupply", getMaxAirSupply());
+            }
+            // CraftBukkit end
             IChatBaseComponent ichatbasecomponent = this.getCustomName();
 
             if (ichatbasecomponent != null) {
@@ -1975,7 +2252,7 @@
                 nbttagcompound.put("Tags", nbttaglist);
             }
 
-            this.addAdditionalSaveData(nbttagcompound);
+            this.addAdditionalSaveData(nbttagcompound, includeAll); // CraftBukkit - pass on includeAll
             if (this.isVehicle()) {
                 nbttaglist = new NBTTagList();
                 iterator = this.getPassengers().iterator();
@@ -1984,7 +2261,7 @@
                     Entity entity = (Entity) iterator.next();
                     NBTTagCompound nbttagcompound1 = new NBTTagCompound();
 
-                    if (entity.saveAsPassenger(nbttagcompound1)) {
+                    if (entity.saveAsPassenger(nbttagcompound1, includeAll)) { // CraftBukkit - pass on includeAll
                         nbttaglist.add(nbttagcompound1);
                     }
                 }
@@ -1994,6 +2271,11 @@
                 }
             }
 
+            // CraftBukkit start - stores eventually existing bukkit values
+            if (this.bukkitEntity != null) {
+                this.bukkitEntity.storeBukkitValues(nbttagcompound);
+            }
+            // CraftBukkit end
             return nbttagcompound;
         } catch (Throwable throwable) {
             CrashReport crashreport = CrashReport.forThrowable(throwable, "Saving entity NBT");
@@ -2080,6 +2362,45 @@
             } else {
                 throw new IllegalStateException("Entity has invalid position");
             }
+
+            // CraftBukkit start
+            this.persist = !nbttagcompound.contains("Bukkit.persist") || nbttagcompound.getBoolean("Bukkit.persist");
+            this.visibleByDefault = !nbttagcompound.contains("Bukkit.visibleByDefault") || nbttagcompound.getBoolean("Bukkit.visibleByDefault");
+            // SPIGOT-6907: re-implement LivingEntity#setMaximumAir()
+            if (nbttagcompound.contains("Bukkit.MaxAirSupply")) {
+                maxAirTicks = nbttagcompound.getInt("Bukkit.MaxAirSupply");
+            }
+            // CraftBukkit end
+
+            // CraftBukkit start - Reset world
+            if (this instanceof EntityPlayer) {
+                Server server = Bukkit.getServer();
+                org.bukkit.World bworld = null;
+
+                // TODO: Remove World related checks, replaced with WorldUID
+                String worldName = nbttagcompound.getString("world");
+
+                if (nbttagcompound.contains("WorldUUIDMost") && nbttagcompound.contains("WorldUUIDLeast")) {
+                    UUID uid = new UUID(nbttagcompound.getLong("WorldUUIDMost"), nbttagcompound.getLong("WorldUUIDLeast"));
+                    bworld = server.getWorld(uid);
+                } else {
+                    bworld = server.getWorld(worldName);
+                }
+
+                if (bworld == null) {
+                    bworld = ((org.bukkit.craftbukkit.CraftServer) server).getServer().getLevel(World.OVERWORLD).getWorld();
+                }
+
+                ((EntityPlayer) this).setLevel(bworld == null ? null : ((CraftWorld) bworld).getHandle());
+            }
+            this.getBukkitEntity().readBukkitValues(nbttagcompound);
+            if (nbttagcompound.contains("Bukkit.invisible")) {
+                boolean bukkitInvisible = nbttagcompound.getBoolean("Bukkit.invisible");
+                this.setInvisible(bukkitInvisible);
+                this.persistentInvisibility = bukkitInvisible;
+            }
+            // CraftBukkit end
+
         } catch (Throwable throwable) {
             CrashReport crashreport = CrashReport.forThrowable(throwable, "Loading entity NBT");
             CrashReportSystemDetails crashreportsystemdetails = crashreport.addCategory("Entity being loaded");
@@ -2101,6 +2422,12 @@
         return entitytypes.canSerialize() && minecraftkey != null ? minecraftkey.toString() : null;
     }
 
+    // CraftBukkit start - allow excluding certain data when saving
+    protected void addAdditionalSaveData(NBTTagCompound nbttagcompound, boolean includeAll) {
+        addAdditionalSaveData(nbttagcompound);
+    }
+    // CraftBukkit end
+
     protected abstract void readAdditionalSaveData(NBTTagCompound nbttagcompound);
 
     protected abstract void addAdditionalSaveData(NBTTagCompound nbttagcompound);
@@ -2153,9 +2480,22 @@
         if (itemstack.isEmpty()) {
             return null;
         } else {
+            // CraftBukkit start - Capture drops for death event
+            if (this instanceof EntityLiving && !((EntityLiving) this).forceDrops) {
+                ((EntityLiving) this).drops.add(org.bukkit.craftbukkit.inventory.CraftItemStack.asBukkitCopy(itemstack));
+                return null;
+            }
+            // CraftBukkit end
             EntityItem entityitem = new EntityItem(worldserver, this.getX(), this.getY() + (double) f, this.getZ(), itemstack);
 
             entityitem.setDefaultPickUpDelay();
+            // CraftBukkit start
+            EntityDropItemEvent event = new EntityDropItemEvent(this.getBukkitEntity(), (org.bukkit.entity.Item) entityitem.getBukkitEntity());
+            Bukkit.getPluginManager().callEvent(event);
+            if (event.isCancelled()) {
+                return null;
+            }
+            // CraftBukkit end
             worldserver.addFreshEntity(entityitem);
             return entityitem;
         }
@@ -2184,6 +2524,12 @@
         if (this.isAlive() && this instanceof Leashable leashable) {
             if (leashable.getLeashHolder() == entityhuman) {
                 if (!this.level().isClientSide()) {
+                    // CraftBukkit start - fire PlayerUnleashEntityEvent
+                    if (CraftEventFactory.callPlayerUnleashEntityEvent(this, entityhuman, enumhand).isCancelled()) {
+                        ((EntityPlayer) entityhuman).connection.send(new PacketPlayOutAttachEntity(this, leashable.getLeashHolder()));
+                        return EnumInteractionResult.PASS;
+                    }
+                    // CraftBukkit end
                     if (entityhuman.hasInfiniteMaterials()) {
                         leashable.removeLeash();
                     } else {
@@ -2200,6 +2546,13 @@
 
             if (itemstack.is(Items.LEAD) && leashable.canHaveALeashAttachedToIt()) {
                 if (!this.level().isClientSide()) {
+                    // CraftBukkit start - fire PlayerLeashEntityEvent
+                    if (CraftEventFactory.callPlayerLeashEntityEvent(this, entityhuman, entityhuman, enumhand).isCancelled()) {
+                        ((EntityPlayer) entityhuman).resendItemInHands(); // SPIGOT-7615: Resend to fix client desync with used item
+                        ((EntityPlayer) entityhuman).connection.send(new PacketPlayOutAttachEntity(this, leashable.getLeashHolder()));
+                        return EnumInteractionResult.PASS;
+                    }
+                    // CraftBukkit end
                     leashable.setLeashedTo(entityhuman, true);
                 }
 
@@ -2273,7 +2626,7 @@
             return false;
         } else if (!entity.couldAcceptPassenger()) {
             return false;
-        } else if (!this.level().isClientSide() && !entity.type.canSerialize()) {
+        } else if (!flag && !this.level().isClientSide() && !entity.type.canSerialize()) { // SPIGOT-7947: Allow force riding all entities
             return false;
         } else {
             for (Entity entity1 = entity; entity1.vehicle != null; entity1 = entity1.vehicle) {
@@ -2285,6 +2638,27 @@
             if (!flag && (!this.canRide(entity) || !entity.canAddPassenger(this))) {
                 return false;
             } else {
+                // CraftBukkit start
+                if (entity.getBukkitEntity() instanceof Vehicle && this.getBukkitEntity() instanceof LivingEntity) {
+                    VehicleEnterEvent event = new VehicleEnterEvent((Vehicle) entity.getBukkitEntity(), this.getBukkitEntity());
+                    // Suppress during worldgen
+                    if (this.valid) {
+                        Bukkit.getPluginManager().callEvent(event);
+                    }
+                    if (event.isCancelled()) {
+                        return false;
+                    }
+                }
+
+                EntityMountEvent event = new EntityMountEvent(this.getBukkitEntity(), entity.getBukkitEntity());
+                // Suppress during worldgen
+                if (this.valid) {
+                    Bukkit.getPluginManager().callEvent(event);
+                }
+                if (event.isCancelled()) {
+                    return false;
+                }
+                // CraftBukkit end
                 if (this.isPassenger()) {
                     this.stopRiding();
                 }
@@ -2318,7 +2692,7 @@
             Entity entity = this.vehicle;
 
             this.vehicle = null;
-            entity.removePassenger(this);
+            if (!entity.removePassenger(this)) this.vehicle = entity; // CraftBukkit
         }
 
     }
@@ -2349,10 +2723,38 @@
         }
     }
 
-    protected void removePassenger(Entity entity) {
+    protected boolean removePassenger(Entity entity) { // CraftBukkit
         if (entity.getVehicle() == this) {
             throw new IllegalStateException("Use x.stopRiding(y), not y.removePassenger(x)");
         } else {
+            // CraftBukkit start
+            CraftEntity craft = (CraftEntity) entity.getBukkitEntity().getVehicle();
+            Entity orig = craft == null ? null : craft.getHandle();
+            if (getBukkitEntity() instanceof Vehicle && entity.getBukkitEntity() instanceof LivingEntity) {
+                VehicleExitEvent event = new VehicleExitEvent(
+                        (Vehicle) getBukkitEntity(),
+                        (LivingEntity) entity.getBukkitEntity()
+                );
+                // Suppress during worldgen
+                if (this.valid) {
+                    Bukkit.getPluginManager().callEvent(event);
+                }
+                CraftEntity craftn = (CraftEntity) entity.getBukkitEntity().getVehicle();
+                Entity n = craftn == null ? null : craftn.getHandle();
+                if (event.isCancelled() || n != orig) {
+                    return false;
+                }
+            }
+
+            EntityDismountEvent event = new EntityDismountEvent(entity.getBukkitEntity(), this.getBukkitEntity());
+            // Suppress during worldgen
+            if (this.valid) {
+                Bukkit.getPluginManager().callEvent(event);
+            }
+            if (event.isCancelled()) {
+                return false;
+            }
+            // CraftBukkit end
             if (this.passengers.size() == 1 && this.passengers.get(0) == entity) {
                 this.passengers = ImmutableList.of();
             } else {
@@ -2364,6 +2766,7 @@
             entity.boardingCooldown = 60;
             this.gameEvent(GameEvent.ENTITY_DISMOUNT, entity);
         }
+        return true; // CraftBukkit
     }
 
     protected boolean canAddPassenger(Entity entity) {
@@ -2464,7 +2867,7 @@
                     if (teleporttransition != null) {
                         WorldServer worldserver1 = teleporttransition.newLevel();
 
-                        if (worldserver.getServer().isLevelEnabled(worldserver1) && (worldserver1.dimension() == worldserver.dimension() || this.canTeleport(worldserver, worldserver1))) {
+                        if (this instanceof EntityPlayer || (worldserver1 != null && (worldserver1.dimension() == worldserver.dimension() || this.canTeleport(worldserver, worldserver1)))) { // CraftBukkit - always call event for players
                             this.teleport(teleporttransition);
                         }
                     }
@@ -2571,6 +2974,13 @@
     }
 
     public void setSwimming(boolean flag) {
+        // CraftBukkit start
+        if (valid && this.isSwimming() != flag && this instanceof EntityLiving) {
+            if (CraftEventFactory.callToggleSwimEvent((EntityLiving) this, flag).isCancelled()) {
+                return;
+            }
+        }
+        // CraftBukkit end
         this.setSharedFlag(4, flag);
     }
 
@@ -2624,8 +3034,12 @@
         return this.getTeam() != null ? this.getTeam().isAlliedTo(scoreboardteambase) : false;
     }
 
+    // CraftBukkit - start
     public void setInvisible(boolean flag) {
-        this.setSharedFlag(5, flag);
+        if (!this.persistentInvisibility) { // Prevent Minecraft from removing our invisibility flag
+            this.setSharedFlag(5, flag);
+        }
+        // CraftBukkit - end
     }
 
     public boolean getSharedFlag(int i) {
@@ -2644,7 +3058,7 @@
     }
 
     public int getMaxAirSupply() {
-        return 300;
+        return maxAirTicks; // CraftBukkit - SPIGOT-6907: re-implement LivingEntity#setMaximumAir()
     }
 
     public int getAirSupply() {
@@ -2652,7 +3066,18 @@
     }
 
     public void setAirSupply(int i) {
-        this.entityData.set(Entity.DATA_AIR_SUPPLY_ID, i);
+        // CraftBukkit start
+        EntityAirChangeEvent event = new EntityAirChangeEvent(this.getBukkitEntity(), i);
+        // Suppress during worldgen
+        if (this.valid) {
+            event.getEntity().getServer().getPluginManager().callEvent(event);
+        }
+        if (event.isCancelled() && this.getAirSupply() != i) {
+            this.entityData.markDirty(Entity.DATA_AIR_SUPPLY_ID);
+            return;
+        }
+        this.entityData.set(Entity.DATA_AIR_SUPPLY_ID, event.getAmount());
+        // CraftBukkit end
     }
 
     public int getTicksFrozen() {
@@ -2679,11 +3104,40 @@
 
     public void thunderHit(WorldServer worldserver, EntityLightning entitylightning) {
         this.setRemainingFireTicks(this.remainingFireTicks + 1);
+        // CraftBukkit start
+        final org.bukkit.entity.Entity thisBukkitEntity = this.getBukkitEntity();
+        final org.bukkit.entity.Entity stormBukkitEntity = entitylightning.getBukkitEntity();
+        final PluginManager pluginManager = Bukkit.getPluginManager();
+        // CraftBukkit end
+
         if (this.remainingFireTicks == 0) {
-            this.igniteForSeconds(8.0F);
+            // CraftBukkit start - Call a combust event when lightning strikes
+            EntityCombustByEntityEvent entityCombustEvent = new EntityCombustByEntityEvent(stormBukkitEntity, thisBukkitEntity, 8.0F);
+            pluginManager.callEvent(entityCombustEvent);
+            if (!entityCombustEvent.isCancelled()) {
+                this.igniteForSeconds(entityCombustEvent.getDuration(), false);
+            }
+            // CraftBukkit end
         }
 
-        this.hurtServer(worldserver, this.damageSources().lightningBolt(), 5.0F);
+        // CraftBukkit start
+        if (thisBukkitEntity instanceof Hanging) {
+            HangingBreakByEntityEvent hangingEvent = new HangingBreakByEntityEvent((Hanging) thisBukkitEntity, stormBukkitEntity);
+            pluginManager.callEvent(hangingEvent);
+
+            if (hangingEvent.isCancelled()) {
+                return;
+            }
+        }
+
+        if (this.fireImmune()) {
+            return;
+        }
+
+        if (!this.hurtServer(worldserver, this.damageSources().lightningBolt().customEntityDamager(entitylightning), 5.0F)) {
+            return;
+        }
+        // CraftBukkit end
     }
 
     public void onAboveBubbleCol(boolean flag) {
@@ -2852,6 +3306,18 @@
 
         if (world instanceof WorldServer worldserver) {
             if (!this.isRemoved()) {
+                // CraftBukkit start
+                PositionMoveRotation absolutePosition = PositionMoveRotation.calculateAbsolute(PositionMoveRotation.of(this), PositionMoveRotation.of(teleporttransition), teleporttransition.relatives());
+                Location to = CraftLocation.toBukkit(absolutePosition.position(), teleporttransition.newLevel().getWorld(), absolutePosition.yRot(), absolutePosition.xRot());
+                EntityTeleportEvent teleEvent = CraftEventFactory.callEntityTeleportEvent(this, to);
+                if (teleEvent.isCancelled()) {
+                    return null;
+                }
+                if (!to.equals(teleEvent.getTo())) {
+                    to = teleEvent.getTo();
+                    teleporttransition = new TeleportTransition(((CraftWorld) to.getWorld()).getHandle(), CraftLocation.toVec3D(to), Vec3D.ZERO, to.getYaw(), to.getPitch(), teleporttransition.missingRespawnBlock(), teleporttransition.asPassenger(), Set.of(), teleporttransition.postTeleportTransition(), teleporttransition.cause());
+                }
+                // CraftBukkit end
                 WorldServer worldserver1 = teleporttransition.newLevel();
                 boolean flag = worldserver1.dimension() != worldserver.dimension();
 
@@ -2920,8 +3386,12 @@
         } else {
             entity.restoreFrom(this);
             this.removeAfterChangingDimensions();
+            // CraftBukkit start - Forward the CraftEntity to the new entity
+            this.getBukkitEntity().setHandle(entity);
+            entity.bukkitEntity = this.getBukkitEntity();
+            // CraftBukkit end
             entity.teleportSetPosition(PositionMoveRotation.of(teleporttransition), teleporttransition.relatives());
-            worldserver.addDuringTeleport(entity);
+            if (this.inWorld) worldserver.addDuringTeleport(entity); // CraftBukkit - Don't spawn the new entity if the current entity isn't spawned
             Iterator iterator1 = list1.iterator();
 
             while (iterator1.hasNext()) {
@@ -2995,8 +3465,9 @@
     }
 
     protected void removeAfterChangingDimensions() {
-        this.setRemoved(Entity.RemovalReason.CHANGED_DIMENSION);
+        this.setRemoved(Entity.RemovalReason.CHANGED_DIMENSION, null); // CraftBukkit - add Bukkit remove cause
         if (this instanceof Leashable leashable) {
+            this.level().getCraftServer().getPluginManager().callEvent(new EntityUnleashEvent(this.getBukkitEntity(), UnleashReason.UNKNOWN)); // CraftBukkit
             leashable.removeLeash();
         }
 
@@ -3006,6 +3477,20 @@
         return BlockPortalShape.getRelativePosition(blockutil_rectangle, enumdirection_enumaxis, this.position(), this.getDimensions(this.getPose()));
     }
 
+    // CraftBukkit start
+    public CraftPortalEvent callPortalEvent(Entity entity, Location exit, PlayerTeleportEvent.TeleportCause cause, int searchRadius, int creationRadius) {
+        org.bukkit.entity.Entity bukkitEntity = entity.getBukkitEntity();
+        Location enter = bukkitEntity.getLocation();
+
+        EntityPortalEvent event = new EntityPortalEvent(bukkitEntity, enter, exit, searchRadius, true, creationRadius);
+        event.getEntity().getServer().getPluginManager().callEvent(event);
+        if (event.isCancelled() || event.getTo() == null || event.getTo().getWorld() == null || !entity.isAlive()) {
+            return null;
+        }
+        return new CraftPortalEvent(event);
+    }
+    // CraftBukkit end
+
     public boolean canUsePortal(boolean flag) {
         return (flag || !this.isPassenger()) && this.isAlive();
     }
@@ -3134,9 +3619,15 @@
         return (Boolean) this.entityData.get(Entity.DATA_CUSTOM_NAME_VISIBLE);
     }
 
-    public boolean teleportTo(WorldServer worldserver, double d0, double d1, double d2, Set<Relative> set, float f, float f1, boolean flag) {
+    // CraftBukkit start
+    public final boolean teleportTo(WorldServer worldserver, double d0, double d1, double d2, Set<Relative> set, float f, float f1, boolean flag) {
+        return teleportTo(worldserver, d0, d1, d2, set, f, f1, flag, PlayerTeleportEvent.TeleportCause.UNKNOWN);
+    }
+
+    public boolean teleportTo(WorldServer worldserver, double d0, double d1, double d2, Set<Relative> set, float f, float f1, boolean flag, org.bukkit.event.player.PlayerTeleportEvent.TeleportCause cause) {
         float f2 = MathHelper.clamp(f1, -90.0F, 90.0F);
-        Entity entity = this.teleport(new TeleportTransition(worldserver, new Vec3D(d0, d1, d2), Vec3D.ZERO, f, f2, set, TeleportTransition.DO_NOTHING));
+        Entity entity = this.teleport(new TeleportTransition(worldserver, new Vec3D(d0, d1, d2), Vec3D.ZERO, f, f2, set, TeleportTransition.DO_NOTHING, cause));
+        // CraftBukkit end
 
         return entity != null;
     }
@@ -3258,7 +3749,26 @@
     }
 
     public final void setBoundingBox(AxisAlignedBB axisalignedbb) {
-        this.bb = axisalignedbb;
+        // CraftBukkit start - block invalid bounding boxes
+        double minX = axisalignedbb.minX,
+                minY = axisalignedbb.minY,
+                minZ = axisalignedbb.minZ,
+                maxX = axisalignedbb.maxX,
+                maxY = axisalignedbb.maxY,
+                maxZ = axisalignedbb.maxZ;
+        double len = axisalignedbb.maxX - axisalignedbb.minX;
+        if (len < 0) maxX = minX;
+        if (len > 64) maxX = minX + 64.0;
+
+        len = axisalignedbb.maxY - axisalignedbb.minY;
+        if (len < 0) maxY = minY;
+        if (len > 64) maxY = minY + 64.0;
+
+        len = axisalignedbb.maxZ - axisalignedbb.minZ;
+        if (len < 0) maxZ = minZ;
+        if (len > 64) maxZ = minZ + 64.0;
+        this.bb = new AxisAlignedBB(minX, minY, minZ, maxX, maxY, maxZ);
+        // CraftBukkit end
     }
 
     public final float getEyeHeight(EntityPose entitypose) {
@@ -3489,8 +3999,37 @@
         return 1;
     }
 
+    // CraftBukkit start
+    private final ICommandListener commandSource = new ICommandListener() {
+
+        @Override
+        public void sendSystemMessage(IChatBaseComponent ichatbasecomponent) {
+        }
+
+        @Override
+        public CommandSender getBukkitSender(CommandListenerWrapper wrapper) {
+            return Entity.this.getBukkitEntity();
+        }
+
+        @Override
+        public boolean acceptsSuccess() {
+            return ((WorldServer) Entity.this.level()).getGameRules().getBoolean(GameRules.RULE_SENDCOMMANDFEEDBACK);
+        }
+
+        @Override
+        public boolean acceptsFailure() {
+            return true;
+        }
+
+        @Override
+        public boolean shouldInformAdmins() {
+            return true;
+        }
+    };
+    // CraftBukkit end
+
     public CommandListenerWrapper createCommandSourceStackForNameResolution(WorldServer worldserver) {
-        return new CommandListenerWrapper(ICommandListener.NULL, this.position(), this.getRotationVector(), worldserver, 0, this.getName().getString(), this.getDisplayName(), worldserver.getServer(), this);
+        return new CommandListenerWrapper(commandSource, this.position(), this.getRotationVector(), worldserver, 0, this.getName().getString(), this.getDisplayName(), worldserver.getServer(), this); // CraftBukkit
     }
 
     public void lookAt(ArgumentAnchor.Anchor argumentanchor_anchor, Vec3D vec3d) {
@@ -3551,6 +4090,11 @@
                                     vec3d = vec3d.add(vec3d1);
                                     ++k1;
                                 }
+                                // CraftBukkit start - store last lava contact location
+                                if (tagkey == TagsFluid.LAVA) {
+                                    this.lastLavaContact = blockposition_mutableblockposition.immutable();
+                                }
+                                // CraftBukkit end
                             }
                         }
                     }
@@ -3818,6 +4362,14 @@
 
     @Override
     public final void setRemoved(Entity.RemovalReason entity_removalreason) {
+        // CraftBukkit start - add Bukkit remove cause
+        setRemoved(entity_removalreason, null);
+    }
+
+    @Override
+    public final void setRemoved(Entity.RemovalReason entity_removalreason, EntityRemoveEvent.Cause cause) {
+        CraftEventFactory.callEntityRemoveEvent(this, cause);
+        // CraftBukkit end
         if (this.removalReason == null) {
             this.removalReason = entity_removalreason;
         }
