From 08698c4642cc1ae9dea605e1ce0efe32f679101c Mon Sep 17 00:00:00 2001
From: Jake Potrebic <jake.m.potrebic@gmail.com>
Date: Tue, 31 May 2016 22:53:50 -0400
Subject: [PATCH] Fix global sound handling

* Only send global sounds to same world if limiting radius
* respect global sound events gamerule

Co-authored-by: Evan McCarthy <evanmccarthy@outlook.com>
Co-authored-by: lexikiq <noellekiq@gmail.com>
Co-authored-by: Aikar <aikar@aikar.co>
---
 .../server/level/ServerLevel.java.patch       | 38 ++++++++++++++++---
 .../boss/enderdragon/EnderDragon.java.patch   | 35 ++++++++---------
 .../entity/boss/wither/WitherBoss.java.patch  | 15 ++++----
 .../world/item/EnderEyeItem.java.patch        | 10 +++--
 4 files changed, 64 insertions(+), 34 deletions(-)

diff --git a/paper-server/patches/sources/net/minecraft/server/level/ServerLevel.java.patch b/paper-server/patches/sources/net/minecraft/server/level/ServerLevel.java.patch
index 74662e2d38..55464c27e3 100644
--- a/paper-server/patches/sources/net/minecraft/server/level/ServerLevel.java.patch
+++ b/paper-server/patches/sources/net/minecraft/server/level/ServerLevel.java.patch
@@ -445,10 +445,9 @@
      @VisibleForTesting
      public void resetWeatherCycle() {
 -        this.serverLevelData.setRainTime(0);
--        this.serverLevelData.setRaining(false);
--        this.serverLevelData.setThunderTime(0);
 +        // CraftBukkit start
-+        this.serverLevelData.setRaining(false);
+         this.serverLevelData.setRaining(false);
+-        this.serverLevelData.setThunderTime(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.isRaining()) {
@@ -674,6 +673,15 @@
                  if (d0 * d0 + d1 * d1 + d2 * d2 < 1024.0D) {
                      entityplayer.connection.send(new ClientboundBlockDestructionPacket(entityId, pos, progress));
                  }
+@@ -1030,7 +1311,7 @@
+ 
+     @Override
+     public void levelEvent(@Nullable Player player, int eventId, BlockPos pos, int data) {
+-        this.server.getPlayerList().broadcast(player, (double) pos.getX(), (double) pos.getY(), (double) pos.getZ(), 64.0D, this.dimension(), new ClientboundLevelEventPacket(eventId, pos, data, false));
++        this.server.getPlayerList().broadcast(player, (double) pos.getX(), (double) pos.getY(), (double) pos.getZ(), 64.0D, this.dimension(), new ClientboundLevelEventPacket(eventId, pos, data, false)); // Paper - diff on change (the 64.0 distance is used as defaults for sound ranges in spigot config for ender dragon, end portal and wither)
+     }
+ 
+     public int getLogicalHeight() {
 @@ -1060,7 +1341,18 @@
              Iterator iterator = this.navigatingMobs.iterator();
  
@@ -882,7 +890,25 @@
          return this.entityManager.getEntityGetter();
      }
  
-@@ -1836,6 +2171,7 @@
+@@ -1802,6 +2137,17 @@
+         return this.serverLevelData.getGameRules();
+     }
+ 
++    // Paper start - respect global sound events gamerule
++    public List<net.minecraft.server.level.ServerPlayer> getPlayersForGlobalSoundGamerule() {
++        return this.getGameRules().getBoolean(GameRules.RULE_GLOBAL_SOUND_EVENTS) ? ((ServerLevel) this).getServer().getPlayerList().players : ((ServerLevel) this).players();
++    }
++
++    public double getGlobalSoundRangeSquared(java.util.function.Function<org.spigotmc.SpigotWorldConfig, Integer> rangeFunction) {
++        final double range = rangeFunction.apply(this.spigotConfig);
++        return range <= 0 ? 64.0 * 64.0 : range * range; // 64 is taken from default in ServerLevel#levelEvent
++    }
++    // Paper end - respect global sound events gamerule
++
+     @Override
+     public CrashReportCategory fillReportDetails(CrashReport report) {
+         CrashReportCategory crashreportsystemdetails = super.fillReportDetails(report);
+@@ -1836,6 +2182,7 @@
          }
  
          public void onTrackingStart(Entity entity) {
@@ -890,7 +916,7 @@
              ServerLevel.this.getChunkSource().addEntity(entity);
              if (entity instanceof ServerPlayer entityplayer) {
                  ServerLevel.this.players.add(entityplayer);
-@@ -1864,9 +2200,52 @@
+@@ -1864,9 +2211,52 @@
              }
  
              entity.updateDynamicGameEventListener(DynamicGameEventListener::add);
@@ -943,7 +969,7 @@
              ServerLevel.this.getChunkSource().removeEntity(entity);
              if (entity instanceof ServerPlayer entityplayer) {
                  ServerLevel.this.players.remove(entityplayer);
-@@ -1895,6 +2274,15 @@
+@@ -1895,6 +2285,15 @@
              }
  
              entity.updateDynamicGameEventListener(DynamicGameEventListener::remove);
diff --git a/paper-server/patches/sources/net/minecraft/world/entity/boss/enderdragon/EnderDragon.java.patch b/paper-server/patches/sources/net/minecraft/world/entity/boss/enderdragon/EnderDragon.java.patch
index c8c9dfefa1..3d5359b4b7 100644
--- a/paper-server/patches/sources/net/minecraft/world/entity/boss/enderdragon/EnderDragon.java.patch
+++ b/paper-server/patches/sources/net/minecraft/world/entity/boss/enderdragon/EnderDragon.java.patch
@@ -91,7 +91,7 @@
  
          for (int k1 = i; k1 <= l; ++k1) {
              for (int l1 = j; l1 <= i1; ++l1) {
-@@ -467,7 +494,11 @@
+@@ -467,14 +494,61 @@
  
                      if (!iblockdata.isAir() && !iblockdata.is(BlockTags.DRAGON_TRANSPARENT)) {
                          if (world.getGameRules().getBoolean(GameRules.RULE_MOBGRIEFING) && !iblockdata.is(BlockTags.DRAGON_IMMUNE)) {
@@ -104,10 +104,11 @@
                          } else {
                              flag = true;
                          }
-@@ -476,6 +507,49 @@
-             }
-         }
- 
+                     }
++                }
++            }
++        }
++
 +        // CraftBukkit start - Set off an EntityExplodeEvent for the dragon exploding all these blocks
 +        // SPIGOT-4882: don't fire event if nothing hit
 +        if (!flag1) {
@@ -143,17 +144,16 @@
 +                        Block.popResource(this.level(), blockposition, itemstack);
 +                    });
 +                    craftBlock.getNMS().spawnAfterBreak((ServerLevel) this.level(), blockposition, ItemStack.EMPTY, false);
