| 1 | package net.minecraft.world.level;
|
| 2 |
|
| 3 | import com.google.common.collect.Maps;
|
| 4 | import it.unimi.dsi.fastutil.longs.Long2ObjectMap;
|
| 5 | import it.unimi.dsi.fastutil.longs.Long2ObjectOpenHashMap;
|
| 6 | import it.unimi.dsi.fastutil.objects.Object2IntMap;
|
| 7 | import it.unimi.dsi.fastutil.objects.Object2IntOpenHashMap;
|
| 8 | import java.util.List;
|
| 9 | import java.util.Map;
|
| 10 | import net.minecraft.server.level.ChunkMap;
|
| 11 | import net.minecraft.server.level.ServerPlayer;
|
| 12 | import net.minecraft.world.entity.MobCategory;
|
| 13 |
|
| 14 | public class LocalMobCapCalculator {
|
| 15 | private final Long2ObjectMap<List<ServerPlayer>> playersNearChunk = new Long2ObjectOpenHashMap<>();
|
| 16 | private final Map<ServerPlayer, LocalMobCapCalculator.MobCounts> playerMobCounts = Maps.newHashMap();
|
| 17 | private final ChunkMap chunkMap;
|
| 18 |
|
| 19 | public LocalMobCapCalculator(final ChunkMap chunkMap) {
|
| 20 | this.chunkMap = chunkMap;
|
| 21 | }
|
| 22 |
|
| 23 | private List<ServerPlayer> getPlayersNear(final ChunkPos pos) {
|
| 24 | return this.playersNearChunk.computeIfAbsent(pos.pack(), key -> this.chunkMap.getPlayersCloseForSpawning(pos));
|
| 25 | }
|
| 26 |
|
| 27 | public void addMob(final ChunkPos pos, final MobCategory category) {
|
| 28 | for (ServerPlayer player : this.getPlayersNear(pos)) {
|
| 29 | this.playerMobCounts.computeIfAbsent(player, key -> new LocalMobCapCalculator.MobCounts()).add(category);
|
| 30 | }
|
| 31 | }
|
| 32 |
|
| 33 | public boolean canSpawn(final MobCategory mobCategory, final ChunkPos pos) {
|
| 34 | for (ServerPlayer serverPlayer : this.getPlayersNear(pos)) {
|
| 35 | LocalMobCapCalculator.MobCounts mobCounts = this.playerMobCounts.get(serverPlayer);
|
| 36 | if (mobCounts == null || mobCounts.canSpawn(mobCategory)) {
|
| 37 | return true;
|
| 38 | }
|
| 39 | }
|
| 40 |
|
| 41 | return false;
|
| 42 | }
|
| 43 |
|
| 44 | private static class MobCounts {
|
| 45 | private final Object2IntMap<MobCategory> counts = new Object2IntOpenHashMap<>(MobCategory.values().length);
|
| 46 |
|
| 47 | public void add(final MobCategory category) {
|
| 48 | this.counts.computeInt(category, (k, count) -> count == null ? 1 : count + 1);
|
| 49 | }
|
| 50 |
|
| 51 | public boolean canSpawn(final MobCategory category) {
|
| 52 | return this.counts.getOrDefault(category, 0) < category.getMaxInstancesPerChunk();
|
| 53 | }
|
| 54 | }
|
| 55 | }
|
| 56 |
|