--- a/net/minecraft/server/level/EntityPlayer.java +++ b/net/minecraft/server/level/EntityPlayer.java @@ -140,6 +140,34 @@ import net.minecraft.world.scores.criteria.IScoreboardCriteria; import org.slf4j.Logger; +// CraftBukkit start +import net.minecraft.nbt.NBTBase; +import net.minecraft.world.damagesource.CombatTracker; +import net.minecraft.world.food.FoodMetaData; +import net.minecraft.world.item.enchantment.EnchantmentManager; +import net.minecraft.world.level.block.BlockChest; +import net.minecraft.world.level.dimension.WorldDimension; +import net.minecraft.world.scores.Scoreboard; +import org.bukkit.Bukkit; +import org.bukkit.Location; +import org.bukkit.WeatherType; +import org.bukkit.craftbukkit.CraftWorld; +import org.bukkit.craftbukkit.CraftWorldBorder; +import org.bukkit.craftbukkit.entity.CraftPlayer; +import org.bukkit.craftbukkit.event.CraftEventFactory; +import org.bukkit.craftbukkit.event.CraftPortalEvent; +import org.bukkit.craftbukkit.inventory.CraftItemStack; +import org.bukkit.craftbukkit.util.CraftDimensionUtil; +import org.bukkit.event.player.PlayerBedLeaveEvent; +import org.bukkit.event.player.PlayerChangedMainHandEvent; +import org.bukkit.event.player.PlayerChangedWorldEvent; +import org.bukkit.event.player.PlayerLocaleChangeEvent; +import org.bukkit.event.player.PlayerPortalEvent; +import org.bukkit.event.player.PlayerTeleportEvent; +import org.bukkit.event.player.PlayerTeleportEvent.TeleportCause; +import org.bukkit.inventory.MainHand; +// CraftBukkit end + public class EntityPlayer extends EntityHuman { private static final Logger LOGGER = LogUtils.getLogger(); @@ -194,6 +222,21 @@ public int latency; public boolean wonGame; + // CraftBukkit start + public String displayName; + public IChatBaseComponent listName; + public org.bukkit.Location compassTarget; + public int newExp = 0; + public int newLevel = 0; + public int newTotalExp = 0; + public boolean keepLevel = false; + public double maxHealthCache; + public boolean joining = true; + public boolean sentListPacket = false; + public Integer clientViewDistance; + public String kickLeaveMessage = null; // SPIGOT-3034: Forward leave message to PlayerQuitEvent + // CraftBukkit end + public EntityPlayer(MinecraftServer minecraftserver, WorldServer worldserver, GameProfile gameprofile) { super(worldserver, worldserver.getSharedSpawnPos(), worldserver.getSharedSpawnAngle(), gameprofile); this.chatVisibility = EnumChatVisibility.FULL; @@ -256,12 +299,56 @@ this.advancements = minecraftserver.getPlayerList().getPlayerAdvancements(this); this.maxUpStep = 1.0F; this.fudgeSpawnLocation(worldserver); + + // CraftBukkit start + this.displayName = this.getScoreboardName(); + this.bukkitPickUpLoot = true; + this.maxHealthCache = this.getMaxHealth(); + } + + // Yes, this doesn't match Vanilla, but it's the best we can do for now. + // If this is an issue, PRs are welcome + public final BlockPosition getSpawnPoint(WorldServer worldserver) { + BlockPosition blockposition = worldserver.getSharedSpawnPos(); + + if (worldserver.dimensionType().hasSkyLight() && worldserver.serverLevelData.getGameType() != EnumGamemode.ADVENTURE) { + int i = Math.max(0, this.server.getSpawnRadius(worldserver)); + int j = MathHelper.floor(worldserver.getWorldBorder().getDistanceToBorder((double) blockposition.getX(), (double) blockposition.getZ())); + + if (j < i) { + i = j; + } + + if (j <= 1) { + i = 1; + } + + long k = (long) (i * 2 + 1); + long l = k * k; + int i1 = l > 2147483647L ? Integer.MAX_VALUE : (int) l; + int j1 = this.getCoprime(i1); + int k1 = (new Random()).nextInt(i1); + + for (int l1 = 0; l1 < i1; ++l1) { + int i2 = (k1 + j1 * l1) % i1; + int j2 = i2 % (i * 2 + 1); + int k2 = i2 / (i * 2 + 1); + BlockPosition blockposition1 = WorldProviderNormal.getOverworldRespawnPos(worldserver, blockposition.getX() + j2 - i, blockposition.getZ() + k2 - i); + + if (blockposition1 != null) { + return blockposition1; + } + } + } + + return blockposition; } + // CraftBukkit end private void fudgeSpawnLocation(WorldServer worldserver) { BlockPosition blockposition = worldserver.getSharedSpawnPos(); - if (worldserver.dimensionType().hasSkyLight() && worldserver.getServer().getWorldData().getGameType() != EnumGamemode.ADVENTURE) { + if (worldserver.dimensionType().hasSkyLight() && worldserver.serverLevelData.getGameType() != EnumGamemode.ADVENTURE) { // CraftBukkit int i = Math.max(0, this.server.getSpawnRadius(worldserver)); int j = MathHelper.floor(worldserver.getWorldBorder().getDistanceToBorder((double) blockposition.getX(), (double) blockposition.getZ())); @@ -319,17 +406,26 @@ if (nbttagcompound.contains("recipeBook", 10)) { this.recipeBook.fromNbt(nbttagcompound.getCompound("recipeBook"), this.server.getRecipeManager()); } + this.getBukkitEntity().readExtraData(nbttagcompound); // CraftBukkit if (this.isSleeping()) { this.stopSleeping(); } + // CraftBukkit start + String spawnWorld = nbttagcompound.getString("SpawnWorld"); + CraftWorld oldWorld = (CraftWorld) Bukkit.getWorld(spawnWorld); + if (oldWorld != null) { + this.respawnDimension = oldWorld.getHandle().dimension(); + } + // CraftBukkit end + if (nbttagcompound.contains("SpawnX", 99) && nbttagcompound.contains("SpawnY", 99) && nbttagcompound.contains("SpawnZ", 99)) { this.respawnPosition = new BlockPosition(nbttagcompound.getInt("SpawnX"), nbttagcompound.getInt("SpawnY"), nbttagcompound.getInt("SpawnZ")); this.respawnForced = nbttagcompound.getBoolean("SpawnForced"); this.respawnAngle = nbttagcompound.getFloat("SpawnAngle"); if (nbttagcompound.contains("SpawnDimension")) { - DataResult dataresult = World.RESOURCE_KEY_CODEC.parse(DynamicOpsNBT.INSTANCE, nbttagcompound.get("SpawnDimension")); + DataResult> dataresult = World.RESOURCE_KEY_CODEC.parse(DynamicOpsNBT.INSTANCE, nbttagcompound.get("SpawnDimension")); // CraftBukkit - decompile error Logger logger = EntityPlayer.LOGGER; Objects.requireNonNull(logger); @@ -356,7 +452,20 @@ Entity entity = this.getRootVehicle(); Entity entity1 = this.getVehicle(); - if (entity1 != null && entity != this && entity.hasExactlyOnePlayerPassenger()) { + // CraftBukkit start - handle non-persistent vehicles + boolean persistVehicle = true; + if (entity1 != null) { + Entity vehicle; + for (vehicle = entity1; vehicle != null; vehicle = vehicle.getVehicle()) { + if (!vehicle.persist) { + persistVehicle = false; + break; + } + } + } + + if (persistVehicle && entity1 != null && entity != this && entity.hasExactlyOnePlayerPassenger()) { + // CraftBukkit end NBTTagCompound nbttagcompound2 = new NBTTagCompound(); NBTTagCompound nbttagcompound3 = new NBTTagCompound(); @@ -374,7 +483,7 @@ nbttagcompound.putInt("SpawnZ", this.respawnPosition.getZ()); nbttagcompound.putBoolean("SpawnForced", this.respawnForced); nbttagcompound.putFloat("SpawnAngle", this.respawnAngle); - DataResult dataresult = MinecraftKey.CODEC.encodeStart(DynamicOpsNBT.INSTANCE, this.respawnDimension.location()); + DataResult dataresult = MinecraftKey.CODEC.encodeStart(DynamicOpsNBT.INSTANCE, this.respawnDimension.location()); // CraftBukkit - decompile error Logger logger = EntityPlayer.LOGGER; Objects.requireNonNull(logger); @@ -382,9 +491,33 @@ nbttagcompound.put("SpawnDimension", nbtbase); }); } + this.getBukkitEntity().setExtraData(nbttagcompound); // CraftBukkit } + // CraftBukkit start - World fallback code, either respawn location or global spawn + public void spawnIn(World world) { + this.level = world; + if (world == null) { + this.unsetRemoved(); + Vec3D position = null; + if (this.respawnDimension != null) { + world = this.getLevel().getCraftServer().getHandle().getServer().getLevel(this.respawnDimension); + if (world != null && this.getRespawnPosition() != null) { + position = EntityHuman.findRespawnPositionAndUseSpawnBlock((WorldServer) world, this.getRespawnPosition(), this.getRespawnAngle(), false, false).orElse(null); + } + } + if (world == null || position == null) { + world = ((CraftWorld) Bukkit.getServer().getWorlds().get(0)).getHandle(); + position = Vec3D.atCenterOf(((WorldServer) world).getSharedSpawnPos()); + } + this.level = world; + this.setPos(position.x(), position.y(), position.z()); + } + this.gameMode.setLevel((WorldServer) world); + } + // CraftBukkit end + public void setExperiencePoints(int i) { float f = (float) this.getXpNeededForNextLevel(); float f1 = (f - 1.0F) / f; @@ -443,6 +576,11 @@ @Override public void tick() { + // CraftBukkit start + if (this.joining) { + this.joining = false; + } + // CraftBukkit end this.gameMode.tick(); --this.spawnInvulnerableTime; if (this.invulnerableTime > 0) { @@ -498,7 +636,7 @@ } if (this.getHealth() != this.lastSentHealth || this.lastSentFood != this.foodData.getFoodLevel() || this.foodData.getSaturationLevel() == 0.0F != this.lastFoodSaturationZero) { - this.connection.send(new PacketPlayOutUpdateHealth(this.getHealth(), this.foodData.getFoodLevel(), this.foodData.getSaturationLevel())); + this.connection.send(new PacketPlayOutUpdateHealth(this.getBukkitEntity().getScaledHealth(), this.foodData.getFoodLevel(), this.foodData.getSaturationLevel())); // CraftBukkit this.lastSentHealth = this.getHealth(); this.lastSentFood = this.foodData.getFoodLevel(); this.lastFoodSaturationZero = this.foodData.getSaturationLevel() == 0.0F; @@ -529,6 +667,12 @@ this.updateScoreForCriteria(IScoreboardCriteria.EXPERIENCE, MathHelper.ceil((float) this.lastRecordedExperience)); } + // CraftBukkit start - Force max health updates + if (this.maxHealthCache != this.getMaxHealth()) { + this.getBukkitEntity().updateScaledHealth(); + } + // CraftBukkit end + if (this.experienceLevel != this.lastRecordedLevel) { this.lastRecordedLevel = this.experienceLevel; this.updateScoreForCriteria(IScoreboardCriteria.LEVEL, MathHelper.ceil((float) this.lastRecordedLevel)); @@ -543,6 +687,20 @@ CriterionTriggers.LOCATION.trigger(this); } + // CraftBukkit start - initialize oldLevel, fire PlayerLevelChangeEvent, and tick client-sided world border + if (this.oldLevel == -1) { + this.oldLevel = this.experienceLevel; + } + + if (this.oldLevel != this.experienceLevel) { + CraftEventFactory.callPlayerLevelChangeEvent(this.getBukkitEntity(), this.oldLevel, this.experienceLevel); + this.oldLevel = this.experienceLevel; + } + + if (this.getBukkitEntity().hasClientWorldBorder()) { + ((CraftWorldBorder) this.getBukkitEntity().getWorldBorder()).getHandle().tick(); + } + // CraftBukkit end } catch (Throwable throwable) { CrashReport crashreport = CrashReport.forThrowable(throwable, "Ticking player"); CrashReportSystemDetails crashreportsystemdetails = crashreport.addCategory("Player being ticked"); @@ -585,7 +743,8 @@ } private void updateScoreForCriteria(IScoreboardCriteria iscoreboardcriteria, int i) { - this.getScoreboard().forAllObjectives(iscoreboardcriteria, this.getScoreboardName(), (scoreboardscore) -> { + // CraftBukkit - Use our scores instead + this.level.getCraftServer().getScoreboardManager().getScoreboardScores(iscoreboardcriteria, this.getScoreboardName(), (scoreboardscore) -> { scoreboardscore.setScore(i); }); } @@ -593,9 +752,47 @@ @Override public void die(DamageSource damagesource) { boolean flag = this.level.getGameRules().getBoolean(GameRules.RULE_SHOWDEATHMESSAGES); + // CraftBukkit start - fire PlayerDeathEvent + if (this.isRemoved()) { + return; + } + java.util.List loot = new java.util.ArrayList(this.getInventory().getContainerSize()); + boolean keepInventory = this.level.getGameRules().getBoolean(GameRules.RULE_KEEPINVENTORY) || this.isSpectator(); + + if (!keepInventory) { + for (ItemStack item : this.getInventory().getContents()) { + if (!item.isEmpty() && !EnchantmentManager.hasVanishingCurse(item)) { + loot.add(CraftItemStack.asCraftMirror(item)); + } + } + } + // SPIGOT-5071: manually add player loot tables (SPIGOT-5195 - ignores keepInventory rule) + this.dropFromLootTable(damagesource, this.lastHurtByPlayerTime > 0); + for (org.bukkit.inventory.ItemStack item : this.drops) { + loot.add(item); + } + this.drops.clear(); // SPIGOT-5188: make sure to clear - if (flag) { - IChatBaseComponent ichatbasecomponent = this.getCombatTracker().getDeathMessage(); + IChatBaseComponent defaultMessage = this.getCombatTracker().getDeathMessage(); + + String deathmessage = defaultMessage.getString(); + keepLevel = keepInventory; // SPIGOT-2222: pre-set keepLevel + org.bukkit.event.entity.PlayerDeathEvent event = CraftEventFactory.callPlayerDeathEvent(this, loot, deathmessage, keepInventory); + + // SPIGOT-943 - only call if they have an inventory open + if (this.containerMenu != this.inventoryMenu) { + this.closeContainer(); + } + + String deathMessage = event.getDeathMessage(); + + if (deathMessage != null && deathMessage.length() > 0 && flag) { // TODO: allow plugins to override? + IChatBaseComponent ichatbasecomponent; + if (deathMessage.equals(deathmessage)) { + ichatbasecomponent = this.getCombatTracker().getDeathMessage(); + } else { + ichatbasecomponent = org.bukkit.craftbukkit.util.CraftChatMessage.fromStringOrNull(deathMessage); + } this.connection.send(new ClientboundPlayerCombatKillPacket(this.getCombatTracker(), ichatbasecomponent), (future) -> { if (!future.isSuccess()) { @@ -629,12 +826,18 @@ if (this.level.getGameRules().getBoolean(GameRules.RULE_FORGIVE_DEAD_PLAYERS)) { this.tellNeutralMobsThatIDied(); } - - if (!this.isSpectator()) { - this.dropAllDeathLoot(damagesource); + // SPIGOT-5478 must be called manually now + this.dropExperience(); + // we clean the player's inventory after the EntityDeathEvent is called so plugins can get the exact state of the inventory. + if (!event.getKeepInventory()) { + this.getInventory().clearContent(); } - this.getScoreboard().forAllObjectives(IScoreboardCriteria.DEATH_COUNT, this.getScoreboardName(), ScoreboardScore::increment); + this.setCamera(this); // Remove spectated target + // CraftBukkit end + + // CraftBukkit - Get our scores instead + this.level.getCraftServer().getScoreboardManager().getScoreboardScores(IScoreboardCriteria.DEATH_COUNT, this.getScoreboardName(), ScoreboardScore::increment); EntityLiving entityliving = this.getKillCredit(); if (entityliving != null) { @@ -671,10 +874,12 @@ String s = this.getScoreboardName(); String s1 = entity.getScoreboardName(); - this.getScoreboard().forAllObjectives(IScoreboardCriteria.KILL_COUNT_ALL, s, ScoreboardScore::increment); + // CraftBukkit - Get our scores instead + this.level.getCraftServer().getScoreboardManager().getScoreboardScores(IScoreboardCriteria.KILL_COUNT_ALL, s, ScoreboardScore::increment); if (entity instanceof EntityHuman) { this.awardStat(StatisticList.PLAYER_KILLS); - this.getScoreboard().forAllObjectives(IScoreboardCriteria.KILL_COUNT_PLAYERS, s, ScoreboardScore::increment); + // CraftBukkit - Get our scores instead + this.level.getCraftServer().getScoreboardManager().getScoreboardScores(IScoreboardCriteria.KILL_COUNT_PLAYERS, s, ScoreboardScore::increment); } else { this.awardStat(StatisticList.MOB_KILLS); } @@ -692,7 +897,8 @@ int i = scoreboardteam.getColor().getId(); if (i >= 0 && i < aiscoreboardcriteria.length) { - this.getScoreboard().forAllObjectives(aiscoreboardcriteria[i], s, ScoreboardScore::increment); + // CraftBukkit - Get our scores instead + this.level.getCraftServer().getScoreboardManager().getScoreboardScores(aiscoreboardcriteria[i], s, ScoreboardScore::increment); } } @@ -736,18 +942,20 @@ } private boolean isPvpAllowed() { - return this.server.isPvpAllowed(); + // CraftBukkit - this.server.isPvpAllowed() -> this.world.pvpMode + return this.level.pvpMode; } @Nullable @Override protected ShapeDetectorShape findDimensionEntryPoint(WorldServer worldserver) { ShapeDetectorShape shapedetectorshape = super.findDimensionEntryPoint(worldserver); + worldserver = (shapedetectorshape == null) ? worldserver : shapedetectorshape.world; // CraftBukkit - if (shapedetectorshape != null && this.level.dimension() == World.OVERWORLD && worldserver.dimension() == World.END) { + if (shapedetectorshape != null && this.level.getTypeKey() == WorldDimension.OVERWORLD && worldserver != null && worldserver.getTypeKey() == WorldDimension.END) { // CraftBukkit Vec3D vec3d = shapedetectorshape.pos.add(0.0D, -1.0D, 0.0D); - return new ShapeDetectorShape(vec3d, Vec3D.ZERO, 90.0F, 0.0F); + return new ShapeDetectorShape(vec3d, Vec3D.ZERO, 90.0F, 0.0F, worldserver, shapedetectorshape.portalEventInfo); // CraftBukkit } else { return shapedetectorshape; } @@ -756,11 +964,20 @@ @Nullable @Override public Entity changeDimension(WorldServer worldserver) { - this.isChangingDimension = true; + // CraftBukkit start + return changeDimension(worldserver, TeleportCause.UNKNOWN); + } + + @Nullable + public Entity changeDimension(WorldServer worldserver, PlayerTeleportEvent.TeleportCause cause) { + // CraftBukkit end + if (this.isSleeping()) return this; // CraftBukkit - SPIGOT-3154 + // this.isChangingDimension = true; // CraftBukkit - Moved down and into PlayerList#changeDimension WorldServer worldserver1 = this.getLevel(); - ResourceKey resourcekey = worldserver1.dimension(); + ResourceKey resourcekey = worldserver1.getTypeKey(); // CraftBukkit - if (resourcekey == World.END && worldserver.dimension() == World.OVERWORLD) { + if (resourcekey == WorldDimension.END && worldserver != null && worldserver.getTypeKey() == WorldDimension.OVERWORLD) { // CraftBukkit + this.isChangingDimension = true; // CraftBukkit - Moved down from above this.unRide(); this.getLevel().removePlayerImmediately(this, Entity.RemovalReason.CHANGED_DIMENSION); if (!this.wonGame) { @@ -771,6 +988,8 @@ return this; } else { + // CraftBukkit start + /* WorldData worlddata = worldserver.getLevelData(); this.connection.send(new PacketPlayOutRespawn(worldserver.dimensionTypeRegistration(), worldserver.dimension(), BiomeManager.obfuscateSeed(worldserver.getSeed()), this.gameMode.getGameModeForPlayer(), this.gameMode.getPreviousGameModeForPlayer(), worldserver.isDebug(), worldserver.isFlat(), true)); @@ -780,22 +999,52 @@ playerlist.sendPlayerPermissionLevel(this); worldserver1.removePlayerImmediately(this, Entity.RemovalReason.CHANGED_DIMENSION); this.unsetRemoved(); + */ + // CraftBukkit end ShapeDetectorShape shapedetectorshape = this.findDimensionEntryPoint(worldserver); if (shapedetectorshape != null) { worldserver1.getProfiler().push("moving"); - if (resourcekey == World.OVERWORLD && worldserver.dimension() == World.NETHER) { + worldserver = shapedetectorshape.world; // CraftBukkit + if (worldserver == null) { } else // CraftBukkit - empty to fall through to null to event + if (resourcekey == WorldDimension.OVERWORLD && worldserver.getTypeKey() == WorldDimension.NETHER) { // CraftBukkit this.enteredNetherPosition = this.position(); - } else if (worldserver.dimension() == World.END) { + } else if (worldserver.getTypeKey() == WorldDimension.END && shapedetectorshape.portalEventInfo != null && shapedetectorshape.portalEventInfo.getCanCreatePortal()) { // CraftBukkit this.createEndPlatform(worldserver, new BlockPosition(shapedetectorshape.pos)); } + // CraftBukkit start + } else { + return null; + } + Location enter = this.getBukkitEntity().getLocation(); + Location exit = (worldserver == null) ? null : new Location(worldserver.getWorld(), shapedetectorshape.pos.x, shapedetectorshape.pos.y, shapedetectorshape.pos.z, shapedetectorshape.yRot, shapedetectorshape.xRot); + PlayerTeleportEvent tpEvent = new PlayerTeleportEvent(this.getBukkitEntity(), enter, exit, cause); + Bukkit.getServer().getPluginManager().callEvent(tpEvent); + if (tpEvent.isCancelled() || tpEvent.getTo() == null) { + return null; + } + exit = tpEvent.getTo(); + worldserver = ((CraftWorld) exit.getWorld()).getHandle(); + // CraftBukkit end + + worldserver1.getProfiler().pop(); + worldserver1.getProfiler().push("placing"); + if (true) { // CraftBukkit + this.isChangingDimension = true; // CraftBukkit - Set teleport invulnerability only if player changing worlds + + this.connection.send(new PacketPlayOutRespawn(worldserver.dimensionTypeRegistration(), worldserver.dimension(), BiomeManager.obfuscateSeed(worldserver.getSeed()), this.gameMode.getGameModeForPlayer(), this.gameMode.getPreviousGameModeForPlayer(), worldserver.isDebug(), worldserver.isFlat(), true)); + this.connection.send(new PacketPlayOutServerDifficulty(this.level.getDifficulty(), this.level.getLevelData().isDifficultyLocked())); + PlayerList playerlist = this.server.getPlayerList(); + + playerlist.sendPlayerPermissionLevel(this); + worldserver1.removePlayerImmediately(this, Entity.RemovalReason.CHANGED_DIMENSION); + this.unsetRemoved(); - worldserver1.getProfiler().pop(); - worldserver1.getProfiler().push("placing"); + // CraftBukkit end this.setLevel(worldserver); worldserver.addDuringPortalTeleport(this); - this.setRot(shapedetectorshape.yRot, shapedetectorshape.xRot); - this.moveTo(shapedetectorshape.pos.x, shapedetectorshape.pos.y, shapedetectorshape.pos.z); + this.connection.teleport(exit); // CraftBukkit - use internal teleport without event + this.connection.resetPosition(); // CraftBukkit - sync position after changing it (from PortalTravelAgent#findAndteleport) worldserver1.getProfiler().pop(); this.triggerDimensionChangeTriggers(worldserver1); this.connection.send(new PacketPlayOutAbilities(this.getAbilities())); @@ -813,12 +1062,31 @@ this.lastSentExp = -1; this.lastSentHealth = -1.0F; this.lastSentFood = -1; + + // CraftBukkit start + PlayerChangedWorldEvent changeEvent = new PlayerChangedWorldEvent(this.getBukkitEntity(), worldserver1.getWorld()); + this.level.getCraftServer().getPluginManager().callEvent(changeEvent); + // CraftBukkit end } return this; } } + // CraftBukkit start + @Override + protected CraftPortalEvent callPortalEvent(Entity entity, WorldServer exitWorldServer, BlockPosition exitPosition, TeleportCause cause, int searchRadius, int creationRadius) { + Location enter = this.getBukkitEntity().getLocation(); + Location exit = new Location(exitWorldServer.getWorld(), exitPosition.getX(), exitPosition.getY(), exitPosition.getZ(), getYRot(), getXRot()); + PlayerPortalEvent event = new PlayerPortalEvent(this.getBukkitEntity(), enter, exit, cause, searchRadius, true, creationRadius); + Bukkit.getServer().getPluginManager().callEvent(event); + if (event.isCancelled() || event.getTo() == null || event.getTo().getWorld() == null) { + return null; + } + return new CraftPortalEvent(event); + } + // CraftBukkit end + private void createEndPlatform(WorldServer worldserver, BlockPosition blockposition) { BlockPosition.MutableBlockPosition blockposition_mutableblockposition = blockposition.mutable(); @@ -835,17 +1103,17 @@ } @Override - protected Optional getExitPortal(WorldServer worldserver, BlockPosition blockposition, boolean flag, WorldBorder worldborder) { - Optional optional = super.getExitPortal(worldserver, blockposition, flag, worldborder); + protected Optional getExitPortal(WorldServer worldserver, BlockPosition blockposition, boolean flag, WorldBorder worldborder, int searchRadius, boolean canCreatePortal, int createRadius) { // CraftBukkit + Optional optional = super.getExitPortal(worldserver, blockposition, flag, worldborder, searchRadius, canCreatePortal, createRadius); // CraftBukkit - if (optional.isPresent()) { + if (optional.isPresent() || !canCreatePortal) { // CraftBukkit return optional; } else { EnumDirection.EnumAxis enumdirection_enumaxis = (EnumDirection.EnumAxis) this.level.getBlockState(this.portalEntrancePos).getOptionalValue(BlockPortal.AXIS).orElse(EnumDirection.EnumAxis.X); - Optional optional1 = worldserver.getPortalForcer().createPortal(blockposition, enumdirection_enumaxis); + Optional optional1 = worldserver.getPortalForcer().createPortal(blockposition, enumdirection_enumaxis, this, createRadius); // CraftBukkit if (!optional1.isPresent()) { - EntityPlayer.LOGGER.error("Unable to create a portal, likely target out of worldborder"); + // EntityPlayer.LOGGER.error("Unable to create a portal, likely target out of worldborder"); // CraftBukkit } return optional1; @@ -855,13 +1123,21 @@ public void triggerDimensionChangeTriggers(WorldServer worldserver) { ResourceKey resourcekey = worldserver.dimension(); ResourceKey resourcekey1 = this.level.dimension(); + // CraftBukkit start + ResourceKey maindimensionkey = CraftDimensionUtil.getMainDimensionKey(worldserver); + ResourceKey maindimensionkey1 = CraftDimensionUtil.getMainDimensionKey(this.level); + + CriterionTriggers.CHANGED_DIMENSION.trigger(this, maindimensionkey, maindimensionkey1); + if (maindimensionkey != resourcekey || maindimensionkey1 != resourcekey1) { + CriterionTriggers.CHANGED_DIMENSION.trigger(this, resourcekey, resourcekey1); + } - CriterionTriggers.CHANGED_DIMENSION.trigger(this, resourcekey, resourcekey1); - if (resourcekey == World.NETHER && resourcekey1 == World.OVERWORLD && this.enteredNetherPosition != null) { + if (maindimensionkey == World.NETHER && maindimensionkey1 == World.OVERWORLD && this.enteredNetherPosition != null) { + // CraftBukkit end CriterionTriggers.NETHER_TRAVEL.trigger(this, this.enteredNetherPosition); } - if (resourcekey1 != World.NETHER) { + if (maindimensionkey1 != World.NETHER) { // CraftBukkit this.enteredNetherPosition = null; } @@ -878,12 +1154,10 @@ this.containerMenu.broadcastChanges(); } - @Override - public Either startSleepInBed(BlockPosition blockposition) { - EnumDirection enumdirection = (EnumDirection) this.level.getBlockState(blockposition).getValue(BlockFacingHorizontal.FACING); - + // CraftBukkit start - moved bed result checks from below into separate method + private Either getBedResult(BlockPosition blockposition, EnumDirection enumdirection) { if (!this.isSleeping() && this.isAlive()) { - if (!this.level.dimensionType().natural()) { + if (!this.level.dimensionType().natural() || !this.level.dimensionType().bedWorks()) { return Either.left(EntityHuman.EnumBedResult.NOT_POSSIBLE_HERE); } else if (!this.bedInRange(blockposition, enumdirection)) { return Either.left(EntityHuman.EnumBedResult.TOO_FAR_AWAY); @@ -907,7 +1181,36 @@ } } - Either either = super.startSleepInBed(blockposition).ifRight((unit) -> { + return Either.right(Unit.INSTANCE); + } + } + } else { + return Either.left(EntityHuman.EnumBedResult.OTHER_PROBLEM); + } + } + + @Override + public Either startSleepInBed(BlockPosition blockposition, boolean force) { + EnumDirection enumdirection = (EnumDirection) this.level.getBlockState(blockposition).getValue(BlockFacingHorizontal.FACING); + Either bedResult = this.getBedResult(blockposition, enumdirection); + + if (bedResult.left().orElse(null) == EntityHuman.EnumBedResult.OTHER_PROBLEM) { + return bedResult; // return immediately if the result is not bypassable by plugins + } + + if (force) { + bedResult = Either.right(Unit.INSTANCE); + } + + bedResult = org.bukkit.craftbukkit.event.CraftEventFactory.callPlayerBedEnterEvent(this, blockposition, bedResult); + if (bedResult.left().isPresent()) { + return bedResult; + } + + { + { + { + Either either = super.startSleepInBed(blockposition, force).ifRight((unit) -> { this.awardStat(StatisticList.SLEEP_IN_BED); CriterionTriggers.SLEPT_IN_BED.trigger(this); }); @@ -920,9 +1223,8 @@ return either; } } - } else { - return Either.left(EntityHuman.EnumBedResult.OTHER_PROBLEM); } + // CraftBukkit end } @Override @@ -949,6 +1251,24 @@ @Override public void stopSleepInBed(boolean flag, boolean flag1) { + if (!this.isSleeping()) return; // CraftBukkit - Can't leave bed if not in one! + // CraftBukkit start - fire PlayerBedLeaveEvent + CraftPlayer player = this.getBukkitEntity(); + BlockPosition bedPosition = this.getSleepingPos().orElse(null); + + org.bukkit.block.Block bed; + if (bedPosition != null) { + bed = this.level.getWorld().getBlockAt(bedPosition.getX(), bedPosition.getY(), bedPosition.getZ()); + } else { + bed = this.level.getWorld().getBlockAt(player.getLocation()); + } + + PlayerBedLeaveEvent event = new PlayerBedLeaveEvent(player, bed, true); + this.level.getCraftServer().getPluginManager().callEvent(event); + if (event.isCancelled()) { + return; + } + // CraftBukkit end if (this.isSleeping()) { this.getLevel().getChunkSource().broadcastAndSend(this, new PacketPlayOutAnimation(this, 2)); } @@ -1030,8 +1350,9 @@ this.connection.send(new PacketPlayOutOpenSignEditor(tileentitysign.getBlockPos())); } - public void nextContainerCounter() { + public int nextContainerCounter() { // CraftBukkit - void -> int this.containerCounter = this.containerCounter % 100 + 1; + return containerCounter; // CraftBukkit } @Override @@ -1039,13 +1360,35 @@ if (itileinventory == null) { return OptionalInt.empty(); } else { + // CraftBukkit start - SPIGOT-6552: Handle inventory closing in CraftEventFactory#callInventoryOpenEvent(...) + /* if (this.containerMenu != this.inventoryMenu) { this.closeContainer(); } + */ + // CraftBukkit end this.nextContainerCounter(); Container container = itileinventory.createMenu(this.containerCounter, this.getInventory(), this); + // CraftBukkit start - Inventory open hook + if (container != null) { + container.setTitle(itileinventory.getDisplayName()); + + boolean cancelled = false; + container = CraftEventFactory.callInventoryOpenEvent(this, container, cancelled); + if (container == null && !cancelled) { // Let pre-cancelled events fall through + // SPIGOT-5263 - close chest if cancelled + if (itileinventory instanceof IInventory) { + ((IInventory) itileinventory).stopOpen(this); + } else if (itileinventory instanceof BlockChest.DoubleInventory) { + // SPIGOT-5355 - double chests too :( + ((BlockChest.DoubleInventory) itileinventory).inventorylargechest.stopOpen(this); + } + return OptionalInt.empty(); + } + } + // CraftBukkit end if (container == null) { if (this.isSpectator()) { this.displayClientMessage((new ChatMessage("container.spectatorCantOpen")).withStyle(EnumChatFormat.RED), true); @@ -1053,9 +1396,11 @@ return OptionalInt.empty(); } else { - this.connection.send(new PacketPlayOutOpenWindow(container.containerId, container.getType(), itileinventory.getDisplayName())); - this.initMenu(container); + // CraftBukkit start this.containerMenu = container; + this.connection.send(new PacketPlayOutOpenWindow(container.containerId, container.getType(), container.getTitle())); + // CraftBukkit end + this.initMenu(container); return OptionalInt.of(this.containerCounter); } } @@ -1068,13 +1413,24 @@ @Override public void openHorseInventory(EntityHorseAbstract entityhorseabstract, IInventory iinventory) { + // CraftBukkit start - Inventory open hook + this.nextContainerCounter(); + Container container = new ContainerHorse(this.containerCounter, this.getInventory(), iinventory, entityhorseabstract); + container.setTitle(entityhorseabstract.getDisplayName()); + container = CraftEventFactory.callInventoryOpenEvent(this, container); + + if (container == null) { + iinventory.stopOpen(this); + return; + } + // CraftBukkit end if (this.containerMenu != this.inventoryMenu) { this.closeContainer(); } - this.nextContainerCounter(); + // this.nextContainerCounter(); // CraftBukkit - moved up this.connection.send(new PacketPlayOutOpenWindowHorse(this.containerCounter, iinventory.getContainerSize(), entityhorseabstract.getId())); - this.containerMenu = new ContainerHorse(this.containerCounter, this.getInventory(), iinventory, entityhorseabstract); + this.containerMenu = container; // CraftBukkit this.initMenu(this.containerMenu); } @@ -1097,6 +1453,7 @@ @Override public void closeContainer() { + CraftEventFactory.handleInventoryCloseEvent(this); // CraftBukkit this.connection.send(new PacketPlayOutCloseWindow(this.containerMenu.containerId)); this.doCloseContainer(); } @@ -1126,7 +1483,7 @@ @Override public void awardStat(Statistic statistic, int i) { this.stats.increment(this, statistic, i); - this.getScoreboard().forAllObjectives(statistic, this.getScoreboardName(), (scoreboardscore) -> { + this.level.getCraftServer().getScoreboardManager().getScoreboardScores(statistic, this.getScoreboardName(), (scoreboardscore) -> { // CraftBukkit - Get our scores instead scoreboardscore.add(i); }); } @@ -1134,7 +1491,7 @@ @Override public void resetStat(Statistic statistic) { this.stats.setValue(this, statistic, 0); - this.getScoreboard().forAllObjectives(statistic, this.getScoreboardName(), ScoreboardScore::reset); + this.level.getCraftServer().getScoreboardManager().getScoreboardScores(statistic, this.getScoreboardName(), ScoreboardScore::reset); // CraftBukkit - Get our scores instead } @Override @@ -1150,7 +1507,7 @@ for (int j = 0; j < i; ++j) { MinecraftKey minecraftkey = aminecraftkey1[j]; - Optional optional = this.server.getRecipeManager().byKey(minecraftkey); + Optional> optional = this.server.getRecipeManager().byKey(minecraftkey); // CraftBukkit - decompile error Objects.requireNonNull(list); optional.ifPresent(list::add); @@ -1185,7 +1542,16 @@ public void resetSentInfo() { this.lastSentHealth = -1.0E8F; + this.lastSentExp = -1; // CraftBukkit - Added to reset + } + + // CraftBukkit start - Support multi-line messages + public void sendMessage(UUID uuid, IChatBaseComponent[] ichatbasecomponent) { + for (IChatBaseComponent component : ichatbasecomponent) { + this.sendMessage(component, (uuid == null) ? SystemUtils.NIL_UUID : uuid); + } } + // CraftBukkit end @Override public void displayClientMessage(IChatBaseComponent ichatbasecomponent, boolean flag) { @@ -1240,7 +1606,7 @@ this.lastSentExp = -1; this.lastSentHealth = -1.0F; this.lastSentFood = -1; - this.recipeBook.copyOverData(entityplayer.recipeBook); + // this.recipeBook.copyOverData(entityplayer.recipeBook); // CraftBukkit this.seenCredits = entityplayer.seenCredits; this.enteredNetherPosition = entityplayer.enteredNetherPosition; this.setShoulderEntityLeft(entityplayer.getShoulderEntityLeft()); @@ -1367,7 +1733,20 @@ return s; } + public String locale = "en_us"; // CraftBukkit - add, lowercase public void updateOptions(PacketPlayInSettings packetplayinsettings) { + // CraftBukkit start + if (getMainArm() != packetplayinsettings.mainHand()) { + PlayerChangedMainHandEvent event = new PlayerChangedMainHandEvent(getBukkitEntity(), getMainArm() == EnumMainHand.LEFT ? MainHand.LEFT : MainHand.RIGHT); + this.server.server.getPluginManager().callEvent(event); + } + if (!this.locale.equals(packetplayinsettings.language)) { + PlayerLocaleChangeEvent event = new PlayerLocaleChangeEvent(getBukkitEntity(), packetplayinsettings.language); + this.server.server.getPluginManager().callEvent(event); + } + this.locale = packetplayinsettings.language; + this.clientViewDistance = packetplayinsettings.viewDistance; + // CraftBukkit end this.chatVisibility = packetplayinsettings.chatVisibility(); this.canChatColor = packetplayinsettings.chatColors(); this.textFilteringEnabled = packetplayinsettings.textFilteringEnabled(); @@ -1438,7 +1817,7 @@ this.camera = (Entity) (entity == null ? this : entity); if (entity1 != this.camera) { this.connection.send(new PacketPlayOutCamera(this.camera)); - this.teleportTo(this.camera.getX(), this.camera.getY(), this.camera.getZ()); + this.connection.teleport(this.camera.getX(), this.camera.getY(), this.camera.getZ(), this.getYRot(), this.getXRot(), TeleportCause.SPECTATE); // CraftBukkit } } @@ -1467,7 +1846,7 @@ @Nullable public IChatBaseComponent getTabListDisplayName() { - return null; + return listName; // CraftBukkit } @Override @@ -1488,9 +1867,16 @@ return this.advancements; } + // CraftBukkit start public void teleportTo(WorldServer worldserver, double d0, double d1, double d2, float f, float f1) { + this.teleportTo(worldserver, d0, d1, d2, f, f1, org.bukkit.event.player.PlayerTeleportEvent.TeleportCause.UNKNOWN); + } + + public void teleportTo(WorldServer worldserver, double d0, double d1, double d2, float f, float f1, org.bukkit.event.player.PlayerTeleportEvent.TeleportCause cause) { + // CraftBukkit end this.setCamera(this); this.stopRiding(); + /* CraftBukkit start - replace with bukkit handling for multi-world if (worldserver == this.level) { this.connection.teleport(d0, d1, d2, f, f1); } else { @@ -1510,6 +1896,9 @@ this.server.getPlayerList().sendLevelInfo(this, worldserver); this.server.getPlayerList().sendAllPlayerInfo(this); } + */ + this.getBukkitEntity().teleport(new Location(worldserver.getWorld(), d0, d1, d2, f, f1), cause); + // CraftBukkit end } @@ -1668,4 +2057,146 @@ public boolean allowsListing() { return this.allowsListing; } + + // CraftBukkit start - Add per-player time and weather. + public long timeOffset = 0; + public boolean relativeTime = true; + + public long getPlayerTime() { + if (this.relativeTime) { + // Adds timeOffset to the current server time. + return this.level.getDayTime() + this.timeOffset; + } else { + // Adds timeOffset to the beginning of this day. + return this.level.getDayTime() - (this.level.getDayTime() % 24000) + this.timeOffset; + } + } + + public WeatherType weather = null; + + public WeatherType getPlayerWeather() { + return this.weather; + } + + public void setPlayerWeather(WeatherType type, boolean plugin) { + if (!plugin && this.weather != null) { + return; + } + + if (plugin) { + this.weather = type; + } + + if (type == WeatherType.DOWNFALL) { + this.connection.send(new PacketPlayOutGameStateChange(PacketPlayOutGameStateChange.STOP_RAINING, 0)); + } else { + this.connection.send(new PacketPlayOutGameStateChange(PacketPlayOutGameStateChange.START_RAINING, 0)); + } + } + + private float pluginRainPosition; + private float pluginRainPositionPrevious; + + public void updateWeather(float oldRain, float newRain, float oldThunder, float newThunder) { + if (this.weather == null) { + // Vanilla + if (oldRain != newRain) { + this.connection.send(new PacketPlayOutGameStateChange(PacketPlayOutGameStateChange.RAIN_LEVEL_CHANGE, newRain)); + } + } else { + // Plugin + if (pluginRainPositionPrevious != pluginRainPosition) { + this.connection.send(new PacketPlayOutGameStateChange(PacketPlayOutGameStateChange.RAIN_LEVEL_CHANGE, pluginRainPosition)); + } + } + + if (oldThunder != newThunder) { + if (weather == WeatherType.DOWNFALL || weather == null) { + this.connection.send(new PacketPlayOutGameStateChange(PacketPlayOutGameStateChange.THUNDER_LEVEL_CHANGE, newThunder)); + } else { + this.connection.send(new PacketPlayOutGameStateChange(PacketPlayOutGameStateChange.THUNDER_LEVEL_CHANGE, 0)); + } + } + } + + public void tickWeather() { + if (this.weather == null) return; + + pluginRainPositionPrevious = pluginRainPosition; + if (weather == WeatherType.DOWNFALL) { + pluginRainPosition += 0.01; + } else { + pluginRainPosition -= 0.01; + } + + pluginRainPosition = MathHelper.clamp(pluginRainPosition, 0.0F, 1.0F); + } + + public void resetPlayerWeather() { + this.weather = null; + this.setPlayerWeather(this.level.getLevelData().isRaining() ? WeatherType.DOWNFALL : WeatherType.CLEAR, false); + } + + @Override + public String toString() { + return super.toString() + "(" + this.getScoreboardName() + " at " + this.getX() + "," + this.getY() + "," + this.getZ() + ")"; + } + + // SPIGOT-1903, MC-98153 + public void forceSetPositionRotation(double x, double y, double z, float yaw, float pitch) { + this.moveTo(x, y, z, yaw, pitch); + this.connection.resetPosition(); + } + + @Override + public boolean isImmobile() { + return super.isImmobile() || !getBukkitEntity().isOnline(); + } + + @Override + public Scoreboard getScoreboard() { + return getBukkitEntity().getScoreboard().getHandle(); + } + + public void reset() { + float exp = 0; + boolean keepInventory = this.level.getGameRules().getBoolean(GameRules.RULE_KEEPINVENTORY); + + if (this.keepLevel) { // CraftBukkit - SPIGOT-6687: Only use keepLevel (was pre-set with RULE_KEEPINVENTORY value in PlayerDeathEvent) + exp = this.experienceProgress; + this.newTotalExp = this.totalExperience; + this.newLevel = this.experienceLevel; + } + + this.setHealth(this.getMaxHealth()); + this.stopUsingItem(); // CraftBukkit - SPIGOT-6682: Clear active item on reset + this.remainingFireTicks = 0; + this.fallDistance = 0; + this.foodData = new FoodMetaData(this); + this.experienceLevel = this.newLevel; + this.totalExperience = this.newTotalExp; + this.experienceProgress = 0; + this.deathTime = 0; + this.setArrowCount(0, true); // CraftBukkit - ArrowBodyCountChangeEvent + this.removeAllEffects(org.bukkit.event.entity.EntityPotionEffectEvent.Cause.DEATH); + this.effectsDirty = true; + this.containerMenu = this.inventoryMenu; + this.lastHurtByPlayer = null; + this.lastHurtByMob = null; + this.combatTracker = new CombatTracker(this); + this.lastSentExp = -1; + if (this.keepLevel) { // CraftBukkit - SPIGOT-6687: Only use keepLevel (was pre-set with RULE_KEEPINVENTORY value in PlayerDeathEvent) + this.experienceProgress = exp; + } else { + this.giveExperiencePoints(this.newExp); + } + this.keepLevel = false; + this.setDeltaMovement(0, 0, 0); // CraftBukkit - SPIGOT-6948: Reset velocity on death + } + + @Override + public CraftPlayer getBukkitEntity() { + return (CraftPlayer) super.getBukkitEntity(); + } + // CraftBukkit end }