-+                }
+                 }
 +                nmsBlock.wasExploded((ServerLevel) this.level(), blockposition, this.explosionSource);
 +
 +                this.level().removeBlock(blockposition, false);
-+            }
-+        }
+             }
+         }
 +        // CraftBukkit end
-+
+ 
          if (flag1) {
              BlockPos blockposition1 = new BlockPos(i + this.random.nextInt(l - i + 1), j + this.random.nextInt(i1 - j + 1), k + this.random.nextInt(j1 - k + 1));
- 
 @@ -531,7 +605,7 @@
  
      @Override
@@ -186,7 +186,7 @@
      protected void tickDeath() {
          if (this.dragonFight != null) {
              this.dragonFight.updateDragon(this);
-@@ -555,21 +644,43 @@
+@@ -555,21 +644,44 @@
              this.level().addParticle(ParticleTypes.EXPLOSION_EMITTER, this.getX() + (double) f, this.getY() + 2.0D + (double) f1, this.getZ() + (double) f2, 0.0D, 0.0D, 0.0D);
          }
  
@@ -214,11 +214,12 @@
 +                // CraftBukkit start - Use relative location for far away sounds
 +                // worldserver.globalLevelEvent(1028, this.blockPosition(), 0);
 +                int viewDistance = worldserver.getCraftServer().getViewDistance() * 16;
-+                for (net.minecraft.server.level.ServerPlayer player : worldserver.getServer().getPlayerList().players) {
++                for (net.minecraft.server.level.ServerPlayer player : worldserver.getPlayersForGlobalSoundGamerule()) { // Paper - respect global sound events gamerule
 +                    double deltaX = this.getX() - player.getX();
 +                    double deltaZ = this.getZ() - player.getZ();
 +                    double distanceSquared = deltaX * deltaX + deltaZ * deltaZ;
-+                    if ( worldserver.spigotConfig.dragonDeathSoundRadius > 0 && distanceSquared > worldserver.spigotConfig.dragonDeathSoundRadius * worldserver.spigotConfig.dragonDeathSoundRadius ) continue; // Spigot
++                    final double soundRadiusSquared = worldserver.getGlobalSoundRangeSquared(config -> config.dragonDeathSoundRadius); // Paper - respect global sound events gamerule
++                    if ( !worldserver.getGameRules().getBoolean(GameRules.RULE_GLOBAL_SOUND_EVENTS) && distanceSquared > soundRadiusSquared ) continue; // Spigot // Paper - respect global sound events gamerule
 +                    if (distanceSquared > viewDistance * viewDistance) {
 +                        double deltaLength = Math.sqrt(distanceSquared);
 +                        double relativeX = player.getX() + (deltaX / deltaLength) * viewDistance;
@@ -232,7 +233,7 @@
              }
          }
  
-@@ -592,7 +703,7 @@
+@@ -592,7 +704,7 @@
              if (world1 instanceof ServerLevel) {
                  ServerLevel worldserver1 = (ServerLevel) world1;
  
@@ -241,7 +242,7 @@
                      ExperienceOrb.award(worldserver1, this.position(), Mth.floor((float) short0 * 0.2F));
                  }
  
-@@ -600,7 +711,7 @@
+@@ -600,7 +712,7 @@
                      this.dragonFight.setDragonKilled(this);
                  }
  
@@ -250,7 +251,7 @@
                  this.gameEvent(GameEvent.ENTITY_DIE);
              }
          }
