mirror of
https://github.com/VolmitSoftware/Iris.git
synced 2026-08-27 04:37:47 +00:00
d
This commit is contained in:
+130
@@ -0,0 +1,130 @@
|
||||
package art.arcane.iris.core.nms.v26_2_R1;
|
||||
|
||||
import art.arcane.iris.core.lifecycle.WorldReplacementSeed;
|
||||
import art.arcane.iris.util.common.scheduling.J;
|
||||
import io.papermc.paper.world.saveddata.PaperLevelOverrides;
|
||||
import io.papermc.paper.world.saveddata.PaperWorldMetadata;
|
||||
import net.minecraft.server.MinecraftServer;
|
||||
import net.minecraft.world.level.storage.PrimaryLevelData;
|
||||
import net.minecraft.world.level.storage.SavedDataStorage;
|
||||
import org.bukkit.Bukkit;
|
||||
import org.bukkit.craftbukkit.CraftServer;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.LinkOption;
|
||||
import java.nio.file.Path;
|
||||
import java.util.List;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.ExecutionException;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.concurrent.TimeoutException;
|
||||
|
||||
final class CurrentPaperWorldDataWriter {
|
||||
private static final long SNAPSHOT_TIMEOUT_SECONDS = 30L;
|
||||
|
||||
private CurrentPaperWorldDataWriter() {
|
||||
}
|
||||
|
||||
static void write(
|
||||
Path sourceWorldDirectory,
|
||||
Path targetWorldDirectory,
|
||||
long seed
|
||||
) throws IOException {
|
||||
CraftServer craftServer = (CraftServer) Bukkit.getServer();
|
||||
MinecraftServer server = craftServer.getHandle().getServer();
|
||||
PaperLevelOverrides levelOverrides = captureLevelOverrides(craftServer, server);
|
||||
|
||||
Path targetWorld = targetWorldDirectory.toAbsolutePath().normalize();
|
||||
UUID metadataUuid = UUID.randomUUID();
|
||||
WorldReplacementSeed.copyWithAuthoritativeSeed(sourceWorldDirectory, targetWorld, seed);
|
||||
try (SavedDataStorage savedDataStorage = new SavedDataStorage(
|
||||
targetWorld.resolve("data"),
|
||||
server.getFixerUpper(),
|
||||
server.registryAccess()
|
||||
)) {
|
||||
savedDataStorage.set(PaperWorldMetadata.TYPE, new PaperWorldMetadata(metadataUuid));
|
||||
savedDataStorage.set(PaperLevelOverrides.TYPE, levelOverrides);
|
||||
}
|
||||
|
||||
List<Path> requiredDataFiles = List.of(
|
||||
targetWorld.resolve("data/minecraft/world_gen_settings.dat"),
|
||||
targetWorld.resolve("data/paper/metadata.dat"),
|
||||
targetWorld.resolve("data/paper/level_overrides.dat")
|
||||
);
|
||||
for (Path requiredDataFile : requiredDataFiles) {
|
||||
if (!Files.isRegularFile(requiredDataFile, LinkOption.NOFOLLOW_LINKS)) {
|
||||
throw new IOException("Current Paper world data was not written: " + requiredDataFile);
|
||||
}
|
||||
}
|
||||
|
||||
long writtenSeed = WorldReplacementSeed.readAuthoritativeSeed(targetWorld);
|
||||
if (writtenSeed != seed) {
|
||||
throw new IOException("Current Paper world data did not retain the requested seed.");
|
||||
}
|
||||
|
||||
try (SavedDataStorage verificationStorage = new SavedDataStorage(
|
||||
targetWorld.resolve("data"),
|
||||
server.getFixerUpper(),
|
||||
server.registryAccess()
|
||||
)) {
|
||||
PaperWorldMetadata metadata = verificationStorage.get(PaperWorldMetadata.TYPE);
|
||||
if (metadata == null || !metadataUuid.equals(metadata.uuid())) {
|
||||
throw new IOException("Current Paper world metadata could not be verified.");
|
||||
}
|
||||
PaperLevelOverrides overrides = verificationStorage.get(PaperLevelOverrides.TYPE);
|
||||
if (overrides == null || overrides.isInitialized()) {
|
||||
throw new IOException("Current Paper level overrides could not be verified.");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static PaperLevelOverrides captureLevelOverrides(
|
||||
CraftServer craftServer,
|
||||
MinecraftServer server
|
||||
) throws IOException {
|
||||
if (craftServer.isGlobalTickThread()) {
|
||||
return createLevelOverrides(craftServer, server);
|
||||
}
|
||||
if (J.isFolia() && J.isPrimaryThread()) {
|
||||
throw new IOException("Current Paper world data cannot be staged from a Folia region tick thread.");
|
||||
}
|
||||
|
||||
CompletableFuture<PaperLevelOverrides> captured = new CompletableFuture<>();
|
||||
boolean scheduled = J.runGlobal(() -> {
|
||||
try {
|
||||
captured.complete(createLevelOverrides(craftServer, server));
|
||||
} catch (Throwable failure) {
|
||||
captured.completeExceptionally(failure);
|
||||
}
|
||||
});
|
||||
if (!scheduled) {
|
||||
throw new IOException("Could not schedule the current Paper level-data snapshot on the global thread.");
|
||||
}
|
||||
|
||||
try {
|
||||
return captured.get(SNAPSHOT_TIMEOUT_SECONDS, TimeUnit.SECONDS);
|
||||
} catch (InterruptedException failure) {
|
||||
Thread.currentThread().interrupt();
|
||||
throw new IOException("Interrupted while capturing current Paper level data.", failure);
|
||||
} catch (ExecutionException failure) {
|
||||
throw new IOException("Could not capture current Paper level data.", failure.getCause());
|
||||
} catch (TimeoutException failure) {
|
||||
throw new IOException("Timed out while capturing current Paper level data.", failure);
|
||||
}
|
||||
}
|
||||
|
||||
private static PaperLevelOverrides createLevelOverrides(
|
||||
CraftServer craftServer,
|
||||
MinecraftServer server
|
||||
) throws IOException {
|
||||
if (!craftServer.isGlobalTickThread()) {
|
||||
throw new IOException("Current Paper level data must be captured on the global tick thread.");
|
||||
}
|
||||
if (!(server.getWorldData().overworldData() instanceof PrimaryLevelData primaryLevelData)) {
|
||||
throw new IOException("Paper primary level data is unavailable for current world data staging.");
|
||||
}
|
||||
return PaperLevelOverrides.createFromLiveLevelData(primaryLevelData);
|
||||
}
|
||||
}
|
||||
+122
-72
@@ -7,7 +7,6 @@ import net.minecraft.core.Holder;
|
||||
import net.minecraft.core.HolderOwner;
|
||||
import net.minecraft.core.Vec3i;
|
||||
import net.minecraft.resources.ResourceKey;
|
||||
import net.minecraft.world.level.chunk.ChunkGeneratorStructureState;
|
||||
import net.minecraft.world.level.levelgen.structure.StructureSet;
|
||||
import net.minecraft.world.level.levelgen.structure.placement.ConcentricRingsStructurePlacement;
|
||||
import net.minecraft.world.level.levelgen.structure.placement.RandomSpreadStructurePlacement;
|
||||
@@ -41,16 +40,31 @@ final class DatapackStructureStateFilter {
|
||||
DatapackStructureScopeIndex scopeIndex,
|
||||
Set<String> declaredSources,
|
||||
IrisImportedStructureControl importedStructures
|
||||
) {
|
||||
return filter(
|
||||
structureSets,
|
||||
scopeIndex,
|
||||
declaredSources,
|
||||
importedStructures,
|
||||
keyIndex(structureSets));
|
||||
}
|
||||
|
||||
static Selection filter(
|
||||
List<Holder<StructureSet>> structureSets,
|
||||
DatapackStructureScopeIndex scopeIndex,
|
||||
Set<String> declaredSources,
|
||||
IrisImportedStructureControl importedStructures,
|
||||
StructureSetKeyIndex keyIndex
|
||||
) {
|
||||
if (scopeIndex.isEmpty()) {
|
||||
return new Selection(
|
||||
scaleFrequencyOverrides(structureSets, importedStructures),
|
||||
scaleFrequencyOverrides(structureSets, importedStructures, keyIndex),
|
||||
0,
|
||||
0);
|
||||
}
|
||||
Map<String, Holder<StructureSet>> holdersByKey = new HashMap<>();
|
||||
for (Holder<StructureSet> holder : structureSets) {
|
||||
String key = structureSetKey(holder);
|
||||
String key = structureSetKey(holder, keyIndex);
|
||||
if (key != null) {
|
||||
holdersByKey.putIfAbsent(key, holder);
|
||||
}
|
||||
@@ -61,7 +75,7 @@ final class DatapackStructureStateFilter {
|
||||
int retainedManagedSets = 0;
|
||||
int excludedManagedSets = 0;
|
||||
for (Holder<StructureSet> holder : structureSets) {
|
||||
String setKey = structureSetKey(holder);
|
||||
String setKey = structureSetKey(holder, keyIndex);
|
||||
boolean managedSet = setKey != null && scopeIndex.isManagedStructureSet(setKey);
|
||||
Holder<StructureSet> scopedHolder = scopeHolder(
|
||||
holder,
|
||||
@@ -69,7 +83,8 @@ final class DatapackStructureStateFilter {
|
||||
declaredSources,
|
||||
holdersByKey,
|
||||
scopedByIdentity,
|
||||
visiting);
|
||||
visiting,
|
||||
keyIndex);
|
||||
if (scopedHolder == null) {
|
||||
if (managedSet) {
|
||||
excludedManagedSets++;
|
||||
@@ -82,21 +97,29 @@ final class DatapackStructureStateFilter {
|
||||
filteredSets.add(scopedHolder);
|
||||
}
|
||||
return new Selection(
|
||||
scaleFrequencyOverrides(List.copyOf(filteredSets), importedStructures),
|
||||
scaleFrequencyOverrides(
|
||||
List.copyOf(filteredSets), importedStructures, keyIndex),
|
||||
retainedManagedSets,
|
||||
excludedManagedSets);
|
||||
}
|
||||
|
||||
static String structureSetKey(Holder<StructureSet> holder) {
|
||||
Optional<ResourceKey<StructureSet>> key = holder.unwrapKey();
|
||||
if (key.isPresent()) {
|
||||
return key.get().identifier().toString();
|
||||
}
|
||||
if (holder.value().placement()
|
||||
instanceof ChunkGeneratorStructureState.KeyedRandomSpreadStructurePlacement keyedPlacement) {
|
||||
return keyedPlacement.key.identifier().toString();
|
||||
}
|
||||
return null;
|
||||
return structureSetKey(holder, keyIndex(List.of(holder)));
|
||||
}
|
||||
|
||||
static StructureSetKeyIndex keyIndex(
|
||||
Iterable<? extends Holder<StructureSet>> registeredStructureSets
|
||||
) {
|
||||
return StructureSetKeyIndex.create(registeredStructureSets);
|
||||
}
|
||||
|
||||
private static String structureSetKey(
|
||||
Holder<StructureSet> holder,
|
||||
StructureSetKeyIndex keyIndex
|
||||
) {
|
||||
return keyIndex.resolve(holder)
|
||||
.map(key -> key.identifier().toString())
|
||||
.orElse(null);
|
||||
}
|
||||
|
||||
private static List<StructureSet.StructureSelectionEntry> filterEntries(
|
||||
@@ -122,7 +145,8 @@ final class DatapackStructureStateFilter {
|
||||
Set<String> declaredSources,
|
||||
Map<String, Holder<StructureSet>> holdersByKey,
|
||||
Map<Holder<StructureSet>, Holder<StructureSet>> scopedByIdentity,
|
||||
Set<Holder<StructureSet>> visiting
|
||||
Set<Holder<StructureSet>> visiting,
|
||||
StructureSetKeyIndex keyIndex
|
||||
) {
|
||||
if (scopedByIdentity.containsKey(holder)) {
|
||||
return scopedByIdentity.get(holder);
|
||||
@@ -131,7 +155,7 @@ final class DatapackStructureStateFilter {
|
||||
return null;
|
||||
}
|
||||
try {
|
||||
String setKey = structureSetKey(holder);
|
||||
String setKey = structureSetKey(holder, keyIndex);
|
||||
if (setKey != null && scopeIndex.isManagedStructureSet(setKey)
|
||||
&& !scopeIndex.allowsStructureSet(setKey, declaredSources)) {
|
||||
scopedByIdentity.put(holder, null);
|
||||
@@ -150,14 +174,15 @@ final class DatapackStructureStateFilter {
|
||||
declaredSources,
|
||||
holdersByKey,
|
||||
scopedByIdentity,
|
||||
visiting);
|
||||
visiting,
|
||||
keyIndex);
|
||||
if (entries.size() == originalSet.structures().size()
|
||||
&& placement == originalSet.placement()) {
|
||||
scopedByIdentity.put(holder, holder);
|
||||
return holder;
|
||||
}
|
||||
Holder<StructureSet> scoped = replacementHolder(
|
||||
holder, new StructureSet(entries, placement));
|
||||
holder, new StructureSet(entries, placement), keyIndex);
|
||||
scopedByIdentity.put(holder, scoped);
|
||||
return scoped;
|
||||
} finally {
|
||||
@@ -184,7 +209,8 @@ final class DatapackStructureStateFilter {
|
||||
Set<String> declaredSources,
|
||||
Map<String, Holder<StructureSet>> holdersByKey,
|
||||
Map<Holder<StructureSet>, Holder<StructureSet>> scopedByIdentity,
|
||||
Set<Holder<StructureSet>> visiting
|
||||
Set<Holder<StructureSet>> visiting,
|
||||
StructureSetKeyIndex keyIndex
|
||||
) {
|
||||
Optional<StructurePlacement.ExclusionZone> currentZone = exclusionZone(placement);
|
||||
if (currentZone.isEmpty()) {
|
||||
@@ -192,7 +218,7 @@ final class DatapackStructureStateFilter {
|
||||
}
|
||||
|
||||
Holder<StructureSet> target = currentZone.get().otherSet();
|
||||
String targetKey = structureSetKey(target);
|
||||
String targetKey = structureSetKey(target, keyIndex);
|
||||
if (targetKey != null) {
|
||||
target = holdersByKey.getOrDefault(targetKey, target);
|
||||
}
|
||||
@@ -202,7 +228,8 @@ final class DatapackStructureStateFilter {
|
||||
declaredSources,
|
||||
holdersByKey,
|
||||
scopedByIdentity,
|
||||
visiting);
|
||||
visiting,
|
||||
keyIndex);
|
||||
Optional<StructurePlacement.ExclusionZone> scopedZone = Optional.empty();
|
||||
if (scopedTarget != null) {
|
||||
scopedZone = Optional.of(new StructurePlacement.ExclusionZone(
|
||||
@@ -217,14 +244,15 @@ final class DatapackStructureStateFilter {
|
||||
|
||||
private static List<Holder<StructureSet>> scaleFrequencyOverrides(
|
||||
List<Holder<StructureSet>> structureSets,
|
||||
IrisImportedStructureControl importedStructures
|
||||
IrisImportedStructureControl importedStructures,
|
||||
StructureSetKeyIndex keyIndex
|
||||
) {
|
||||
if (!importedStructures.hasFrequencyOverrides()) {
|
||||
return structureSets;
|
||||
}
|
||||
Map<String, Holder<StructureSet>> holdersByKey = new HashMap<>();
|
||||
for (Holder<StructureSet> holder : structureSets) {
|
||||
String key = structureSetKey(holder);
|
||||
String key = structureSetKey(holder, keyIndex);
|
||||
if (key != null) {
|
||||
holdersByKey.putIfAbsent(key, holder);
|
||||
}
|
||||
@@ -234,7 +262,11 @@ final class DatapackStructureStateFilter {
|
||||
boolean changed = false;
|
||||
for (Holder<StructureSet> holder : structureSets) {
|
||||
Holder<StructureSet> scaled = scaleFrequencyHolder(
|
||||
holder, importedStructures, holdersByKey, scaledByIdentity);
|
||||
holder,
|
||||
importedStructures,
|
||||
holdersByKey,
|
||||
scaledByIdentity,
|
||||
keyIndex);
|
||||
scaledSets.add(scaled);
|
||||
changed |= scaled != holder;
|
||||
}
|
||||
@@ -245,17 +277,19 @@ final class DatapackStructureStateFilter {
|
||||
Holder<StructureSet> holder,
|
||||
IrisImportedStructureControl importedStructures,
|
||||
Map<String, Holder<StructureSet>> holdersByKey,
|
||||
Map<Holder<StructureSet>, Holder<StructureSet>> scaledByIdentity
|
||||
Map<Holder<StructureSet>, Holder<StructureSet>> scaledByIdentity,
|
||||
StructureSetKeyIndex keyIndex
|
||||
) {
|
||||
if (scaledByIdentity.containsKey(holder)) {
|
||||
return scaledByIdentity.get(holder);
|
||||
}
|
||||
if (!dependsOnFrequencyOverride(holder, importedStructures, holdersByKey)) {
|
||||
if (!dependsOnFrequencyOverride(
|
||||
holder, importedStructures, holdersByKey, keyIndex)) {
|
||||
scaledByIdentity.put(holder, holder);
|
||||
return holder;
|
||||
}
|
||||
|
||||
ResourceKey<StructureSet> holderKey = structureSetResourceKey(holder).orElseThrow(() ->
|
||||
ResourceKey<StructureSet> holderKey = keyIndex.resolve(holder).orElseThrow(() ->
|
||||
new IllegalStateException(
|
||||
"An affected native structure-set exclusion graph has an unkeyed holder"));
|
||||
ReboundStructureSetHolder scaledHolder = new ReboundStructureSetHolder(holderKey);
|
||||
@@ -267,16 +301,21 @@ final class DatapackStructureStateFilter {
|
||||
Optional<StructurePlacement.ExclusionZone> scaledZone = originalZone;
|
||||
if (originalZone.isPresent()) {
|
||||
Holder<StructureSet> target = canonicalHolder(
|
||||
originalZone.get().otherSet(), holdersByKey);
|
||||
originalZone.get().otherSet(), holdersByKey, keyIndex);
|
||||
Holder<StructureSet> scaledTarget = scaleFrequencyHolder(
|
||||
target, importedStructures, holdersByKey, scaledByIdentity);
|
||||
target,
|
||||
importedStructures,
|
||||
holdersByKey,
|
||||
scaledByIdentity,
|
||||
keyIndex);
|
||||
if (scaledTarget != originalZone.get().otherSet()) {
|
||||
scaledZone = Optional.of(new StructurePlacement.ExclusionZone(
|
||||
scaledTarget, originalZone.get().chunkCount()));
|
||||
}
|
||||
}
|
||||
|
||||
double multiplier = importedStructures.frequencyMultiplier(structureSetKey(holder));
|
||||
double multiplier = importedStructures.frequencyMultiplier(
|
||||
structureSetKey(holder, keyIndex));
|
||||
StructurePlacement scaledPlacement = multiplier == 1D && scaledZone.equals(originalZone)
|
||||
? originalPlacement
|
||||
: copyPlacement(originalPlacement, scaledZone, multiplier);
|
||||
@@ -287,12 +326,14 @@ final class DatapackStructureStateFilter {
|
||||
private static boolean dependsOnFrequencyOverride(
|
||||
Holder<StructureSet> holder,
|
||||
IrisImportedStructureControl importedStructures,
|
||||
Map<String, Holder<StructureSet>> holdersByKey
|
||||
Map<String, Holder<StructureSet>> holdersByKey,
|
||||
StructureSetKeyIndex keyIndex
|
||||
) {
|
||||
Set<Holder<StructureSet>> visited = Collections.newSetFromMap(new IdentityHashMap<>());
|
||||
Holder<StructureSet> current = holder;
|
||||
while (visited.add(current)) {
|
||||
if (importedStructures.frequencyMultiplier(structureSetKey(current)) != 1D) {
|
||||
if (importedStructures.frequencyMultiplier(
|
||||
structureSetKey(current, keyIndex)) != 1D) {
|
||||
return true;
|
||||
}
|
||||
Optional<StructurePlacement.ExclusionZone> zone =
|
||||
@@ -300,24 +341,26 @@ final class DatapackStructureStateFilter {
|
||||
if (zone.isEmpty()) {
|
||||
return false;
|
||||
}
|
||||
current = canonicalHolder(zone.get().otherSet(), holdersByKey);
|
||||
current = canonicalHolder(zone.get().otherSet(), holdersByKey, keyIndex);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
private static Holder<StructureSet> canonicalHolder(
|
||||
Holder<StructureSet> holder,
|
||||
Map<String, Holder<StructureSet>> holdersByKey
|
||||
Map<String, Holder<StructureSet>> holdersByKey,
|
||||
StructureSetKeyIndex keyIndex
|
||||
) {
|
||||
String key = structureSetKey(holder);
|
||||
String key = structureSetKey(holder, keyIndex);
|
||||
return key == null ? holder : holdersByKey.getOrDefault(key, holder);
|
||||
}
|
||||
|
||||
private static Holder<StructureSet> replacementHolder(
|
||||
Holder<StructureSet> original,
|
||||
StructureSet replacement
|
||||
StructureSet replacement,
|
||||
StructureSetKeyIndex keyIndex
|
||||
) {
|
||||
Optional<ResourceKey<StructureSet>> key = structureSetResourceKey(original);
|
||||
Optional<ResourceKey<StructureSet>> key = keyIndex.resolve(original);
|
||||
if (key.isEmpty()) {
|
||||
return Holder.direct(replacement);
|
||||
}
|
||||
@@ -326,20 +369,6 @@ final class DatapackStructureStateFilter {
|
||||
return holder;
|
||||
}
|
||||
|
||||
private static Optional<ResourceKey<StructureSet>> structureSetResourceKey(
|
||||
Holder<StructureSet> holder
|
||||
) {
|
||||
Optional<ResourceKey<StructureSet>> key = holder.unwrapKey();
|
||||
if (key.isPresent()) {
|
||||
return key;
|
||||
}
|
||||
if (holder.value().placement()
|
||||
instanceof ChunkGeneratorStructureState.KeyedRandomSpreadStructurePlacement keyedPlacement) {
|
||||
return Optional.of(keyedPlacement.key);
|
||||
}
|
||||
return Optional.empty();
|
||||
}
|
||||
|
||||
private static StructurePlacement copyPlacement(
|
||||
StructurePlacement placement,
|
||||
Optional<StructurePlacement.ExclusionZone> exclusionZone,
|
||||
@@ -357,26 +386,7 @@ final class DatapackStructureStateFilter {
|
||||
int salt = (int) declaredFieldValue(
|
||||
StructurePlacement.class, placement, int.class);
|
||||
|
||||
if (placement.getClass()
|
||||
== ChunkGeneratorStructureState.KeyedRandomSpreadStructurePlacement.class) {
|
||||
ChunkGeneratorStructureState.KeyedRandomSpreadStructurePlacement keyedPlacement =
|
||||
(ChunkGeneratorStructureState.KeyedRandomSpreadStructurePlacement) placement;
|
||||
NativeStructureFrequencyScale scale = NativeStructureFrequencyScale.randomSpread(
|
||||
frequency, keyedPlacement.spacing(), keyedPlacement.separation(), frequencyMultiplier);
|
||||
return new ChunkGeneratorStructureState.KeyedRandomSpreadStructurePlacement(
|
||||
keyedPlacement.key,
|
||||
locateOffset,
|
||||
frequencyReductionMethod,
|
||||
scale.frequency(),
|
||||
salt,
|
||||
exclusionZone,
|
||||
scale.spacing(),
|
||||
keyedPlacement.separation(),
|
||||
keyedPlacement.spreadType());
|
||||
}
|
||||
if (placement.getClass() == RandomSpreadStructurePlacement.class) {
|
||||
RandomSpreadStructurePlacement randomSpread =
|
||||
(RandomSpreadStructurePlacement) placement;
|
||||
if (placement instanceof RandomSpreadStructurePlacement randomSpread) {
|
||||
NativeStructureFrequencyScale scale = NativeStructureFrequencyScale.randomSpread(
|
||||
frequency, randomSpread.spacing(), randomSpread.separation(), frequencyMultiplier);
|
||||
return new RandomSpreadStructurePlacement(
|
||||
@@ -439,6 +449,46 @@ final class DatapackStructureStateFilter {
|
||||
}
|
||||
}
|
||||
|
||||
static final class StructureSetKeyIndex {
|
||||
private final Map<List<StructureSet.StructureSelectionEntry>, ResourceKey<StructureSet>>
|
||||
keysByEntries;
|
||||
|
||||
private StructureSetKeyIndex(
|
||||
Map<List<StructureSet.StructureSelectionEntry>, ResourceKey<StructureSet>>
|
||||
keysByEntries
|
||||
) {
|
||||
this.keysByEntries = keysByEntries;
|
||||
}
|
||||
|
||||
private static StructureSetKeyIndex create(
|
||||
Iterable<? extends Holder<StructureSet>> registeredStructureSets
|
||||
) {
|
||||
Map<List<StructureSet.StructureSelectionEntry>, ResourceKey<StructureSet>> keys =
|
||||
new IdentityHashMap<>();
|
||||
for (Holder<StructureSet> holder : registeredStructureSets) {
|
||||
Optional<ResourceKey<StructureSet>> key = holder.unwrapKey();
|
||||
if (key.isEmpty()) {
|
||||
continue;
|
||||
}
|
||||
List<StructureSet.StructureSelectionEntry> entries = holder.value().structures();
|
||||
ResourceKey<StructureSet> previous = keys.put(entries, key.get());
|
||||
if (previous != null && !previous.equals(key.get())) {
|
||||
throw new IllegalStateException(
|
||||
"Multiple registered structure sets share the same entry list");
|
||||
}
|
||||
}
|
||||
return new StructureSetKeyIndex(keys);
|
||||
}
|
||||
|
||||
private Optional<ResourceKey<StructureSet>> resolve(Holder<StructureSet> holder) {
|
||||
Optional<ResourceKey<StructureSet>> key = holder.unwrapKey();
|
||||
if (key.isPresent()) {
|
||||
return key;
|
||||
}
|
||||
return Optional.ofNullable(keysByEntries.get(holder.value().structures()));
|
||||
}
|
||||
}
|
||||
|
||||
record Selection(
|
||||
List<Holder<StructureSet>> structureSets,
|
||||
int retainedManagedSets,
|
||||
|
||||
+146
-132
@@ -15,7 +15,6 @@ import art.arcane.iris.core.nms.container.BiomeColor;
|
||||
import art.arcane.iris.core.nms.container.Pair;
|
||||
import art.arcane.iris.core.nms.container.BlockProperty;
|
||||
import art.arcane.iris.core.nms.datapack.DataVersion;
|
||||
import art.arcane.iris.core.lifecycle.WorldReplacementSeed;
|
||||
import art.arcane.iris.engine.data.cache.AtomicCache;
|
||||
import art.arcane.iris.engine.data.chunk.TerrainChunk;
|
||||
import art.arcane.iris.engine.framework.Engine;
|
||||
@@ -55,8 +54,6 @@ import art.arcane.volmlib.util.nbt.tag.CompoundTag;
|
||||
import art.arcane.iris.util.common.scheduling.J;
|
||||
import it.unimi.dsi.fastutil.objects.Object2IntMap;
|
||||
import it.unimi.dsi.fastutil.shorts.ShortList;
|
||||
import io.papermc.paper.world.saveddata.PaperLevelOverrides;
|
||||
import io.papermc.paper.world.saveddata.PaperWorldMetadata;
|
||||
import net.bytebuddy.ByteBuddy;
|
||||
import net.bytebuddy.agent.builder.AgentBuilder;
|
||||
import net.bytebuddy.agent.builder.ResettableClassFileTransformer;
|
||||
@@ -119,14 +116,14 @@ import net.minecraft.world.level.levelgen.XoroshiroRandomSource;
|
||||
import net.minecraft.world.level.levelgen.structure.StructureCheck;
|
||||
import net.minecraft.world.level.levelgen.structure.BoundingBox;
|
||||
import net.minecraft.world.level.levelgen.structure.Structure;
|
||||
import net.minecraft.world.level.levelgen.structure.StructureSet;
|
||||
import net.minecraft.world.level.levelgen.structure.structures.JigsawStructure;
|
||||
import net.minecraft.world.level.storage.PrimaryLevelData;
|
||||
import net.minecraft.world.level.storage.SavedDataStorage;
|
||||
import net.minecraft.world.level.levelgen.feature.AbstractHugeMushroomFeature;
|
||||
import net.minecraft.world.level.levelgen.feature.ConfiguredFeature;
|
||||
import net.minecraft.world.level.levelgen.feature.FallenTreeFeature;
|
||||
import net.minecraft.world.level.levelgen.feature.Feature;
|
||||
import net.minecraft.world.level.levelgen.feature.TreeFeature;
|
||||
import net.minecraft.world.level.storage.LevelStorageSource;
|
||||
import net.minecraft.world.level.levelgen.flat.FlatLayerInfo;
|
||||
import net.minecraft.world.level.levelgen.flat.FlatLevelGeneratorSettings;
|
||||
import org.bukkit.Bukkit;
|
||||
@@ -162,8 +159,6 @@ import java.lang.reflect.Field;
|
||||
import java.lang.reflect.InvocationTargetException;
|
||||
import java.lang.reflect.Method;
|
||||
import java.lang.reflect.Modifier;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.LinkOption;
|
||||
import java.nio.file.Path;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
@@ -173,23 +168,18 @@ import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.ExecutionException;
|
||||
import java.util.concurrent.Executor;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.concurrent.TimeoutException;
|
||||
import java.util.concurrent.atomic.AtomicBoolean;
|
||||
import java.util.concurrent.atomic.AtomicInteger;
|
||||
|
||||
public class NMSBinding implements INMSBinding {
|
||||
private static final long CURRENT_WORLD_DATA_SNAPSHOT_TIMEOUT_SECONDS = 30L;
|
||||
|
||||
private final KMap<Biome, Object> baseBiomeCache = new KMap<>();
|
||||
private volatile DataVersion dataVersion;
|
||||
private final BlockData AIR = Material.AIR.createBlockData();
|
||||
private final AtomicCache<MCAIdMap<net.minecraft.world.level.biome.Biome>> biomeMapCache = new AtomicCache<>();
|
||||
private final AtomicBoolean injected = new AtomicBoolean();
|
||||
private volatile ResettableClassFileTransformer levelStorageAccessTransformer;
|
||||
private volatile ResettableClassFileTransformer serverLevelTransformer;
|
||||
private final AtomicCache<MCAIdMapper<BlockState>> registryCache = new AtomicCache<>();
|
||||
private final AtomicCache<MCAPalette<BlockState>> globalCache = new AtomicCache<>();
|
||||
@@ -1249,8 +1239,15 @@ public class NMSBinding implements INMSBinding {
|
||||
ChunkGeneratorStructureState currentState = level.getChunkSource().getGeneratorState();
|
||||
net.minecraft.world.level.chunk.ChunkGenerator generator = level.getChunkSource().getGenerator();
|
||||
ChunkGeneratorStructureState scopedState = createStructureState(level, generator, currentState);
|
||||
Registry<StructureSet> structureSetRegistry =
|
||||
level.registryAccess().lookupOrThrow(Registries.STRUCTURE_SET);
|
||||
DatapackStructureStateFilter.Selection selection = DatapackStructureStateFilter.filter(
|
||||
scopedState.possibleStructureSets(), scopeIndex, declaredSources, importedStructures);
|
||||
scopedState.possibleStructureSets(),
|
||||
scopeIndex,
|
||||
declaredSources,
|
||||
importedStructures,
|
||||
DatapackStructureStateFilter.keyIndex(
|
||||
structureSetRegistry.listElements().toList()));
|
||||
|
||||
Field possibleSetsField = getField(scopedState.getClass(), List.class);
|
||||
possibleSetsField.setAccessible(true);
|
||||
@@ -1328,7 +1325,7 @@ public class NMSBinding implements INMSBinding {
|
||||
level.registryAccess().lookupOrThrow(Registries.STRUCTURE_SET),
|
||||
currentState.randomState(),
|
||||
currentState.getLevelSeed(),
|
||||
currentState.conf);
|
||||
level.spigotConfig);
|
||||
}
|
||||
|
||||
private void initializeAndPublishStructureState(
|
||||
@@ -1542,6 +1539,18 @@ public class NMSBinding implements INMSBinding {
|
||||
}
|
||||
try {
|
||||
IrisLogging.info("Injecting Bukkit");
|
||||
levelStorageAccessTransformer = new AgentBuilder.Default()
|
||||
.disableClassFormatChanges()
|
||||
.with(AgentBuilder.RedefinitionStrategy.RETRANSFORMATION)
|
||||
.type(ElementMatchers.is(LevelStorageSource.LevelStorageAccess.class))
|
||||
.transform((builder, typeDescription, classLoader, module, protectionDomain) ->
|
||||
builder.visit(Advice.to(LevelStorageAccessAdvice.class).on(ElementMatchers.isConstructor()
|
||||
.and(ElementMatchers.takesArguments(4))
|
||||
.and(ElementMatchers.takesArgument(0, LevelStorageSource.class))
|
||||
.and(ElementMatchers.takesArgument(1, String.class))
|
||||
.and(ElementMatchers.takesArgument(2, Path.class))
|
||||
.and(ElementMatchers.takesArgument(3, ResourceKey.class)))))
|
||||
.installOn(Agent.getInstrumentation());
|
||||
serverLevelTransformer = new AgentBuilder.Default()
|
||||
.disableClassFormatChanges()
|
||||
.with(AgentBuilder.RedefinitionStrategy.RETRANSFORMATION)
|
||||
@@ -1549,8 +1558,7 @@ public class NMSBinding implements INMSBinding {
|
||||
.transform((builder, typeDescription, classLoader, module, protectionDomain) ->
|
||||
builder.visit(Advice.to(ServerLevelAdvice.class).on(ElementMatchers.isConstructor()
|
||||
.and(ElementMatchers.takesArgument(0, MinecraftServer.class))
|
||||
.and(ElementMatchers.takesArgument(5, LevelStem.class))
|
||||
.and(ElementMatchers.takesArgument(12, ChunkGenerator.class)))))
|
||||
.and(ElementMatchers.takesArgument(5, LevelStem.class)))))
|
||||
.installOn(Agent.getInstrumentation());
|
||||
ByteBuddy buddy = new ByteBuddy();
|
||||
for (Class<?> clazz : List.of(ChunkAccess.class, ProtoChunk.class)) {
|
||||
@@ -1565,12 +1573,17 @@ public class NMSBinding implements INMSBinding {
|
||||
} catch (Throwable e) {
|
||||
IrisLogging.error(C.RED + "Failed to inject Bukkit");
|
||||
e.printStackTrace();
|
||||
// The ServerLevel transformer may already be installed when the ChunkAccess
|
||||
// redefine throws; remove it or a retry would stack a second one and orphan
|
||||
// this one permanently.
|
||||
ResettableClassFileTransformer partial = serverLevelTransformer;
|
||||
ResettableClassFileTransformer partialServerLevel = serverLevelTransformer;
|
||||
ResettableClassFileTransformer partialStorageAccess = levelStorageAccessTransformer;
|
||||
serverLevelTransformer = null;
|
||||
if (partial != null) {
|
||||
levelStorageAccessTransformer = null;
|
||||
for (ResettableClassFileTransformer partial : new ResettableClassFileTransformer[]{
|
||||
partialServerLevel,
|
||||
partialStorageAccess
|
||||
}) {
|
||||
if (partial == null) {
|
||||
continue;
|
||||
}
|
||||
try {
|
||||
partial.reset(Agent.getInstrumentation(), AgentBuilder.RedefinitionStrategy.RETRANSFORMATION);
|
||||
} catch (Throwable ignored) {
|
||||
@@ -1586,26 +1599,36 @@ public class NMSBinding implements INMSBinding {
|
||||
if (!injected.get())
|
||||
return;
|
||||
try {
|
||||
Agent.getInstrumentation().retransformClasses(ServerLevel.class);
|
||||
Agent.getInstrumentation().retransformClasses(
|
||||
LevelStorageSource.LevelStorageAccess.class,
|
||||
ServerLevel.class
|
||||
);
|
||||
} catch (Throwable e) {
|
||||
IrisLogging.error(C.RED + "Failed to re-apply ServerLevel injection");
|
||||
IrisLogging.error(C.RED + "Failed to re-apply Bukkit world lifecycle injection");
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void uninjectBukkit() {
|
||||
synchronized (injected) {
|
||||
ResettableClassFileTransformer transformer = serverLevelTransformer;
|
||||
ResettableClassFileTransformer activeServerLevel = serverLevelTransformer;
|
||||
ResettableClassFileTransformer activeStorageAccess = levelStorageAccessTransformer;
|
||||
serverLevelTransformer = null;
|
||||
levelStorageAccessTransformer = null;
|
||||
injected.set(false);
|
||||
if (transformer == null) {
|
||||
return;
|
||||
}
|
||||
try {
|
||||
transformer.reset(Agent.getInstrumentation(), AgentBuilder.RedefinitionStrategy.RETRANSFORMATION);
|
||||
} catch (Throwable e) {
|
||||
IrisLogging.error(C.RED + "Failed to remove ServerLevel injection");
|
||||
e.printStackTrace();
|
||||
for (ResettableClassFileTransformer transformer : new ResettableClassFileTransformer[]{
|
||||
activeServerLevel,
|
||||
activeStorageAccess
|
||||
}) {
|
||||
if (transformer == null) {
|
||||
continue;
|
||||
}
|
||||
try {
|
||||
transformer.reset(Agent.getInstrumentation(), AgentBuilder.RedefinitionStrategy.RETRANSFORMATION);
|
||||
} catch (Throwable e) {
|
||||
IrisLogging.error(C.RED + "Failed to remove Bukkit world lifecycle injection");
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1616,103 +1639,7 @@ public class NMSBinding implements INMSBinding {
|
||||
Path targetWorldDirectory,
|
||||
long seed
|
||||
) throws IOException {
|
||||
CraftServer craftServer = (CraftServer) Bukkit.getServer();
|
||||
MinecraftServer server = craftServer.getHandle().getServer();
|
||||
PaperLevelOverrides levelOverrides = captureCurrentPaperLevelOverrides(craftServer, server);
|
||||
|
||||
Path targetWorld = targetWorldDirectory.toAbsolutePath().normalize();
|
||||
UUID metadataUuid = UUID.randomUUID();
|
||||
WorldReplacementSeed.copyWithAuthoritativeSeed(sourceWorldDirectory, targetWorld, seed);
|
||||
try (SavedDataStorage savedDataStorage = new SavedDataStorage(
|
||||
targetWorld.resolve("data"),
|
||||
server.getFixerUpper(),
|
||||
server.registryAccess()
|
||||
)) {
|
||||
savedDataStorage.set(PaperWorldMetadata.TYPE, new PaperWorldMetadata(metadataUuid));
|
||||
savedDataStorage.set(
|
||||
PaperLevelOverrides.TYPE,
|
||||
levelOverrides
|
||||
);
|
||||
}
|
||||
|
||||
List<Path> requiredDataFiles = List.of(
|
||||
targetWorld.resolve("data/minecraft/world_gen_settings.dat"),
|
||||
targetWorld.resolve("data/paper/metadata.dat"),
|
||||
targetWorld.resolve("data/paper/level_overrides.dat")
|
||||
);
|
||||
for (Path requiredDataFile : requiredDataFiles) {
|
||||
if (!Files.isRegularFile(requiredDataFile, LinkOption.NOFOLLOW_LINKS)) {
|
||||
throw new IOException("Current Paper world data was not written: " + requiredDataFile);
|
||||
}
|
||||
}
|
||||
|
||||
long writtenSeed = WorldReplacementSeed.readAuthoritativeSeed(targetWorld);
|
||||
if (writtenSeed != seed) {
|
||||
throw new IOException("Current Paper world data did not retain the requested seed.");
|
||||
}
|
||||
|
||||
try (SavedDataStorage verificationStorage = new SavedDataStorage(
|
||||
targetWorld.resolve("data"),
|
||||
server.getFixerUpper(),
|
||||
server.registryAccess()
|
||||
)) {
|
||||
PaperWorldMetadata metadata = verificationStorage.get(PaperWorldMetadata.TYPE);
|
||||
if (metadata == null || !metadataUuid.equals(metadata.uuid())) {
|
||||
throw new IOException("Current Paper world metadata could not be verified.");
|
||||
}
|
||||
PaperLevelOverrides overrides = verificationStorage.get(PaperLevelOverrides.TYPE);
|
||||
if (overrides == null || overrides.isInitialized()) {
|
||||
throw new IOException("Current Paper level overrides could not be verified.");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private PaperLevelOverrides captureCurrentPaperLevelOverrides(
|
||||
CraftServer craftServer,
|
||||
MinecraftServer server
|
||||
) throws IOException {
|
||||
if (craftServer.isGlobalTickThread()) {
|
||||
return createCurrentPaperLevelOverrides(craftServer, server);
|
||||
}
|
||||
if (J.isFolia() && J.isPrimaryThread()) {
|
||||
throw new IOException("Current Paper world data cannot be staged from a Folia region tick thread.");
|
||||
}
|
||||
|
||||
CompletableFuture<PaperLevelOverrides> captured = new CompletableFuture<>();
|
||||
boolean scheduled = J.runGlobal(() -> {
|
||||
try {
|
||||
captured.complete(createCurrentPaperLevelOverrides(craftServer, server));
|
||||
} catch (Throwable failure) {
|
||||
captured.completeExceptionally(failure);
|
||||
}
|
||||
});
|
||||
if (!scheduled) {
|
||||
throw new IOException("Could not schedule the current Paper level-data snapshot on the global thread.");
|
||||
}
|
||||
|
||||
try {
|
||||
return captured.get(CURRENT_WORLD_DATA_SNAPSHOT_TIMEOUT_SECONDS, TimeUnit.SECONDS);
|
||||
} catch (InterruptedException failure) {
|
||||
Thread.currentThread().interrupt();
|
||||
throw new IOException("Interrupted while capturing current Paper level data.", failure);
|
||||
} catch (ExecutionException failure) {
|
||||
throw new IOException("Could not capture current Paper level data.", failure.getCause());
|
||||
} catch (TimeoutException failure) {
|
||||
throw new IOException("Timed out while capturing current Paper level data.", failure);
|
||||
}
|
||||
}
|
||||
|
||||
private PaperLevelOverrides createCurrentPaperLevelOverrides(
|
||||
CraftServer craftServer,
|
||||
MinecraftServer server
|
||||
) throws IOException {
|
||||
if (!craftServer.isGlobalTickThread()) {
|
||||
throw new IOException("Current Paper level data must be captured on the global tick thread.");
|
||||
}
|
||||
if (!(server.getWorldData().overworldData() instanceof PrimaryLevelData primaryLevelData)) {
|
||||
throw new IOException("Paper primary level data is unavailable for current world data staging.");
|
||||
}
|
||||
return PaperLevelOverrides.createFromLiveLevelData(primaryLevelData);
|
||||
CurrentPaperWorldDataWriter.write(sourceWorldDirectory, targetWorldDirectory, seed);
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -1777,13 +1704,76 @@ public class NMSBinding implements INMSBinding {
|
||||
}
|
||||
}
|
||||
|
||||
private static class LevelStorageAccessAdvice {
|
||||
@Advice.OnMethodEnter
|
||||
static void enter(
|
||||
@Advice.Argument(1) String levelId,
|
||||
@Advice.Argument(value = 3, readOnly = false) ResourceKey<LevelStem> dimensionType
|
||||
) {
|
||||
if (levelId == null || levelId.isBlank()) {
|
||||
return;
|
||||
}
|
||||
|
||||
ClassLoader pluginClassLoader;
|
||||
Class<?> generatorType;
|
||||
Class<?> stagingType;
|
||||
try {
|
||||
org.bukkit.plugin.Plugin irisPlugin = Bukkit.getPluginManager().getPlugin("Iris");
|
||||
if (irisPlugin == null) {
|
||||
return;
|
||||
}
|
||||
pluginClassLoader = irisPlugin.getClass().getClassLoader();
|
||||
generatorType = Class.forName("art.arcane.iris.engine.platform.PlatformChunkGenerator", true, pluginClassLoader);
|
||||
stagingType = Class.forName("art.arcane.iris.core.lifecycle.WorldLifecycleStaging", true, pluginClassLoader);
|
||||
} catch (Throwable ignored) {
|
||||
return;
|
||||
}
|
||||
|
||||
Object generator;
|
||||
try {
|
||||
generator = stagingType
|
||||
.getDeclaredMethod("peekStemGenerator", String.class)
|
||||
.invoke(null, levelId);
|
||||
} catch (Throwable e) {
|
||||
throw new RuntimeException("Iris failed to inspect the staged world generator",
|
||||
e instanceof InvocationTargetException ex ? ex.getCause() : e);
|
||||
}
|
||||
if (generator == null || !generatorType.isInstance(generator)) {
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
Object target = generatorType.getMethod("getTarget").invoke(generator);
|
||||
if (target == null) {
|
||||
throw new IllegalStateException("Iris generator has no engine target.");
|
||||
}
|
||||
Object world = target.getClass().getMethod("getWorld").invoke(target);
|
||||
if (world == null) {
|
||||
throw new IllegalStateException("Iris generator target has no world identity.");
|
||||
}
|
||||
Object rawIdentity = world.getClass().getMethod("identity").invoke(world);
|
||||
String worldIdentity = rawIdentity == null ? "" : rawIdentity.toString().trim();
|
||||
Identifier worldIdentifier = Identifier.parse(worldIdentity);
|
||||
if (!"iris".equals(worldIdentifier.getNamespace())
|
||||
&& !"minecraft".equals(worldIdentifier.getNamespace())) {
|
||||
throw new IllegalStateException(
|
||||
"Iris generator has an unmanaged world identity: " + worldIdentity);
|
||||
}
|
||||
dimensionType = ResourceKey.create(Registries.LEVEL_STEM, worldIdentifier);
|
||||
} catch (Throwable e) {
|
||||
throw new RuntimeException("Iris failed to bind the staged world storage identity",
|
||||
e instanceof InvocationTargetException ex ? ex.getCause() : e);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static class ServerLevelAdvice {
|
||||
@Advice.OnMethodEnter
|
||||
static void enter(
|
||||
@Advice.Argument(0) MinecraftServer server,
|
||||
@Advice.Argument(4) ResourceKey<Level> dimensionKey,
|
||||
@Advice.Argument(value = 4, readOnly = false) ResourceKey<Level> dimensionKey,
|
||||
@Advice.Argument(value = 5, readOnly = false) LevelStem levelStem,
|
||||
@Advice.Argument(12) ChunkGenerator constructorGenerator
|
||||
@Advice.AllArguments Object[] constructorArguments
|
||||
) {
|
||||
if (dimensionKey == null)
|
||||
return;
|
||||
@@ -1818,6 +1808,13 @@ public class NMSBinding implements INMSBinding {
|
||||
// the vanilla stem corrupts generation.
|
||||
ChunkGenerator gen = null;
|
||||
try {
|
||||
ChunkGenerator constructorGenerator = null;
|
||||
for (Object argument : constructorArguments) {
|
||||
if (argument instanceof ChunkGenerator candidate) {
|
||||
constructorGenerator = candidate;
|
||||
break;
|
||||
}
|
||||
}
|
||||
Object generator = generatorType.isInstance(constructorGenerator) ? constructorGenerator : null;
|
||||
if (generator == null) {
|
||||
generator = stagingType
|
||||
@@ -1855,10 +1852,27 @@ public class NMSBinding implements INMSBinding {
|
||||
if (stemMethod == null) {
|
||||
throw new IllegalStateException("Iris binding is missing createRuntimeLevelStem.");
|
||||
}
|
||||
Object target = generatorType.getMethod("getTarget").invoke(gen);
|
||||
if (target == null) {
|
||||
throw new IllegalStateException("Iris generator has no engine target.");
|
||||
}
|
||||
Object world = target.getClass().getMethod("getWorld").invoke(target);
|
||||
if (world == null) {
|
||||
throw new IllegalStateException("Iris generator target has no world identity.");
|
||||
}
|
||||
Object rawIdentity = world.getClass().getMethod("identity").invoke(world);
|
||||
String worldIdentity = rawIdentity == null ? "" : rawIdentity.toString().trim();
|
||||
Identifier worldIdentifier = Identifier.parse(worldIdentity);
|
||||
if (!"iris".equals(worldIdentifier.getNamespace())
|
||||
&& !"minecraft".equals(worldIdentifier.getNamespace())) {
|
||||
throw new IllegalStateException(
|
||||
"Iris generator has an unmanaged world identity: " + worldIdentity);
|
||||
}
|
||||
Object resolvedStem = stemMethod.invoke(bindings, server.registryAccess(), gen);
|
||||
if (!(resolvedStem instanceof LevelStem runtimeStem)) {
|
||||
throw new IllegalStateException("Iris runtime LevelStem binding returned " + (resolvedStem == null ? "null" : resolvedStem.getClass().getName()) + ".");
|
||||
}
|
||||
dimensionKey = ResourceKey.create(Registries.DIMENSION, worldIdentifier);
|
||||
levelStem = runtimeStem;
|
||||
} catch (Throwable e) {
|
||||
throw new RuntimeException("Iris failed to replace the levelStem", e instanceof InvocationTargetException ex ? ex.getCause() : e);
|
||||
|
||||
+8
@@ -215,6 +215,14 @@ final class NativeStructureWorldgenAccess implements WorldGenLevel {
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public ChunkAccess getChunk(int chunkX, int chunkZ) {
|
||||
if (isInsideGenerationRegion(chunkX, chunkZ)) {
|
||||
return delegate.getChunk(chunkX, chunkZ);
|
||||
}
|
||||
return outsideChunk(chunkX, chunkZ);
|
||||
}
|
||||
|
||||
@Override
|
||||
public ChunkAccess getChunk(int chunkX, int chunkZ, ChunkStatus status, boolean create) {
|
||||
if (isInsideGenerationRegion(chunkX, chunkZ)) {
|
||||
|
||||
+45
-12
@@ -3,29 +3,54 @@ package art.arcane.iris.core.nms.v26_2_R1;
|
||||
import art.arcane.iris.core.nms.INMSBinding;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.io.InputStream;
|
||||
import java.lang.reflect.InvocationHandler;
|
||||
import java.lang.reflect.Proxy;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
|
||||
import static org.junit.Assert.assertFalse;
|
||||
import static org.junit.Assert.assertNotNull;
|
||||
import static org.junit.Assert.assertThrows;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
public class NMSBindingCurrentPaperWorldDataContractTest {
|
||||
@Test
|
||||
public void stagesAllCurrentPaperWorldDataFromLiveServerState() throws Exception {
|
||||
String source = Files.readString(Path.of(System.getProperty("iris.nmsBindingSource")));
|
||||
public void bindingDelegatesWithoutLinkingPaperSavedDataClasses() throws Exception {
|
||||
String bindingSource = Files.readString(bindingSourcePath());
|
||||
String writer = section(
|
||||
source,
|
||||
bindingSource,
|
||||
"public void writeCurrentPaperWorldData(",
|
||||
"public KMap<Material, List<BlockProperty>> getBlockProperties()"
|
||||
"public boolean awaitServerShutdownBoundary("
|
||||
);
|
||||
|
||||
assertTrue(writer.contains("CurrentPaperWorldDataWriter.write("));
|
||||
assertFalse(bindingSource.contains("PaperWorldMetadata"));
|
||||
assertFalse(bindingSource.contains("PaperLevelOverrides"));
|
||||
assertFalse(bindingSource.contains("io.papermc.paper.world.saveddata"));
|
||||
|
||||
InputStream classResource = NMSBindingCurrentPaperWorldDataContractTest.class
|
||||
.getResourceAsStream("NMSBinding.class");
|
||||
assertNotNull(classResource);
|
||||
try (InputStream input = classResource) {
|
||||
String classFile = new String(input.readAllBytes(), StandardCharsets.ISO_8859_1);
|
||||
assertFalse(classFile.contains("PaperWorldMetadata"));
|
||||
assertFalse(classFile.contains("PaperLevelOverrides"));
|
||||
assertFalse(classFile.contains("io/papermc/paper/world/saveddata"));
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void stagesAllCurrentPaperWorldDataFromLiveServerState() throws Exception {
|
||||
String writer = Files.readString(writerSourcePath());
|
||||
|
||||
assertTrue(writer.contains("WorldReplacementSeed.copyWithAuthoritativeSeed("));
|
||||
assertTrue(writer.contains("UUID metadataUuid = UUID.randomUUID()"));
|
||||
assertTrue(writer.contains("new PaperWorldMetadata(metadataUuid)"));
|
||||
assertTrue(writer.contains("captureCurrentPaperLevelOverrides(craftServer, server)"));
|
||||
assertTrue(writer.contains("captureLevelOverrides(craftServer, server)"));
|
||||
assertTrue(writer.indexOf("captureLevelOverrides(craftServer, server)")
|
||||
< writer.indexOf("WorldReplacementSeed.copyWithAuthoritativeSeed("));
|
||||
assertTrue(writer.contains("new SavedDataStorage("));
|
||||
assertTrue(writer.contains("server.getFixerUpper()"));
|
||||
assertTrue(writer.contains("server.registryAccess()"));
|
||||
@@ -44,23 +69,23 @@ public class NMSBindingCurrentPaperWorldDataContractTest {
|
||||
|
||||
@Test
|
||||
public void capturesOnlyLiveLevelOverridesOnTheGlobalThread() throws Exception {
|
||||
String source = Files.readString(Path.of(System.getProperty("iris.nmsBindingSource")));
|
||||
String source = Files.readString(writerSourcePath());
|
||||
String capture = section(
|
||||
source,
|
||||
"private PaperLevelOverrides captureCurrentPaperLevelOverrides(",
|
||||
"private PaperLevelOverrides createCurrentPaperLevelOverrides("
|
||||
"private static PaperLevelOverrides captureLevelOverrides(",
|
||||
"private static PaperLevelOverrides createLevelOverrides("
|
||||
);
|
||||
String create = section(
|
||||
source,
|
||||
"private PaperLevelOverrides createCurrentPaperLevelOverrides(",
|
||||
"public KMap<Material, List<BlockProperty>> getBlockProperties()"
|
||||
"private static PaperLevelOverrides createLevelOverrides(",
|
||||
"\n }\n}"
|
||||
);
|
||||
|
||||
assertTrue(capture.contains("craftServer.isGlobalTickThread()"));
|
||||
assertTrue(capture.contains("J.isFolia() && J.isPrimaryThread()"));
|
||||
assertTrue(capture.contains("J.runGlobal("));
|
||||
assertTrue(capture.contains("createCurrentPaperLevelOverrides(craftServer, server)"));
|
||||
assertTrue(capture.contains("captured.get(CURRENT_WORLD_DATA_SNAPSHOT_TIMEOUT_SECONDS"));
|
||||
assertTrue(capture.contains("createLevelOverrides(craftServer, server)"));
|
||||
assertTrue(capture.contains("captured.get(SNAPSHOT_TIMEOUT_SECONDS"));
|
||||
assertTrue(capture.contains("Thread.currentThread().interrupt()"));
|
||||
assertTrue(create.contains("if (!craftServer.isGlobalTickThread())"));
|
||||
assertTrue(create.indexOf("if (!craftServer.isGlobalTickThread())")
|
||||
@@ -89,6 +114,14 @@ public class NMSBindingCurrentPaperWorldDataContractTest {
|
||||
assertTrue(error.getMessage().contains("does not support current Paper world data staging"));
|
||||
}
|
||||
|
||||
private static Path bindingSourcePath() {
|
||||
return Path.of(System.getProperty("iris.nmsBindingSource"));
|
||||
}
|
||||
|
||||
private static Path writerSourcePath() {
|
||||
return bindingSourcePath().resolveSibling("CurrentPaperWorldDataWriter.java");
|
||||
}
|
||||
|
||||
private static String section(String source, String startMarker, String endMarker) {
|
||||
int start = source.indexOf(startMarker);
|
||||
int end = source.indexOf(endMarker, start);
|
||||
|
||||
+72
-23
@@ -27,6 +27,8 @@ import org.junit.Test;
|
||||
import org.junit.BeforeClass;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.List;
|
||||
@@ -38,8 +40,8 @@ import java.util.stream.Stream;
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertFalse;
|
||||
import static org.junit.Assert.assertNotSame;
|
||||
import static org.junit.Assert.assertNotNull;
|
||||
import static org.junit.Assert.assertSame;
|
||||
import static org.junit.Assert.assertThrows;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
public class NMSBindingDatapackStructureScopeTest {
|
||||
@@ -108,28 +110,56 @@ public class NMSBindingDatapackStructureScopeTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void spigotDirectHolderRetainsItsStructureSetKey() {
|
||||
public void spigotDirectHolderRecoversItsRegistryKeyFromSharedEntries() {
|
||||
ResourceKey<StructureSet> key = ResourceKey.create(
|
||||
Registries.STRUCTURE_SET,
|
||||
Identifier.parse("minecraft:villages"));
|
||||
ChunkGeneratorStructureState.KeyedRandomSpreadStructurePlacement placement =
|
||||
new ChunkGeneratorStructureState.KeyedRandomSpreadStructurePlacement(
|
||||
key,
|
||||
Vec3i.ZERO,
|
||||
StructurePlacement.FrequencyReductionMethod.DEFAULT,
|
||||
1.0F,
|
||||
10387312,
|
||||
Optional.empty(),
|
||||
34,
|
||||
8,
|
||||
RandomSpreadType.LINEAR);
|
||||
StructureSet structureSet = new StructureSet(
|
||||
List.of(new StructureSet.StructureSelectionEntry(
|
||||
structureHolder("minecraft:village_plains"), 1)),
|
||||
placement);
|
||||
Identifier.parse("managed:illager_barracks"));
|
||||
List<StructureSet.StructureSelectionEntry> entries = List.of(
|
||||
new StructureSet.StructureSelectionEntry(
|
||||
structureHolder("minecraft:pillager_outpost"), 1));
|
||||
Holder<StructureSet> registered = new KeyedHolder<>(key, new StructureSet(
|
||||
entries,
|
||||
new RandomSpreadStructurePlacement(
|
||||
34, 8, RandomSpreadType.LINEAR, 10387312)));
|
||||
Holder<StructureSet> spigotDirect = Holder.direct(new StructureSet(
|
||||
entries,
|
||||
new RandomSpreadStructurePlacement(
|
||||
34, 8, RandomSpreadType.LINEAR, 14357620)));
|
||||
DatapackStructureScopeIndex scopeIndex = index(
|
||||
List.of(), List.of("managed:illager_barracks"));
|
||||
DatapackStructureStateFilter.StructureSetKeyIndex keyIndex =
|
||||
DatapackStructureStateFilter.keyIndex(List.of(registered));
|
||||
|
||||
assertEquals("minecraft:villages",
|
||||
DatapackStructureStateFilter.structureSetKey(Holder.direct(structureSet)));
|
||||
DatapackStructureStateFilter.Selection excluded =
|
||||
DatapackStructureStateFilter.filter(
|
||||
List.of(spigotDirect),
|
||||
scopeIndex,
|
||||
Set.of(),
|
||||
new IrisImportedStructureControl(),
|
||||
keyIndex);
|
||||
DatapackStructureStateFilter.Selection retained =
|
||||
DatapackStructureStateFilter.filter(
|
||||
List.of(spigotDirect),
|
||||
scopeIndex,
|
||||
scopeIndex.declaredSources(List.of(SOURCE)),
|
||||
new IrisImportedStructureControl(),
|
||||
keyIndex);
|
||||
|
||||
assertEquals(0, excluded.structureSets().size());
|
||||
assertEquals(1, excluded.excludedManagedSets());
|
||||
assertSame(spigotDirect, retained.structureSets().getFirst());
|
||||
assertEquals(1, retained.retainedManagedSets());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void structureScopeDoesNotLinkPaperOnlyPlacementClasses() throws IOException {
|
||||
InputStream classResource = NMSBindingDatapackStructureScopeTest.class
|
||||
.getResourceAsStream("DatapackStructureStateFilter.class");
|
||||
assertNotNull(classResource);
|
||||
try (InputStream input = classResource) {
|
||||
String classFile = new String(input.readAllBytes(), StandardCharsets.ISO_8859_1);
|
||||
assertFalse(classFile.contains("KeyedRandomSpreadStructurePlacement"));
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -271,7 +301,7 @@ public class NMSBindingDatapackStructureScopeTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void affectedRandomSpreadSubclassFailsInsteadOfLosingSubtypeBehavior() {
|
||||
public void randomSpreadSubtypeUsesTheCanonicalPlacementContract() {
|
||||
Holder<StructureSet> custom = structureSetHolder(
|
||||
"example:custom",
|
||||
new CustomRandomSpreadPlacement(),
|
||||
@@ -283,8 +313,12 @@ public class NMSBindingDatapackStructureScopeTest {
|
||||
IrisImportedStructureControl control = new IrisImportedStructureControl()
|
||||
.setFrequencyOverrides(overrides);
|
||||
|
||||
assertThrows(IllegalStateException.class, () -> DatapackStructureStateFilter.filter(
|
||||
List.of(custom), index(List.of(), List.of()), Set.of(), control));
|
||||
DatapackStructureStateFilter.Selection selection = DatapackStructureStateFilter.filter(
|
||||
List.of(custom), index(List.of(), List.of()), Set.of(), control);
|
||||
StructurePlacement placement = selection.structureSets().getFirst().value().placement();
|
||||
|
||||
assertEquals(RandomSpreadStructurePlacement.class, placement.getClass());
|
||||
assertEquals(26, ((RandomSpreadStructurePlacement) placement).spacing());
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -395,6 +429,21 @@ public class NMSBindingDatapackStructureScopeTest {
|
||||
assertTrue(structureRetarget > identityGate);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void structureStateRecreationUsesTheWorldOwnedSpigotConfiguration() throws IOException {
|
||||
Path chunkGeneratorSource = Path.of(System.getProperty("iris.nmsChunkGeneratorSource"));
|
||||
String source = Files.readString(chunkGeneratorSource.resolveSibling("NMSBinding.java"));
|
||||
int methodStart = source.indexOf("private ChunkGeneratorStructureState createStructureState(");
|
||||
int methodEnd = source.indexOf(
|
||||
"\n private void initializeAndPublishStructureState(", methodStart);
|
||||
|
||||
assertTrue(methodStart >= 0);
|
||||
assertTrue(methodEnd > methodStart);
|
||||
String method = source.substring(methodStart, methodEnd);
|
||||
assertTrue(method.contains("level.spigotConfig"));
|
||||
assertFalse(method.contains("currentState.conf"));
|
||||
}
|
||||
|
||||
private static DatapackStructureScopeIndex index(
|
||||
List<String> structureKeys,
|
||||
List<String> structureSetKeys
|
||||
|
||||
+103
@@ -0,0 +1,103 @@
|
||||
package art.arcane.iris.core.nms.v26_2_R1;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
|
||||
import static org.junit.Assert.assertFalse;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
public class NMSBindingServerLevelAdviceContractTest {
|
||||
@Test
|
||||
public void serverLevelAdviceSupportsCurrentSpigotAndPaperConstructorLayouts() throws Exception {
|
||||
String source = Files.readString(
|
||||
Path.of(System.getProperty("iris.nmsBindingSource")));
|
||||
String transformer = section(
|
||||
source,
|
||||
"public boolean injectBukkit()",
|
||||
"public void ensureServerLevelInjection()");
|
||||
String advice = section(
|
||||
source,
|
||||
"private static class ServerLevelAdvice",
|
||||
"\n }\n}");
|
||||
|
||||
assertTrue(transformer.contains("takesArgument(0, MinecraftServer.class)"));
|
||||
assertTrue(transformer.contains("takesArgument(5, LevelStem.class)"));
|
||||
assertFalse(transformer.contains("takesArgument(12, ChunkGenerator.class)"));
|
||||
assertFalse(transformer.contains("takesArgument(13, ChunkGenerator.class)"));
|
||||
assertTrue(advice.contains("@Advice.AllArguments Object[] constructorArguments"));
|
||||
assertTrue(advice.contains("argument instanceof ChunkGenerator candidate"));
|
||||
assertFalse(advice.contains("@Advice.Argument(12)"));
|
||||
assertFalse(advice.contains("@Advice.Argument(13)"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void currentSpigotStorageAccessReceivesManagedIdentityBeforeConstruction() throws Exception {
|
||||
String source = Files.readString(
|
||||
Path.of(System.getProperty("iris.nmsBindingSource")));
|
||||
String transformer = section(
|
||||
source,
|
||||
"public boolean injectBukkit()",
|
||||
"public void ensureServerLevelInjection()");
|
||||
String advice = section(
|
||||
source,
|
||||
"private static class LevelStorageAccessAdvice",
|
||||
"private static class ServerLevelAdvice");
|
||||
|
||||
assertTrue(transformer.contains(
|
||||
".type(ElementMatchers.is(LevelStorageSource.LevelStorageAccess.class))"));
|
||||
assertTrue(transformer.contains("Advice.to(LevelStorageAccessAdvice.class)"));
|
||||
assertTrue(transformer.contains("ElementMatchers.takesArguments(4)"));
|
||||
assertTrue(transformer.contains(
|
||||
"ElementMatchers.takesArgument(0, LevelStorageSource.class)"));
|
||||
assertTrue(transformer.contains("ElementMatchers.takesArgument(1, String.class)"));
|
||||
assertTrue(transformer.contains("ElementMatchers.takesArgument(2, Path.class)"));
|
||||
assertTrue(transformer.contains("ElementMatchers.takesArgument(3, ResourceKey.class)"));
|
||||
assertTrue(advice.contains("@Advice.Argument(1) String levelId"));
|
||||
assertTrue(advice.contains(
|
||||
"@Advice.Argument(value = 3, readOnly = false) ResourceKey<LevelStem> dimensionType"));
|
||||
assertTrue(advice.contains("getDeclaredMethod(\"peekStemGenerator\", String.class)"));
|
||||
assertTrue(advice.contains(".invoke(null, levelId)"));
|
||||
assertTrue(advice.contains(
|
||||
"dimensionType = ResourceKey.create(Registries.LEVEL_STEM, worldIdentifier);"));
|
||||
assertFalse(advice.contains("dimensionRoot("));
|
||||
assertFalse(advice.contains("Files.copy"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void ownedWorldPublishesItsManagedIdentityAndRuntimeStemTogether() throws Exception {
|
||||
String source = Files.readString(
|
||||
Path.of(System.getProperty("iris.nmsBindingSource")));
|
||||
String advice = section(
|
||||
source,
|
||||
"private static class ServerLevelAdvice",
|
||||
"\n }\n}");
|
||||
|
||||
assertTrue(advice.contains(
|
||||
"@Advice.Argument(value = 4, readOnly = false) ResourceKey<Level> dimensionKey"));
|
||||
assertTrue(advice.contains("getMethod(\"getTarget\")"));
|
||||
assertTrue(advice.contains("getMethod(\"getWorld\")"));
|
||||
assertTrue(advice.contains("getMethod(\"identity\")"));
|
||||
assertTrue(advice.contains("\"iris\".equals(worldIdentifier.getNamespace())"));
|
||||
assertTrue(advice.contains("\"minecraft\".equals(worldIdentifier.getNamespace())"));
|
||||
|
||||
int resolvedStem = advice.indexOf("Object resolvedStem = stemMethod.invoke(");
|
||||
int validatedStem = advice.indexOf("resolvedStem instanceof LevelStem runtimeStem");
|
||||
int identityPublication = advice.indexOf(
|
||||
"dimensionKey = ResourceKey.create(Registries.DIMENSION, worldIdentifier);");
|
||||
int stemPublication = advice.indexOf("levelStem = runtimeStem;");
|
||||
assertTrue(resolvedStem >= 0);
|
||||
assertTrue(validatedStem > resolvedStem);
|
||||
assertTrue(identityPublication > validatedStem);
|
||||
assertTrue(stemPublication > identityPublication);
|
||||
}
|
||||
|
||||
private static String section(String source, String startMarker, String endMarker) {
|
||||
int start = source.indexOf(startMarker);
|
||||
int end = source.indexOf(endMarker, start);
|
||||
assertTrue("Missing source section starting with " + startMarker, start >= 0);
|
||||
assertTrue("Missing source section ending with " + endMarker, end > start);
|
||||
return source.substring(start, end);
|
||||
}
|
||||
}
|
||||
+24
-1
@@ -135,6 +135,18 @@ public class NativeStructureWorldgenAccessTest {
|
||||
assertEquals(1, recording.blockTicks.count());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void statuslessChunkReadsPreserveWorldgenDelegateSemantics() {
|
||||
RecordingDelegate recording = new RecordingDelegate();
|
||||
NativeStructureWorldgenAccess access = access(recording);
|
||||
ChunkPos generationCenter = generationCenter();
|
||||
|
||||
assertNull(access.getChunk(generationCenter.getWorldPosition()));
|
||||
|
||||
assertEquals(1, recording.statuslessChunkReads);
|
||||
assertEquals(0, recording.statusChunkReads);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void entityQueriesRejectDisjointAreasAndClampOverlaps() {
|
||||
RecordingDelegate recording = new RecordingDelegate();
|
||||
@@ -187,6 +199,8 @@ public class NativeStructureWorldgenAccessTest {
|
||||
private int terrainReads;
|
||||
private int heightReads;
|
||||
private int chunkReads;
|
||||
private int statuslessChunkReads;
|
||||
private int statusChunkReads;
|
||||
private int mutations;
|
||||
private int events;
|
||||
|
||||
@@ -240,7 +254,16 @@ public class NativeStructureWorldgenAccessTest {
|
||||
terrainReads++;
|
||||
return Blocks.WATER.defaultBlockState().getFluidState();
|
||||
}
|
||||
if (name.equals("getChunk") || name.equals("getChunkIfLoadedImmediately")) {
|
||||
if (name.equals("getChunk")) {
|
||||
chunkReads++;
|
||||
if (arguments.length == 2) {
|
||||
statuslessChunkReads++;
|
||||
} else {
|
||||
statusChunkReads++;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
if (name.equals("getChunkIfLoadedImmediately")) {
|
||||
chunkReads++;
|
||||
return null;
|
||||
}
|
||||
|
||||
@@ -3,7 +3,7 @@ def mainClass = 'art.arcane.iris.Iris'
|
||||
def bootstrapperClass = 'art.arcane.iris.IrisBootstrap'
|
||||
|
||||
String volmLibCoordinate = providers.gradleProperty('volmLibCoordinate')
|
||||
.orElse('com.github.VolmitSoftware:VolmLib:d9026a7c8ebc391c8109f401ce79a0ce65df3969')
|
||||
.orElse('com.github.VolmitSoftware:VolmLib:5486ac97ad6d6833e27275dc768222d377721522')
|
||||
.get()
|
||||
|
||||
dependencies {
|
||||
|
||||
@@ -756,6 +756,7 @@ public class Iris extends VolmitPlugin implements Listener, ReloadAware {
|
||||
IrisStartupValidation.begin();
|
||||
Bukkit.getPluginManager().registerEvents(new IrisStartupAdmissionListener(), this);
|
||||
Bukkit.getPluginManager().registerEvents(pendingWorldReplacements, this);
|
||||
pendingWorldReplacements.registerPlatformEntryListener();
|
||||
boolean enabled = enable();
|
||||
if (!enabled) {
|
||||
return;
|
||||
|
||||
+29
-17
@@ -22,13 +22,13 @@ import art.arcane.iris.Iris;
|
||||
import art.arcane.iris.core.lifecycle.BukkitWorldConfiguration;
|
||||
import art.arcane.iris.core.lifecycle.LifecycleOperationCoordinator;
|
||||
import art.arcane.iris.core.nms.INMS;
|
||||
import art.arcane.iris.core.pack.PackValidationRegistry;
|
||||
import art.arcane.iris.core.tools.IrisToolbelt;
|
||||
import art.arcane.iris.engine.object.IrisDimension;
|
||||
import art.arcane.iris.platform.bukkit.BukkitEnvironment;
|
||||
import art.arcane.iris.util.common.format.C;
|
||||
import art.arcane.iris.util.common.misc.ServerProperties;
|
||||
import art.arcane.volmlib.util.bukkit.WorldIdentity;
|
||||
import org.bukkit.Bukkit;
|
||||
import org.bukkit.NamespacedKey;
|
||||
import org.bukkit.World;
|
||||
import org.bukkit.WorldCreator;
|
||||
@@ -698,16 +698,17 @@ public final class BukkitWorldReconciler {
|
||||
@Override
|
||||
public CompletableFuture<World> createWorld(NamespacedKey worldKey, String dimension, Long seed) {
|
||||
try {
|
||||
String worldName = IrisWorldStorage.logicalName(worldKey);
|
||||
Iris.info("Loading World: %s | Generator: %s", worldName, dimension);
|
||||
ChunkGenerator generator = plugin.getDefaultWorldGenerator(worldName, dimension);
|
||||
IrisDimension irisDimension = IrisWorldGeneratorResolver.loadDimension(worldName, dimension);
|
||||
String logicalWorldName = IrisWorldStorage.logicalName(worldKey);
|
||||
String configuredWorldName = configuredWorldName(worldKey);
|
||||
Iris.info("Loading World: %s | Generator: %s", logicalWorldName, dimension);
|
||||
ChunkGenerator generator = plugin.getDefaultWorldGenerator(configuredWorldName, dimension);
|
||||
IrisDimension irisDimension = IrisWorldGeneratorResolver.loadDimension(configuredWorldName, dimension);
|
||||
if (generator == null || irisDimension == null) {
|
||||
throw new IllegalStateException("Could not resolve the Iris generator or dimension \"" + dimension + "\".");
|
||||
}
|
||||
|
||||
Iris.info(C.LIGHT_PURPLE + "Preparing Spawn for " + worldName + " using Iris:" + dimension + "...");
|
||||
WorldCreator creator = WorldCreatorCompat.ofKey(worldKey)
|
||||
Iris.info(C.LIGHT_PURPLE + "Preparing Spawn for " + logicalWorldName + " using Iris:" + dimension + "...");
|
||||
WorldCreator creator = WorldCreatorCompat.ofPersistentKey(worldKey)
|
||||
.generator(generator)
|
||||
.environment(BukkitEnvironment.from(irisDimension.getEnvironment()));
|
||||
if (seed != null) {
|
||||
@@ -726,7 +727,7 @@ public final class BukkitWorldReconciler {
|
||||
|
||||
@Override
|
||||
public DimensionResolution resolveDimension(NamespacedKey worldKey) {
|
||||
File dimensionsDirectory = new File(IrisWorldStorage.packRoot(worldKey), "dimensions");
|
||||
File dimensionsDirectory = new File(snapshotRoot(worldKey), "dimensions");
|
||||
if (!dimensionsDirectory.isDirectory()) {
|
||||
return DimensionResolution.failed(new IllegalStateException("The world has no Iris dimensions directory."));
|
||||
}
|
||||
@@ -764,19 +765,30 @@ public final class BukkitWorldReconciler {
|
||||
|
||||
@Override
|
||||
public void requireDimensionLoadable(NamespacedKey worldKey, String dimension) {
|
||||
File snapshotRoot = IrisWorldStorage.packRoot(worldKey);
|
||||
boolean snapshotPresent = snapshotRoot.isDirectory();
|
||||
if (snapshotPresent) {
|
||||
IrisWorldGeneratorResolver.requireSnapshotLoadable(snapshotRoot);
|
||||
}
|
||||
String worldName = IrisWorldStorage.logicalName(worldKey);
|
||||
IrisDimension irisDimension = IrisWorldGeneratorResolver.loadDimension(worldName, dimension);
|
||||
File snapshotRoot = snapshotRoot(worldKey);
|
||||
IrisWorldGeneratorResolver.requireSnapshotLoadable(snapshotRoot);
|
||||
String configuredWorldName = configuredWorldName(worldKey);
|
||||
IrisDimension irisDimension = IrisWorldGeneratorResolver.loadDimension(configuredWorldName, dimension);
|
||||
if (irisDimension == null) {
|
||||
throw new IllegalStateException("Could not resolve the Iris dimension \"" + dimension + "\".");
|
||||
}
|
||||
if (!snapshotPresent) {
|
||||
PackValidationRegistry.requireLoadable(irisDimension.getLoader().getDataFolder().getName());
|
||||
}
|
||||
|
||||
private File snapshotRoot(NamespacedKey worldKey) {
|
||||
File levelRoot = IrisWorldStorage.levelRoot();
|
||||
File dimensionRoot = IrisWorldStorage.requireFrozenDimensionRoot(
|
||||
Bukkit.getWorldContainer(),
|
||||
levelRoot,
|
||||
configuredWorldName(worldKey),
|
||||
worldKey
|
||||
);
|
||||
File expectedRoot = WorldCreatorCompat.persistentDimensionRoot(worldKey);
|
||||
if (!dimensionRoot.toPath().toAbsolutePath().normalize()
|
||||
.equals(expectedRoot.toPath().toAbsolutePath().normalize())) {
|
||||
throw new IllegalStateException("Iris world storage does not match the current platform layout for "
|
||||
+ worldKey + ".");
|
||||
}
|
||||
return IrisWorldStorage.requireFrozenPackRoot(dimensionRoot);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+1
-2
@@ -1,6 +1,5 @@
|
||||
package art.arcane.iris.core;
|
||||
|
||||
import net.kyori.adventure.text.Component;
|
||||
import org.bukkit.event.EventHandler;
|
||||
import org.bukkit.event.EventPriority;
|
||||
import org.bukkit.event.Listener;
|
||||
@@ -11,6 +10,6 @@ public final class IrisStartupAdmissionListener implements Listener {
|
||||
public void onAsyncPlayerPreLogin(AsyncPlayerPreLoginEvent event) {
|
||||
IrisStartupValidation.denialReason().ifPresent(reason -> event.disallow(
|
||||
AsyncPlayerPreLoginEvent.Result.KICK_OTHER,
|
||||
Component.text(reason + " Check the server console, correct the reported Iris state, and restart.")));
|
||||
reason + " Check the server console, correct the reported Iris state, and restart."));
|
||||
}
|
||||
}
|
||||
|
||||
+55
-40
@@ -29,12 +29,12 @@ import art.arcane.iris.core.pack.PackValidationRegistry;
|
||||
import art.arcane.iris.core.pack.PackValidationResult;
|
||||
import art.arcane.iris.core.pack.PackValidator;
|
||||
import art.arcane.iris.spi.IrisPlatforms;
|
||||
import art.arcane.iris.core.service.StudioSVC;
|
||||
import art.arcane.iris.engine.object.IrisDimension;
|
||||
import art.arcane.iris.engine.object.IrisWorld;
|
||||
import art.arcane.iris.engine.platform.BukkitChunkGenerator;
|
||||
import art.arcane.iris.util.common.plugin.VolmitPlugin;
|
||||
import lombok.NonNull;
|
||||
import org.bukkit.Bukkit;
|
||||
import org.bukkit.NamespacedKey;
|
||||
import org.bukkit.generator.BiomeProvider;
|
||||
import org.bukkit.generator.ChunkGenerator;
|
||||
@@ -231,9 +231,18 @@ public final class IrisWorldGeneratorResolver {
|
||||
|
||||
@Nullable
|
||||
public static IrisDimension loadDimension(@NonNull String worldName, @NonNull String id) {
|
||||
NamespacedKey worldKey = configuredWorldKey(worldName, IrisWorldStorage.levelRoot().getName());
|
||||
File pack = IrisWorldStorage.packRoot(worldKey);
|
||||
IrisDimension dimension = pack.isDirectory() ? IrisData.get(pack).getDimensionLoader().load(id) : null;
|
||||
File levelRoot = IrisWorldStorage.levelRoot();
|
||||
NamespacedKey worldKey = configuredWorldKey(worldName, levelRoot.getName());
|
||||
String configuredWorldName = IrisWorldStorage.configuredWorldName(worldKey, levelRoot.getName());
|
||||
File pack = IrisWorldStorage.frozenDimensionRoot(
|
||||
Bukkit.getWorldContainer(),
|
||||
levelRoot,
|
||||
configuredWorldName,
|
||||
worldKey
|
||||
)
|
||||
.map(IrisWorldStorage::requireFrozenPackRoot)
|
||||
.orElse(null);
|
||||
IrisDimension dimension = pack == null ? null : IrisData.get(pack).getDimensionLoader().load(id);
|
||||
if (dimension == null) dimension = IrisData.loadAnyDimension(id, null);
|
||||
if (dimension == null) {
|
||||
File packsRoot = IrisPlatforms.get().packsFolderNoCreate();
|
||||
@@ -279,57 +288,63 @@ public final class IrisWorldGeneratorResolver {
|
||||
if (id == null || id.isEmpty()) id = IrisSettings.get().getGenerator().getDefaultWorldType();
|
||||
Iris.debug("Generator ID: " + id + " requested by bukkit/plugin");
|
||||
|
||||
IrisDimension dim = loadDimension(worldName, id);
|
||||
if (dim == null) {
|
||||
throw new RuntimeException("Can't find dimension " + id + "!");
|
||||
}
|
||||
NamespacedKey worldKey = configuredWorldKey(worldName, IrisWorldStorage.levelRoot().getName());
|
||||
File snapshotRoot = IrisWorldStorage.packRoot(worldKey);
|
||||
File dimensionPackRoot = dim.getLoader().getDataFolder();
|
||||
String packName = dimensionPackRoot.getName();
|
||||
try {
|
||||
if (snapshotRoot.toPath().toAbsolutePath().normalize()
|
||||
.equals(dimensionPackRoot.toPath().toAbsolutePath().normalize())) {
|
||||
requireSnapshotLoadable(snapshotRoot);
|
||||
} else {
|
||||
PackValidationRegistry.requireLoadable(packName);
|
||||
}
|
||||
return resolveFrozenWorldGenerator(worldName, id);
|
||||
} catch (RuntimeException failure) {
|
||||
Iris.reportError("Refusing to load configured Iris world '" + worldName
|
||||
+ "' because its frozen world-local pack snapshot could not be used.", failure);
|
||||
Bukkit.shutdown();
|
||||
throw failure;
|
||||
}
|
||||
}
|
||||
|
||||
private ChunkGenerator resolveFrozenWorldGenerator(String worldName, String id) {
|
||||
File levelRoot = IrisWorldStorage.levelRoot();
|
||||
NamespacedKey worldKey = configuredWorldKey(worldName, levelRoot.getName());
|
||||
File dimensionRoot = IrisWorldStorage.requireFrozenDimensionRoot(
|
||||
Bukkit.getWorldContainer(),
|
||||
levelRoot,
|
||||
worldName,
|
||||
worldKey
|
||||
);
|
||||
File expectedDimensionRoot = WorldCreatorCompat.persistentDimensionRoot(worldKey);
|
||||
if (!dimensionRoot.toPath().toAbsolutePath().normalize()
|
||||
.equals(expectedDimensionRoot.toPath().toAbsolutePath().normalize())) {
|
||||
throw new IllegalStateException("Frozen Iris world storage does not match the current platform layout for "
|
||||
+ worldKey + ".");
|
||||
}
|
||||
File snapshotRoot = IrisWorldStorage.requireFrozenPackRoot(dimensionRoot);
|
||||
try {
|
||||
requireSnapshotLoadable(snapshotRoot);
|
||||
} catch (BrokenPackException exception) {
|
||||
Iris.error("Refusing to create world '" + worldName + "' using broken pack '" + packName + "':");
|
||||
Iris.error("Refusing to create world '" + worldName + "' using broken snapshot at '"
|
||||
+ snapshotRoot + "':");
|
||||
for (String reason : exception.getReasons()) {
|
||||
Iris.error(" - " + reason);
|
||||
}
|
||||
throw exception;
|
||||
}
|
||||
|
||||
Iris.debug("Assuming IrisDimension: " + dim.getName());
|
||||
IrisDimension dimension = IrisData.get(snapshotRoot).getDimensionLoader().load(id, false);
|
||||
if (dimension == null) {
|
||||
throw new IllegalStateException("Frozen Iris pack snapshot at " + snapshotRoot
|
||||
+ " does not contain dimension " + id + ".");
|
||||
}
|
||||
|
||||
IrisWorld w = IrisWorld.builder()
|
||||
Iris.debug("Assuming IrisDimension: " + dimension.getName());
|
||||
|
||||
IrisWorld world = IrisWorld.builder()
|
||||
.platformIdentity(worldKey.toString())
|
||||
.name(worldName)
|
||||
.seed(1337)
|
||||
.worldFolder(IrisWorldStorage.dimensionRoot(worldKey))
|
||||
.minHeight(dim.getMinHeight())
|
||||
.maxHeight(dim.getMaxHeight())
|
||||
.worldFolder(dimensionRoot)
|
||||
.minHeight(dimension.getMinHeight())
|
||||
.maxHeight(dimension.getMaxHeight())
|
||||
.build();
|
||||
|
||||
Iris.debug("Generator Config: " + w.toString());
|
||||
Iris.debug("Generator Config: " + world);
|
||||
|
||||
File ff = new File(w.worldFolder(), "iris/pack");
|
||||
IrisDimension installedDimension = ff.isDirectory()
|
||||
? IrisData.get(ff).getDimensionLoader().load(dim.getLoadKey(), false)
|
||||
: null;
|
||||
if (installedDimension == null) {
|
||||
dim = Iris.service(StudioSVC.class).replaceIntoWorld(Iris.getSender(), dim, w.worldFolder());
|
||||
if (dim == null) {
|
||||
throw new IllegalStateException("Failed to install dimension pack for " + id);
|
||||
}
|
||||
} else {
|
||||
dim = installedDimension;
|
||||
}
|
||||
requireSnapshotLoadable(ff);
|
||||
|
||||
return new BukkitChunkGenerator(w, false, ff, dim.getLoadKey());
|
||||
return new BukkitChunkGenerator(world, false, snapshotRoot, dimension.getLoadKey());
|
||||
}
|
||||
|
||||
private record FreshValidation(
|
||||
|
||||
+54
@@ -0,0 +1,54 @@
|
||||
package art.arcane.iris.core;
|
||||
|
||||
import io.papermc.paper.event.player.AsyncPlayerSpawnLocationEvent;
|
||||
import net.kyori.adventure.text.Component;
|
||||
import org.bukkit.Location;
|
||||
import org.bukkit.event.EventHandler;
|
||||
import org.bukkit.event.EventPriority;
|
||||
import org.bukkit.event.Listener;
|
||||
|
||||
import java.util.Objects;
|
||||
import java.util.UUID;
|
||||
|
||||
public final class PaperWorldReplacementEntryListener implements Listener {
|
||||
private final PendingWorldReplacementManager manager;
|
||||
|
||||
public PaperWorldReplacementEntryListener(PendingWorldReplacementManager manager) {
|
||||
this.manager = Objects.requireNonNull(manager, "manager");
|
||||
}
|
||||
|
||||
@EventHandler(priority = EventPriority.HIGHEST)
|
||||
public void onAsyncPlayerSpawnLocation(AsyncPlayerSpawnLocationEvent event) {
|
||||
UUID playerId = event.getConnection().getProfile().getId();
|
||||
if (playerId == null) {
|
||||
return;
|
||||
}
|
||||
try {
|
||||
PendingWorldReplacementManager.ReplacementEntryRedirect redirect = manager.prepareReplacementEntry(
|
||||
playerId,
|
||||
event.getSpawnLocation(),
|
||||
event.isNewPlayer()
|
||||
);
|
||||
if (redirect == null) {
|
||||
return;
|
||||
}
|
||||
Location location = redirect.location();
|
||||
event.setSpawnLocation(location);
|
||||
if (redirect.acknowledgementRequired()) {
|
||||
manager.expectReplacementEntryAcknowledgement(playerId, redirect.transactionId());
|
||||
}
|
||||
} catch (InterruptedException failure) {
|
||||
Thread.currentThread().interrupt();
|
||||
refuseUnsafeEntry(event, playerId, failure);
|
||||
} catch (Throwable failure) {
|
||||
refuseUnsafeEntry(event, playerId, failure);
|
||||
}
|
||||
}
|
||||
|
||||
private void refuseUnsafeEntry(AsyncPlayerSpawnLocationEvent event, UUID playerId, Throwable failure) {
|
||||
manager.reportUnsafeEntry(playerId, failure);
|
||||
event.getConnection().disconnect(Component.text(
|
||||
"Iris could not verify a safe login location after the Overworld replacement. Retry after startup completes."
|
||||
));
|
||||
}
|
||||
}
|
||||
+35
-2
@@ -451,18 +451,51 @@ public final class PendingWorldDeleteQueue implements WorldDeletionQueue {
|
||||
|
||||
if (type == QueueEntryType.EXACT) {
|
||||
NamespacedKey key = IrisWorldStorage.managedKeyFromName(storedName, levelRoot.getName());
|
||||
Path path = IrisWorldStorage.requireSafeManagedDimensionRoot(levelRoot, key).toPath();
|
||||
Path path = currentStorageRoot(levelRoot, key);
|
||||
return List.of(new DeleteTarget(key, path));
|
||||
}
|
||||
|
||||
ArrayList<DeleteTarget> targets = new ArrayList<>(3);
|
||||
for (String familyWorldName : TransientWorldCleanupSupport.worldFamilyNames(storedName)) {
|
||||
NamespacedKey key = IrisWorldStorage.managedKeyFromName(familyWorldName, levelRoot.getName());
|
||||
Path path = IrisWorldStorage.requireSafeManagedDimensionRoot(levelRoot, key).toPath();
|
||||
Path path = currentStorageRoot(levelRoot, key);
|
||||
targets.add(new DeleteTarget(key, path));
|
||||
}
|
||||
return targets;
|
||||
}
|
||||
|
||||
private static Path currentStorageRoot(File levelRoot, NamespacedKey key) {
|
||||
File worldContainer = levelRoot.getAbsoluteFile().getParentFile();
|
||||
if (worldContainer == null) {
|
||||
throw new IllegalArgumentException("Selected level root has no world container: " + levelRoot);
|
||||
}
|
||||
String configuredWorldName = IrisWorldStorage.configuredWorldName(key, levelRoot.getName());
|
||||
Path directRoot = IrisWorldStorage.requireSafeManagedDimensionRoot(levelRoot, key)
|
||||
.toPath()
|
||||
.toAbsolutePath()
|
||||
.normalize();
|
||||
Path dimensionRoot = IrisWorldStorage.frozenDimensionRoot(
|
||||
worldContainer,
|
||||
levelRoot,
|
||||
configuredWorldName,
|
||||
key
|
||||
).map(file -> file.toPath().toAbsolutePath().normalize()).orElse(directRoot);
|
||||
if (dimensionRoot.equals(directRoot)) {
|
||||
return directRoot;
|
||||
}
|
||||
Path configuredDimensionRoot = IrisWorldStorage.configuredDimensionRoot(
|
||||
worldContainer,
|
||||
levelRoot,
|
||||
key
|
||||
).toPath().toAbsolutePath().normalize();
|
||||
if (!dimensionRoot.equals(configuredDimensionRoot)) {
|
||||
throw new IllegalStateException("Iris world storage does not match the current platform layout.");
|
||||
}
|
||||
return IrisWorldStorage.configuredLevelRoot(worldContainer, levelRoot, key)
|
||||
.toPath()
|
||||
.toAbsolutePath()
|
||||
.normalize();
|
||||
}
|
||||
}
|
||||
|
||||
private static Path requireSafeQuarantinePath(File levelRoot, String quarantineName) throws IOException {
|
||||
|
||||
+419
@@ -8,6 +8,7 @@ import art.arcane.iris.core.lifecycle.BukkitWorldConfiguration.WorldGeneratorSna
|
||||
import art.arcane.iris.core.lifecycle.LifecycleOperationCoordinator;
|
||||
import art.arcane.iris.core.lifecycle.WorldReplacementBootstrap;
|
||||
import art.arcane.iris.core.lifecycle.WorldReplacementBootstrapMarker;
|
||||
import art.arcane.iris.core.lifecycle.WorldReplacementEntryGuard;
|
||||
import art.arcane.iris.core.lifecycle.WorldReplacementFilesystem;
|
||||
import art.arcane.iris.core.lifecycle.WorldReplacementFilesystem.ReplacementPaths;
|
||||
import art.arcane.iris.core.lifecycle.WorldReplacementJournal;
|
||||
@@ -15,24 +16,32 @@ import art.arcane.iris.core.lifecycle.WorldReplacementJournal.Phase;
|
||||
import art.arcane.iris.core.lifecycle.WorldReplacementJournal.Transaction;
|
||||
import art.arcane.iris.core.lifecycle.WorldReplacementSeed;
|
||||
import art.arcane.iris.core.pack.PackValidationRegistry;
|
||||
import art.arcane.iris.core.runtime.WorldRuntimeControlService;
|
||||
import art.arcane.iris.core.service.StudioSVC;
|
||||
import art.arcane.iris.core.tools.IrisToolbelt;
|
||||
import art.arcane.iris.engine.object.IrisDimension;
|
||||
import art.arcane.iris.engine.object.IrisEnvironment;
|
||||
import art.arcane.iris.engine.platform.BukkitChunkGenerator;
|
||||
import art.arcane.iris.engine.platform.PlatformChunkGenerator;
|
||||
import art.arcane.iris.util.common.misc.ServerProperties;
|
||||
import art.arcane.iris.util.common.plugin.VolmitSender;
|
||||
import art.arcane.iris.util.common.scheduling.J;
|
||||
import art.arcane.volmlib.util.bukkit.WorldIdentity;
|
||||
import org.bukkit.Bukkit;
|
||||
import org.bukkit.Chunk;
|
||||
import org.bukkit.Location;
|
||||
import org.bukkit.NamespacedKey;
|
||||
import org.bukkit.World;
|
||||
import org.bukkit.event.EventHandler;
|
||||
import org.bukkit.event.EventPriority;
|
||||
import org.bukkit.event.Listener;
|
||||
import org.bukkit.event.player.PlayerJoinEvent;
|
||||
import org.bukkit.event.world.WorldLoadEvent;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.lang.reflect.Constructor;
|
||||
import java.lang.reflect.InvocationTargetException;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.ArrayList;
|
||||
@@ -40,23 +49,60 @@ import java.util.HashSet;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.Objects;
|
||||
import java.util.Optional;
|
||||
import java.util.OptionalLong;
|
||||
import java.util.Set;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.concurrent.ExecutionException;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.concurrent.TimeoutException;
|
||||
|
||||
public final class PendingWorldReplacementManager implements Listener {
|
||||
private static final WorldSlotKey OVERWORLD_KEY = WorldSlotKey.minecraft("overworld");
|
||||
private static final long SAFE_ENTRY_TIMEOUT_SECONDS = 30L;
|
||||
|
||||
private final Iris plugin;
|
||||
private final Set<UUID> cleanupInFlight = new HashSet<>();
|
||||
private final Set<UUID> verificationInFlight = new HashSet<>();
|
||||
private final ConcurrentHashMap<UUID, UUID> pendingEntryAcknowledgements = new ConcurrentHashMap<>();
|
||||
private volatile WorldReplacementEntryGuard.Entry overworldEntryGuard;
|
||||
private volatile Path overworldEntryWorldDirectory;
|
||||
private volatile CompletableFuture<Location> overworldSafeEntry;
|
||||
private volatile UUID overworldEntryAwaitingVerification;
|
||||
private volatile World overworldEntryWorld;
|
||||
private volatile boolean paperEntryListenerRegistered;
|
||||
|
||||
public PendingWorldReplacementManager(Iris plugin) {
|
||||
this.plugin = Objects.requireNonNull(plugin, "plugin");
|
||||
}
|
||||
|
||||
public void registerPlatformEntryListener() {
|
||||
ClassLoader loader = getClass().getClassLoader();
|
||||
try {
|
||||
Class.forName("io.papermc.paper.event.player.AsyncPlayerSpawnLocationEvent", false, loader);
|
||||
} catch (ClassNotFoundException | LinkageError unavailable) {
|
||||
return;
|
||||
}
|
||||
try {
|
||||
Class<?> listenerType = Class.forName(
|
||||
"art.arcane.iris.core.PaperWorldReplacementEntryListener",
|
||||
true,
|
||||
loader
|
||||
);
|
||||
Constructor<?> constructor = listenerType.getConstructor(PendingWorldReplacementManager.class);
|
||||
Listener listener = (Listener) constructor.newInstance(this);
|
||||
Bukkit.getPluginManager().registerEvents(listener, plugin);
|
||||
paperEntryListenerRegistered = true;
|
||||
} catch (InvocationTargetException failure) {
|
||||
Throwable cause = failure.getCause() == null ? failure : failure.getCause();
|
||||
throw new IllegalStateException("Paper replacement entry listener registration failed.", cause);
|
||||
} catch (ReflectiveOperationException | LinkageError failure) {
|
||||
throw new IllegalStateException("Paper replacement entry listener is unavailable.", failure);
|
||||
}
|
||||
}
|
||||
|
||||
public NamespacedKey resolveRequestedWorldKey(String requestedName) {
|
||||
NamespacedKey worldKey = IrisWorldStorage.replacementKeyFromName(
|
||||
requestedName,
|
||||
@@ -129,6 +175,9 @@ public final class PendingWorldReplacementManager implements Listener {
|
||||
paths.stage(),
|
||||
seedSelection
|
||||
);
|
||||
if (target.slotKind() == SlotKind.VANILLA_OVERWORLD) {
|
||||
WorldReplacementEntryGuard.stage(target.levelRoot(), paths.stage(), transactionId);
|
||||
}
|
||||
File stagedPack = paths.stage().resolve("iris/pack").toFile();
|
||||
IrisWorldGeneratorResolver.requireSnapshotLoadable(stagedPack);
|
||||
String packFingerprint = WorldReplacementFilesystem.fingerprintPack(stagedPack.toPath());
|
||||
@@ -205,6 +254,20 @@ public final class PendingWorldReplacementManager implements Listener {
|
||||
public synchronized void processPendingStartupReplacements() {
|
||||
ArrayList<String> failures = new ArrayList<>();
|
||||
ArrayList<String> restartBoundaries = new ArrayList<>();
|
||||
try {
|
||||
loadOverworldEntryGuard();
|
||||
} catch (Throwable failure) {
|
||||
String message = "Iris could not load the Overworld replacement entry guard: " + detail(failure);
|
||||
Iris.reportError(message, failure);
|
||||
IrisStartupValidation.markPacksInvalid(List.of(message));
|
||||
return;
|
||||
}
|
||||
if (overworldEntryGuard != null && !paperEntryListenerRegistered) {
|
||||
String message = "A pending Overworld replacement requires the Paper safe-entry capability.";
|
||||
Iris.error(message);
|
||||
IrisStartupValidation.markPacksInvalid(List.of(message));
|
||||
return;
|
||||
}
|
||||
List<Transaction> transactions;
|
||||
try {
|
||||
transactions = loadTransactions();
|
||||
@@ -215,6 +278,9 @@ public final class PendingWorldReplacementManager implements Listener {
|
||||
return;
|
||||
}
|
||||
for (Transaction transaction : transactions) {
|
||||
if (OVERWORLD_KEY.equals(transaction.worldKey()) && transaction.phase() == Phase.PUBLISHED) {
|
||||
overworldEntryAwaitingVerification = transaction.id();
|
||||
}
|
||||
try {
|
||||
inspectStartupTransaction(transaction);
|
||||
} catch (RestartBoundaryRequired boundary) {
|
||||
@@ -229,6 +295,7 @@ public final class PendingWorldReplacementManager implements Listener {
|
||||
Iris.reportError(message, failure);
|
||||
}
|
||||
}
|
||||
scheduleLoadedOverworldEntryPreparation();
|
||||
if (!failures.isEmpty()) {
|
||||
IrisStartupValidation.markPacksInvalid(failures);
|
||||
}
|
||||
@@ -258,6 +325,245 @@ public final class PendingWorldReplacementManager implements Listener {
|
||||
scheduleRuntimeCapture(transaction, 0);
|
||||
}
|
||||
}
|
||||
scheduleLoadedOverworldEntryPreparation();
|
||||
}
|
||||
|
||||
private void scheduleLoadedOverworldEntryPreparation() {
|
||||
if (overworldEntryGuard == null) {
|
||||
return;
|
||||
}
|
||||
try {
|
||||
J.s(this::prepareLoadedOverworldEntry);
|
||||
} catch (Throwable failure) {
|
||||
failOverworldEntryPreparation(failure);
|
||||
}
|
||||
}
|
||||
|
||||
private void prepareLoadedOverworldEntry() {
|
||||
World world;
|
||||
try {
|
||||
world = WorldIdentity.resolve(toNamespacedKey(OVERWORLD_KEY)).orElse(null);
|
||||
} catch (Throwable failure) {
|
||||
failOverworldEntryPreparation(failure);
|
||||
return;
|
||||
}
|
||||
if (world != null) {
|
||||
prepareOverworldEntry(world);
|
||||
}
|
||||
}
|
||||
|
||||
private void prepareOverworldEntry(World world) {
|
||||
WorldReplacementEntryGuard.Entry guard = overworldEntryGuard;
|
||||
if (guard == null
|
||||
|| guard.transactionId().equals(overworldEntryAwaitingVerification)
|
||||
|| !OVERWORLD_KEY.equals(toWorldSlotKey(WorldIdentity.key(world)))) {
|
||||
return;
|
||||
}
|
||||
CompletableFuture<Location> targetFuture;
|
||||
synchronized (this) {
|
||||
if (overworldSafeEntry != null) {
|
||||
return;
|
||||
}
|
||||
targetFuture = new CompletableFuture<>();
|
||||
overworldSafeEntry = targetFuture;
|
||||
overworldEntryWorld = world;
|
||||
}
|
||||
try {
|
||||
PlatformChunkGenerator generator = IrisToolbelt.access(world);
|
||||
if (!(generator instanceof BukkitChunkGenerator bukkitGenerator)) {
|
||||
throw new IOException("The replaced Overworld does not have a Bukkit Iris generator.");
|
||||
}
|
||||
Location anchor = bukkitGenerator.getInitialSpawnLocation(world);
|
||||
int chunkX = anchor.getBlockX() >> 4;
|
||||
int chunkZ = anchor.getBlockZ() >> 4;
|
||||
WorldRuntimeControlService runtime = WorldRuntimeControlService.get();
|
||||
CompletableFuture<Chunk> chunkFuture = runtime.requestChunkAsync(world, chunkX, chunkZ, true);
|
||||
if (chunkFuture == null) {
|
||||
throw new IOException("The replacement spawn chunk request was not accepted.");
|
||||
}
|
||||
chunkFuture
|
||||
.thenCompose(chunk -> runtime.resolveSafeEntry(world, anchor))
|
||||
.thenCompose(this::applyOverworldSpawn)
|
||||
.thenCompose(this::persistOverworldSpawn)
|
||||
.whenComplete((safeEntry, failure) -> {
|
||||
if (failure != null) {
|
||||
targetFuture.completeExceptionally(failure);
|
||||
Iris.reportError("Could not prepare a safe spawn for the replaced Overworld.", failure);
|
||||
return;
|
||||
}
|
||||
targetFuture.complete(safeEntry.clone());
|
||||
retireOverworldEntryIfComplete(guard.transactionId());
|
||||
});
|
||||
} catch (Throwable failure) {
|
||||
targetFuture.completeExceptionally(failure);
|
||||
Iris.reportError("Could not prepare a safe spawn for the replaced Overworld.", failure);
|
||||
}
|
||||
}
|
||||
|
||||
private CompletableFuture<Location> applyOverworldSpawn(Location safeEntry) {
|
||||
Location requiredSafeEntry = Objects.requireNonNull(safeEntry, "safeEntry").clone();
|
||||
World world = Objects.requireNonNull(requiredSafeEntry.getWorld(), "safeEntry.world");
|
||||
CompletableFuture<Location> applied = new CompletableFuture<>();
|
||||
int chunkX = requiredSafeEntry.getBlockX() >> 4;
|
||||
int chunkZ = requiredSafeEntry.getBlockZ() >> 4;
|
||||
boolean scheduled = J.runRegion(world, chunkX, chunkZ, () -> {
|
||||
try {
|
||||
if (!world.setSpawnLocation(requiredSafeEntry)) {
|
||||
throw new IOException("The server rejected the replacement spawn location.");
|
||||
}
|
||||
applied.complete(requiredSafeEntry.clone());
|
||||
} catch (Throwable failure) {
|
||||
applied.completeExceptionally(failure);
|
||||
}
|
||||
});
|
||||
if (!scheduled) {
|
||||
applied.completeExceptionally(new IOException("Could not schedule the replacement spawn update."));
|
||||
}
|
||||
return applied;
|
||||
}
|
||||
|
||||
private CompletableFuture<Location> persistOverworldSpawn(Location safeEntry) {
|
||||
Location requiredSafeEntry = Objects.requireNonNull(safeEntry, "safeEntry").clone();
|
||||
World world = Objects.requireNonNull(requiredSafeEntry.getWorld(), "safeEntry.world");
|
||||
CompletableFuture<Location> persisted = new CompletableFuture<>();
|
||||
boolean scheduled = J.runGlobal(() -> {
|
||||
try {
|
||||
world.save();
|
||||
persisted.complete(requiredSafeEntry.clone());
|
||||
} catch (Throwable failure) {
|
||||
persisted.completeExceptionally(failure);
|
||||
}
|
||||
});
|
||||
if (!scheduled) {
|
||||
persisted.completeExceptionally(new IOException("Could not schedule replacement spawn persistence."));
|
||||
}
|
||||
return persisted;
|
||||
}
|
||||
|
||||
private CompletableFuture<Boolean> inspectLoginCollision(Location location) {
|
||||
Location requiredLocation = Objects.requireNonNull(location, "location").clone();
|
||||
World world = Objects.requireNonNull(requiredLocation.getWorld(), "location.world");
|
||||
int chunkX = requiredLocation.getBlockX() >> 4;
|
||||
int chunkZ = requiredLocation.getBlockZ() >> 4;
|
||||
WorldRuntimeControlService runtime = WorldRuntimeControlService.get();
|
||||
CompletableFuture<Chunk> chunkFuture = runtime.requestChunkAsync(world, chunkX, chunkZ, true);
|
||||
if (chunkFuture == null) {
|
||||
return CompletableFuture.failedFuture(new IOException("The saved login chunk request was not accepted."));
|
||||
}
|
||||
return chunkFuture.thenCompose(chunk -> inspectLoadedLoginCollision(requiredLocation));
|
||||
}
|
||||
|
||||
private CompletableFuture<Boolean> inspectLoadedLoginCollision(Location location) {
|
||||
World world = Objects.requireNonNull(location.getWorld(), "location.world");
|
||||
CompletableFuture<Boolean> inspected = new CompletableFuture<>();
|
||||
int chunkX = location.getBlockX() >> 4;
|
||||
int chunkZ = location.getBlockZ() >> 4;
|
||||
boolean scheduled = J.runRegion(world, chunkX, chunkZ, () -> {
|
||||
try {
|
||||
int blockY = location.getBlockY();
|
||||
if (blockY < world.getMinHeight() || blockY + 1 >= world.getMaxHeight()) {
|
||||
inspected.complete(false);
|
||||
return;
|
||||
}
|
||||
boolean feetPassable = world.getBlockAt(location.getBlockX(), blockY, location.getBlockZ())
|
||||
.isPassable();
|
||||
boolean headPassable = world.getBlockAt(location.getBlockX(), blockY + 1, location.getBlockZ())
|
||||
.isPassable();
|
||||
inspected.complete(feetPassable && headPassable);
|
||||
} catch (Throwable failure) {
|
||||
inspected.completeExceptionally(failure);
|
||||
}
|
||||
});
|
||||
if (!scheduled) {
|
||||
inspected.completeExceptionally(new IOException("Could not schedule the saved login collision check."));
|
||||
}
|
||||
return inspected;
|
||||
}
|
||||
|
||||
private void completeOverworldEntry(UUID playerId, UUID transactionId) {
|
||||
try {
|
||||
J.a(() -> completeOverworldEntryAsync(playerId, transactionId));
|
||||
} catch (Throwable failure) {
|
||||
Iris.reportError("Could not record a completed Overworld replacement entry for " + playerId + ".", failure);
|
||||
}
|
||||
}
|
||||
|
||||
private void completeOverworldEntryAsync(UUID playerId, UUID transactionId) {
|
||||
boolean retire = false;
|
||||
try {
|
||||
synchronized (this) {
|
||||
WorldReplacementEntryGuard.Entry current = overworldEntryGuard;
|
||||
Path worldDirectory = overworldEntryWorldDirectory;
|
||||
if (current == null
|
||||
|| worldDirectory == null
|
||||
|| !current.transactionId().equals(transactionId)
|
||||
|| !current.pendingPlayers().contains(playerId)) {
|
||||
return;
|
||||
}
|
||||
Optional<WorldReplacementEntryGuard.Entry> updated = WorldReplacementEntryGuard.completePlayer(
|
||||
worldDirectory,
|
||||
transactionId,
|
||||
playerId
|
||||
);
|
||||
overworldEntryGuard = updated.orElse(null);
|
||||
retire = overworldEntryGuard != null && overworldEntryGuard.pendingPlayers().isEmpty();
|
||||
}
|
||||
} catch (Throwable failure) {
|
||||
Iris.reportError("Could not record a completed Overworld replacement entry for " + playerId + ".", failure);
|
||||
return;
|
||||
}
|
||||
if (retire) {
|
||||
retireOverworldEntryIfCompleteAsync(transactionId);
|
||||
}
|
||||
}
|
||||
|
||||
private void retireOverworldEntryIfComplete(UUID transactionId) {
|
||||
try {
|
||||
J.a(() -> retireOverworldEntryIfCompleteAsync(transactionId));
|
||||
} catch (Throwable failure) {
|
||||
Iris.reportError("Could not schedule Overworld replacement entry marker retirement.", failure);
|
||||
}
|
||||
}
|
||||
|
||||
private synchronized void retireOverworldEntryIfCompleteAsync(UUID transactionId) {
|
||||
WorldReplacementEntryGuard.Entry current = overworldEntryGuard;
|
||||
Path worldDirectory = overworldEntryWorldDirectory;
|
||||
CompletableFuture<Location> safeEntry = overworldSafeEntry;
|
||||
if (current == null
|
||||
|| worldDirectory == null
|
||||
|| !current.transactionId().equals(transactionId)
|
||||
|| !current.pendingPlayers().isEmpty()
|
||||
|| safeEntry == null
|
||||
|| !safeEntry.isDone()
|
||||
|| safeEntry.isCompletedExceptionally()) {
|
||||
return;
|
||||
}
|
||||
try {
|
||||
if (!WorldReplacementEntryGuard.retireIfEmpty(worldDirectory, transactionId)) {
|
||||
return;
|
||||
}
|
||||
overworldEntryGuard = null;
|
||||
overworldEntryWorldDirectory = null;
|
||||
overworldSafeEntry = null;
|
||||
overworldEntryWorld = null;
|
||||
pendingEntryAcknowledgements.entrySet().removeIf(entry -> entry.getValue().equals(transactionId));
|
||||
} catch (Throwable failure) {
|
||||
Iris.reportError("Could not retire the completed Overworld replacement entry marker.", failure);
|
||||
}
|
||||
}
|
||||
|
||||
void reportUnsafeEntry(UUID playerId, Throwable failure) {
|
||||
Iris.reportError("Refused unsafe Overworld replacement entry for " + playerId + ".", failure);
|
||||
}
|
||||
|
||||
private synchronized void failOverworldEntryPreparation(Throwable failure) {
|
||||
CompletableFuture<Location> future = overworldSafeEntry;
|
||||
if (future == null) {
|
||||
future = new CompletableFuture<>();
|
||||
overworldSafeEntry = future;
|
||||
}
|
||||
future.completeExceptionally(failure);
|
||||
Iris.reportError("Could not prepare a safe spawn for the replaced Overworld.", failure);
|
||||
}
|
||||
|
||||
@EventHandler(priority = EventPriority.MONITOR)
|
||||
@@ -269,9 +575,81 @@ public final class PendingWorldReplacementManager implements Listener {
|
||||
Iris.reportError("Failed to capture a loaded world identity for replacement verification.", failure);
|
||||
return;
|
||||
}
|
||||
if (OVERWORLD_KEY.equals(worldKey)) {
|
||||
prepareOverworldEntry(event.getWorld());
|
||||
}
|
||||
J.a(() -> discoverLoadedWorldTransaction(worldKey));
|
||||
}
|
||||
|
||||
ReplacementEntryRedirect prepareReplacementEntry(UUID playerId, Location savedLocation, boolean newPlayer)
|
||||
throws IOException, InterruptedException, ExecutionException, TimeoutException {
|
||||
WorldReplacementEntryGuard.Entry guard = overworldEntryGuard;
|
||||
if (guard == null || playerId == null) {
|
||||
return null;
|
||||
}
|
||||
boolean pendingPlayer = guard.pendingPlayers().contains(playerId);
|
||||
if (!pendingPlayer && !newPlayer) {
|
||||
return null;
|
||||
}
|
||||
Location requiredSavedLocation = Objects.requireNonNull(savedLocation, "savedLocation").clone();
|
||||
World replacementWorld = overworldEntryWorld;
|
||||
if (replacementWorld == null) {
|
||||
throw new IOException("The replacement Overworld is not ready.");
|
||||
}
|
||||
if (requiredSavedLocation.getWorld() != replacementWorld) {
|
||||
if (pendingPlayer) {
|
||||
completeOverworldEntry(playerId, guard.transactionId());
|
||||
}
|
||||
return null;
|
||||
}
|
||||
if (!newPlayer) {
|
||||
boolean collisionSafe = inspectLoginCollision(requiredSavedLocation)
|
||||
.get(SAFE_ENTRY_TIMEOUT_SECONDS, TimeUnit.SECONDS);
|
||||
if (collisionSafe) {
|
||||
completeOverworldEntry(playerId, guard.transactionId());
|
||||
return null;
|
||||
}
|
||||
}
|
||||
CompletableFuture<Location> safeEntry = overworldSafeEntry;
|
||||
if (safeEntry == null) {
|
||||
throw new IOException("The replacement safe spawn is not ready.");
|
||||
}
|
||||
Location prepared = safeEntry.get(SAFE_ENTRY_TIMEOUT_SECONDS, TimeUnit.SECONDS).clone();
|
||||
prepared.setYaw(requiredSavedLocation.getYaw());
|
||||
prepared.setPitch(requiredSavedLocation.getPitch());
|
||||
return new ReplacementEntryRedirect(guard.transactionId(), prepared, pendingPlayer);
|
||||
}
|
||||
|
||||
void expectReplacementEntryAcknowledgement(UUID playerId, UUID transactionId) throws IOException {
|
||||
WorldReplacementEntryGuard.Entry guard = overworldEntryGuard;
|
||||
if (guard == null
|
||||
|| !guard.transactionId().equals(transactionId)
|
||||
|| !guard.pendingPlayers().contains(playerId)) {
|
||||
throw new IOException("The Overworld replacement entry receipt is no longer active.");
|
||||
}
|
||||
pendingEntryAcknowledgements.put(playerId, transactionId);
|
||||
}
|
||||
|
||||
@EventHandler(priority = EventPriority.MONITOR)
|
||||
public void onPlayerJoin(PlayerJoinEvent event) {
|
||||
UUID playerId = event.getPlayer().getUniqueId();
|
||||
UUID transactionId = pendingEntryAcknowledgements.remove(playerId);
|
||||
if (transactionId == null) {
|
||||
return;
|
||||
}
|
||||
boolean scheduled = J.runEntity(event.getPlayer(), () -> {
|
||||
try {
|
||||
event.getPlayer().saveData();
|
||||
completeOverworldEntry(playerId, transactionId);
|
||||
} catch (Throwable failure) {
|
||||
Iris.reportError("Could not persist safe Overworld replacement entry for " + playerId + ".", failure);
|
||||
}
|
||||
});
|
||||
if (!scheduled) {
|
||||
Iris.error("Could not schedule safe Overworld replacement entry persistence for " + playerId + ".");
|
||||
}
|
||||
}
|
||||
|
||||
private void discoverLoadedWorldTransaction(WorldSlotKey worldKey) {
|
||||
Transaction transaction;
|
||||
try {
|
||||
@@ -412,6 +790,10 @@ public final class PendingWorldReplacementManager implements Listener {
|
||||
try {
|
||||
writeTransaction(committed);
|
||||
Iris.success("Committed Iris world replacement for " + transaction.worldKey() + ".");
|
||||
if (OVERWORLD_KEY.equals(transaction.worldKey())) {
|
||||
overworldEntryAwaitingVerification = null;
|
||||
scheduleLoadedOverworldEntryPreparation();
|
||||
}
|
||||
scheduleCommittedCleanup(committed);
|
||||
} catch (Throwable failure) {
|
||||
Iris.reportError("The replacement for " + transaction.worldKey()
|
||||
@@ -456,6 +838,9 @@ public final class PendingWorldReplacementManager implements Listener {
|
||||
private void initiateRollback(Transaction transaction, Throwable failure) {
|
||||
Iris.reportError("Iris world replacement verification failed for " + transaction.worldKey()
|
||||
+ "; the retained world will be restored on restart.", failure);
|
||||
if (OVERWORLD_KEY.equals(transaction.worldKey())) {
|
||||
clearOverworldEntryGuard();
|
||||
}
|
||||
try {
|
||||
Transaction rollback = transaction.withPhase(Phase.ROLLBACK_PENDING);
|
||||
writeTransaction(rollback);
|
||||
@@ -608,6 +993,24 @@ public final class PendingWorldReplacementManager implements Listener {
|
||||
return plugin.getDataFolder().toPath().toAbsolutePath().normalize();
|
||||
}
|
||||
|
||||
private synchronized void loadOverworldEntryGuard() throws IOException {
|
||||
ExactWorldSlotPathPolicy.Target target = resolveTarget(OVERWORLD_KEY);
|
||||
Optional<WorldReplacementEntryGuard.Entry> loaded = WorldReplacementEntryGuard.load(target.worldDirectory());
|
||||
overworldEntryGuard = loaded.orElse(null);
|
||||
overworldEntryWorldDirectory = loaded.isPresent() ? target.worldDirectory() : null;
|
||||
overworldSafeEntry = null;
|
||||
overworldEntryAwaitingVerification = null;
|
||||
}
|
||||
|
||||
private synchronized void clearOverworldEntryGuard() {
|
||||
overworldEntryGuard = null;
|
||||
overworldEntryWorldDirectory = null;
|
||||
overworldSafeEntry = null;
|
||||
overworldEntryAwaitingVerification = null;
|
||||
overworldEntryWorld = null;
|
||||
pendingEntryAcknowledgements.clear();
|
||||
}
|
||||
|
||||
private ExactWorldSlotPathPolicy.Target resolveTransactionTarget(Transaction transaction) throws IOException {
|
||||
return WorldReplacementJournal.resolveTarget(transaction, IrisWorldStorage.levelRoot().toPath());
|
||||
}
|
||||
@@ -738,6 +1141,22 @@ public final class PendingWorldReplacementManager implements Listener {
|
||||
private record VanillaLevelContext(boolean allowNether, boolean allowEnd) {
|
||||
}
|
||||
|
||||
record ReplacementEntryRedirect(
|
||||
UUID transactionId,
|
||||
Location location,
|
||||
boolean acknowledgementRequired
|
||||
) {
|
||||
ReplacementEntryRedirect {
|
||||
Objects.requireNonNull(transactionId, "transactionId");
|
||||
location = Objects.requireNonNull(location, "location").clone();
|
||||
}
|
||||
|
||||
@Override
|
||||
public Location location() {
|
||||
return location.clone();
|
||||
}
|
||||
}
|
||||
|
||||
private static final class RestartBoundaryRequired extends IOException {
|
||||
private RestartBoundaryRequired(String message) {
|
||||
super(message);
|
||||
|
||||
@@ -801,8 +801,14 @@ public class CommandIris implements DirectorExecutor {
|
||||
}
|
||||
|
||||
boolean doesWorldExist(String worldName) {
|
||||
File worldDirectory = IrisWorldStorage.dimensionRoot(worldName);
|
||||
return worldDirectory.exists() && worldDirectory.isDirectory();
|
||||
NamespacedKey worldKey = IrisWorldStorage.managedKeyFromName(worldName);
|
||||
File levelRoot = IrisWorldStorage.levelRoot();
|
||||
return IrisWorldStorage.frozenDimensionRoot(
|
||||
Bukkit.getWorldContainer(),
|
||||
levelRoot,
|
||||
IrisWorldStorage.configuredWorldName(worldKey, levelRoot.getName()),
|
||||
worldKey
|
||||
).isPresent();
|
||||
}
|
||||
|
||||
public static class ManagedWorldNameHandler implements DirectorParameterHandler<String> {
|
||||
|
||||
+55
@@ -93,6 +93,61 @@ public class IrisWorldGeneratorResolverTest {
|
||||
);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void configuredWorldResolutionUsesOnlyFrozenWorldLocalSnapshot() throws Exception {
|
||||
String source = Files.readString(Path.of(
|
||||
"src/main/java/art/arcane/iris/core/IrisWorldGeneratorResolver.java"));
|
||||
int resolverStart = source.indexOf("private ChunkGenerator resolveFrozenWorldGenerator(");
|
||||
int resolverEnd = source.indexOf("private record FreshValidation", resolverStart);
|
||||
String resolver = source.substring(resolverStart, resolverEnd);
|
||||
|
||||
int dimensionRoot = resolver.indexOf("IrisWorldStorage.requireFrozenDimensionRoot(");
|
||||
int currentPlatformRoot = resolver.indexOf("WorldCreatorCompat.persistentDimensionRoot(worldKey)");
|
||||
int layoutRefusal = resolver.indexOf(
|
||||
"Frozen Iris world storage does not match the current platform layout",
|
||||
currentPlatformRoot
|
||||
);
|
||||
int snapshotRoot = resolver.indexOf("IrisWorldStorage.requireFrozenPackRoot(dimensionRoot)");
|
||||
int validation = resolver.indexOf("requireSnapshotLoadable(snapshotRoot)");
|
||||
int exactLoad = resolver.indexOf(
|
||||
"IrisData.get(snapshotRoot).getDimensionLoader().load(id, false)"
|
||||
);
|
||||
int canonicalIdentity = resolver.indexOf(".platformIdentity(worldKey.toString())");
|
||||
int resolvedStorage = resolver.indexOf(".worldFolder(dimensionRoot)");
|
||||
|
||||
assertTrue(dimensionRoot >= 0);
|
||||
assertTrue(currentPlatformRoot > dimensionRoot);
|
||||
assertTrue(layoutRefusal > currentPlatformRoot);
|
||||
assertTrue(snapshotRoot > layoutRefusal);
|
||||
assertTrue(validation > snapshotRoot);
|
||||
assertTrue(exactLoad > validation);
|
||||
assertTrue(canonicalIdentity > exactLoad);
|
||||
assertTrue(resolvedStorage > canonicalIdentity);
|
||||
assertFalse(resolver.contains("loadDimension("));
|
||||
assertFalse(resolver.contains("loadAnyDimension("));
|
||||
assertFalse(resolver.contains("replaceIntoWorld("));
|
||||
assertFalse(resolver.contains("installIntoWorld("));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void configuredWorldSnapshotFailureStopsStartupAndRethrows() throws Exception {
|
||||
String source = Files.readString(Path.of(
|
||||
"src/main/java/art/arcane/iris/core/IrisWorldGeneratorResolver.java"));
|
||||
int resolverStart = source.indexOf("public ChunkGenerator resolveDefaultWorldGenerator(");
|
||||
int resolverEnd = source.indexOf("private ChunkGenerator resolveFrozenWorldGenerator(", resolverStart);
|
||||
String resolver = source.substring(resolverStart, resolverEnd);
|
||||
|
||||
int failureCapture = resolver.indexOf("catch (RuntimeException failure)");
|
||||
int report = resolver.indexOf("Iris.reportError(", failureCapture);
|
||||
int shutdown = resolver.indexOf("Bukkit.shutdown()", report);
|
||||
int rethrow = resolver.indexOf("throw failure", shutdown);
|
||||
|
||||
assertTrue(failureCapture >= 0);
|
||||
assertTrue(report > failureCapture);
|
||||
assertTrue(shutdown > report);
|
||||
assertTrue(rethrow > shutdown);
|
||||
}
|
||||
|
||||
private static void writeValidPack(Path packRoot) throws Exception {
|
||||
Files.createDirectories(packRoot.resolve("dimensions"));
|
||||
Files.createDirectories(packRoot.resolve("regions"));
|
||||
|
||||
+13
@@ -174,6 +174,19 @@ public class PendingWorldDeleteQueueTest {
|
||||
), family);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void exactLogicalEntryResolvesCurrentCraftBukkitLevelStorage() throws IOException {
|
||||
Path worldContainer = temporaryFolder.newFolder("configured-delete-server").toPath();
|
||||
File levelRoot = Files.createDirectory(worldContainer.resolve("world")).toFile();
|
||||
Path configuredLevelRoot = worldContainer.resolve("world_iris_alpha");
|
||||
Files.createDirectories(configuredLevelRoot.resolve("dimensions/iris/alpha"));
|
||||
|
||||
assertEquals(
|
||||
List.of(configuredLevelRoot.toAbsolutePath().normalize()),
|
||||
PendingWorldDeleteQueue.resolveQueueEntryPaths(levelRoot, "exact:alpha")
|
||||
);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void failedSafeDeletionSignalsQueueRetentionAndSucceedsOnRetry() throws IOException {
|
||||
File levelRoot = temporaryFolder.newFolder("retry-world");
|
||||
|
||||
+78
@@ -164,6 +164,84 @@ public class PendingWorldReplacementThreadAffinityTest {
|
||||
assertFalse(irisSource.contains("J.a(pendingWorldReplacements::verifyLoadedPublishedWorlds)"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void paperLoginHookIsIsolatedFromAlwaysLoadedSpigotClasses() throws Exception {
|
||||
String managerSource = Files.readString(Path.of(
|
||||
"src/main/java/art/arcane/iris/core/PendingWorldReplacementManager.java"));
|
||||
String irisSource = Files.readString(Path.of("src/main/java/art/arcane/iris/Iris.java"));
|
||||
String listenerSource = Files.readString(Path.of(
|
||||
"src/main/java/art/arcane/iris/core/PaperWorldReplacementEntryListener.java"));
|
||||
String registration = method(managerSource, "public void registerPlatformEntryListener()");
|
||||
|
||||
assertFalse(managerSource.contains("import io.papermc.paper.event.player.AsyncPlayerSpawnLocationEvent"));
|
||||
assertFalse(managerSource.contains("AsyncPlayerSpawnLocationEvent event"));
|
||||
assertFalse(irisSource.contains("AsyncPlayerSpawnLocationEvent"));
|
||||
assertTrue(registration.contains("Class.forName(\"io.papermc.paper.event.player.AsyncPlayerSpawnLocationEvent\""));
|
||||
assertTrue(registration.contains("Class.forName("));
|
||||
assertTrue(registration.contains("PaperWorldReplacementEntryListener"));
|
||||
assertTrue(irisSource.contains("pendingWorldReplacements.registerPlatformEntryListener();"));
|
||||
assertTrue(listenerSource.contains("onAsyncPlayerSpawnLocation(AsyncPlayerSpawnLocationEvent event)"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void redirectedPlayerReceiptSurvivesUntilTheMaterializedPositionIsSaved() throws Exception {
|
||||
String managerSource = Files.readString(Path.of(
|
||||
"src/main/java/art/arcane/iris/core/PendingWorldReplacementManager.java"));
|
||||
String listenerSource = Files.readString(Path.of(
|
||||
"src/main/java/art/arcane/iris/core/PaperWorldReplacementEntryListener.java"));
|
||||
String preparation = method(
|
||||
managerSource,
|
||||
"ReplacementEntryRedirect prepareReplacementEntry(UUID playerId, Location savedLocation, boolean newPlayer)"
|
||||
);
|
||||
String acknowledgement = method(
|
||||
managerSource,
|
||||
"void expectReplacementEntryAcknowledgement(UUID playerId, UUID transactionId)"
|
||||
);
|
||||
String join = method(managerSource, "public void onPlayerJoin(PlayerJoinEvent event)");
|
||||
String listener = method(
|
||||
listenerSource,
|
||||
"public void onAsyncPlayerSpawnLocation(AsyncPlayerSpawnLocationEvent event)"
|
||||
);
|
||||
|
||||
assertTrue(preparation.contains("return new ReplacementEntryRedirect(guard.transactionId(), prepared, pendingPlayer)"));
|
||||
assertFalse(preparation.substring(preparation.indexOf("CompletableFuture<Location> safeEntry"))
|
||||
.contains("completeOverworldEntry("));
|
||||
assertBefore(listener, "event.setSpawnLocation(location)",
|
||||
"manager.expectReplacementEntryAcknowledgement(playerId, redirect.transactionId())");
|
||||
assertTrue(acknowledgement.contains("pendingEntryAcknowledgements.put(playerId, transactionId)"));
|
||||
assertBefore(join, "event.getPlayer().saveData()", "completeOverworldEntry(playerId, transactionId)");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void replacementSpawnIsPersistedBeforeFinalMarkerRetirement() throws Exception {
|
||||
String managerSource = Files.readString(Path.of(
|
||||
"src/main/java/art/arcane/iris/core/PendingWorldReplacementManager.java"));
|
||||
String listenerSource = Files.readString(Path.of(
|
||||
"src/main/java/art/arcane/iris/core/PaperWorldReplacementEntryListener.java"));
|
||||
String preparation = method(managerSource, "private void prepareOverworldEntry(World world)");
|
||||
String persistence = method(managerSource, "private CompletableFuture<Location> persistOverworldSpawn(Location safeEntry)");
|
||||
String retirement = method(
|
||||
managerSource,
|
||||
"private synchronized void retireOverworldEntryIfCompleteAsync(UUID transactionId)"
|
||||
);
|
||||
String listener = method(
|
||||
listenerSource,
|
||||
"public void onAsyncPlayerSpawnLocation(AsyncPlayerSpawnLocationEvent event)"
|
||||
);
|
||||
String generatorSource = Files.readString(Path.of(System.getProperty("iris.bukkitChunkGeneratorSource")));
|
||||
|
||||
assertBefore(preparation, ".thenCompose(this::applyOverworldSpawn)",
|
||||
".thenCompose(this::persistOverworldSpawn)");
|
||||
assertBefore(preparation, "targetFuture.complete(safeEntry.clone())",
|
||||
"retireOverworldEntryIfComplete(guard.transactionId())");
|
||||
assertTrue(persistence.contains("world.save()"));
|
||||
assertTrue(retirement.contains("!current.pendingPlayers().isEmpty()"));
|
||||
assertTrue(retirement.contains("!safeEntry.isDone()"));
|
||||
assertTrue(retirement.contains("safeEntry.isCompletedExceptionally()"));
|
||||
assertTrue(listener.contains("event.isNewPlayer()"));
|
||||
assertTrue(generatorSource.contains("world.getHighestBlockYAt(initialSpawn) + 1"));
|
||||
}
|
||||
|
||||
private static PendingWorldReplacementManager.PublishedWorldRuntimeState runtimeState(
|
||||
WorldSlotKey worldKey,
|
||||
long seed,
|
||||
|
||||
Reference in New Issue
Block a user