aboutsummaryrefslogtreecommitdiffhomepage
path: root/paper-server/patches/features/0003-Entity-Activation-Range-2.0.patch
blob: adff760447df1f35d476c4b76079aec0270255b8 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
From: Aikar <aikar@aikar.co>
Date: Fri, 13 May 2016 01:38:06 -0400
Subject: [PATCH] Entity Activation Range 2.0

Optimizes performance of Activation Range

Adds many new configurations and a new wake up inactive system

Fixes and adds new Immunities to improve gameplay behavior

Adds water Mobs to activation range config and nerfs fish
Adds flying monsters to control ghast and phantoms
Adds villagers as separate config

diff --git a/io/papermc/paper/entity/activation/ActivationRange.java b/io/papermc/paper/entity/activation/ActivationRange.java
new file mode 100644
index 0000000000000000000000000000000000000000..bd888ef719b9bfc93bace0b1d0fb771ac659f515
--- /dev/null
+++ b/io/papermc/paper/entity/activation/ActivationRange.java
@@ -0,0 +1,318 @@
+package io.papermc.paper.entity.activation;
+
+import net.minecraft.core.BlockPos;
+import net.minecraft.server.MinecraftServer;
+import net.minecraft.world.entity.Entity;
+import net.minecraft.world.entity.ExperienceOrb;
+import net.minecraft.world.entity.FlyingMob;
+import net.minecraft.world.entity.LightningBolt;
+import net.minecraft.world.entity.LivingEntity;
+import net.minecraft.world.entity.Mob;
+import net.minecraft.world.entity.ai.Brain;
+import net.minecraft.world.entity.animal.Animal;
+import net.minecraft.world.entity.animal.Bee;
+import net.minecraft.world.entity.animal.Sheep;
+import net.minecraft.world.entity.animal.horse.Llama;
+import net.minecraft.world.entity.boss.EnderDragonPart;
+import net.minecraft.world.entity.boss.enderdragon.EndCrystal;
+import net.minecraft.world.entity.boss.enderdragon.EnderDragon;
+import net.minecraft.world.entity.boss.wither.WitherBoss;
+import net.minecraft.world.entity.item.ItemEntity;
+import net.minecraft.world.entity.item.PrimedTnt;
+import net.minecraft.world.entity.monster.Creeper;
+import net.minecraft.world.entity.monster.Pillager;
+import net.minecraft.world.entity.npc.Villager;
+import net.minecraft.world.entity.player.Player;
+import net.minecraft.world.entity.projectile.AbstractArrow;
+import net.minecraft.world.entity.projectile.AbstractHurtingProjectile;
+import net.minecraft.world.entity.projectile.EyeOfEnder;
+import net.minecraft.world.entity.projectile.FireworkRocketEntity;
+import net.minecraft.world.entity.projectile.ThrowableProjectile;
+import net.minecraft.world.entity.projectile.ThrownTrident;
+import net.minecraft.world.entity.schedule.Activity;
+import net.minecraft.world.level.Level;
+import net.minecraft.world.phys.AABB;
+import org.spigotmc.SpigotWorldConfig;
+
+public final class ActivationRange {
+
+    private ActivationRange() {
+    }
+
+    static Activity[] VILLAGER_PANIC_IMMUNITIES = {
+        Activity.HIDE,
+        Activity.PRE_RAID,
+        Activity.RAID,
+        Activity.PANIC
+    };
+
+    private static int checkInactiveWakeup(final Entity entity) {
+        final Level world = entity.level();
+        final SpigotWorldConfig config = world.spigotConfig;
+        final long inactiveFor = MinecraftServer.currentTick - entity.activatedTick;
+        if (entity.activationType == ActivationType.VILLAGER) {
+            if (inactiveFor > config.wakeUpInactiveVillagersEvery && world.wakeupInactiveRemainingVillagers > 0) {
+                world.wakeupInactiveRemainingVillagers--;
+                return config.wakeUpInactiveVillagersFor;
+            }
+        } else if (entity.activationType == ActivationType.ANIMAL) {
+            if (inactiveFor > config.wakeUpInactiveAnimalsEvery && world.wakeupInactiveRemainingAnimals > 0) {
+                world.wakeupInactiveRemainingAnimals--;
+                return config.wakeUpInactiveAnimalsFor;
+            }
+        } else if (entity.activationType == ActivationType.FLYING_MONSTER) {
+            if (inactiveFor > config.wakeUpInactiveFlyingEvery && world.wakeupInactiveRemainingFlying > 0) {
+                world.wakeupInactiveRemainingFlying--;
+                return config.wakeUpInactiveFlyingFor;
+            }
+        } else if (entity.activationType == ActivationType.MONSTER || entity.activationType == ActivationType.RAIDER) {
+            if (inactiveFor > config.wakeUpInactiveMonstersEvery && world.wakeupInactiveRemainingMonsters > 0) {
+                world.wakeupInactiveRemainingMonsters--;
+                return config.wakeUpInactiveMonstersFor;
+            }
+        }
+        return -1;
+    }
+
+    static AABB maxBB = new AABB(0, 0, 0, 0, 0, 0);
+
+    /**
+     * These entities are excluded from Activation range checks.
+     *
+     * @param entity
+     * @param config
+     * @return boolean If it should always tick.
+     */
+    public static boolean initializeEntityActivationState(final Entity entity, final SpigotWorldConfig config) {
+        return (entity.activationType == ActivationType.MISC && config.miscActivationRange == 0)
+            || (entity.activationType == ActivationType.RAIDER && config.raiderActivationRange == 0)
+            || (entity.activationType == ActivationType.ANIMAL && config.animalActivationRange == 0)
+            || (entity.activationType == ActivationType.MONSTER && config.monsterActivationRange == 0)
+            || (entity.activationType == ActivationType.VILLAGER && config.villagerActivationRange <= 0)
+            || (entity.activationType == ActivationType.WATER && config.waterActivationRange <= 0)
+            || (entity.activationType == ActivationType.FLYING_MONSTER && config.flyingMonsterActivationRange <= 0)
+            || entity instanceof EyeOfEnder
+            || entity instanceof Player
+            || entity instanceof ThrowableProjectile
+            || entity instanceof EnderDragon
+            || entity instanceof EnderDragonPart
+            || entity instanceof WitherBoss
+            || entity instanceof AbstractHurtingProjectile
+            || entity instanceof LightningBolt
+            || entity instanceof PrimedTnt
+            || entity instanceof net.minecraft.world.entity.item.FallingBlockEntity
+            || entity instanceof net.minecraft.world.entity.vehicle.AbstractMinecart
+            || entity instanceof net.minecraft.world.entity.vehicle.AbstractBoat
+            || entity instanceof EndCrystal
+            || entity instanceof FireworkRocketEntity
+            || entity instanceof ThrownTrident;
+    }
+
+    /**
+     * Find what entities are in range of the players in the world and set
+     * active if in range.
+     *
+     * @param world
+     */
+    public static void activateEntities(final Level world) {
+        final int miscActivationRange = world.spigotConfig.miscActivationRange;
+        final int raiderActivationRange = world.spigotConfig.raiderActivationRange;
+        final int animalActivationRange = world.spigotConfig.animalActivationRange;
+        final int monsterActivationRange = world.spigotConfig.monsterActivationRange;
+        final int waterActivationRange = world.spigotConfig.waterActivationRange;
+        final int flyingActivationRange = world.spigotConfig.flyingMonsterActivationRange;
+        final int villagerActivationRange = world.spigotConfig.villagerActivationRange;
+        world.wakeupInactiveRemainingAnimals = Math.min(world.wakeupInactiveRemainingAnimals + 1, world.spigotConfig.wakeUpInactiveAnimals);
+        world.wakeupInactiveRemainingVillagers = Math.min(world.wakeupInactiveRemainingVillagers + 1, world.spigotConfig.wakeUpInactiveVillagers);
+        world.wakeupInactiveRemainingMonsters = Math.min(world.wakeupInactiveRemainingMonsters + 1, world.spigotConfig.wakeUpInactiveMonsters);
+        world.wakeupInactiveRemainingFlying = Math.min(world.wakeupInactiveRemainingFlying + 1, world.spigotConfig.wakeUpInactiveFlying);
+
+        int maxRange = Math.max(monsterActivationRange, animalActivationRange);
+        maxRange = Math.max(maxRange, raiderActivationRange);
+        maxRange = Math.max(maxRange, miscActivationRange);
+        maxRange = Math.max(maxRange, flyingActivationRange);
+        maxRange = Math.max(maxRange, waterActivationRange);
+        maxRange = Math.max(maxRange, villagerActivationRange);
+        maxRange = Math.min((world.spigotConfig.simulationDistance << 4) - 8, maxRange);
+
+        for (final Player player : world.players()) {
+            player.activatedTick = MinecraftServer.currentTick;
+            if (world.spigotConfig.ignoreSpectatorActivation && player.isSpectator()) {
+                continue;
+            }
+
+            final int worldHeight = world.getHeight();
+            ActivationRange.maxBB = player.getBoundingBox().inflate(maxRange, worldHeight, maxRange);
+            ActivationType.MISC.boundingBox = player.getBoundingBox().inflate(miscActivationRange, worldHeight, miscActivationRange);
+            ActivationType.RAIDER.boundingBox = player.getBoundingBox().inflate(raiderActivationRange, worldHeight, raiderActivationRange);
+            ActivationType.ANIMAL.boundingBox = player.getBoundingBox().inflate(animalActivationRange, worldHeight, animalActivationRange);
+            ActivationType.MONSTER.boundingBox = player.getBoundingBox().inflate(monsterActivationRange, worldHeight, monsterActivationRange);
+            ActivationType.WATER.boundingBox = player.getBoundingBox().inflate(waterActivationRange, worldHeight, waterActivationRange);
+            ActivationType.FLYING_MONSTER.boundingBox = player.getBoundingBox().inflate(flyingActivationRange, worldHeight, flyingActivationRange);
+            ActivationType.VILLAGER.boundingBox = player.getBoundingBox().inflate(villagerActivationRange, worldHeight, villagerActivationRange);
+
+            final java.util.List<Entity> entities = world.getEntities((Entity) null, ActivationRange.maxBB, e -> true);
+            final boolean tickMarkers = world.paperConfig().entities.markers.tick;
+            for (final Entity entity : entities) {
+                if (!tickMarkers && entity instanceof net.minecraft.world.entity.Marker) {
+                    continue;
+                }
+
+                ActivationRange.activateEntity(entity);
+            }
+        }
+    }
+
+    /**
+     * Tries to activate an entity.
+     *
+     * @param entity
+     */
+    private static void activateEntity(final Entity entity) {
+        if (MinecraftServer.currentTick > entity.activatedTick) {
+            if (entity.defaultActivationState) {
+                entity.activatedTick = MinecraftServer.currentTick;
+                return;
+            }
+            if (entity.activationType.boundingBox.intersects(entity.getBoundingBox())) {
+                entity.activatedTick = MinecraftServer.currentTick;
+            }
+        }
+    }
+
+    /**
+     * If an entity is not in range, do some more checks to see if we should
+     * give it a shot.
+     *
+     * @param entity
+     * @return
+     */
+    public static int checkEntityImmunities(final Entity entity) { // return # of ticks to get immunity
+        final SpigotWorldConfig config = entity.level().spigotConfig;
+        final int inactiveWakeUpImmunity = checkInactiveWakeup(entity);
+        if (inactiveWakeUpImmunity > -1) {
+            return inactiveWakeUpImmunity;
+        }
+        if (entity.getRemainingFireTicks() > 0) {
+            return 2;
+        }
+        if (entity.activatedImmunityTick >= MinecraftServer.currentTick) {
+            return 1;
+        }
+        final long inactiveFor = MinecraftServer.currentTick - entity.activatedTick;
+        if ((entity.activationType != ActivationType.WATER && entity.isInWater() && entity.isPushedByFluid())) {
+            return 100;
+        }
+        if (!entity.onGround() || entity.getDeltaMovement().horizontalDistanceSqr() > 9.999999747378752E-6D) {
+            return 100;
+        }
+        if (!(entity instanceof final AbstractArrow arrow)) {
+            if ((!entity.onGround() && !(entity instanceof FlyingMob))) {
+                return 10;
+            }
+        } else if (!arrow.isInGround()) {
+            return 1;
+        }
+        // special cases.
+        if (entity instanceof final LivingEntity living) {
+            if (living.onClimbable() || living.jumping || living.hurtTime > 0 || !living.activeEffects.isEmpty() || living.isFreezing()) {
+                return 1;
+            }
+            if (entity instanceof final Mob mob && mob.getTarget() != null) {
+                return 20;
+            }
+            if (entity instanceof final Bee bee) {
+                final BlockPos movingTarget = bee.getMovingTarget();
+                if (bee.isAngry() ||
+                    (bee.getHivePos() != null && bee.getHivePos().equals(movingTarget)) ||
+                    (bee.getSavedFlowerPos() != null && bee.getSavedFlowerPos().equals(movingTarget))
+                ) {
+                    return 20;
+                }
+            }
+            if (entity instanceof final Villager villager) {
+                final Brain<Villager> behaviorController = villager.getBrain();
+
+                if (config.villagersActiveForPanic) {
+                    for (final Activity activity : VILLAGER_PANIC_IMMUNITIES) {
+                        if (behaviorController.isActive(activity)) {
+                            return 20 * 5;
+                        }
+                    }
+                }
+
+                if (config.villagersWorkImmunityAfter > 0 && inactiveFor >= config.villagersWorkImmunityAfter) {
+                    if (behaviorController.isActive(Activity.WORK)) {
+                        return config.villagersWorkImmunityFor;
+                    }
+                }
+            }
+            if (entity instanceof final Llama llama && llama.inCaravan()) {
+                return 1;
+            }
+            if (entity instanceof final Animal animal) {
+                if (animal.isBaby() || animal.isInLove()) {
+                    return 5;
+                }
+                if (entity instanceof final Sheep sheep && sheep.isSheared()) {
+                    return 1;
+                }
+            }
+            if (entity instanceof final Creeper creeper && creeper.isIgnited()) { // isExplosive
+                return 20;
+            }
+            if (entity instanceof final Mob mob && mob.targetSelector.hasTasks()) {
+                return 0;
+            }
+            if (entity instanceof final Pillager pillager) {
+                // TODO:?
+            }
+        }
+        // SPIGOT-6644: Otherwise the target refresh tick will be missed
+        if (entity instanceof ExperienceOrb) {
+            return 20;
+        }
+        return -1;
+    }
+
+    /**
+     * Checks if the entity is active for this tick.
+     *
+     * @param entity
+     * @return
+     */
+    public static boolean checkIfActive(final Entity entity) {
+        // Never safe to skip fireworks or item gravity
+        if (entity instanceof FireworkRocketEntity || (entity instanceof ItemEntity && (entity.tickCount + entity.getId()) % 4 == 0)) { // Needed for item gravity, see ItemEntity tick
+            return true;
+        }
+        // special case always immunities
+        // immunize brand-new entities, dead entities, and portal scenarios
+        if (entity.defaultActivationState || entity.tickCount < 20 * 10 || !entity.isAlive() || (entity.portalProcess != null && !entity.portalProcess.hasExpired()) || entity.portalCooldown > 0) {
+            return true;
+        }
+        // immunize leashed entities
+        if (entity instanceof final Mob mob && mob.getLeashHolder() instanceof Player) {
+            return true;
+        }
+
+        boolean isActive = entity.activatedTick >= MinecraftServer.currentTick;
+        entity.isTemporarilyActive = false;
+
+        // Should this entity tick?
+        if (!isActive) {
+            if ((MinecraftServer.currentTick - entity.activatedTick - 1) % 20 == 0) {
+                // Check immunities every 20 ticks.
+                final int immunity = checkEntityImmunities(entity);
+                if (immunity >= 0) {
+                    entity.activatedTick = MinecraftServer.currentTick + immunity;
+                } else {
+                    entity.isTemporarilyActive = true;
+                }
+                isActive = true;
+            }
+        }
+        // removed the original's dumb tick skipping for active entities
+        return isActive;
+    }
+}
diff --git a/net/minecraft/server/level/ChunkMap.java b/net/minecraft/server/level/ChunkMap.java
index d95413af04121fe91ca0f3b0c70025b9808acef9..ad665c7535c615d2b03a3e7864be435f933235dd 100644
--- a/net/minecraft/server/level/ChunkMap.java
+++ b/net/minecraft/server/level/ChunkMap.java
@@ -4,7 +4,6 @@ import com.google.common.collect.ImmutableList;
 import com.google.common.collect.Iterables;
 import com.google.common.collect.Lists;
 import com.google.common.collect.Queues;
