| 1 | package net.minecraft.server.level;
|
| 2 |
|
| 3 | import com.mojang.datafixers.util.Pair;
|
| 4 | import java.util.ArrayList;
|
| 5 | import java.util.List;
|
| 6 | import java.util.Objects;
|
| 7 | import java.util.concurrent.CompletableFuture;
|
| 8 | import java.util.concurrent.atomic.AtomicInteger;
|
| 9 | import java.util.concurrent.atomic.AtomicReference;
|
| 10 | import java.util.concurrent.atomic.AtomicReferenceArray;
|
| 11 | import net.minecraft.CrashReport;
|
| 12 | import net.minecraft.util.StaticCache2D;
|
| 13 | import net.minecraft.util.VisibleForDebug;
|
| 14 | import net.minecraft.util.thread.BlockableEventLoop;
|
| 15 | import net.minecraft.world.level.ChunkPos;
|
| 16 | import net.minecraft.world.level.chunk.ChunkAccess;
|
| 17 | import net.minecraft.world.level.chunk.ImposterProtoChunk;
|
| 18 | import net.minecraft.world.level.chunk.ProtoChunk;
|
| 19 | import net.minecraft.world.level.chunk.status.ChunkStatus;
|
| 20 | import net.minecraft.world.level.chunk.status.ChunkStep;
|
| 21 | import org.jspecify.annotations.Nullable;
|
| 22 |
|
| 23 | public abstract class GenerationChunkHolder {
|
| 24 | private static final List<ChunkStatus> CHUNK_STATUSES = ChunkStatus.getStatusList();
|
| 25 | private static final ChunkResult<ChunkAccess> NOT_DONE_YET = ChunkResult.error("Not done yet");
|
| 26 | public static final ChunkResult<ChunkAccess> UNLOADED_CHUNK = ChunkResult.error("Unloaded chunk");
|
| 27 | public static final CompletableFuture<ChunkResult<ChunkAccess>> UNLOADED_CHUNK_FUTURE = CompletableFuture.completedFuture(UNLOADED_CHUNK);
|
| 28 | protected final ChunkPos pos;
|
| 29 | private volatile @Nullable ChunkStatus highestAllowedStatus;
|
| 30 | private final AtomicReference<@Nullable ChunkStatus> startedWork = new AtomicReference<>();
|
| 31 | private final AtomicReferenceArray<@Nullable CompletableFuture<ChunkResult<ChunkAccess>>> futures = new AtomicReferenceArray<>(CHUNK_STATUSES.size());
|
| 32 | private final AtomicReference<@Nullable ChunkGenerationTask> task = new AtomicReference<>();
|
| 33 | private final AtomicInteger generationRefCount = new AtomicInteger();
|
| 34 | private volatile CompletableFuture<Void> generationSaveSyncFuture = CompletableFuture.completedFuture(null);
|
| 35 |
|
| 36 | public GenerationChunkHolder(final ChunkPos pos) {
|
| 37 | this.pos = pos;
|
| 38 | if (!pos.isValid()) {
|
| 39 | throw new IllegalStateException("Trying to create chunk out of reasonable bounds: " + pos);
|
| 40 | }
|
| 41 | }
|
| 42 |
|
| 43 | public CompletableFuture<ChunkResult<ChunkAccess>> scheduleChunkGenerationTask(final ChunkStatus status, final ChunkMap scheduler) {
|
| 44 | if (this.isStatusDisallowed(status)) {
|
| 45 | return UNLOADED_CHUNK_FUTURE;
|
| 46 | }
|
| 47 |
|
| 48 | CompletableFuture<ChunkResult<ChunkAccess>> future = this.getOrCreateFuture(status);
|
| 49 | if (future.isDone()) {
|
| 50 | return future;
|
| 51 | }
|
| 52 |
|
| 53 | ChunkGenerationTask task = this.task.get();
|
| 54 | if (task == null || status.isAfter(task.targetStatus)) {
|
| 55 | this.rescheduleChunkTask(scheduler, status);
|
| 56 | }
|
| 57 |
|
| 58 | return future;
|
| 59 | }
|
| 60 |
|
| 61 | CompletableFuture<ChunkResult<ChunkAccess>> applyStep(
|
| 62 | final ChunkStep step, final GeneratingChunkMap chunkMap, final StaticCache2D<GenerationChunkHolder> cache
|
| 63 | ) {
|
| 64 | if (this.isStatusDisallowed(step.targetStatus())) {
|
| 65 | return UNLOADED_CHUNK_FUTURE;
|
| 66 | } else {
|
| 67 | return this.acquireStatusBump(step.targetStatus()) ? chunkMap.applyStep(this, step, cache).handle((chunk, exception) -> {
|
| 68 | if (exception != null) {
|
| 69 | CrashReport report = CrashReport.forThrowable(exception, "Exception chunk generation/loading");
|
| 70 | BlockableEventLoop.relayDelayCrash(report);
|
| 71 | } else {
|
| 72 | this.completeFuture(step.targetStatus(), chunk);
|
| 73 | }
|
| 74 |
|
| 75 | return ChunkResult.of(chunk);
|
| 76 | }) : this.getOrCreateFuture(step.targetStatus());
|
| 77 | }
|
| 78 | }
|
| 79 |
|
| 80 | protected void updateHighestAllowedStatus(final ChunkMap scheduler) {
|
| 81 | ChunkStatus oldStatus = this.highestAllowedStatus;
|
| 82 | ChunkStatus newStatus = ChunkLevel.generationStatus(this.getTicketLevel());
|
| 83 | this.highestAllowedStatus = newStatus;
|
| 84 | boolean statusDropped = oldStatus != null && (newStatus == null || newStatus.isBefore(oldStatus));
|
| 85 | if (statusDropped) {
|
| 86 | this.failAndClearPendingFuturesBetween(newStatus, oldStatus);
|
| 87 | if (this.task.get() != null) {
|
| 88 | this.rescheduleChunkTask(scheduler, this.findHighestStatusWithPendingFuture(newStatus));
|
| 89 | }
|
| 90 | }
|
| 91 | }
|
| 92 |
|
| 93 | public void replaceProtoChunk(final ImposterProtoChunk chunk) {
|
| 94 | CompletableFuture<ChunkResult<ChunkAccess>> imposterFuture = CompletableFuture.completedFuture(ChunkResult.of(chunk));
|
| 95 |
|
| 96 | for (int i = 0; i < this.futures.length() - 1; i++) {
|
| 97 | CompletableFuture<ChunkResult<ChunkAccess>> future = this.futures.get(i);
|
| 98 | Objects.requireNonNull(future);
|
| 99 | ChunkAccess maybeProtoChunk = future.getNow(NOT_DONE_YET).orElse(null);
|
| 100 | if (!(maybeProtoChunk instanceof ProtoChunk)) {
|
| 101 | throw new IllegalStateException("Trying to replace a ProtoChunk, but found " + maybeProtoChunk);
|
| 102 | }
|
| 103 |
|
| 104 | if (!this.futures.compareAndSet(i, future, imposterFuture)) {
|
| 105 | throw new IllegalStateException("Future changed by other thread while trying to replace it");
|
| 106 | }
|
| 107 | }
|
| 108 | }
|
| 109 |
|
| 110 | void removeTask(final ChunkGenerationTask task) {
|
| 111 | this.task.compareAndSet(task, null);
|
| 112 | }
|
| 113 |
|
| 114 | private void rescheduleChunkTask(final ChunkMap scheduler, final @Nullable ChunkStatus status) {
|
| 115 | ChunkGenerationTask newTask;
|
| 116 | if (status != null) {
|
| 117 | newTask = scheduler.scheduleGenerationTask(status, this.getPos());
|
| 118 | } else {
|
| 119 | newTask = null;
|
| 120 | }
|
| 121 |
|
| 122 | ChunkGenerationTask oldTask = this.task.getAndSet(newTask);
|
| 123 | if (oldTask != null) {
|
| 124 | oldTask.markForCancellation();
|
| 125 | }
|
| 126 | }
|
| 127 |
|
| 128 | private CompletableFuture<ChunkResult<ChunkAccess>> getOrCreateFuture(final ChunkStatus status) {
|
| 129 | if (this.isStatusDisallowed(status)) {
|
| 130 | return UNLOADED_CHUNK_FUTURE;
|
| 131 | }
|
| 132 |
|
| 133 | int index = status.getIndex();
|
| 134 | CompletableFuture<ChunkResult<ChunkAccess>> future = this.futures.get(index);
|
| 135 |
|
| 136 | while (future == null) {
|
| 137 | CompletableFuture<ChunkResult<ChunkAccess>> newValue = new CompletableFuture<>();
|
| 138 | future = this.futures.compareAndExchange(index, null, newValue);
|
| 139 | if (future == null) {
|
| 140 | if (this.isStatusDisallowed(status)) {
|
| 141 | this.failAndClearPendingFuture(index, newValue);
|
| 142 | return UNLOADED_CHUNK_FUTURE;
|
| 143 | }
|
| 144 |
|
| 145 | return newValue;
|
| 146 | }
|
| 147 | }
|
| 148 |
|
| 149 | return future;
|
| 150 | }
|
| 151 |
|
| 152 | private void failAndClearPendingFuturesBetween(final @Nullable ChunkStatus fromExclusive, final ChunkStatus toInclusive) {
|
| 153 | int start = fromExclusive == null ? 0 : fromExclusive.getIndex() + 1;
|
| 154 | int end = toInclusive.getIndex();
|
| 155 |
|
| 156 | for (int i = start; i <= end; i++) {
|
| 157 | CompletableFuture<ChunkResult<ChunkAccess>> previous = this.futures.get(i);
|
| 158 | if (previous != null) {
|
| 159 | this.failAndClearPendingFuture(i, previous);
|
| 160 | }
|
| 161 | }
|
| 162 | }
|
| 163 |
|
| 164 | private void failAndClearPendingFuture(final int index, final CompletableFuture<ChunkResult<ChunkAccess>> previous) {
|
| 165 | if (previous.complete(UNLOADED_CHUNK) && !this.futures.compareAndSet(index, previous, null)) {
|
| 166 | throw new IllegalStateException("Nothing else should replace the future here");
|
| 167 | }
|
| 168 | }
|
| 169 |
|
| 170 | private void completeFuture(final ChunkStatus status, final ChunkAccess chunk) {
|
| 171 | ChunkResult<ChunkAccess> result = ChunkResult.of(chunk);
|
| 172 | int index = status.getIndex();
|
| 173 |
|
| 174 | while (true) {
|
| 175 | CompletableFuture<ChunkResult<ChunkAccess>> future = this.futures.get(index);
|
| 176 | if (future == null) {
|
| 177 | if (this.futures.compareAndSet(index, null, CompletableFuture.completedFuture(result))) {
|
| 178 | return;
|
| 179 | }
|
| 180 | } else {
|
| 181 | if (future.complete(result)) {
|
| 182 | return;
|
| 183 | }
|
| 184 |
|
| 185 | if (future.getNow(NOT_DONE_YET).isSuccess()) {
|
| 186 | throw new IllegalStateException("Trying to complete a future but found it to be completed successfully already");
|
| 187 | }
|
| 188 |
|
| 189 | Thread.yield();
|
| 190 | }
|
| 191 | }
|
| 192 | }
|
| 193 |
|
| 194 | private @Nullable ChunkStatus findHighestStatusWithPendingFuture(final @Nullable ChunkStatus newStatus) {
|
| 195 | if (newStatus == null) {
|
| 196 | return null;
|
| 197 | }
|
| 198 |
|
| 199 | ChunkStatus highestStatus = newStatus;
|
| 200 |
|
| 201 | for (ChunkStatus alreadyStarted = this.startedWork.get();
|
| 202 | alreadyStarted == null || highestStatus.isAfter(alreadyStarted);
|
| 203 | highestStatus = highestStatus.getParent()
|
| 204 | ) {
|
| 205 | if (this.futures.get(highestStatus.getIndex()) != null) {
|
| 206 | return highestStatus;
|
| 207 | }
|
| 208 |
|
| 209 | if (highestStatus == ChunkStatus.EMPTY) {
|
| 210 | break;
|
| 211 | }
|
| 212 | }
|
| 213 |
|
| 214 | return null;
|
| 215 | }
|
| 216 |
|
| 217 | private boolean acquireStatusBump(final ChunkStatus status) {
|
| 218 | ChunkStatus parent = status == ChunkStatus.EMPTY ? null : status.getParent();
|
| 219 | ChunkStatus previousStarted = this.startedWork.compareAndExchange(parent, status);
|
| 220 | if (previousStarted == parent) {
|
| 221 | return true;
|
| 222 | } else if (previousStarted != null && !status.isAfter(previousStarted)) {
|
| 223 | return false;
|
| 224 | } else {
|
| 225 | throw new IllegalStateException("Unexpected last startedWork status: " + previousStarted + " while trying to start: " + status);
|
| 226 | }
|
| 227 | }
|
| 228 |
|
| 229 | private boolean isStatusDisallowed(final ChunkStatus status) {
|
| 230 | ChunkStatus highestAllowedStatus = this.highestAllowedStatus;
|
| 231 | return highestAllowedStatus == null || status.isAfter(highestAllowedStatus);
|
| 232 | }
|
| 233 |
|
| 234 | protected abstract void addSaveDependency(final CompletableFuture<?> sync);
|
| 235 |
|
| 236 | public void increaseGenerationRefCount() {
|
| 237 | if (this.generationRefCount.getAndIncrement() == 0) {
|
| 238 | this.generationSaveSyncFuture = new CompletableFuture<>();
|
| 239 | this.addSaveDependency(this.generationSaveSyncFuture);
|
| 240 | }
|
| 241 | }
|
| 242 |
|
| 243 | public void decreaseGenerationRefCount() {
|
| 244 | CompletableFuture<Void> future = this.generationSaveSyncFuture;
|
| 245 | int newValue = this.generationRefCount.decrementAndGet();
|
| 246 | if (newValue == 0) {
|
| 247 | future.complete(null);
|
| 248 | }
|
| 249 |
|
| 250 | if (newValue < 0) {
|
| 251 | throw new IllegalStateException("More releases than claims. Count: " + newValue);
|
| 252 | }
|
| 253 | }
|
| 254 |
|
| 255 | public @Nullable ChunkAccess getChunkIfPresentUnchecked(final ChunkStatus status) {
|
| 256 | CompletableFuture<ChunkResult<ChunkAccess>> future = this.futures.get(status.getIndex());
|
| 257 | return future == null ? null : future.getNow(NOT_DONE_YET).orElse(null);
|
| 258 | }
|
| 259 |
|
| 260 | public @Nullable ChunkAccess getChunkIfPresent(final ChunkStatus status) {
|
| 261 | return this.isStatusDisallowed(status) ? null : this.getChunkIfPresentUnchecked(status);
|
| 262 | }
|
| 263 |
|
| 264 | public @Nullable ChunkAccess getLatestChunk() {
|
| 265 | ChunkStatus status = this.startedWork.get();
|
| 266 | if (status == null) {
|
| 267 | return null;
|
| 268 | }
|
| 269 |
|
| 270 | ChunkAccess chunk = this.getChunkIfPresentUnchecked(status);
|
| 271 | return chunk != null ? chunk : this.getChunkIfPresentUnchecked(status.getParent());
|
| 272 | }
|
| 273 |
|
| 274 | public @Nullable ChunkStatus getPersistedStatus() {
|
| 275 | CompletableFuture<ChunkResult<ChunkAccess>> future = this.futures.get(ChunkStatus.EMPTY.getIndex());
|
| 276 | ChunkAccess chunkAccess = future == null ? null : future.getNow(NOT_DONE_YET).orElse(null);
|
| 277 | return chunkAccess == null ? null : chunkAccess.getPersistedStatus();
|
| 278 | }
|
| 279 |
|
| 280 | public ChunkPos getPos() {
|
| 281 | return this.pos;
|
| 282 | }
|
| 283 |
|
| 284 | public FullChunkStatus getFullStatus() {
|
| 285 | return ChunkLevel.fullStatus(this.getTicketLevel());
|
| 286 | }
|
| 287 |
|
| 288 | public abstract int getTicketLevel();
|
| 289 |
|
| 290 | public abstract int getQueueLevel();
|
| 291 |
|
| 292 | @VisibleForDebug
|
| 293 | public List<Pair<ChunkStatus, @Nullable CompletableFuture<ChunkResult<ChunkAccess>>>> getAllFutures() {
|
| 294 | List<Pair<ChunkStatus, CompletableFuture<ChunkResult<ChunkAccess>>>> result = new ArrayList<>();
|
| 295 |
|
| 296 | for (int i = 0; i < CHUNK_STATUSES.size(); i++) {
|
| 297 | result.add(Pair.of(CHUNK_STATUSES.get(i), this.futures.get(i)));
|
| 298 | }
|
| 299 |
|
| 300 | return result;
|
| 301 | }
|
| 302 |
|
| 303 | @VisibleForDebug
|
| 304 | public @Nullable ChunkStatus getLatestStatus() {
|
| 305 | ChunkStatus status = this.startedWork.get();
|
| 306 | if (status == null) {
|
| 307 | return null;
|
| 308 | }
|
| 309 |
|
| 310 | ChunkAccess chunk = this.getChunkIfPresentUnchecked(status);
|
| 311 | return chunk != null ? status : status.getParent();
|
| 312 | }
|
| 313 | }
|
| 314 |
|