From 32f7b1fa11deb0e379a7ab9794ba002973d95260 Mon Sep 17 00:00:00 2001
From: Trigary <trigary0@gmail.com>
Date: Wed, 10 Mar 2021 12:24:20 +0100
Subject: [PATCH] fix patch 'Remove streams from SensorNearest' (fixes #5330)

---
 .../Remove-streams-from-SensorNearest.patch          | 12 +++++++-----
 1 file changed, 7 insertions(+), 5 deletions(-)

diff --git a/Spigot-Server-Patches/Remove-streams-from-SensorNearest.patch b/Spigot-Server-Patches/Remove-streams-from-SensorNearest.patch
index 0269b032f5..1c489bef27 100644
--- a/Spigot-Server-Patches/Remove-streams-from-SensorNearest.patch
+++ b/Spigot-Server-Patches/Remove-streams-from-SensorNearest.patch
@@ -85,7 +85,7 @@ index 0000000000000000000000000000000000000000..00000000000000000000000000000000
 -        });
 +        // Paper start - remove streams in favour of lists
 +        List<EntityHuman> players = new java.util.ArrayList<>(worldserver.getPlayers());
-+        players.removeIf(player -> IEntitySelector.notSpectator().test(player) || entityliving.a(player, 16.0D)); // Paper - removeIf only re-allocates once compared to iterator
++        players.removeIf(player -> !IEntitySelector.notSpectator().test(player) || !entityliving.a(player, 16.0D)); // Paper - removeIf only re-allocates once compared to iterator
 +        players.sort(Comparator.comparingDouble(entityliving::h));
  
 -        entityliving.getClass();
@@ -105,14 +105,16 @@ index 0000000000000000000000000000000000000000..00000000000000000000000000000000
 +
 +        EntityHuman nearest = null, nearestTargetable = null;
 +        for (EntityHuman player : players) {
-+            if (!Sensor.a(entityliving, player)) {
++            if (Sensor.a(entityliving, player)) {
 +                if (nearest == null) nearest = player;
-+                if (IEntitySelector.canAITarget().test(player)) nearestTargetable = player; // Paper - after setting nearestTargetable the loop will definitely break, we do not need a null check.
++                if (IEntitySelector.canAITarget().test(player)) {
++                    nearestTargetable = player;
++                    break; // Both variables are assigned, no reason to loop further
++                }
 +            }
-+            if (nearest != null && nearestTargetable != null) break;
 +        }
 +        behaviorcontroller.setMemory(MemoryModuleType.NEAREST_VISIBLE_PLAYER, nearest);
-+        behaviorcontroller.setMemory(MemoryModuleType.NEAREST_VISIBLE_TARGETABLE_PLAYER, nearest != null && IEntitySelector.canAITarget().test(nearest) ? Optional.of(nearest) : Optional.empty());
++        behaviorcontroller.setMemory(MemoryModuleType.NEAREST_VISIBLE_TARGETABLE_PLAYER, nearestTargetable);
 +        // Paper end
      }
  }