-import com.google.common.collect.Sets;
 import com.google.common.collect.ImmutableList.Builder;
 import com.mojang.datafixers.DataFixer;
 import com.mojang.logging.LogUtils;
@@ -19,7 +18,6 @@ import it.unimi.dsi.fastutil.longs.LongIterator;
 import it.unimi.dsi.fastutil.longs.LongLinkedOpenHashSet;
 import it.unimi.dsi.fastutil.longs.LongOpenHashSet;
 import it.unimi.dsi.fastutil.longs.LongSet;
-import it.unimi.dsi.fastutil.longs.Long2ObjectMap.Entry;
 import java.io.IOException;
 import java.io.Writer;
 import java.nio.file.Path;
@@ -95,7 +93,6 @@ import net.minecraft.world.level.levelgen.structure.StructureStart;
 import net.minecraft.world.level.levelgen.structure.templatesystem.StructureTemplateManager;
 import net.minecraft.world.level.storage.DimensionDataStorage;
 import net.minecraft.world.level.storage.LevelStorageSource;
-import net.minecraft.world.phys.Vec3;
 import org.apache.commons.lang3.mutable.MutableBoolean;
 import org.slf4j.Logger;
 
diff --git a/net/minecraft/server/level/ServerLevel.java b/net/minecraft/server/level/ServerLevel.java
index 3164f3784131babf9a6663335517a12df7e88a7b..da8848e2a3e3745949eb2356a049451d30f763a7 100644
--- a/net/minecraft/server/level/ServerLevel.java
+++ b/net/minecraft/server/level/ServerLevel.java
@@ -551,6 +551,7 @@ public class ServerLevel extends Level implements ServerEntityGetter, WorldGenLe
                 profilerFiller.pop();
             }
 
