Partially rewrite kaiiju entity throttler

This commit is contained in:
2026-07-17 21:04:02 +08:00
parent fb6a193259
commit 0cf1ddec5c
4 changed files with 52 additions and 75 deletions
+1 -2
View File
@@ -64,7 +64,7 @@
} }
} }
val log4jPlugins = sourceSets.create("log4jPlugins") { val log4jPlugins = sourceSets.create("log4jPlugins") {
@@ -134,7 +_,15 @@ @@ -134,7 +_,14 @@
} }
dependencies { dependencies {
@@ -76,7 +76,6 @@
+ implementation("com.github.luben:zstd-jni:1.5.4-1") + implementation("com.github.luben:zstd-jni:1.5.4-1")
+ implementation("net.openhft:zero-allocation-hashing:0.16") + implementation("net.openhft:zero-allocation-hashing:0.16")
+ implementation("net.objecthunter:exp4j:0.4.8") + implementation("net.objecthunter:exp4j:0.4.8")
+ implementation("io.github.classgraph:classgraph:4.8.158")
+ // Shiroha end + // Shiroha end
implementation("ca.spottedleaf:leafpile:1.0.0") implementation("ca.spottedleaf:leafpile:1.0.0")
implementation("org.jline:jline-terminal-ffm:3.27.1") // use ffm on java 22+ implementation("org.jline:jline-terminal-ffm:3.27.1") // use ffm on java 22+
@@ -53,3 +53,15 @@ index ed4024b744f7913cfd423617936f9affe7c2c46e..d348fa43e6703dbe461eabbab29699ed
} finally { foliaProfiler.stopTimer(ca.spottedleaf.leafprofiler.LProfilerRegistry.ENTITY_TICK); } // Folia - profiler } finally { foliaProfiler.stopTimer(ca.spottedleaf.leafprofiler.LProfilerRegistry.ENTITY_TICK); } // Folia - profiler
if (this.paperConfig().unsupportedSettings.ticking.blockEntities) { // Paper - option to disable ticking if (this.paperConfig().unsupportedSettings.ticking.blockEntities) { // Paper - option to disable ticking
profiler.popPush("blockEntities"); profiler.popPush("blockEntities");
diff --git a/net/minecraft/world/entity/EntityType.java b/net/minecraft/world/entity/EntityType.java
index 6efaa78faca15c7a48bdffb24480d1bac29f3ba8..31619890f1bd4f458b6f9a31fac8cefaafe09e8e 100644
--- a/net/minecraft/world/entity/EntityType.java
+++ b/net/minecraft/world/entity/EntityType.java
@@ -73,6 +73,7 @@ public class EntityType<T extends Entity> implements EntityTypeTest<Entity, T>,
private final float spawnDimensionsScale;
private final FeatureFlagSet requiredFeatures;
private final boolean allowedInPeaceful;
+ public volatile dev.kaiijumc.kaiiju.KaiijuEntityLimits.EntityLimit entityLimit;
public static Identifier getKey(final EntityType<?> type) {
return BuiltInRegistries.ENTITY_TYPE.getKey(type);
@@ -19,20 +19,19 @@ package dev.kaiijumc.kaiiju;
import com.google.common.base.Throwables; import com.google.common.base.Throwables;
import com.mojang.logging.LogUtils; import com.mojang.logging.LogUtils;
import io.github.classgraph.ClassGraph; import net.minecraft.core.Holder;
import io.github.classgraph.ClassInfo; import net.minecraft.core.registries.BuiltInRegistries;
import io.github.classgraph.ScanResult; import net.minecraft.resources.Identifier;
import it.unimi.dsi.fastutil.objects.Object2ObjectOpenHashMap; import net.minecraft.world.entity.EntityType;
import net.minecraft.world.entity.Entity;
import org.bukkit.Bukkit; import org.bukkit.Bukkit;
import org.bukkit.configuration.InvalidConfigurationException; import org.bukkit.configuration.InvalidConfigurationException;
import org.bukkit.configuration.file.YamlConfiguration; import org.bukkit.configuration.file.YamlConfiguration;
import org.jspecify.annotations.NonNull;
import org.slf4j.Logger; import org.slf4j.Logger;
import java.io.File; import java.io.File;
import java.io.IOException; import java.io.IOException;
import java.util.HashMap; import java.util.Optional;
import java.util.Map;
import java.util.logging.Level; import java.util.logging.Level;
@SuppressWarnings("unused") @SuppressWarnings("unused")
@@ -44,26 +43,11 @@ public class KaiijuEntityLimits {
"Per region entity limits for Kaiiju.\n" "Per region entity limits for Kaiiju.\n"
+ "If there are more of particular entity type in a region than limit, entity ticking will be throttled.\n" + "If there are more of particular entity type in a region than limit, entity ticking will be throttled.\n"
+ "Example: for Wither limit 100 & 300 Withers in a region -> 100 Withers tick every tick & every Wither ticks every 3 ticks.\n" + "Example: for Wither limit 100 & 300 Withers in a region -> 100 Withers tick every tick & every Wither ticks every 3 ticks.\n"
+ "Available entities: GlowSquid, Ambient, Bat, Animal, Bee, Cat, Chicken, Cod, Cow, Dolphin, Fish, FishSchool, Fox, Golem, IronGolem, " + "Entity names are named under the registry of minecraft's entity type";
+ "MushroomCow, Ocelot, Panda, Parrot, Perchable, Pig, PolarBear, PufferFish, Rabbit, Salmon, Sheep, Snowman, Squid, TropicalFish, Turtle, "
+ "WaterAnimal, Wolf, Allay, Axolotl, Camel, Frog, Tadpole, Goat, Horse, HorseAbstract, HorseChestedAbstract, HorseDonkey, HorseMule, "
+ "HorseSkeleton, HorseZombie, Llama, LlamaTrader, Sniffer, EnderCrystal, EnderDragon, Wither, ArmorStand, Hanging, ItemFrame, Leash, "
+ "Painting, GlowItemFrame, FallingBlock, Item, TNTPrimed, Blaze, CaveSpider, Creeper, Drowned, Enderman, Endermite, Evoker, Ghast, "
+ "GiantZombie, Guardian, GuardianElder, IllagerAbstract, IllagerIllusioner, IllagerWizard, MagmaCube, Monster, MonsterPatrolling, Phantom, "
+ "ZombifiedPiglin, Pillager, Ravager, Shulker, Silverfish, Skeleton, SkeletonAbstract, SkeletonStray, SkeletonWither, Slime, Spider, Strider, Vex, "
+ "Vindicator, Witch, Zoglin, Zombie, ZombieHusk, ZombieVillager, Hoglin, Piglin, PiglinAbstract, PiglinBrute, Warden, Villager, "
+ "VillagerTrader, Arrow, DragonFireball, Egg, EnderPearl, EnderSignal, EvokerFangs, Fireball, FireballFireball, Fireworks, FishingHook, "
+ "LargeFireball, LlamaSpit, Potion, Projectile, ProjectileThrowable, ShulkerBullet, SmallFireball, Snowball, SpectralArrow, ThrownExpBottle, "
+ "ThrownTrident, TippedArrow, WitherSkull, Raider, ChestBoat, Boat, MinecartAbstract, MinecartChest, MinecartCommandBlock, MinecartContainer, "
+ "MinecartFurnace, MinecartHopper, MinecartMobSpawner, MinecartRideable, MinecartTNT\n";
protected static final File ENTITY_LIMITS_FILE = new File(CONFIG_FOLDER, "kaiiju_entity_limits.yml"); protected static final File ENTITY_LIMITS_FILE = new File(CONFIG_FOLDER, "kaiiju_entity_limits.yml");
public static YamlConfiguration entityLimitsConfig; public static YamlConfiguration entityLimitsConfig;
public static boolean enabled = false; public static boolean enabled = false;
protected static Map<Class<? extends Entity>, EntityLimit> entityLimits;
static final String ENTITY_PREFIX = "Entity";
public static void init() { public static void init() {
init(true); init(true);
} }
@@ -84,8 +68,9 @@ public class KaiijuEntityLimits {
entityLimitsConfig.options().header(HEADER); entityLimitsConfig.options().header(HEADER);
entityLimitsConfig.options().copyDefaults(true); entityLimitsConfig.options().copyDefaults(true);
entityLimitsConfig.set("enabled", enabled); entityLimitsConfig.set("enabled", enabled);
entityLimitsConfig.set("Axolotl.limit", 1000); entityLimitsConfig.set("axolotl.limit", 1000);
entityLimitsConfig.set("Axolotl.removal", 2000); entityLimitsConfig.set("axolotl.removal", 2000);
try { try {
entityLimitsConfig.save(ENTITY_LIMITS_FILE); entityLimitsConfig.save(ENTITY_LIMITS_FILE);
} catch (IOException ex) { } catch (IOException ex) {
@@ -96,62 +81,42 @@ public class KaiijuEntityLimits {
enabled = entityLimitsConfig.getBoolean("enabled"); enabled = entityLimitsConfig.getBoolean("enabled");
entityLimits = new Object2ObjectOpenHashMap<>(); if (!enabled) {
try (ScanResult scanResult = new ClassGraph().enableAllInfo().acceptPackages("net.minecraft.world.entity").scan()) { return;
Map<String, ClassInfo> entityClasses = new HashMap<>();
for (ClassInfo classInfo : scanResult.getAllClasses()) {
Class<?> entityClass = Class.forName(classInfo.getName());
if (Entity.class.isAssignableFrom(entityClass)) {
String entityName = extractEntityName(entityClass.getSimpleName());
entityClasses.put(entityName, classInfo);
}
}
for (String key : entityLimitsConfig.getKeys(false)) {
if (key.equals("enabled")) {
continue;
}
if (!entityClasses.containsKey(key)) {
LOGGER.error("Unknown entity '" + key + "' in kaiiju-entity-limits.yml, skipping");
continue;
}
int limit = entityLimitsConfig.getInt(key + ".limit");
int removal = entityLimitsConfig.getInt(key + ".removal");
if (limit < 1) {
LOGGER.error(key + " has a limit less than the minimum of 1, ignoring");
continue;
}
if (removal <= limit && removal != -1) {
LOGGER.error(key + " has a removal limit that is less than or equal to its limit, setting removal to limit * 10");
removal = limit * 10;
}
entityLimits.put((Class<? extends Entity>) Class.forName(entityClasses.get(key).getName()), new EntityLimit(limit, removal));
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
} }
}
public static EntityLimit getEntityLimit(Entity entity) { for (String key : entityLimitsConfig.getKeys(false)) {
return entityLimits.get(entity.getClass()); if (key.equals("enabled")) {
} continue;
}
private static String extractEntityName(String input) { final Optional<Holder.Reference<EntityType<?>>> lookup = BuiltInRegistries.ENTITY_TYPE.get(Identifier.fromNamespaceAndPath(Identifier.DEFAULT_NAMESPACE, key));
int prefixLength = ENTITY_PREFIX.length(); if (lookup.isEmpty()) {
LOGGER.error("Unknown entity '{}' in kaiiju-entity-limits.yml, skipping", key);
continue;
}
if (input.length() <= prefixLength || !input.startsWith(ENTITY_PREFIX)) { final EntityType<?> value = lookup.get().value();
return input;
} else { int limit = entityLimitsConfig.getInt(key + ".limit");
return input.substring(prefixLength); int removal = entityLimitsConfig.getInt(key + ".removal");
if (limit < 1) {
LOGGER.error("{} has a limit less than the minimum of 1, ignoring", key);
continue;
}
if (removal <= limit && removal != -1) {
LOGGER.error("{} has a removal limit that is less than or equal to its limit, setting removal to limit * 10", key);
removal = limit * 10;
}
value.entityLimit = new EntityLimit(limit, removal);
} }
} }
public record EntityLimit(int limit, int removal) { public record EntityLimit(int limit, int removal) {
@Override @Override
public String toString() { public @NonNull String toString() {
return "EntityLimit{limit=" + limit + ", removal=" + removal + "}"; return "EntityLimit{limit=" + limit + ", removal=" + removal + "}";
} }
} }
@@ -45,7 +45,8 @@ public class KaiijuEntityThrottler {
public EntityThrottlerReturn tickLimiterShouldSkip(Entity entity) { public EntityThrottlerReturn tickLimiterShouldSkip(Entity entity) {
EntityThrottlerReturn retVal = new EntityThrottlerReturn(); EntityThrottlerReturn retVal = new EntityThrottlerReturn();
if (entity.isRemoved()) return retVal; if (entity.isRemoved()) return retVal;
KaiijuEntityLimits.EntityLimit entityLimit = KaiijuEntityLimits.getEntityLimit(entity);
KaiijuEntityLimits.EntityLimit entityLimit = entity.getType().entityLimit;
if (entityLimit != null) { if (entityLimit != null) {
TickInfo tickInfo = entityLimitTickInfoMap.computeIfAbsent(entityLimit, el -> { TickInfo tickInfo = entityLimitTickInfoMap.computeIfAbsent(entityLimit, el -> {