--- a/net/minecraft/world/entity/EntityLiving.java
+++ b/net/minecraft/world/entity/EntityLiving.java
@@ -136,6 +136,33 @@
 import net.minecraft.world.scores.ScoreboardTeam;
 import org.slf4j.Logger;
 
+// CraftBukkit start
+import java.util.ArrayList;
+import java.util.HashSet;
+import java.util.Set;
+import java.util.LinkedList;
+import java.util.UUID;
+import net.minecraft.nbt.NBTTagFloat;
+import net.minecraft.nbt.NBTTagInt;
+import net.minecraft.world.item.component.Consumable;
+import org.bukkit.Location;
+import org.bukkit.craftbukkit.attribute.CraftAttributeMap;
+import org.bukkit.craftbukkit.event.CraftEventFactory;
+import org.bukkit.craftbukkit.inventory.CraftItemStack;
+import org.bukkit.entity.LivingEntity;
+import org.bukkit.entity.Player;
+import org.bukkit.event.entity.ArrowBodyCountChangeEvent;
+import org.bukkit.event.entity.EntityDamageEvent;
+import org.bukkit.event.entity.EntityDamageEvent.DamageModifier;
+import org.bukkit.event.entity.EntityKnockbackEvent;
+import org.bukkit.event.entity.EntityPotionEffectEvent;
+import org.bukkit.event.entity.EntityRegainHealthEvent;
+import org.bukkit.event.entity.EntityRemoveEvent;
+import org.bukkit.event.entity.EntityResurrectEvent;
+import org.bukkit.event.entity.EntityTeleportEvent;
+import org.bukkit.event.player.PlayerItemConsumeEvent;
+// CraftBukkit end
+
 public abstract class EntityLiving extends Entity implements Attackable {
 
     private static final Logger LOGGER = LogUtils.getLogger();
@@ -260,6 +287,19 @@
     protected boolean skipDropExperience;
     private final EnumMap<EnumItemSlot, Reference2ObjectMap<Enchantment, Set<EnchantmentLocationBasedEffect>>> activeLocationDependentEnchantments;
     protected float appliedScale;
+    // CraftBukkit start
+    public int expToDrop;
+    public ArrayList<org.bukkit.inventory.ItemStack> drops = new ArrayList<org.bukkit.inventory.ItemStack>();
+    public final org.bukkit.craftbukkit.attribute.CraftAttributeMap craftAttributes;
+    public boolean collides = true;
+    public Set<UUID> collidableExemptions = new HashSet<>();
+    public boolean bukkitPickUpLoot;
+
+    @Override
+    public float getBukkitYaw() {
+        return getYHeadRot();
+    }
+    // CraftBukkit end
 
     protected EntityLiving(EntityTypes<? extends EntityLiving> entitytypes, World world) {
         super(entitytypes, world);
@@ -276,7 +316,9 @@
         this.activeLocationDependentEnchantments = new EnumMap(EnumItemSlot.class);
         this.appliedScale = 1.0F;
         this.attributes = new AttributeMapBase(AttributeDefaults.getSupplier(entitytypes));
-        this.setHealth(this.getMaxHealth());
+        this.craftAttributes = new CraftAttributeMap(attributes); // CraftBukkit
+        // CraftBukkit - setHealth(getMaxHealth()) inlined and simplified to skip the instanceof check for EntityPlayer, as getBukkitEntity() is not initialized in constructor
+        this.entityData.set(EntityLiving.DATA_HEALTH_ID, (float) this.getAttribute(GenericAttributes.MAX_HEALTH).getValue());
         this.blocksBuilding = true;
         this.rotA = (float) ((Math.random() + 1.0D) * 0.009999999776482582D);
         this.reapplyPosition();
@@ -356,7 +398,13 @@
                     double d8 = Math.min((double) (0.2F + f / 15.0F), 2.5D);
                     int i = (int) (150.0D * d8);
 
-                    worldserver.sendParticles(new ParticleParamBlock(Particles.BLOCK, iblockdata), d2, d3, d4, i, 0.0D, 0.0D, 0.0D, 0.15000000596046448D);
+                    // CraftBukkit start - visiblity api
+                    if (this instanceof EntityPlayer) {
+                        worldserver.sendParticlesSource((EntityPlayer) this, new ParticleParamBlock(Particles.BLOCK, iblockdata), false, false, d2, d3, d4, i, 0.0D, 0.0D, 0.0D, 0.15000000596046448D);
+                    } else {
+                        worldserver.sendParticles(new ParticleParamBlock(Particles.BLOCK, iblockdata), d2, d3, d4, i, 0.0D, 0.0D, 0.0D, 0.15000000596046448D);
+                    }
+                    // CraftBukkit end
                 }
             }
         }
@@ -573,7 +621,7 @@
         ++this.deathTime;
         if (this.deathTime >= 20 && !this.level().isClientSide() && !this.isRemoved()) {
             this.level().broadcastEntityEvent(this, (byte) 60);
-            this.remove(Entity.RemovalReason.KILLED);
+            this.remove(Entity.RemovalReason.KILLED, EntityRemoveEvent.Cause.DEATH); // CraftBukkit - add Bukkit remove cause
         }
 
     }
@@ -679,13 +727,19 @@
     }
 
     public void onEquipItem(EnumItemSlot enumitemslot, ItemStack itemstack, ItemStack itemstack1) {
+        // CraftBukkit start
+        onEquipItem(enumitemslot, itemstack, itemstack1, false);
+    }
+
+    public void onEquipItem(EnumItemSlot enumitemslot, ItemStack itemstack, ItemStack itemstack1, boolean silent) {
+        // CraftBukkit end
         if (!this.level().isClientSide() && !this.isSpectator()) {
             boolean flag = itemstack1.isEmpty() && itemstack.isEmpty();
 
             if (!flag && !ItemStack.isSameItemSameComponents(itemstack, itemstack1) && !this.firstTick) {
                 Equippable equippable = (Equippable) itemstack1.get(DataComponents.EQUIPPABLE);
 
-                if (!this.isSilent() && equippable != null && enumitemslot == equippable.slot()) {
+                if (!this.isSilent() && equippable != null && enumitemslot == equippable.slot() && !silent) { // CraftBukkit
                     this.level().playSeededSound((EntityHuman) null, this.getX(), this.getY(), this.getZ(), equippable.equipSound(), this.getSoundSource(), 1.0F, 1.0F, this.random.nextLong());
                 }
 
@@ -699,6 +753,13 @@
 
     @Override
     public void remove(Entity.RemovalReason entity_removalreason) {
+        // CraftBukkit start - add Bukkit remove cause
+        this.remove(entity_removalreason, null);
+    }
+
+    @Override
+    public void remove(Entity.RemovalReason entity_removalreason, EntityRemoveEvent.Cause cause) {
+        // CraftBukkit end
         if (entity_removalreason == Entity.RemovalReason.KILLED || entity_removalreason == Entity.RemovalReason.DISCARDED) {
             World world = this.level();
 
@@ -709,7 +770,7 @@
             }
         }
 
-        super.remove(entity_removalreason);
+        super.remove(entity_removalreason, cause); // CraftBukkit
         this.brain.clearMemories();
     }
 
@@ -722,6 +783,7 @@
             mobeffect.onMobRemoved(worldserver, this, entity_removalreason);
         }
 
+        this.removeAllEffects(org.bukkit.event.entity.EntityPotionEffectEvent.Cause.DEATH); // CraftBukkit
         this.activeEffects.clear();
     }
 
@@ -781,6 +843,17 @@
             }
         }
 
