| 1 | package net.minecraft.server.level;
|
| 2 |
|
| 3 | import com.google.common.collect.ImmutableList;
|
| 4 | import com.google.common.collect.Lists;
|
| 5 | import com.google.common.collect.Queues;
|
| 6 | import com.google.common.collect.Sets;
|
| 7 | import com.google.common.collect.ImmutableList.Builder;
|
| 8 | import com.mojang.datafixers.DataFixer;
|
| 9 | import com.mojang.logging.LogUtils;
|
| 10 | import it.unimi.dsi.fastutil.ints.Int2ObjectMap;
|
| 11 | import it.unimi.dsi.fastutil.ints.Int2ObjectOpenHashMap;
|
| 12 | import it.unimi.dsi.fastutil.longs.Long2ByteMap;
|
| 13 | import it.unimi.dsi.fastutil.longs.Long2ByteOpenHashMap;
|
| 14 | import it.unimi.dsi.fastutil.longs.Long2LongMap;
|
| 15 | import it.unimi.dsi.fastutil.longs.Long2LongOpenHashMap;
|
| 16 | import it.unimi.dsi.fastutil.longs.Long2ObjectLinkedOpenHashMap;
|
| 17 | import it.unimi.dsi.fastutil.longs.LongIterator;
|
| 18 | import it.unimi.dsi.fastutil.longs.LongLinkedOpenHashSet;
|
| 19 | import it.unimi.dsi.fastutil.longs.LongOpenHashSet;
|
| 20 | import it.unimi.dsi.fastutil.longs.LongSet;
|
| 21 | import it.unimi.dsi.fastutil.longs.Long2ObjectMap.Entry;
|
| 22 | import java.io.IOException;
|
| 23 | import java.io.Writer;
|
| 24 | import java.nio.file.Path;
|
| 25 | import java.util.ArrayList;
|
| 26 | import java.util.HashMap;
|
| 27 | import java.util.List;
|
| 28 | import java.util.Locale;
|
| 29 | import java.util.Map;
|
| 30 | import java.util.Objects;
|
| 31 | import java.util.Optional;
|
| 32 | import java.util.Queue;
|
| 33 | import java.util.Set;
|
| 34 | import java.util.concurrent.CancellationException;
|
| 35 | import java.util.concurrent.CompletableFuture;
|
| 36 | import java.util.concurrent.CompletionException;
|
| 37 | import java.util.concurrent.CompletionStage;
|
| 38 | import java.util.concurrent.Executor;
|
| 39 | import java.util.concurrent.atomic.AtomicInteger;
|
| 40 | import java.util.function.BooleanSupplier;
|
| 41 | import java.util.function.Consumer;
|
| 42 | import java.util.function.IntConsumer;
|
| 43 | import java.util.function.IntFunction;
|
| 44 | import java.util.function.IntSupplier;
|
| 45 | import java.util.function.Predicate;
|
| 46 | import java.util.stream.Stream;
|
| 47 | import net.minecraft.CrashReport;
|
| 48 | import net.minecraft.CrashReportCategory;
|
| 49 | import net.minecraft.ReportedException;
|
| 50 | import net.minecraft.SharedConstants;
|
| 51 | import net.minecraft.core.BlockPos;
|
| 52 | import net.minecraft.core.RegistryAccess;
|
| 53 | import net.minecraft.core.SectionPos;
|
| 54 | import net.minecraft.core.registries.Registries;
|
| 55 | import net.minecraft.nbt.CompoundTag;
|
| 56 | import net.minecraft.nbt.NbtException;
|
| 57 | import net.minecraft.network.protocol.Packet;
|
| 58 | import net.minecraft.network.protocol.game.ClientGamePacketListener;
|
| 59 | import net.minecraft.network.protocol.game.ClientboundChunksBiomesPacket;
|
| 60 | import net.minecraft.network.protocol.game.ClientboundSetChunkCacheCenterPacket;
|
| 61 | import net.minecraft.resources.Identifier;
|
| 62 | import net.minecraft.resources.ResourceKey;
|
| 63 | import net.minecraft.server.network.ServerPlayerConnection;
|
| 64 | import net.minecraft.util.CsvOutput;
|
| 65 | import net.minecraft.util.Mth;
|
| 66 | import net.minecraft.util.StaticCache2D;
|
| 67 | import net.minecraft.util.TriState;
|
| 68 | import net.minecraft.util.Util;
|
| 69 | import net.minecraft.util.datafix.DataFixTypes;
|
| 70 | import net.minecraft.util.profiling.Profiler;
|
| 71 | import net.minecraft.util.profiling.ProfilerFiller;
|
| 72 | import net.minecraft.util.thread.BlockableEventLoop;
|
| 73 | import net.minecraft.util.thread.ConsecutiveExecutor;
|
| 74 | import net.minecraft.world.entity.Entity;
|
| 75 | import net.minecraft.world.entity.EntityType;
|
| 76 | import net.minecraft.world.entity.UpdateInterval;
|
| 77 | import net.minecraft.world.entity.ai.village.poi.PoiManager;
|
| 78 | import net.minecraft.world.entity.boss.enderdragon.EnderDragonPart;
|
| 79 | import net.minecraft.world.level.ChunkPos;
|
| 80 | import net.minecraft.world.level.Level;
|
| 81 | import net.minecraft.world.level.TicketStorage;
|
| 82 | import net.minecraft.world.level.block.Blocks;
|
| 83 | import net.minecraft.world.level.chunk.ChunkAccess;
|
| 84 | import net.minecraft.world.level.chunk.ChunkGenerator;
|
| 85 | import net.minecraft.world.level.chunk.ChunkGeneratorStructureState;
|
| 86 | import net.minecraft.world.level.chunk.ImposterProtoChunk;
|
| 87 | import net.minecraft.world.level.chunk.LevelChunk;
|
| 88 | import net.minecraft.world.level.chunk.LightChunkGetter;
|
| 89 | import net.minecraft.world.level.chunk.ProtoChunk;
|
| 90 | import net.minecraft.world.level.chunk.UpgradeData;
|
| 91 | import net.minecraft.world.level.chunk.status.ChunkStatus;
|
| 92 | import net.minecraft.world.level.chunk.status.ChunkStep;
|
| 93 | import net.minecraft.world.level.chunk.status.ChunkType;
|
| 94 | import net.minecraft.world.level.chunk.status.WorldGenContext;
|
| 95 | import net.minecraft.world.level.chunk.storage.RegionStorageInfo;
|
| 96 | import net.minecraft.world.level.chunk.storage.SerializableChunkData;
|
| 97 | import net.minecraft.world.level.chunk.storage.SimpleRegionStorage;
|
| 98 | import net.minecraft.world.level.entity.ChunkStatusUpdateListener;
|
| 99 | import net.minecraft.world.level.gamerules.GameRules;
|
| 100 | import net.minecraft.world.level.levelgen.NoiseBasedChunkGenerator;
|
| 101 | import net.minecraft.world.level.levelgen.NoiseRouterData;
|
| 102 | import net.minecraft.world.level.levelgen.RandomState;
|
| 103 | import net.minecraft.world.level.levelgen.structure.StructureStart;
|
| 104 | import net.minecraft.world.level.levelgen.structure.templatesystem.StructureTemplateManager;
|
| 105 | import net.minecraft.world.level.storage.LevelStorageSource;
|
| 106 | import net.minecraft.world.phys.Vec3;
|
| 107 | import org.apache.commons.lang3.mutable.MutableBoolean;
|
| 108 | import org.jspecify.annotations.Nullable;
|
| 109 | import org.slf4j.Logger;
|
| 110 |
|
| 111 | public class ChunkMap extends SimpleRegionStorage implements ChunkHolder.PlayerProvider, GeneratingChunkMap {
|
| 112 | private static final ChunkResult<List<ChunkAccess>> UNLOADED_CHUNK_LIST_RESULT = ChunkResult.error("Unloaded chunks found in range");
|
| 113 | private static final CompletableFuture<ChunkResult<List<ChunkAccess>>> UNLOADED_CHUNK_LIST_FUTURE = CompletableFuture.completedFuture(
|
| 114 | UNLOADED_CHUNK_LIST_RESULT
|
| 115 | );
|
| 116 | private static final byte CHUNK_TYPE_REPLACEABLE = -1;
|
| 117 | private static final byte CHUNK_TYPE_UNKNOWN = 0;
|
| 118 | private static final byte CHUNK_TYPE_FULL = 1;
|
| 119 | private static final Logger LOGGER = LogUtils.getLogger();
|
| 120 | private static final int CHUNK_SAVED_PER_TICK = 200;
|
| 121 | private static final int CHUNK_SAVED_EAGERLY_PER_TICK = 20;
|
| 122 | private static final int EAGER_CHUNK_SAVE_COOLDOWN_IN_MILLIS = 10000;
|
| 123 | private static final int MAX_ACTIVE_CHUNK_WRITES = 128;
|
| 124 | public static final int MIN_VIEW_DISTANCE = 2;
|
| 125 | public static final int MAX_VIEW_DISTANCE = 32;
|
| 126 | public static final int FORCED_TICKET_LEVEL = ChunkLevel.byStatus(FullChunkStatus.ENTITY_TICKING);
|
| 127 | private final Long2ObjectLinkedOpenHashMap<ChunkHolder> updatingChunkMap = new Long2ObjectLinkedOpenHashMap<>();
|
| 128 | private volatile Long2ObjectLinkedOpenHashMap<ChunkHolder> visibleChunkMap = this.updatingChunkMap.clone();
|
| 129 | private final Long2ObjectLinkedOpenHashMap<ChunkHolder> pendingUnloads = new Long2ObjectLinkedOpenHashMap<>();
|
| 130 | private final List<ChunkGenerationTask> pendingGenerationTasks = new ArrayList<>();
|
| 131 | private final ServerLevel level;
|
| 132 | private final ThreadedLevelLightEngine lightEngine;
|
| 133 | private final BlockableEventLoop<Runnable> mainThreadExecutor;
|
| 134 | private final RandomState randomState;
|
| 135 | private final ChunkGeneratorStructureState chunkGeneratorState;
|
| 136 | private final TicketStorage ticketStorage;
|
| 137 | private final PoiManager poiManager;
|
| 138 | private final LongSet toDrop = new LongOpenHashSet();
|
| 139 | private boolean modified;
|
| 140 | private final ChunkTaskDispatcher worldgenTaskDispatcher;
|
| 141 | private final ChunkTaskDispatcher lightTaskDispatcher;
|
| 142 | private final ChunkStatusUpdateListener chunkStatusListener;
|
| 143 | private final ChunkMap.DistanceManager distanceManager;
|
| 144 | private final PlayerMap playerMap = new PlayerMap();
|
| 145 | private final Int2ObjectMap<ChunkMap.TrackedEntity> entityMap = new Int2ObjectOpenHashMap<>();
|
| 146 | private final Long2ByteMap chunkTypeCache = new Long2ByteOpenHashMap();
|
| 147 | private final Long2LongMap nextChunkSaveTime = new Long2LongOpenHashMap();
|
| 148 | private final LongSet chunksToEagerlySave = new LongLinkedOpenHashSet();
|
| 149 | private final Queue<Runnable> unloadQueue = Queues.newConcurrentLinkedQueue();
|
| 150 | private final AtomicInteger activeChunkWrites = new AtomicInteger();
|
| 151 | private int serverViewDistance;
|
| 152 | private final WorldGenContext worldGenContext;
|
| 153 |
|
| 154 | public ChunkMap(
|
| 155 | final ServerLevel level,
|
| 156 | final LevelStorageSource.LevelStorageAccess levelStorage,
|
| 157 | final DataFixer dataFixer,
|
| 158 | final StructureTemplateManager structureManager,
|
| 159 | final Executor executor,
|
| 160 | final BlockableEventLoop<Runnable> mainThreadExecutor,
|
| 161 | final LightChunkGetter chunkGetter,
|
| 162 | final ChunkGenerator generator,
|
| 163 | final ChunkStatusUpdateListener chunkStatusListener,
|
| 164 | final TicketStorage ticketStorage,
|
| 165 | final int serverViewDistance,
|
| 166 | final boolean syncWrites
|
| 167 | ) {
|
| 168 | super(
|
| 169 | new RegionStorageInfo(levelStorage.getLevelId(), level.dimension(), "chunk"),
|
| 170 | levelStorage.getDimensionPath(level.dimension()).resolve("region"),
|
| 171 | dataFixer,
|
| 172 | syncWrites,
|
| 173 | DataFixTypes.CHUNK
|
| 174 | );
|
| 175 | Path storageFolder = levelStorage.getDimensionPath(level.dimension());
|
| 176 | this.level = level;
|
| 177 | RegistryAccess registryAccess = level.registryAccess();
|
| 178 | long levelSeed = level.getSeed();
|
| 179 | if (generator instanceof NoiseBasedChunkGenerator noiseGenerator) {
|
| 180 | this.randomState = RandomState.create(registryAccess.lookupOrThrow(Registries.NOISE), levelSeed, noiseGenerator.generatorSettings().value());
|
| 181 | } else {
|
| 182 | this.randomState = RandomState.create(
|
| 183 | registryAccess.lookupOrThrow(Registries.NOISE), levelSeed, false, Blocks.STONE.defaultBlockState(), 63, NoiseRouterData.none()
|
| 184 | );
|
| 185 | }
|
| 186 |
|
| 187 | this.chunkGeneratorState = generator.createState(registryAccess.lookupOrThrow(Registries.STRUCTURE_SET), this.randomState, levelSeed);
|
| 188 | this.mainThreadExecutor = mainThreadExecutor;
|
| 189 | ConsecutiveExecutor worldgen = new ConsecutiveExecutor(executor, "worldgen");
|
| 190 | this.chunkStatusListener = chunkStatusListener;
|
| 191 | ConsecutiveExecutor light = new ConsecutiveExecutor(executor, "light");
|
| 192 | this.worldgenTaskDispatcher = new ChunkTaskDispatcher(worldgen, executor);
|
| 193 | this.lightTaskDispatcher = new ChunkTaskDispatcher(light, executor);
|
| 194 | this.lightEngine = new ThreadedLevelLightEngine(chunkGetter, this, this.level.dimensionType().hasSkyLight(), light, this.lightTaskDispatcher);
|
| 195 | this.distanceManager = new ChunkMap.DistanceManager(ticketStorage, executor, mainThreadExecutor);
|
| 196 | this.ticketStorage = ticketStorage;
|
| 197 | this.poiManager = new PoiManager(
|
| 198 | new RegionStorageInfo(levelStorage.getLevelId(), level.dimension(), "poi"),
|
| 199 | storageFolder.resolve("poi"),
|
| 200 | dataFixer,
|
| 201 | syncWrites,
|
| 202 | registryAccess,
|
| 203 | level.getServer(),
|
| 204 | level
|
| 205 | );
|
| 206 | this.setServerViewDistance(serverViewDistance);
|
| 207 | this.worldGenContext = new WorldGenContext(level, generator, structureManager, this.lightEngine, mainThreadExecutor, this::setChunkUnsaved);
|
| 208 | }
|
| 209 |
|
| 210 | private void setChunkUnsaved(final ChunkPos chunkPos) {
|
| 211 | this.chunksToEagerlySave.add(chunkPos.pack());
|
| 212 | }
|
| 213 |
|
| 214 | protected ChunkGenerator generator() {
|
| 215 | return this.worldGenContext.generator();
|
| 216 | }
|
| 217 |
|
| 218 | protected ChunkGeneratorStructureState generatorState() {
|
| 219 | return this.chunkGeneratorState;
|
| 220 | }
|
| 221 |
|
| 222 | protected RandomState randomState() {
|
| 223 | return this.randomState;
|
| 224 | }
|
| 225 |
|
| 226 | public boolean isChunkTracked(final ServerPlayer player, final int chunkX, final int chunkZ) {
|
| 227 | return player.getChunkTrackingView().contains(chunkX, chunkZ) && !player.connection.chunkSender.isPending(ChunkPos.pack(chunkX, chunkZ));
|
| 228 | }
|
| 229 |
|
| 230 | private boolean isChunkOnTrackedBorder(final ServerPlayer player, final int chunkX, final int chunkZ) {
|
| 231 | if (!this.isChunkTracked(player, chunkX, chunkZ)) {
|
| 232 | return false;
|
| 233 | }
|
| 234 |
|
| 235 | for (int dx = -1; dx <= 1; dx++) {
|
| 236 | for (int dz = -1; dz <= 1; dz++) {
|
| 237 | if ((dx != 0 || dz != 0) && !this.isChunkTracked(player, chunkX + dx, chunkZ + dz)) {
|
| 238 | return true;
|
| 239 | }
|
| 240 | }
|
| 241 | }
|
| 242 |
|
| 243 | return false;
|
| 244 | }
|
| 245 |
|
| 246 | protected ThreadedLevelLightEngine getLightEngine() {
|
| 247 | return this.lightEngine;
|
| 248 | }
|
| 249 |
|
| 250 | public @Nullable ChunkHolder getUpdatingChunkIfPresent(final long key) {
|
| 251 | return this.updatingChunkMap.get(key);
|
| 252 | }
|
| 253 |
|
| 254 | protected @Nullable ChunkHolder getVisibleChunkIfPresent(final long key) {
|
| 255 | return this.visibleChunkMap.get(key);
|
| 256 | }
|
| 257 |
|
| 258 | public @Nullable ChunkStatus getLatestStatus(final long key) {
|
| 259 | ChunkHolder chunkHolder = this.getVisibleChunkIfPresent(key);
|
| 260 | return chunkHolder != null ? chunkHolder.getLatestStatus() : null;
|
| 261 | }
|
| 262 |
|
| 263 | protected IntSupplier getChunkQueueLevel(final long pos) {
|
| 264 | return () -> {
|
| 265 | ChunkHolder chunk = this.getVisibleChunkIfPresent(pos);
|
| 266 | return chunk == null ? ChunkTaskPriorityQueue.PRIORITY_LEVEL_COUNT - 1 : Math.min(chunk.getQueueLevel(), ChunkTaskPriorityQueue.PRIORITY_LEVEL_COUNT - 1);
|
| 267 | };
|
| 268 | }
|
| 269 |
|
| 270 | public String getChunkDebugData(final ChunkPos pos) {
|
| 271 | ChunkHolder chunkHolder = this.getVisibleChunkIfPresent(pos.pack());
|
| 272 | if (chunkHolder == null) {
|
| 273 | return "null";
|
| 274 | }
|
| 275 |
|
| 276 | String result = chunkHolder.getTicketLevel() + "\n";
|
| 277 | ChunkStatus status = chunkHolder.getLatestStatus();
|
| 278 | ChunkAccess chunk = chunkHolder.getLatestChunk();
|
| 279 | if (status != null) {
|
| 280 | result = result + "St: §" + status.getIndex() + status + "§r\n";
|
| 281 | }
|
| 282 |
|
| 283 | if (chunk != null) {
|
| 284 | result = result + "Ch: §" + chunk.getPersistedStatus().getIndex() + chunk.getPersistedStatus() + "§r\n";
|
| 285 | }
|
| 286 |
|
| 287 | FullChunkStatus fullStatus = chunkHolder.getFullStatus();
|
| 288 | result = result + '§' + fullStatus.ordinal() + fullStatus;
|
| 289 | return result + "§r";
|
| 290 | }
|
| 291 |
|
| 292 | CompletableFuture<ChunkResult<List<ChunkAccess>>> getChunkRangeFuture(
|
| 293 | final ChunkHolder centerChunk, final int range, final IntFunction<ChunkStatus> distanceToStatus
|
| 294 | ) {
|
| 295 | if (range == 0) {
|
| 296 | ChunkStatus status = distanceToStatus.apply(0);
|
| 297 | return centerChunk.scheduleChunkGenerationTask(status, this).thenApply(r -> r.map(List::of));
|
| 298 | }
|
| 299 |
|
| 300 | int chunkCount = Mth.square(range * 2 + 1);
|
| 301 | List<CompletableFuture<ChunkResult<ChunkAccess>>> deps = new ArrayList<>(chunkCount);
|
| 302 | ChunkPos centerPos = centerChunk.getPos();
|
| 303 |
|
| 304 | for (int z = -range; z <= range; z++) {
|
| 305 | for (int x = -range; x <= range; x++) {
|
| 306 | int distance = Math.max(Math.abs(x), Math.abs(z));
|
| 307 | long chunkNode = ChunkPos.pack(centerPos.x() + x, centerPos.z() + z);
|
| 308 | ChunkHolder chunk = this.getUpdatingChunkIfPresent(chunkNode);
|
| 309 | if (chunk == null) {
|
| 310 | return UNLOADED_CHUNK_LIST_FUTURE;
|
| 311 | }
|
| 312 |
|
| 313 | ChunkStatus depStatus = distanceToStatus.apply(distance);
|
| 314 | deps.add(chunk.scheduleChunkGenerationTask(depStatus, this));
|
| 315 | }
|
| 316 | }
|
| 317 |
|
| 318 | return Util.sequence(deps).thenApply(chunkResults -> {
|
| 319 | List<ChunkAccess> chunks = new ArrayList<>(chunkResults.size());
|
| 320 |
|
| 321 | for (ChunkResult<ChunkAccess> chunkResult : chunkResults) {
|
| 322 | if (chunkResult == null) {
|
| 323 | throw this.debugFuturesAndCreateReportedException(new IllegalStateException("At least one of the chunk futures were null"), "n/a");
|
| 324 | }
|
| 325 |
|
| 326 | ChunkAccess chunkx = chunkResult.orElse(null);
|
| 327 | if (chunkx == null) {
|
| 328 | return UNLOADED_CHUNK_LIST_RESULT;
|
| 329 | }
|
| 330 |
|
| 331 | chunks.add(chunkx);
|
| 332 | }
|
| 333 |
|
| 334 | return ChunkResult.of(chunks);
|
| 335 | });
|
| 336 | }
|
| 337 |
|
| 338 | public ReportedException debugFuturesAndCreateReportedException(final IllegalStateException exception, final String details) {
|
| 339 | StringBuilder sb = new StringBuilder();
|
| 340 | Consumer<ChunkHolder> addToDebug = holder -> holder.getAllFutures().forEach(pair -> {
|
| 341 | ChunkStatus status = pair.getFirst();
|
| 342 | CompletableFuture<ChunkResult<ChunkAccess>> future = pair.getSecond();
|
| 343 | if (future != null && future.isDone() && future.join() == null) {
|
| 344 | sb.append(holder.getPos()).append(" - status: ").append(status).append(" future: ").append(future).append(System.lineSeparator());
|
| 345 | }
|
| 346 | });
|
| 347 | sb.append("Updating:").append(System.lineSeparator());
|
| 348 | this.updatingChunkMap.values().forEach(addToDebug);
|
| 349 | sb.append("Visible:").append(System.lineSeparator());
|
| 350 | this.visibleChunkMap.values().forEach(addToDebug);
|
| 351 | CrashReport report = CrashReport.forThrowable(exception, "Chunk loading");
|
| 352 | CrashReportCategory category = report.addCategory("Chunk loading");
|
| 353 | category.setDetail("Details", details);
|
| 354 | category.setDetail("Futures", sb);
|
| 355 | return new ReportedException(report);
|
| 356 | }
|
| 357 |
|
| 358 | public CompletableFuture<ChunkResult<LevelChunk>> prepareEntityTickingChunk(final ChunkHolder chunk) {
|
| 359 | return this.getChunkRangeFuture(chunk, 2, distance -> ChunkStatus.FULL)
|
| 360 | .thenApply(chunkResult -> chunkResult.map(list -> (LevelChunk)list.get(list.size() / 2)));
|
| 361 | }
|
| 362 |
|
| 363 | private @Nullable ChunkHolder updateChunkScheduling(final long node, final int level, @Nullable ChunkHolder chunk, final int oldLevel) {
|
| 364 | if (!ChunkLevel.isLoaded(oldLevel) && !ChunkLevel.isLoaded(level)) {
|
| 365 | return chunk;
|
| 366 | }
|
| 367 |
|
| 368 | if (chunk != null) {
|
| 369 | chunk.setTicketLevel(level);
|
| 370 | }
|
| 371 |
|
| 372 | if (chunk != null) {
|
| 373 | if (!ChunkLevel.isLoaded(level)) {
|
| 374 | this.toDrop.add(node);
|
| 375 | } else {
|
| 376 | this.toDrop.remove(node);
|
| 377 | }
|
| 378 | }
|
| 379 |
|
| 380 | if (ChunkLevel.isLoaded(level) && chunk == null) {
|
| 381 | chunk = this.pendingUnloads.remove(node);
|
| 382 | if (chunk != null) {
|
| 383 | chunk.setTicketLevel(level);
|
| 384 | } else {
|
| 385 | chunk = new ChunkHolder(ChunkPos.unpack(node), level, this.level, this.lightEngine, this::onLevelChange, this);
|
| 386 | }
|
| 387 |
|
| 388 | this.updatingChunkMap.put(node, chunk);
|
| 389 | this.modified = true;
|
| 390 | }
|
| 391 |
|
| 392 | return chunk;
|
| 393 | }
|
| 394 |
|
| 395 | private void onLevelChange(final ChunkPos pos, final IntSupplier oldLevel, final int newLevel, final IntConsumer setQueueLevel) {
|
| 396 | this.worldgenTaskDispatcher.onLevelChange(pos, oldLevel, newLevel, setQueueLevel);
|
| 397 | this.lightTaskDispatcher.onLevelChange(pos, oldLevel, newLevel, setQueueLevel);
|
| 398 | }
|
| 399 |
|
| 400 | @Override
|
| 401 | public void close() throws IOException {
|
| 402 | try {
|
| 403 | this.worldgenTaskDispatcher.close();
|
| 404 | this.lightTaskDispatcher.close();
|
| 405 | this.poiManager.close();
|
| 406 | } finally {
|
| 407 | super.close();
|
| 408 | }
|
| 409 | }
|
| 410 |
|
| 411 | protected void saveAllChunks(final boolean flushStorage) {
|
| 412 | if (flushStorage) {
|
| 413 | List<ChunkHolder> chunksToSave = this.visibleChunkMap
|
| 414 | .values()
|
| 415 | .stream()
|
| 416 | .filter(ChunkHolder::wasAccessibleSinceLastSave)
|
| 417 | .peek(ChunkHolder::refreshAccessibility)
|
| 418 | .toList();
|
| 419 | MutableBoolean didWork = new MutableBoolean();
|
| 420 |
|
| 421 | do {
|
| 422 | didWork.setFalse();
|
| 423 | chunksToSave.stream().map(chunkx -> {
|
| 424 | this.mainThreadExecutor.managedBlock(chunkx::isReadyForSaving);
|
| 425 | return chunkx.getLatestChunk();
|
| 426 | }).filter(chunkAccess -> chunkAccess instanceof ImposterProtoChunk || chunkAccess instanceof LevelChunk).filter(this::save).forEach(c -> didWork.setTrue());
|
| 427 | } while (didWork.isTrue());
|
| 428 |
|
| 429 | this.poiManager.flushAll();
|
| 430 | this.processUnloads(() -> true);
|
| 431 | this.synchronize(true).join();
|
| 432 | } else {
|
| 433 | this.nextChunkSaveTime.clear();
|
| 434 | long now = Util.getMillis();
|
| 435 |
|
| 436 | for (ChunkHolder chunk : this.visibleChunkMap.values()) {
|
| 437 | this.saveChunkIfNeeded(chunk, now);
|
| 438 | }
|
| 439 | }
|
| 440 | }
|
| 441 |
|
| 442 | protected void tick(final BooleanSupplier haveTime) {
|
| 443 | ProfilerFiller profiler = Profiler.get();
|
| 444 | profiler.push("poi");
|
| 445 | this.poiManager.tick(haveTime);
|
| 446 | profiler.popPush("chunk_unload");
|
| 447 | if (!this.level.noSave()) {
|
| 448 | this.processUnloads(haveTime);
|
| 449 | }
|
| 450 |
|
| 451 | profiler.pop();
|
| 452 | }
|
| 453 |
|
| 454 | public boolean hasWork() {
|
| 455 | return this.lightEngine.hasLightWork()
|
| 456 | || !this.pendingUnloads.isEmpty()
|
| 457 | || !this.updatingChunkMap.isEmpty()
|
| 458 | || this.poiManager.hasWork()
|
| 459 | || !this.toDrop.isEmpty()
|
| 460 | || !this.unloadQueue.isEmpty()
|
| 461 | || this.worldgenTaskDispatcher.hasWork()
|
| 462 | || this.lightTaskDispatcher.hasWork()
|
| 463 | || this.distanceManager.hasTickets();
|
| 464 | }
|
| 465 |
|
| 466 | private void processUnloads(final BooleanSupplier haveTime) {
|
| 467 | for (LongIterator iterator = this.toDrop.iterator(); iterator.hasNext(); iterator.remove()) {
|
| 468 | long pos = iterator.nextLong();
|
| 469 | ChunkHolder chunkHolder = this.updatingChunkMap.get(pos);
|
| 470 | if (chunkHolder != null) {
|
| 471 | this.updatingChunkMap.remove(pos);
|
| 472 | this.pendingUnloads.put(pos, chunkHolder);
|
| 473 | this.modified = true;
|
| 474 | this.scheduleUnload(pos, chunkHolder);
|
| 475 | }
|
| 476 | }
|
| 477 |
|
| 478 | int minimalNumberOfChunksToProcess = Math.max(0, this.unloadQueue.size() - 2000);
|
| 479 |
|
| 480 | Runnable unloadTask;
|
| 481 | while ((minimalNumberOfChunksToProcess > 0 || haveTime.getAsBoolean()) && (unloadTask = this.unloadQueue.poll()) != null) {
|
| 482 | minimalNumberOfChunksToProcess--;
|
| 483 | unloadTask.run();
|
| 484 | }
|
| 485 |
|
| 486 | this.saveChunksEagerly(haveTime);
|
| 487 | }
|
| 488 |
|
| 489 | private void saveChunksEagerly(final BooleanSupplier haveTime) {
|
| 490 | long now = Util.getMillis();
|
| 491 | int eagerlySavedCount = 0;
|
| 492 | LongIterator iterator = this.chunksToEagerlySave.iterator();
|
| 493 |
|
| 494 | while (eagerlySavedCount < 20 && this.activeChunkWrites.get() < 128 && haveTime.getAsBoolean() && iterator.hasNext()) {
|
| 495 | long chunkPos = iterator.nextLong();
|
| 496 | ChunkHolder chunkHolder = this.visibleChunkMap.get(chunkPos);
|
| 497 | ChunkAccess latestChunk = chunkHolder != null ? chunkHolder.getLatestChunk() : null;
|
| 498 | if (latestChunk == null || !latestChunk.isUnsaved()) {
|
| 499 | iterator.remove();
|
| 500 | } else if (this.saveChunkIfNeeded(chunkHolder, now)) {
|
| 501 | eagerlySavedCount++;
|
| 502 | iterator.remove();
|
| 503 | }
|
| 504 | }
|
| 505 | }
|
| 506 |
|
| 507 | private void scheduleUnload(final long pos, final ChunkHolder chunkHolder) {
|
| 508 | CompletableFuture<?> saveSyncFuture = chunkHolder.getSaveSyncFuture();
|
| 509 | saveSyncFuture.thenRunAsync(() -> {
|
| 510 | CompletableFuture<?> currentFuture = chunkHolder.getSaveSyncFuture();
|
| 511 | if (currentFuture != saveSyncFuture) {
|
| 512 | this.scheduleUnload(pos, chunkHolder);
|
| 513 | } else {
|
| 514 | ChunkAccess chunk = chunkHolder.getLatestChunk();
|
| 515 | if (this.pendingUnloads.remove(pos, chunkHolder) && chunk != null) {
|
| 516 | if (chunk instanceof LevelChunk levelChunk) {
|
| 517 | levelChunk.setLoaded(false);
|
| 518 | }
|
| 519 |
|
| 520 | this.save(chunk);
|
| 521 | if (chunk instanceof LevelChunk levelChunk) {
|
| 522 | this.level.unload(levelChunk);
|
| 523 | }
|
| 524 |
|
| 525 | this.lightEngine.updateChunkStatus(chunk.getPos());
|
| 526 | this.lightEngine.tryScheduleUpdate();
|
| 527 | this.nextChunkSaveTime.remove(chunk.getPos().pack());
|
| 528 | }
|
| 529 | }
|
| 530 | }, this.unloadQueue::add).whenComplete((ignored, throwable) -> {
|
| 531 | if (throwable != null) {
|
| 532 | LOGGER.error("Failed to save chunk {}", chunkHolder.getPos(), throwable);
|
| 533 | }
|
| 534 | });
|
| 535 | }
|
| 536 |
|
| 537 | protected boolean promoteChunkMap() {
|
| 538 | if (!this.modified) {
|
| 539 | return false;
|
| 540 | }
|
| 541 |
|
| 542 | this.visibleChunkMap = this.updatingChunkMap.clone();
|
| 543 | this.modified = false;
|
| 544 | return true;
|
| 545 | }
|
| 546 |
|
| 547 | private CompletableFuture<ChunkAccess> scheduleChunkLoad(final ChunkPos pos) {
|
| 548 | CompletableFuture<Optional<SerializableChunkData>> chunkDataFuture = this.readChunk(pos).thenApplyAsync(chunkData -> chunkData.map(tag -> {
|
| 549 | SerializableChunkData parsedData = SerializableChunkData.parse(this.level, this.level.palettedContainerFactory(), tag);
|
| 550 | if (parsedData == null) {
|
| 551 | LOGGER.error("Chunk file at {} is missing level data, skipping", pos);
|
| 552 | }
|
| 553 |
|
| 554 | return parsedData;
|
| 555 | }), Util.backgroundExecutor().forName("parseChunk"));
|
| 556 | CompletableFuture<?> poiFuture = this.poiManager.prefetch(pos);
|
| 557 | return chunkDataFuture.<Object, Optional<SerializableChunkData>>thenCombine((CompletionStage<? extends Object>)poiFuture, (chunkData, ignored) -> chunkData)
|
| 558 | .thenApplyAsync(chunkData -> {
|
| 559 | Profiler.get().incrementCounter("chunkLoad");
|
| 560 | if (chunkData.isPresent()) {
|
| 561 | ChunkAccess chunk = chunkData.get().read(this.level, this.poiManager, this.storageInfo(), pos);
|
| 562 | this.markPosition(pos, chunk.getPersistedStatus().getChunkType());
|
| 563 | return chunk;
|
| 564 | } else {
|
| 565 | return this.createEmptyChunk(pos);
|
| 566 | }
|
| 567 | }, this.mainThreadExecutor)
|
| 568 | .exceptionallyAsync(throwable -> this.handleChunkLoadFailure(throwable, pos), this.mainThreadExecutor);
|
| 569 | }
|
| 570 |
|
| 571 | private ChunkAccess handleChunkLoadFailure(final Throwable throwable, final ChunkPos pos) {
|
| 572 | Throwable unwrapped = throwable instanceof CompletionException e ? e.getCause() : throwable;
|
| 573 | Throwable cause = unwrapped instanceof ReportedException e ? e.getCause() : unwrapped;
|
| 574 | boolean alwaysThrow = cause instanceof Error;
|
| 575 | boolean ioException = cause instanceof IOException || cause instanceof NbtException;
|
| 576 | if (!alwaysThrow) {
|
| 577 | if (!ioException) {
|
| 578 | }
|
| 579 |
|
| 580 | this.level.getServer().reportChunkLoadFailure(cause, this.storageInfo(), pos);
|
| 581 | return this.createEmptyChunk(pos);
|
| 582 | } else {
|
| 583 | CrashReport report = CrashReport.forThrowable(throwable, "Exception loading chunk");
|
| 584 | CrashReportCategory chunkBeingLoaded = report.addCategory("Chunk being loaded");
|
| 585 | chunkBeingLoaded.setDetail("pos", pos);
|
| 586 | this.markPositionReplaceable(pos);
|
| 587 | throw new ReportedException(report);
|
| 588 | }
|
| 589 | }
|
| 590 |
|
| 591 | private ChunkAccess createEmptyChunk(final ChunkPos pos) {
|
| 592 | this.markPositionReplaceable(pos);
|
| 593 | return new ProtoChunk(pos, UpgradeData.EMPTY, this.level, this.level.palettedContainerFactory(), null);
|
| 594 | }
|
| 595 |
|
| 596 | private void markPositionReplaceable(final ChunkPos pos) {
|
| 597 | this.chunkTypeCache.put(pos.pack(), (byte)-1);
|
| 598 | }
|
| 599 |
|
| 600 | private byte markPosition(final ChunkPos pos, final ChunkType type) {
|
| 601 | return this.chunkTypeCache.put(pos.pack(), (byte)(type == ChunkType.PROTOCHUNK ? -1 : 1));
|
| 602 | }
|
| 603 |
|
| 604 | @Override
|
| 605 | public GenerationChunkHolder acquireGeneration(final long chunkNode) {
|
| 606 | ChunkHolder chunkHolder = this.updatingChunkMap.get(chunkNode);
|
| 607 | chunkHolder.increaseGenerationRefCount();
|
| 608 | return chunkHolder;
|
| 609 | }
|
| 610 |
|
| 611 | @Override
|
| 612 | public void releaseGeneration(final GenerationChunkHolder chunkHolder) {
|
| 613 | chunkHolder.decreaseGenerationRefCount();
|
| 614 | }
|
| 615 |
|
| 616 | @Override
|
| 617 | public CompletableFuture<ChunkAccess> applyStep(
|
| 618 | final GenerationChunkHolder chunkHolder, final ChunkStep step, final StaticCache2D<GenerationChunkHolder> cache
|
| 619 | ) {
|
| 620 | ChunkPos pos = chunkHolder.getPos();
|
| 621 | if (step.targetStatus() == ChunkStatus.EMPTY) {
|
| 622 | return this.scheduleChunkLoad(pos);
|
| 623 | }
|
| 624 |
|
| 625 | try {
|
| 626 | GenerationChunkHolder holder = cache.get(pos.x(), pos.z());
|
| 627 | ChunkAccess centerChunk = holder.getChunkIfPresentUnchecked(step.targetStatus().getParent());
|
| 628 | if (centerChunk == null) {
|
| 629 | throw new IllegalStateException("Parent chunk missing");
|
| 630 | } else {
|
| 631 | return step.apply(this.worldGenContext, cache, centerChunk);
|
| 632 | }
|
| 633 | } catch (Exception e) {
|
| 634 | e.getStackTrace();
|
| 635 | CrashReport report = CrashReport.forThrowable(e, "Exception generating new chunk");
|
| 636 | CrashReportCategory category = report.addCategory("Chunk to be generated");
|
| 637 | category.setDetail("Status being generated", () -> step.targetStatus().getName());
|
| 638 | category.setDetail("Location", String.format(Locale.ROOT, "%d,%d", pos.x(), pos.z()));
|
| 639 | category.setDetail("Position hash", ChunkPos.pack(pos.x(), pos.z()));
|
| 640 | category.setDetail("Generator", this.generator());
|
| 641 | throw new ReportedException(report);
|
| 642 | }
|
| 643 | }
|
| 644 |
|
| 645 | @Override
|
| 646 | public ChunkGenerationTask scheduleGenerationTask(final ChunkStatus targetStatus, final ChunkPos pos) {
|
| 647 | ChunkGenerationTask task = ChunkGenerationTask.create(this, targetStatus, pos);
|
| 648 | this.pendingGenerationTasks.add(task);
|
| 649 | return task;
|
| 650 | }
|
| 651 |
|
| 652 | private void runGenerationTask(final ChunkGenerationTask task) {
|
| 653 | GenerationChunkHolder chunk = task.getCenter();
|
| 654 | this.worldgenTaskDispatcher.submit(() -> {
|
| 655 | CompletableFuture<?> future = task.runUntilWait();
|
| 656 | if (future != null) {
|
| 657 | future.thenRun(() -> this.runGenerationTask(task));
|
| 658 | }
|
| 659 | }, chunk.getPos().pack(), chunk::getQueueLevel);
|
| 660 | }
|
| 661 |
|
| 662 | @Override
|
| 663 | public void runGenerationTasks() {
|
| 664 | this.pendingGenerationTasks.forEach(this::runGenerationTask);
|
| 665 | this.pendingGenerationTasks.clear();
|
| 666 | }
|
| 667 |
|
| 668 | public CompletableFuture<ChunkResult<LevelChunk>> prepareTickingChunk(final ChunkHolder chunk) {
|
| 669 | CompletableFuture<ChunkResult<List<ChunkAccess>>> future = this.getChunkRangeFuture(chunk, 1, distance -> ChunkStatus.FULL);
|
| 670 | return future.thenApplyAsync(listResult -> listResult.map(list -> {
|
| 671 | LevelChunk levelChunk = (LevelChunk)list.get(list.size() / 2);
|
| 672 | levelChunk.postProcessGeneration(this.level);
|
| 673 | this.level.startTickingChunk(levelChunk);
|
| 674 | CompletableFuture<?> sendSyncFuture = chunk.getSendSyncFuture();
|
| 675 | if (sendSyncFuture.isDone()) {
|
| 676 | this.onChunkReadyToSend(chunk, levelChunk);
|
| 677 | } else {
|
| 678 | sendSyncFuture.thenAcceptAsync(ignored -> this.onChunkReadyToSend(chunk, levelChunk), this.mainThreadExecutor);
|
| 679 | }
|
| 680 |
|
| 681 | return levelChunk;
|
| 682 | }), this.mainThreadExecutor);
|
| 683 | }
|
| 684 |
|
| 685 | private void onChunkReadyToSend(final ChunkHolder chunkHolder, final LevelChunk chunk) {
|
| 686 | ChunkPos chunkPos = chunk.getPos();
|
| 687 |
|
| 688 | for (ServerPlayer player : this.playerMap.getAllPlayers()) {
|
| 689 | if (player.getChunkTrackingView().contains(chunkPos)) {
|
| 690 | markChunkPendingToSend(player, chunk);
|
| 691 | }
|
| 692 | }
|
| 693 |
|
| 694 | this.level.getChunkSource().onChunkReadyToSend(chunkHolder);
|
| 695 | this.level.debugSynchronizers().registerChunk(chunk);
|
| 696 | }
|
| 697 |
|
| 698 | public CompletableFuture<ChunkResult<LevelChunk>> prepareAccessibleChunk(final ChunkHolder chunk) {
|
| 699 | return this.getChunkRangeFuture(chunk, 1, ChunkLevel::getStatusAroundFullChunk)
|
| 700 | .thenApply(chunkResult -> chunkResult.map(list -> (LevelChunk)list.get(list.size() / 2)));
|
| 701 | }
|
| 702 |
|
| 703 | Stream<ChunkHolder> allChunksWithAtLeastStatus(final ChunkStatus status) {
|
| 704 | int level = ChunkLevel.byStatus(status);
|
| 705 | return this.visibleChunkMap.values().stream().filter(chunk -> chunk.getTicketLevel() <= level);
|
| 706 | }
|
| 707 |
|
| 708 | private boolean saveChunkIfNeeded(final ChunkHolder chunk, final long now) {
|
| 709 | if (chunk.wasAccessibleSinceLastSave() && chunk.isReadyForSaving()) {
|
| 710 | ChunkAccess chunkAccess = chunk.getLatestChunk();
|
| 711 | if (!(chunkAccess instanceof ImposterProtoChunk) && !(chunkAccess instanceof LevelChunk)) {
|
| 712 | return false;
|
| 713 | }
|
| 714 |
|
| 715 | if (!chunkAccess.isUnsaved()) {
|
| 716 | return false;
|
| 717 | }
|
| 718 |
|
| 719 | long chunkPos = chunkAccess.getPos().pack();
|
| 720 | long nextSaveTime = this.nextChunkSaveTime.getOrDefault(chunkPos, -1L);
|
| 721 | if (now < nextSaveTime) {
|
| 722 | return false;
|
| 723 | }
|
| 724 |
|
| 725 | boolean saved = this.save(chunkAccess);
|
| 726 | chunk.refreshAccessibility();
|
| 727 | if (saved) {
|
| 728 | this.nextChunkSaveTime.put(chunkPos, now + 10000L);
|
| 729 | }
|
| 730 |
|
| 731 | return saved;
|
| 732 | } else {
|
| 733 | return false;
|
| 734 | }
|
| 735 | }
|
| 736 |
|
| 737 | private boolean save(final ChunkAccess chunk) {
|
| 738 | this.poiManager.flush(chunk.getPos());
|
| 739 | if (!chunk.tryMarkSaved()) {
|
| 740 | return false;
|
| 741 | }
|
| 742 |
|
| 743 | ChunkPos pos = chunk.getPos();
|
| 744 |
|
| 745 | try {
|
| 746 | ChunkStatus status = chunk.getPersistedStatus();
|
| 747 | if (status.getChunkType() != ChunkType.LEVELCHUNK) {
|
| 748 | if (this.isExistingChunkFull(pos)) {
|
| 749 | return false;
|
| 750 | }
|
| 751 |
|
| 752 | if (status == ChunkStatus.EMPTY && chunk.getAllStarts().values().stream().noneMatch(StructureStart::isValid)) {
|
| 753 | return false;
|
| 754 | }
|
| 755 | }
|
| 756 |
|
| 757 | Profiler.get().incrementCounter("chunkSave");
|
| 758 | this.activeChunkWrites.incrementAndGet();
|
| 759 | SerializableChunkData data = SerializableChunkData.copyOf(this.level, chunk);
|
| 760 | CompletableFuture<CompoundTag> encodedData = CompletableFuture.supplyAsync(data::write, Util.backgroundExecutor());
|
| 761 | this.write(pos, encodedData::join).handle((ignored, throwable) -> {
|
| 762 | if (throwable != null) {
|
| 763 | this.level.getServer().reportChunkSaveFailure(throwable, this.storageInfo(), pos);
|
| 764 | }
|
| 765 |
|
| 766 | this.activeChunkWrites.decrementAndGet();
|
| 767 | return null;
|
| 768 | });
|
| 769 | this.markPosition(pos, status.getChunkType());
|
| 770 | return true;
|
| 771 | } catch (Exception e) {
|
| 772 | this.level.getServer().reportChunkSaveFailure(e, this.storageInfo(), pos);
|
| 773 | return false;
|
| 774 | }
|
| 775 | }
|
| 776 |
|
| 777 | private boolean isExistingChunkFull(final ChunkPos pos) {
|
| 778 | byte cachedChunkType = this.chunkTypeCache.get(pos.pack());
|
| 779 | if (cachedChunkType != 0) {
|
| 780 | return cachedChunkType == 1;
|
| 781 | }
|
| 782 |
|
| 783 | CompoundTag currentTag;
|
| 784 | try {
|
| 785 | currentTag = this.readChunk(pos).join().orElse(null);
|
| 786 | if (currentTag == null) {
|
| 787 | this.markPositionReplaceable(pos);
|
| 788 | return false;
|
| 789 | }
|
| 790 | } catch (Exception e) {
|
| 791 | LOGGER.error("Failed to read chunk {}", pos, e);
|
| 792 | this.markPositionReplaceable(pos);
|
| 793 | return false;
|
| 794 | }
|
| 795 |
|
| 796 | ChunkType chunkType = SerializableChunkData.getChunkStatusFromTag(currentTag).getChunkType();
|
| 797 | return this.markPosition(pos, chunkType) == 1;
|
| 798 | }
|
| 799 |
|
| 800 | protected void setServerViewDistance(final int newViewDistance) {
|
| 801 | int actualNewDistance = Mth.clamp(newViewDistance, 2, 32);
|
| 802 | if (actualNewDistance != this.serverViewDistance) {
|
| 803 | this.serverViewDistance = actualNewDistance;
|
| 804 | this.distanceManager.updatePlayerTickets(this.serverViewDistance);
|
| 805 |
|
| 806 | for (ServerPlayer player : this.playerMap.getAllPlayers()) {
|
| 807 | this.updateChunkTracking(player);
|
| 808 | }
|
| 809 | }
|
| 810 | }
|
| 811 |
|
| 812 | private int getPlayerViewDistance(final ServerPlayer player) {
|
| 813 | return Mth.clamp(player.requestedViewDistance(), 2, this.serverViewDistance);
|
| 814 | }
|
| 815 |
|
| 816 | private void markChunkPendingToSend(final ServerPlayer player, final ChunkPos pos) {
|
| 817 | LevelChunk chunk = this.getChunkToSend(pos.pack());
|
| 818 | if (chunk != null) {
|
| 819 | markChunkPendingToSend(player, chunk);
|
| 820 | }
|
| 821 | }
|
| 822 |
|
| 823 | private static void markChunkPendingToSend(final ServerPlayer player, final LevelChunk chunk) {
|
| 824 | player.connection.chunkSender.markChunkPendingToSend(chunk);
|
| 825 | }
|
| 826 |
|
| 827 | private static void dropChunk(final ServerPlayer player, final ChunkPos pos) {
|
| 828 | player.connection.chunkSender.dropChunk(player, pos);
|
| 829 | }
|
| 830 |
|
| 831 | public @Nullable LevelChunk getChunkToSend(final long key) {
|
| 832 | ChunkHolder chunkHolder = this.getVisibleChunkIfPresent(key);
|
| 833 | return chunkHolder == null ? null : chunkHolder.getChunkToSend();
|
| 834 | }
|
| 835 |
|
| 836 | public int size() {
|
| 837 | return this.visibleChunkMap.size();
|
| 838 | }
|
| 839 |
|
| 840 | public net.minecraft.server.level.DistanceManager getDistanceManager() {
|
| 841 | return this.distanceManager;
|
| 842 | }
|
| 843 |
|
| 844 | void dumpChunks(final Writer output) throws IOException {
|
| 845 | CsvOutput csvOutput = CsvOutput.builder()
|
| 846 | .addColumn("x")
|
| 847 | .addColumn("z")
|
| 848 | .addColumn("level")
|
| 849 | .addColumn("in_memory")
|
| 850 | .addColumn("status")
|
| 851 | .addColumn("full_status")
|
| 852 | .addColumn("accessible_ready")
|
| 853 | .addColumn("ticking_ready")
|
| 854 | .addColumn("entity_ticking_ready")
|
| 855 | .addColumn("ticket")
|
| 856 | .addColumn("spawning")
|
| 857 | .addColumn("block_entity_count")
|
| 858 | .addColumn("ticking_ticket")
|
| 859 | .addColumn("ticking_level")
|
| 860 | .addColumn("block_ticks")
|
| 861 | .addColumn("fluid_ticks")
|
| 862 | .build(output);
|
| 863 |
|
| 864 | for (Entry<ChunkHolder> entry : this.visibleChunkMap.long2ObjectEntrySet()) {
|
| 865 | long posKey = entry.getLongKey();
|
| 866 | ChunkPos pos = ChunkPos.unpack(posKey);
|
| 867 | ChunkHolder holder = entry.getValue();
|
| 868 | Optional<ChunkAccess> chunk = Optional.ofNullable(holder.getLatestChunk());
|
| 869 | Optional<LevelChunk> fullChunk = chunk.flatMap(chunkAccess -> chunkAccess instanceof LevelChunk levelChunk ? Optional.of(levelChunk) : Optional.empty());
|
| 870 | csvOutput.writeRow(
|
| 871 | pos.x(),
|
| 872 | pos.z(),
|
| 873 | holder.getTicketLevel(),
|
| 874 | chunk.isPresent(),
|
| 875 | chunk.map(ChunkAccess::getPersistedStatus).orElse(null),
|
| 876 | fullChunk.map(LevelChunk::getFullStatus).orElse(null),
|
| 877 | printFuture(holder.getFullChunkFuture()),
|
| 878 | printFuture(holder.getTickingChunkFuture()),
|
| 879 | printFuture(holder.getEntityTickingChunkFuture()),
|
| 880 | this.ticketStorage.getTicketDebugString(posKey, false),
|
| 881 | this.anyPlayerCloseEnoughForSpawning(pos),
|
| 882 | fullChunk.<Integer>map(c -> c.getBlockEntities().size()).orElse(0),
|
| 883 | this.ticketStorage.getTicketDebugString(posKey, true),
|
| 884 | this.distanceManager.getChunkLevel(posKey, true),
|
| 885 | fullChunk.<Integer>map(levelChunk -> levelChunk.getBlockTicks().count()).orElse(0),
|
| 886 | fullChunk.<Integer>map(levelChunk -> levelChunk.getFluidTicks().count()).orElse(0)
|
| 887 | );
|
| 888 | }
|
| 889 | }
|
| 890 |
|
| 891 | private static String printFuture(final CompletableFuture<ChunkResult<LevelChunk>> future) {
|
| 892 | try {
|
| 893 | ChunkResult<LevelChunk> result = future.getNow(null);
|
| 894 | if (result != null) {
|
| 895 | return result.isSuccess() ? "done" : "unloaded";
|
| 896 | } else {
|
| 897 | return "not completed";
|
| 898 | }
|
| 899 | } catch (CompletionException e) {
|
| 900 | return "failed " + e.getCause().getMessage();
|
| 901 | } catch (CancellationException e) {
|
| 902 | return "cancelled";
|
| 903 | }
|
| 904 | }
|
| 905 |
|
| 906 | private CompletableFuture<Optional<CompoundTag>> readChunk(final ChunkPos pos) {
|
| 907 | return this.read(pos).thenApplyAsync(chunkTag -> chunkTag.map(this::upgradeChunkTag), Util.backgroundExecutor().forName("upgradeChunk"));
|
| 908 | }
|
| 909 |
|
| 910 | private CompoundTag upgradeChunkTag(final CompoundTag tag) {
|
| 911 | return this.upgradeChunkTag(
|
| 912 | tag,
|
| 913 | -1,
|
| 914 | getChunkDataFixContextTag(this.level.dimension(), this.generator().getTypeNameForDataFixer()),
|
| 915 | SharedConstants.getCurrentVersion().dataVersion().version()
|
| 916 | );
|
| 917 | }
|
| 918 |
|
| 919 | public static CompoundTag getChunkDataFixContextTag(final ResourceKey<Level> dimension, final Optional<Identifier> generatorIdentifier) {
|
| 920 | CompoundTag contextTag = new CompoundTag();
|
| 921 | contextTag.putString("dimension", dimension.identifier().toString());
|
| 922 | generatorIdentifier.ifPresent(identifier -> contextTag.putString("generator", identifier.toString()));
|
| 923 | return contextTag;
|
| 924 | }
|
| 925 |
|
| 926 | public void collectSpawningChunks(final List<LevelChunk> output) {
|
| 927 | LongIterator spawnCandidateChunks = this.distanceManager.getSpawnCandidateChunks();
|
| 928 |
|
| 929 | while (spawnCandidateChunks.hasNext()) {
|
| 930 | ChunkHolder holder = this.visibleChunkMap.get(spawnCandidateChunks.nextLong());
|
| 931 | if (holder != null) {
|
| 932 | LevelChunk chunk = holder.getTickingChunk();
|
| 933 | if (chunk != null && this.anyPlayerCloseEnoughForSpawningInternal(holder.getPos())) {
|
| 934 | output.add(chunk);
|
| 935 | }
|
| 936 | }
|
| 937 | }
|
| 938 | }
|
| 939 |
|
| 940 | public void forEachBlockTickingChunk(final Consumer<LevelChunk> tickingChunkConsumer) {
|
| 941 | this.distanceManager.forEachEntityTickingChunk(chunkPos -> {
|
| 942 | ChunkHolder holder = this.visibleChunkMap.get(chunkPos);
|
| 943 | if (holder != null) {
|
| 944 | LevelChunk chunk = holder.getTickingChunk();
|
| 945 | if (chunk != null) {
|
| 946 | tickingChunkConsumer.accept(chunk);
|
| 947 | }
|
| 948 | }
|
| 949 | });
|
| 950 | }
|
| 951 |
|
| 952 | public boolean anyPlayerCloseEnoughForSpawning(final ChunkPos pos) {
|
| 953 | TriState triState = this.distanceManager.hasPlayersNearby(pos.pack());
|
| 954 | return triState == TriState.DEFAULT ? this.anyPlayerCloseEnoughForSpawningInternal(pos) : triState.toBoolean(true);
|
| 955 | }
|
| 956 |
|
| 957 | public boolean anyPlayerCloseEnoughTo(final BlockPos pos, final int maxDistance) {
|
| 958 | Vec3 target = new Vec3(pos);
|
| 959 |
|
| 960 | for (ServerPlayer player : this.playerMap.getAllPlayers()) {
|
| 961 | if (this.playerIsCloseEnoughTo(player, target, maxDistance)) {
|
| 962 | return true;
|
| 963 | }
|
| 964 | }
|
| 965 |
|
| 966 | return false;
|
| 967 | }
|
| 968 |
|
| 969 | private boolean anyPlayerCloseEnoughForSpawningInternal(final ChunkPos pos) {
|
| 970 | for (ServerPlayer player : this.playerMap.getAllPlayers()) {
|
| 971 | if (this.playerIsCloseEnoughForSpawning(player, pos)) {
|
| 972 | return true;
|
| 973 | }
|
| 974 | }
|
| 975 |
|
| 976 | return false;
|
| 977 | }
|
| 978 |
|
| 979 | public List<ServerPlayer> getPlayersCloseForSpawning(final ChunkPos pos) {
|
| 980 | long key = pos.pack();
|
| 981 | if (!this.distanceManager.hasPlayersNearby(key).toBoolean(true)) {
|
| 982 | return List.of();
|
| 983 | }
|
| 984 |
|
| 985 | Builder<ServerPlayer> builder = ImmutableList.builder();
|
| 986 |
|
| 987 | for (ServerPlayer player : this.playerMap.getAllPlayers()) {
|
| 988 | if (this.playerIsCloseEnoughForSpawning(player, pos)) {
|
| 989 | builder.add(player);
|
| 990 | }
|
| 991 | }
|
| 992 |
|
| 993 | return builder.build();
|
| 994 | }
|
| 995 |
|
| 996 | private boolean playerIsCloseEnoughForSpawning(final ServerPlayer player, final ChunkPos pos) {
|
| 997 | if (player.isSpectator()) {
|
| 998 | return false;
|
| 999 | }
|
| 1000 |
|
| 1001 | double distanceToChunk = euclideanDistanceSquared(pos, player.position());
|
| 1002 | return distanceToChunk < 16384.0;
|
| 1003 | }
|
| 1004 |
|
| 1005 | private boolean playerIsCloseEnoughTo(final ServerPlayer player, final Vec3 pos, final int maxDistance) {
|
| 1006 | if (player.isSpectator()) {
|
| 1007 | return false;
|
| 1008 | }
|
| 1009 |
|
| 1010 | double distanceToPos = player.position().distanceTo(pos);
|
| 1011 | return distanceToPos < maxDistance;
|
| 1012 | }
|
| 1013 |
|
| 1014 | private static double euclideanDistanceSquared(final ChunkPos chunkPos, final Vec3 pos) {
|
| 1015 | double xPos = SectionPos.sectionToBlockCoord(chunkPos.x(), 8);
|
| 1016 | double zPos = SectionPos.sectionToBlockCoord(chunkPos.z(), 8);
|
| 1017 | double xd = xPos - pos.x;
|
| 1018 | double zd = zPos - pos.z;
|
| 1019 | return xd * xd + zd * zd;
|
| 1020 | }
|
| 1021 |
|
| 1022 | private boolean skipPlayer(final ServerPlayer player) {
|
| 1023 | return player.isSpectator() && !this.level.getGameRules().get(GameRules.SPECTATORS_GENERATE_CHUNKS);
|
| 1024 | }
|
| 1025 |
|
| 1026 | private void updatePlayerStatus(final ServerPlayer player, final boolean added) {
|
| 1027 | boolean ignored = this.skipPlayer(player);
|
| 1028 | boolean wasIgnored = this.playerMap.ignoredOrUnknown(player);
|
| 1029 | if (added) {
|
| 1030 | this.playerMap.addPlayer(player, ignored);
|
| 1031 | this.updatePlayerPos(player);
|
| 1032 | if (!ignored) {
|
| 1033 | this.distanceManager.addPlayer(SectionPos.of(player), player);
|
| 1034 | }
|
| 1035 |
|
| 1036 | player.setChunkTrackingView(ChunkTrackingView.EMPTY);
|
| 1037 | this.updateChunkTracking(player);
|
| 1038 | } else {
|
| 1039 | SectionPos lastPos = player.getLastSectionPos();
|
| 1040 | this.playerMap.removePlayer(player);
|
| 1041 | if (!wasIgnored) {
|
| 1042 | this.distanceManager.removePlayer(lastPos, player);
|
| 1043 | }
|
| 1044 |
|
| 1045 | this.applyChunkTrackingView(player, ChunkTrackingView.EMPTY);
|
| 1046 | }
|
| 1047 | }
|
| 1048 |
|
| 1049 | private void updatePlayerPos(final ServerPlayer player) {
|
| 1050 | SectionPos pos = SectionPos.of(player);
|
| 1051 | player.setLastSectionPos(pos);
|
| 1052 | }
|
| 1053 |
|
| 1054 | public void move(final ServerPlayer player) {
|
| 1055 | for (ChunkMap.TrackedEntity trackedEntity : this.entityMap.values()) {
|
| 1056 | if (trackedEntity.entity == player) {
|
| 1057 | trackedEntity.updatePlayers(this.level.players());
|
| 1058 | } else {
|
| 1059 | trackedEntity.updatePlayer(player);
|
| 1060 | }
|
| 1061 | }
|
| 1062 |
|
| 1063 | SectionPos oldSection = player.getLastSectionPos();
|
| 1064 | SectionPos newSection = SectionPos.of(player);
|
| 1065 | boolean wasIgnored = this.playerMap.ignored(player);
|
| 1066 | boolean ignored = this.skipPlayer(player);
|
| 1067 | boolean positionChanged = oldSection.asLong() != newSection.asLong();
|
| 1068 | if (positionChanged || wasIgnored != ignored) {
|
| 1069 | this.updatePlayerPos(player);
|
| 1070 | if (!wasIgnored) {
|
| 1071 | this.distanceManager.removePlayer(oldSection, player);
|
| 1072 | }
|
| 1073 |
|
| 1074 | if (!ignored) {
|
| 1075 | this.distanceManager.addPlayer(newSection, player);
|
| 1076 | }
|
| 1077 |
|
| 1078 | if (!wasIgnored && ignored) {
|
| 1079 | this.playerMap.ignorePlayer(player);
|
| 1080 | }
|
| 1081 |
|
| 1082 | if (wasIgnored && !ignored) {
|
| 1083 | this.playerMap.unIgnorePlayer(player);
|
| 1084 | }
|
| 1085 |
|
| 1086 | this.updateChunkTracking(player);
|
| 1087 | }
|
| 1088 | }
|
| 1089 |
|
| 1090 | private void updateChunkTracking(final ServerPlayer player) {
|
| 1091 | ChunkPos chunkPos = player.chunkPosition();
|
| 1092 | int playerViewDistance = this.getPlayerViewDistance(player);
|
| 1093 | if (!(
|
| 1094 | player.getChunkTrackingView() instanceof ChunkTrackingView.Positioned view && view.center().equals(chunkPos) && view.viewDistance() == playerViewDistance
|
| 1095 | )) {
|
| 1096 | this.applyChunkTrackingView(player, ChunkTrackingView.of(chunkPos, playerViewDistance));
|
| 1097 | }
|
| 1098 | }
|
| 1099 |
|
| 1100 | private void applyChunkTrackingView(final ServerPlayer player, final ChunkTrackingView next) {
|
| 1101 | if (player.level() == this.level) {
|
| 1102 | ChunkTrackingView previous = player.getChunkTrackingView();
|
| 1103 | if (next instanceof ChunkTrackingView.Positioned to && !(previous instanceof ChunkTrackingView.Positioned from && from.center().equals(to.center()))) {
|
| 1104 | player.connection.send(new ClientboundSetChunkCacheCenterPacket(to.center().x(), to.center().z()));
|
| 1105 | }
|
| 1106 |
|
| 1107 | ChunkTrackingView.difference(previous, next, pos -> this.markChunkPendingToSend(player, pos), pos -> dropChunk(player, pos));
|
| 1108 | player.setChunkTrackingView(next);
|
| 1109 | }
|
| 1110 | }
|
| 1111 |
|
| 1112 | @Override
|
| 1113 | public List<ServerPlayer> getPlayers(final ChunkPos pos, final boolean borderOnly) {
|
| 1114 | Set<ServerPlayer> allPlayers = this.playerMap.getAllPlayers();
|
| 1115 | Builder<ServerPlayer> result = ImmutableList.builder();
|
| 1116 |
|
| 1117 | for (ServerPlayer player : allPlayers) {
|
| 1118 | if (borderOnly && this.isChunkOnTrackedBorder(player, pos.x(), pos.z()) || !borderOnly && this.isChunkTracked(player, pos.x(), pos.z())) {
|
| 1119 | result.add(player);
|
| 1120 | }
|
| 1121 | }
|
| 1122 |
|
| 1123 | return result.build();
|
| 1124 | }
|
| 1125 |
|
| 1126 | public boolean hasEntityWithId(final int id) {
|
| 1127 | return this.entityMap.containsKey(id);
|
| 1128 | }
|
| 1129 |
|
| 1130 | protected void addEntity(final Entity entity) {
|
| 1131 | if (!(entity instanceof EnderDragonPart)) {
|
| 1132 | EntityType<?> type = entity.getType();
|
| 1133 | int range = type.clientTrackingRange() * 16;
|
| 1134 | if (range != 0) {
|
| 1135 | if (this.entityMap.containsKey(entity.getId())) {
|
| 1136 | throw (IllegalStateException)Util.pauseInIde(new IllegalStateException("Entity is already tracked!"));
|
| 1137 | }
|
| 1138 |
|
| 1139 | UpdateInterval updateInterval = type.hasUpdateInterval() ? UpdateInterval.periodic(type.updateInterval()) : UpdateInterval.NEVER;
|
| 1140 | ChunkMap.TrackedEntity trackedEntity = new ChunkMap.TrackedEntity(entity, range, updateInterval, type.trackDeltas());
|
| 1141 | this.entityMap.put(entity.getId(), trackedEntity);
|
| 1142 | trackedEntity.updatePlayers(this.level.players());
|
| 1143 | if (entity instanceof ServerPlayer player) {
|
| 1144 | this.updatePlayerStatus(player, true);
|
| 1145 |
|
| 1146 | for (ChunkMap.TrackedEntity e : this.entityMap.values()) {
|
| 1147 | if (e.entity != player) {
|
| 1148 | e.updatePlayer(player);
|
| 1149 | }
|
| 1150 | }
|
| 1151 | }
|
| 1152 | }
|
| 1153 | }
|
| 1154 | }
|
| 1155 |
|
| 1156 | protected void removeEntity(final Entity entity) {
|
| 1157 | if (entity instanceof ServerPlayer player) {
|
| 1158 | this.updatePlayerStatus(player, false);
|
| 1159 |
|
| 1160 | for (ChunkMap.TrackedEntity trackedEntity : this.entityMap.values()) {
|
| 1161 | trackedEntity.removePlayer(player);
|
| 1162 | }
|
| 1163 | }
|
| 1164 |
|
| 1165 | ChunkMap.TrackedEntity trackedEntity = this.entityMap.remove(entity.getId());
|
| 1166 | if (trackedEntity != null) {
|
| 1167 | trackedEntity.broadcastRemoved();
|
| 1168 | }
|
| 1169 | }
|
| 1170 |
|
| 1171 | protected void tick() {
|
| 1172 | for (ServerPlayer player : this.playerMap.getAllPlayers()) {
|
| 1173 | this.updateChunkTracking(player);
|
| 1174 | }
|
| 1175 |
|
| 1176 | List<ServerPlayer> movedPlayers = Lists.newArrayList();
|
| 1177 | List<ServerPlayer> players = this.level.players();
|
| 1178 |
|
| 1179 | for (ChunkMap.TrackedEntity trackedEntity : this.entityMap.values()) {
|
| 1180 | SectionPos oldPos = trackedEntity.lastSectionPos;
|
| 1181 | SectionPos newPos = SectionPos.of(trackedEntity.entity);
|
| 1182 | boolean sectionPosChanged = !Objects.equals(oldPos, newPos);
|
| 1183 | if (sectionPosChanged) {
|
| 1184 | trackedEntity.updatePlayers(players);
|
| 1185 | if (trackedEntity.entity instanceof ServerPlayer serverPlayer) {
|
| 1186 | movedPlayers.add(serverPlayer);
|
| 1187 | }
|
| 1188 |
|
| 1189 | trackedEntity.lastSectionPos = newPos;
|
| 1190 | }
|
| 1191 |
|
| 1192 | if (sectionPosChanged || trackedEntity.entity.needsSync || this.distanceManager.inEntityTickingRange(newPos.chunk().pack())) {
|
| 1193 | trackedEntity.serverEntity.sendChanges();
|
| 1194 | }
|
| 1195 | }
|
| 1196 |
|
| 1197 | if (!movedPlayers.isEmpty()) {
|
| 1198 | for (ChunkMap.TrackedEntity trackedEntity : this.entityMap.values()) {
|
| 1199 | trackedEntity.updatePlayers(movedPlayers);
|
| 1200 | }
|
| 1201 | }
|
| 1202 | }
|
| 1203 |
|
| 1204 | public void sendToTrackingPlayers(final Entity entity, final Packet<? super ClientGamePacketListener> packet) {
|
| 1205 | ChunkMap.TrackedEntity trackedEntity = this.entityMap.get(entity.getId());
|
| 1206 | if (trackedEntity != null) {
|
| 1207 | trackedEntity.sendToTrackingPlayers(packet);
|
| 1208 | }
|
| 1209 | }
|
| 1210 |
|
| 1211 | public void sendToTrackingPlayersFiltered(
|
| 1212 | final Entity entity, final Packet<? super ClientGamePacketListener> packet, final Predicate<ServerPlayer> targetPredicate
|
| 1213 | ) {
|
| 1214 | ChunkMap.TrackedEntity trackedEntity = this.entityMap.get(entity.getId());
|
| 1215 | if (trackedEntity != null) {
|
| 1216 | trackedEntity.sendToTrackingPlayersFiltered(packet, targetPredicate);
|
| 1217 | }
|
| 1218 | }
|
| 1219 |
|
| 1220 | protected void sendToTrackingPlayersAndSelf(final Entity entity, final Packet<? super ClientGamePacketListener> packet) {
|
| 1221 | ChunkMap.TrackedEntity trackedEntity = this.entityMap.get(entity.getId());
|
| 1222 | if (trackedEntity != null) {
|
| 1223 | trackedEntity.sendToTrackingPlayersAndSelf(packet);
|
| 1224 | }
|
| 1225 | }
|
| 1226 |
|
| 1227 | public boolean isTrackedByAnyPlayer(final Entity entity) {
|
| 1228 | ChunkMap.TrackedEntity trackedEntity = this.entityMap.get(entity.getId());
|
| 1229 | return trackedEntity != null ? !trackedEntity.seenBy.isEmpty() : false;
|
| 1230 | }
|
| 1231 |
|
| 1232 | public void forEachEntityTrackedBy(final ServerPlayer player, final Consumer<Entity> consumer) {
|
| 1233 | for (ChunkMap.TrackedEntity entity : this.entityMap.values()) {
|
| 1234 | if (entity.seenBy.contains(player.connection)) {
|
| 1235 | consumer.accept(entity.entity);
|
| 1236 | }
|
| 1237 | }
|
| 1238 | }
|
| 1239 |
|
| 1240 | public void resendBiomesForChunks(final List<ChunkAccess> chunks) {
|
| 1241 | Map<ServerPlayer, List<LevelChunk>> chunksForPlayers = new HashMap<>();
|
| 1242 |
|
| 1243 | for (ChunkAccess chunkAccess : chunks) {
|
| 1244 | ChunkPos pos = chunkAccess.getPos();
|
| 1245 | LevelChunk chunk;
|
| 1246 | if (chunkAccess instanceof LevelChunk levelChunk) {
|
| 1247 | chunk = levelChunk;
|
| 1248 | } else {
|
| 1249 | chunk = this.level.getChunk(pos.x(), pos.z());
|
| 1250 | }
|
| 1251 |
|
| 1252 | for (ServerPlayer player : this.getPlayers(pos, false)) {
|
| 1253 | chunksForPlayers.computeIfAbsent(player, p -> new ArrayList<>()).add(chunk);
|
| 1254 | }
|
| 1255 | }
|
| 1256 |
|
| 1257 | chunksForPlayers.forEach((playerx, chunkList) -> playerx.connection.send(ClientboundChunksBiomesPacket.forChunks((List<LevelChunk>)chunkList)));
|
| 1258 | }
|
| 1259 |
|
| 1260 | protected PoiManager getPoiManager() {
|
| 1261 | return this.poiManager;
|
| 1262 | }
|
| 1263 |
|
| 1264 | void onFullChunkStatusChange(final ChunkPos pos, final FullChunkStatus status) {
|
| 1265 | this.chunkStatusListener.onChunkStatusChange(pos, status);
|
| 1266 | }
|
| 1267 |
|
| 1268 | public void waitForLightBeforeSending(final ChunkPos centerChunk, final int chunkRadius) {
|
| 1269 | int affectedLightChunkRadius = chunkRadius + 1;
|
| 1270 | ChunkPos.rangeClosed(centerChunk, affectedLightChunkRadius).forEach(chunkPos -> {
|
| 1271 | ChunkHolder chunkHolder = this.getVisibleChunkIfPresent(chunkPos.pack());
|
| 1272 | if (chunkHolder != null) {
|
| 1273 | chunkHolder.addSendDependency(this.lightEngine.waitForPendingTasks(chunkPos.x(), chunkPos.z()));
|
| 1274 | }
|
| 1275 | });
|
| 1276 | }
|
| 1277 |
|
| 1278 | public void forEachReadyToSendChunk(final Consumer<LevelChunk> consumer) {
|
| 1279 | for (ChunkHolder chunkHolder : this.visibleChunkMap.values()) {
|
| 1280 | LevelChunk chunk = chunkHolder.getChunkToSend();
|
| 1281 | if (chunk != null) {
|
| 1282 | consumer.accept(chunk);
|
| 1283 | }
|
| 1284 | }
|
| 1285 | }
|
| 1286 |
|
| 1287 | private class DistanceManager extends net.minecraft.server.level.DistanceManager {
|
| 1288 | protected DistanceManager(final TicketStorage ticketStorage, final Executor executor, final Executor mainThreadExecutor) {
|
| 1289 | super(ticketStorage, executor, mainThreadExecutor);
|
| 1290 | }
|
| 1291 |
|
| 1292 | @Override
|
| 1293 | protected boolean isChunkToRemove(final long node) {
|
| 1294 | return ChunkMap.this.toDrop.contains(node);
|
| 1295 | }
|
| 1296 |
|
| 1297 | @Override
|
| 1298 | protected @Nullable ChunkHolder getChunk(final long node) {
|
| 1299 | return ChunkMap.this.getUpdatingChunkIfPresent(node);
|
| 1300 | }
|
| 1301 |
|
| 1302 | @Override
|
| 1303 | protected @Nullable ChunkHolder updateChunkScheduling(final long node, final int level, final @Nullable ChunkHolder chunk, final int oldLevel) {
|
| 1304 | return ChunkMap.this.updateChunkScheduling(node, level, chunk, oldLevel);
|
| 1305 | }
|
| 1306 | }
|
| 1307 |
|
| 1308 | private class TrackedEntity implements ServerEntity.Synchronizer {
|
| 1309 | private final ServerEntity serverEntity;
|
| 1310 | private final Entity entity;
|
| 1311 | private final int range;
|
| 1312 | private SectionPos lastSectionPos;
|
| 1313 | private final Set<ServerPlayerConnection> seenBy = Sets.newIdentityHashSet();
|
| 1314 |
|
| 1315 | public TrackedEntity(final Entity entity, final int range, final UpdateInterval updateInterval, final boolean trackDelta) {
|
| 1316 | this.serverEntity = new ServerEntity(ChunkMap.this.level, entity, updateInterval, trackDelta, this);
|
| 1317 | this.entity = entity;
|
| 1318 | this.range = range;
|
| 1319 | this.lastSectionPos = SectionPos.of(entity);
|
| 1320 | }
|
| 1321 |
|
| 1322 | @Override
|
| 1323 | public boolean equals(final Object obj) {
|
| 1324 | return obj instanceof ChunkMap.TrackedEntity trackedEntity ? trackedEntity.entity.getId() == this.entity.getId() : false;
|
| 1325 | }
|
| 1326 |
|
| 1327 | @Override
|
| 1328 | public int hashCode() {
|
| 1329 | return this.entity.getId();
|
| 1330 | }
|
| 1331 |
|
| 1332 | @Override
|
| 1333 | public void sendToTrackingPlayers(final Packet<? super ClientGamePacketListener> packet) {
|
| 1334 | for (ServerPlayerConnection connection : this.seenBy) {
|
| 1335 | connection.send(packet);
|
| 1336 | }
|
| 1337 | }
|
| 1338 |
|
| 1339 | @Override
|
| 1340 | public void sendToTrackingPlayersAndSelf(final Packet<? super ClientGamePacketListener> packet) {
|
| 1341 | this.sendToTrackingPlayers(packet);
|
| 1342 | if (this.entity instanceof ServerPlayer player) {
|
| 1343 | player.connection.send(packet);
|
| 1344 | }
|
| 1345 | }
|
| 1346 |
|
| 1347 | @Override
|
| 1348 | public void sendToTrackingPlayersFiltered(final Packet<? super ClientGamePacketListener> packet, final Predicate<ServerPlayer> targetPredicate) {
|
| 1349 | for (ServerPlayerConnection connection : this.seenBy) {
|
| 1350 | if (targetPredicate.test(connection.getPlayer())) {
|
| 1351 | connection.send(packet);
|
| 1352 | }
|
| 1353 | }
|
| 1354 | }
|
| 1355 |
|
| 1356 | public void broadcastRemoved() {
|
| 1357 | for (ServerPlayerConnection connection : this.seenBy) {
|
| 1358 | this.serverEntity.removePairing(connection.getPlayer());
|
| 1359 | }
|
| 1360 | }
|
| 1361 |
|
| 1362 | public void removePlayer(final ServerPlayer player) {
|
| 1363 | if (this.seenBy.remove(player.connection)) {
|
| 1364 | this.serverEntity.removePairing(player);
|
| 1365 | if (this.seenBy.isEmpty()) {
|
| 1366 | ChunkMap.this.level.debugSynchronizers().dropEntity(this.entity);
|
| 1367 | }
|
| 1368 | }
|
| 1369 | }
|
| 1370 |
|
| 1371 | public void updatePlayer(final ServerPlayer player) {
|
| 1372 | if (player != this.entity) {
|
| 1373 | Vec3 deltaToPlayer = player.position().subtract(this.entity.position());
|
| 1374 | int playerViewDistance = ChunkMap.this.getPlayerViewDistance(player);
|
| 1375 | double visibleRange = Math.min(this.getEffectiveRange(), playerViewDistance * 16);
|
| 1376 | double distanceSquared = deltaToPlayer.x * deltaToPlayer.x + deltaToPlayer.z * deltaToPlayer.z;
|
| 1377 | double rangeSquared = visibleRange * visibleRange;
|
| 1378 | boolean visibleToPlayer = distanceSquared <= rangeSquared
|
| 1379 | && this.entity.broadcastToPlayer(player)
|
| 1380 | && ChunkMap.this.isChunkTracked(player, this.entity.chunkPosition().x(), this.entity.chunkPosition().z());
|
| 1381 | if (visibleToPlayer) {
|
| 1382 | if (this.seenBy.add(player.connection)) {
|
| 1383 | this.serverEntity.addPairing(player);
|
| 1384 | if (this.seenBy.size() == 1) {
|
| 1385 | ChunkMap.this.level.debugSynchronizers().registerEntity(this.entity);
|
| 1386 | }
|
| 1387 |
|
| 1388 | ChunkMap.this.level.debugSynchronizers().startTrackingEntity(player, this.entity);
|
| 1389 | }
|
| 1390 | } else {
|
| 1391 | this.removePlayer(player);
|
| 1392 | }
|
| 1393 | }
|
| 1394 | }
|
| 1395 |
|
| 1396 | private int scaledRange(final int range) {
|
| 1397 | return ChunkMap.this.level.getServer().getScaledTrackingDistance(range);
|
| 1398 | }
|
| 1399 |
|
| 1400 | private int getEffectiveRange() {
|
| 1401 | int effectiveRange = this.range;
|
| 1402 |
|
| 1403 | for (Entity passenger : this.entity.getIndirectPassengers()) {
|
| 1404 | int passengerRange = passenger.getType().clientTrackingRange() * 16;
|
| 1405 | if (passengerRange > effectiveRange) {
|
| 1406 | effectiveRange = passengerRange;
|
| 1407 | }
|
| 1408 | }
|
| 1409 |
|
| 1410 | return this.scaledRange(effectiveRange);
|
| 1411 | }
|
| 1412 |
|
| 1413 | public void updatePlayers(final List<ServerPlayer> players) {
|
| 1414 | for (ServerPlayer player : players) {
|
| 1415 | this.updatePlayer(player);
|
| 1416 | }
|
| 1417 | }
|
| 1418 | }
|
| 1419 | }
|
| 1420 |
|