--- a/net/minecraft/server/Chunk.java
+++ b/net/minecraft/server/Chunk.java
@@ -21,6 +21,13 @@
 import org.apache.logging.log4j.LogManager;
 import org.apache.logging.log4j.Logger;
 
+// CraftBukkit start
+import com.google.common.collect.Lists;
+import java.util.LinkedList;
+import org.bukkit.craftbukkit.event.CraftEventFactory;
+import org.bukkit.event.entity.CreatureSpawnEvent;
+// CraftBukkit end
+
 public class Chunk implements IChunkAccess {
 
     private static final Logger d = LogManager.getLogger();
@@ -56,6 +63,35 @@
     private final AtomicInteger E;
     private final ChunkCoordIntPair F;
 
+    // CraftBukkit start - Neighbor loaded cache for chunk lighting and entity ticking
+    private int neighbors = 0x1 << 12;
+    public long chunkKey;
+
+    public boolean areNeighborsLoaded(final int radius) {
+        switch (radius) {
+            case 2:
+                return this.neighbors == Integer.MAX_VALUE >> 6;
+            case 1:
+                final int mask =
+                        //       x        z   offset          x        z   offset          x         z   offset
+                        (0x1 << (1 * 5 +  1 + 12)) | (0x1 << (0 * 5 +  1 + 12)) | (0x1 << (-1 * 5 +  1 + 12)) |
+                        (0x1 << (1 * 5 +  0 + 12)) | (0x1 << (0 * 5 +  0 + 12)) | (0x1 << (-1 * 5 +  0 + 12)) |
+                        (0x1 << (1 * 5 + -1 + 12)) | (0x1 << (0 * 5 + -1 + 12)) | (0x1 << (-1 * 5 + -1 + 12));
+                return (this.neighbors & mask) == mask;
+            default:
+                throw new UnsupportedOperationException(String.valueOf(radius));
+        }
+    }
+
+    public void setNeighborLoaded(final int x, final int z) {
+        this.neighbors |= 0x1 << (x * 5 + 12 + z);
+    }
+
+    public void setNeighborUnloaded(final int x, final int z) {
+        this.neighbors &= ~(0x1 << (x * 5 + 12 + z));
+    }
+    // CraftBukkit end
+
     public Chunk(World world, int i, int j, BiomeBase[] abiomebase, ChunkConverter chunkconverter, TickList<Block> ticklist, TickList<FluidType> ticklist1, long k) {
         this.sections = new ChunkSection[16];
         this.g = new boolean[256];
@@ -94,8 +130,16 @@
         this.s = ticklist;
         this.t = ticklist1;
         this.z = k;
+        // CraftBukkit start
+        this.bukkitChunk = new org.bukkit.craftbukkit.CraftChunk(this);
+        this.chunkKey = ChunkCoordIntPair.a(this.locX, this.locZ);
     }
 
+    public org.bukkit.Chunk bukkitChunk;
+    public boolean mustSave;
+    private boolean needsDecoration;
+    // CraftBukkit end
+
     public Chunk(World world, ProtoChunk protochunk, int i, int j) {
         this(world, i, j, protochunk.getBiomeIndex(), protochunk.v(), protochunk.k(), protochunk.l(), protochunk.m());
 
@@ -143,6 +187,7 @@
 
         this.x = true;
         this.a(ChunkStatus.FULLCHUNK);
+        this.needsDecoration = true; // CraftBukkit
     }
 
     public Set<BlockPosition> t() {
@@ -412,8 +457,15 @@
         }
     }
 
+    // CraftBukkit start
     @Nullable
     public IBlockData setType(BlockPosition blockposition, IBlockData iblockdata, boolean flag) {
+        return this.setType(blockposition, iblockdata, flag, true);
+    }
+
+    @Nullable
+    public IBlockData setType(BlockPosition blockposition, IBlockData iblockdata, boolean flag, boolean doPlace) {
+        // CraftBukkit end
         int i = blockposition.getX() & 15;
         int j = blockposition.getY();
         int k = blockposition.getZ() & 15;
@@ -473,7 +525,8 @@
                     }
                 }
 