+        // CraftBukkit start
+        if (nbttagcompound.contains("Bukkit.MaxHealth")) {
+            NBTBase nbtbase = nbttagcompound.get("Bukkit.MaxHealth");
+            if (nbtbase.getId() == 5) {
+                this.getAttribute(GenericAttributes.MAX_HEALTH).setBaseValue(((NBTTagFloat) nbtbase).getAsDouble());
+            } else if (nbtbase.getId() == 3) {
+                this.getAttribute(GenericAttributes.MAX_HEALTH).setBaseValue(((NBTTagInt) nbtbase).getAsDouble());
+            }
+        }
+        // CraftBukkit end
+
         if (nbttagcompound.contains("Health", 99)) {
             this.setHealth(nbttagcompound.getFloat("Health"));
         }
@@ -819,9 +892,32 @@
 
     }
 
+    // CraftBukkit start
+    private boolean isTickingEffects = false;
+    private List<ProcessableEffect> effectsToProcess = Lists.newArrayList();
+
+    private static class ProcessableEffect {
+
+        private Holder<MobEffectList> type;
+        private MobEffect effect;
+        private final EntityPotionEffectEvent.Cause cause;
+
+        private ProcessableEffect(MobEffect effect, EntityPotionEffectEvent.Cause cause) {
+            this.effect = effect;
+            this.cause = cause;
+        }
+
+        private ProcessableEffect(Holder<MobEffectList> type, EntityPotionEffectEvent.Cause cause) {
+            this.type = type;
+            this.cause = cause;
+        }
+    }
+    // CraftBukkit end
+
     protected void tickEffects() {
         Iterator<Holder<MobEffectList>> iterator = this.activeEffects.keySet().iterator();
 
+        isTickingEffects = true; // CraftBukkit
         try {
             while (iterator.hasNext()) {
                 Holder<MobEffectList> holder = (Holder) iterator.next();
@@ -831,6 +927,12 @@
                     this.onEffectUpdated(mobeffect, true, (Entity) null);
                 })) {
                     if (!this.level().isClientSide) {
+                        // CraftBukkit start
+                        EntityPotionEffectEvent event = CraftEventFactory.callEntityPotionEffectChangeEvent(this, mobeffect, null, org.bukkit.event.entity.EntityPotionEffectEvent.Cause.EXPIRATION);
+                        if (event.isCancelled()) {
+                            continue;
+                        }
+                        // CraftBukkit end
                         iterator.remove();
                         this.onEffectsRemoved(List.of(mobeffect));
                     }
@@ -841,6 +943,17 @@
         } catch (ConcurrentModificationException concurrentmodificationexception) {
             ;
         }
+        // CraftBukkit start
+        isTickingEffects = false;
+        for (ProcessableEffect e : effectsToProcess) {
+            if (e.effect != null) {
+                addEffect(e.effect, e.cause);
+            } else {
+                removeEffect(e.type, e.cause);
+            }
+        }
+        effectsToProcess.clear();
+        // CraftBukkit end
 
         if (this.effectsDirty) {
             if (!this.level().isClientSide) {
@@ -952,17 +1065,36 @@
         this.entityData.set(EntityLiving.DATA_EFFECT_PARTICLES, List.of());
     }
 
+    // CraftBukkit start
     public boolean removeAllEffects() {
+        return removeAllEffects(org.bukkit.event.entity.EntityPotionEffectEvent.Cause.UNKNOWN);
+    }
+
+    public boolean removeAllEffects(EntityPotionEffectEvent.Cause cause) {
+        // CraftBukkit end
         if (this.level().isClientSide) {
             return false;
         } else if (this.activeEffects.isEmpty()) {
             return false;
         } else {
-            Map<Holder<MobEffectList>, MobEffect> map = Maps.newHashMap(this.activeEffects);
+            // CraftBukkit start
+            List<MobEffect> toRemove = new LinkedList<>();
+            Iterator<MobEffect> iterator = this.activeEffects.values().iterator();
 
-            this.activeEffects.clear();
-            this.onEffectsRemoved(map.values());
-            return true;
+            while (iterator.hasNext()) {
+                MobEffect effect = iterator.next();
+                EntityPotionEffectEvent event = CraftEventFactory.callEntityPotionEffectChangeEvent(this, effect, null, cause, EntityPotionEffectEvent.Action.CLEARED);
+                if (event.isCancelled()) {
+                    continue;
+                }
+
+                iterator.remove();
+                toRemove.add(effect);
+            }
+
+            this.onEffectsRemoved(toRemove);
+            return !toRemove.isEmpty();
+            // CraftBukkit end
         }
     }
 
@@ -987,20 +1119,50 @@
         return this.addEffect(mobeffect, (Entity) null);
     }
 
