Repackage patches

By: md_5 <git@md-5.net>
This commit is contained in:
CraftBukkit/Spigot
2021-03-16 09:00:00 +11:00
parent 2777f7b780
commit 18496e998f
433 changed files with 0 additions and 0 deletions

View File

@@ -0,0 +1,138 @@
--- a/net/minecraft/server/ChunkMapDistance.java
+++ b/net/minecraft/server/ChunkMapDistance.java
@@ -59,7 +59,7 @@
while (objectiterator.hasNext()) {
Entry<ArraySetSorted<Ticket<?>>> entry = (Entry) objectiterator.next();
- if (((ArraySetSorted) entry.getValue()).removeIf((ticket) -> {
+ if ((entry.getValue()).removeIf((ticket) -> { // CraftBukkit - decompile error
return ticket.b(this.currentTick);
})) {
this.ticketLevelTracker.update(entry.getLongKey(), getLowestTicketLevel((ArraySetSorted) entry.getValue()), false);
@@ -95,10 +95,25 @@
}
if (!this.pendingChunkUpdates.isEmpty()) {
- this.pendingChunkUpdates.forEach((playerchunk) -> {
+ // CraftBukkit start
+ // Iterate pending chunk updates with protection against concurrent modification exceptions
+ java.util.Iterator<PlayerChunk> iter = this.pendingChunkUpdates.iterator();
+ int expectedSize = this.pendingChunkUpdates.size();
+ do {
+ PlayerChunk playerchunk = iter.next();
+ iter.remove();
+ expectedSize--;
+
playerchunk.a(playerchunkmap);
- });
- this.pendingChunkUpdates.clear();
+
+ // Reset iterator if set was modified using add()
+ if (this.pendingChunkUpdates.size() != expectedSize) {
+ expectedSize = this.pendingChunkUpdates.size();
+ iter = this.pendingChunkUpdates.iterator();
+ }
+ } while (iter.hasNext());
+ // CraftBukkit end
+
return true;
} else {
if (!this.l.isEmpty()) {
@@ -134,23 +149,25 @@
}
}
- private void addTicket(long i, Ticket<?> ticket) {
+ private boolean addTicket(long i, Ticket<?> ticket) { // CraftBukkit - void -> boolean
ArraySetSorted<Ticket<?>> arraysetsorted = this.e(i);
int j = getLowestTicketLevel(arraysetsorted);
- Ticket<?> ticket1 = (Ticket) arraysetsorted.a((Object) ticket);
+ Ticket<?> ticket1 = (Ticket) arraysetsorted.a(ticket); // CraftBukkit - decompile error
ticket1.a(this.currentTick);
if (ticket.b() < j) {
this.ticketLevelTracker.update(i, ticket.b(), true);
}
+ return ticket == ticket1; // CraftBukkit
}
- private void removeTicket(long i, Ticket<?> ticket) {
+ private boolean removeTicket(long i, Ticket<?> ticket) { // CraftBukkit - void -> boolean
ArraySetSorted<Ticket<?>> arraysetsorted = this.e(i);
+ boolean removed = false; // CraftBukkit
if (arraysetsorted.remove(ticket)) {
- ;
+ removed = true; // CraftBukkit
}
if (arraysetsorted.isEmpty()) {
@@ -158,16 +175,29 @@
}
this.ticketLevelTracker.update(i, getLowestTicketLevel(arraysetsorted), false);
+ return removed; // CraftBukkit
}
public <T> void a(TicketType<T> tickettype, ChunkCoordIntPair chunkcoordintpair, int i, T t0) {
- this.addTicket(chunkcoordintpair.pair(), new Ticket<>(tickettype, i, t0));
+ // CraftBukkit start
+ this.addTicketAtLevel(tickettype, chunkcoordintpair, i, t0);
+ }
+
+ public <T> boolean addTicketAtLevel(TicketType<T> ticketType, ChunkCoordIntPair chunkcoordintpair, int level, T identifier) {
+ return this.addTicket(chunkcoordintpair.pair(), new Ticket<>(ticketType, level, identifier));
+ // CraftBukkit end
}
public <T> void b(TicketType<T> tickettype, ChunkCoordIntPair chunkcoordintpair, int i, T t0) {
- Ticket<T> ticket = new Ticket<>(tickettype, i, t0);
+ // CraftBukkit start
+ this.removeTicketAtLevel(tickettype, chunkcoordintpair, i, t0);
+ }
- this.removeTicket(chunkcoordintpair.pair(), ticket);
+ public <T> boolean removeTicketAtLevel(TicketType<T> ticketType, ChunkCoordIntPair chunkcoordintpair, int level, T identifier) {
+ Ticket<T> ticket = new Ticket<>(ticketType, level, identifier);
+
+ return this.removeTicket(chunkcoordintpair.pair(), ticket);
+ // CraftBukkit end
}
public <T> void addTicket(TicketType<T> tickettype, ChunkCoordIntPair chunkcoordintpair, int i, T t0) {
@@ -210,6 +240,7 @@
public void b(SectionPosition sectionposition, EntityPlayer entityplayer) {
long i = sectionposition.r().pair();
ObjectSet<EntityPlayer> objectset = (ObjectSet) this.c.get(i);
+ if (objectset == null) return; // CraftBukkit - SPIGOT-6208
objectset.remove(entityplayer);
if (objectset.isEmpty()) {
@@ -251,6 +282,26 @@
return this.i.a();
}
+ // CraftBukkit start
+ public <T> void removeAllTicketsFor(TicketType<T> ticketType, int ticketLevel, T ticketIdentifier) {
+ Ticket<T> target = new Ticket<>(ticketType, ticketLevel, ticketIdentifier);
+
+ for (java.util.Iterator<Entry<ArraySetSorted<Ticket<?>>>> iterator = this.tickets.long2ObjectEntrySet().fastIterator(); iterator.hasNext();) {
+ Entry<ArraySetSorted<Ticket<?>>> entry = iterator.next();
+ ArraySetSorted<Ticket<?>> tickets = entry.getValue();
+ if (tickets.remove(target)) {
+ // copied from removeTicket
+ this.ticketLevelTracker.update(entry.getLongKey(), getLowestTicketLevel(tickets), false);
+
+ // can't use entry after it's removed
+ if (tickets.isEmpty()) {
+ iterator.remove();
+ }
+ }
+ }
+ }
+ // CraftBukkit end
+
class a extends ChunkMap {
public a() {

View File

@@ -0,0 +1,167 @@
--- a/net/minecraft/server/ChunkProviderServer.java
+++ b/net/minecraft/server/ChunkProviderServer.java
@@ -54,6 +54,24 @@
this.clearCache();
}
+ // CraftBukkit start - properly implement isChunkLoaded
+ public boolean isChunkLoaded(int chunkX, int chunkZ) {
+ PlayerChunk chunk = this.playerChunkMap.getUpdatingChunk(ChunkCoordIntPair.pair(chunkX, chunkZ));
+ if (chunk == null) {
+ return false;
+ }
+ return chunk.getFullChunk() != null;
+ }
+
+ public Chunk getChunkUnchecked(int chunkX, int chunkZ) {
+ PlayerChunk chunk = this.playerChunkMap.getUpdatingChunk(ChunkCoordIntPair.pair(chunkX, chunkZ));
+ if (chunk == null) {
+ return null;
+ }
+ return chunk.getFullChunkUnchecked();
+ }
+ // CraftBukkit end
+
@Override
public LightEngineThreaded getLightEngine() {
return this.lightEngine;
@@ -98,7 +116,7 @@
for (int l = 0; l < 4; ++l) {
if (k == this.cachePos[l] && chunkstatus == this.cacheStatus[l]) {
ichunkaccess = this.cacheChunk[l];
- if (ichunkaccess != null || !flag) {
+ if (ichunkaccess != null) { // CraftBukkit - the chunk can become accessible in the meantime TODO for non-null chunks it might also make sense to check that the chunk's state hasn't changed in the meantime
return ichunkaccess;
}
}
@@ -144,12 +162,12 @@
if (playerchunk == null) {
return null;
} else {
- Either<IChunkAccess, PlayerChunk.Failure> either = (Either) playerchunk.b(ChunkStatus.FULL).getNow((Object) null);
+ Either<IChunkAccess, PlayerChunk.Failure> either = (Either) playerchunk.b(ChunkStatus.FULL).getNow(null); // CraftBukkit - decompile error
if (either == null) {
return null;
} else {
- IChunkAccess ichunkaccess1 = (IChunkAccess) either.left().orElse((Object) null);
+ IChunkAccess ichunkaccess1 = (IChunkAccess) either.left().orElse(null); // CraftBukkit - decompile error
if (ichunkaccess1 != null) {
this.a(k, ichunkaccess1, ChunkStatus.FULL);
@@ -176,7 +194,15 @@
int l = 33 + ChunkStatus.a(chunkstatus);
PlayerChunk playerchunk = this.getChunk(k);
- if (flag) {
+ // CraftBukkit start - don't add new ticket for currently unloading chunk
+ boolean currentlyUnloading = false;
+ if (playerchunk != null) {
+ PlayerChunk.State oldChunkState = PlayerChunk.getChunkState(playerchunk.oldTicketLevel);
+ PlayerChunk.State currentChunkState = PlayerChunk.getChunkState(playerchunk.getTicketLevel());
+ currentlyUnloading = (oldChunkState.isAtLeast(PlayerChunk.State.BORDER) && !currentChunkState.isAtLeast(PlayerChunk.State.BORDER));
+ }
+ if (flag && !currentlyUnloading) {
+ // CraftBukkit end
this.chunkMapDistance.a(TicketType.UNKNOWN, chunkcoordintpair, l, chunkcoordintpair);
if (this.a(playerchunk, l)) {
GameProfilerFiller gameprofilerfiller = this.world.getMethodProfiler();
@@ -195,7 +221,7 @@
}
private boolean a(@Nullable PlayerChunk playerchunk, int i) {
- return playerchunk == null || playerchunk.getTicketLevel() > i;
+ return playerchunk == null || playerchunk.oldTicketLevel > i; // CraftBukkit using oldTicketLevel for isLoaded checks
}
public boolean isLoaded(int i, int j) {
@@ -257,19 +283,19 @@
public boolean a(Entity entity) {
long i = ChunkCoordIntPair.pair(MathHelper.floor(entity.locX()) >> 4, MathHelper.floor(entity.locZ()) >> 4);
- return this.a(i, PlayerChunk::b);
+ return this.a(i, (Function<PlayerChunk, CompletableFuture<Either<Chunk, PlayerChunk.Failure>>>) PlayerChunk::b); // CraftBukkit - decompile error
}
@Override
public boolean a(ChunkCoordIntPair chunkcoordintpair) {
- return this.a(chunkcoordintpair.pair(), PlayerChunk::b);
+ return this.a(chunkcoordintpair.pair(), (Function<PlayerChunk, CompletableFuture<Either<Chunk, PlayerChunk.Failure>>>) PlayerChunk::b); // CraftBukkit - decompile error
}
@Override
public boolean a(BlockPosition blockposition) {
long i = ChunkCoordIntPair.pair(blockposition.getX() >> 4, blockposition.getZ() >> 4);
- return this.a(i, PlayerChunk::a);
+ return this.a(i, (Function<PlayerChunk, CompletableFuture<Either<Chunk, PlayerChunk.Failure>>>) PlayerChunk::a); // CraftBukkit - decompile error
}
private boolean a(long i, Function<PlayerChunk, CompletableFuture<Either<Chunk, PlayerChunk.Failure>>> function) {
@@ -291,11 +317,31 @@
@Override
public void close() throws IOException {
- this.save(true);
+ // CraftBukkit start
+ close(true);
+ }
+
+ public void close(boolean save) throws IOException {
+ if (save) {
+ this.save(true);
+ }
+ // CraftBukkit end
this.lightEngine.close();
this.playerChunkMap.close();
}
+ // CraftBukkit start - modelled on below
+ public void purgeUnload() {
+ this.world.getMethodProfiler().enter("purge");
+ this.chunkMapDistance.purgeTickets();
+ this.tickDistanceManager();
+ this.world.getMethodProfiler().exitEnter("unload");
+ this.playerChunkMap.unloadChunks(() -> true);
+ this.world.getMethodProfiler().exit();
+ this.clearCache();
+ }
+ // CraftBukkit end
+
public void tick(BooleanSupplier booleansupplier) {
this.world.getMethodProfiler().enter("purge");
this.chunkMapDistance.purgeTickets();
@@ -315,12 +361,12 @@
this.lastTickTime = i;
WorldData worlddata = this.world.getWorldData();
boolean flag = this.world.isDebugWorld();
- boolean flag1 = this.world.getGameRules().getBoolean(GameRules.DO_MOB_SPAWNING);
+ boolean flag1 = this.world.getGameRules().getBoolean(GameRules.DO_MOB_SPAWNING) && !world.getPlayers().isEmpty(); // CraftBukkit
if (!flag) {
this.world.getMethodProfiler().enter("pollingChunks");
int k = this.world.getGameRules().getInt(GameRules.RANDOM_TICK_SPEED);
- boolean flag2 = worlddata.getTime() % 400L == 0L;
+ boolean flag2 = world.ticksPerAnimalSpawns != 0L && worlddata.getTime() % world.ticksPerAnimalSpawns == 0L; // CraftBukkit
this.world.getMethodProfiler().enter("naturalSpawnCount");
int l = this.chunkMapDistance.b();
@@ -507,12 +553,18 @@
@Override
protected boolean executeNext() {
+ // CraftBukkit start - process pending Chunk loadCallback() and unloadCallback() after each run task
+ try {
if (ChunkProviderServer.this.tickDistanceManager()) {
return true;
} else {
ChunkProviderServer.this.lightEngine.queueUpdate();
return super.executeNext();
}
+ } finally {
+ playerChunkMap.callbackExecutor.run();
+ }
+ // CraftBukkit end
}
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,174 @@
--- a/net/minecraft/server/EntityTrackerEntry.java
+++ b/net/minecraft/server/EntityTrackerEntry.java
@@ -11,6 +11,11 @@
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
+// CraftBukkit start
+import org.bukkit.entity.Player;
+import org.bukkit.event.player.PlayerVelocityEvent;
+// CraftBukkit end
+
public class EntityTrackerEntry {
private static final Logger LOGGER = LogManager.getLogger();
@@ -31,8 +36,12 @@
private List<Entity> p;
private boolean q;
private boolean r;
+ // CraftBukkit start
+ private final Set<EntityPlayer> trackedPlayers;
- public EntityTrackerEntry(WorldServer worldserver, Entity entity, int i, boolean flag, Consumer<Packet<?>> consumer) {
+ public EntityTrackerEntry(WorldServer worldserver, Entity entity, int i, boolean flag, Consumer<Packet<?>> consumer, Set<EntityPlayer> trackedPlayers) {
+ this.trackedPlayers = trackedPlayers;
+ // CraftBukkit end
this.m = Vec3D.ORIGIN;
this.p = Collections.emptyList();
this.b = worldserver;
@@ -52,16 +61,17 @@
if (!list.equals(this.p)) {
this.p = list;
- this.f.accept(new PacketPlayOutMount(this.tracker));
+ this.broadcastIncludingSelf(new PacketPlayOutMount(this.tracker)); // CraftBukkit
}
- if (this.tracker instanceof EntityItemFrame && this.tickCounter % 10 == 0) {
+ // PAIL : rename
+ if (this.tracker instanceof EntityItemFrame /*&& this.tickCounter % 10 == 0*/) { // CraftBukkit - Moved below, should always enter this block
EntityItemFrame entityitemframe = (EntityItemFrame) this.tracker;
ItemStack itemstack = entityitemframe.getItem();
- if (itemstack.getItem() instanceof ItemWorldMap) {
+ if (this.tickCounter % 10 == 0 && itemstack.getItem() instanceof ItemWorldMap) { // CraftBukkit - Moved this.tickCounter % 10 logic here so item frames do not enter the other blocks
WorldMap worldmap = ItemWorldMap.getSavedMap(itemstack, this.b);
- Iterator iterator = this.b.getPlayers().iterator();
+ Iterator iterator = this.trackedPlayers.iterator(); // CraftBukkit
while (iterator.hasNext()) {
EntityPlayer entityplayer = (EntityPlayer) iterator.next();
@@ -106,6 +116,17 @@
boolean flag2 = flag1 || this.tickCounter % 60 == 0;
boolean flag3 = Math.abs(i - this.yRot) >= 1 || Math.abs(j - this.xRot) >= 1;
+ // CraftBukkit start - Code moved from below
+ if (flag2) {
+ this.d();
+ }
+
+ if (flag3) {
+ this.yRot = i;
+ this.xRot = j;
+ }
+ // CraftBukkit end
+
if (this.tickCounter > 0 || this.tracker instanceof EntityArrow) {
long k = PacketPlayOutEntity.a(vec3d.x);
long l = PacketPlayOutEntity.a(vec3d.y);
@@ -144,6 +165,7 @@
}
this.c();
+ /* CraftBukkit start - Code moved up
if (flag2) {
this.d();
}
@@ -152,6 +174,7 @@
this.yRot = i;
this.xRot = j;
}
+ // CraftBukkit end */
this.q = false;
}
@@ -167,7 +190,27 @@
++this.tickCounter;
if (this.tracker.velocityChanged) {
- this.broadcastIncludingSelf(new PacketPlayOutEntityVelocity(this.tracker));
+ // CraftBukkit start - Create PlayerVelocity event
+ boolean cancelled = false;
+
+ if (this.tracker instanceof EntityPlayer) {
+ Player player = (Player) this.tracker.getBukkitEntity();
+ org.bukkit.util.Vector velocity = player.getVelocity();
+
+ PlayerVelocityEvent event = new PlayerVelocityEvent(player, velocity.clone());
+ this.tracker.world.getServer().getPluginManager().callEvent(event);
+
+ if (event.isCancelled()) {
+ cancelled = true;
+ } else if (!velocity.equals(event.getVelocity())) {
+ player.setVelocity(event.getVelocity());
+ }
+ }
+
+ if (!cancelled) {
+ this.broadcastIncludingSelf(new PacketPlayOutEntityVelocity(this.tracker));
+ }
+ // CraftBukkit end
this.tracker.velocityChanged = false;
}
@@ -182,14 +225,17 @@
PlayerConnection playerconnection = entityplayer.playerConnection;
entityplayer.playerConnection.getClass();
- this.a(playerconnection::sendPacket);
+ this.a(playerconnection::sendPacket, entityplayer); // CraftBukkit - add player
this.tracker.b(entityplayer);
entityplayer.d(this.tracker);
}
- public void a(Consumer<Packet<?>> consumer) {
+ public void a(Consumer<Packet<?>> consumer, EntityPlayer entityplayer) { // CraftBukkit - add player
if (this.tracker.dead) {
- EntityTrackerEntry.LOGGER.warn("Fetching packet for removed entity " + this.tracker);
+ // CraftBukkit start - Remove useless error spam, just return
+ // EntityTrackerEntry.LOGGER.warn("Fetching packet for removed entity " + this.tracker);
+ return;
+ // CraftBukkit end
}
Packet<?> packet = this.tracker.P();
@@ -205,6 +251,12 @@
if (this.tracker instanceof EntityLiving) {
Collection<AttributeModifiable> collection = ((EntityLiving) this.tracker).getAttributeMap().b();
+ // CraftBukkit start - If sending own attributes send scaled health instead of current maximum health
+ if (this.tracker.getId() == entityplayer.getId()) {
+ ((EntityPlayer) this.tracker).getBukkitEntity().injectScaledMaxHealth(collection, false);
+ }
+ // CraftBukkit end
+
if (!collection.isEmpty()) {
consumer.accept(new PacketPlayOutUpdateAttributes(this.tracker.getId(), collection));
}
@@ -236,8 +288,14 @@
if (!list.isEmpty()) {
consumer.accept(new PacketPlayOutEntityEquipment(this.tracker.getId(), list));
}
+ ((EntityLiving) this.tracker).updateEquipment(); // CraftBukkit - SPIGOT-3789: sync again immediately after sending
}
+ // CraftBukkit start - Fix for nonsensical head yaw
+ this.headYaw = MathHelper.d(this.tracker.getHeadRotation() * 256.0F / 360.0F);
+ consumer.accept(new PacketPlayOutEntityHeadRotation(this.tracker, (byte) headYaw));
+ // CraftBukkit end
+
if (this.tracker instanceof EntityLiving) {
EntityLiving entityliving = (EntityLiving) this.tracker;
Iterator iterator = entityliving.getEffects().iterator();
@@ -278,6 +336,11 @@
Set<AttributeModifiable> set = ((EntityLiving) this.tracker).getAttributeMap().getAttributes();
if (!set.isEmpty()) {
+ // CraftBukkit start - Send scaled max health
+ if (this.tracker instanceof EntityPlayer) {
+ ((EntityPlayer) this.tracker).getBukkitEntity().injectScaledMaxHealth(set, false);
+ }
+ // CraftBukkit end
this.broadcastIncludingSelf(new PacketPlayOutUpdateAttributes(this.tracker.getId(), set));
}

View File

@@ -0,0 +1,127 @@
--- a/net/minecraft/server/PlayerChunk.java
+++ b/net/minecraft/server/PlayerChunk.java
@@ -44,7 +44,7 @@
this.fullChunkFuture = PlayerChunk.UNLOADED_CHUNK_FUTURE;
this.tickingFuture = PlayerChunk.UNLOADED_CHUNK_FUTURE;
this.entityTickingFuture = PlayerChunk.UNLOADED_CHUNK_FUTURE;
- this.chunkSave = CompletableFuture.completedFuture((Object) null);
+ this.chunkSave = CompletableFuture.completedFuture(null); // CraftBukkit - decompile error
this.dirtyBlocks = new ShortSet[16];
this.location = chunkcoordintpair;
this.lightEngine = lightengine;
@@ -56,6 +56,19 @@
this.a(i);
}
+ // CraftBukkit start
+ public Chunk getFullChunk() {
+ if (!getChunkState(this.oldTicketLevel).isAtLeast(PlayerChunk.State.BORDER)) return null; // note: using oldTicketLevel for isLoaded checks
+ return this.getFullChunkUnchecked();
+ }
+
+ public Chunk getFullChunkUnchecked() {
+ CompletableFuture<Either<IChunkAccess, PlayerChunk.Failure>> statusFuture = this.getStatusFutureUnchecked(ChunkStatus.FULL);
+ Either<IChunkAccess, PlayerChunk.Failure> either = (Either<IChunkAccess, PlayerChunk.Failure>) statusFuture.getNow(null);
+ return (either == null) ? null : (Chunk) either.left().orElse(null);
+ }
+ // CraftBukkit end
+
public CompletableFuture<Either<IChunkAccess, PlayerChunk.Failure>> getStatusFutureUnchecked(ChunkStatus chunkstatus) {
CompletableFuture<Either<IChunkAccess, PlayerChunk.Failure>> completablefuture = (CompletableFuture) this.statusFutures.get(chunkstatus.c());
@@ -81,9 +94,9 @@
@Nullable
public Chunk getChunk() {
CompletableFuture<Either<Chunk, PlayerChunk.Failure>> completablefuture = this.a();
- Either<Chunk, PlayerChunk.Failure> either = (Either) completablefuture.getNow((Object) null);
+ Either<Chunk, PlayerChunk.Failure> either = (Either) completablefuture.getNow(null); // CraftBukkit - decompile error
- return either == null ? null : (Chunk) either.left().orElse((Object) null);
+ return either == null ? null : (Chunk) either.left().orElse(null); // CraftBukkit - decompile error
}
@Nullable
@@ -114,6 +127,7 @@
if (chunk != null) {
byte b0 = (byte) SectionPosition.a(blockposition.getY());
+ if (b0 < 0 || b0 >= this.dirtyBlocks.length) return; // CraftBukkit - SPIGOT-6086, SPIGOT-6296
if (this.dirtyBlocks[b0] == null) {
this.p = true;
this.dirtyBlocks[b0] = new ShortArraySet();
@@ -216,7 +230,7 @@
CompletableFuture<Either<IChunkAccess, PlayerChunk.Failure>> completablefuture = (CompletableFuture) this.statusFutures.get(i);
if (completablefuture != null) {
- Either<IChunkAccess, PlayerChunk.Failure> either = (Either) completablefuture.getNow((Object) null);
+ Either<IChunkAccess, PlayerChunk.Failure> either = (Either) completablefuture.getNow(null); // CraftBukkit - decompile error
if (either == null || either.left().isPresent()) {
return completablefuture;
@@ -271,6 +285,30 @@
boolean flag1 = this.ticketLevel <= PlayerChunkMap.GOLDEN_TICKET;
PlayerChunk.State playerchunk_state = getChunkState(this.oldTicketLevel);
PlayerChunk.State playerchunk_state1 = getChunkState(this.ticketLevel);
+ // CraftBukkit start
+ // ChunkUnloadEvent: Called before the chunk is unloaded: isChunkLoaded is still true and chunk can still be modified by plugins.
+ if (playerchunk_state.isAtLeast(PlayerChunk.State.BORDER) && !playerchunk_state1.isAtLeast(PlayerChunk.State.BORDER)) {
+ this.getStatusFutureUnchecked(ChunkStatus.FULL).thenAccept((either) -> {
+ Chunk chunk = (Chunk)either.left().orElse(null);
+ if (chunk != null) {
+ playerchunkmap.callbackExecutor.execute(() -> {
+ // Minecraft will apply the chunks tick lists to the world once the chunk got loaded, and then store the tick
+ // lists again inside the chunk once the chunk becomes inaccessible and set the chunk's needsSaving flag.
+ // These actions may however happen deferred, so we manually set the needsSaving flag already here.
+ chunk.setNeedsSaving(true);
+ chunk.unloadCallback();
+ });
+ }
+ }).exceptionally((throwable) -> {
+ // ensure exceptions are printed, by default this is not the case
+ MinecraftServer.LOGGER.fatal("Failed to schedule unload callback for chunk " + PlayerChunk.this.location, throwable);
+ return null;
+ });
+
+ // Run callback right away if the future was already done
+ playerchunkmap.callbackExecutor.run();
+ }
+ // CraftBukkit end
CompletableFuture completablefuture;
if (flag) {
@@ -302,7 +340,7 @@
if (flag2 && !flag3) {
completablefuture = this.fullChunkFuture;
this.fullChunkFuture = PlayerChunk.UNLOADED_CHUNK_FUTURE;
- this.a(completablefuture.thenApply((either1) -> {
+ this.a(((CompletableFuture<Either<Chunk, PlayerChunk.Failure>>) completablefuture).thenApply((either1) -> { // CraftBukkit - decompile error
playerchunkmap.getClass();
return either1.ifLeft(playerchunkmap::a);
}));
@@ -340,6 +378,26 @@
this.u.a(this.location, this::k, this.ticketLevel, this::d);
this.oldTicketLevel = this.ticketLevel;
+ // CraftBukkit start
+ // ChunkLoadEvent: Called after the chunk is loaded: isChunkLoaded returns true and chunk is ready to be modified by plugins.
+ if (!playerchunk_state.isAtLeast(PlayerChunk.State.BORDER) && playerchunk_state1.isAtLeast(PlayerChunk.State.BORDER)) {
+ this.getStatusFutureUnchecked(ChunkStatus.FULL).thenAccept((either) -> {
+ Chunk chunk = (Chunk)either.left().orElse(null);
+ if (chunk != null) {
+ playerchunkmap.callbackExecutor.execute(() -> {
+ chunk.loadCallback();
+ });
+ }
+ }).exceptionally((throwable) -> {
+ // ensure exceptions are printed, by default this is not the case
+ MinecraftServer.LOGGER.fatal("Failed to schedule load callback for chunk " + PlayerChunk.this.location, throwable);
+ return null;
+ });
+
+ // Run callback right away if the future was already done
+ playerchunkmap.callbackExecutor.run();
+ }
+ // CraftBukkit end
}
public static ChunkStatus getChunkStatus(int i) {

View File

@@ -0,0 +1,165 @@
--- a/net/minecraft/server/PlayerChunkMap.java
+++ b/net/minecraft/server/PlayerChunkMap.java
@@ -45,6 +45,8 @@
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
+import org.bukkit.entity.Player; // CraftBukkit
+
public class PlayerChunkMap extends IChunkLoader implements PlayerChunk.d {
private static final Logger LOGGER = LogManager.getLogger();
@@ -75,6 +77,31 @@
private final Queue<Runnable> A;
private int viewDistance;
+ // CraftBukkit start - recursion-safe executor for Chunk loadCallback() and unloadCallback()
+ public final CallbackExecutor callbackExecutor = new CallbackExecutor();
+ public static final class CallbackExecutor implements java.util.concurrent.Executor, Runnable {
+
+ private Runnable queued;
+
+ @Override
+ public void execute(Runnable runnable) {
+ if (queued != null) {
+ throw new IllegalStateException("Already queued");
+ }
+ queued = runnable;
+ }
+
+ @Override
+ public void run() {
+ Runnable task = queued;
+ queued = null;
+ if (task != null) {
+ task.run();
+ }
+ }
+ };
+ // CraftBukkit end
+
public PlayerChunkMap(WorldServer worldserver, Convertable.ConversionSession convertable_conversionsession, DataFixer datafixer, DefinedStructureManager definedstructuremanager, Executor executor, IAsyncTaskHandler<Runnable> iasynctaskhandler, ILightAccess ilightaccess, ChunkGenerator chunkgenerator, WorldLoadListener worldloadlistener, Supplier<WorldPersistentData> supplier, int i, boolean flag) {
super(new File(convertable_conversionsession.a(worldserver.getDimensionKey()), "region"), datafixer, flag);
this.visibleChunks = this.updatingChunks.clone();
@@ -195,9 +222,12 @@
return completablefuture1.thenApply((list1) -> {
List<IChunkAccess> list2 = Lists.newArrayList();
- final int l1 = 0;
+ // CraftBukkit start - decompile error
+ int cnt = 0;
- for (Iterator iterator = list1.iterator(); iterator.hasNext(); ++l1) {
+ for (Iterator iterator = list1.iterator(); iterator.hasNext(); ++cnt) {
+ final int l1 = cnt;
+ // CraftBukkit end
final Either<IChunkAccess, PlayerChunk.Failure> either = (Either) iterator.next();
Optional<IChunkAccess> optional = either.left();
@@ -300,7 +330,7 @@
PlayerChunkMap.LOGGER.info("ThreadedAnvilChunkStorage ({}): All chunks are saved", this.w.getName());
} else {
this.visibleChunks.values().stream().filter(PlayerChunk::hasBeenLoaded).forEach((playerchunk) -> {
- IChunkAccess ichunkaccess = (IChunkAccess) playerchunk.getChunkSave().getNow((Object) null);
+ IChunkAccess ichunkaccess = (IChunkAccess) playerchunk.getChunkSave().getNow(null); // CraftBukkit - decompile error
if (ichunkaccess instanceof ProtoChunkExtension || ichunkaccess instanceof Chunk) {
this.saveChunk(ichunkaccess);
@@ -311,7 +341,6 @@
}
}
-
protected void unloadChunks(BooleanSupplier booleansupplier) {
GameProfilerFiller gameprofilerfiller = this.world.getMethodProfiler();
@@ -350,7 +379,7 @@
private void a(long i, PlayerChunk playerchunk) {
CompletableFuture<IChunkAccess> completablefuture = playerchunk.getChunkSave();
- Consumer consumer = (ichunkaccess) -> {
+ Consumer<IChunkAccess> consumer = (ichunkaccess) -> { // CraftBukkit - decompile error
CompletableFuture<IChunkAccess> completablefuture1 = playerchunk.getChunkSave();
if (completablefuture1 != completablefuture) {
@@ -572,8 +601,15 @@
while (iterator.hasNext()) {
Entity entity = (Entity) iterator.next();
+ // CraftBukkit start - these are spawned serialized (DefinedStructure) and we don't call an add event below at the moment due to ordering complexities
+ boolean needsRemoval = false;
+ if (chunk.needsDecoration && !this.world.getServer().getServer().getSpawnNPCs() && entity instanceof NPC) {
+ entity.die();
+ needsRemoval = true;
+ }
- if (!(entity instanceof EntityHuman) && !this.world.addEntityChunk(entity)) {
+ if (!(entity instanceof EntityHuman) && (needsRemoval || !this.world.addEntityChunk(entity))) {
+ // CraftBukkit end
if (list == null) {
list = Lists.newArrayList(new Entity[]{entity});
} else {
@@ -784,7 +820,8 @@
return ichunkaccess instanceof Chunk ? Optional.of((Chunk) ichunkaccess) : Optional.empty();
});
- csvwriter.a(chunkcoordintpair.x, chunkcoordintpair.z, playerchunk.getTicketLevel(), optional.isPresent(), optional.map(IChunkAccess::getChunkStatus).orElse((Object) null), optional1.map(Chunk::getState).orElse((Object) null), a(playerchunk.c()), a(playerchunk.a()), a(playerchunk.b()), this.chunkDistanceManager.c(entry.getLongKey()), !this.isOutsideOfRange(chunkcoordintpair), optional1.map((chunk) -> {
+ // CraftBukkit - decompile error
+ csvwriter.a(chunkcoordintpair.x, chunkcoordintpair.z, playerchunk.getTicketLevel(), optional.isPresent(), optional.map(IChunkAccess::getChunkStatus).orElse(null), optional1.map(Chunk::getState).orElse(null), a(playerchunk.c()), a(playerchunk.a()), a(playerchunk.b()), this.chunkDistanceManager.c(entry.getLongKey()), !this.isOutsideOfRange(chunkcoordintpair), optional1.map((chunk) -> {
return Stream.of(chunk.getEntitySlices()).mapToInt(EntitySlice::size).sum();
}).orElse(0), optional1.map((chunk) -> {
return chunk.getTileEntities().size();
@@ -795,7 +832,7 @@
private static String a(CompletableFuture<Either<Chunk, PlayerChunk.Failure>> completablefuture) {
try {
- Either<Chunk, PlayerChunk.Failure> either = (Either) completablefuture.getNow((Object) null);
+ Either<Chunk, PlayerChunk.Failure> either = (Either) completablefuture.getNow(null); // CraftBukkit - decompile error
return either != null ? (String) either.map((chunk) -> {
return "done";
@@ -813,7 +850,7 @@
private NBTTagCompound readChunkData(ChunkCoordIntPair chunkcoordintpair) throws IOException {
NBTTagCompound nbttagcompound = this.read(chunkcoordintpair);
- return nbttagcompound == null ? null : this.getChunkData(this.world.getDimensionKey(), this.l, nbttagcompound);
+ return nbttagcompound == null ? null : this.getChunkData(this.world.getTypeKey(), this.l, nbttagcompound, chunkcoordintpair, world); // CraftBukkit
}
boolean isOutsideOfRange(ChunkCoordIntPair chunkcoordintpair) {
@@ -1145,7 +1182,7 @@
public final Set<EntityPlayer> trackedPlayers = Sets.newHashSet();
public EntityTracker(Entity entity, int i, int j, boolean flag) {
- this.trackerEntry = new EntityTrackerEntry(PlayerChunkMap.this.world, entity, j, flag, this::broadcast);
+ this.trackerEntry = new EntityTrackerEntry(PlayerChunkMap.this.world, entity, j, flag, this::broadcast, trackedPlayers); // CraftBukkit
this.tracker = entity;
this.trackingDistance = i;
this.e = SectionPosition.a(entity);
@@ -1198,7 +1235,7 @@
public void updatePlayer(EntityPlayer entityplayer) {
if (entityplayer != this.tracker) {
- Vec3D vec3d = entityplayer.getPositionVector().d(this.trackerEntry.b());
+ Vec3D vec3d = entityplayer.getPositionVector().d(this.tracker.getPositionVector()); // MC-155077, SPIGOT-5113
int i = Math.min(this.b(), (PlayerChunkMap.this.viewDistance - 1) * 16);
boolean flag = vec3d.x >= (double) (-i) && vec3d.x <= (double) i && vec3d.z >= (double) (-i) && vec3d.z <= (double) i && this.tracker.a(entityplayer);
@@ -1214,6 +1251,17 @@
}
}
+ // CraftBukkit start - respect vanish API
+ if (this.tracker instanceof EntityPlayer) {
+ Player player = ((EntityPlayer) this.tracker).getBukkitEntity();
+ if (!entityplayer.getBukkitEntity().canSee(player)) {
+ flag1 = false;
+ }
+ }
+
+ entityplayer.removeQueue.remove(Integer.valueOf(this.tracker.getId()));
+ // CraftBukkit end
+
if (flag1 && this.trackedPlayers.add(entityplayer)) {
this.trackerEntry.b(entityplayer);
}

View File

@@ -0,0 +1,336 @@
--- a/net/minecraft/server/PlayerInteractManager.java
+++ b/net/minecraft/server/PlayerInteractManager.java
@@ -4,6 +4,16 @@
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
+// CraftBukkit start
+import java.util.ArrayList;
+import org.bukkit.craftbukkit.block.CraftBlock;
+import org.bukkit.event.block.BlockBreakEvent;
+import org.bukkit.craftbukkit.event.CraftEventFactory;
+import org.bukkit.event.Event;
+import org.bukkit.event.block.Action;
+import org.bukkit.event.player.PlayerInteractEvent;
+// CraftBukkit end
+
public class PlayerInteractManager {
private static final Logger LOGGER = LogManager.getLogger();
@@ -38,7 +48,7 @@
this.gamemode = enumgamemode;
enumgamemode.a(this.player.abilities);
this.player.updateAbilities();
- this.player.server.getPlayerList().sendAll(new PacketPlayOutPlayerInfo(PacketPlayOutPlayerInfo.EnumPlayerInfoAction.UPDATE_GAME_MODE, new EntityPlayer[]{this.player}));
+ this.player.server.getPlayerList().sendAll(new PacketPlayOutPlayerInfo(PacketPlayOutPlayerInfo.EnumPlayerInfoAction.UPDATE_GAME_MODE, new EntityPlayer[]{this.player}), this.player); // CraftBukkit
this.world.everyoneSleeping();
}
@@ -67,7 +77,7 @@
}
public void a() {
- ++this.currentTick;
+ this.currentTick = MinecraftServer.currentTick; // CraftBukkit;
IBlockData iblockdata;
if (this.j) {
@@ -123,9 +133,31 @@
if (packetplayinblockdig_enumplayerdigtype == PacketPlayInBlockDig.EnumPlayerDigType.START_DESTROY_BLOCK) {
if (!this.world.a((EntityHuman) this.player, blockposition)) {
+ // CraftBukkit start - fire PlayerInteractEvent
+ CraftEventFactory.callPlayerInteractEvent(this.player, Action.LEFT_CLICK_BLOCK, blockposition, enumdirection, this.player.inventory.getItemInHand(), EnumHand.MAIN_HAND);
this.player.playerConnection.sendPacket(new PacketPlayOutBlockBreak(blockposition, this.world.getType(blockposition), packetplayinblockdig_enumplayerdigtype, false, "may not interact"));
+ // Update any tile entity data for this block
+ TileEntity tileentity = world.getTileEntity(blockposition);
+ if (tileentity != null) {
+ this.player.playerConnection.sendPacket(tileentity.getUpdatePacket());
+ }
+ // CraftBukkit end
+ return;
+ }
+
+ // CraftBukkit start
+ PlayerInteractEvent event = CraftEventFactory.callPlayerInteractEvent(this.player, Action.LEFT_CLICK_BLOCK, blockposition, enumdirection, this.player.inventory.getItemInHand(), EnumHand.MAIN_HAND);
+ if (event.isCancelled()) {
+ // Let the client know the block still exists
+ this.player.playerConnection.sendPacket(new PacketPlayOutBlockChange(this.world, blockposition));
+ // Update any tile entity data for this block
+ TileEntity tileentity = this.world.getTileEntity(blockposition);
+ if (tileentity != null) {
+ this.player.playerConnection.sendPacket(tileentity.getUpdatePacket());
+ }
return;
}
+ // CraftBukkit end
if (this.isCreative()) {
this.a(blockposition, packetplayinblockdig_enumplayerdigtype, "creative destroy");
@@ -141,11 +173,43 @@
float f = 1.0F;
iblockdata = this.world.getType(blockposition);
- if (!iblockdata.isAir()) {
+ // CraftBukkit start - Swings at air do *NOT* exist.
+ if (event.useInteractedBlock() == Event.Result.DENY) {
+ // If we denied a door from opening, we need to send a correcting update to the client, as it already opened the door.
+ IBlockData data = this.world.getType(blockposition);
+ if (data.getBlock() instanceof BlockDoor) {
+ // For some reason *BOTH* the bottom/top part have to be marked updated.
+ boolean bottom = data.get(BlockDoor.HALF) == BlockPropertyDoubleBlockHalf.LOWER;
+ this.player.playerConnection.sendPacket(new PacketPlayOutBlockChange(this.world, blockposition));
+ this.player.playerConnection.sendPacket(new PacketPlayOutBlockChange(this.world, bottom ? blockposition.up() : blockposition.down()));
+ } else if (data.getBlock() instanceof BlockTrapdoor) {
+ this.player.playerConnection.sendPacket(new PacketPlayOutBlockChange(this.world, blockposition));
+ }
+ } else if (!iblockdata.isAir()) {
iblockdata.attack(this.world, blockposition, this.player);
f = iblockdata.getDamage(this.player, this.player.world, blockposition);
}
+ if (event.useItemInHand() == Event.Result.DENY) {
+ // If we 'insta destroyed' then the client needs to be informed.
+ if (f > 1.0f) {
+ this.player.playerConnection.sendPacket(new PacketPlayOutBlockChange(this.world, blockposition));
+ }
+ return;
+ }
+ org.bukkit.event.block.BlockDamageEvent blockEvent = CraftEventFactory.callBlockDamageEvent(this.player, blockposition.getX(), blockposition.getY(), blockposition.getZ(), this.player.inventory.getItemInHand(), f >= 1.0f);
+
+ if (blockEvent.isCancelled()) {
+ // Let the client know the block still exists
+ this.player.playerConnection.sendPacket(new PacketPlayOutBlockChange(this.world, blockposition));
+ return;
+ }
+
+ if (blockEvent.getInstaBreak()) {
+ f = 2.0f;
+ }
+ // CraftBukkit end
+
if (!iblockdata.isAir() && f >= 1.0F) {
this.a(blockposition, packetplayinblockdig_enumplayerdigtype, "insta mine");
} else {
@@ -189,7 +253,7 @@
} else if (packetplayinblockdig_enumplayerdigtype == PacketPlayInBlockDig.EnumPlayerDigType.ABORT_DESTROY_BLOCK) {
this.f = false;
if (!Objects.equals(this.h, blockposition)) {
- PlayerInteractManager.LOGGER.warn("Mismatch in destroy block pos: " + this.h + " " + blockposition);
+ PlayerInteractManager.LOGGER.debug("Mismatch in destroy block pos: " + this.h + " " + blockposition); // CraftBukkit - SPIGOT-5457 sent by client when interact event cancelled
this.world.a(this.player.getId(), this.h, -1);
this.player.playerConnection.sendPacket(new PacketPlayOutBlockBreak(this.h, this.world.getType(this.h), packetplayinblockdig_enumplayerdigtype, true, "aborted mismatched destroying"));
}
@@ -205,17 +269,73 @@
if (this.breakBlock(blockposition)) {
this.player.playerConnection.sendPacket(new PacketPlayOutBlockBreak(blockposition, this.world.getType(blockposition), packetplayinblockdig_enumplayerdigtype, true, s));
} else {
- this.player.playerConnection.sendPacket(new PacketPlayOutBlockBreak(blockposition, this.world.getType(blockposition), packetplayinblockdig_enumplayerdigtype, false, s));
+ this.player.playerConnection.sendPacket(new PacketPlayOutBlockChange(this.world, blockposition)); // CraftBukkit - SPIGOT-5196
}
}
public boolean breakBlock(BlockPosition blockposition) {
IBlockData iblockdata = this.world.getType(blockposition);
+ // CraftBukkit start - fire BlockBreakEvent
+ org.bukkit.block.Block bblock = CraftBlock.at(world, blockposition);
+ BlockBreakEvent event = null;
+
+ if (this.player instanceof EntityPlayer) {
+ // Sword + Creative mode pre-cancel
+ boolean isSwordNoBreak = !this.player.getItemInMainHand().getItem().a(iblockdata, this.world, blockposition, (EntityHuman) this.player);
+
+ // Tell client the block is gone immediately then process events
+ // Don't tell the client if its a creative sword break because its not broken!
+ if (world.getTileEntity(blockposition) == null && !isSwordNoBreak) {
+ PacketPlayOutBlockChange packet = new PacketPlayOutBlockChange(this.world, blockposition);
+ packet.block = Blocks.AIR.getBlockData();
+ this.player.playerConnection.sendPacket(packet);
+ }
+
+ event = new BlockBreakEvent(bblock, this.player.getBukkitEntity());
+
+ // Sword + Creative mode pre-cancel
+ event.setCancelled(isSwordNoBreak);
+
+ // Calculate default block experience
+ IBlockData nmsData = this.world.getType(blockposition);
+ Block nmsBlock = nmsData.getBlock();
+
+ ItemStack itemstack = this.player.getEquipment(EnumItemSlot.MAINHAND);
+
+ if (nmsBlock != null && !event.isCancelled() && !this.isCreative() && this.player.hasBlock(nmsBlock.getBlockData())) {
+ event.setExpToDrop(nmsBlock.getExpDrop(nmsData, this.world, blockposition, itemstack));
+ }
- if (!this.player.getItemInMainHand().getItem().a(iblockdata, (World) this.world, blockposition, (EntityHuman) this.player)) {
+ this.world.getServer().getPluginManager().callEvent(event);
+
+ if (event.isCancelled()) {
+ if (isSwordNoBreak) {
+ return false;
+ }
+ // Let the client know the block still exists
+ this.player.playerConnection.sendPacket(new PacketPlayOutBlockChange(this.world, blockposition));
+
+ // Brute force all possible updates
+ for (EnumDirection dir : EnumDirection.values()) {
+ this.player.playerConnection.sendPacket(new PacketPlayOutBlockChange(world, blockposition.shift(dir)));
+ }
+
+ // Update any tile entity data for this block
+ TileEntity tileentity = this.world.getTileEntity(blockposition);
+ if (tileentity != null) {
+ this.player.playerConnection.sendPacket(tileentity.getUpdatePacket());
+ }
+ return false;
+ }
+ }
+ // CraftBukkit end
+
+ if (false && !this.player.getItemInMainHand().getItem().a(iblockdata, (World) this.world, blockposition, (EntityHuman) this.player)) { // CraftBukkit - false
return false;
} else {
+ iblockdata = this.world.getType(blockposition); // CraftBukkit - update state from plugins
+ if (iblockdata.isAir()) return false; // CraftBukkit - A plugin set block to air without cancelling
TileEntity tileentity = this.world.getTileEntity(blockposition);
Block block = iblockdata.getBlock();
@@ -225,6 +345,10 @@
} else if (this.player.a((World) this.world, blockposition, this.gamemode)) {
return false;
} else {
+ // CraftBukkit start
+ org.bukkit.block.BlockState state = bblock.getState();
+ world.captureDrops = new ArrayList<>();
+ // CraftBukkit end
block.a((World) this.world, blockposition, iblockdata, (EntityHuman) this.player);
boolean flag = this.world.a(blockposition, false);
@@ -233,19 +357,32 @@
}
if (this.isCreative()) {
- return true;
+ // return true; // CraftBukkit
} else {
ItemStack itemstack = this.player.getItemInMainHand();
ItemStack itemstack1 = itemstack.cloneItemStack();
boolean flag1 = this.player.hasBlock(iblockdata);
itemstack.a(this.world, iblockdata, blockposition, this.player);
- if (flag && flag1) {
+ if (flag && flag1 && event.isDropItems()) { // CraftBukkit - Check if block should drop items
block.a(this.world, this.player, blockposition, iblockdata, tileentity, itemstack1);
}
- return true;
+ // return true; // CraftBukkit
+ }
+ // CraftBukkit start
+ if (event.isDropItems()) {
+ org.bukkit.craftbukkit.event.CraftEventFactory.handleBlockDropItemEvent(bblock, state, this.player, world.captureDrops);
+ }
+ world.captureDrops = null;
+
+ // Drop event experience
+ if (flag && event != null) {
+ iblockdata.getBlock().dropExperience(this.world, blockposition, event.getExpToDrop());
}
+
+ return true;
+ // CraftBukkit end
}
}
}
@@ -287,12 +424,46 @@
}
}
+ // CraftBukkit start - whole method
+ public boolean interactResult = false;
+ public boolean firedInteract = false;
+ public BlockPosition interactPosition;
+ public EnumHand interactHand;
+ public ItemStack interactItemStack;
public EnumInteractionResult a(EntityPlayer entityplayer, World world, ItemStack itemstack, EnumHand enumhand, MovingObjectPositionBlock movingobjectpositionblock) {
BlockPosition blockposition = movingobjectpositionblock.getBlockPosition();
IBlockData iblockdata = world.getType(blockposition);
+ EnumInteractionResult enuminteractionresult = EnumInteractionResult.PASS;
+ boolean cancelledBlock = false;
if (this.gamemode == EnumGamemode.SPECTATOR) {
ITileInventory itileinventory = iblockdata.b(world, blockposition);
+ cancelledBlock = !(itileinventory instanceof ITileInventory);
+ }
+
+ if (entityplayer.getCooldownTracker().hasCooldown(itemstack.getItem())) {
+ cancelledBlock = true;
+ }
+
+ PlayerInteractEvent event = CraftEventFactory.callPlayerInteractEvent(entityplayer, Action.RIGHT_CLICK_BLOCK, blockposition, movingobjectpositionblock.getDirection(), itemstack, cancelledBlock, enumhand);
+ firedInteract = true;
+ interactResult = event.useItemInHand() == Event.Result.DENY;
+ interactPosition = blockposition.immutableCopy();
+ interactHand = enumhand;
+ interactItemStack = itemstack.cloneItemStack();
+
+ if (event.useInteractedBlock() == Event.Result.DENY) {
+ // If we denied a door from opening, we need to send a correcting update to the client, as it already opened the door.
+ if (iblockdata.getBlock() instanceof BlockDoor) {
+ boolean bottom = iblockdata.get(BlockDoor.HALF) == BlockPropertyDoubleBlockHalf.LOWER;
+ entityplayer.playerConnection.sendPacket(new PacketPlayOutBlockChange(world, bottom ? blockposition.up() : blockposition.down()));
+ } else if (iblockdata.getBlock() instanceof BlockCake) {
+ entityplayer.getBukkitEntity().sendHealthUpdate(); // SPIGOT-1341 - reset health for cake
+ }
+ entityplayer.getBukkitEntity().updateInventory(); // SPIGOT-2867
+ enuminteractionresult = (event.useItemInHand() != Event.Result.ALLOW) ? EnumInteractionResult.SUCCESS : EnumInteractionResult.PASS;
+ } else if (this.gamemode == EnumGamemode.SPECTATOR) {
+ ITileInventory itileinventory = iblockdata.b(world, blockposition);
if (itileinventory != null) {
entityplayer.openContainer(itileinventory);
@@ -306,7 +477,7 @@
ItemStack itemstack1 = itemstack.cloneItemStack();
if (!flag1) {
- EnumInteractionResult enuminteractionresult = iblockdata.interact(world, entityplayer, enumhand, movingobjectpositionblock);
+ enuminteractionresult = iblockdata.interact(world, entityplayer, enumhand, movingobjectpositionblock);
if (enuminteractionresult.a()) {
CriterionTriggers.M.a(entityplayer, blockposition, itemstack1);
@@ -314,17 +485,17 @@
}
}
- if (!itemstack.isEmpty() && !entityplayer.getCooldownTracker().hasCooldown(itemstack.getItem())) {
+ if (!itemstack.isEmpty() && enuminteractionresult != EnumInteractionResult.SUCCESS && !interactResult) { // add !interactResult SPIGOT-764
ItemActionContext itemactioncontext = new ItemActionContext(entityplayer, enumhand, movingobjectpositionblock);
EnumInteractionResult enuminteractionresult1;
if (this.isCreative()) {
int i = itemstack.getCount();
- enuminteractionresult1 = itemstack.placeItem(itemactioncontext);
+ enuminteractionresult1 = itemstack.placeItem(itemactioncontext, enumhand);
itemstack.setCount(i);
} else {
- enuminteractionresult1 = itemstack.placeItem(itemactioncontext);
+ enuminteractionresult1 = itemstack.placeItem(itemactioncontext, enumhand);
}
if (enuminteractionresult1.a()) {
@@ -332,10 +503,10 @@
}
return enuminteractionresult1;
- } else {
- return EnumInteractionResult.PASS;
}
}
+ return enuminteractionresult;
+ // CraftBukkit end
}
public void a(WorldServer worldserver) {

View File

@@ -0,0 +1,16 @@
--- a/net/minecraft/server/RegionLimitedWorldAccess.java
+++ b/net/minecraft/server/RegionLimitedWorldAccess.java
@@ -236,6 +236,13 @@
@Override
public boolean addEntity(Entity entity) {
+ // CraftBukkit start
+ return addEntity(entity, org.bukkit.event.entity.CreatureSpawnEvent.SpawnReason.DEFAULT);
+ }
+
+ @Override
+ public boolean addEntity(Entity entity, org.bukkit.event.entity.CreatureSpawnEvent.SpawnReason reason) {
+ // CraftBukkit end
int i = MathHelper.floor(entity.locX() / 16.0D);
int j = MathHelper.floor(entity.locZ() / 16.0D);

View File

@@ -0,0 +1,11 @@
--- a/net/minecraft/server/TicketType.java
+++ b/net/minecraft/server/TicketType.java
@@ -19,6 +19,8 @@
public static final TicketType<BlockPosition> PORTAL = a("portal", BaseBlockPosition::compareTo, 300);
public static final TicketType<Integer> POST_TELEPORT = a("post_teleport", Integer::compareTo, 5);
public static final TicketType<ChunkCoordIntPair> UNKNOWN = a("unknown", Comparator.comparingLong(ChunkCoordIntPair::pair), 1);
+ public static final TicketType<Unit> PLUGIN = a("plugin", (a, b) -> 0); // CraftBukkit
+ public static final TicketType<org.bukkit.plugin.Plugin> PLUGIN_TICKET = a("plugin_ticket", (plugin1, plugin2) -> plugin1.getClass().getName().compareTo(plugin2.getClass().getName())); // CraftBukkit
public static <T> TicketType<T> a(String s, Comparator<T> comparator) {
return new TicketType<>(s, comparator, 0L);

View File

@@ -0,0 +1,687 @@
--- a/net/minecraft/server/WorldServer.java
+++ b/net/minecraft/server/WorldServer.java
@@ -39,6 +39,18 @@
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
+// CraftBukkit start
+import java.util.logging.Level;
+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 a = new BlockPosition(100, 50, 0);
@@ -50,7 +62,7 @@
private final ChunkProviderServer chunkProvider;
boolean tickingEntities;
private final MinecraftServer server;
- public final IWorldDataServer worldDataServer;
+ public final WorldDataServer worldDataServer; // CraftBukkit - type
public boolean savingDisabled;
private boolean everyoneSleeping;
private int emptyTime;
@@ -67,8 +79,23 @@
private final StructureManager structureManager;
private final boolean Q;
- 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) {
- 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.chunkProvider.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) {
+ super(iworlddataserver, resourcekey, dimensionmanager, minecraftserver::getMethodProfiler, false, flag, i, gen, env);
+ this.pvpMode = minecraftserver.getPVP();
+ convertable = convertable_conversionsession;
+ uuid = WorldUUID.getUUID(convertable_conversionsession.folder.toFile());
+ // CraftBukkit end
this.nextTickListBlock = new TickListServer<>(this, (block) -> {
return block == null || block.getBlockData().isAir();
}, IRegistry.BLOCK::getKey, this::b);
@@ -80,10 +107,17 @@
this.Q = flag1;
this.server = minecraftserver;
this.mobSpawners = list;
- this.worldDataServer = iworlddataserver;
+ // CraftBukkit start
+ this.worldDataServer = (WorldDataServer) iworlddataserver;
+ worldDataServer.world = this;
+ if (gen != null) {
+ chunkgenerator = new org.bukkit.craftbukkit.generator.CustomChunkGenerator(this, chunkgenerator, gen);
+ }
+
this.chunkProvider = new ChunkProviderServer(this, convertable_conversionsession, minecraftserver.getDataFixer(), minecraftserver.getDefinedStructureManager(), executor, chunkgenerator, minecraftserver.getPlayerList().getViewDistance(), minecraftserver.isSyncChunkWrites(), worldloadlistener, () -> {
return minecraftserver.E().getWorldPersistentData();
});
+ // CraftBukkit end
this.portalTravelAgent = new PortalTravelAgent(this);
this.Q();
this.R();
@@ -95,14 +129,48 @@
iworlddataserver.setGameType(minecraftserver.getGamemode());
}
- this.structureManager = new StructureManager(this, minecraftserver.getSaveData().getGeneratorSettings());
+ this.structureManager = new StructureManager(this, this.worldDataServer.getGeneratorSettings()); // CraftBukkit
if (this.getDimensionManager().isCreateDragonBattle()) {
- this.dragonBattle = new EnderDragonBattle(this, minecraftserver.getSaveData().getGeneratorSettings().getSeed(), minecraftserver.getSaveData().C());
+ this.dragonBattle = new EnderDragonBattle(this, this.worldDataServer.getGeneratorSettings().getSeed(), this.worldDataServer.C()); // CraftBukkit
} else {
this.dragonBattle = null;
}
+ this.getServer().addWorld(this.getWorld()); // CraftBukkit
+ }
+
+ // CraftBukkit start
+ @Override
+ protected TileEntity getTileEntity(BlockPosition pos, boolean validate) {
+ TileEntity result = super.getTileEntity(pos, validate);
+ if (!validate || Thread.currentThread() != this.serverThread) {
+ // SPIGOT-5378: avoid deadlock, this can be called in loading logic (i.e lighting) but getType() will block on chunk load
+ return result;
+ }
+ Block type = getType(pos).getBlock();
+ if (result != null && type != Blocks.AIR) {
+ if (!result.getTileType().isValidBlock(type)) {
+ result = fixTileEntity(pos, type, result);
+ }
+ }
+
+ return result;
+ }
+
+ private TileEntity fixTileEntity(BlockPosition pos, Block type, TileEntity found) {
+ this.getServer().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(this);
+ replacement.world = this;
+ this.setTileEntity(pos, replacement);
+ return replacement;
+ } else {
+ return found;
+ }
}
+ // CraftBukkit end
public void a(int i, int j, boolean flag, boolean flag1) {
this.worldDataServer.setClearWeatherTime(i);
@@ -193,6 +261,7 @@
this.rainLevel = MathHelper.a(this.rainLevel, 0.0F, 1.0F);
}
+ /* CraftBukkit start
if (this.lastRainLevel != this.rainLevel) {
this.server.getPlayerList().a((Packet) (new PacketPlayOutGameStateChange(PacketPlayOutGameStateChange.h, this.rainLevel)), this.getDimensionKey());
}
@@ -211,18 +280,47 @@
this.server.getPlayerList().sendAll(new PacketPlayOutGameStateChange(PacketPlayOutGameStateChange.h, this.rainLevel));
this.server.getPlayerList().sendAll(new PacketPlayOutGameStateChange(PacketPlayOutGameStateChange.i, this.thunderLevel));
}
+ // */
+ for (int idx = 0; idx < this.players.size(); ++idx) {
+ if (((EntityPlayer) this.players.get(idx)).world == 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)).world == 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)).world == this) {
+ ((EntityPlayer) this.players.get(idx)).updateWeather(this.lastRainLevel, this.rainLevel, this.lastThunderLevel, this.thunderLevel);
+ }
+ }
+ // CraftBukkit end
if (this.everyoneSleeping && this.players.stream().noneMatch((entityplayer) -> {
- return !entityplayer.isSpectator() && !entityplayer.isDeeplySleeping();
+ return !entityplayer.isSpectator() && !entityplayer.isDeeplySleeping() && !entityplayer.fauxSleeping; // CraftBukkit
})) {
- this.everyoneSleeping = false;
+ // CraftBukkit start
+ long l = this.worldData.getDayTime() + 24000L;
+ TimeSkipEvent event = new TimeSkipEvent(this.getWorld(), TimeSkipEvent.SkipReason.NIGHT_SKIP, (l - l % 24000L) - this.getDayTime());
if (this.getGameRules().getBoolean(GameRules.DO_DAYLIGHT_CYCLE)) {
- long l = this.worldData.getDayTime() + 24000L;
+ getServer().getPluginManager().callEvent(event);
+ if (!event.isCancelled()) {
+ this.setDayTime(this.getDayTime() + event.getSkipAmount());
+ }
- this.setDayTime(l - l % 24000L);
}
- this.wakeupPlayers();
+ if (!event.isCancelled()) {
+ this.everyoneSleeping = false;
+ this.wakeupPlayers();
+ }
+ // CraftBukkit end
if (this.getGameRules().getBoolean(GameRules.DO_WEATHER_CYCLE)) {
this.clearWeather();
}
@@ -244,7 +342,7 @@
this.ak();
this.ticking = false;
gameprofilerfiller.exitEnter("entities");
- 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();
@@ -263,6 +361,7 @@
Entity entity = (Entity) entry.getValue();
Entity entity1 = entity.getVehicle();
+ /* CraftBukkit start - We prevent spawning in general, so this butchering is not needed
if (!this.server.getSpawnAnimals() && (entity instanceof EntityAnimal || entity instanceof EntityWaterAnimal)) {
entity.die();
}
@@ -270,6 +369,7 @@
if (!this.server.getSpawnNPCs() && entity instanceof NPC) {
entity.die();
}
+ // CraftBukkit end */
gameprofilerfiller.enter("checkDespawn");
if (!entity.dead) {
@@ -344,7 +444,7 @@
}
private void wakeupPlayers() {
- ((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);
});
}
@@ -371,14 +471,14 @@
entityhorseskeleton.t(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
}
}
@@ -389,11 +489,11 @@
BiomeBase biomebase = this.getBiome(blockposition);
if (biomebase.a(this, blockposition1)) {
- this.setTypeUpdate(blockposition1, Blocks.ICE.getBlockData());
+ org.bukkit.craftbukkit.event.CraftEventFactory.handleBlockFormEvent(this, blockposition1, Blocks.ICE.getBlockData(), null); // CraftBukkit
}
if (flag && biomebase.b(this, blockposition)) {
- this.setTypeUpdate(blockposition, Blocks.SNOW.getBlockData());
+ org.bukkit.craftbukkit.event.CraftEventFactory.handleBlockFormEvent(this, blockposition, Blocks.SNOW.getBlockData(), null); // CraftBukkit
}
if (flag && this.getBiome(blockposition1).c() == BiomeBase.Precipitation.RAIN) {
@@ -440,7 +540,7 @@
protected BlockPosition a(BlockPosition blockposition) {
BlockPosition blockposition1 = this.getHighestBlockYAt(HeightMap.Type.MOTION_BLOCKING, blockposition);
AxisAlignedBB axisalignedbb = (new AxisAlignedBB(blockposition1, new BlockPosition(blockposition1.getX(), this.getBuildHeight(), blockposition1.getZ()))).g(3.0D);
- List<EntityLiving> list = this.a(EntityLiving.class, axisalignedbb, (entityliving) -> {
+ List<EntityLiving> list = this.a(EntityLiving.class, axisalignedbb, (java.util.function.Predicate<EntityLiving>) (entityliving) -> { // CraftBukkit - decompile error
return entityliving != null && entityliving.isAlive() && this.e(entityliving.getChunkCoordinates());
});
@@ -469,7 +569,7 @@
while (iterator.hasNext()) {
EntityPlayer entityplayer = (EntityPlayer) iterator.next();
- if (entityplayer.isSpectator()) {
+ if (entityplayer.isSpectator() || (entityplayer.fauxSleeping && !entityplayer.isSleeping())) { // CraftBukkit
++i;
} else if (entityplayer.isSleeping()) {
++j;
@@ -487,10 +587,22 @@
}
private void clearWeather() {
- this.worldDataServer.setWeatherDuration(0);
+ // CraftBukkit start
this.worldDataServer.setStorm(false);
- this.worldDataServer.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.worldDataServer.hasStorm()) {
+ this.worldDataServer.setWeatherDuration(0);
+ }
+ // CraftBukkit end
this.worldDataServer.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.worldDataServer.isThundering()) {
+ this.worldDataServer.setThunderDuration(0);
+ }
+ // CraftBukkit end
}
public void resetEmptyTime() {
@@ -531,6 +643,7 @@
});
gameprofilerfiller.c("tickNonPassenger");
entity.tick();
+ entity.postTick(); // CraftBukkit
gameprofilerfiller.exit();
}
@@ -563,6 +676,7 @@
});
gameprofilerfiller.c("tickPassenger");
entity1.passengerTick();
+ entity1.postTick(); // CraftBukkit
gameprofilerfiller.exit();
}
@@ -619,6 +733,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"));
}
@@ -630,11 +745,19 @@
chunkproviderserver.save(flag);
}
+
+ // CraftBukkit start - moved from MinecraftServer.saveChunks
+ WorldServer worldserver1 = this;
+
+ worldDataServer.a(worldserver1.getWorldBorder().t());
+ worldDataServer.setCustomBossEvents(this.server.getBossBattleCustomData().save());
+ convertable.a(this.server.customRegistry, this.worldDataServer, this.server.getPlayerList().save());
+ // CraftBukkit end
}
private void aj() {
if (this.dragonBattle != null) {
- this.server.getSaveData().a(this.dragonBattle.a());
+ this.worldDataServer.a(this.dragonBattle.a()); // CraftBukkit
}
this.getChunkProvider().getWorldPersistentData().a();
@@ -695,11 +818,24 @@
@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) {
@@ -749,13 +885,18 @@
this.registerEntity(entityplayer);
}
- private boolean addEntity0(Entity entity) {
+ // CraftBukkit start
+ private boolean addEntity0(Entity entity, CreatureSpawnEvent.SpawnReason spawnReason) {
if (entity.dead) {
- 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 if (this.isUUIDTaken(entity)) {
return false;
} else {
+ if (!CraftEventFactory.doEntityAddEventCalling(this, entity, spawnReason)) {
+ return false;
+ }
+ // CraftBukkit end
IChunkAccess ichunkaccess = this.getChunkAt(MathHelper.floor(entity.locX() / 16.0D), MathHelper.floor(entity.locZ() / 16.0D), ChunkStatus.FULL, entity.attachedToPlayer);
if (!(ichunkaccess instanceof Chunk)) {
@@ -784,7 +925,7 @@
if (entity1 == null) {
return false;
} else {
- WorldServer.LOGGER.warn("Trying to add entity with duplicated UUID {}. Existing {}#{}, new: {}#{}", uuid, EntityTypes.getName(entity1.getEntityType()), entity1.getId(), EntityTypes.getName(entity.getEntityType()), entity.getId());
+ // WorldServer.LOGGER.warn("Trying to add entity with duplicated UUID {}. Existing {}#{}, new: {}#{}", uuid, EntityTypes.getName(entity1.getEntityType()), entity1.getId(), EntityTypes.getName(entity.getEntityType()), entity.getId()); // CraftBukkit
return true;
}
}
@@ -813,10 +954,16 @@
}
public boolean addAllEntitiesSafely(Entity entity) {
+ // 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
if (entity.recursiveStream().anyMatch(this::isUUIDTaken)) {
return false;
} else {
- this.addAllEntities(entity);
+ this.addAllEntities(entity, reason); // CraftBukkit
return true;
}
}
@@ -867,10 +1014,17 @@
}
this.getScoreboard().a(entity);
+ // CraftBukkit start - SPIGOT-5278
+ if (entity instanceof EntityDrowned) {
+ this.navigators.remove(((EntityDrowned) entity).navigationWater);
+ this.navigators.remove(((EntityDrowned) entity).navigationLand);
+ } else
+ // CraftBukkit end
if (entity instanceof EntityInsentient) {
this.navigators.remove(((EntityInsentient) entity).getNavigation());
}
+ entity.valid = false; // CraftBukkit
}
private void registerEntity(Entity entity) {
@@ -891,9 +1045,16 @@
this.entitiesByUUID.put(entity.getUniqueID(), entity);
this.getChunkProvider().addEntity(entity);
+ // CraftBukkit start - SPIGOT-5278
+ if (entity instanceof EntityDrowned) {
+ this.navigators.add(((EntityDrowned) entity).navigationWater);
+ this.navigators.add(((EntityDrowned) entity).navigationLand);
+ } else
+ // CraftBukkit end
if (entity instanceof EntityInsentient) {
this.navigators.add(((EntityInsentient) entity).getNavigation());
}
+ entity.valid = true; // CraftBukkit
}
}
@@ -909,7 +1070,7 @@
}
private void removeEntityFromChunk(Entity entity) {
- IChunkAccess ichunkaccess = this.getChunkAt(entity.chunkX, entity.chunkZ, ChunkStatus.FULL, false);
+ IChunkAccess ichunkaccess = chunkProvider.getChunkUnchecked(entity.chunkX, entity.chunkZ); // CraftBukkit - SPIGOT-5228: getChunkAt won't find the entity's chunk if it has already been unloaded (i.e. if it switched to state INACCESSIBLE).
if (ichunkaccess instanceof Chunk) {
((Chunk) ichunkaccess).b(entity);
@@ -923,10 +1084,33 @@
this.everyoneSleeping();
}
+ // CraftBukkit start
+ public boolean strikeLightning(Entity entitylightning) {
+ return this.strikeLightning(entitylightning, LightningStrikeEvent.Cause.UNKNOWN);
+ }
+
+ public boolean strikeLightning(Entity entitylightning, LightningStrikeEvent.Cause cause) {
+ LightningStrikeEvent lightning = new LightningStrikeEvent(this.getWorld(), (org.bukkit.entity.LightningStrike) entitylightning.getBukkitEntity(), cause);
+ this.getServer().getPluginManager().callEvent(lightning);
+
+ 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();
@@ -935,6 +1119,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.playerConnection.sendPacket(new PacketPlayOutBlockBreakAnimation(i, blockposition, j));
}
@@ -973,7 +1163,18 @@
Iterator iterator = this.navigators.iterator();
while (iterator.hasNext()) {
- NavigationAbstract navigationabstract = (NavigationAbstract) iterator.next();
+ // CraftBukkit start - fix SPIGOT-6362
+ NavigationAbstract navigationabstract;
+ try {
+ navigationabstract = (NavigationAbstract) 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
if (!navigationabstract.i()) {
navigationabstract.b(blockposition);
@@ -995,10 +1196,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();
}
@@ -1063,13 +1274,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;
}
}
@@ -1111,7 +1329,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.worldDataServer.getGeneratorSettings().shouldGenerateMapFeatures() ? null : this.getChunkProvider().getChunkGenerator().findNearestMapFeature(this, structuregenerator, blockposition, i, flag); // CraftBukkit
}
@Nullable
@@ -1149,7 +1367,13 @@
@Override
public WorldMap a(String s) {
return (WorldMap) this.getMinecraftServer().E().getWorldPersistentData().b(() -> {
- return new WorldMap(s);
+ // CraftBukkit start
+ // We only get here when the data file exists, but is not a valid map
+ WorldMap newMap = new WorldMap(s);
+ MapInitializeEvent event = new MapInitializeEvent(newMap.mapView);
+ Bukkit.getServer().getPluginManager().callEvent(event);
+ return newMap;
+ // CraftBukkit end
}, s);
}
@@ -1460,6 +1684,11 @@
@Override
public void update(BlockPosition blockposition, Block block) {
if (!this.isDebugWorld()) {
+ // CraftBukkit start
+ if (populating) {
+ return;
+ }
+ // CraftBukkit end
this.applyPhysics(blockposition, block);
}
@@ -1474,12 +1703,12 @@
}
public boolean isFlatWorld() {
- return this.server.getSaveData().getGeneratorSettings().isFlatWorld();
+ return this.worldDataServer.getGeneratorSettings().isFlatWorld(); // CraftBukkit
}
@Override
public long getSeed() {
- return this.server.getSaveData().getGeneratorSettings().getSeed();
+ return this.worldDataServer.getGeneratorSettings().getSeed(); // CraftBukkit
}
@Nullable
@@ -1499,9 +1728,9 @@
@VisibleForTesting
public String F() {
- return String.format("players: %s, entities: %d [%s], block_entities: %d [%s], block_ticks: %d, fluid_ticks: %d, chunk_source: %s", this.players.size(), this.entitiesById.size(), a((Collection) this.entitiesById.values(), (entity) -> {
+ return String.format("players: %s, entities: %d [%s], block_entities: %d [%s], block_ticks: %d, fluid_ticks: %d, chunk_source: %s", this.players.size(), this.entitiesById.size(), a(this.entitiesById.values(), (entity) -> { // CraftBukkit - decompile error
return IRegistry.ENTITY_TYPE.getKey(entity.getEntityType());
- }), this.tileEntityListTick.size(), a((Collection) this.tileEntityListTick, (tileentity) -> {
+ }), this.tileEntityListTick.size(), a(this.tileEntityListTick, (tileentity) -> { // CraftBukkit - decompile error
return IRegistry.BLOCK_ENTITY_TYPE.getKey(tileentity.getTileType());
}), this.getBlockTickList().a(), this.getFluidTickList().a(), this.P());
}
@@ -1509,7 +1738,7 @@
private static <T> String a(Collection<T> collection, Function<T, MinecraftKey> function) {
try {
Object2IntOpenHashMap<MinecraftKey> object2intopenhashmap = new Object2IntOpenHashMap();
- Iterator iterator = collection.iterator();
+ Iterator<T> iterator = collection.iterator(); // CraftBukkit - decompile error
while (iterator.hasNext()) {
T t0 = iterator.next();
@@ -1518,7 +1747,8 @@
object2intopenhashmap.addTo(minecraftkey, 1);
}
- return (String) object2intopenhashmap.object2IntEntrySet().stream().sorted(Comparator.comparing(it.unimi.dsi.fastutil.objects.Object2IntMap.Entry::getIntValue).reversed()).limit(5L).map((it_unimi_dsi_fastutil_objects_object2intmap_entry) -> {
+ // CraftBukkit - decompile error
+ return (String) object2intopenhashmap.object2IntEntrySet().stream().sorted(Comparator.comparing(it.unimi.dsi.fastutil.objects.Object2IntMap.Entry<MinecraftKey>::getIntValue).reversed()).limit(5L).map((it_unimi_dsi_fastutil_objects_object2intmap_entry) -> {
return it_unimi_dsi_fastutil_objects_object2intmap_entry.getKey() + ":" + it_unimi_dsi_fastutil_objects_object2intmap_entry.getIntValue();
}).collect(Collectors.joining(","));
} catch (Exception exception) {
@@ -1527,16 +1757,32 @@
}
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.a;
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.getServer().getPluginManager().callEvent(portalEvent);
+ if (!portalEvent.isCancelled()) {
+ blockList.updateList();
+ }
+ // CraftBukkit end
}
}