--- a/net/minecraft/server/level/WorldServer.java
+++ b/net/minecraft/server/level/WorldServer.java
@@ -152,6 +152,22 @@
 import org.apache.logging.log4j.LogManager;
 import org.apache.logging.log4j.Logger;
 
+// CraftBukkit start
+import java.util.logging.Level;
+import net.minecraft.world.entity.monster.EntityDrowned;
+import net.minecraft.world.level.block.ITileEntity;
+import net.minecraft.world.level.block.entity.TileEntity;
+import net.minecraft.world.level.storage.WorldDataServer;
+import org.bukkit.Bukkit;
+import org.bukkit.WeatherType;
+import org.bukkit.craftbukkit.event.CraftEventFactory;
+import org.bukkit.craftbukkit.util.WorldUUID;
+import org.bukkit.event.entity.CreatureSpawnEvent;
+import org.bukkit.event.server.MapInitializeEvent;
+import org.bukkit.event.weather.LightningStrikeEvent;
+import org.bukkit.event.world.TimeSkipEvent;
+// CraftBukkit end
+
 public class WorldServer extends World implements GeneratorAccessSeed {
 
     public static final BlockPosition END_SPAWN_POINT = new BlockPosition(100, 50, 0);
@@ -160,9 +176,9 @@
     final List<EntityPlayer> players;
     private final ChunkProviderServer chunkSource;
     private final MinecraftServer server;
-    public final IWorldDataServer serverLevelData;
+    public final WorldDataServer serverLevelData; // CraftBukkit - type
     final EntityTickList entityTickList;
-    private final PersistentEntitySectionManager<Entity> entityManager;
+    public final PersistentEntitySectionManager<Entity> entityManager;
     public boolean noSave;
     private final SleepStatus sleepStatus;
     private int emptyTime;
@@ -180,31 +196,52 @@
     private final StructureManager structureFeatureManager;
     private final boolean tickTime;
 
-    public WorldServer(MinecraftServer minecraftserver, Executor executor, Convertable.ConversionSession convertable_conversionsession, IWorldDataServer iworlddataserver, ResourceKey<World> resourcekey, DimensionManager dimensionmanager, WorldLoadListener worldloadlistener, ChunkGenerator chunkgenerator, boolean flag, long i, List<MobSpawner> list, boolean flag1) {
-        Objects.requireNonNull(minecraftserver);
-        super(iworlddataserver, resourcekey, dimensionmanager, minecraftserver::getMethodProfiler, false, flag, i);
+
+    // CraftBukkit start
+    private int tickPosition;
+    public final Convertable.ConversionSession convertable;
+    public final UUID uuid;
+
+    public Chunk getChunkIfLoaded(int x, int z) {
+        return this.chunkSource.getChunkAt(x, z, false);
+    }
+
+    // Add env and gen to constructor, WorldData -> WorldDataServer
+    public WorldServer(MinecraftServer minecraftserver, Executor executor, Convertable.ConversionSession convertable_conversionsession, IWorldDataServer iworlddataserver, ResourceKey<World> resourcekey, DimensionManager dimensionmanager, WorldLoadListener worldloadlistener, ChunkGenerator chunkgenerator, boolean flag, long i, List<MobSpawner> list, boolean flag1, org.bukkit.World.Environment env, org.bukkit.generator.ChunkGenerator gen) {
+        // Objects.requireNonNull(minecraftserver); // CraftBukkit - decompile error
+        super(iworlddataserver, resourcekey, dimensionmanager, minecraftserver::getMethodProfiler, false, flag, i, gen, env);
+        this.pvpMode = minecraftserver.getPVP();
+        convertable = convertable_conversionsession;
+        uuid = WorldUUID.getUUID(convertable_conversionsession.levelPath.toFile());
+        // CraftBukkit end
         this.players = Lists.newArrayList();
         this.entityTickList = new EntityTickList();
-        Predicate predicate = (block) -> {
+        Predicate<Block> predicate = (block) -> { // CraftBukkit - decompile eror
             return block == null || block.getBlockData().isAir();
         };
         RegistryBlocks registryblocks = IRegistry.BLOCK;
 
         Objects.requireNonNull(registryblocks);
-        this.blockTicks = new TickListServer<>(this, predicate, registryblocks::getKey, this::b);
-        predicate = (fluidtype) -> {
+        this.blockTicks = new TickListServer<>(this, predicate, IRegistry.BLOCK::getKey, this::b); // CraftBukkit - decompile error
+        Predicate<FluidType> predicate2 = (fluidtype) -> { // CraftBukkit - decompile error
             return fluidtype == null || fluidtype == FluidTypes.EMPTY;
         };
         registryblocks = IRegistry.FLUID;
         Objects.requireNonNull(registryblocks);
-        this.liquidTicks = new TickListServer<>(this, predicate, registryblocks::getKey, this::a);
+        this.liquidTicks = new TickListServer<>(this, predicate2, IRegistry.FLUID::getKey, this::a); // CraftBukkit - decompile error
         this.navigatingMobs = new ObjectOpenHashSet();
         this.blockEvents = new ObjectLinkedOpenHashSet();
         this.dragonParts = new Int2ObjectOpenHashMap();
         this.tickTime = flag1;
         this.server = minecraftserver;
         this.customSpawners = list;
-        this.serverLevelData = iworlddataserver;
+        // CraftBukkit start
+        this.serverLevelData = (WorldDataServer) iworlddataserver;
+        serverLevelData.world = this;
+        if (gen != null) {
+            chunkgenerator = new org.bukkit.craftbukkit.generator.CustomChunkGenerator(this, chunkgenerator, gen);
+        }
+        // CraftBukkit end
         boolean flag2 = minecraftserver.isSyncChunkWrites();
         DataFixer datafixer = minecraftserver.getDataFixer();
         EntityPersistentStorage<Entity> entitypersistentstorage = new EntityStorage(this, new File(convertable_conversionsession.a(resourcekey), "entities"), datafixer, flag2, minecraftserver);
@@ -231,15 +268,51 @@
             iworlddataserver.setGameType(minecraftserver.getGamemode());
         }
 
-        this.structureFeatureManager = new StructureManager(this, minecraftserver.getSaveData().getGeneratorSettings());
+        this.structureFeatureManager = new StructureManager(this, this.serverLevelData.getGeneratorSettings()); // CraftBukkit
         if (this.getDimensionManager().isCreateDragonBattle()) {
-            this.dragonFight = new EnderDragonBattle(this, minecraftserver.getSaveData().getGeneratorSettings().getSeed(), minecraftserver.getSaveData().C());
+            this.dragonFight = new EnderDragonBattle(this, this.serverLevelData.getGeneratorSettings().getSeed(), this.serverLevelData.C()); // CraftBukkit
         } else {
             this.dragonFight = null;
         }
 
         this.sleepStatus = new SleepStatus();
+        this.getCraftServer().addWorld(this.getWorld()); // CraftBukkit
+    }
+
+    // CraftBukkit start
+    @Override
+    public TileEntity getTileEntity(BlockPosition pos, boolean validate) {
+        TileEntity result = super.getTileEntity(pos, validate);
+        if (!validate || Thread.currentThread() != this.thread) {
+            // SPIGOT-5378: avoid deadlock, this can be called in loading logic (i.e lighting) but getType() will block on chunk load
+            return result;
+        }
+        IBlockData type = getType(pos);
+
+        if (result != null && !type.a(Blocks.AIR)) {
+            if (!result.getTileType().isValidBlock(type)) {
+                result = fixTileEntity(pos, type, result);
+            }
+        }
+
+        return result;
+    }
+
+    private TileEntity fixTileEntity(BlockPosition pos, IBlockData type, TileEntity found) {
+        this.getCraftServer().getLogger().log(Level.SEVERE, "Block at {0}, {1}, {2} is {3} but has {4}" + ". "
+                + "Bukkit will attempt to fix this, but there may be additional damage that we cannot recover.", new Object[]{pos.getX(), pos.getY(), pos.getZ(), type, found});
+
+        if (type instanceof ITileEntity) {
+            TileEntity replacement = ((ITileEntity) type).createTile(pos, type);
+            if (replacement != null) {
+                this.setTileEntity(replacement);
+            }
+            return replacement;
+        } else {
+            return found;
+        }
     }
+    // CraftBukkit end
 
     public void a(int i, int j, boolean flag, boolean flag1) {
         this.serverLevelData.setClearWeatherTime(i);
@@ -331,6 +404,7 @@
             this.rainLevel = MathHelper.a(this.rainLevel, 0.0F, 1.0F);
         }
 
+        /* CraftBukkit start
         if (this.oRainLevel != this.rainLevel) {
             this.server.getPlayerList().a((Packet) (new PacketPlayOutGameStateChange(PacketPlayOutGameStateChange.RAIN_LEVEL_CHANGE, this.rainLevel)), this.getDimensionKey());
         }
@@ -349,16 +423,45 @@
             this.server.getPlayerList().sendAll(new PacketPlayOutGameStateChange(PacketPlayOutGameStateChange.RAIN_LEVEL_CHANGE, this.rainLevel));
             this.server.getPlayerList().sendAll(new PacketPlayOutGameStateChange(PacketPlayOutGameStateChange.THUNDER_LEVEL_CHANGE, this.thunderLevel));
         }
+        // */
+        for (int idx = 0; idx < this.players.size(); ++idx) {
+            if (((EntityPlayer) this.players.get(idx)).level == this) {
+                ((EntityPlayer) this.players.get(idx)).tickWeather();
+            }
+        }
+
+        if (flag != this.isRaining()) {
+            // Only send weather packets to those affected
+            for (int idx = 0; idx < this.players.size(); ++idx) {
+                if (((EntityPlayer) this.players.get(idx)).level == this) {
+                    ((EntityPlayer) this.players.get(idx)).setPlayerWeather((!flag ? WeatherType.DOWNFALL : WeatherType.CLEAR), false);
+                }
+            }
+        }
+        for (int idx = 0; idx < this.players.size(); ++idx) {
+            if (((EntityPlayer) this.players.get(idx)).level == this) {
+                ((EntityPlayer) this.players.get(idx)).updateWeather(this.oRainLevel, this.rainLevel, this.oThunderLevel, this.thunderLevel);
+            }
+        }
+        // CraftBukkit end
 
         i = this.getGameRules().getInt(GameRules.RULE_PLAYERS_SLEEPING_PERCENTAGE);
         if (this.sleepStatus.a(i) && this.sleepStatus.a(i, this.players)) {
+            // CraftBukkit start
+            long l = this.levelData.getDayTime() + 24000L;
+            TimeSkipEvent event = new TimeSkipEvent(this.getWorld(), TimeSkipEvent.SkipReason.NIGHT_SKIP, (l - l % 24000L) - this.getDayTime());
             if (this.getGameRules().getBoolean(GameRules.RULE_DAYLIGHT)) {
-                long l = this.levelData.getDayTime() + 24000L;
+                getCraftServer().getPluginManager().callEvent(event);
+                if (!event.isCancelled()) {
+                    this.setDayTime(this.getDayTime() + event.getSkipAmount());
+                }
 
-                this.setDayTime(l - l % 24000L);
             }
 
-            this.wakeupPlayers();
+            if (!event.isCancelled()) {
+                this.wakeupPlayers();
+            }
+            // CraftBukkit end
             if (this.getGameRules().getBoolean(GameRules.RULE_WEATHER_CYCLE)) {
                 this.clearWeather();
             }
@@ -380,7 +483,7 @@
         this.aq();
         this.handlingTick = false;
         gameprofilerfiller.exit();
-        boolean flag3 = !this.players.isEmpty() || !this.getForceLoadedChunks().isEmpty();
+        boolean flag3 = true || !this.players.isEmpty() || !this.getForceLoadedChunks().isEmpty(); // CraftBukkit - this prevents entity cleanup, other issues on servers with no players
 
         if (flag3) {
             this.resetEmptyTime();
@@ -396,7 +499,7 @@
 
             this.entityTickList.a((entity) -> {
                 if (!entity.isRemoved()) {
-                    if (this.i(entity)) {
+                    if (false && this.i(entity)) { // CraftBukkit - We prevent spawning in general, so this butchering is not needed
                         entity.die();
                     } else {
                         gameprofilerfiller.enter("checkDespawn");
@@ -461,7 +564,7 @@
 
     private void wakeupPlayers() {
         this.sleepStatus.a();
-        ((List) this.players.stream().filter(EntityLiving::isSleeping).collect(Collectors.toList())).forEach((entityplayer) -> {
+        (this.players.stream().filter(EntityLiving::isSleeping).collect(Collectors.toList())).forEach((entityplayer) -> { // CraftBukkit - decompile error
             entityplayer.wakeup(false, false);
         });
     }
@@ -488,14 +591,14 @@
                     entityhorseskeleton.v(true);
                     entityhorseskeleton.setAgeRaw(0);
                     entityhorseskeleton.setPosition((double) blockposition.getX(), (double) blockposition.getY(), (double) blockposition.getZ());
-                    this.addEntity(entityhorseskeleton);
+                    this.addEntity(entityhorseskeleton, org.bukkit.event.entity.CreatureSpawnEvent.SpawnReason.LIGHTNING); // CraftBukkit
                 }
 
                 EntityLightning entitylightning = (EntityLightning) EntityTypes.LIGHTNING_BOLT.a((World) this);
 
                 entitylightning.d(Vec3D.c((BaseBlockPosition) blockposition));
                 entitylightning.setEffect(flag1);
-                this.addEntity(entitylightning);
+                this.strikeLightning(entitylightning, org.bukkit.event.weather.LightningStrikeEvent.Cause.WEATHER); // CraftBukkit
             }
         }
 
@@ -506,12 +609,12 @@
             BiomeBase biomebase = this.getBiome(blockposition);
 
             if (biomebase.a((IWorldReader) this, blockposition1)) {
-                this.setTypeUpdate(blockposition1, Blocks.ICE.getBlockData());
+                org.bukkit.craftbukkit.event.CraftEventFactory.handleBlockFormEvent(this, blockposition1, Blocks.ICE.getBlockData(), null); // CraftBukkit
             }
 
             if (flag) {
                 if (biomebase.b(this, blockposition)) {
-                    this.setTypeUpdate(blockposition, Blocks.SNOW.getBlockData());
+                    org.bukkit.craftbukkit.event.CraftEventFactory.handleBlockFormEvent(this, blockposition, Blocks.SNOW.getBlockData(), null); // CraftBukkit
                 }
 
                 IBlockData iblockdata = this.getType(blockposition1);
@@ -642,10 +745,22 @@
     }
 
     private void clearWeather() {
-        this.serverLevelData.setWeatherDuration(0);
+        // CraftBukkit start
         this.serverLevelData.setStorm(false);
-        this.serverLevelData.setThunderDuration(0);
+        // If we stop due to everyone sleeping we should reset the weather duration to some other random value.
+        // Not that everyone ever manages to get the whole server to sleep at the same time....
+        if (!this.serverLevelData.hasStorm()) {
+            this.serverLevelData.setWeatherDuration(0);
+        }
+        // CraftBukkit end
         this.serverLevelData.setThundering(false);
+        // CraftBukkit start
+        // If we stop due to everyone sleeping we should reset the weather duration to some other random value.
+        // Not that everyone ever manages to get the whole server to sleep at the same time....
+        if (!this.serverLevelData.isThundering()) {
+            this.serverLevelData.setThunderDuration(0);
+        }
+        // CraftBukkit end
     }
 
     public void resetEmptyTime() {
@@ -680,6 +795,7 @@
         });
         gameprofilerfiller.c("tickNonPassenger");
         entity.tick();
+        entity.postTick(); // CraftBukkit
         this.getMethodProfiler().exit();
         Iterator iterator = entity.getPassengers().iterator();
 
@@ -703,6 +819,7 @@
                 });
                 gameprofilerfiller.c("tickPassenger");
                 entity1.passengerTick();
+                entity1.postTick(); // CraftBukkit
                 gameprofilerfiller.exit();
                 Iterator iterator = entity1.getPassengers().iterator();
 
@@ -727,6 +844,7 @@
         ChunkProviderServer chunkproviderserver = this.getChunkProvider();
 
         if (!flag1) {
+            org.bukkit.Bukkit.getPluginManager().callEvent(new org.bukkit.event.world.WorldSaveEvent(getWorld())); // CraftBukkit
             if (iprogressupdate != null) {
                 iprogressupdate.a(new ChatMessage("menu.savingLevel"));
             }
@@ -744,11 +862,19 @@
             }
 
         }
+
+        // CraftBukkit start - moved from MinecraftServer.saveChunks
+        WorldServer worldserver1 = this;
+
+        serverLevelData.a(worldserver1.getWorldBorder().t());
+        serverLevelData.setCustomBossEvents(this.server.getBossBattleCustomData().save());
+        convertable.a(this.server.registryHolder, this.serverLevelData, this.server.getPlayerList().save());
+        // CraftBukkit end
     }
 
     private void ap() {
         if (this.dragonFight != null) {
-            this.server.getSaveData().a(this.dragonFight.a());
+            this.serverLevelData.a(this.dragonFight.a()); // CraftBukkit
         }
 
         this.getChunkProvider().getWorldPersistentData().a();
@@ -794,15 +920,34 @@
 
     @Override
     public boolean addEntity(Entity entity) {
-        return this.addEntity0(entity);
+        // CraftBukkit start
+        return this.addEntity0(entity, CreatureSpawnEvent.SpawnReason.DEFAULT);
+    }
+
+    @Override
+    public boolean addEntity(Entity entity, CreatureSpawnEvent.SpawnReason reason) {
+        return this.addEntity0(entity, reason);
+        // CraftBukkit end
     }
 
     public boolean addEntitySerialized(Entity entity) {
-        return this.addEntity0(entity);
+        // CraftBukkit start
+        return this.addEntitySerialized(entity, CreatureSpawnEvent.SpawnReason.DEFAULT);
+    }
+
+    public boolean addEntitySerialized(Entity entity, CreatureSpawnEvent.SpawnReason reason) {
+        return this.addEntity0(entity, reason);
+        // CraftBukkit end
     }
 
     public void addEntityTeleport(Entity entity) {
-        this.addEntity0(entity);
+        // CraftBukkit start
+        this.addEntity0(entity, CreatureSpawnEvent.SpawnReason.DEFAULT);
+    }
+
+    public void addEntityTeleport(Entity entity, CreatureSpawnEvent.SpawnReason reason) {
+        this.addEntity0(entity, reason);
+        // CraftBukkit end
     }
 
     public void addPlayerCommand(EntityPlayer entityplayer) {
@@ -830,27 +975,39 @@
             this.a((EntityPlayer) entity, Entity.RemovalReason.DISCARDED);
         }
 
-        this.entityManager.a((EntityAccess) entityplayer);
+        this.entityManager.a(entityplayer); // CraftBukkit - decompile error
     }
 
-    private boolean addEntity0(Entity entity) {
+    // CraftBukkit start
+    private boolean addEntity0(Entity entity, CreatureSpawnEvent.SpawnReason spawnReason) {
         if (entity.isRemoved()) {
-            WorldServer.LOGGER.warn("Tried to add entity {} but it was marked as removed already", EntityTypes.getName(entity.getEntityType()));
+            // WorldServer.LOGGER.warn("Tried to add entity {} but it was marked as removed already", EntityTypes.getName(entity.getEntityType())); // CraftBukkit
             return false;
         } else {
-            return this.entityManager.a((EntityAccess) entity);
+            if (!CraftEventFactory.doEntityAddEventCalling(this, entity, spawnReason)) {
+                return false;
+            }
+            // CraftBukkit end
+
+            return this.entityManager.a(entity); // CraftBukkit - decompile error
         }
     }
 
     public boolean addAllEntitiesSafely(Entity entity) {
-        Stream stream = entity.recursiveStream().map(Entity::getUniqueID);
+        // CraftBukkit start
+        return this.addAllEntitiesSafely(entity, org.bukkit.event.entity.CreatureSpawnEvent.SpawnReason.DEFAULT);
+    }
+
+    public boolean addAllEntitiesSafely(Entity entity, org.bukkit.event.entity.CreatureSpawnEvent.SpawnReason reason) {
+        // CraftBukkit end
+        Stream<UUID> stream = entity.recursiveStream().map(Entity::getUniqueID); // CraftBukkit - decompile error
         PersistentEntitySectionManager persistententitysectionmanager = this.entityManager;
 
         Objects.requireNonNull(this.entityManager);
         if (stream.anyMatch(persistententitysectionmanager::a)) {
             return false;
         } else {
-            this.addAllEntities(entity);
+            this.addAllEntities(entity, reason); // CraftBukkit
             return true;
         }
     }
@@ -863,10 +1020,32 @@
         entityplayer.a(entity_removalreason);
     }
 
+    // CraftBukkit start
+    public boolean strikeLightning(Entity entitylightning) {
+        return this.strikeLightning(entitylightning, LightningStrikeEvent.Cause.UNKNOWN);
+    }
+
+    public boolean strikeLightning(Entity entitylightning, LightningStrikeEvent.Cause cause) {
+        LightningStrikeEvent lightning = CraftEventFactory.callLightningStrikeEvent((org.bukkit.entity.LightningStrike) entitylightning.getBukkitEntity(), cause);
+
+        if (lightning.isCancelled()) {
+            return false;
+        }
+
+        return this.addEntity(entitylightning);
+    }
+    // CraftBukkit end
+
     @Override
     public void a(int i, BlockPosition blockposition, int j) {
         Iterator iterator = this.server.getPlayerList().getPlayers().iterator();
 
+        // CraftBukkit start
+        EntityHuman entityhuman = null;
+        Entity entity = this.getEntity(i);
+        if (entity instanceof EntityHuman) entityhuman = (EntityHuman) entity;
+        // CraftBukkit end
+
         while (iterator.hasNext()) {
             EntityPlayer entityplayer = (EntityPlayer) iterator.next();
 
@@ -875,6 +1054,12 @@
                 double d1 = (double) blockposition.getY() - entityplayer.locY();
                 double d2 = (double) blockposition.getZ() - entityplayer.locZ();
 
+                // CraftBukkit start
+                if (entityhuman != null && entityhuman instanceof EntityPlayer && !entityplayer.getBukkitEntity().canSee(((EntityPlayer) entityhuman).getBukkitEntity())) {
+                    continue;
+                }
+                // CraftBukkit end
+
                 if (d0 * d0 + d1 * d1 + d2 * d2 < 1024.0D) {
                     entityplayer.connection.sendPacket(new PacketPlayOutBlockBreakAnimation(i, blockposition, j));
                 }
@@ -923,7 +1108,18 @@
             Iterator iterator = this.navigatingMobs.iterator();
 
             while (iterator.hasNext()) {
-                EntityInsentient entityinsentient = (EntityInsentient) iterator.next();
+                // CraftBukkit start - fix SPIGOT-6362
+                EntityInsentient entityinsentient;
+                try {
+                    entityinsentient = (EntityInsentient) iterator.next();
+                } catch (java.util.ConcurrentModificationException ex) {
+                    // This can happen because the pathfinder update below may trigger a chunk load, which in turn may cause more navigators to register
+                    // In this case we just run the update again across all the iterators as the chunk will then be loaded
+                    // As this is a relative edge case it is much faster than copying navigators (on either read or write)
+                    notify(blockposition, iblockdata, iblockdata1, i);
+                    return;
+                }
+                // CraftBukkit end
                 NavigationAbstract navigationabstract = entityinsentient.getNavigation();
 
                 if (!navigationabstract.i()) {
@@ -946,10 +1142,20 @@
 
     @Override
     public Explosion createExplosion(@Nullable Entity entity, @Nullable DamageSource damagesource, @Nullable ExplosionDamageCalculator explosiondamagecalculator, double d0, double d1, double d2, float f, boolean flag, Explosion.Effect explosion_effect) {
+        // CraftBukkit start
+        Explosion explosion = super.createExplosion(entity, damagesource, explosiondamagecalculator, d0, d1, d2, f, flag, explosion_effect);
+
+        if (explosion.wasCanceled) {
+            return explosion;
+        }
+
+        /* Remove
         Explosion explosion = new Explosion(this, entity, damagesource, explosiondamagecalculator, d0, d1, d2, f, flag, explosion_effect);
 
         explosion.a();
         explosion.a(false);
+        */
+        // CraftBukkit end - TODO: Check if explosions are still properly implemented
         if (explosion_effect == Explosion.Effect.NONE) {
             explosion.clearBlocks();
         }
@@ -1023,13 +1229,20 @@
     }
 
     public <T extends ParticleParam> int a(T t0, double d0, double d1, double d2, int i, double d3, double d4, double d5, double d6) {
-        PacketPlayOutWorldParticles packetplayoutworldparticles = new PacketPlayOutWorldParticles(t0, false, d0, d1, d2, (float) d3, (float) d4, (float) d5, (float) d6, i);
+        // CraftBukkit - visibility api support
+        return sendParticles(null, t0, d0, d1, d2, i, d3, d4, d5, d6, false);
+    }
+
+    public <T extends ParticleParam> int sendParticles(EntityPlayer sender, T t0, double d0, double d1, double d2, int i, double d3, double d4, double d5, double d6, boolean force) {
+        PacketPlayOutWorldParticles packetplayoutworldparticles = new PacketPlayOutWorldParticles(t0, force, d0, d1, d2, (float) d3, (float) d4, (float) d5, (float) d6, i);
+        // CraftBukkit end
         int j = 0;
 
         for (int k = 0; k < this.players.size(); ++k) {
             EntityPlayer entityplayer = (EntityPlayer) this.players.get(k);
+            if (sender != null && !entityplayer.getBukkitEntity().canSee(sender.getBukkitEntity())) continue; // CraftBukkit
 
-            if (this.a(entityplayer, false, d0, d1, d2, packetplayoutworldparticles)) {
+            if (this.a(entityplayer, force, d0, d1, d2, packetplayoutworldparticles)) { // CraftBukkit
                 ++j;
             }
         }
@@ -1079,7 +1292,7 @@
 
     @Nullable
     public BlockPosition a(StructureGenerator<?> structuregenerator, BlockPosition blockposition, int i, boolean flag) {
-        return !this.server.getSaveData().getGeneratorSettings().shouldGenerateMapFeatures() ? null : this.getChunkProvider().getChunkGenerator().findNearestMapFeature(this, structuregenerator, blockposition, i, flag);
+        return !this.serverLevelData.getGeneratorSettings().shouldGenerateMapFeatures() ? null : this.getChunkProvider().getChunkGenerator().findNearestMapFeature(this, structuregenerator, blockposition, i, flag); // CraftBukkit
     }
 
     @Nullable
@@ -1116,11 +1329,21 @@
     @Nullable
     @Override
     public WorldMap a(String s) {
-        return (WorldMap) this.getMinecraftServer().F().getWorldPersistentData().a(WorldMap::b, s);
+        return (WorldMap) this.getMinecraftServer().F().getWorldPersistentData().a((nbttagcompound) -> {
+            // CraftBukkit start
+            // We only get here when the data file exists, but is not a valid map
+            WorldMap newMap = WorldMap.b(nbttagcompound);
+            newMap.id = s;
+            MapInitializeEvent event = new MapInitializeEvent(newMap.mapView);
+            Bukkit.getServer().getPluginManager().callEvent(event);
+            return newMap;
+            // CraftBukkit end
+        }, s);
     }
 
     @Override
     public void a(String s, WorldMap worldmap) {
+        worldmap.id = s; // CraftBukkit
         this.getMinecraftServer().F().getWorldPersistentData().a(s, (PersistentBase) worldmap);
     }
 
@@ -1432,6 +1655,11 @@
     @Override
     public void update(BlockPosition blockposition, Block block) {
         if (!this.isDebugWorld()) {
+            // CraftBukkit start
+            if (populating) {
+                return;
+            }
+            // CraftBukkit end
             this.applyPhysics(blockposition, block);
         }
 
@@ -1451,12 +1679,12 @@
     }
 
     public boolean isFlatWorld() {
-        return this.server.getSaveData().getGeneratorSettings().isFlatWorld();
+        return this.serverLevelData.getGeneratorSettings().isFlatWorld(); // CraftBukkit
     }
 
     @Override
     public long getSeed() {
-        return this.server.getSaveData().getGeneratorSettings().getSeed();
+        return this.serverLevelData.getGeneratorSettings().getSeed(); // CraftBukkit
     }
 
     @Nullable
@@ -1484,7 +1712,7 @@
     private static <T> String a(Iterable<T> iterable, Function<T, String> function) {
         try {
             Object2IntOpenHashMap<String> object2intopenhashmap = new Object2IntOpenHashMap();
-            Iterator iterator = iterable.iterator();
+            Iterator<T> iterator = iterable.iterator(); // CraftBukkit - decompile error
 
             while (iterator.hasNext()) {
                 T t0 = iterator.next();
@@ -1493,7 +1721,7 @@
                 object2intopenhashmap.addTo(s, 1);
             }
 
-            return (String) object2intopenhashmap.object2IntEntrySet().stream().sorted(Comparator.comparing(Entry::getIntValue).reversed()).limit(5L).map((entry) -> {
+            return (String) object2intopenhashmap.object2IntEntrySet().stream().sorted(Comparator.comparing(Entry<String>::getIntValue).reversed()).limit(5L).map((entry) -> { // CraftBukkit - decompile error
                 String s1 = (String) entry.getKey();
 
                 return s1 + ":" + entry.getIntValue();
@@ -1504,17 +1732,33 @@
     }
 
     public static void a(WorldServer worldserver) {
+        // CraftBukkit start
+        WorldServer.a(worldserver, null);
+    }
+
+    public static void a(WorldServer worldserver, Entity entity) {
+        // CraftBukkit end
         BlockPosition blockposition = WorldServer.END_SPAWN_POINT;
         int i = blockposition.getX();
         int j = blockposition.getY() - 2;
         int k = blockposition.getZ();
 
+        // CraftBukkit start
+        org.bukkit.craftbukkit.util.BlockStateListPopulator blockList = new org.bukkit.craftbukkit.util.BlockStateListPopulator(worldserver);
         BlockPosition.b(i - 2, j + 1, k - 2, i + 2, j + 3, k + 2).forEach((blockposition1) -> {
-            worldserver.setTypeUpdate(blockposition1, Blocks.AIR.getBlockData());
+            blockList.setTypeAndData(blockposition1, Blocks.AIR.getBlockData(), 3);
         });
         BlockPosition.b(i - 2, j, k - 2, i + 2, j, k + 2).forEach((blockposition1) -> {
-            worldserver.setTypeUpdate(blockposition1, Blocks.OBSIDIAN.getBlockData());
+            blockList.setTypeAndData(blockposition1, Blocks.OBSIDIAN.getBlockData(), 3);
         });
+        org.bukkit.World bworld = worldserver.getWorld();
+        org.bukkit.event.world.PortalCreateEvent portalEvent = new org.bukkit.event.world.PortalCreateEvent((List<org.bukkit.block.BlockState>) (List) blockList.getList(), bworld, (entity == null) ? null : entity.getBukkitEntity(), org.bukkit.event.world.PortalCreateEvent.CreateReason.END_PLATFORM);
+
+        worldserver.getCraftServer().getPluginManager().callEvent(portalEvent);
+        if (!portalEvent.isCancelled()) {
+            blockList.updateList();
+        }
+        // CraftBukkit end
     }
 
     @Override
@@ -1601,6 +1845,7 @@
                 }
             }
 
+            entity.valid = true; // CraftBukkit
         }
 
         public void a(Entity entity) {
@@ -1633,6 +1878,7 @@
                 gameeventlistenerregistrar.a(entity.level);
             }
 
+            entity.valid = false; // CraftBukkit
         }
     }
 }