+    // CraftBukkit start
+    public boolean addEffect(MobEffect mobeffect, EntityPotionEffectEvent.Cause cause) {
+        return this.addEffect(mobeffect, (Entity) null, cause);
+    }
+
     public boolean addEffect(MobEffect mobeffect, @Nullable Entity entity) {
+        return this.addEffect(mobeffect, entity, org.bukkit.event.entity.EntityPotionEffectEvent.Cause.UNKNOWN);
+    }
+
+    public boolean addEffect(MobEffect mobeffect, @Nullable Entity entity, EntityPotionEffectEvent.Cause cause) {
+        if (isTickingEffects) {
+            effectsToProcess.add(new ProcessableEffect(mobeffect, cause));
+            return true;
+        }
+        // CraftBukkit end
+
         if (!this.canBeAffected(mobeffect)) {
             return false;
         } else {
             MobEffect mobeffect1 = (MobEffect) this.activeEffects.get(mobeffect.getEffect());
             boolean flag = false;
 
+            // CraftBukkit start
+            boolean override = false;
+            if (mobeffect1 != null) {
+                override = new MobEffect(mobeffect1).update(mobeffect);
+            }
+
+            EntityPotionEffectEvent event = CraftEventFactory.callEntityPotionEffectChangeEvent(this, mobeffect1, mobeffect, cause, override);
+            if (event.isCancelled()) {
+                return false;
+            }
+            // CraftBukkit end
+
             if (mobeffect1 == null) {
                 this.activeEffects.put(mobeffect.getEffect(), mobeffect);
                 this.onEffectAdded(mobeffect, entity);
                 flag = true;
                 mobeffect.onEffectAdded(this);
-            } else if (mobeffect1.update(mobeffect)) {
+                // CraftBukkit start
+            } else if (event.isOverride()) {
+                mobeffect1.update(mobeffect);
                 this.onEffectUpdated(mobeffect1, true, entity);
+                // CraftBukkit end
                 flag = true;
             }
 
@@ -1031,13 +1193,39 @@
         return this.getType().is(TagsEntity.INVERTED_HEALING_AND_HARM);
     }
 
+    // CraftBukkit start
     @Nullable
     public MobEffect removeEffectNoUpdate(Holder<MobEffectList> holder) {
+        return removeEffectNoUpdate(holder, org.bukkit.event.entity.EntityPotionEffectEvent.Cause.UNKNOWN);
+    }
+
+    @Nullable
+    public MobEffect removeEffectNoUpdate(Holder<MobEffectList> holder, EntityPotionEffectEvent.Cause cause) {
+        if (isTickingEffects) {
+            effectsToProcess.add(new ProcessableEffect(holder, cause));
+            return null;
+        }
+
+        MobEffect effect = this.activeEffects.get(holder);
+        if (effect == null) {
+            return null;
+        }
+
+        EntityPotionEffectEvent event = CraftEventFactory.callEntityPotionEffectChangeEvent(this, effect, null, cause);
+        if (event.isCancelled()) {
+            return null;
+        }
+
         return (MobEffect) this.activeEffects.remove(holder);
     }
 
     public boolean removeEffect(Holder<MobEffectList> holder) {
-        MobEffect mobeffect = this.removeEffectNoUpdate(holder);
+        return removeEffect(holder, org.bukkit.event.entity.EntityPotionEffectEvent.Cause.UNKNOWN);
+    }
+
+    public boolean removeEffect(Holder<MobEffectList> holder, EntityPotionEffectEvent.Cause cause) {
+        MobEffect mobeffect = this.removeEffectNoUpdate(holder, cause);
+        // CraftBukkit end
 
         if (mobeffect != null) {
             this.onEffectsRemoved(List.of(mobeffect));
@@ -1142,20 +1330,55 @@
 
     }
 
+    // CraftBukkit start - Delegate so we can handle providing a reason for health being regained
     public void heal(float f) {
+        heal(f, EntityRegainHealthEvent.RegainReason.CUSTOM);
+    }
+
+    public void heal(float f, EntityRegainHealthEvent.RegainReason regainReason) {
         float f1 = this.getHealth();
 
         if (f1 > 0.0F) {
-            this.setHealth(f1 + f);
+            EntityRegainHealthEvent event = new EntityRegainHealthEvent(this.getBukkitEntity(), f, regainReason);
+            // Suppress during worldgen
+            if (this.valid) {
+                this.level().getCraftServer().getPluginManager().callEvent(event);
+            }
+
+            if (!event.isCancelled()) {
+                this.setHealth((float) (this.getHealth() + event.getAmount()));
+            }
+            // CraftBukkit end
         }
 
     }
 
     public float getHealth() {
+        // CraftBukkit start - Use unscaled health
+        if (this instanceof EntityPlayer) {
+            return (float) ((EntityPlayer) this).getBukkitEntity().getHealth();
+        }
+        // CraftBukkit end
         return (Float) this.entityData.get(EntityLiving.DATA_HEALTH_ID);
     }
 
     public void setHealth(float f) {
+        // CraftBukkit start - Handle scaled health
+        if (this instanceof EntityPlayer) {
+            org.bukkit.craftbukkit.entity.CraftPlayer player = ((EntityPlayer) this).getBukkitEntity();
+            // Squeeze
+            if (f < 0.0F) {
+                player.setRealHealth(0.0D);
+            } else if (f > player.getMaxHealth()) {
+                player.setRealHealth(player.getMaxHealth());
+            } else {
+                player.setRealHealth(f);
+            }
+
+            player.updateScaledHealth(false);
+            return;
+        }
+        // CraftBukkit end
         this.entityData.set(EntityLiving.DATA_HEALTH_ID, MathHelper.clamp(f, 0.0F, this.getMaxHealth()));
     }
 
@@ -1167,7 +1390,7 @@
     public boolean hurtServer(WorldServer worldserver, DamageSource damagesource, float f) {
         if (this.isInvulnerableTo(worldserver, damagesource)) {
             return false;
-        } else if (this.isDeadOrDying()) {
+        } else if (this.isRemoved() || this.dead || this.getHealth() <= 0.0F) { // CraftBukkit - Don't allow entities that got set to dead/killed elsewhere to get damaged and die
             return false;
         } else if (damagesource.is(DamageTypeTags.IS_FIRE) && this.hasEffect(MobEffects.FIRE_RESISTANCE)) {
             return false;
@@ -1182,10 +1405,11 @@
             }
 
             float f1 = f;
-            boolean flag = false;
+            boolean flag = f > 0.0F && this.isDamageSourceBlocked(damagesource); // Copied from below
             float f2 = 0.0F;
 
-            if (f > 0.0F && this.isDamageSourceBlocked(damagesource)) {
+            // CraftBukkit - Moved into handleEntityDamage(DamageSource, float) for get f and actuallyHurt(DamageSource, float, EntityDamageEvent) for handle damage
+            if (false && f > 0.0F && this.isDamageSourceBlocked(damagesource)) {
                 this.hurtCurrentlyUsedShield(f);
                 f2 = f;
                 f = 0.0F;
@@ -1202,15 +1426,26 @@
                 flag = true;
             }
 
-            if (damagesource.is(DamageTypeTags.IS_FREEZING) && this.getType().is(TagsEntity.FREEZE_HURTS_EXTRA_TYPES)) {
+            // CraftBukkit - Moved into handleEntityDamage(DamageSource, float) for get f
+            if (false && damagesource.is(DamageTypeTags.IS_FREEZING) && this.getType().is(TagsEntity.FREEZE_HURTS_EXTRA_TYPES)) {
                 f *= 5.0F;
             }
 
-            if (damagesource.is(DamageTypeTags.DAMAGES_HELMET) && !this.getItemBySlot(EnumItemSlot.HEAD).isEmpty()) {
+            // CraftBukkit - Moved into handleEntityDamage(DamageSource, float) for get f and actuallyHurt(DamageSource, float, EntityDamageEvent) for handle damage
+            if (false && damagesource.is(DamageTypeTags.DAMAGES_HELMET) && !this.getItemBySlot(EnumItemSlot.HEAD).isEmpty()) {
                 this.hurtHelmet(damagesource, f);
                 f *= 0.75F;
             }
 
+            // CraftBukkit start
+            EntityDamageEvent event = handleEntityDamage(damagesource, f);
+            f = 0;
+            f += (float) event.getDamage(DamageModifier.BASE);
+            f += (float) event.getDamage(DamageModifier.BLOCKING);
+            f += (float) event.getDamage(DamageModifier.FREEZING);
+            f += (float) event.getDamage(DamageModifier.HARD_HAT);
+            // CraftBukkit end
+
             this.walkAnimation.setSpeed(1.5F);
             if (Float.isNaN(f) || Float.isInfinite(f)) {
                 f = Float.MAX_VALUE;
@@ -1218,18 +1453,27 @@
 
             boolean flag1 = true;
 
-            if ((float) this.invulnerableTime > 10.0F && !damagesource.is(DamageTypeTags.BYPASSES_COOLDOWN)) {
+            if ((float) this.invulnerableTime > (float) this.invulnerableDuration / 2.0F && !damagesource.is(DamageTypeTags.BYPASSES_COOLDOWN)) { // CraftBukkit - restore use of maxNoDamageTicks
                 if (f <= this.lastHurt) {
                     return false;
                 }
 
-                this.actuallyHurt(worldserver, damagesource, f - this.lastHurt);
+                // CraftBukkit start
+                if (!this.actuallyHurt(worldserver, damagesource, (float) event.getFinalDamage() - this.lastHurt, event)) {
+                    return false;
+                }
+                // CraftBukkit end
                 this.lastHurt = f;
                 flag1 = false;
             } else {
+                // CraftBukkit start
+                if (!this.actuallyHurt(worldserver, damagesource, (float) event.getFinalDamage(), event)) {
+                    return false;
+                }
                 this.lastHurt = f;
-                this.invulnerableTime = 20;
-                this.actuallyHurt(worldserver, damagesource, f);
+                this.invulnerableTime = this.invulnerableDuration; // CraftBukkit - restore use of maxNoDamageTicks
+                // this.actuallyHurt(worldserver, damagesource, f);
+                // CraftBukkit end
                 this.hurtDuration = 10;
                 this.hurtTime = this.hurtDuration;
             }
@@ -1243,7 +1487,7 @@
                     worldserver.broadcastDamageEvent(this, damagesource);
                 }
 
-                if (!damagesource.is(DamageTypeTags.NO_IMPACT) && (!flag || f > 0.0F)) {
+                if (!damagesource.is(DamageTypeTags.NO_IMPACT) && !flag) { // CraftBukkit - Prevent marking hurt if the damage is blocked
                     this.markHurt();
                 }
 
@@ -1263,7 +1507,7 @@
                         d1 = damagesource.getSourcePosition().z() - this.getZ();
                     }
 
-                    this.knockback(0.4000000059604645D, d0, d1);
+                    this.knockback(0.4000000059604645D, d0, d1, entity1, entity1 == null ? EntityKnockbackEvent.KnockbackCause.DAMAGE : EntityKnockbackEvent.KnockbackCause.ENTITY_ATTACK); // CraftBukkit
                     if (!flag) {
                         this.indicateDamage(d0, d1);
                     }
@@ -1282,7 +1526,7 @@
                 this.playHurtSound(damagesource);
             }
 
-            boolean flag2 = !flag || f > 0.0F;
+            boolean flag2 = !flag; // CraftBukkit - Ensure to return false if damage is blocked
 
             if (flag2) {
                 this.lastDamageSource = damagesource;
@@ -1363,7 +1607,7 @@
     }
 
     protected void blockedByShield(EntityLiving entityliving) {
-        entityliving.knockback(0.5D, entityliving.getX() - this.getX(), entityliving.getZ() - this.getZ());
+        entityliving.knockback(0.5D, entityliving.getX() - this.getX(), entityliving.getZ() - this.getZ(), null, EntityKnockbackEvent.KnockbackCause.SHIELD_BLOCK); // CraftBukkit
     }
 
     private boolean checkTotemDeathProtection(DamageSource damagesource) {
@@ -1375,20 +1619,33 @@
             EnumHand[] aenumhand = EnumHand.values();
             int i = aenumhand.length;
 
+            // CraftBukkit start
+            EnumHand hand = null;
+            ItemStack itemstack1 = ItemStack.EMPTY;
             for (int j = 0; j < i; ++j) {
                 EnumHand enumhand = aenumhand[j];
-                ItemStack itemstack1 = this.getItemInHand(enumhand);
+                itemstack1 = this.getItemInHand(enumhand);
 
                 deathprotection = (DeathProtection) itemstack1.get(DataComponents.DEATH_PROTECTION);
                 if (deathprotection != null) {
+                    hand = enumhand; // CraftBukkit
                     itemstack = itemstack1.copy();
-                    itemstack1.shrink(1);
+                    // itemstack1.subtract(1); // CraftBukkit
                     break;
                 }
             }
 
-            if (itemstack != null) {
-                if (this instanceof EntityPlayer) {
+            org.bukkit.inventory.EquipmentSlot handSlot = (hand != null) ? org.bukkit.craftbukkit.CraftEquipmentSlot.getHand(hand) : null;
+            EntityResurrectEvent event = new EntityResurrectEvent((LivingEntity) this.getBukkitEntity(), handSlot);
+            event.setCancelled(itemstack == null);
+            this.level().getCraftServer().getPluginManager().callEvent(event);
+
+            if (!event.isCancelled()) {
+                if (!itemstack1.isEmpty()) {
+                    itemstack1.shrink(1);
+                }
+                if (itemstack != null && this instanceof EntityPlayer) {
+                    // CraftBukkit end
                     EntityPlayer entityplayer = (EntityPlayer) this;
 
                     entityplayer.awardStat(StatisticList.ITEM_USED.get(itemstack.getItem()));
@@ -1512,14 +1769,22 @@
                     IBlockData iblockdata = Blocks.WITHER_ROSE.defaultBlockState();
 
                     if (this.level().getBlockState(blockposition).isAir() && iblockdata.canSurvive(this.level(), blockposition)) {
-                        this.level().setBlock(blockposition, iblockdata, 3);
-                        flag = true;
+                        // CraftBukkit start - call EntityBlockFormEvent for Wither Rose
+                        flag = org.bukkit.craftbukkit.event.CraftEventFactory.handleBlockFormEvent(this.level(), blockposition, iblockdata, 3, this);
+                        // CraftBukkit end
                     }
                 }
 
                 if (!flag) {
                     EntityItem entityitem = new EntityItem(this.level(), this.getX(), this.getY(), this.getZ(), new ItemStack(Items.WITHER_ROSE));
 
+                    // CraftBukkit start
+                    org.bukkit.event.entity.EntityDropItemEvent event = new org.bukkit.event.entity.EntityDropItemEvent(this.getBukkitEntity(), (org.bukkit.entity.Item) entityitem.getBukkitEntity());
+                    CraftEventFactory.callEvent(event);
+                    if (event.isCancelled()) {
+                        return;
+                    }
+                    // CraftBukkit end
                     this.level().addFreshEntity(entityitem);
                 }
             }
@@ -1530,22 +1795,37 @@
     protected void dropAllDeathLoot(WorldServer worldserver, DamageSource damagesource) {
         boolean flag = this.lastHurtByPlayerTime > 0;
 
+        this.dropEquipment(worldserver); // CraftBukkit - from below
         if (this.shouldDropLoot() && worldserver.getGameRules().getBoolean(GameRules.RULE_DOMOBLOOT)) {
             this.dropFromLootTable(worldserver, damagesource, flag);
             this.dropCustomDeathLoot(worldserver, damagesource, flag);
         }
+        // CraftBukkit start - Call death event
+        CraftEventFactory.callEntityDeathEvent(this, damagesource, this.drops);
+        this.drops = new ArrayList<>();
+        // CraftBukkit end
 
-        this.dropEquipment(worldserver);
+        // this.dropEquipment(worldserver);// CraftBukkit - moved up
         this.dropExperience(worldserver, damagesource.getEntity());
     }
 
     protected void dropEquipment(WorldServer worldserver) {}
 
-    protected void dropExperience(WorldServer worldserver, @Nullable Entity entity) {
+    public int getExpReward(WorldServer worldserver, @Nullable Entity entity) { // CraftBukkit
         if (!this.wasExperienceConsumed() && (this.isAlwaysExperienceDropper() || this.lastHurtByPlayerTime > 0 && this.shouldDropExperience() && worldserver.getGameRules().getBoolean(GameRules.RULE_DOMOBLOOT))) {
-            EntityExperienceOrb.award(worldserver, this.position(), this.getExperienceReward(worldserver, entity));
+            return this.getExperienceReward(worldserver, entity); // CraftBukkit            }
         }
 
+        return 0; // CraftBukkit
+    }
+
+    protected void dropExperience(WorldServer worldserver, @Nullable Entity entity) {
+        // CraftBukkit start - Update getExpReward() above if the removed if() changes!
+        if (!(this instanceof net.minecraft.world.entity.boss.enderdragon.EntityEnderDragon)) { // CraftBukkit - SPIGOT-2420: Special case ender dragon will drop the xp over time
+            EntityExperienceOrb.award(worldserver, this.position(), this.expToDrop);
+            this.expToDrop = 0;
+        }
+        // CraftBukkit end
     }
 
     protected void dropCustomDeathLoot(WorldServer worldserver, DamageSource damagesource, boolean flag) {}
@@ -1612,9 +1892,14 @@
     }
 
     public void knockback(double d0, double d1, double d2) {
+        // CraftBukkit start - EntityKnockbackEvent
+        knockback(d0, d1, d2, null, EntityKnockbackEvent.KnockbackCause.UNKNOWN);
+    }
+
+    public void knockback(double d0, double d1, double d2, Entity attacker, EntityKnockbackEvent.KnockbackCause cause) {
         d0 *= 1.0D - this.getAttributeValue(GenericAttributes.KNOCKBACK_RESISTANCE);
-        if (d0 > 0.0D) {
-            this.hasImpulse = true;
+        if (true || d0 > 0.0D) { // CraftBukkit - Call event even when force is 0
+            //this.hasImpulse = true; // CraftBukkit - Move down
 
             Vec3D vec3d;
 
@@ -1624,7 +1909,14 @@
 
             Vec3D vec3d1 = (new Vec3D(d1, 0.0D, d2)).normalize().scale(d0);
 
-            this.setDeltaMovement(vec3d.x / 2.0D - vec3d1.x, this.onGround() ? Math.min(0.4D, vec3d.y / 2.0D + d0) : vec3d.y, vec3d.z / 2.0D - vec3d1.z);
+            EntityKnockbackEvent event = CraftEventFactory.callEntityKnockbackEvent((org.bukkit.craftbukkit.entity.CraftLivingEntity) this.getBukkitEntity(), attacker, cause, d0, vec3d1, vec3d.x / 2.0D - vec3d1.x, this.onGround() ? Math.min(0.4D, vec3d.y / 2.0D + d0) : vec3d.y, vec3d.z / 2.0D - vec3d1.z);
+            if (event.isCancelled()) {
+                return;
+            }
+
+            this.hasImpulse = true;
+            this.setDeltaMovement(event.getFinalKnockback().getX(), event.getFinalKnockback().getY(), event.getFinalKnockback().getZ());
+            // CraftBukkit end
         }
     }
 
@@ -1683,6 +1975,20 @@
         return new EntityLiving.a(SoundEffects.GENERIC_SMALL_FALL, SoundEffects.GENERIC_BIG_FALL);
     }
 
+    // CraftBukkit start - Add delegate methods
+    public SoundEffect getHurtSound0(DamageSource damagesource) {
+        return getHurtSound(damagesource);
+    }
+
+    public SoundEffect getDeathSound0() {
+        return getDeathSound();
+    }
+
+    public SoundEffect getFallDamageSound0(int fallHeight) {
+        return getFallDamageSound(fallHeight);
+    }
+    // CraftBukkit end
+
     public Optional<BlockPosition> getLastClimbablePos() {
         return this.lastClimbablePos;
     }
@@ -1757,9 +2063,14 @@
         int i = this.calculateFallDamage(f, f1);
 
         if (i > 0) {
+            // CraftBukkit start
+            if (!this.hurtServer((WorldServer) this.level(), damagesource, (float) i)) {
+                return true;
+            }
+            // CraftBukkit end
             this.playSound(this.getFallDamageSound(i), 1.0F, 1.0F);
             this.playBlockFallSound();
-            this.hurt(damagesource, (float) i);
+            // this.damageEntity(damagesource, (float) i); // CraftBukkit - moved up
             return true;
         } else {
             return flag;
@@ -1830,7 +2141,7 @@
 
     protected float getDamageAfterArmorAbsorb(DamageSource damagesource, float f) {
         if (!damagesource.is(DamageTypeTags.BYPASSES_ARMOR)) {
-            this.hurtArmor(damagesource, f);
+            // this.hurtArmor(damagesource, f); // CraftBukkit - actuallyHurt(DamageSource, float, EntityDamageEvent) for handle damage
             f = CombatMath.getDamageAfterAbsorb(this, f, damagesource, (float) this.getArmorValue(), (float) this.getAttributeValue(GenericAttributes.ARMOR_TOUGHNESS));
         }
 
@@ -1841,7 +2152,8 @@
         if (damagesource.is(DamageTypeTags.BYPASSES_EFFECTS)) {
             return f;
         } else {
-            if (this.hasEffect(MobEffects.DAMAGE_RESISTANCE) && !damagesource.is(DamageTypeTags.BYPASSES_RESISTANCE)) {
+            // CraftBukkit - Moved to handleEntityDamage(DamageSource, float)
+            if (false && this.hasEffect(MobEffects.DAMAGE_RESISTANCE) && !damagesource.is(DamageTypeTags.BYPASSES_RESISTANCE)) {
                 int i = (this.getEffect(MobEffects.DAMAGE_RESISTANCE).getAmplifier() + 1) * 5;
                 int j = 25 - i;
                 float f1 = f * (float) j;
@@ -1884,15 +2196,141 @@
         }
     }
 
-    protected void actuallyHurt(WorldServer worldserver, DamageSource damagesource, float f) {
+    // CraftBukkit start
+    private EntityDamageEvent handleEntityDamage(final DamageSource damagesource, float f) {
+        float originalDamage = f;
+
+        com.google.common.base.Function<Double, Double> freezing = new com.google.common.base.Function<Double, Double>() {
+            @Override
+            public Double apply(Double f) {
+                if (damagesource.is(DamageTypeTags.IS_FREEZING) && EntityLiving.this.getType().is(TagsEntity.FREEZE_HURTS_EXTRA_TYPES)) {
+                    return -(f - (f * 5.0F));
+                }
+                return -0.0;
+            }
+        };
+        float freezingModifier = freezing.apply((double) f).floatValue();
+        f += freezingModifier;
+
+        com.google.common.base.Function<Double, Double> hardHat = new com.google.common.base.Function<Double, Double>() {
+            @Override
+            public Double apply(Double f) {
+                if (damagesource.is(DamageTypeTags.DAMAGES_HELMET) && !EntityLiving.this.getItemBySlot(EnumItemSlot.HEAD).isEmpty()) {
+                    return -(f - (f * 0.75F));
+                }
+                return -0.0;
+            }
+        };
+        float hardHatModifier = hardHat.apply((double) f).floatValue();
+        f += hardHatModifier;
+
+        com.google.common.base.Function<Double, Double> blocking = new com.google.common.base.Function<Double, Double>() {
+            @Override
+            public Double apply(Double f) {
+                return -((EntityLiving.this.isDamageSourceBlocked(damagesource)) ? f : 0.0);
+            }
+        };
+        float blockingModifier = blocking.apply((double) f).floatValue();
+        f += blockingModifier;
+
+        com.google.common.base.Function<Double, Double> armor = new com.google.common.base.Function<Double, Double>() {
+            @Override
+            public Double apply(Double f) {
+                return -(f - EntityLiving.this.getDamageAfterArmorAbsorb(damagesource, f.floatValue()));
+            }
+        };
+        float armorModifier = armor.apply((double) f).floatValue();
+        f += armorModifier;
+
+        com.google.common.base.Function<Double, Double> resistance = new com.google.common.base.Function<Double, Double>() {
+            @Override
+            public Double apply(Double f) {
+                if (!damagesource.is(DamageTypeTags.BYPASSES_EFFECTS) && EntityLiving.this.hasEffect(MobEffects.DAMAGE_RESISTANCE) && !damagesource.is(DamageTypeTags.BYPASSES_RESISTANCE)) {
+                    int i = (EntityLiving.this.getEffect(MobEffects.DAMAGE_RESISTANCE).getAmplifier() + 1) * 5;
+                    int j = 25 - i;
+                    float f1 = f.floatValue() * (float) j;
+
+                    return -(f - Math.max(f1 / 25.0F, 0.0F));
+                }
+                return -0.0;
+            }
+        };
+        float resistanceModifier = resistance.apply((double) f).floatValue();
+        f += resistanceModifier;
+
+        com.google.common.base.Function<Double, Double> magic = new com.google.common.base.Function<Double, Double>() {
+            @Override
+            public Double apply(Double f) {
+                return -(f - EntityLiving.this.getDamageAfterMagicAbsorb(damagesource, f.floatValue()));
+            }
+        };
+        float magicModifier = magic.apply((double) f).floatValue();
+        f += magicModifier;
+
+        com.google.common.base.Function<Double, Double> absorption = new com.google.common.base.Function<Double, Double>() {
+            @Override
+            public Double apply(Double f) {
+                return -(Math.max(f - Math.max(f - EntityLiving.this.getAbsorptionAmount(), 0.0F), 0.0F));
+            }
+        };
+        float absorptionModifier = absorption.apply((double) f).floatValue();
+
+        return CraftEventFactory.handleLivingEntityDamageEvent(this, damagesource, originalDamage, freezingModifier, hardHatModifier, blockingModifier, armorModifier, resistanceModifier, magicModifier, absorptionModifier, freezing, hardHat, blocking, armor, resistance, magic, absorption);
+    }
+
+    protected boolean actuallyHurt(WorldServer worldserver, final DamageSource damagesource, float f, final EntityDamageEvent event) { // void -> boolean, add final
         if (!this.isInvulnerableTo(worldserver, damagesource)) {
-            f = this.getDamageAfterArmorAbsorb(damagesource, f);
-            f = this.getDamageAfterMagicAbsorb(damagesource, f);
-            float f1 = f;
+            if (event.isCancelled()) {
+                return false;
+            }
 
-            f = Math.max(f - this.getAbsorptionAmount(), 0.0F);
-            this.setAbsorptionAmount(this.getAbsorptionAmount() - (f1 - f));
-            float f2 = f1 - f;
+            if (damagesource.getEntity() instanceof EntityHuman) {
+                ((EntityHuman) damagesource.getEntity()).resetAttackStrengthTicker(); // Moved from EntityHuman in order to make the cooldown reset get called after the damage event is fired
+            }
+
+            // Resistance
+            if (event.getDamage(DamageModifier.RESISTANCE) < 0) {
+                float f3 = (float) -event.getDamage(DamageModifier.RESISTANCE);
+                if (f3 > 0.0F && f3 < 3.4028235E37F) {
+                    if (this instanceof EntityPlayer) {
+                        ((EntityPlayer) this).awardStat(StatisticList.DAMAGE_RESISTED, Math.round(f3 * 10.0F));
+                    } else if (damagesource.getEntity() instanceof EntityPlayer) {
+                        ((EntityPlayer) damagesource.getEntity()).awardStat(StatisticList.DAMAGE_DEALT_RESISTED, Math.round(f3 * 10.0F));
+                    }
+                }
+            }
+
+            // Apply damage to helmet
+            if (damagesource.is(DamageTypeTags.DAMAGES_HELMET) && !this.getItemBySlot(EnumItemSlot.HEAD).isEmpty()) {
+                this.hurtHelmet(damagesource, f);
+            }
+
+            // Apply damage to armor
+            if (!damagesource.is(DamageTypeTags.BYPASSES_ARMOR)) {
+                float armorDamage = (float) (event.getDamage() + event.getDamage(DamageModifier.BLOCKING) + event.getDamage(DamageModifier.HARD_HAT));
+                this.hurtArmor(damagesource, armorDamage);
+            }
+
+            // Apply blocking code // PAIL: steal from above
+            if (event.getDamage(DamageModifier.BLOCKING) < 0) {
+                this.hurtCurrentlyUsedShield((float) -event.getDamage(DamageModifier.BLOCKING));
+                Entity entity = damagesource.getDirectEntity();
+
+                if (entity instanceof EntityLiving) {
+                    this.blockUsingShield((EntityLiving) entity);
+                }
+            }
+
+            boolean human = this instanceof EntityHuman;
+            float originalDamage = (float) event.getDamage();
+            float absorptionModifier = (float) -event.getDamage(DamageModifier.ABSORPTION);
+            this.setAbsorptionAmount(Math.max(this.getAbsorptionAmount() - absorptionModifier, 0.0F));
+            float f2 = absorptionModifier;
+
+            if (f2 > 0.0F && f2 < 3.4028235E37F && this instanceof EntityHuman) {
+                ((EntityHuman) this).awardStat(StatisticList.DAMAGE_ABSORBED, Math.round(f2 * 10.0F));
+            }
+            // CraftBukkit end
 
             if (f2 > 0.0F && f2 < 3.4028235E37F) {
                 Entity entity = damagesource.getEntity();
@@ -1904,13 +2342,48 @@
                 }
             }
 
-            if (f != 0.0F) {
+            // CraftBukkit start
+            if (f > 0 || !human) {
+                if (human) {
+                    // PAIL: Be sure to drag all this code from the EntityHuman subclass each update.
+                    ((EntityHuman) this).causeFoodExhaustion(damagesource.getFoodExhaustion(), org.bukkit.event.entity.EntityExhaustionEvent.ExhaustionReason.DAMAGED); // CraftBukkit - EntityExhaustionEvent
+                    if (f < 3.4028235E37F) {
+                        ((EntityHuman) this).awardStat(StatisticList.DAMAGE_TAKEN, Math.round(f * 10.0F));
+                    }
+                }
+                // CraftBukkit end
                 this.getCombatTracker().recordDamage(damagesource, f);
                 this.setHealth(this.getHealth() - f);
-                this.setAbsorptionAmount(this.getAbsorptionAmount() - f);
+                // CraftBukkit start
+                if (!human) {
+                    this.setAbsorptionAmount(this.getAbsorptionAmount() - f);
+                }
                 this.gameEvent(GameEvent.ENTITY_DAMAGE);
+
+                return true;
+            } else {
+                // Duplicate triggers if blocking
+                if (event.getDamage(DamageModifier.BLOCKING) < 0) {
+                    if (this instanceof EntityPlayer) {
+                        CriterionTriggers.ENTITY_HURT_PLAYER.trigger((EntityPlayer) this, damagesource, f, originalDamage, true);
+                        f2 = (float) -event.getDamage(DamageModifier.BLOCKING);
+                        if (f2 > 0.0F && f2 < 3.4028235E37F) {
+                            ((EntityPlayer) this).awardStat(StatisticList.DAMAGE_BLOCKED_BY_SHIELD, Math.round(originalDamage * 10.0F));
+                        }
+                    }
+
+                    if (damagesource.getEntity() instanceof EntityPlayer) {
+                        CriterionTriggers.PLAYER_HURT_ENTITY.trigger((EntityPlayer) damagesource.getEntity(), this, damagesource, f, originalDamage, true);
+                    }
+
+                    return true;
+                } else {
+                    return originalDamage > 0;
+                }
+                // CraftBukkit end
             }
         }
+        return false; // CraftBukkit
     }
 
     public CombatTracker getCombatTracker() {
@@ -1935,9 +2408,19 @@
     }
 
     public final void setArrowCount(int i) {
-        this.entityData.set(EntityLiving.DATA_ARROW_COUNT_ID, i);
+        // CraftBukkit start
+        setArrowCount(i, false);
     }
 
+    public final void setArrowCount(int i, boolean flag) {
+        ArrowBodyCountChangeEvent event = CraftEventFactory.callArrowBodyCountChangeEvent(this, getArrowCount(), i, flag);
+        if (event.isCancelled()) {
+            return;
+        }
+        this.entityData.set(EntityLiving.DATA_ARROW_COUNT_ID, event.getNewAmount());
+    }
+    // CraftBukkit end
+
     public final int getStingerCount() {
         return (Integer) this.entityData.get(EntityLiving.DATA_STINGER_COUNT_ID);
     }
@@ -2182,6 +2665,12 @@
 
     public abstract ItemStack getItemBySlot(EnumItemSlot enumitemslot);
 
+    // CraftBukkit start
+    public void setItemSlot(EnumItemSlot enumitemslot, ItemStack itemstack, boolean silent) {
+        this.setItemSlot(enumitemslot, itemstack);
+    }
+    // CraftBukkit end
+
     public abstract void setItemSlot(EnumItemSlot enumitemslot, ItemStack itemstack);
 
     public Iterable<ItemStack> getHandSlots() {
@@ -2634,7 +3123,7 @@
                 }
             }
 
-            this.detectEquipmentUpdates();
+            this.detectEquipmentUpdatesPublic(); // CraftBukkit
             if (this.tickCount % 20 == 0) {
                 this.getCombatTracker().recheckStatus();
             }
@@ -2741,7 +3230,7 @@
         this.elytraAnimationState.tick();
     }
 
-    public void detectEquipmentUpdates() {
+    public void detectEquipmentUpdatesPublic() { // CraftBukkit
         Map<EnumItemSlot, ItemStack> map = this.collectEquipmentChanges();
 
         if (map != null) {
@@ -3063,6 +3552,7 @@
         this.checkSlowFallDistance();
         if (!this.level().isClientSide) {
             if (!this.canGlide()) {
+                if (this.getSharedFlag(7) != false && !CraftEventFactory.callToggleGlideEvent(this, false).isCancelled()) // CraftBukkit
                 this.setSharedFlag(7, false);
                 return;
             }
@@ -3305,14 +3795,21 @@
 
     @Override
     public boolean isPickable() {
-        return !this.isRemoved();
+        return !this.isRemoved() && this.collides; // CraftBukkit
     }
 
     @Override
     public boolean isPushable() {
-        return this.isAlive() && !this.isSpectator() && !this.onClimbable();
+        return this.isAlive() && !this.isSpectator() && !this.onClimbable() && this.collides; // CraftBukkit
     }
 
+    // CraftBukkit start - collidable API
+    @Override
+    public boolean canCollideWithBukkit(Entity entity) {
+        return isPushable() && this.collides != this.collidableExemptions.contains(entity.getUUID());
+    }
+    // CraftBukkit end
+
     @Override
     public float getYHeadRot() {
         return this.yHeadRot;
@@ -3483,7 +3980,30 @@
                 this.releaseUsingItem();
             } else {
                 if (!this.useItem.isEmpty() && this.isUsingItem()) {
-                    ItemStack itemstack = this.useItem.finishUsingItem(this.level(), this);
+                    // CraftBukkit start - fire PlayerItemConsumeEvent
+                    ItemStack itemstack;
+                    if (this instanceof EntityPlayer entityPlayer) {
+                        org.bukkit.inventory.ItemStack craftItem = CraftItemStack.asBukkitCopy(this.useItem);
+                        org.bukkit.inventory.EquipmentSlot hand = org.bukkit.craftbukkit.CraftEquipmentSlot.getHand(enumhand);
+                        PlayerItemConsumeEvent event = new PlayerItemConsumeEvent((Player) this.getBukkitEntity(), craftItem, hand);
+                        this.level().getCraftServer().getPluginManager().callEvent(event);
+
+                        if (event.isCancelled()) {
+                            // Update client
+                            Consumable consumable = this.useItem.get(DataComponents.CONSUMABLE);
+                            if (consumable != null) {
+                                consumable.cancelUsingItem(entityPlayer, this.useItem);
+                            }
+                            entityPlayer.getBukkitEntity().updateInventory();
+                            entityPlayer.getBukkitEntity().updateScaledHealth();
+                            return;
+                        }
+
+                        itemstack = (craftItem.equals(event.getItem())) ? this.useItem.finishUsingItem(this.level(), this) : CraftItemStack.asNMSCopy(event.getItem()).finishUsingItem(this.level(), this);
+                    } else {
+                        itemstack = this.useItem.finishUsingItem(this.level(), this);
+                    }
+                    // CraftBukkit end
 
                     if (itemstack != this.useItem) {
                         this.setItemInHand(enumhand, itemstack);
@@ -3568,6 +4088,12 @@
     }
 
     public boolean randomTeleport(double d0, double d1, double d2, boolean flag) {
+        // CraftBukkit start
+        return randomTeleport(d0, d1, d2, flag, org.bukkit.event.player.PlayerTeleportEvent.TeleportCause.UNKNOWN).orElse(false);
+    }
+
+    public Optional<Boolean> randomTeleport(double d0, double d1, double d2, boolean flag, org.bukkit.event.player.PlayerTeleportEvent.TeleportCause cause) {
+        // CraftBukkit end
         double d3 = this.getX();
         double d4 = this.getY();
         double d5 = this.getZ();
@@ -3592,16 +4118,41 @@
             }
 
             if (flag2) {
-                this.teleportTo(d0, d6, d2);
+                // CraftBukkit start - Teleport event
+                // this.teleportTo(d0, d6, d2);
+
+                // first set position, to check if the place to teleport is valid
+                this.setPos(d0, d6, d2);
                 if (world.noCollision((Entity) this) && !world.containsAnyLiquid(this.getBoundingBox())) {
                     flag1 = true;
                 }
+                // now revert and call event if the teleport place is valid
+                this.setPos(d3, d4, d5);
+
+                if (flag1) {
+                    if (!(this instanceof EntityPlayer)) {
+                        EntityTeleportEvent teleport = new EntityTeleportEvent(this.getBukkitEntity(), new Location(this.level().getWorld(), d3, d4, d5), new Location(this.level().getWorld(), d0, d6, d2));
+                        this.level().getCraftServer().getPluginManager().callEvent(teleport);
+                        if (!teleport.isCancelled()) {
+                            Location to = teleport.getTo();
+                            this.teleportTo(to.getX(), to.getY(), to.getZ());
+                        } else {
+                            return Optional.empty();
+                        }
+                    } else {
+                        // player teleport event is called in the underlining code
+                        if (!((EntityPlayer) this).connection.teleport(d0, d6, d2, this.getYRot(), this.getXRot(), cause)) {
+                            return Optional.empty();
+                        }
+                    }
+                }
+                // CraftBukkit end
             }
         }
 
         if (!flag1) {
-            this.teleportTo(d3, d4, d5);
-            return false;
+            // this.enderTeleportTo(d3, d4, d5); // CraftBukkit - already set the location back
+            return Optional.of(false); // CraftBukkit
         } else {
             if (flag) {
                 world.broadcastEntityEvent(this, (byte) 46);
@@ -3613,7 +4164,7 @@
                 entitycreature.getNavigation().stop();
             }
 
-            return true;
+            return Optional.of(true); // CraftBukkit
         }
     }
 
@@ -3706,7 +4257,7 @@
     }
 
     public void stopSleeping() {
-        Optional optional = this.getSleepingPos();
+        Optional<BlockPosition> optional = this.getSleepingPos(); // CraftBukkit - decompile error
         World world = this.level();
 
         java.util.Objects.requireNonNull(world);
@@ -3740,7 +4291,7 @@
 
     @Nullable
     public EnumDirection getBedOrientation() {
-        BlockPosition blockposition = (BlockPosition) this.getSleepingPos().orElse((Object) null);
+        BlockPosition blockposition = (BlockPosition) this.getSleepingPos().orElse(null); // CraftBukkit - decompile error
 
         return blockposition != null ? BlockBed.getBedOrientation(this.level(), blockposition) : null;
     }
