--- ../work/decompile-8eb82bde//net/minecraft/server/EntityPlayer.java	2014-12-02 15:12:17.558036243 +0000
+++ src/main/java/net/minecraft/server/EntityPlayer.java	2014-12-02 15:08:46.878040919 +0000
@@ -13,6 +13,17 @@
 import org.apache.logging.log4j.LogManager;
 import org.apache.logging.log4j.Logger;
 
+// CraftBukkit start
+import org.bukkit.Bukkit;
+import org.bukkit.WeatherType;
+import org.bukkit.craftbukkit.CraftWorld;
+import org.bukkit.craftbukkit.entity.CraftPlayer;
+import org.bukkit.craftbukkit.event.CraftEventFactory;
+import org.bukkit.craftbukkit.inventory.CraftItemStack;
+import org.bukkit.event.inventory.InventoryType;
+import org.bukkit.event.player.PlayerTeleportEvent.TeleportCause;
+// CraftBukkit end
+
 public class EntityPlayer extends EntityHuman implements ICrafting {
 
     private static final Logger bF = LogManager.getLogger();
@@ -39,6 +50,18 @@
     public boolean g;
     public int ping;
     public boolean viewingCredits;
+    
+    // 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;
+    // CraftBukkit end
 
     public EntityPlayer(MinecraftServer minecraftserver, WorldServer worldserver, GameProfile gameprofile, PlayerInteractManager playerinteractmanager) {
         super(worldserver, gameprofile);
@@ -69,7 +92,11 @@
         while (!worldserver.getCubes(this, this.getBoundingBox()).isEmpty() && this.locY < 255.0D) {
             this.setPosition(this.locX, this.locY + 1.0D, this.locZ);
         }
-
+        // CraftBukkit start
+        this.displayName = this.getName();
+        // this.canPickUpLoot = true; TODO
+        this.maxHealthCache = this.getMaxHealth();
+        // CraftBukkit end
     }
 
     public void a(NBTTagCompound nbttagcompound) {
@@ -81,14 +108,40 @@
                 this.playerInteractManager.setGameMode(EnumGamemode.getById(nbttagcompound.getInt("playerGameType")));
             }
         }
-
+        this.getBukkitEntity().readExtraData(nbttagcompound); // CraftBukkit
     }
 
     public void b(NBTTagCompound nbttagcompound) {
         super.b(nbttagcompound);
         nbttagcompound.setInt("playerGameType", this.playerInteractManager.getGameMode().getId());
+        this.getBukkitEntity().setExtraData(nbttagcompound); // CraftBukkit
     }
 
+    // CraftBukkit start - World fallback code, either respawn location or global spawn
+    public void spawnIn(World world) {
+        super.spawnIn(world);
+        if (world == null) {
+            this.dead = false;
+            BlockPosition position = null;
+            if (this.spawnWorld != null && !this.spawnWorld.equals("")) {
+                CraftWorld cworld = (CraftWorld) Bukkit.getServer().getWorld(this.spawnWorld);
+                if (cworld != null && this.getBed() != null) {
+                    world = cworld.getHandle();
+                    position = EntityHuman.getBed(cworld.getHandle(), this.getBed(), false);
+                }
+            }
+            if (world == null || position == null) {
+                world = ((CraftWorld) Bukkit.getServer().getWorlds().get(0)).getHandle();
+                position = world.getSpawn();
+            }
+            this.world = world;
+            this.setPosition(position.getX() + 0.5, position.getY(), position.getZ() + 0.5);
+        }
+        this.dimension = ((WorldServer) this.world).dimension;
+        this.playerInteractManager.a((WorldServer) world);
+    }
+    // CraftBukkit end
+
     public void levelDown(int i) {
         super.levelDown(i);
         this.lastSentExp = -1;
@@ -114,6 +167,11 @@
     }
 
     public void s_() {
+        // CraftBukkit start
+        if (this.joining) {
+            this.joining = false;
+        }
+        // CraftBukkit end
         this.playerInteractManager.a();
         --this.invulnerableTicks;
         if (this.noDamageTicks > 0) {
@@ -155,7 +213,7 @@
                         chunk = this.world.getChunkAt(chunkcoordintpair.x, chunkcoordintpair.z);
                         if (chunk.isReady()) {
                             arraylist.add(chunk);
-                            arraylist1.addAll(((WorldServer) this.world).getTileEntities(chunkcoordintpair.x * 16, 0, chunkcoordintpair.z * 16, chunkcoordintpair.x * 16 + 16, 256, chunkcoordintpair.z * 16 + 16));
+                            arraylist1.addAll(chunk.tileEntities.values()); // CraftBukkit - Get tile entities directly from the chunk instead of the world
                             iterator1.remove();
                         }
                     }
@@ -220,8 +278,9 @@
                 }
             }
 