+            io.papermc.paper.entity.activation.ActivationRange.activateEntities(this); // Paper - EAR
             this.entityTickList
                 .forEach(
                     entity -> {
@@ -979,12 +980,15 @@ public class ServerLevel extends Level implements ServerEntityGetter, WorldGenLe
         entity.tickCount++;
         profilerFiller.push(() -> BuiltInRegistries.ENTITY_TYPE.getKey(entity.getType()).toString());
         profilerFiller.incrementCounter("tickNonPassenger");
+        final boolean isActive = io.papermc.paper.entity.activation.ActivationRange.checkIfActive(entity); // Paper - EAR 2
+        if (isActive) { // Paper - EAR 2
         entity.tick();
         entity.postTick(); // CraftBukkit
+        } else {entity.inactiveTick();} // Paper - EAR 2
         profilerFiller.pop();
 
         for (Entity entity1 : entity.getPassengers()) {
-            this.tickPassenger(entity, entity1);
+            this.tickPassenger(entity, entity1, isActive); // Paper - EAR 2
         }
         // Paper start - log detailed entity tick information
         } finally {
@@ -995,7 +999,7 @@ public class ServerLevel extends Level implements ServerEntityGetter, WorldGenLe
         // Paper end - log detailed entity tick information
     }
 
-    private void tickPassenger(Entity ridingEntity, Entity passengerEntity) {
+    private void tickPassenger(Entity ridingEntity, Entity passengerEntity, final boolean isActive) { // Paper - EAR 2
         if (passengerEntity.isRemoved() || passengerEntity.getVehicle() != ridingEntity) {
             passengerEntity.stopRiding();
         } else if (passengerEntity instanceof Player || this.entityTickList.contains(passengerEntity)) {
@@ -1004,12 +1008,21 @@ public class ServerLevel extends Level implements ServerEntityGetter, WorldGenLe
             ProfilerFiller profilerFiller = Profiler.get();
             profilerFiller.push(() -> BuiltInRegistries.ENTITY_TYPE.getKey(passengerEntity.getType()).toString());
             profilerFiller.incrementCounter("tickPassenger");
+            // Paper start - EAR 2
+            if (isActive) {
             passengerEntity.rideTick();
             passengerEntity.postTick(); // CraftBukkit
+            } else {
+                passengerEntity.setDeltaMovement(Vec3.ZERO);
+                passengerEntity.inactiveTick();
+                // copied from inside of if (isPassenger()) of passengerTick, but that ifPassenger is unnecessary
+                ridingEntity.positionRider(passengerEntity);
+            }
+            // Paper end - EAR 2
             profilerFiller.pop();
 
             for (Entity entity : passengerEntity.getPassengers()) {
-                this.tickPassenger(passengerEntity, entity);
+                this.tickPassenger(passengerEntity, entity, isActive); // Paper - EAR 2
             }
         }
     }
diff --git a/net/minecraft/world/entity/AgeableMob.java b/net/minecraft/world/entity/AgeableMob.java
index a9f01e616ef6b0d74caf57cd68eb371a4fd30fd5..179f4e4b9b1eb57f78bbb2f9fa34b11ea79b7a88 100644
--- a/net/minecraft/world/entity/AgeableMob.java
+++ b/net/minecraft/world/entity/AgeableMob.java
@@ -126,6 +126,23 @@ public abstract class AgeableMob extends PathfinderMob {
         super.onSyncedDataUpdated(key);
     }
 
+    // Paper start - EAR 2
+    @Override
+    public void inactiveTick() {
+        super.inactiveTick();
+        if (this.level().isClientSide || this.ageLocked) { // CraftBukkit
+            this.refreshDimensions();
+        } else {
+            int age = this.getAge();
+            if (age < 0) {
+                this.setAge(++age);
+            } else if (age > 0) {
+                this.setAge(--age);
+            }
+        }
+    }
+    // Paper end - EAR 2
+
     @Override
     public void aiStep() {
         super.aiStep();
diff --git a/net/minecraft/world/entity/AreaEffectCloud.java b/net/minecraft/world/entity/AreaEffectCloud.java
index 24735284fda151414d99faad401d25ba60995f9a..23b342cc31c7e72ade0e1ccad86a9ccf34380f13 100644
--- a/net/minecraft/world/entity/AreaEffectCloud.java
+++ b/net/minecraft/world/entity/AreaEffectCloud.java
@@ -128,6 +128,16 @@ public class AreaEffectCloud extends Entity implements TraceableEntity {
         this.duration = duration;
     }
 
+    // Paper start - EAR 2
+    @Override
+    public void inactiveTick() {
+        super.inactiveTick();
+        if (this.tickCount >= this.waitTime + this.duration) {
+            this.discard(org.bukkit.event.entity.EntityRemoveEvent.Cause.DESPAWN); // CraftBukkit - add Bukkit remove cause
+        }
+    }
+    // Paper end - EAR 2
+
     @Override
     public void tick() {
         super.tick();
diff --git a/net/minecraft/world/entity/Entity.java b/net/minecraft/world/entity/Entity.java
index e7889c9c7b155db46730f5e168bb7fd3d1732a8c..334859c5ff7023c730513301cc11c9837b2c7823 100644
--- a/net/minecraft/world/entity/Entity.java
+++ b/net/minecraft/world/entity/Entity.java
@@ -380,6 +380,15 @@ public abstract class Entity implements SyncedDataHolder, Nameable, EntityAccess
     public boolean fixedPose = false; // Paper - Expand Pose API
     private final int despawnTime; // Paper - entity despawn time limit
     public final io.papermc.paper.entity.activation.ActivationType activationType = io.papermc.paper.entity.activation.ActivationType.activationTypeFor(this); // Paper - EAR 2/tracking ranges
+    // Paper start - EAR 2
+    public final boolean defaultActivationState;
+    public long activatedTick = Integer.MIN_VALUE;
+    public boolean isTemporarilyActive;
+    public long activatedImmunityTick = Integer.MIN_VALUE;
+
+    public void inactiveTick() {
+    }
+    // Paper end - EAR 2
 
     public void setOrigin(@javax.annotation.Nonnull org.bukkit.Location location) {
         this.origin = location.toVector();
@@ -417,6 +426,13 @@ public abstract class Entity implements SyncedDataHolder, Nameable, EntityAccess
         this.position = Vec3.ZERO;
         this.blockPosition = BlockPos.ZERO;
         this.chunkPosition = ChunkPos.ZERO;
+        // Paper start - EAR 2
+        if (level != null) {
+            this.defaultActivationState = io.papermc.paper.entity.activation.ActivationRange.initializeEntityActivationState(this, level.spigotConfig);
+        } else {
+            this.defaultActivationState = false;
+        }
+        // Paper end - EAR 2
         SynchedEntityData.Builder builder = new SynchedEntityData.Builder(this);
         builder.define(DATA_SHARED_FLAGS_ID, (byte)0);
         builder.define(DATA_AIR_SUPPLY_ID, this.getMaxAirSupply());
@@ -981,6 +997,8 @@ public abstract class Entity implements SyncedDataHolder, Nameable, EntityAccess
         } else {
             this.wasOnFire = this.isOnFire();
             if (type == MoverType.PISTON) {
+                this.activatedTick = Math.max(this.activatedTick, MinecraftServer.currentTick + 20); // Paper - EAR 2
+                this.activatedImmunityTick = Math.max(this.activatedImmunityTick, MinecraftServer.currentTick + 20);   // Paper - EAR 2
                 movement = this.limitPistonMovement(movement);
                 if (movement.equals(Vec3.ZERO)) {
                     return;
@@ -994,6 +1012,13 @@ public abstract class Entity implements SyncedDataHolder, Nameable, EntityAccess
                 this.stuckSpeedMultiplier = Vec3.ZERO;
                 this.setDeltaMovement(Vec3.ZERO);
             }
+            // Paper start - ignore movement changes while inactive.
+            if (isTemporarilyActive && !(this instanceof ItemEntity) && movement == getDeltaMovement() && type == MoverType.SELF) {
+                setDeltaMovement(Vec3.ZERO);
+                profilerFiller.pop();
+                return;
+            }
+            // Paper end
 
             movement = this.maybeBackOffFromEdge(movement, type);
             Vec3 vec3 = this.collide(movement);
diff --git a/net/minecraft/world/entity/LivingEntity.java b/net/minecraft/world/entity/LivingEntity.java
index a71a153a91de5a564b946091d8d3ccbb330e4b89..195e1151f7b2a32d6c4eb67edd1952e38f58b266 100644
--- a/net/minecraft/world/entity/LivingEntity.java
+++ b/net/minecraft/world/entity/LivingEntity.java
@@ -3094,6 +3094,14 @@ public abstract class LivingEntity extends Entity implements Attackable {
         return false;
     }
 
+    // Paper start - EAR 2
+    @Override
+    public void inactiveTick() {
+        super.inactiveTick();
+        ++this.noActionTime; // Above all the floats
+    }
+    // Paper end - EAR 2
+
     @Override
     public void tick() {
         super.tick();
diff --git a/net/minecraft/world/entity/Mob.java b/net/minecraft/world/entity/Mob.java
index f7d69db61d1293510428ae275e8a50571dde5ddf..1ed07fd23985a6bf8cf8300f74c92b7531a79fc6 100644
--- a/net/minecraft/world/entity/Mob.java
+++ b/net/minecraft/world/entity/Mob.java
@@ -215,6 +215,19 @@ public abstract class Mob extends LivingEntity implements EquipmentUser, Leashab
         return this.lookControl;
     }
 
+    // Paper start
+    @Override
+    public void inactiveTick() {
+        super.inactiveTick();
+        if (this.goalSelector.inactiveTick()) {
+            this.goalSelector.tick();
+        }
+        if (this.targetSelector.inactiveTick()) {
+            this.targetSelector.tick();
+        }
+    }
+    // Paper end
+
     public MoveControl getMoveControl() {
         return this.getControlledVehicle() instanceof Mob mob ? mob.getMoveControl() : this.moveControl;
     }
diff --git a/net/minecraft/world/entity/PathfinderMob.java b/net/minecraft/world/entity/PathfinderMob.java
index 0caf50ec50f056b83a20bbc6a2fe0144593aef39..af59a700755654eb68d6bf57d0712c4a2ac6c09b 100644
--- a/net/minecraft/world/entity/PathfinderMob.java
+++ b/net/minecraft/world/entity/PathfinderMob.java
@@ -17,6 +17,8 @@ public abstract class PathfinderMob extends Mob {
         super(entityType, level);
     }
 
+    public BlockPos movingTarget; public BlockPos getMovingTarget() { return movingTarget; } // Paper
+
     public float getWalkTargetValue(BlockPos pos) {
         return this.getWalkTargetValue(pos, this.level());
     }
diff --git a/net/minecraft/world/entity/ai/goal/GoalSelector.java b/net/minecraft/world/entity/ai/goal/GoalSelector.java
index 9338e63cc28413f5559bb0122ef5e04a84bd51d1..eeba224bd575451ba6023df65ef9d9b97f7f1c71 100644
--- a/net/minecraft/world/entity/ai/goal/GoalSelector.java
+++ b/net/minecraft/world/entity/ai/goal/GoalSelector.java
@@ -25,6 +25,7 @@ public class GoalSelector {
     private final Map<Goal.Flag, WrappedGoal> lockedFlags = new EnumMap<>(Goal.Flag.class);
     private final Set<WrappedGoal> availableGoals = new ObjectLinkedOpenHashSet<>();
     private final EnumSet<Goal.Flag> disabledFlags = EnumSet.noneOf(Goal.Flag.class);
+    private int curRate; // Paper - EAR 2
 
     public void addGoal(int priority, Goal goal) {
         this.availableGoals.add(new WrappedGoal(priority, goal));
@@ -35,6 +36,22 @@ public class GoalSelector {
         this.availableGoals.removeIf(wrappedGoal -> filter.test(wrappedGoal.getGoal()));
     }
 
+    // Paper start - EAR 2
+    public boolean inactiveTick() {
+        this.curRate++;
+        return this.curRate % 3 == 0; // TODO newGoalRate was already unused in 1.20.4, check if this is correct
+    }
+
+    public boolean hasTasks() {
+        for (WrappedGoal task : this.availableGoals) {
+            if (task.isRunning()) {
+                return true;
+            }
+        }
+        return false;
+    }
+    // Paper end - EAR 2
+
     public void removeGoal(Goal goal) {
         for (WrappedGoal wrappedGoal : this.availableGoals) {
             if (wrappedGoal.getGoal() == goal && wrappedGoal.isRunning()) {
diff --git a/net/minecraft/world/entity/ai/goal/MoveToBlockGoal.java b/net/minecraft/world/entity/ai/goal/MoveToBlockGoal.java
index 789fea258d70e60d38271ebb31270562dc7eb3ab..d0ab3db7bbd2942db19f473474371b20ce822608 100644
--- a/net/minecraft/world/entity/ai/goal/MoveToBlockGoal.java
+++ b/net/minecraft/world/entity/ai/goal/MoveToBlockGoal.java
@@ -23,6 +23,14 @@ public abstract class MoveToBlockGoal extends Goal {
     public MoveToBlockGoal(PathfinderMob mob, double speedModifier, int searchRange) {
         this(mob, speedModifier, searchRange, 1);
     }
+    // Paper start - activation range improvements
+    @Override
+    public void stop() {
+        super.stop();
+        this.blockPos = BlockPos.ZERO;
+        this.mob.movingTarget = null;
+    }
+    // Paper end
 
     public MoveToBlockGoal(PathfinderMob mob, double speedModifier, int searchRange, int verticalSearchRange) {
         this.mob = mob;
@@ -113,6 +121,7 @@ public abstract class MoveToBlockGoal extends Goal {
                         mutableBlockPos.setWithOffset(blockPos, i4, i2 - 1, i5);
                         if (this.mob.isWithinRestriction(mutableBlockPos) && this.isValidTarget(this.mob.level(), mutableBlockPos)) {
                             this.blockPos = mutableBlockPos;
+                            this.mob.movingTarget = mutableBlockPos == BlockPos.ZERO ? null : mutableBlockPos.immutable(); // Paper
                             return true;
                         }
                     }
diff --git a/net/minecraft/world/entity/item/ItemEntity.java b/net/minecraft/world/entity/item/ItemEntity.java
index 8b034b6bda937b25dbb3d09b8293fed6d7dc512c..52a7ed0d991758bad0dcedcb7f97fb15ac6c6d04 100644
--- a/net/minecraft/world/entity/item/ItemEntity.java
+++ b/net/minecraft/world/entity/item/ItemEntity.java
@@ -124,6 +124,29 @@ public class ItemEntity extends Entity implements TraceableEntity {
         return 0.04;
     }
 
+    // Paper start - EAR 2
+    @Override
+    public void inactiveTick() {
+        super.inactiveTick();
+        if (this.pickupDelay > 0 && this.pickupDelay != 32767) {
+            this.pickupDelay--;
+        }
+        if (this.age != -32768) {
+            this.age++;
+        }
+
+        if (!this.level().isClientSide && this.age >= this.despawnRate) {// Paper - Alternative item-despawn-rate
+            // CraftBukkit start - fire ItemDespawnEvent
+            if (org.bukkit.craftbukkit.event.CraftEventFactory.callItemDespawnEvent(this).isCancelled()) {
+                this.age = 0;
+                return;
+            }
+            // CraftBukkit end
+            this.discard(org.bukkit.event.entity.EntityRemoveEvent.Cause.DESPAWN); // CraftBukkit - add Bukkit remove cause
+        }
+    }
+    // Paper end - EAR 2
+
     @Override
     public void tick() {
         if (this.getItem().isEmpty()) {
diff --git a/net/minecraft/world/entity/npc/Villager.java b/net/minecraft/world/entity/npc/Villager.java
index 27568a1604d2dd5d46e836bbc25431929e218aa1..2b83262e4a13eae86df82913ce4f3121e3631a43 100644
--- a/net/minecraft/world/entity/npc/Villager.java
+++ b/net/minecraft/world/entity/npc/Villager.java
@@ -265,11 +265,35 @@ public class Villager extends AbstractVillager implements ReputationEventHandler
         return this.assignProfessionWhenSpawned;
     }
 
+    // Paper start - EAR 2
+    @Override
+    public void inactiveTick() {
+        // SPIGOT-3874, SPIGOT-3894, SPIGOT-3846, SPIGOT-5286 :(
+        if (this.getUnhappyCounter() > 0) {
+            this.setUnhappyCounter(this.getUnhappyCounter() - 1);
+        }
+        if (this.isEffectiveAi()) {
+            if (this.level().spigotConfig.tickInactiveVillagers) {
+                this.customServerAiStep(this.level().getMinecraftWorld());
+            } else {
+                this.customServerAiStep(this.level().getMinecraftWorld(), true);
+            }
+        }
+        maybeDecayGossip();
+        super.inactiveTick();
+    }
+    // Paper end - EAR 2
+
     @Override
     protected void customServerAiStep(ServerLevel level) {
+        // Paper start - EAR 2
+        this.customServerAiStep(level, false);
+    }
+    protected void customServerAiStep(ServerLevel level, final boolean inactive) {
+        // Paper end - EAR 2
         ProfilerFiller profilerFiller = Profiler.get();
         profilerFiller.push("villagerBrain");
-        this.getBrain().tick(level, this);
+        if (!inactive) this.getBrain().tick(level, this); // Paper - EAR 2
         profilerFiller.pop();
         if (this.assignProfessionWhenSpawned) {
             this.assignProfessionWhenSpawned = false;
@@ -293,7 +317,7 @@ public class Villager extends AbstractVillager implements ReputationEventHandler
             this.lastTradedPlayer = null;
         }
 
-        if (!this.isNoAi() && this.random.nextInt(100) == 0) {
+        if (!inactive && !this.isNoAi() && this.random.nextInt(100) == 0) { // Paper - EAR 2
             Raid raidAt = level.getRaidAt(this.blockPosition());
             if (raidAt != null && raidAt.isActive() && !raidAt.isOver()) {
                 level.broadcastEntityEvent(this, (byte)42);
@@ -303,6 +327,7 @@ public class Villager extends AbstractVillager implements ReputationEventHandler
         if (this.getVillagerData().getProfession() == VillagerProfession.NONE && this.isTrading()) {
             this.stopTrading();
         }
+        if (inactive) return; // Paper - EAR 2
 
         super.customServerAiStep(level);
     }
diff --git a/net/minecraft/world/entity/projectile/Arrow.java b/net/minecraft/world/entity/projectile/Arrow.java
index c1e09e701757a300183b62d343ded03033e63aa7..56574f8ef879159edc0114da09300143a2c79a35 100644
--- a/net/minecraft/world/entity/projectile/Arrow.java
+++ b/net/minecraft/world/entity/projectile/Arrow.java
@@ -66,6 +66,16 @@ public class Arrow extends AbstractArrow {
         builder.define(ID_EFFECT_COLOR, -1);
     }
 
+    // Paper start - EAR 2
+    @Override
+    public void inactiveTick() {
+        if (this.isInGround()) {
+            this.life++;
+        }
+        super.inactiveTick();
+    }
+    // Paper end
+
     @Override
     public void tick() {
         super.tick();
diff --git a/net/minecraft/world/entity/projectile/FireworkRocketEntity.java b/net/minecraft/world/entity/projectile/FireworkRocketEntity.java
index 7c0862c50b44555fb27ce7dc46f4ec95a3eb0022..774ca9e0b56fd175ae246051de762d0c4256ca58 100644
--- a/net/minecraft/world/entity/projectile/FireworkRocketEntity.java
+++ b/net/minecraft/world/entity/projectile/FireworkRocketEntity.java
@@ -102,6 +102,21 @@ public class FireworkRocketEntity extends Projectile implements ItemSupplier {
         return super.shouldRender(x, y, z) && !this.isAttachedToEntity();
     }
 
+    // Paper start - EAR 2
+    @Override
+    public void inactiveTick() {
+        this.life++;
+        if (this.life > this.lifetime && this.level() instanceof ServerLevel serverLevel) {
+            // CraftBukkit start
+            if (!org.bukkit.craftbukkit.event.CraftEventFactory.callFireworkExplodeEvent(this).isCancelled()) {
+                this.explode(serverLevel);
+            }
+            // CraftBukkit end
+        }
+        super.inactiveTick();
+    }
+    // Paper end - EAR 2
+
     @Override
     public void tick() {
         super.tick();
diff --git a/net/minecraft/world/entity/vehicle/MinecartHopper.java b/net/minecraft/world/entity/vehicle/MinecartHopper.java
index c553cf0592dfa606dbbb1e6854d3377b9feb5efb..8341e7f01606fca90e69384c16fc19bb9e20d1b7 100644
--- a/net/minecraft/world/entity/vehicle/MinecartHopper.java
+++ b/net/minecraft/world/entity/vehicle/MinecartHopper.java
@@ -47,6 +47,7 @@ public class MinecartHopper extends AbstractMinecartContainer implements Hopper
         if (flag != this.isEnabled()) {
             this.setEnabled(flag);
         }
+        this.immunize(); // Paper
     }
 
     public boolean isEnabled() {
@@ -100,11 +101,13 @@ public class MinecartHopper extends AbstractMinecartContainer implements Hopper
 
     public boolean suckInItems() {
         if (HopperBlockEntity.suckInItems(this.level(), this)) {
+            this.immunize(); // Paper
             return true;
         } else {
             for (ItemEntity itemEntity : this.level()
                 .getEntitiesOfClass(ItemEntity.class, this.getBoundingBox().inflate(0.25, 0.0, 0.25), EntitySelector.ENTITY_STILL_ALIVE)) {
                 if (HopperBlockEntity.addItem(this, itemEntity)) {
+                    this.immunize(); // Paper
                     return true;
                 }
             }
@@ -139,4 +142,11 @@ public class MinecartHopper extends AbstractMinecartContainer implements Hopper
     public AbstractContainerMenu createMenu(int id, Inventory playerInventory) {
         return new HopperMenu(id, playerInventory, this);
     }
+
+    // Paper start
+    public void immunize() {
+        this.activatedImmunityTick = Math.max(this.activatedImmunityTick, net.minecraft.server.MinecraftServer.currentTick + 20);
+    }
+    // Paper end
+
 }
diff --git a/net/minecraft/world/level/Level.java b/net/minecraft/world/level/Level.java
index 32f184288f6065259c921293922c1b0163df4dc4..0f346faa82b988e86834c38837f6f11bea7f31c6 100644
--- a/net/minecraft/world/level/Level.java
+++ b/net/minecraft/world/level/Level.java
@@ -153,6 +153,12 @@ public abstract class Level implements LevelAccessor, AutoCloseable {
     public Map<BlockPos, BlockEntity> capturedTileEntities = new java.util.LinkedHashMap<>(); // Paper - Retain block place order when capturing blockstates
     public List<net.minecraft.world.entity.item.ItemEntity> captureDrops;
     public final it.unimi.dsi.fastutil.objects.Object2LongOpenHashMap<SpawnCategory> ticksPerSpawnCategory = new it.unimi.dsi.fastutil.objects.Object2LongOpenHashMap<>();
+    // Paper start
+    public int wakeupInactiveRemainingAnimals;
+    public int wakeupInactiveRemainingFlying;
+    public int wakeupInactiveRemainingMonsters;
+    public int wakeupInactiveRemainingVillagers;
+    // Paper end
     public boolean populating;
     public final org.spigotmc.SpigotWorldConfig spigotConfig; // Spigot
     // Paper start - add paper world config
diff --git a/net/minecraft/world/level/block/piston/PistonMovingBlockEntity.java b/net/minecraft/world/level/block/piston/PistonMovingBlockEntity.java
index 754cfdcd5a28287aa3545aaffdce1e391cbefc1e..1e6e940fca9d96ef410c7bf05524bd9b24db4a79 100644
--- a/net/minecraft/world/level/block/piston/PistonMovingBlockEntity.java
+++ b/net/minecraft/world/level/block/piston/PistonMovingBlockEntity.java
@@ -149,6 +149,10 @@ public class PistonMovingBlockEntity extends BlockEntity {
                                 }
 
                                 entity.setDeltaMovement(d1, d2, d3);
+                                // Paper - EAR items stuck in slime pushed by a piston
+                                entity.activatedTick = Math.max(entity.activatedTick, net.minecraft.server.MinecraftServer.currentTick + 10);
+                                entity.activatedImmunityTick = Math.max(entity.activatedImmunityTick, net.minecraft.server.MinecraftServer.currentTick + 10);
+                                // Paper end
                                 break;
                             }
                         }