-@@ -814,6 +925,7 @@
+@@ -814,6 +926,7 @@
          super.addAdditionalSaveData(nbt);
          nbt.putInt("DragonPhase", this.phaseManager.getCurrentPhase().getPhase().getId());
          nbt.putInt("DragonDeathTime", this.dragonDeathTime);
@@ -258,7 +259,7 @@
      }
  
      @Override
-@@ -827,6 +939,11 @@
+@@ -827,6 +940,11 @@
              this.dragonDeathTime = nbt.getInt("DragonDeathTime");
          }
  
diff --git a/paper-server/patches/sources/net/minecraft/world/entity/boss/wither/WitherBoss.java.patch b/paper-server/patches/sources/net/minecraft/world/entity/boss/wither/WitherBoss.java.patch
index 8f87fcdada..f61485c525 100644
--- a/paper-server/patches/sources/net/minecraft/world/entity/boss/wither/WitherBoss.java.patch
+++ b/paper-server/patches/sources/net/minecraft/world/entity/boss/wither/WitherBoss.java.patch
@@ -38,7 +38,7 @@
  
  public class WitherBoss extends Monster implements RangedAttackMob {
  
-@@ -252,15 +261,41 @@
+@@ -252,15 +261,42 @@
              i = this.getInvulnerableTicks() - 1;
              this.bossEvent.setProgress(1.0F - (float) i / 220.0F);
              if (i <= 0) {
@@ -58,11 +58,12 @@
 +                    // CraftBukkit start - Use relative location for far away sounds
 +                    // worldserver.globalLevelEvent(1023, new BlockPosition(this), 0);
 +                    int viewDistance = world.getCraftServer().getViewDistance() * 16;
-+                    for (ServerPlayer player : (List<ServerPlayer>) MinecraftServer.getServer().getPlayerList().players) {
++                    for (ServerPlayer player : world.getPlayersForGlobalSoundGamerule()) { // Paper - respect global sound events gamerule
 +                        double deltaX = this.getX() - player.getX();
 +                        double deltaZ = this.getZ() - player.getZ();
 +                        double distanceSquared = deltaX * deltaX + deltaZ * deltaZ;
-+                        if ( world.spigotConfig.witherSpawnSoundRadius > 0 && distanceSquared > world.spigotConfig.witherSpawnSoundRadius * world.spigotConfig.witherSpawnSoundRadius ) continue; // Spigot
++                        final double soundRadiusSquared = world.getGlobalSoundRangeSquared(config -> config.witherSpawnSoundRadius); // Paper - respect global sound events gamerule
++                        if ( !world.getGameRules().getBoolean(GameRules.RULE_GLOBAL_SOUND_EVENTS) && distanceSquared > soundRadiusSquared ) continue; // Spigot // Paper - respect global sound events gamerule
 +                        if (distanceSquared > viewDistance * viewDistance) {
 +                            double deltaLength = Math.sqrt(distanceSquared);
 +                            double relativeX = player.getX() + (deltaX / deltaLength) * viewDistance;
@@ -83,7 +84,7 @@
              }
  
          } else {
-@@ -305,6 +340,7 @@
+@@ -305,6 +341,7 @@
                          if (!list.isEmpty()) {
                              LivingEntity entityliving1 = (LivingEntity) list.get(this.random.nextInt(list.size()));
  
@@ -91,7 +92,7 @@
                              this.setAlternativeTarget(i, entityliving1.getId());
                          }
                      }
-@@ -331,6 +367,11 @@
+@@ -331,6 +368,11 @@
                          BlockState iblockdata = world.getBlockState(blockposition);
  
                          if (WitherBoss.canDestroy(iblockdata)) {
@@ -103,7 +104,7 @@
                              flag = world.destroyBlock(blockposition, true, this) || flag;
                          }
                      }
-@@ -342,7 +383,7 @@
+@@ -342,7 +384,7 @@
              }
  
              if (this.tickCount % 20 == 0) {
@@ -112,7 +113,7 @@
              }
  
              this.bossEvent.setProgress(this.getHealth() / this.getMaxHealth());
-@@ -499,7 +540,7 @@
+@@ -499,7 +541,7 @@
      @Override
      public void checkDespawn() {
          if (this.level().getDifficulty() == Difficulty.PEACEFUL && this.shouldDespawnInPeaceful()) {
diff --git a/paper-server/patches/sources/net/minecraft/world/item/EnderEyeItem.java.patch b/paper-server/patches/sources/net/minecraft/world/item/EnderEyeItem.java.patch
index 1287382a8d..1336d6aa77 100644
--- a/paper-server/patches/sources/net/minecraft/world/item/EnderEyeItem.java.patch
+++ b/paper-server/patches/sources/net/minecraft/world/item/EnderEyeItem.java.patch
@@ -1,6 +1,6 @@
 --- a/net/minecraft/world/item/EnderEyeItem.java
 +++ b/net/minecraft/world/item/EnderEyeItem.java
-@@ -62,7 +62,25 @@
+@@ -62,7 +62,27 @@
                          }
                      }
  
@@ -9,11 +9,13 @@
 +                    // world.globalLevelEvent(1038, blockposition1.offset(1, 0, 1), 0);
 +                    int viewDistance = world.getCraftServer().getViewDistance() * 16;
 +                    BlockPos soundPos = blockposition1.offset(1, 0, 1);
-+                    for (ServerPlayer player : world.getServer().getPlayerList().players) {
++                    final net.minecraft.server.level.ServerLevel serverLevel = (net.minecraft.server.level.ServerLevel) world; // Paper - respect global sound events gamerule - ensured by isClientSide check above
++                    for (ServerPlayer player : serverLevel.getPlayersForGlobalSoundGamerule()) { // Paper - respect global sound events gamerule
 +                        double deltaX = soundPos.getX() - player.getX();
 +                        double deltaZ = soundPos.getZ() - player.getZ();
 +                        double distanceSquared = deltaX * deltaX + deltaZ * deltaZ;
-+                        if (world.spigotConfig.endPortalSoundRadius > 0 && distanceSquared > world.spigotConfig.endPortalSoundRadius * world.spigotConfig.endPortalSoundRadius) continue; // Spigot
++                        final double soundRadiusSquared = serverLevel.getGlobalSoundRangeSquared(config -> config.endPortalSoundRadius); // Paper - respect global sound events gamerule
++                        if (!serverLevel.getGameRules().getBoolean(net.minecraft.world.level.GameRules.RULE_GLOBAL_SOUND_EVENTS) && distanceSquared > soundRadiusSquared) continue; // Spigot // Paper - respect global sound events gamerule
 +                        if (distanceSquared > viewDistance * viewDistance) {
 +                            double deltaLength = Math.sqrt(distanceSquared);
 +                            double relativeX = player.getX() + (deltaX / deltaLength) * viewDistance;
@@ -27,7 +29,7 @@
                  }
  
                  return InteractionResult.SUCCESS;
-@@ -99,7 +117,11 @@
+@@ -99,7 +119,11 @@
                  entityendersignal.setItem(itemstack);
                  entityendersignal.signalTo(blockposition);
                  world.gameEvent((Holder) GameEvent.PROJECTILE_SHOOT, entityendersignal.position(), GameEvent.Context.of((Entity) user));