-                if (!this.world.isClientSide) {
+                // CraftBukkit - Don't place while processing the BlockPlaceEvent, unless it's a BlockContainer. Prevents blocks such as TNT from activating when cancelled.
+                if (!this.world.isClientSide && doPlace && (!this.world.captureBlockStates || block instanceof BlockTileEntity)) {
                     iblockdata.onPlace(this.world, blockposition, iblockdata1);
                 }
 
@@ -653,7 +706,12 @@
 
     @Nullable
     public TileEntity a(BlockPosition blockposition, Chunk.EnumTileEntityState chunk_enumtileentitystate) {
-        TileEntity tileentity = (TileEntity) this.tileEntities.get(blockposition);
+        // CraftBukkit start
+        TileEntity tileentity = world.capturedTileEntities.get(blockposition);
+        if (tileentity == null) {
+            tileentity = (TileEntity) this.tileEntities.get(blockposition);
+        }
+        // CraftBukkit end
 
         if (tileentity == null) {
             NBTTagCompound nbttagcompound = (NBTTagCompound) this.h.remove(blockposition);
@@ -700,6 +758,13 @@
 
             tileentity.z();
             this.tileEntities.put(blockposition.h(), tileentity);
+            // CraftBukkit start
+        } else {
+            System.out.println("Attempted to place a tile entity (" + tileentity + ") at " + tileentity.position.getX() + "," + tileentity.position.getY() + "," + tileentity.position.getZ()
+                + " (" + getType(blockposition) + ") where there was no entity tile!");
+            System.out.println("Chunk coordinates: " + (this.locX * 16) + "," + (this.locZ * 16));
+            new Exception().printStackTrace();
+            // CraftBukkit end
         }
     }
 
@@ -727,11 +792,53 @@
         for (int j = 0; j < i; ++j) {
             EntitySlice<Entity> entityslice = aentityslice[j];
 
+            // CraftBukkit start
+            List<Entity> toRemove = new LinkedList<>();
             this.world.a(entityslice.stream().filter((entity) -> {
+                if (this.needsDecoration && !CraftEventFactory.doEntityAddEventCalling(this.world, entity, CreatureSpawnEvent.SpawnReason.CHUNK_GEN)) { // Only call for new chunks
+                    toRemove.add(entity);
+                    return false;
+                }
                 return !(entity instanceof EntityHuman);
             }));
+            entityslice.removeAll(toRemove);
+            // CraftBukkit end
         }
 
+        // CraftBukkit start
+        org.bukkit.Server server = this.world.getServer();
+        if (server != null) {
+            /*
+             * If it's a new world, the first few chunks are generated inside
+             * the World constructor. We can't reliably alter that, so we have
+             * no way of creating a CraftWorld/CraftServer at that point.
+             */
+            server.getPluginManager().callEvent(new org.bukkit.event.world.ChunkLoadEvent(this.bukkitChunk, this.needsDecoration));
+
+            if (this.needsDecoration) {
+                BlockSand.instaFall = true;
+                java.util.Random random = new java.util.Random();
+                random.setSeed(world.getSeed());
+                long xRand = random.nextLong() / 2L * 2L + 1L;
+                long zRand = random.nextLong() / 2L * 2L + 1L;
+                random.setSeed((long) locX * xRand + (long) locZ * zRand ^ world.getSeed());
+
+                org.bukkit.World world = this.world.getWorld();
+                if (world != null) {
+                    this.world.populating = true;
+                    try {
+                        for (org.bukkit.generator.BlockPopulator populator : world.getPopulators()) {
+                            populator.populate(world, random, bukkitChunk);
+                        }
+                    } finally {
+                        this.world.populating = false;
+                    }
+                }
+                BlockSand.instaFall = false;
+                server.getPluginManager().callEvent(new org.bukkit.event.world.ChunkPopulateEvent(bukkitChunk));
+            }
+        }
+        // CraftBukkit end
     }
 
     public void removeEntities() {
@@ -748,9 +855,21 @@
         int i = aentityslice.length;
 
         for (int j = 0; j < i; ++j) {
-            EntitySlice<Entity> entityslice = aentityslice[j];
+            // CraftBukkit start
+            List<Entity> newList = Lists.newArrayList(aentityslice[j]);
+            java.util.Iterator<Entity> iter = newList.iterator();
+            while (iter.hasNext()) {
+                Entity entity = iter.next();
+
+                // Do not pass along players, as doing so can get them stuck outside of time.
+                // (which for example disables inventory icon updates and prevents block breaking)
+                if (entity instanceof EntityPlayer) {
+                    iter.remove();
+                }
+            }
 
-            this.world.b((Collection) entityslice);
+            this.world.b((Collection) newList);
+            // CraftBukkit end
         }
 
     }
@@ -810,7 +929,7 @@
             Iterator iterator = this.entitySlices[k].c(oclass).iterator();
 
             while (iterator.hasNext()) {
-                T t0 = (Entity) iterator.next();
+                T t0 = (T) iterator.next(); // CraftBukkit - decompile error
 
                 if (t0.getBoundingBox().c(axisalignedbb) && (predicate == null || predicate.test(t0))) {
                     list.add(t0);
@@ -1073,13 +1192,13 @@
             }
 
             if (this.s instanceof ProtoChunkTickList) {
-                ((ProtoChunkTickList) this.s).a(this.world.getBlockTickList(), (blockposition1) -> {
+                ((ProtoChunkTickList<Block>) this.s).a(this.world.getBlockTickList(), (blockposition1) -> { // CraftBukkit - decompile error
                     return this.world.getType(blockposition1).getBlock();
                 });
             }
 
             if (this.t instanceof ProtoChunkTickList) {
-                ((ProtoChunkTickList) this.t).a(this.world.getFluidTickList(), (blockposition1) -> {
+                ((ProtoChunkTickList<FluidType>) this.t).a(this.world.getFluidTickList(), (blockposition1) -> { // CraftBukkit - decompile error
                     return this.world.getFluid(blockposition1).c();
                 });
             }