+            // CraftBukkit - Optionally scale health
             if (this.getHealth() != this.bK || this.bL != this.foodData.getFoodLevel() || this.foodData.getSaturationLevel() == 0.0F != this.bM) {
-                this.playerConnection.sendPacket(new PacketPlayOutUpdateHealth(this.getHealth(), this.foodData.getFoodLevel(), this.foodData.getSaturationLevel()));
+                this.playerConnection.sendPacket(new PacketPlayOutUpdateHealth(this.getBukkitEntity().getScaledHealth(), this.foodData.getFoodLevel(), this.foodData.getSaturationLevel()));
                 this.bK = this.getHealth();
                 this.bL = this.foodData.getFoodLevel();
                 this.bM = this.foodData.getSaturationLevel() == 0.0F;
@@ -229,15 +288,14 @@
 
             if (this.getHealth() + this.getAbsorptionHearts() != this.bJ) {
                 this.bJ = this.getHealth() + this.getAbsorptionHearts();
-                Collection collection = this.getScoreboard().getObjectivesForCriteria(IScoreboardCriteria.g);
-                Iterator iterator = collection.iterator();
-
-                while (iterator.hasNext()) {
-                    ScoreboardObjective scoreboardobjective = (ScoreboardObjective) iterator.next();
-
-                    this.getScoreboard().getPlayerScoreForObjective(this.getName(), scoreboardobjective).updateForList(Arrays.asList(new EntityHuman[] { this}));
-                }
+                // CraftBukkit - Update ALL the scores!
+                this.world.getServer().getScoreboardManager().updateAllScoresForList(IScoreboardCriteria.g, this.getName(), com.google.common.collect.ImmutableList.of(this));
+            }
+            // CraftBukkit start - Force max health updates
+            if (this.maxHealthCache != this.getMaxHealth()) {
+                this.getBukkitEntity().updateScaledHealth();
             }
+            // CraftBukkit end
 
             if (this.expTotal != this.lastSentExp) {
                 this.lastSentExp = this.expTotal;
@@ -247,7 +305,17 @@
             if (this.ticksLived % 20 * 5 == 0 && !this.getStatisticManager().hasAchievement(AchievementList.L)) {
                 this.h_();
             }
+            
+            // CraftBukkit start - initialize oldLevel and fire PlayerLevelChangeEvent
+            if (this.oldLevel == -1) {
+                this.oldLevel = this.expLevel;
+            }
 
+            if (this.oldLevel != this.expLevel) {
+                CraftEventFactory.callPlayerLevelChangeEvent(this.world.getServer().getPlayer((EntityPlayer) this), this.oldLevel, this.expLevel);
+                this.oldLevel = this.expLevel;
+            }
+            // CraftBukkit end            
         } catch (Throwable throwable) {
             CrashReport crashreport = CrashReport.a(throwable, "Ticking player");
             CrashReportSystemDetails crashreportsystemdetails = crashreport.a("Player being ticked");
@@ -296,30 +364,64 @@
     }
 
     public void die(DamageSource damagesource) {
-        if (this.world.getGameRules().getBoolean("showDeathMessages")) {
-            ScoreboardTeamBase scoreboardteambase = this.getScoreboardTeam();
+        // CraftBukkit start - fire PlayerDeathEvent
+        if (this.dead) {
+            return;
+        }
 
-            if (scoreboardteambase != null && scoreboardteambase.j() != EnumNameTagVisibility.ALWAYS) {
-                if (scoreboardteambase.j() == EnumNameTagVisibility.HIDE_FOR_OTHER_TEAMS) {
-                    this.server.getPlayerList().a((EntityHuman) this, this.br().b());
-                } else if (scoreboardteambase.j() == EnumNameTagVisibility.HIDE_FOR_OWN_TEAM) {
-                    this.server.getPlayerList().b((EntityHuman) this, this.br().b());
+        java.util.List<org.bukkit.inventory.ItemStack> loot = new java.util.ArrayList<org.bukkit.inventory.ItemStack>();
+        boolean keepInventory = this.world.getGameRules().getBoolean("keepInventory");
+
+        if (!keepInventory) {
+            for (int i = 0; i < this.inventory.items.length; ++i) {
+                if (this.inventory.items[i] != null) {
+                    loot.add(CraftItemStack.asCraftMirror(this.inventory.items[i]));
                 }
+            }
+
+            for (int i = 0; i < this.inventory.armor.length; ++i) {
+                if (this.inventory.armor[i] != null) {
+                    loot.add(CraftItemStack.asCraftMirror(this.inventory.armor[i]));
+                }
+            }
+        }
+
+        IChatBaseComponent chatmessage = this.br().b();
+
+        String deathmessage = chatmessage.c();
+        org.bukkit.event.entity.PlayerDeathEvent event = CraftEventFactory.callPlayerDeathEvent(this, loot, deathmessage, keepInventory);
+
+        String deathMessage = event.getDeathMessage();
+
+        if (deathMessage != null && deathMessage.length() > 0 && this.world.getGameRules().getBoolean("showDeathMessages")) { // TODO: allow plugins to override?
+            if (deathMessage.equals(deathmessage)) {
+                this.server.getPlayerList().sendMessage(chatmessage);
             } else {
-                this.server.getPlayerList().sendMessage(this.br().b());
+                this.server.getPlayerList().sendMessage(org.bukkit.craftbukkit.util.CraftChatMessage.fromString(deathMessage));
             }
         }
+        
+        // we clean the player's inventory after the EntityDeathEvent is called so plugins can get the exact state of the inventory.
+        if (!event.getKeepInventory()) {
+            for (int i = 0; i < this.inventory.items.length; ++i) {
+                this.inventory.items[i] = null;
+            }
 
-        if (!this.world.getGameRules().getBoolean("keepInventory")) {
-            this.inventory.n();
+            for (int i = 0; i < this.inventory.armor.length; ++i) {
+                this.inventory.armor[i] = null;
+            }
         }
 
-        Collection collection = this.world.getScoreboard().getObjectivesForCriteria(IScoreboardCriteria.d);
+        this.closeInventory();
+        this.e((Entity) this); // Remove spectated target
+        // CraftBukkit end
+        
+        // CraftBukkit - Get our scores instead
+        Collection collection = this.world.getServer().getScoreboardManager().getScoreboardScores(IScoreboardCriteria.c, this.getName(), new java.util.ArrayList<ScoreboardScore>());
         Iterator iterator = collection.iterator();
 
         while (iterator.hasNext()) {
-            ScoreboardObjective scoreboardobjective = (ScoreboardObjective) iterator.next();
-            ScoreboardScore scoreboardscore = this.getScoreboard().getPlayerScoreForObjective(this.getName(), scoreboardobjective);
+            ScoreboardScore scoreboardscore = (ScoreboardScore) iterator.next(); // CraftBukkit - Use our scores instead
 
             scoreboardscore.incrementScore();
         }
@@ -376,7 +478,8 @@
     }
 
     private boolean cq() {
-        return this.server.getPVP();
+        // CraftBukkit - this.server.getPvP() -> this.world.pvpMode
+        return this.world.pvpMode;
     }
 
     public void c(int i) {
@@ -388,6 +491,8 @@
         } else {
             if (this.dimension == 0 && i == 1) {
                 this.b((Statistic) AchievementList.C);
+                // CraftBukkit start - Rely on custom portal management
+                /*
                 BlockPosition blockposition = this.server.getWorldServer(i).getDimensionSpawn();
 
                 if (blockposition != null) {
@@ -395,11 +500,16 @@
                 }
 
                 i = 1;
+                */
+                // CraftBukkit end
             } else {
                 this.b((Statistic) AchievementList.y);
             }
 
-            this.server.getPlayerList().changeDimension(this, i);
+            // CraftBukkit start
+            TeleportCause cause = (this.dimension == 1 || i == 1) ? TeleportCause.END_PORTAL : TeleportCause.NETHER_PORTAL;
+            this.server.getPlayerList().changeDimension(this, i, cause);
+            // CraftBukkit end
             this.lastSentExp = -1;
             this.bK = -1.0F;
             this.bL = -1;
@@ -442,6 +552,8 @@
     }
 
     public void a(boolean flag, boolean flag1, boolean flag2) {
+        if (!this.sleeping) return; // CraftBukkit - Can't leave bed if not in one!
+        
         if (this.isSleeping()) {
             this.u().getTracker().sendPacketToEntity(this, new PacketPlayOutAnimation(this, 2));
         }
@@ -454,14 +566,23 @@
     }
 
     public void mount(Entity entity) {
-        Entity entity1 = this.vehicle;
+        // CraftBukkit start
+        this.setPassengerOf(entity);
+    }
+    
+    public void setPassengerOf(Entity entity) {
+        // mount(null) doesn't really fly for overloaded methods,
+        // so this method is needed
+        Entity currentVehicle = this.vehicle;
+
+        super.setPassengerOf(entity);
 
-        super.mount(entity);
-        if (entity != entity1) {
+        // Check if the vehicle actually changed.
+        if (currentVehicle != this.vehicle) {
             this.playerConnection.sendPacket(new PacketPlayOutAttachEntity(0, this, this.vehicle));
             this.playerConnection.a(this.locX, this.locY, this.locZ, this.yaw, this.pitch);
         }
-
+        // CraftBukkit end
     }
 
     protected void a(double d0, boolean flag, Block block, BlockPosition blockposition) {}
@@ -490,19 +611,38 @@
         this.playerConnection.sendPacket(new PacketPlayOutOpenSignEditor(tileentitysign.getPosition()));
     }
 
-    public void nextContainerCounter() {
+    public int nextContainerCounter() { // CraftBukkit - private void -> public int
         this.containerCounter = this.containerCounter % 100 + 1;
+        return containerCounter; // CraftBukkit
     }
 
     public void openTileEntity(ITileEntityContainer itileentitycontainer) {
+        // CraftBukkit start - Inventory open hook
+        Container container = CraftEventFactory.callInventoryOpenEvent(this, itileentitycontainer.createContainer(this.inventory, this));
+        if (container == null) {
+            return;
+        }
+        // CraftBukkit end
         this.nextContainerCounter();
         this.playerConnection.sendPacket(new PacketPlayOutOpenWindow(this.containerCounter, itileentitycontainer.getContainerName(), itileentitycontainer.getScoreboardDisplayName()));
-        this.activeContainer = itileentitycontainer.createContainer(this.inventory, this);
+        this.activeContainer = container; // CraftBukkit 
         this.activeContainer.windowId = this.containerCounter;
         this.activeContainer.addSlotListener(this);
     }
 
     public void openContainer(IInventory iinventory) {
+        // CraftBukkit start - Inventory open hook
+        Container container;
+        if (iinventory instanceof ITileEntityContainer) {
+            container = ((ITileEntityContainer)iinventory).createContainer(this.inventory, this);
+        } else {
+            container = new ContainerChest(this.inventory, iinventory, this);
+        }
+        container = CraftEventFactory.callInventoryOpenEvent(this, container);
+        if (container == null) {
+            return;
+        }
+        // CraftBukkit end
         if (this.activeContainer != this.defaultContainer) {
             this.closeInventory();
         }
@@ -520,10 +660,10 @@
         this.nextContainerCounter();
         if (iinventory instanceof ITileEntityContainer) {
             this.playerConnection.sendPacket(new PacketPlayOutOpenWindow(this.containerCounter, ((ITileEntityContainer) iinventory).getContainerName(), iinventory.getScoreboardDisplayName(), iinventory.getSize()));
-            this.activeContainer = ((ITileEntityContainer) iinventory).createContainer(this.inventory, this);
+            this.activeContainer = container; // CraftBukkit 
         } else {
             this.playerConnection.sendPacket(new PacketPlayOutOpenWindow(this.containerCounter, "minecraft:container", iinventory.getScoreboardDisplayName(), iinventory.getSize()));
-            this.activeContainer = new ContainerChest(this.inventory, iinventory, this);
+            this.activeContainer = container; // CraftBukkit 
         }
 
         this.activeContainer.windowId = this.containerCounter;
@@ -531,8 +671,14 @@
     }
 
     public void openTrade(IMerchant imerchant) {
+        // CraftBukkit start - Inventory open hook
+        Container container = CraftEventFactory.callInventoryOpenEvent(this, new ContainerMerchant(this.inventory, imerchant, this.world));
+        if (container == null) {
+            return;
+        }
+        // CraftBukkit end
         this.nextContainerCounter();
-        this.activeContainer = new ContainerMerchant(this.inventory, imerchant, this.world);
+        this.activeContainer = container; // CraftBukkit 
         this.activeContainer.windowId = this.containerCounter;
         this.activeContainer.addSlotListener(this);
         InventoryMerchant inventorymerchant = ((ContainerMerchant) this.activeContainer).e();
@@ -552,13 +698,20 @@
     }
 
     public void openHorseInventory(EntityHorse entityhorse, IInventory iinventory) {
+        // CraftBukkit start - Inventory open hook
+        Container container = CraftEventFactory.callInventoryOpenEvent(this, new ContainerHorse(this.inventory, iinventory, entityhorse, this));
+        if (container == null) {
+            iinventory.closeContainer(this);
+            return;
+        }
+        // CraftBukkit end        
         if (this.activeContainer != this.defaultContainer) {
             this.closeInventory();
         }
 
         this.nextContainerCounter();
         this.playerConnection.sendPacket(new PacketPlayOutOpenWindow(this.containerCounter, "EntityHorse", iinventory.getScoreboardDisplayName(), iinventory.getSize(), entityhorse.getId()));
-        this.activeContainer = new ContainerHorse(this.inventory, iinventory, entityhorse, this);
+        this.activeContainer = container;
         this.activeContainer.windowId = this.containerCounter;
         this.activeContainer.addSlotListener(this);
     }
@@ -587,6 +740,11 @@
     public void a(Container container, List list) {
         this.playerConnection.sendPacket(new PacketPlayOutWindowItems(container.windowId, list));
         this.playerConnection.sendPacket(new PacketPlayOutSetSlot(-1, -1, this.inventory.getCarried()));
+        // CraftBukkit start - Send a Set Slot to update the crafting result slot
+        if (java.util.EnumSet.of(InventoryType.CRAFTING,InventoryType.WORKBENCH).contains(container.getBukkitView().getType())) {
+            this.playerConnection.sendPacket(new PacketPlayOutSetSlot(container.windowId, 0, container.getSlot(0).getItem()));
+        }
+        // CraftBukkit end
     }
 
     public void setContainerData(Container container, int i, int j) {
@@ -601,6 +759,7 @@
     }
 
     public void closeInventory() {
+        CraftEventFactory.handleInventoryCloseEvent(this); // CraftBukkit
         this.playerConnection.sendPacket(new PacketPlayOutCloseWindow(this.activeContainer.windowId));
         this.p();
     }
@@ -681,7 +840,16 @@
 
     public void triggerHealthUpdate() {
         this.bK = -1.0E8F;
+        this.lastSentExp = -1; // CraftBukkit - Added to reset
     }
+    
+    // CraftBukkit start - Support multi-line messages
+    public void sendMessage(IChatBaseComponent[] ichatbasecomponent) {
+        for (IChatBaseComponent component : ichatbasecomponent) {
+            this.sendMessage(component);
+        }
+    }
+    // CraftBukkit end
 
     public void b(IChatBaseComponent ichatbasecomponent) {
         this.playerConnection.sendPacket(new PacketPlayOutChat(ichatbasecomponent));
@@ -867,6 +1035,129 @@
     }
 
     public IChatBaseComponent getPlayerListName() {
-        return null;
+        return listName; // CraftBukkit
+    }
+
+    // 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.world.getDayTime() + this.timeOffset;
+        } else {
+            // Adds timeOffset to the beginning of this day.
+            return this.world.getDayTime() - (this.world.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.playerConnection.sendPacket(new PacketPlayOutGameStateChange(2, 0));
+        } else {
+            this.playerConnection.sendPacket(new PacketPlayOutGameStateChange(1, 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.playerConnection.sendPacket(new PacketPlayOutGameStateChange(7, newRain));
+            }            
+        } else {
+            // Plugin
+            if (pluginRainPositionPrevious != pluginRainPosition) {
+                this.playerConnection.sendPacket(new PacketPlayOutGameStateChange(7, pluginRainPosition));
+            }   
+        }
+
+        if (oldThunder != newThunder) {
+            if (weather == WeatherType.DOWNFALL || weather == null) {
+                this.playerConnection.sendPacket(new PacketPlayOutGameStateChange(8, newThunder));
+            } else {
+                this.playerConnection.sendPacket(new PacketPlayOutGameStateChange(8, 0));
+            }
+        }
+    }
+    
+    public void tickWeather() {
+        if (this.weather == null) return;
+
+        pluginRainPositionPrevious = pluginRainPosition;
+        if (weather == WeatherType.DOWNFALL) {
+            pluginRainPosition += 0.01;
+        } else {
+            pluginRainPosition -= 0.01;
+        }
+
+        pluginRainPosition = MathHelper.a(pluginRainPosition, 0.0F, 1.0F);
+    }
+
+    public void resetPlayerWeather() {
+        this.weather = null;
+        this.setPlayerWeather(this.world.getWorldData().hasStorm() ? WeatherType.DOWNFALL : WeatherType.CLEAR, false);
+    }
+
+    @Override
+    public String toString() {
+        return super.toString() + "(" + this.getName() + " at " + this.locX + "," + this.locY + "," + this.locZ + ")";
+    }
+
+    public void reset() {
+        float exp = 0;
+        boolean keepInventory = this.world.getGameRules().getBoolean("keepInventory");
+
+        if (this.keepLevel || keepInventory) {
+            exp = this.exp;
+            this.newTotalExp = this.expTotal;
+            this.newLevel = this.expLevel;
+        }
+
+        this.setHealth(this.getMaxHealth());
+        this.fireTicks = 0;
+        this.fallDistance = 0;
+        this.foodData = new FoodMetaData(this);
+        this.expLevel = this.newLevel;
+        this.expTotal = this.newTotalExp;
+        this.exp = 0;
+        this.deathTicks = 0;
+        this.removeAllEffects();
+        this.updateEffects = true;
+        this.activeContainer = this.defaultContainer;
+        this.killer = null;
+        this.lastDamager = null;
+        this.combatTracker = new CombatTracker(this);
+        this.lastSentExp = -1;
+        if (this.keepLevel || keepInventory) {
+            this.exp = exp;
+        } else {
+            this.giveExp(this.newExp);
+        }
+        this.keepLevel = false;
+    }
+
+    @Override
+    public CraftPlayer getBukkitEntity() {
+        return (CraftPlayer) super.getBukkitEntity();
     }
+    // CraftBukkit end
 }