Merge branch 'wave3b/3' into feat/irisapi-host

# Conflicts:
#	core/src/main/java/art/arcane/iris/core/modules/IrisModuleHost.java
#	core/src/test/java/art/arcane/iris/core/modules/BuiltInPack.java
This commit is contained in:
piexel committed 2026-10-15 07:09:43 +02:00
commit 4928a80035
61 files changed
+1784 -1307

No files matched your search

@@ -4,9 +4,7 @@ import art.arcane.iris.engine.object.world.biome.custom.IrisBiomeCustom;
import art.arcane.iris.engine.framework.Engine; import art.arcane.iris.engine.framework.Engine;
import art.arcane.iris.engine.framework.NativeFeatureGenerationPolicy; import art.arcane.iris.engine.framework.NativeFeatureGenerationPolicy;
import art.arcane.iris.engine.object.world.biome.IrisBiome; import art.arcane.iris.engine.object.world.biome.IrisBiome;
import art.arcane.iris.engine.object.decoration.IrisDecorationStep;
import art.arcane.iris.engine.object.world.dimension.IrisDimension; import art.arcane.iris.engine.object.world.dimension.IrisDimension;
import art.arcane.iris.engine.object.decoration.IrisImportedFeatureControl;
import art.arcane.iris.spi.IrisLogging; import art.arcane.iris.spi.IrisLogging;
import it.unimi.dsi.fastutil.ints.IntArraySet; import it.unimi.dsi.fastutil.ints.IntArraySet;
import it.unimi.dsi.fastutil.ints.IntSet; import it.unimi.dsi.fastutil.ints.IntSet;
@@ -32,6 +30,7 @@ import net.minecraft.world.level.levelgen.placement.PlacedFeature;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Arrays; import java.util.Arrays;
import java.util.BitSet;
import java.util.HashMap; import java.util.HashMap;
import java.util.LinkedHashSet; import java.util.LinkedHashSet;
import java.util.List; import java.util.List;
@@ -112,22 +111,22 @@ final class ImportedFeatureStage {
} }
private void build(WorldGenLevel level, IrisDimension dimension) { private void build(WorldGenLevel level, IrisDimension dimension) {
IrisImportedFeatureControl control; boolean enabled;
try { try {
control = NativeFeatureGenerationPolicy.control(engine); enabled = NativeFeatureGenerationPolicy.isEnabled(engine);
} catch (RuntimeException error) { } catch (RuntimeException error) {
IrisLogging.error("Iris could not read importedFeatures for this dimension; features off: " IrisLogging.error("Iris could not read importedFeatures for this dimension; features off: "
+ error); + error);
markInert(dimension); markInert(dimension);
return; return;
} }
if (!control.shouldGenerateFeatures()) { if (!enabled) {
markInert(dimension); markInert(dimension);
return; return;
} }
FeatureTable built; FeatureTable built;
try { try {
built = buildTable(level, control, dimension); built = buildTable(level, dimension);
} catch (Throwable error) { } catch (Throwable error) {
IrisLogging.error("Iris importedFeatures is off for " + dimensionKey() IrisLogging.error("Iris importedFeatures is off for " + dimensionKey()
+ ": feature table construction failed: " + error); + ": feature table construction failed: " + error);
@@ -150,8 +149,7 @@ final class ImportedFeatureStage {
inertDimension = dimension; inertDimension = dimension;
} }
private FeatureTable buildTable(WorldGenLevel level, IrisImportedFeatureControl control, private FeatureTable buildTable(WorldGenLevel level, IrisDimension dimension) {
IrisDimension dimension) {
Registry<Biome> registry = level.registryAccess().lookupOrThrow(Registries.BIOME); Registry<Biome> registry = level.registryAccess().lookupOrThrow(Registries.BIOME);
Set<String> visibleKeys = visibleBiomeKeys(); Set<String> visibleKeys = visibleBiomeKeys();
// Registry-ordered walk, never a hash-ordered set: FeatureSorter's cycle detection walks this list and // Registry-ordered walk, never a hash-ordered set: FeatureSorter's cycle detection walks this list and
@@ -185,9 +183,17 @@ final class ImportedFeatureStage {
+ ". Remove or reorder the conflicting content, or leave importedFeatures.enabled false."); + ". Remove or reorder the conflicting content, or leave importedFeatures.enabled false.");
return null; return null;
} }
boolean filtered = control.getDisabled() != null && !control.getDisabled().isEmpty(); return new FeatureTable(dimension, List.copyOf(biomes), Set.copyOf(biomes),
return new FeatureTable(dimension, control, List.copyOf(biomes), Set.copyOf(biomes), Map.copyOf(byKey), steps, Map.copyOf(derivatives), generatedSteps(steps.size()));
Map.copyOf(byKey), steps, Map.copyOf(derivatives), filtered); }
/** The decoration steps whose features generate, by the platform's step index. */
private BitSet generatedSteps(int stepCount) {
BitSet generated = new BitSet(stepCount);
for (int stepIndex = 0; stepIndex < stepCount; stepIndex++) {
generated.set(stepIndex, NativeFeatureGenerationPolicy.shouldGenerateStep(engine, stepIndex));
}
return generated;
} }
/** /**
@@ -290,7 +296,7 @@ final class ImportedFeatureStage {
try { try {
for (int stepIndex = 0; stepIndex < steps.size(); stepIndex++) { for (int stepIndex = 0; stepIndex < steps.size(); stepIndex++) {
if (!table.control().shouldGenerateStep(IrisDecorationStep.byOrdinal(stepIndex))) { if (!table.generatedSteps().get(stepIndex)) {
continue; continue;
} }
placeStep(level, table, steps.get(stepIndex), featureRegistry, chunkBiomes, owner, placeStep(level, table, steps.get(stepIndex), featureRegistry, chunkBiomes, owner,
@@ -327,11 +333,9 @@ final class ImportedFeatureStage {
Arrays.sort(featureIndices); Arrays.sort(featureIndices);
for (int globalIndex : featureIndices) { for (int globalIndex : featureIndices) {
PlacedFeature feature = stepData.features().get(globalIndex); PlacedFeature feature = stepData.features().get(globalIndex);
if (table.filtered()) { Identifier featureId = featureRegistry.getKey(feature);
Identifier featureId = featureRegistry.getKey(feature); if (featureId != null && !NativeFeatureGenerationPolicy.shouldGenerate(engine, featureId.toString())) {
if (featureId != null && !table.control().shouldGenerate(featureId.toString())) { continue;
continue;
}
} }
random.setFeatureSeed(decorationSeed, globalIndex, stepIndex); random.setFeatureSeed(decorationSeed, globalIndex, stepIndex);
level.setCurrentlyGenerating(() -> describeFeature(featureRegistry, feature)); level.setCurrentlyGenerating(() -> describeFeature(featureRegistry, feature));
@@ -390,10 +394,10 @@ final class ImportedFeatureStage {
return identifier == null ? null : identifier.toString().toLowerCase(Locale.ROOT); return identifier == null ? null : identifier.toString().toLowerCase(Locale.ROOT);
} }
private record FeatureTable(IrisDimension dimension, IrisImportedFeatureControl control, private record FeatureTable(IrisDimension dimension,
List<Holder<Biome>> biomes, Set<Holder<Biome>> biomeSet, List<Holder<Biome>> biomes, Set<Holder<Biome>> biomeSet,
Map<String, Holder<Biome>> byKey, Map<String, Holder<Biome>> byKey,
List<FeatureSorter.StepFeatureData> steps, List<FeatureSorter.StepFeatureData> steps,
Map<String, Holder<Biome>> derivatives, boolean filtered) { Map<String, Holder<Biome>> derivatives, BitSet generatedSteps) {
} }
} }
@@ -3,7 +3,7 @@ package art.arcane.iris.core.nms.v26_2_R1;
import art.arcane.iris.engine.framework.Engine; import art.arcane.iris.engine.framework.Engine;
import art.arcane.iris.engine.framework.GenerationSessionException; import art.arcane.iris.engine.framework.GenerationSessionException;
import art.arcane.iris.engine.framework.GenerationSessionLease; import art.arcane.iris.engine.framework.GenerationSessionLease;
import art.arcane.iris.engine.framework.IrisStructureLocator; import art.arcane.iris.core.modules.ModuleServices;
import art.arcane.iris.engine.framework.NativeStructureOwnershipRecord; import art.arcane.iris.engine.framework.NativeStructureOwnershipRecord;
import art.arcane.iris.engine.framework.NativeStructureStartPlan; import art.arcane.iris.engine.framework.NativeStructureStartPlan;
import art.arcane.iris.engine.framework.NativeStructureGenerationPolicy; import art.arcane.iris.engine.framework.NativeStructureGenerationPolicy;
@@ -208,7 +208,7 @@ public class IrisChunkGenerator extends CustomChunkGenerator {
throw new IllegalStateException("Native structure locate received an unregistered structure holder"); throw new IllegalStateException("Native structure locate received an unregistered structure holder");
} }
String structureId = id.toString(); String structureId = id.toString();
if (!IrisStructureLocator.hasNativePlacement(engine, structureId)) { if (!ModuleServices.startsStructure(engine, structureId)) {
continue; continue;
} }
NativeStructureLocatePersistence.Probe probe = NativeStructureLocatePersistence.probe( NativeStructureLocatePersistence.Probe probe = NativeStructureLocatePersistence.probe(
@@ -220,19 +220,19 @@ public class IrisChunkGenerator extends CustomChunkGenerator {
searches.sort(Comparator.comparing(IrisNativeLocateSearch::structureId)); searches.sort(Comparator.comparing(IrisNativeLocateSearch::structureId));
for (int attempt = 0; attempt < NativeStructureLocatePersistence.MAX_SELECTED_CANDIDATE_RETRIES; attempt++) { for (int attempt = 0; attempt < NativeStructureLocatePersistence.MAX_SELECTED_CANDIDATE_RETRIES; attempt++) {
IrisNativeLocateSearch bestSearch = null; IrisNativeLocateSearch bestSearch = null;
IrisStructureLocator.LocateResult bestResult = null; ModuleServices.StructureSearch bestResult = null;
long bestDistance = Long.MAX_VALUE; long bestDistance = Long.MAX_VALUE;
for (IrisNativeLocateSearch search : searches) { for (IrisNativeLocateSearch search : searches) {
IrisStructureLocator.LocateResult result = search.search().predict(); ModuleServices.StructureSearch result = search.search().predict();
if (result.status() == IrisStructureLocator.LocateStatus.SEARCH_LIMIT_REACHED) { if (result.outcome() == ModuleServices.StructureSearch.Outcome.SEARCH_LIMIT_REACHED) {
throw new IllegalStateException("Iris structure locate reached its safety limit for " throw new IllegalStateException("Iris structure locate reached its safety limit for "
+ search.structureId() + " within " + radius + " placement rings"); + search.structureId() + " within " + radius + " placement rings");
} }
if (!result.found()) { if (!result.found()) {
continue; continue;
} }
long dx = (long) result.originX() - pos.getX(); long dx = (long) result.x() - pos.getX();
long dz = (long) result.originZ() - pos.getZ(); long dz = (long) result.z() - pos.getZ();
long distance = dx * dx + dz * dz; long distance = dx * dx + dz * dz;
if (distance < bestDistance) { if (distance < bestDistance) {
bestDistance = distance; bestDistance = distance;
@@ -245,7 +245,7 @@ public class IrisChunkGenerator extends CustomChunkGenerator {
pos, null, () -> { }, nativeLocated, nativeReference); pos, null, () -> { }, nativeLocated, nativeReference);
} }
Pair<BlockPos, Holder<Structure>> predicted = Pair.of( Pair<BlockPos, Holder<Structure>> predicted = Pair.of(
new BlockPos(bestResult.originX(), bestResult.baseY(), bestResult.originZ()), new BlockPos(bestResult.x(), bestResult.y(), bestResult.z()),
bestSearch.holder()); bestSearch.holder());
if (NativeStructureLocateResults.nearest(pos, predicted, nativeLocated) != predicted) { if (NativeStructureLocateResults.nearest(pos, predicted, nativeLocated) != predicted) {
return NativeStructureLocateResults.selectAndReference( return NativeStructureLocateResults.selectAndReference(
@@ -258,8 +258,8 @@ public class IrisChunkGenerator extends CustomChunkGenerator {
continue; continue;
} }
BlockPos located = new BlockPos( BlockPos located = new BlockPos(
bestResult.originX(), verified.ownership().locatorY(), bestResult.x(), verified.ownership().locatorY(),
bestResult.originZ()); bestResult.z());
Pair<BlockPos, Holder<Structure>> irisLocated = Pair.of(located, bestSearch.holder()); Pair<BlockPos, Holder<Structure>> irisLocated = Pair.of(located, bestSearch.holder());
IrisNativeLocateSearch selectedSearch = bestSearch; IrisNativeLocateSearch selectedSearch = bestSearch;
NativeStructureLocatePersistence.VerifiedStart selectedStart = verified; NativeStructureLocatePersistence.VerifiedStart selectedStart = verified;
@@ -31,9 +31,9 @@ public class IrisChunkGeneratorMonumentLocateContractTest {
String irisHelper = source.substring(irisHelperStart, filterStart); String irisHelper = source.substring(irisHelperStart, filterStart);
int registryLookup = irisHelper.indexOf("level.registryAccess().lookupOrThrow(Registries.STRUCTURE)"); int registryLookup = irisHelper.indexOf("level.registryAccess().lookupOrThrow(Registries.STRUCTURE)");
int placedCheck = irisHelper.indexOf( int placedCheck = irisHelper.indexOf(
"if (!IrisStructureLocator.hasNativePlacement(engine, structureId))"); "if (!ModuleServices.startsStructure(engine, structureId))");
int irisLocate = irisHelper.indexOf("NativeStructureLocatePersistence.search(", placedCheck); int irisLocate = irisHelper.indexOf("NativeStructureLocatePersistence.search(", placedCheck);
int searchLimit = irisHelper.indexOf("LocateStatus.SEARCH_LIMIT_REACHED", irisLocate); int searchLimit = irisHelper.indexOf("Outcome.SEARCH_LIMIT_REACHED", irisLocate);
int nativeFilter = outerMethod.indexOf("filterReachableStructures(level, holders)"); int nativeFilter = outerMethod.indexOf("filterReachableStructures(level, holders)");
int nativePrediction = outerMethod.indexOf("NativeStructureVanillaLocator.predict(", nativeFilter); int nativePrediction = outerMethod.indexOf("NativeStructureVanillaLocator.predict(", nativeFilter);
int irisResolution = outerMethod.indexOf("return findNearestIrisStructure(", nativePrediction); int irisResolution = outerMethod.indexOf("return findNearestIrisStructure(", nativePrediction);
@@ -3,7 +3,9 @@ package art.arcane.iris.nativegen;
import art.arcane.iris.engine.framework.NativeStructureOwnershipRecord; import art.arcane.iris.engine.framework.NativeStructureOwnershipRecord;
import art.arcane.iris.engine.framework.NativeStructureStartPlan; import art.arcane.iris.engine.framework.NativeStructureStartPlan;
import art.arcane.iris.engine.framework.StructurePlacementGrid; import art.arcane.iris.engine.framework.StructurePlacementGrid;
import art.arcane.iris.engine.object.structure.IrisStructurePlacement; import art.arcane.iris.builtin.structure.StructurePlacement;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import art.arcane.iris.engine.framework.NativeStartMemo; import art.arcane.iris.engine.framework.NativeStartMemo;
import art.arcane.iris.engine.framework.NativeStructureReach; import art.arcane.iris.engine.framework.NativeStructureReach;
import net.minecraft.SharedConstants; import net.minecraft.SharedConstants;
@@ -242,7 +244,7 @@ public class NativeStructureOwnershipFingerprintTest {
private static NativeStructureStartPlan plan(ChunkPos origin, int baseY) { private static NativeStructureStartPlan plan(ChunkPos origin, int baseY) {
return new NativeStructureStartPlan("minecraft:monument", origin.x(), origin.z(), baseY, false, false, return new NativeStructureStartPlan("minecraft:monument", origin.x(), origin.z(), baseY, false, false,
StructurePlacementGrid.placementIdentity(new IrisStructurePlacement().setPlacementId("monument-test")), StructurePlacementGrid.placementIdentity(placementWithId("monument-test")),
null, new NativeStartMemo("{\"mode\":\"SOURCE\"}", "null")); null, new NativeStartMemo("{\"mode\":\"SOURCE\"}", "null"));
} }
@@ -328,4 +330,11 @@ public class NativeStructureOwnershipFingerprintTest {
} }
return null; return null;
} }
/** A structure placement as a pack writing only its {@code placementId} has it. */
private static StructurePlacement placementWithId(String placementId) {
JsonObject json = new JsonObject();
json.addProperty("placementId", placementId);
return new Gson().fromJson(json, StructurePlacement.class);
}
} }
@@ -5,7 +5,9 @@ import art.arcane.iris.engine.framework.NativeStructureStartPlan;
import art.arcane.iris.engine.framework.StructurePlacementGrid; import art.arcane.iris.engine.framework.StructurePlacementGrid;
import art.arcane.iris.engine.framework.NativeStartMemo; import art.arcane.iris.engine.framework.NativeStartMemo;
import art.arcane.iris.engine.framework.NativeStructureReach; import art.arcane.iris.engine.framework.NativeStructureReach;
import art.arcane.iris.engine.object.structure.IrisStructurePlacement; import art.arcane.iris.builtin.structure.StructurePlacement;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import net.minecraft.SharedConstants; import net.minecraft.SharedConstants;
import net.minecraft.core.Direction; import net.minecraft.core.Direction;
import net.minecraft.core.HolderSet; import net.minecraft.core.HolderSet;
@@ -295,7 +297,7 @@ public class NativeStructureOwnershipRecoveryTest {
monumentStart(structure(), origin, 1L)).minY(), monumentStart(structure(), origin, 1L)).minY(),
false, false,
false, false,
StructurePlacementGrid.placementIdentity(new IrisStructurePlacement().setPlacementId(placementId)), StructurePlacementGrid.placementIdentity(placementWithId(placementId)),
null, null,
new NativeStartMemo(terrain, "null") new NativeStartMemo(terrain, "null")
); );
@@ -322,4 +324,11 @@ public class NativeStructureOwnershipRecoveryTest {
} }
return false; return false;
} }
/** A structure placement as a pack writing only its {@code placementId} has it. */
private static StructurePlacement placementWithId(String placementId) {
JsonObject json = new JsonObject();
json.addProperty("placementId", placementId);
return new Gson().fromJson(json, StructurePlacement.class);
}
} }
@@ -26,7 +26,6 @@ import art.arcane.iris.core.localization.IrisLanguage;
import art.arcane.iris.core.datapack.DatapackIngestService; import art.arcane.iris.core.datapack.DatapackIngestService;
import art.arcane.iris.core.service.ObjectStudioSaveService; import art.arcane.iris.core.service.ObjectStudioSaveService;
import art.arcane.iris.engine.framework.Engine; import art.arcane.iris.engine.framework.Engine;
import art.arcane.iris.engine.framework.IrisStructureLocator;
import art.arcane.iris.engine.framework.NativeStructureGenerationPolicy; import art.arcane.iris.engine.framework.NativeStructureGenerationPolicy;
import art.arcane.iris.engine.framework.StructureReachability; import art.arcane.iris.engine.framework.StructureReachability;
import art.arcane.iris.engine.object.world.biome.IrisBiome; import art.arcane.iris.engine.object.world.biome.IrisBiome;
@@ -146,8 +145,8 @@ public class CommandFind implements DirectorExecutor {
NativeStructureGenerationStatus status = registered NativeStructureGenerationStatus status = registered
? NativeStructureGenerationPolicy.resolve(e, structureKey) ? NativeStructureGenerationPolicy.resolve(e, structureKey)
: null; : null;
boolean nativePlacement = IrisStructureLocator.hasNativePlacement(e, structureKey); boolean nativePlacement = ModuleServices.startsStructure(e, structureKey);
boolean locatableNativePlacement = IrisStructureLocator.hasLocatableNativePlacement(e, structureKey); boolean locatableNativePlacement = ModuleServices.canLocateStart(e, structureKey);
boolean locatableEditablePlacement = ModuleServices.canLocateStructure(e, structureKey); boolean locatableEditablePlacement = ModuleServices.canLocateStructure(e, structureKey);
World targetWorld = target.getWorld(); World targetWorld = target.getWorld();
boolean nativeGenerationEnabled = targetWorld.canGenerateStructures(); boolean nativeGenerationEnabled = targetWorld.canGenerateStructures();
@@ -273,8 +272,8 @@ public class CommandFind implements DirectorExecutor {
String normalizedKey = entry.getKey(); String normalizedKey = entry.getKey();
String key = entry.getValue(); String key = entry.getValue();
NativeStructureGenerationStatus status = NativeStructureGenerationPolicy.resolve(engine, key); NativeStructureGenerationStatus status = NativeStructureGenerationPolicy.resolve(engine, key);
boolean nativePlacement = IrisStructureLocator.hasNativePlacement(engine, key); boolean nativePlacement = ModuleServices.startsStructure(engine, key);
boolean locatableNativePlacement = IrisStructureLocator.hasLocatableNativePlacement(engine, key); boolean locatableNativePlacement = ModuleServices.canLocateStart(engine, key);
boolean locatableEditablePlacement = ModuleServices.canLocateStructure(engine, key); boolean locatableEditablePlacement = ModuleServices.canLocateStructure(engine, key);
StructureLookupRoute route = selectStructureLookupRoute( StructureLookupRoute route = selectStructureLookupRoute(
true, status, nativePlacement, locatableNativePlacement, true, status, nativePlacement, locatableNativePlacement,
@@ -296,18 +295,18 @@ public class CommandFind implements DirectorExecutor {
int configuredUnregistered = 0; int configuredUnregistered = 0;
Set<String> configuredUnregisteredKeys = new LinkedHashSet<>(); Set<String> configuredUnregisteredKeys = new LinkedHashSet<>();
for (String configuredKey : IrisStructureLocator.placedKeys(engine)) { for (String configuredKey : ModuleServices.placedStructures(engine)) {
String normalizedKey = normalizeStructureKey(configuredKey); String normalizedKey = normalizeStructureKey(configuredKey);
if (normalizedKey.isEmpty() if (normalizedKey.isEmpty()
|| registeredKeys.containsKey(normalizedKey) || registeredKeys.containsKey(normalizedKey)
|| !IrisStructureLocator.hasNativePlacement(engine, configuredKey) || !ModuleServices.startsStructure(engine, configuredKey)
|| !configuredUnregisteredKeys.add(normalizedKey)) { || !configuredUnregisteredKeys.add(normalizedKey)) {
continue; continue;
} }
exclusions.add(new StructureExclusion( exclusions.add(new StructureExclusion(
StructureExclusionKind.UNREGISTERED, configuredKey, null, StructureExclusionKind.UNREGISTERED, configuredKey, null,
describeConfiguredUnregisteredNative( describeConfiguredUnregisteredNative(
IrisStructureLocator.hasLocatableNativePlacement(engine, configuredKey)))); ModuleServices.canLocateStart(engine, configuredKey))));
configuredUnregistered++; configuredUnregistered++;
} }
@@ -319,11 +318,11 @@ public class CommandFind implements DirectorExecutor {
String normalizedKey = normalizeStructureKey(editableKey); String normalizedKey = normalizeStructureKey(editableKey);
if (!isUnplacedEditableCandidate( if (!isUnplacedEditableCandidate(
normalizedKey, registeredKeys.keySet(), locatableEditableKeys, normalizedKey, registeredKeys.keySet(), locatableEditableKeys,
IrisStructureLocator.hasNativePlacement(engine, editableKey)) ModuleServices.startsStructure(engine, editableKey))
|| !unplacedEditableKeys.add(normalizedKey)) { || !unplacedEditableKeys.add(normalizedKey)) {
continue; continue;
} }
boolean configuredPlacement = IrisStructureLocator.hasEditablePlacement(engine, editableKey); boolean configuredPlacement = ModuleServices.placesStructure(engine, editableKey);
String reason = configuredPlacement String reason = configuredPlacement
? "editable Iris structure has a configured placement, but no matching placement is active " ? "editable Iris structure has a configured placement, but no matching placement is active "
+ "because its density is not positive or its Y band does not intersect this world" + "because its density is not positive or its Y band does not intersect this world"
@@ -28,7 +28,7 @@ import art.arcane.iris.core.structure.StructureCaptureImporter;
import art.arcane.iris.core.structure.StructureImporter; import art.arcane.iris.core.structure.StructureImporter;
import art.arcane.iris.core.structure.StructureIndexService; import art.arcane.iris.core.structure.StructureIndexService;
import art.arcane.iris.engine.framework.Engine; import art.arcane.iris.engine.framework.Engine;
import art.arcane.iris.engine.framework.IrisStructureLocator; import art.arcane.iris.core.modules.ModuleServices;
import art.arcane.iris.engine.framework.NativeStructureGenerationPolicy; import art.arcane.iris.engine.framework.NativeStructureGenerationPolicy;
import art.arcane.iris.engine.framework.PlacedStructurePiece; import art.arcane.iris.engine.framework.PlacedStructurePiece;
import art.arcane.iris.engine.framework.StructureAssembler; import art.arcane.iris.engine.framework.StructureAssembler;
@@ -156,7 +156,7 @@ public class CommandStructure implements DirectorExecutor {
} }
} }
} }
for (String placedKey : IrisStructureLocator.placedKeys(engine)) { for (String placedKey : ModuleServices.placedStructures(engine)) {
if (!structureKeys.contains(placedKey)) { if (!structureKeys.contains(placedKey)) {
structureKeys.add(placedKey); structureKeys.add(placedKey);
} }
@@ -177,7 +177,7 @@ public class CommandStructure implements DirectorExecutor {
for (String keyName : structureKeys) { for (String keyName : structureKeys) {
NativeStructureGenerationStatus status = NativeStructureGenerationPolicy.resolve(engine, keyName); NativeStructureGenerationStatus status = NativeStructureGenerationPolicy.resolve(engine, keyName);
statuses.put(keyName, status); statuses.put(keyName, status);
requiresNativeReachability |= !IrisStructureLocator.isPlaced(engine, keyName) requiresNativeReachability |= !ModuleServices.placesStructure(engine, keyName)
&& status == NativeStructureGenerationStatus.GENERATE_NATIVE; && status == NativeStructureGenerationStatus.GENERATE_NATIVE;
} }
Set<String> reachable = Set.of(); Set<String> reachable = Set.of();
@@ -199,11 +199,11 @@ public class CommandStructure implements DirectorExecutor {
int errors = 0; int errors = 0;
for (String keyName : structureKeys) { for (String keyName : structureKeys) {
NativeStructureGenerationStatus status = statuses.get(keyName); NativeStructureGenerationStatus status = statuses.get(keyName);
if (IrisStructureLocator.isPlaced(engine, keyName)) { if (ModuleServices.placesStructure(engine, keyName)) {
try { try {
IrisStructureLocator.LocateResult result = ModuleServices.StructureSearch result =
IrisStructureLocator.locate(engine, keyName, centerX, centerZ, searchRadius); ModuleServices.locateStructure(engine, keyName, centerX, centerZ, searchRadius);
if (result.status() == IrisStructureLocator.LocateStatus.SEARCH_LIMIT_REACHED) { if (result.outcome() == ModuleServices.StructureSearch.Outcome.SEARCH_LIMIT_REACHED) {
searchLimited++; searchLimited++;
messages.add(C.YELLOW + "[iris-search-limit] " + C.WHITE + keyName + C.YELLOW messages.add(C.YELLOW + "[iris-search-limit] " + C.WHITE + keyName + C.YELLOW
+ ": unable to complete the density search before its safety limit was reached"); + ": unable to complete the density search before its safety limit was reached");
@@ -215,7 +215,7 @@ public class CommandStructure implements DirectorExecutor {
} }
located++; located++;
messages.add(C.AQUA + "[iris-planned] " + C.WHITE + keyName + C.GREEN + " @ " messages.add(C.AQUA + "[iris-planned] " + C.WHITE + keyName + C.GREEN + " @ "
+ result.originX() + "," + result.baseY() + "," + result.originZ()); + result.x() + "," + result.y() + "," + result.z());
} catch (Throwable error) { } catch (Throwable error) {
errors++; errors++;
messages.add(C.RED + "[error] " + C.WHITE + keyName + C.RED + ": " messages.add(C.RED + "[error] " + C.WHITE + keyName + C.RED + ": "
@@ -35,7 +35,7 @@ public class IrisStructureLocateCommandContractTest {
int nativeResolution = method.indexOf("resolveNativeStructure(structureKey)"); int nativeResolution = method.indexOf("resolveNativeStructure(structureKey)");
int policyResolution = method.indexOf("NativeStructureGenerationPolicy.resolve(", nativeResolution); int policyResolution = method.indexOf("NativeStructureGenerationPolicy.resolve(", nativeResolution);
int nativeLocatableCheck = method.indexOf( int nativeLocatableCheck = method.indexOf(
"IrisStructureLocator.hasLocatableNativePlacement(e, structureKey)", policyResolution); "ModuleServices.canLocateStart(e, structureKey)", policyResolution);
int editableLocatableCheck = method.indexOf( int editableLocatableCheck = method.indexOf(
"ModuleServices.canLocateStructure(e, structureKey)", nativeLocatableCheck); "ModuleServices.canLocateStructure(e, structureKey)", nativeLocatableCheck);
int worldGenerationCheck = method.indexOf("targetWorld.canGenerateStructures()", editableLocatableCheck); int worldGenerationCheck = method.indexOf("targetWorld.canGenerateStructures()", editableLocatableCheck);
@@ -49,7 +49,7 @@ public class IrisStructureLocateCommandContractTest {
assertTrue(worldGenerationCheck > editableLocatableCheck); assertTrue(worldGenerationCheck > editableLocatableCheck);
assertTrue(routeResolution > editableLocatableCheck); assertTrue(routeResolution > editableLocatableCheck);
assertTrue(nativeLocate > routeResolution); assertTrue(nativeLocate > routeResolution);
assertFalse(method.contains("IrisStructureLocator.isPlaced(e, structureKey)")); assertFalse(method.contains("ModuleServices.placesStructure(e, structureKey)"));
assertFalse(method.contains("NativeStructureLocateCapability")); assertFalse(method.contains("NativeStructureLocateCapability"));
} }
@@ -232,7 +232,7 @@ public class IrisStructureLocateCommandContractTest {
assertTrue(source.contains("[iris-search-limit]")); assertTrue(source.contains("[iris-search-limit]"));
assertTrue(source.contains("density searches safety-limited")); assertTrue(source.contains("density searches safety-limited"));
assertTrue(source.contains("result.originX() + \",\" + result.baseY() + \",\" + result.originZ()")); assertTrue(source.contains("result.x() + \",\" + result.y() + \",\" + result.z()"));
assertFalse(source.contains("at[0] + 8")); assertFalse(source.contains("at[0] + 8"));
assertFalse(source.contains("at[2] + 8")); assertFalse(source.contains("at[2] + 8"));
} }
@@ -282,7 +282,7 @@ public class IrisStructureLocateCommandContractTest {
String method = source.substring(methodStart, methodEnd); String method = source.substring(methodStart, methodEnd);
int policyResolution = method.indexOf("NativeStructureGenerationPolicy.resolve(engine, keyName)"); int policyResolution = method.indexOf("NativeStructureGenerationPolicy.resolve(engine, keyName)");
int nativeRequirement = method.indexOf( int nativeRequirement = method.indexOf(
"requiresNativeReachability |= !IrisStructureLocator.isPlaced", policyResolution); "requiresNativeReachability |= !ModuleServices.placesStructure", policyResolution);
int reachabilityGuard = method.indexOf("if (requiresNativeReachability)", nativeRequirement); int reachabilityGuard = method.indexOf("if (requiresNativeReachability)", nativeRequirement);
int reachabilityLookup = method.indexOf("StructureReachability.reachableKeys(engine)", reachabilityGuard); int reachabilityLookup = method.indexOf("StructureReachability.reachableKeys(engine)", reachabilityGuard);
@@ -1,7 +1,8 @@
package art.arcane.iris.nativegen; package art.arcane.iris.nativegen;
import art.arcane.iris.engine.framework.Engine; import art.arcane.iris.engine.framework.Engine;
import art.arcane.iris.engine.framework.IrisStructureLocator; import art.arcane.iris.core.modules.ModuleServices;
import art.arcane.iris.core.modules.StructureSearchLimitException;
import art.arcane.iris.engine.framework.NativeStructureOwnershipRecord; import art.arcane.iris.engine.framework.NativeStructureOwnershipRecord;
import art.arcane.iris.spi.IrisLogging; import art.arcane.iris.spi.IrisLogging;
import net.minecraft.SharedConstants; import net.minecraft.SharedConstants;
@@ -149,7 +150,7 @@ public final class NativeStructureLocatePersistence {
private void claim() { private void claim() {
if (used >= maximum) { if (used >= maximum) {
throw new IrisStructureLocator.CandidateSearchLimitException(); throw new StructureSearchLimitException();
} }
used++; used++;
} }
@@ -256,20 +257,19 @@ public final class NativeStructureLocatePersistence {
this.probe = probe; this.probe = probe;
} }
public IrisStructureLocator.LocateResult predict() { public ModuleServices.StructureSearch predict() {
if (rejectedChunks.size() >= MAX_SELECTED_CANDIDATE_RETRIES) { if (rejectedChunks.size() >= MAX_SELECTED_CANDIDATE_RETRIES) {
return new IrisStructureLocator.LocateResult( return ModuleServices.StructureSearch.SEARCH_LIMIT_REACHED;
IrisStructureLocator.LocateStatus.SEARCH_LIMIT_REACHED, 0, 0, 0);
} }
return IrisStructureLocator.locateInPlacementRings( return ModuleServices.locateStart(
engine, structureKey, blockX, blockZ, radius, engine, structureKey, blockX, blockZ, radius,
(chunkX, chunkZ) -> !rejectedChunks.contains(ChunkPos.pack(chunkX, chunkZ)) (chunkX, chunkZ) -> !rejectedChunks.contains(ChunkPos.pack(chunkX, chunkZ))
&& probe.accepts(chunkX, chunkZ)); && probe.accepts(chunkX, chunkZ));
} }
public VerifiedStart verify(IrisStructureLocator.LocateResult result) { public VerifiedStart verify(ModuleServices.StructureSearch result) {
int chunkX = result.originX() >> 4; int chunkX = result.x() >> 4;
int chunkZ = result.originZ() >> 4; int chunkZ = result.z() >> 4;
StructureStart start = probe.verifySelected(chunkX, chunkZ); StructureStart start = probe.verifySelected(chunkX, chunkZ);
if (start == null) { if (start == null) {
return null; return null;
@@ -282,8 +282,8 @@ public final class NativeStructureLocatePersistence {
return new VerifiedStart(start, ownership); return new VerifiedStart(start, ownership);
} }
public void reject(IrisStructureLocator.LocateResult result) { public void reject(ModuleServices.StructureSearch result) {
rejectedChunks.add(ChunkPos.pack(result.originX() >> 4, result.originZ() >> 4)); rejectedChunks.add(ChunkPos.pack(result.x() >> 4, result.z() >> 4));
} }
public void reference(VerifiedStart verified) { public void reference(VerifiedStart verified) {
@@ -23,8 +23,6 @@ import art.arcane.iris.engine.framework.Engine;
import art.arcane.iris.engine.framework.GenerationSessionLease; import art.arcane.iris.engine.framework.GenerationSessionLease;
import art.arcane.iris.engine.framework.NativeFeatureGenerationPolicy; import art.arcane.iris.engine.framework.NativeFeatureGenerationPolicy;
import art.arcane.iris.engine.object.world.biome.IrisBiome; import art.arcane.iris.engine.object.world.biome.IrisBiome;
import art.arcane.iris.engine.object.decoration.IrisDecorationStep;
import art.arcane.iris.engine.object.decoration.IrisImportedFeatureControl;
import art.arcane.iris.util.project.context.IrisContext; import art.arcane.iris.util.project.context.IrisContext;
import it.unimi.dsi.fastutil.ints.IntArraySet; import it.unimi.dsi.fastutil.ints.IntArraySet;
import it.unimi.dsi.fastutil.ints.IntSet; import it.unimi.dsi.fastutil.ints.IntSet;
@@ -49,6 +47,7 @@ import net.minecraft.world.level.levelgen.placement.PlacedFeature;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Arrays; import java.util.Arrays;
import java.util.BitSet;
import java.util.HashMap; import java.util.HashMap;
import java.util.LinkedHashSet; import java.util.LinkedHashSet;
import java.util.List; import java.util.List;
@@ -172,23 +171,23 @@ final class ModdedImportedFeatureStage {
} }
private void build(Engine engine, long generation) { private void build(Engine engine, long generation) {
IrisImportedFeatureControl control; boolean enabled;
try { try {
control = NativeFeatureGenerationPolicy.control(engine); enabled = NativeFeatureGenerationPolicy.isEnabled(engine);
} catch (RuntimeException error) { } catch (RuntimeException error) {
ModdedIrisLog.error("Iris could not read importedFeatures for this dimension; features off: {}", ModdedIrisLog.error("Iris could not read importedFeatures for this dimension; features off: {}",
error.toString()); error.toString());
markInert(generation); markInert(generation);
return; return;
} }
if (!control.shouldGenerateFeatures()) { if (!enabled) {
markInert(generation); markInert(generation);
return; return;
} }
FeatureTable built; FeatureTable built;
try (GenerationSessionLease lease = engine.acquireGenerationLease("modded_imported_features"); try (GenerationSessionLease lease = engine.acquireGenerationLease("modded_imported_features");
IrisContext.Scope ignored = IrisContext.open(engine, lease.sessionId(), null)) { IrisContext.Scope ignored = IrisContext.open(engine, lease.sessionId(), null)) {
built = buildTable(engine, control, generation); built = buildTable(engine, generation);
} catch (Throwable error) { } catch (Throwable error) {
ModdedIrisLog.error("Iris importedFeatures is off for {}: feature table construction failed: {}", ModdedIrisLog.error("Iris importedFeatures is off for {}: feature table construction failed: {}",
dimensionKey(engine), error.toString()); dimensionKey(engine), error.toString());
@@ -214,7 +213,7 @@ final class ModdedImportedFeatureStage {
inertGeneration = generation; inertGeneration = generation;
} }
private FeatureTable buildTable(Engine engine, IrisImportedFeatureControl control, long generation) { private FeatureTable buildTable(Engine engine, long generation) {
// Registry-ordered biome list. FeatureSorter's cycle detection walks it, so an unordered list makes // Registry-ordered biome list. FeatureSorter's cycle detection walks it, so an unordered list makes
// detection depend on JVM hash order and turns a real cycle into an intermittent one. // detection depend on JVM hash order and turns a real cycle into an intermittent one.
List<Holder<Biome>> biomes = biomeSource.orderedPossibleBiomes(); List<Holder<Biome>> biomes = biomeSource.orderedPossibleBiomes();
@@ -248,9 +247,17 @@ final class ModdedImportedFeatureStage {
dimensionKey(engine), message); dimensionKey(engine), message);
return null; return null;
} }
boolean filtered = control.getDisabled() != null && !control.getDisabled().isEmpty(); return new FeatureTable(generation, List.copyOf(biomes), Set.copyOf(biomes),
return new FeatureTable(generation, control, List.copyOf(biomes), Set.copyOf(biomes), Map.copyOf(byKey), steps, Map.copyOf(derivatives), generatedSteps(engine, steps.size()));
Map.copyOf(byKey), steps, Map.copyOf(derivatives), filtered); }
/** The decoration steps whose features generate, by the platform's step index. */
private static BitSet generatedSteps(Engine engine, int stepCount) {
BitSet generated = new BitSet(stepCount);
for (int stepIndex = 0; stepIndex < stepCount; stepIndex++) {
generated.set(stepIndex, NativeFeatureGenerationPolicy.shouldGenerateStep(engine, stepIndex));
}
return generated;
} }
/** /**
@@ -324,10 +331,10 @@ final class ModdedImportedFeatureStage {
try { try {
for (int stepIndex = 0; stepIndex < steps.size(); stepIndex++) { for (int stepIndex = 0; stepIndex < steps.size(); stepIndex++) {
if (!table.control().shouldGenerateStep(IrisDecorationStep.byOrdinal(stepIndex))) { if (!table.generatedSteps().get(stepIndex)) {
continue; continue;
} }
placeStep(level, table, steps.get(stepIndex), featureRegistry, chunkBiomes, owner, placeStep(level, engine, table, steps.get(stepIndex), featureRegistry, chunkBiomes, owner,
random, decorationSeed, origin, stepIndex); random, decorationSeed, origin, stepIndex);
} }
} catch (Throwable error) { } catch (Throwable error) {
@@ -340,7 +347,7 @@ final class ModdedImportedFeatureStage {
WorldCheckFeaturePlacement.recordPlacementPass(); WorldCheckFeaturePlacement.recordPlacementPass();
} }
private void placeStep(WorldGenLevel level, FeatureTable table, FeatureSorter.StepFeatureData stepData, private void placeStep(WorldGenLevel level, Engine engine, FeatureTable table, FeatureSorter.StepFeatureData stepData,
Registry<PlacedFeature> featureRegistry, Set<Holder<Biome>> chunkBiomes, Registry<PlacedFeature> featureRegistry, Set<Holder<Biome>> chunkBiomes,
IrisModdedChunkGenerator owner, WorldgenRandom random, long decorationSeed, IrisModdedChunkGenerator owner, WorldgenRandom random, long decorationSeed,
BlockPos origin, int stepIndex) { BlockPos origin, int stepIndex) {
@@ -363,11 +370,9 @@ final class ModdedImportedFeatureStage {
Arrays.sort(featureIndices); Arrays.sort(featureIndices);
for (int globalIndex : featureIndices) { for (int globalIndex : featureIndices) {
PlacedFeature feature = stepData.features().get(globalIndex); PlacedFeature feature = stepData.features().get(globalIndex);
if (table.filtered()) { Identifier featureId = featureRegistry.getKey(feature);
Identifier featureId = featureRegistry.getKey(feature); if (featureId != null && !NativeFeatureGenerationPolicy.shouldGenerate(engine, featureId.toString())) {
if (featureId != null && !table.control().shouldGenerate(featureId.toString())) { continue;
continue;
}
} }
random.setFeatureSeed(decorationSeed, globalIndex, stepIndex); random.setFeatureSeed(decorationSeed, globalIndex, stepIndex);
level.setCurrentlyGenerating(() -> describeFeature(featureRegistry, feature)); level.setCurrentlyGenerating(() -> describeFeature(featureRegistry, feature));
@@ -423,10 +428,10 @@ final class ModdedImportedFeatureStage {
return identifier == null ? null : identifier.toString().toLowerCase(Locale.ROOT); return identifier == null ? null : identifier.toString().toLowerCase(Locale.ROOT);
} }
private record FeatureTable(long generation, IrisImportedFeatureControl control, private record FeatureTable(long generation,
List<Holder<Biome>> biomes, Set<Holder<Biome>> biomeSet, List<Holder<Biome>> biomes, Set<Holder<Biome>> biomeSet,
Map<String, Holder<Biome>> byKey, Map<String, Holder<Biome>> byKey,
List<FeatureSorter.StepFeatureData> steps, List<FeatureSorter.StepFeatureData> steps,
Map<String, Holder<Biome>> derivatives, boolean filtered) { Map<String, Holder<Biome>> derivatives, BitSet generatedSteps) {
} }
} }
@@ -19,7 +19,7 @@
package art.arcane.iris.modded; package art.arcane.iris.modded;
import art.arcane.iris.engine.framework.Engine; import art.arcane.iris.engine.framework.Engine;
import art.arcane.iris.engine.framework.IrisStructureLocator; import art.arcane.iris.core.modules.ModuleServices;
import art.arcane.iris.engine.framework.NativeStructureGenerationPolicy; import art.arcane.iris.engine.framework.NativeStructureGenerationPolicy;
import art.arcane.iris.engine.framework.NativeStructureLayouts; import art.arcane.iris.engine.framework.NativeStructureLayouts;
import art.arcane.iris.engine.framework.nativefit.NativeStructureFitting; import art.arcane.iris.engine.framework.nativefit.NativeStructureFitting;
@@ -129,7 +129,7 @@ final class ModdedNativeStructureStage {
throw new IllegalStateException("Native structure locate received an unregistered structure holder"); throw new IllegalStateException("Native structure locate received an unregistered structure holder");
} }
String structureId = id.toString(); String structureId = id.toString();
if (!IrisStructureLocator.hasNativePlacement(current, structureId)) { if (!ModuleServices.startsStructure(current, structureId)) {
continue; continue;
} }
NativeStructureLocatePersistence.Probe probe = NativeStructureLocatePersistence.probe( NativeStructureLocatePersistence.Probe probe = NativeStructureLocatePersistence.probe(
@@ -141,19 +141,19 @@ final class ModdedNativeStructureStage {
searches.sort(Comparator.comparing(IrisNativeLocateSearch::structureId)); searches.sort(Comparator.comparing(IrisNativeLocateSearch::structureId));
for (int attempt = 0; attempt < NativeStructureLocatePersistence.MAX_SELECTED_CANDIDATE_RETRIES; attempt++) { for (int attempt = 0; attempt < NativeStructureLocatePersistence.MAX_SELECTED_CANDIDATE_RETRIES; attempt++) {
IrisNativeLocateSearch bestSearch = null; IrisNativeLocateSearch bestSearch = null;
IrisStructureLocator.LocateResult bestResult = null; ModuleServices.StructureSearch bestResult = null;
long bestDistance = Long.MAX_VALUE; long bestDistance = Long.MAX_VALUE;
for (IrisNativeLocateSearch search : searches) { for (IrisNativeLocateSearch search : searches) {
IrisStructureLocator.LocateResult result = search.search().predict(); ModuleServices.StructureSearch result = search.search().predict();
if (result.status() == IrisStructureLocator.LocateStatus.SEARCH_LIMIT_REACHED) { if (result.outcome() == ModuleServices.StructureSearch.Outcome.SEARCH_LIMIT_REACHED) {
throw new IllegalStateException("Iris structure locate reached its safety limit for " throw new IllegalStateException("Iris structure locate reached its safety limit for "
+ search.structureId() + " within " + radius + " placement rings"); + search.structureId() + " within " + radius + " placement rings");
} }
if (!result.found()) { if (!result.found()) {
continue; continue;
} }
long dx = (long) result.originX() - pos.getX(); long dx = (long) result.x() - pos.getX();
long dz = (long) result.originZ() - pos.getZ(); long dz = (long) result.z() - pos.getZ();
long distance = dx * dx + dz * dz; long distance = dx * dx + dz * dz;
if (distance < bestDistance) { if (distance < bestDistance) {
bestDistance = distance; bestDistance = distance;
@@ -166,7 +166,7 @@ final class ModdedNativeStructureStage {
pos, null, () -> { }, nativeLocated, nativeReference); pos, null, () -> { }, nativeLocated, nativeReference);
} }
Pair<BlockPos, Holder<Structure>> predicted = Pair.of( Pair<BlockPos, Holder<Structure>> predicted = Pair.of(
new BlockPos(bestResult.originX(), bestResult.baseY(), bestResult.originZ()), new BlockPos(bestResult.x(), bestResult.y(), bestResult.z()),
bestSearch.holder()); bestSearch.holder());
if (NativeStructureLocateResults.nearest(pos, predicted, nativeLocated) != predicted) { if (NativeStructureLocateResults.nearest(pos, predicted, nativeLocated) != predicted) {
return NativeStructureLocateResults.selectAndReference( return NativeStructureLocateResults.selectAndReference(
@@ -179,8 +179,8 @@ final class ModdedNativeStructureStage {
continue; continue;
} }
BlockPos located = new BlockPos( BlockPos located = new BlockPos(
bestResult.originX(), verified.ownership().locatorY(), bestResult.x(), verified.ownership().locatorY(),
bestResult.originZ()); bestResult.z());
Pair<BlockPos, Holder<Structure>> irisLocated = Pair.of(located, bestSearch.holder()); Pair<BlockPos, Holder<Structure>> irisLocated = Pair.of(located, bestSearch.holder());
IrisNativeLocateSearch selectedSearch = bestSearch; IrisNativeLocateSearch selectedSearch = bestSearch;
NativeStructureLocatePersistence.VerifiedStart selectedStart = verified; NativeStructureLocatePersistence.VerifiedStart selectedStart = verified;
@@ -23,7 +23,6 @@ import art.arcane.iris.modded.ModdedIrisLog;
import art.arcane.iris.spi.IrisPlatforms; import art.arcane.iris.spi.IrisPlatforms;
import art.arcane.iris.core.pack.PackDirectoryResolver; import art.arcane.iris.core.pack.PackDirectoryResolver;
import art.arcane.iris.engine.framework.Engine; import art.arcane.iris.engine.framework.Engine;
import art.arcane.iris.engine.framework.IrisStructureLocator;
import art.arcane.iris.engine.framework.NativeStructureGenerationPolicy; import art.arcane.iris.engine.framework.NativeStructureGenerationPolicy;
import art.arcane.iris.engine.framework.StructureReachability; import art.arcane.iris.engine.framework.StructureReachability;
import art.arcane.iris.engine.framework.NativeStructureGenerationStatus; import art.arcane.iris.engine.framework.NativeStructureGenerationStatus;
@@ -133,9 +132,9 @@ final class ModdedCommandSuggestions {
String key = identifier.toString(); String key = identifier.toString();
registeredKeys.add(normalizeKey(key)); registeredKeys.add(normalizeKey(key));
NativeStructureGenerationStatus status = NativeStructureGenerationPolicy.resolve(engine, key); NativeStructureGenerationStatus status = NativeStructureGenerationPolicy.resolve(engine, key);
boolean nativePlacement = IrisStructureLocator.hasNativePlacement(engine, key); boolean nativePlacement = ModuleServices.startsStructure(engine, key);
boolean locatableNativePlacement = nativePlacement boolean locatableNativePlacement = nativePlacement
&& IrisStructureLocator.hasLocatableNativePlacement(engine, key); && ModuleServices.canLocateStart(engine, key);
boolean locatableEditableReplacement = !nativePlacement boolean locatableEditableReplacement = !nativePlacement
&& status == NativeStructureGenerationStatus.REPLACED_BY_IRIS && status == NativeStructureGenerationStatus.REPLACED_BY_IRIS
&& ModuleServices.canLocateStructure(engine, key); && ModuleServices.canLocateStructure(engine, key);
@@ -147,7 +146,7 @@ final class ModdedCommandSuggestions {
} }
Collection<String> unregisteredIrisKeys = eligibleUnregisteredEditableKeys( Collection<String> unregisteredIrisKeys = eligibleUnregisteredEditableKeys(
irisKeys, registeredKeys, irisKeys, registeredKeys,
(String candidate) -> IrisStructureLocator.hasNativePlacement(engine, candidate)); (String candidate) -> ModuleServices.startsStructure(engine, candidate));
return SharedSuggestionProvider.suggest( return SharedSuggestionProvider.suggest(
combineStructureKeys(unregisteredIrisKeys, nativeKeys), builder); combineStructureKeys(unregisteredIrisKeys, nativeKeys), builder);
} catch (Throwable e) { } catch (Throwable e) {
@@ -25,7 +25,6 @@ import art.arcane.iris.core.localization.ModdedCommandMessages;
import art.arcane.iris.engine.framework.Engine; import art.arcane.iris.engine.framework.Engine;
import art.arcane.iris.engine.framework.GenerationSessionException; import art.arcane.iris.engine.framework.GenerationSessionException;
import art.arcane.iris.engine.framework.GenerationSessionLease; import art.arcane.iris.engine.framework.GenerationSessionLease;
import art.arcane.iris.engine.framework.IrisStructureLocator;
import art.arcane.iris.engine.framework.Locator; import art.arcane.iris.engine.framework.Locator;
import art.arcane.iris.engine.framework.NativeStructureGenerationPolicy; import art.arcane.iris.engine.framework.NativeStructureGenerationPolicy;
import art.arcane.iris.engine.framework.StructureReachability; import art.arcane.iris.engine.framework.StructureReachability;
@@ -156,7 +155,7 @@ final class ModdedLocateCommands {
} }
Optional<NativeStructureTarget> resolved = resolveNativeStructure(source, level, engine, key); Optional<NativeStructureTarget> resolved = resolveNativeStructure(source, level, engine, key);
if (resolved.isEmpty()) { if (resolved.isEmpty()) {
if (!IrisStructureLocator.hasNativePlacement(engine, key) if (!ModuleServices.startsStructure(engine, key)
&& ModuleServices.canLocateStructure(engine, key)) { && ModuleServices.canLocateStructure(engine, key)) {
locateIrisStructure(source, level, engine, player, key); locateIrisStructure(source, level, engine, player, key);
return 1; return 1;
@@ -168,9 +167,9 @@ final class ModdedLocateCommands {
NativeStructureGenerationStatus status = NativeStructureGenerationPolicy.resolve(engine, target.key()); NativeStructureGenerationStatus status = NativeStructureGenerationPolicy.resolve(engine, target.key());
boolean nativeGenerationEnabled = boolean nativeGenerationEnabled =
source.getServer().getWorldGenSettings().options().generateStructures(); source.getServer().getWorldGenSettings().options().generateStructures();
boolean nativePlacement = IrisStructureLocator.hasNativePlacement(engine, target.key()); boolean nativePlacement = ModuleServices.startsStructure(engine, target.key());
boolean locatableNativePlacement = nativePlacement boolean locatableNativePlacement = nativePlacement
&& IrisStructureLocator.hasLocatableNativePlacement(engine, target.key()); && ModuleServices.canLocateStart(engine, target.key());
boolean locatableEditableReplacement = !nativePlacement boolean locatableEditableReplacement = !nativePlacement
&& status == NativeStructureGenerationStatus.REPLACED_BY_IRIS && status == NativeStructureGenerationStatus.REPLACED_BY_IRIS
&& ModuleServices.canLocateStructure(engine, target.key()); && ModuleServices.canLocateStructure(engine, target.key());
@@ -357,7 +356,7 @@ final class ModdedLocateCommands {
case NO_PLACEMENT -> unsupported++; case NO_PLACEMENT -> unsupported++;
} }
} }
int irisPlaced = IrisStructureLocator.placedKeys(engine).size(); int irisPlaced = ModuleServices.placedStructures(engine).size();
IrisModdedCommands.ok(source, IrisLanguage.plain(ModdedCommandMessages.IRIS_MODDED_COMMANDS_STRUCTURE_REACHABILITY_NATIVE_GENERATION_ELIGIBLE_IRIS_PLACED_NATIVE_DISABLED_NATIVE, MessageArgument.untrusted("available", available), MessageArgument.untrusted("irisPlaced", irisPlaced), MessageArgument.untrusted("disabled", disabled), MessageArgument.untrusted("suppressed", suppressed), MessageArgument.untrusted("unreachableBiomes", unreachableBiomes), MessageArgument.untrusted("unsupported", unsupported))); IrisModdedCommands.ok(source, IrisLanguage.plain(ModdedCommandMessages.IRIS_MODDED_COMMANDS_STRUCTURE_REACHABILITY_NATIVE_GENERATION_ELIGIBLE_IRIS_PLACED_NATIVE_DISABLED_NATIVE, MessageArgument.untrusted("available", available), MessageArgument.untrusted("irisPlaced", irisPlaced), MessageArgument.untrusted("disabled", disabled), MessageArgument.untrusted("suppressed", suppressed), MessageArgument.untrusted("unreachableBiomes", unreachableBiomes), MessageArgument.untrusted("unsupported", unsupported)));
return 1; return 1;
} }
@@ -365,7 +364,7 @@ final class ModdedLocateCommands {
private static int verifyStructure(CommandSourceStack source, ServerLevel level, Engine engine, String key) { private static int verifyStructure(CommandSourceStack source, ServerLevel level, Engine engine, String key) {
Optional<NativeStructureTarget> target = resolveNativeStructure(source, level, engine, key); Optional<NativeStructureTarget> target = resolveNativeStructure(source, level, engine, key);
if (target.isEmpty()) { if (target.isEmpty()) {
if (IrisStructureLocator.isPlaced(engine, key)) { if (ModuleServices.placesStructure(engine, key)) {
IrisModdedCommands.ok(source, IrisLanguage.plain(ModdedCommandMessages.IRIS_MODDED_COMMANDS_STRUCTURE_IS_IRIS_PLACED_LOCATABLE_WITH_IRIS_GOTO_STRUCTURE, MessageArgument.untrusted("key", key), MessageArgument.untrusted("key2", key))); IrisModdedCommands.ok(source, IrisLanguage.plain(ModdedCommandMessages.IRIS_MODDED_COMMANDS_STRUCTURE_IS_IRIS_PLACED_LOCATABLE_WITH_IRIS_GOTO_STRUCTURE, MessageArgument.untrusted("key", key), MessageArgument.untrusted("key2", key)));
return 1; return 1;
} }
@@ -38,7 +38,7 @@ import art.arcane.iris.engine.object.terrain.IrisGenerator;
import art.arcane.iris.core.pack.ModuleResourceClosure; import art.arcane.iris.core.pack.ModuleResourceClosure;
import art.arcane.iris.core.pack.PackExportClosure; import art.arcane.iris.core.pack.PackExportClosure;
import art.arcane.iris.engine.object.world.region.IrisRegion; import art.arcane.iris.engine.object.world.region.IrisRegion;
import art.arcane.iris.engine.object.structure.IrisStructurePlacement; import art.arcane.iris.engine.object.structure.IrisStructure;
import art.arcane.iris.modded.ModdedDimensionManager; import art.arcane.iris.modded.ModdedDimensionManager;
import art.arcane.iris.modded.ModdedEngineBootstrap; import art.arcane.iris.modded.ModdedEngineBootstrap;
import art.arcane.iris.modded.ModdedScheduler; import art.arcane.iris.modded.ModdedScheduler;
@@ -881,9 +881,8 @@ public final class ModdedStudioCommands {
LinkedHashSet<String> regionKeys = new LinkedHashSet<>(); LinkedHashSet<String> regionKeys = new LinkedHashSet<>();
LinkedHashSet<String> biomeKeys = new LinkedHashSet<>(); LinkedHashSet<String> biomeKeys = new LinkedHashSet<>();
LinkedHashSet<String> generatorKeys = new LinkedHashSet<>(); LinkedHashSet<String> generatorKeys = new LinkedHashSet<>();
ModuleResourceClosure moduleResources = new ModuleResourceClosure(dm); ModuleResourceClosure moduleResources = new ModuleResourceClosure(dm).exportingElsewhere(IrisStructure.class);
LinkedHashSet<String> objectKeys = new LinkedHashSet<>(); LinkedHashSet<String> objectKeys = new LinkedHashSet<>();
LinkedHashSet<String> structureKeys = new LinkedHashSet<>();
dimension.getAllRegions(() -> dm).forEach((IrisRegion region) -> { dimension.getAllRegions(() -> dm).forEach((IrisRegion region) -> {
if (region != null && region.getLoadKey() != null) { if (region != null && region.getLoadKey() != null) {
@@ -896,7 +895,6 @@ public final class ModdedStudioCommands {
} }
}); });
moduleResources.followSettingsOf(dimension); moduleResources.followSettingsOf(dimension);
collectStructureKeys(structureKeys, dimension.getStructures());
for (String regionKey : regionKeys) { for (String regionKey : regionKeys) {
IrisRegion region = dm.getRegionLoader().load(regionKey); IrisRegion region = dm.getRegionLoader().load(regionKey);
@@ -910,7 +908,6 @@ public final class ModdedStudioCommands {
}); });
moduleResources.followSettingsOf(region); moduleResources.followSettingsOf(region);
moduleResources.follow(region.getObjects()); moduleResources.follow(region.getObjects());
collectStructureKeys(structureKeys, region.getStructures());
objectKeys.addAll(PackExportClosure.collectObjectKeys(region.getObjects())); objectKeys.addAll(PackExportClosure.collectObjectKeys(region.getObjects()));
} }
for (String biomeKey : biomeKeys) { for (String biomeKey : biomeKeys) {
@@ -921,11 +918,11 @@ public final class ModdedStudioCommands {
biome.getGenerators().forEach((IrisBiomeGeneratorLink link) -> generatorKeys.add(link.getGenerator())); biome.getGenerators().forEach((IrisBiomeGeneratorLink link) -> generatorKeys.add(link.getGenerator()));
moduleResources.followSettingsOf(biome); moduleResources.followSettingsOf(biome);
moduleResources.follow(biome.getObjects()); moduleResources.follow(biome.getObjects());
collectStructureKeys(structureKeys, biome.getStructures());
objectKeys.addAll(PackExportClosure.collectObjectKeys(biome.getObjects())); objectKeys.addAll(PackExportClosure.collectObjectKeys(biome.getObjects()));
} }
StringBuilder hashes = new StringBuilder(); StringBuilder hashes = new StringBuilder();
List<String> structureKeys = moduleResources.keysOf(IrisStructure.class);
StructurePackageClosure structureClosure = StructurePackageClosure.collect(packFolder, structureKeys); StructurePackageClosure structureClosure = StructurePackageClosure.collect(packFolder, structureKeys);
if (!structureClosure.isValid()) { if (!structureClosure.isValid()) {
throw new IOException("Structure package closure is invalid: " + String.join("; ", structureClosure.errors())); throw new IOException("Structure package closure is invalid: " + String.join("; ", structureClosure.errors()));
@@ -969,20 +966,6 @@ public final class ModdedStudioCommands {
return output; return output;
} }
private static void collectStructureKeys(LinkedHashSet<String> keys, List<IrisStructurePlacement> placements) {
if (placements == null) {
return;
}
for (IrisStructurePlacement placement : placements) {
if (placement == null || placement.getStructures() == null) {
continue;
}
for (String structureKey : placement.getStructures()) {
keys.add(structureKey);
}
}
}
private static String copyJson(File folder, String category, String key, File file) { private static String copyJson(File folder, String category, String key, File file) {
if (file == null || !file.isFile()) { if (file == null || !file.isFile()) {
return ""; return "";
@@ -21,7 +21,6 @@ package art.arcane.iris.modded.command;
import art.arcane.iris.core.modules.ModuleServices; import art.arcane.iris.core.modules.ModuleServices;
import art.arcane.iris.modded.ModdedIrisLog; import art.arcane.iris.modded.ModdedIrisLog;
import art.arcane.iris.engine.framework.Engine; import art.arcane.iris.engine.framework.Engine;
import art.arcane.iris.engine.framework.IrisStructureLocator;
import art.arcane.iris.engine.framework.NativeStructureGenerationPolicy; import art.arcane.iris.engine.framework.NativeStructureGenerationPolicy;
import art.arcane.iris.engine.framework.StructureReachability; import art.arcane.iris.engine.framework.StructureReachability;
import art.arcane.iris.engine.framework.NativeStructureGenerationStatus; import art.arcane.iris.engine.framework.NativeStructureGenerationStatus;
@@ -107,9 +106,9 @@ final class ModdedUnregisteredStructures {
continue; continue;
} }
NativeStructureGenerationStatus status = NativeStructureGenerationPolicy.resolve(engine, key); NativeStructureGenerationStatus status = NativeStructureGenerationPolicy.resolve(engine, key);
boolean nativePlacement = IrisStructureLocator.hasNativePlacement(engine, key); boolean nativePlacement = ModuleServices.startsStructure(engine, key);
boolean locatableNativePlacement = nativePlacement boolean locatableNativePlacement = nativePlacement
&& IrisStructureLocator.hasLocatableNativePlacement(engine, key); && ModuleServices.canLocateStart(engine, key);
boolean locatableEditableReplacement = !nativePlacement boolean locatableEditableReplacement = !nativePlacement
&& status == NativeStructureGenerationStatus.REPLACED_BY_IRIS && status == NativeStructureGenerationStatus.REPLACED_BY_IRIS
&& ModuleServices.canLocateStructure(engine, key); && ModuleServices.canLocateStructure(engine, key);
@@ -128,8 +127,8 @@ final class ModdedUnregisteredStructures {
excluded.put(normalizedKey, new ExcludedStructure(ReportStatus.EXCLUDED, key, reason)); excluded.put(normalizedKey, new ExcludedStructure(ReportStatus.EXCLUDED, key, reason));
} }
List<String> absentNativeKeys = missingConfiguredNativeKeys( List<String> absentNativeKeys = missingConfiguredNativeKeys(
IrisStructureLocator.placedKeys(engine), registeredKeys, ModuleServices.placedStructures(engine), registeredKeys,
(String key) -> IrisStructureLocator.hasNativePlacement(engine, key)); (String key) -> ModuleServices.startsStructure(engine, key));
for (String key : absentNativeKeys) { for (String key : absentNativeKeys) {
String normalizedKey = ModdedCommandSuggestions.normalizeKey(key); String normalizedKey = ModdedCommandSuggestions.normalizeKey(key);
excluded.putIfAbsent(normalizedKey, new ExcludedStructure(ReportStatus.UNREGISTERED, key, excluded.putIfAbsent(normalizedKey, new ExcludedStructure(ReportStatus.UNREGISTERED, key,
@@ -143,12 +142,12 @@ final class ModdedUnregisteredStructures {
continue; continue;
} }
boolean registered = registeredKeys.contains(normalizedKey); boolean registered = registeredKeys.contains(normalizedKey);
boolean nativePlacement = IrisStructureLocator.hasNativePlacement(engine, key); boolean nativePlacement = ModuleServices.startsStructure(engine, key);
boolean locatableEditable = ModuleServices.canLocateStructure(engine, key); boolean locatableEditable = ModuleServices.canLocateStructure(engine, key);
if (!registered && !nativePlacement && locatableEditable) { if (!registered && !nativePlacement && locatableEditable) {
continue; continue;
} }
boolean configured = IrisStructureLocator.hasEditablePlacement(engine, key); boolean configured = ModuleServices.placesStructure(engine, key);
excluded.putIfAbsent(normalizedKey, new ExcludedStructure( excluded.putIfAbsent(normalizedKey, new ExcludedStructure(
ReportStatus.UNPLACED, key.trim(), editableExclusionReason(configured))); ReportStatus.UNPLACED, key.trim(), editableExclusionReason(configured)));
} }
@@ -197,16 +197,16 @@ public class IrisModdedStructureCommandTest {
assertTrue(method.contains("ServerLevel level = source.getLevel()")); assertTrue(method.contains("ServerLevel level = source.getLevel()"));
assertTrue(method.contains("Engine engine = IrisModdedCommands.engineFor(level)")); assertTrue(method.contains("Engine engine = IrisModdedCommands.engineFor(level)"));
assertFalse(method.contains("IrisStructureLocator.locatableKeys(engine)")); assertFalse(method.contains("IrisStructureLocator"));
assertTrue(method.contains("ModuleServices.locatableStructures(engine)")); assertTrue(method.contains("ModuleServices.locatableStructures(engine)"));
assertTrue(method.contains("StructureReachability.reachableKeys(engine)")); assertTrue(method.contains("StructureReachability.reachableKeys(engine)"));
assertTrue(method.contains("NativeStructureGenerationPolicy.resolve(engine, key)")); assertTrue(method.contains("NativeStructureGenerationPolicy.resolve(engine, key)"));
assertTrue(method.contains("IrisStructureLocator.hasLocatableNativePlacement(engine, key)")); assertTrue(method.contains("ModuleServices.canLocateStart(engine, key)"));
assertTrue(method.contains("ModuleServices.canLocateStructure(engine, key)")); assertTrue(method.contains("ModuleServices.canLocateStructure(engine, key)"));
assertTrue(method.contains("reachableNativeKeys.contains(normalizeKey(key))")); assertTrue(method.contains("reachableNativeKeys.contains(normalizeKey(key))"));
assertTrue(method.contains("nativeGenerationEnabled")); assertTrue(method.contains("nativeGenerationEnabled"));
assertTrue(method.contains("eligibleUnregisteredEditableKeys(")); assertTrue(method.contains("eligibleUnregisteredEditableKeys("));
assertTrue(method.contains("IrisStructureLocator.hasNativePlacement(engine, candidate)")); assertTrue(method.contains("ModuleServices.startsStructure(engine, candidate)"));
assertFalse(method.contains("NativeStructureGenerationKeys.active(level)")); assertFalse(method.contains("NativeStructureGenerationKeys.active(level)"));
assertFalse(method.contains("getPlacementsForStructure")); assertFalse(method.contains("getPlacementsForStructure"));
} }
@@ -219,7 +219,7 @@ public class IrisModdedStructureCommandTest {
String method = source.substring(methodStart, methodEnd); String method = source.substring(methodStart, methodEnd);
int registryLookup = method.indexOf("level.registryAccess().lookupOrThrow(Registries.STRUCTURE)"); int registryLookup = method.indexOf("level.registryAccess().lookupOrThrow(Registries.STRUCTURE)");
int placedCheck = method.indexOf( int placedCheck = method.indexOf(
"if (!IrisStructureLocator.hasNativePlacement(current, structureId))"); "if (!ModuleServices.startsStructure(current, structureId))");
int irisLocate = method.indexOf("NativeStructureLocatePersistence.search(", placedCheck); int irisLocate = method.indexOf("NativeStructureLocatePersistence.search(", placedCheck);
int nearestSelection = method.indexOf( int nearestSelection = method.indexOf(
"NativeStructureLocateResults.nearest(pos, predicted, nativeLocated)", irisLocate); "NativeStructureLocateResults.nearest(pos, predicted, nativeLocated)", irisLocate);
@@ -235,7 +235,7 @@ public class IrisModdedStructureCommandTest {
assertTrue(selectedReference > selectedVerification); assertTrue(selectedReference > selectedVerification);
assertTrue(method.contains("NativeStructureLocatePersistence.probe(")); assertTrue(method.contains("NativeStructureLocatePersistence.probe("));
assertTrue(method.contains("findUnexplored")); assertTrue(method.contains("findUnexplored"));
assertTrue(method.contains("LocateStatus.SEARCH_LIMIT_REACHED")); assertTrue(method.contains("Outcome.SEARCH_LIMIT_REACHED"));
assertTrue(method.contains("verified.ownership().locatorY()")); assertTrue(method.contains("verified.ownership().locatorY()"));
assertTrue(method.contains("selectedSearch.search().reference(selectedStart)")); assertTrue(method.contains("selectedSearch.search().reference(selectedStart)"));
assertTrue(method.contains("NativeStructureLocateResults.selectAndReference(")); assertTrue(method.contains("NativeStructureLocateResults.selectAndReference("));
@@ -271,12 +271,12 @@ public class IrisModdedStructureCommandTest {
assertTrue(eligibilityCheck > policyResolution); assertTrue(eligibilityCheck > policyResolution);
assertTrue(replacementLocate > eligibilityCheck); assertTrue(replacementLocate > eligibilityCheck);
assertTrue(nativeLocate > replacementLocate); assertTrue(nativeLocate > replacementLocate);
assertTrue(method.contains("IrisStructureLocator.hasLocatableNativePlacement(engine, target.key())")); assertTrue(method.contains("ModuleServices.canLocateStart(engine, target.key())"));
assertTrue(method.contains("ModuleServices.canLocateStructure(engine, target.key())")); assertTrue(method.contains("ModuleServices.canLocateStructure(engine, target.key())"));
assertTrue(method.contains("!IrisStructureLocator.hasNativePlacement(engine, key)")); assertTrue(method.contains("!ModuleServices.startsStructure(engine, key)"));
assertTrue(method.contains("StructureReachability.isReachable(engine, target.key())")); assertTrue(method.contains("StructureReachability.isReachable(engine, target.key())"));
assertTrue(method.contains("getWorldGenSettings().options().generateStructures()")); assertTrue(method.contains("getWorldGenSettings().options().generateStructures()"));
assertFalse(method.contains("IrisStructureLocator.isPlaced(engine, key)")); assertFalse(method.contains("ModuleServices.placesStructure(engine, key)"));
} }
@Test @Test
@@ -287,7 +287,7 @@ public class IrisModdedStructureCommandTest {
methodStart); methodStart);
String method = source.substring(methodStart, methodEnd); String method = source.substring(methodStart, methodEnd);
int nativeResolution = method.indexOf("resolveNativeStructure(source, level, engine, key)"); int nativeResolution = method.indexOf("resolveNativeStructure(source, level, engine, key)");
int genericIrisLookup = method.indexOf("IrisStructureLocator.isPlaced(engine, key)", nativeResolution); int genericIrisLookup = method.indexOf("ModuleServices.placesStructure(engine, key)", nativeResolution);
assertTrue(nativeResolution >= 0); assertTrue(nativeResolution >= 0);
assertTrue(genericIrisLookup > nativeResolution); assertTrue(genericIrisLookup > nativeResolution);
@@ -60,8 +60,9 @@ public final class IrisModuleHost {
* {@code IrisModule/builtin-modules.txt}) instead of being compiled into Iris. A pack loads them from its {@code modules} * {@code IrisModule/builtin-modules.txt}) instead of being compiled into Iris. A pack loads them from its {@code modules}
* folder, and {@link MissingBuiltInModules} warns when it loads none; a test keeps this equal to the jar's list. * folder, and {@link MissingBuiltInModules} warns when it loads none; a test keeps this equal to the jar's list.
*/ */
public static final List<String> JAR_MODULE_IDS = List.of("iris:post", "iris:perfection", "iris:matter", "iris:loot", "iris:spawn", public static final List<String> JAR_MODULE_IDS = List.of("iris:post", "iris:perfection", "iris:matter", "iris:loot",
"iris:prepare", "iris:anchor", "iris:validate", "iris:bore", "iris:blocks", "iris:stilt", "iris:vacuum", "iris:snow"); "iris:spawn", "iris:prepare", "iris:anchor", "iris:validate", "iris:bore", "iris:blocks", "iris:stilt", "iris:vacuum",
"iris:snow", "iris:vanilla-features");
/** Iris's pack object model: built-in settings may hold these classes, which Iris reads and describes itself. */ /** Iris's pack object model: built-in settings may hold these classes, which Iris reads and describes itself. */
public static final String HOST_TYPE_PACKAGE = "art.arcane.iris.engine.object"; public static final String HOST_TYPE_PACKAGE = "art.arcane.iris.engine.object";
private static final String[] JAR_COPY_FOLDER = {"cache", "module-jars"}; private static final String[] JAR_COPY_FOLDER = {"cache", "module-jars"};
@@ -24,6 +24,7 @@ import com.volmit.host.FeatureCatalog;
import com.volmit.host.ServiceRegistration; import com.volmit.host.ServiceRegistration;
import com.volmit.entity.EntitySpec; import com.volmit.entity.EntitySpec;
import com.volmit.item.ItemDrop; import com.volmit.item.ItemDrop;
import com.volmit.resource.ResourceId;
import com.volmit.service.AmbientEffects; import com.volmit.service.AmbientEffects;
import com.volmit.service.BlockDrops; import com.volmit.service.BlockDrops;
import com.volmit.service.CaveBiomes; import com.volmit.service.CaveBiomes;
@@ -33,6 +34,8 @@ import com.volmit.service.Loot;
import com.volmit.service.ObjectsAt; import com.volmit.service.ObjectsAt;
import com.volmit.service.SaplingGrowth; import com.volmit.service.SaplingGrowth;
import com.volmit.service.StructureLocator; import com.volmit.service.StructureLocator;
import com.volmit.service.VanillaFeatures;
import com.volmit.service.VanillaStructures;
import com.volmit.world.BlockPosition; import com.volmit.world.BlockPosition;
import com.volmit.world.PackWorld; import com.volmit.world.PackWorld;
import java.util.ArrayList; import java.util.ArrayList;
@@ -41,6 +44,7 @@ import java.util.List;
import java.util.Locale; import java.util.Locale;
import java.util.Optional; import java.util.Optional;
import java.util.Set; import java.util.Set;
import java.util.function.BiFunction;
/** /**
* What Iris core asks the pack's modules through their services ({@link com.volmit.service.Service}) instead of reading * What Iris core asks the pack's modules through their services ({@link com.volmit.service.Service}) instead of reading
@@ -84,6 +88,14 @@ public final class ModuleServices {
.orElseGet(() -> new CaveBiomeAnswers(owner, null, owner.getGeneration().world()))); .orElseGet(() -> new CaveBiomeAnswers(owner, null, owner.getGeneration().world())));
} }
/** What the modules say about the platform's own placed features in the engine's world, kept for the world. */
public static VanillaFeatureAnswers vanillaFeatures(Engine engine) {
return engine.getGeneration().state(VanillaFeatureAnswers.class, owner -> new VanillaFeatureAnswers(
providers(owner, VanillaFeatures.class).stream()
.map(provider -> new VanillaFeatureAnswers.Provider(provider.service(), provider.world()))
.toList()));
}
/** The objects every module would place in the chunk at {@code chunkX}, {@code chunkZ}, guessed without generating it. */ /** The objects every module would place in the chunk at {@code chunkX}, {@code chunkZ}, guessed without generating it. */
public static Set<String> objectsAt(Engine engine, int chunkX, int chunkZ) { public static Set<String> objectsAt(Engine engine, int chunkX, int chunkZ) {
Set<String> keys = new LinkedHashSet<>(); Set<String> keys = new LinkedHashSet<>();
@@ -227,26 +239,90 @@ public final class ModuleServices {
/** Whether a module of the world can locate structure {@code key}, matched without regard to case. */ /** Whether a module of the world can locate structure {@code key}, matched without regard to case. */
public static boolean canLocateStructure(Engine engine, String key) { public static boolean canLocateStructure(Engine engine, String key) {
return structureLocatorOf(engine, key).isPresent(); return structureLocatorOf(engine, key, StructureLocator::locatable).isPresent();
}
/**
* Every key under which the world's modules find what they place, locatable or not: their own structures and the
* platform structures they start or stand in for.
*/
public static Set<String> placedStructures(Engine engine) {
Set<String> keys = new LinkedHashSet<>();
for (Provider<StructureLocator> provider : providers(engine, StructureLocator.class)) {
keys.addAll(provider.service().placed(provider.world()));
}
return keys;
}
/** Whether a module of the world places structure {@code key}, located or not, matched without regard to case. */
public static boolean placesStructure(Engine engine, String key) {
return structureLocatorOf(engine, key, StructureLocator::placed).isPresent();
} }
/** /**
* Searches for the start of structure {@code key} nearest to {@code fromX}, {@code fromZ} with the first module that * Searches for the start of structure {@code key} nearest to {@code fromX}, {@code fromZ} with the first module that
* can locate it, in the world's own coordinates; not found when none can. * places it, in the world's own coordinates; not found when none does.
*/ */
public static StructureSearch locateStructure(Engine engine, String key, int fromX, int fromZ, int maxRadiusChunks) { public static StructureSearch locateStructure(Engine engine, String key, int fromX, int fromZ, int maxRadiusChunks) {
LocateResult result = structureLocatorOf(engine, key) LocateResult result = structureLocatorOf(engine, key, StructureLocator::placed)
.map(provider -> provider.service().locate(provider.world(), key, fromX, fromZ, maxRadiusChunks)) .map(provider -> provider.service().locate(provider.world(), key, fromX, fromZ, maxRadiusChunks))
.orElse(LocateResult.NOT_FOUND); .orElse(LocateResult.NOT_FOUND);
return StructureSearch.of(result, engine); return StructureSearch.of(result, engine);
} }
/** The platform structures the world's modules start themselves, as lower-case registry keys. */
public static Set<String> startedStructures(Engine engine) {
return platformStructures(engine, VanillaStructures::startedStructures);
}
/** Whether a module of the world starts the platform structure {@code key} itself. */
public static boolean startsStructure(Engine engine, String key) {
return key != null && startedStructures(engine).contains(normalized(key));
}
/** Whether a module of the world can find the starts it makes of the platform structure {@code key}. */
public static boolean canLocateStart(Engine engine, String key) {
return key != null && platformStructures(engine, VanillaStructures::locatableStarts).contains(normalized(key));
}
/**
* Searches ring by ring, up to {@code maxRings} rings, for the start the first module that can find them makes of the
* platform structure {@code key} nearest to {@code fromX}, {@code fromZ}, trying only chunks {@code candidates}
* accepts, in the world's own coordinates. A {@link StructureSearchLimitException} from {@code candidates} ends the
* search as {@link StructureSearch.Outcome#SEARCH_LIMIT_REACHED}.
*/
public static StructureSearch locateStart(Engine engine, String key, int fromX, int fromZ, int maxRings,
CandidateChunks candidates) {
Optional<ResourceId> structure = registryId(key);
if (structure.isEmpty()) {
return StructureSearch.NOT_FOUND;
}
for (Provider<VanillaStructures> provider : providers(engine, VanillaStructures.class)) {
if (!provider.service().locatableStarts(provider.world()).contains(structure.get())) {
continue;
}
try {
return StructureSearch.of(provider.service().locateStart(provider.world(), structure.get(), fromX, fromZ,
maxRings, candidates::accepts), engine);
} catch (StructureSearchLimitException limit) {
return StructureSearch.SEARCH_LIMIT_REACHED;
}
}
return StructureSearch.NOT_FOUND;
}
/** The chunks a search for a module's start of a platform structure may answer with. */
@FunctionalInterface
public interface CandidateChunks {
boolean accepts(int chunkX, int chunkZ);
}
/** How a structure search ended. A found start is at {@code x}, {@code y}, {@code z}: world coordinates, Y the world's own. */ /** How a structure search ended. A found start is at {@code x}, {@code y}, {@code z}: world coordinates, Y the world's own. */
public record StructureSearch(Outcome outcome, int x, int y, int z) { public record StructureSearch(Outcome outcome, int x, int y, int z) {
public enum Outcome { FOUND, NOT_FOUND, SEARCH_LIMIT_REACHED } public enum Outcome { FOUND, NOT_FOUND, SEARCH_LIMIT_REACHED }
private static final StructureSearch NOT_FOUND = new StructureSearch(Outcome.NOT_FOUND, 0, 0, 0); public static final StructureSearch NOT_FOUND = new StructureSearch(Outcome.NOT_FOUND, 0, 0, 0);
private static final StructureSearch SEARCH_LIMIT_REACHED = new StructureSearch(Outcome.SEARCH_LIMIT_REACHED, 0, 0, 0); public static final StructureSearch SEARCH_LIMIT_REACHED = new StructureSearch(Outcome.SEARCH_LIMIT_REACHED, 0, 0, 0);
public boolean found() { public boolean found() {
return outcome == Outcome.FOUND; return outcome == Outcome.FOUND;
@@ -263,20 +339,41 @@ public final class ModuleServices {
} }
} }
/** The first provider, in the catalog's order, whose locatable structures hold {@code key}. */ /** The first provider, in the catalog's order, whose structures of the kind {@code keys} lists hold {@code key}. */
private static Optional<Provider<StructureLocator>> structureLocatorOf(Engine engine, String key) { private static Optional<Provider<StructureLocator>> structureLocatorOf(Engine engine, String key,
BiFunction<StructureLocator, PackWorld, Set<String>> keys) {
if (key == null || key.isBlank()) { if (key == null || key.isBlank()) {
return Optional.empty(); return Optional.empty();
} }
String wanted = normalized(key); String wanted = normalized(key);
for (Provider<StructureLocator> provider : providers(engine, StructureLocator.class)) { for (Provider<StructureLocator> provider : providers(engine, StructureLocator.class)) {
if (provider.service().locatable(provider.world()).stream().map(ModuleServices::normalized).anyMatch(wanted::equals)) { if (keys.apply(provider.service(), provider.world()).stream().map(ModuleServices::normalized).anyMatch(wanted::equals)) {
return Optional.of(provider); return Optional.of(provider);
} }
} }
return Optional.empty(); return Optional.empty();
} }
/** The platform structures every provider lists with {@code structures}, as lower-case registry keys. */
private static Set<String> platformStructures(Engine engine, BiFunction<VanillaStructures, PackWorld, Set<ResourceId>> structures) {
Set<String> keys = new LinkedHashSet<>();
for (Provider<VanillaStructures> provider : providers(engine, VanillaStructures.class)) {
structures.apply(provider.service(), provider.world()).forEach(id -> keys.add(id.toString()));
}
return keys;
}
private static Optional<ResourceId> registryId(String key) {
if (key == null || key.isBlank()) {
return Optional.empty();
}
try {
return Optional.of(ResourceId.parse(normalized(key.trim())));
} catch (IllegalArgumentException notAnId) {
return Optional.empty();
}
}
private static String normalized(String key) { private static String normalized(String key) {
return key.toLowerCase(Locale.ROOT); return key.toLowerCase(Locale.ROOT);
} }
@@ -37,10 +37,10 @@ import com.volmit.host.ServiceRegistration;
import com.volmit.mantle.BlockBox; import com.volmit.mantle.BlockBox;
import com.volmit.resource.ResourceId; import com.volmit.resource.ResourceId;
import com.volmit.service.VanillaStructures; import com.volmit.service.VanillaStructures;
import com.volmit.vanilla.DecorationStep;
import com.volmit.vanilla.PieceKind; import com.volmit.vanilla.PieceKind;
import com.volmit.vanilla.StartMemo; import com.volmit.vanilla.StartMemo;
import com.volmit.vanilla.StructureFit; import com.volmit.vanilla.StructureFit;
import com.volmit.vanilla.StructureStep;
import com.volmit.vanilla.TemplateCells; import com.volmit.vanilla.TemplateCells;
import com.volmit.vanilla.TerrainAdaptation; import com.volmit.vanilla.TerrainAdaptation;
import com.volmit.ModuleLog; import com.volmit.ModuleLog;
@@ -337,8 +337,8 @@ public final class ModuleStructureFitting implements NativeStructureFitting {
} }
@Override @Override
public StructureStep step() { public DecorationStep step() {
return StructureStep.valueOf(start.step()); return DecorationStep.valueOf(start.step());
} }
@Override @Override
@@ -0,0 +1,29 @@
/*
* Iris is a World Generator for Minecraft Servers
* Copyright (c) 2026 Arcane Arts (Volmit Software)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package art.arcane.iris.core.modules;
/**
* Thrown by a host's {@link ModuleServices.CandidateChunks} to end a search for a module's start of a platform structure
* when the host's own checks ran out of budget; {@link ModuleServices#locateStart} reports it as a reached search limit.
*/
public final class StructureSearchLimitException extends RuntimeException {
public StructureSearchLimitException() {
super(null, null, false, false);
}
}
@@ -0,0 +1,99 @@
/*
* Iris is a World Generator for Minecraft Servers
* Copyright (c) 2026 Arcane Arts (Volmit Software)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package art.arcane.iris.core.modules;
import com.volmit.resource.ResourceId;
import com.volmit.service.VanillaFeatures;
import com.volmit.vanilla.DecorationStep;
import com.volmit.world.PackWorld;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Predicate;
/**
* What the world's {@link VanillaFeatures} providers say, kept for the world: whether the platform's placed features run
* over its terrain, and which decoration steps and features they leave out. Each answer is asked once per world.
*/
public final class VanillaFeatureAnswers {
private static final DecorationStep[] STEPS = DecorationStep.values();
/** One provider and the world as its module sees it. */
record Provider(VanillaFeatures service, PackWorld world) {
}
private final List<Provider> providers;
private final boolean generates;
private final Map<Integer, Boolean> steps = new ConcurrentHashMap<>();
private final Map<String, Boolean> features = new ConcurrentHashMap<>();
VanillaFeatureAnswers(List<Provider> providers) {
this.providers = List.copyOf(providers);
this.generates = this.providers.stream().anyMatch(provider -> provider.service().generates(provider.world()));
}
/** Whether the platform runs its placed features over the world's terrain: some module turned them on. */
public boolean generates() {
return generates;
}
/**
* Whether the platform places the features of its decoration step {@code stepIndex}, counted in the platform's order
* (a step past the ones IrisApi names is asked as an unknown step). False while the features are off.
*/
public boolean generatesStep(int stepIndex) {
if (!generates) {
return false;
}
return steps.computeIfAbsent(stepIndex, index -> everyProviderAllows(provider ->
provider.service().generatesStep(provider.world(), stepAt(index))));
}
/** Whether the platform places the feature {@code featureKey}; false while the features are off and for a key that is no registry key. */
public boolean generatesFeature(String featureKey) {
if (!generates || featureKey == null || featureKey.isBlank()) {
return false;
}
Boolean known = features.get(featureKey);
if (known != null) {
return known;
}
return features.computeIfAbsent(featureKey, key -> registryId(key)
.map(feature -> everyProviderAllows(provider -> provider.service().generatesFeature(provider.world(), feature)))
.orElse(false));
}
private boolean everyProviderAllows(Predicate<Provider> allows) {
return providers.stream().allMatch(allows);
}
private static Optional<DecorationStep> stepAt(int index) {
return index >= 0 && index < STEPS.length ? Optional.of(STEPS[index]) : Optional.empty();
}
private static Optional<ResourceId> registryId(String key) {
try {
return Optional.of(ResourceId.parse(key.trim()));
} catch (IllegalArgumentException notAnId) {
return Optional.empty();
}
}
}
@@ -43,6 +43,7 @@ import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.Set; import java.util.Set;
import java.util.TreeMap; import java.util.TreeMap;
import java.util.TreeSet;
/** /**
* The resources of the pack's module resource kinds that a pack export has to carry: what the settings of the * The resources of the pack's module resource kinds that a pack export has to carry: what the settings of the
@@ -59,6 +60,7 @@ public final class ModuleResourceClosure {
private final Map<Class<?>, ResourceKind<?>> kindsByType = new HashMap<>(); private final Map<Class<?>, ResourceKind<?>> kindsByType = new HashMap<>();
private final Map<ResourceKind<?>, Map<String, Object>> found = new LinkedHashMap<>(); private final Map<ResourceKind<?>, Map<String, Object>> found = new LinkedHashMap<>();
private final Set<Object> visited = java.util.Collections.newSetFromMap(new IdentityHashMap<>()); private final Set<Object> visited = java.util.Collections.newSetFromMap(new IdentityHashMap<>());
private final Map<Class<?>, Set<String>> exportedElsewhere = new HashMap<>();
public ModuleResourceClosure(IrisData data) { public ModuleResourceClosure(IrisData data) {
this.data = data; this.data = data;
@@ -67,6 +69,16 @@ public final class ModuleResourceClosure {
} }
} }
/**
* Leaves the resources that read into {@code type} to another exporter, such as Iris's structure closure that
* copies structures with their pools, pieces and loot: {@link #keysOf} names the ones referenced, but they are
* not loaded, followed or written. Call before following anything.
*/
public ModuleResourceClosure exportingElsewhere(Class<?> type) {
exportedElsewhere.putIfAbsent(type, new TreeSet<>());
return this;
}
/** Adds the resources that the module settings of {@code owner} reference, and those they reference. */ /** Adds the resources that the module settings of {@code owner} reference, and those they reference. */
public void followSettingsOf(IrisRegistrant owner) { public void followSettingsOf(IrisRegistrant owner) {
owner.getModuleSettings().values().forEach(this::follow); owner.getModuleSettings().values().forEach(this::follow);
@@ -108,6 +120,9 @@ public final class ModuleResourceClosure {
/** The keys of the resources found of the kind that reads into {@code type}, in key order. */ /** The keys of the resources found of the kind that reads into {@code type}, in key order. */
public List<String> keysOf(Class<?> type) { public List<String> keysOf(Class<?> type) {
if (exportedElsewhere.containsKey(type)) {
return new ArrayList<>(exportedElsewhere.get(type));
}
ResourceKind<?> kind = kindsByType.get(type); ResourceKind<?> kind = kindsByType.get(type);
return kind == null || !found.containsKey(kind) ? List.of() : new ArrayList<>(new TreeMap<>(found.get(kind)).keySet()); return kind == null || !found.containsKey(kind) ? List.of() : new ArrayList<>(new TreeMap<>(found.get(kind)).keySet());
} }
@@ -175,6 +190,11 @@ public final class ModuleResourceClosure {
if (kind == null || key == null || key.isBlank()) { if (kind == null || key == null || key.isBlank()) {
return; return;
} }
Set<String> elsewhere = exportedElsewhere.get(type);
if (elsewhere != null) {
elsewhere.add(key);
return;
}
Map<String, Object> ofKind = found.computeIfAbsent(kind, ignored -> new LinkedHashMap<>()); Map<String, Object> ofKind = found.computeIfAbsent(kind, ignored -> new LinkedHashMap<>());
if (ofKind.containsKey(key)) { if (ofKind.containsKey(key)) {
return; return;
@@ -34,7 +34,7 @@ import art.arcane.iris.engine.object.material.IrisBlockData;
import art.arcane.iris.engine.object.world.dimension.IrisDimension; import art.arcane.iris.engine.object.world.dimension.IrisDimension;
import art.arcane.iris.engine.object.terrain.IrisGenerator; import art.arcane.iris.engine.object.terrain.IrisGenerator;
import art.arcane.iris.engine.object.world.region.IrisRegion; import art.arcane.iris.engine.object.world.region.IrisRegion;
import art.arcane.iris.engine.object.structure.IrisStructurePlacement; import art.arcane.iris.engine.object.structure.IrisStructure;
import art.arcane.iris.spi.IrisLogging; import art.arcane.iris.spi.IrisLogging;
import art.arcane.iris.spi.IrisPlatforms; import art.arcane.iris.spi.IrisPlatforms;
import art.arcane.iris.util.common.plugin.VolmitSender; import art.arcane.iris.util.common.plugin.VolmitSender;
@@ -52,8 +52,7 @@ import org.zeroturnaround.zip.ZipUtil;
import java.io.File; import java.io.File;
import java.io.IOException; import java.io.IOException;
import java.util.LinkedHashSet; import java.util.List;
import java.util.Set;
import java.util.UUID; import java.util.UUID;
@SuppressWarnings("ALL") @SuppressWarnings("ALL")
@@ -105,7 +104,7 @@ public class IrisPackageCompiler {
KSet<IrisRegion> regions = new KSet<>(); KSet<IrisRegion> regions = new KSet<>();
KSet<IrisBiome> biomes = new KSet<>(); KSet<IrisBiome> biomes = new KSet<>();
KSet<IrisGenerator> generators = new KSet<>(); KSet<IrisGenerator> generators = new KSet<>();
ModuleResourceClosure moduleResources = new ModuleResourceClosure(dm); ModuleResourceClosure moduleResources = new ModuleResourceClosure(dm).exportingElsewhere(IrisStructure.class);
KSet<IrisBlockData> blocks = new KSet<>(); KSet<IrisBlockData> blocks = new KSet<>();
// KSet is ConcurrentHashMap-backed: both add(null) and remove(null) throw NPE, so a // KSet is ConcurrentHashMap-backed: both add(null) and remove(null) throw NPE, so a
@@ -125,10 +124,7 @@ public class IrisPackageCompiler {
regions.forEach((r) -> allPlacements.addAll(r.getObjects())); regions.forEach((r) -> allPlacements.addAll(r.getObjects()));
biomes.forEach((i) -> allPlacements.addAll(i.getObjects())); biomes.forEach((i) -> allPlacements.addAll(i.getObjects()));
moduleResources.follow(allPlacements); moduleResources.follow(allPlacements);
Set<String> structureKeys = new LinkedHashSet<>(); List<String> structureKeys = moduleResources.keysOf(IrisStructure.class);
collectStructureKeys(structureKeys, dimension.getStructures());
regions.forEach((region) -> collectStructureKeys(structureKeys, region.getStructures()));
biomes.forEach((biome) -> collectStructureKeys(structureKeys, biome.getStructures()));
KMap<String, String> renameObjects = new KMap<>(); KMap<String, String> renameObjects = new KMap<>();
String a; String a;
StringBuilder b = new StringBuilder(); StringBuilder b = new StringBuilder();
@@ -265,18 +261,4 @@ public class IrisPackageCompiler {
settings.keySet().forEach(key -> json.put(key, settings.get(key))); settings.keySet().forEach(key -> json.put(key, settings.get(key)));
return json; return json;
} }
private static void collectStructureKeys(Set<String> keys, KList<IrisStructurePlacement> placements) {
if (placements == null) {
return;
}
for (IrisStructurePlacement placement : placements) {
if (placement == null || placement.getStructures() == null) {
continue;
}
for (String structureKey : placement.getStructures()) {
keys.add(structureKey);
}
}
}
} }
@@ -28,14 +28,12 @@ import art.arcane.iris.core.loader.ResourceLoader;
import art.arcane.iris.core.modules.IrisValues; import art.arcane.iris.core.modules.IrisValues;
import art.arcane.iris.core.modules.ModuleResourceFiles; import art.arcane.iris.core.modules.ModuleResourceFiles;
import art.arcane.iris.core.modules.ModuleTargets; import art.arcane.iris.core.modules.ModuleTargets;
import art.arcane.iris.engine.framework.structure.StructureResources;
import art.arcane.iris.engine.object.image.IrisImageMap; import art.arcane.iris.engine.object.image.IrisImageMap;
import art.arcane.iris.engine.object.noise.NoiseStyle; import art.arcane.iris.engine.object.noise.NoiseStyle;
import art.arcane.iris.engine.object.noise.expression.IrisExpression; import art.arcane.iris.engine.object.noise.expression.IrisExpression;
import art.arcane.iris.engine.object.prefab.IrisObject; import art.arcane.iris.engine.object.prefab.IrisObject;
import art.arcane.iris.engine.object.world.biome.IrisBiome; import art.arcane.iris.engine.object.world.biome.IrisBiome;
import art.arcane.iris.engine.object.world.region.IrisRegion; import art.arcane.iris.engine.object.world.region.IrisRegion;
import art.arcane.iris.core.structure.StructureSchemaKeys;
import art.arcane.iris.engine.framework.ListFunction; import art.arcane.iris.engine.framework.ListFunction;
import art.arcane.iris.engine.object.annotations.ArrayType; import art.arcane.iris.engine.object.annotations.ArrayType;
import art.arcane.iris.engine.object.annotations.Desc; import art.arcane.iris.engine.object.annotations.Desc;
@@ -51,7 +49,6 @@ import art.arcane.iris.engine.object.annotations.RegistryListItemType;
import art.arcane.iris.engine.object.annotations.RegistryListPotionEffect; import art.arcane.iris.engine.object.annotations.RegistryListPotionEffect;
import art.arcane.iris.engine.object.annotations.RegistryListResource; import art.arcane.iris.engine.object.annotations.RegistryListResource;
import art.arcane.iris.engine.object.annotations.RegistryListSpecialEntity; import art.arcane.iris.engine.object.annotations.RegistryListSpecialEntity;
import art.arcane.iris.engine.object.annotations.RegistryListStructure;
import art.arcane.iris.engine.object.annotations.RegistryListVanillaStructure; import art.arcane.iris.engine.object.annotations.RegistryListVanillaStructure;
import art.arcane.iris.engine.object.annotations.RegistryMapBlockState; import art.arcane.iris.engine.object.annotations.RegistryMapBlockState;
import art.arcane.iris.engine.object.annotations.Required; import art.arcane.iris.engine.object.annotations.Required;
@@ -601,21 +598,6 @@ public class SchemaBuilder {
} else { } else {
IrisLogging.error("Cannot find Registry Loader for type " + rr.value() + " used in " + k.getDeclaringClass().getCanonicalName() + " in field " + k.getName()); IrisLogging.error("Cannot find Registry Loader for type " + rr.value() + " used in " + k.getDeclaringClass().getCanonicalName() + " in field " + k.getName());
} }
} else if (k.isAnnotationPresent(RegistryListStructure.class)) {
String key = "enum-iris-structure-placement";
if (!definitions.containsKey(key)) {
JSONObject j = new JSONObject();
j.put("enum", new JSONArray(StructureSchemaKeys.collect(
StructureResources.structureKeys(data),
StructureResources.pieceKeys(data)).toArray(new String[0])));
definitions.put(key, j);
}
fancyType = "Structure";
prop.put("$ref", "#/definitions/" + key);
description.add(SYMBOL_TYPE__N + " Must be a valid vanilla, datapack, or imported Iris structure (use ctrl+space for auto complete!)");
} else if (k.isAnnotationPresent(RegistryListBlockType.class)) { } else if (k.isAnnotationPresent(RegistryListBlockType.class)) {
fancyType = "Block Type"; fancyType = "Block Type";
putRegistryEnumRef(prop, "enum-block-type", this::blockTypes); putRegistryEnumRef(prop, "enum-block-type", this::blockTypes);
@@ -777,22 +759,6 @@ public class SchemaBuilder {
} else { } else {
IrisLogging.error("Cannot find Registry Loader for type (list schema) " + rr.value() + " used in " + k.getDeclaringClass().getCanonicalName() + " in field " + k.getName()); IrisLogging.error("Cannot find Registry Loader for type (list schema) " + rr.value() + " used in " + k.getDeclaringClass().getCanonicalName() + " in field " + k.getName());
} }
} else if (k.isAnnotationPresent(RegistryListStructure.class)) {
fancyType = "List<Structure>";
String key = "enum-iris-structure-placement";
if (!definitions.containsKey(key)) {
JSONObject j = new JSONObject();
j.put("enum", new JSONArray(StructureSchemaKeys.collect(
StructureResources.structureKeys(data),
StructureResources.pieceKeys(data)).toArray(new String[0])));
definitions.put(key, j);
}
JSONObject items = new JSONObject();
items.put("$ref", "#/definitions/" + key);
prop.put("items", items);
description.add(SYMBOL_TYPE__N + " Must be a valid vanilla, datapack, or imported Iris structure (use ctrl+space for auto complete!)");
} else if (k.isAnnotationPresent(RegistryListVanillaStructure.class)) { } else if (k.isAnnotationPresent(RegistryListVanillaStructure.class)) {
fancyType = "List<Vanilla Structure>"; fancyType = "List<Vanilla Structure>";
putRegistryEnumItems(prop, "enum-vanilla-structure", this::vanillaStructures); putRegistryEnumItems(prop, "enum-vanilla-structure", this::vanillaStructures);
@@ -1,57 +0,0 @@
/*
* Iris is a World Generator for Minecraft Bukkit Servers
* Copyright (c) 2022 Arcane Arts (Volmit Software)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package art.arcane.iris.core.structure;
import art.arcane.volmlib.util.collection.KList;
import java.util.Collection;
import java.util.HashSet;
import java.util.Set;
import java.util.TreeSet;
public final class StructureSchemaKeys {
private StructureSchemaKeys() {
}
public static KList<String> collect(Collection<String> structureKeys, Collection<String> jigsawPieceKeys) {
Set<String> pieces = new HashSet<>();
if (jigsawPieceKeys != null) {
for (String piece : jigsawPieceKeys) {
if (piece != null && !piece.isBlank()) {
pieces.add(piece);
}
}
}
TreeSet<String> merged = new TreeSet<>();
if (structureKeys != null) {
for (String key : structureKeys) {
if (key == null || key.isBlank()) {
continue;
}
if (pieces.contains(key)) {
continue;
}
merged.add(key);
}
}
return new KList<>(merged);
}
}
@@ -24,8 +24,6 @@ import art.arcane.iris.engine.EngineRuntime.BiomeMaxes;
import art.arcane.iris.engine.EngineRuntimeBuilder.RuntimeAssembly; import art.arcane.iris.engine.EngineRuntimeBuilder.RuntimeAssembly;
import art.arcane.iris.engine.IrisEngine.LifecycleState; import art.arcane.iris.engine.IrisEngine.LifecycleState;
import art.arcane.iris.engine.framework.EngineTarget; import art.arcane.iris.engine.framework.EngineTarget;
import art.arcane.iris.engine.framework.IrisStructureLocator;
import art.arcane.iris.engine.framework.StructureReachability;
import art.arcane.iris.engine.object.world.dimension.IrisDimension; import art.arcane.iris.engine.object.world.dimension.IrisDimension;
import art.arcane.iris.spi.IrisLogging; import art.arcane.iris.spi.IrisLogging;
import art.arcane.iris.spi.IrisServices; import art.arcane.iris.spi.IrisServices;
@@ -117,8 +115,6 @@ final class EngineHotloader {
} }
engine.getPlatformHooks().validateDimensionHotload(engine, replacement); engine.getPlatformHooks().validateDimensionHotload(engine, replacement);
replacementData.registerEngine(engine); replacementData.registerEngine(engine);
IrisStructureLocator.invalidate(engine);
StructureReachability.invalidate(engine);
EngineTarget replacementTarget = new EngineTarget(engine.getWorld(), replacement, replacementData); EngineTarget replacementTarget = new EngineTarget(engine.getWorld(), replacement, replacementData);
EngineRuntime nextRuntime = engine.runtimeBuilder.buildRuntime(replacementTarget); EngineRuntime nextRuntime = engine.runtimeBuilder.buildRuntime(replacementTarget);
engine.runtimeBuilder.publishRuntime(nextRuntime, previousRuntime); engine.runtimeBuilder.publishRuntime(nextRuntime, previousRuntime);
@@ -151,8 +147,6 @@ final class EngineHotloader {
e.addSuppressed(replacementDataFailure); e.addSuppressed(replacementDataFailure);
} }
} }
IrisStructureLocator.invalidate(engine);
StructureReachability.invalidate(engine);
if (engine.lifecycleState != LifecycleState.FAILED) { if (engine.lifecycleState != LifecycleState.FAILED) {
Throwable rollbackFailure = runCleanup(null, engine.getMantle()::hotload); Throwable rollbackFailure = runCleanup(null, engine.getMantle()::hotload);
if (rollbackFailure == null) { if (rollbackFailure == null) {
@@ -18,75 +18,39 @@
package art.arcane.iris.engine.framework; package art.arcane.iris.engine.framework;
import art.arcane.iris.engine.object.decoration.IrisDecorationStep; import art.arcane.iris.core.modules.ModuleServices;
import art.arcane.iris.engine.object.world.dimension.IrisDimension; import art.arcane.iris.core.modules.VanillaFeatureAnswers;
import art.arcane.iris.engine.object.decoration.IrisImportedFeatureControl;
import art.arcane.iris.engine.object.decoration.NativeFeatureGenerationStatus;
import java.util.Objects; import java.util.Objects;
/** /**
* Single decision point for native placed-feature generation, mirroring {@link NativeStructureGenerationPolicy}. * Single decision point for native placed-feature generation, mirroring {@link NativeStructureGenerationPolicy}: what
* Both platform generators call only through here so the Bukkit and modded feature passes cannot drift. * the pack's modules say through {@link com.volmit.service.VanillaFeatures}, kept for the engine's world. Both platform
* generators call only through here so the Bukkit and modded feature passes cannot drift.
*/ */
public final class NativeFeatureGenerationPolicy { public final class NativeFeatureGenerationPolicy {
/**
* Stand-in for a dimension that has no control block. Immutable in practice: nothing here hands it out for
* mutation, and every default in {@link IrisImportedFeatureControl} is "off".
*/
private static final IrisImportedFeatureControl DISABLED = new IrisImportedFeatureControl();
private NativeFeatureGenerationPolicy() { private NativeFeatureGenerationPolicy() {
} }
/** /**
* The dimension's control block, or a disabled default when it has none. * True when a module turned the native feature pass on for this world. Checked before any feature machinery is
* <p> * built so a world without it never allocates a feature table.
* An absent {@code importedFeatures} member deserializes to the field's initializer, but an explicit
* {@code "importedFeatures": null} in dimension JSON overwrites that initializer with null - Gson assigns what
* the document says. This runs on the generation path for every feature decision, so throwing there turns one
* stray null in a pack into a failed chunk rather than a dimension that simply generates no native features.
*/
public static IrisImportedFeatureControl control(Engine engine) {
Engine activeEngine = Objects.requireNonNull(engine, "Native feature policy requires an engine");
IrisDimension dimension = Objects.requireNonNull(activeEngine.getDimension(),
"Native feature policy requires a bound dimension");
IrisImportedFeatureControl control = dimension.getImportedFeatures();
return control == null ? DISABLED : control;
}
/**
* True when this dimension opted into the native feature pass. Checked before any feature machinery is
* built so a disabled dimension never allocates a feature table.
*/ */
public static boolean isEnabled(Engine engine) { public static boolean isEnabled(Engine engine) {
return control(engine).shouldGenerateFeatures(); return answers(engine).generates();
} }
public static NativeFeatureGenerationStatus resolve(Engine engine, String placedFeatureKey, /** Whether the features of the platform's decoration step {@code stepIndex} (in the platform's order) generate. */
IrisDecorationStep step) { public static boolean shouldGenerateStep(Engine engine, int stepIndex) {
return control(engine).resolve(placedFeatureKey, step); return answers(engine).generatesStep(stepIndex);
} }
public static boolean shouldGenerateStep(Engine engine, IrisDecorationStep step) { /** Whether the placed feature {@code placedFeatureKey}, such as {@code minecraft:ore_diamond}, generates. */
return control(engine).shouldGenerateStep(step); public static boolean shouldGenerate(Engine engine, String placedFeatureKey) {
return answers(engine).generatesFeature(placedFeatureKey);
} }
public static String generationStatusMessage(String placedFeatureKey, private static VanillaFeatureAnswers answers(Engine engine) {
NativeFeatureGenerationStatus status) { return ModuleServices.vanillaFeatures(Objects.requireNonNull(engine, "Native feature policy requires an engine"));
String key = placedFeatureKey == null ? "" : placedFeatureKey.trim();
return switch (Objects.requireNonNull(status, "Native feature status must not be null")) {
case GENERATE_NATIVE -> "Native feature " + key + " generates natively.";
case FEATURES_DISABLED -> "Native feature " + key
+ " does not generate because this dimension's importedFeatures.enabled is false.";
case STEP_DISABLED -> "Native feature " + key
+ " does not generate because its decoration step is excluded by importedFeatures.";
case DISABLED_BY_PACK -> "Native feature " + key
+ " is disabled by this dimension's importedFeatures.disabled list.";
case CYCLE_DEGRADED -> "Native feature " + key
+ " does not generate because the registered features could not be ordered "
+ "(feature order cycle); importedFeatures was degraded to off for this dimension.";
case INVALID_REGISTRY_KEY -> "Native feature registry key is invalid: " + key;
};
} }
} }
@@ -0,0 +1,124 @@
/*
* Iris is a World Generator for Minecraft Bukkit Servers
* Copyright (c) 2022 Arcane Arts (Volmit Software)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package art.arcane.iris.engine.framework;
import art.arcane.iris.engine.object.world.IrisWorld;
import art.arcane.iris.spi.IrisPlatforms;
import art.arcane.volmlib.util.collection.KList;
import java.util.Collections;
import java.util.LinkedHashSet;
import java.util.Locale;
import java.util.Objects;
import java.util.Set;
/**
* Determines which vanilla/datapack structures can ever generate in a world, using the same biome
* gate vanilla applies: a structure is reachable when its biome filter intersects the set of vanilla
* biomes the pack actually produces (its {@code possibleBiomes}). Structures whose required biomes are
* never produced cannot generate and must not be scanned for by {@code /locate} or {@code /iris find}
* (an unbounded scan for an absent biome is what stalls the server).
*
* <p>The reachable set is fixed per world: it is kept in the world's state, so a hotload's new world builds it again.
* It is the platform's answer, so Iris core asks it, not a module.
*/
public final class StructureReachability {
private StructureReachability() {
}
public static Set<String> reachableKeys(Engine engine) {
Engine activeEngine = Objects.requireNonNull(engine, "Structure reachability requires an engine");
if (activeEngine.getData() == null) {
throw new IllegalStateException("Structure reachability requires a bound pack data loader");
}
return activeEngine.getGeneration().state(ReachableKeys.class, ReachableKeys::of).keys();
}
public static boolean isReachable(Engine engine, String structureKey) {
String normalizedStructureKey = normalizeStructureKey(structureKey);
return reachableKeys(engine).contains(normalizedStructureKey);
}
private static Set<String> build(Engine engine) {
IrisWorld world = engine.getWorld();
if (world == null) {
throw new IllegalStateException("Structure reachability requires a bound Iris world");
}
if (world.platformWorld() == null) {
throw new IllegalStateException("Structure reachability requires a bound platform world");
}
Set<String> reachable = new LinkedHashSet<>();
for (String key : IrisPlatforms.get().structureHooks().reachableStructureKeys(world.platformWorld())) {
if (key == null || key.isBlank()) {
throw new IllegalStateException("Platform structure reachability returned a blank registry key");
}
reachable.add(key.toLowerCase(Locale.ROOT));
}
return Collections.unmodifiableSet(reachable);
}
/**
* The vanilla biome keys (e.g. {@code minecraft:taiga}) from a structure's filter that the pack
* does not produce. An empty list means the structure is reachable. Used by the structure verify
* diagnostic to explain why a structure cannot generate.
*/
public static KList<String> missingBiomeKeys(Engine engine, String structureKey) {
KList<String> missing = new KList<>();
Engine activeEngine = Objects.requireNonNull(engine, "Structure biome diagnostics require an engine");
String normalizedStructureKey = normalizeStructureKey(structureKey);
IrisWorld world = activeEngine.getWorld();
if (world == null) {
throw new IllegalStateException("Structure biome diagnostics require a bound Iris world");
}
if (world.platformWorld() == null) {
throw new IllegalStateException("Structure biome diagnostics require a bound platform world");
}
Set<String> possible = new LinkedHashSet<>();
for (String key : IrisPlatforms.get().structureHooks().possibleBiomeKeys(world.platformWorld())) {
if (key == null || key.isBlank()) {
throw new IllegalStateException("Platform structure biome query returned a blank possible-biome key");
}
possible.add(key.toLowerCase(Locale.ROOT));
}
for (String biomeKey : IrisPlatforms.get().structureHooks().structureBiomeKeys(normalizedStructureKey)) {
if (biomeKey == null || biomeKey.isBlank()) {
throw new IllegalStateException("Platform structure biome query returned a blank required-biome key for "
+ normalizedStructureKey);
}
if (!possible.contains(biomeKey.toLowerCase(Locale.ROOT))) {
missing.add(biomeKey);
}
}
return missing;
}
/** The world's reachable structure keys, in lower case. */
private record ReachableKeys(Set<String> keys) {
static ReachableKeys of(Engine engine) {
return new ReachableKeys(build(engine));
}
}
private static String normalizeStructureKey(String structureKey) {
if (structureKey == null || structureKey.isBlank()) {
throw new IllegalArgumentException("Registered structure key must not be blank");
}
return structureKey.trim().toLowerCase(Locale.ROOT);
}
}
@@ -12,7 +12,7 @@ public interface NativeFitStart<S> {
int chunkZ(); int chunkZ();
/** The name of the platform's decoration step, as the API's {@code StructureStep} names it. */ /** The name of the platform's decoration step, as the API's {@code DecorationStep} names it. */
String step(); String step();
/** The name of the structure definition's terrain adaptation, as the API's {@code TerrainAdaptation} names it. */ /** The name of the structure definition's terrain adaptation, as the API's {@code TerrainAdaptation} names it. */
@@ -20,7 +20,6 @@ package art.arcane.iris.util.common.director.specialhandlers;
import art.arcane.iris.core.modules.ModuleServices; import art.arcane.iris.core.modules.ModuleServices;
import art.arcane.iris.engine.framework.Engine; import art.arcane.iris.engine.framework.Engine;
import art.arcane.iris.engine.framework.IrisStructureLocator;
import art.arcane.iris.engine.framework.NativeStructureGenerationPolicy; import art.arcane.iris.engine.framework.NativeStructureGenerationPolicy;
import art.arcane.iris.engine.framework.StructureReachability; import art.arcane.iris.engine.framework.StructureReachability;
import art.arcane.iris.engine.framework.NativeStructureGenerationStatus; import art.arcane.iris.engine.framework.NativeStructureGenerationStatus;
@@ -62,7 +61,7 @@ public class StructureHandler implements DirectorParameterHandler<String> {
String normalizedKey = normalizeKey(key); String normalizedKey = normalizeKey(key);
if (!normalizedKey.isEmpty() if (!normalizedKey.isEmpty()
&& !registeredKeys.containsKey(normalizedKey) && !registeredKeys.containsKey(normalizedKey)
&& !IrisStructureLocator.hasNativePlacement(activeEngine, key)) { && !ModuleServices.startsStructure(activeEngine, key)) {
suggestions.putIfAbsent(normalizedKey, key.trim()); suggestions.putIfAbsent(normalizedKey, key.trim());
} }
} }
@@ -116,9 +115,9 @@ public class StructureHandler implements DirectorParameterHandler<String> {
private static boolean isEligibleRegisteredKey(Engine engine, String key, String normalizedKey, private static boolean isEligibleRegisteredKey(Engine engine, String key, String normalizedKey,
Set<String> reachableKeys, boolean nativeGenerationEnabled) { Set<String> reachableKeys, boolean nativeGenerationEnabled) {
NativeStructureGenerationStatus status = NativeStructureGenerationPolicy.resolve(engine, key); NativeStructureGenerationStatus status = NativeStructureGenerationPolicy.resolve(engine, key);
boolean nativePlacement = IrisStructureLocator.hasNativePlacement(engine, key); boolean nativePlacement = ModuleServices.startsStructure(engine, key);
boolean locatableNativePlacement = nativePlacement boolean locatableNativePlacement = nativePlacement
&& IrisStructureLocator.hasLocatableNativePlacement(engine, key); && ModuleServices.canLocateStart(engine, key);
boolean locatableEditableReplacement = !nativePlacement boolean locatableEditableReplacement = !nativePlacement
&& status == NativeStructureGenerationStatus.REPLACED_BY_IRIS && status == NativeStructureGenerationStatus.REPLACED_BY_IRIS
&& ModuleServices.canLocateStructure(engine, key); && ModuleServices.canLocateStructure(engine, key);
@@ -0,0 +1,18 @@
package art.arcane.iris.builtin.structure;
import com.volmit.config.Desc;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
public class NativeStructureSuppressionDescTest {
@Test
public void suppressionTypeAndValuesKeepTheirStudioDescriptions() throws NoSuchFieldException {
assertEquals("Controls whether an Iris structure placement suppresses its imported native source.",
NativeStructureSuppression.class.getAnnotation(Desc.class).value());
assertEquals("Leaves native generation enabled alongside this Iris structure placement.",
NativeStructureSuppression.class.getField("NONE").getAnnotation(Desc.class).value());
assertEquals("Suppresses the structure's vanillaSource when used by a validated dimension-level replacement placement.",
NativeStructureSuppression.class.getField("REPLACE_SOURCE").getAnnotation(Desc.class).value());
}
}
@@ -0,0 +1,38 @@
package art.arcane.iris.builtin.structure;
import org.junit.Test;
import static art.arcane.iris.engine.framework.StructurePlacementFixtures.placement;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
public class StructurePlacementAnchorTest {
@Test
public void legacyPreservesUndergroundBehavior() {
StructurePlacement surface = new StructurePlacement();
StructurePlacement underground = placement("underground", true);
assertEquals(StructureAnchorMode.SURFACE, surface.resolvedAnchor());
assertEquals(StructureAnchorMode.HEIGHT_BAND, underground.resolvedAnchor());
assertFalse(surface.isAnchoredUnderground());
assertTrue(underground.isAnchoredUnderground());
}
@Test
public void explicitAnchorOverridesLegacyBoolean() {
StructurePlacement floor = placement("underground", false, "anchor", StructureAnchorMode.CAVE_FLOOR);
StructurePlacement surface = placement("underground", true, "anchor", StructureAnchorMode.SURFACE);
assertTrue(floor.isAnchoredUnderground());
assertFalse(surface.isAnchoredUnderground());
}
@Test
public void aMissingAnchorIsLegacy() {
StructurePlacement placement = placement("anchor", null, "underground", true);
assertEquals(StructureAnchorMode.LEGACY, placement.anchor());
assertEquals(StructureAnchorMode.HEIGHT_BAND, placement.resolvedAnchor());
}
}
@@ -21,6 +21,7 @@ package art.arcane.iris.core.modules;
import art.arcane.iris.core.loader.IrisData; import art.arcane.iris.core.loader.IrisData;
import art.arcane.iris.engine.framework.Engine; import art.arcane.iris.engine.framework.Engine;
import art.arcane.iris.engine.framework.SeedManager; import art.arcane.iris.engine.framework.SeedManager;
import art.arcane.iris.engine.framework.vanillafeatures.VanillaFeaturesModule;
import art.arcane.iris.engine.loot.LootModule; import art.arcane.iris.engine.loot.LootModule;
import art.arcane.iris.engine.modifier.MatterModule; import art.arcane.iris.engine.modifier.MatterModule;
import art.arcane.iris.engine.modifier.PerfectionModule; import art.arcane.iris.engine.modifier.PerfectionModule;
@@ -62,8 +63,8 @@ public final class BuiltInPack {
*/ */
public static List<IrisModule> jarModules() { public static List<IrisModule> jarModules() {
return List.of(new PostModule(), new PerfectionModule(), new MatterModule(), new LootModule(), new SpawnModule(), return List.of(new PostModule(), new PerfectionModule(), new MatterModule(), new LootModule(), new SpawnModule(),
new PrepareModule(), new AnchorModule(), new ValidateModule(), new BoreModule(), new BlocksModule(), new StiltModule(), new PrepareModule(), new AnchorModule(), new ValidateModule(), new BoreModule(), new BlocksModule(),
new VacuumModule(), new SnowModule()); new StiltModule(), new VacuumModule(), new SnowModule(), new VanillaFeaturesModule());
} }
/** Every built-in module: Iris's own and the compiled-in copies of the jar's ({@link #jarModules()}). */ /** Every built-in module: Iris's own and the compiled-in copies of the jar's ({@link #jarModules()}). */
@@ -60,8 +60,7 @@ public class BuiltInServicesTest {
@Test @Test
public void theModulesThatNeedToHearAboutWorldsHearThem() { public void theModulesThatNeedToHearAboutWorldsHearThem() {
assertEquals(List.of("iris:decorant", "iris:objects", "iris:structure", "iris:terrain"), BUILT_INS.lifecycles().stream() assertEquals(List.of("iris:decorant", "iris:objects", "iris:terrain"), BUILT_INS.lifecycles().stream()
.map(LifecycleRegistration::module).map(module -> module.info().id().toString()).toList()); .map(LifecycleRegistration::module).map(module -> module.info().id().toString()).toList());
assertTrue(BUILT_INS.lifecycles().stream().anyMatch(registration -> registration.lifecycle() instanceof StructureModule));
} }
} }
@@ -0,0 +1,202 @@
/*
* Iris is a World Generator for Minecraft Servers
* Copyright (c) 2026 Arcane Arts (Volmit Software)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package art.arcane.iris.core.modules;
import art.arcane.iris.builtin.structure.NativeStructureSource;
import art.arcane.iris.builtin.structure.NativeStructureSuppression;
import art.arcane.iris.builtin.structure.StructureAnchorMode;
import art.arcane.iris.builtin.structure.StructureDistribution;
import art.arcane.iris.builtin.structure.StructurePlacement;
import art.arcane.iris.builtin.structure.StructurePlacementSettings;
import art.arcane.iris.builtin.structure.StructureTerrainMode;
import art.arcane.iris.engine.framework.StructurePlacementGrid;
import art.arcane.volmlib.util.json.JSONObject;
import com.google.gson.Gson;
import com.volmit.FeatureAttachment.Target;
import com.volmit.host.LoadedPack;
import com.volmit.host.ModuleHost;
import org.junit.After;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import java.io.IOException;
import java.nio.file.Path;
import java.util.List;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
/**
* The {@code "structures"} of dimensions, regions and biomes as packs have always written them, read into
* {@link StructurePlacementSettings}. The pins are what the old host placement class gave for the same JSON.
*/
public class StructurePlacementSettingsDecodingTest {
/** The overworld's ancient city placement, as the pack wrote it before the move. */
private static final String OVERWORLD = """
{
"structures": [
{
"nativeStructures": [
{
"structure": "minecraft:ancient_city"
}
],
"placementId": "ancient-city-native",
"nativeSuppression": "REPLACE_SOURCE",
"underground": true,
"terrain": {
"mode": "FORCE_CARVE",
"horizontalPadding": 14,
"ceilingPadding": 12,
"floorPadding": 0,
"shape": "ERODED",
"erosionStrength": 1.0,
"erosionFrequency": 0.05
},
"stilt": {
"maxDepth": 768,
"spacing": 1,
"palette": {
"style": {
"style": "STATIC"
},
"palette": [
{
"block": "minecraft:deepslate_bricks",
"weight": 6
},
{
"block": "minecraft:cracked_deepslate_bricks",
"weight": 1
},
{
"block": "minecraft:deepslate_tiles",
"weight": 2
},
{
"block": "minecraft:cracked_deepslate_tiles",
"weight": 1
}
]
}
},
"minHeight": -220,
"maxHeight": -220,
"distribution": "RANDOM_SPREAD",
"spacing": 64,
"separation": 5,
"salt": 42069
}
]
}
""";
/** The same placement without its id, a second source, a cave anchor and density starts. */
private static final String ANONYMOUS = """
{"structures": [{"nativeStructures": [{"structure": "minecraft:ancient_city"}, {"structure": "minecraft:trial_chambers", "weight": 3}], "nativeSuppression": "REPLACE_SOURCE", "underground": true, "terrain": {"mode": "FORCE_CARVE", "horizontalPadding": 14, "ceilingPadding": 12, "floorPadding": 0, "shape": "ERODED", "erosionStrength": 1.0, "erosionFrequency": 0.05}, "stilt": {"maxDepth": 768, "spacing": 1, "palette": {"style": {"style": "STATIC"}, "palette": [{"block": "minecraft:deepslate_bricks", "weight": 6}, {"block": "minecraft:cracked_deepslate_bricks", "weight": 1}, {"block": "minecraft:deepslate_tiles", "weight": 2}, {"block": "minecraft:cracked_deepslate_tiles", "weight": 1}]}}, "minHeight": -220, "maxHeight": -220, "distribution": "DENSITY", "spacing": 64, "separation": 5, "salt": 42069, "anchor": "CAVE_FLOOR", "caveBiomes": ["Deep", " crystal"], "density": 0.4}]}
""";
private static final long WORLD_SEED = 1337L;
private static final int SCANNED_CHUNKS_FROM = -32;
private static final int SCANNED_CHUNKS_TO = 32;
@Rule
public TemporaryFolder folder = new TemporaryFolder();
private LoadedPack pack;
private ModuleSettingsDecoder decoder;
@Before
public void loadBuiltIns() throws IOException {
Path packFolder = folder.newFolder("pack").toPath();
pack = LoadedPack.load(packFolder, ModuleHost.of(BuiltInPack.allBuiltIns())
.describingHostTypesIn(IrisModuleHost.HOST_TYPE_PACKAGE).copyingJarsTo(folder.newFolder("copies").toPath()));
decoder = new ModuleSettingsDecoder(pack.catalog(), packFolder, Gson::new);
}
@After
public void closePack() {
pack.close();
}
@Test
public void theOverworldPlacementReadsAsThePackWroteIt() {
StructurePlacement placement = placements(Target.DIMENSION, OVERWORLD).getFirst();
assertEquals(List.of("minecraft:ancient_city"), placement.nativeStructures().stream().map(NativeStructureSource::structure).toList());
assertEquals(1, placement.nativeStructures().getFirst().weight());
assertTrue(placement.nativeStructures().getFirst().jigsaw().isEmpty());
assertEquals(List.of(), placement.structures());
assertEquals("ancient-city-native", placement.placementId());
assertEquals(NativeStructureSuppression.REPLACE_SOURCE, placement.nativeSuppression());
assertTrue(placement.underground());
assertEquals(StructureTerrainMode.FORCE_CARVE, placement.resolvedTerrain().resolvedMode());
assertEquals(14, placement.resolvedTerrain().horizontalPadding());
assertEquals(768, placement.stilt().orElseThrow().maxDepth());
assertEquals(-220, placement.minHeight());
assertEquals(-220, placement.maxHeight());
assertEquals(StructureDistribution.RANDOM_SPREAD, placement.distribution());
assertEquals(64, placement.spacing());
assertEquals(5, placement.separation());
assertEquals(42069, placement.salt());
assertEquals(StructureAnchorMode.HEIGHT_BAND, placement.resolvedAnchor());
}
@Test
public void placementsKeepTheirIdentityAndStarts() {
StructurePlacement overworld = placements(Target.DIMENSION, OVERWORLD).getFirst();
StructurePlacement anonymous = placements(Target.BIOME, ANONYMOUS).getFirst();
assertEquals(-5401497891314909808L, StructurePlacementGrid.placementIdentity(overworld));
assertEquals(-2165116524116229836L, StructurePlacementGrid.placementRng(overworld, 7, -11, 123L).getSeed());
assertEquals(new Starts(2, -939), starts(overworld));
assertEquals(-5867838400029675033L, StructurePlacementGrid.placementIdentity(anonymous));
assertEquals(-4577893773733009372L, StructurePlacementGrid.placementRng(anonymous, 7, -11, 123L).getSeed());
assertEquals(new Starts(1585, 865), starts(anonymous));
}
@Test
public void regionsAndBiomesDeclarePlacementsUnderTheSameKey() {
assertTrue(decoder.keys(Target.REGION).contains("structures"));
assertTrue(decoder.keys(Target.BIOME).contains("structures"));
assertEquals(1, placements(Target.REGION, OVERWORLD).size());
}
private List<StructurePlacement> placements(Target target, String json) {
return decoder.decode(target, new JSONObject(json), "test resource")
.find(StructurePlacementSettings.class).orElseThrow().placements();
}
private static Starts starts(StructurePlacement placement) {
int count = 0;
long checksum = 0;
for (int chunkX = SCANNED_CHUNKS_FROM; chunkX < SCANNED_CHUNKS_TO; chunkX++) {
for (int chunkZ = SCANNED_CHUNKS_FROM; chunkZ < SCANNED_CHUNKS_TO; chunkZ++) {
if (StructurePlacementGrid.startsInChunk(placement, chunkX, chunkZ, WORLD_SEED)) {
count++;
checksum += chunkX * 31L + chunkZ;
}
}
}
return new Starts(count, checksum);
}
private record Starts(int count, long checksum) {
}
}
@@ -0,0 +1,112 @@
/*
* Iris is a World Generator for Minecraft Servers
* Copyright (c) 2026 Arcane Arts (Volmit Software)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package art.arcane.iris.core.modules;
import art.arcane.iris.builtin.vanillafeatures.ImportedFeaturesSettings;
import art.arcane.volmlib.util.json.JSONObject;
import com.google.gson.Gson;
import com.volmit.FeatureAttachment.Target;
import com.volmit.host.LoadedPack;
import com.volmit.host.ModuleHost;
import com.volmit.vanilla.DecorationStep;
import org.junit.After;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import java.io.IOException;
import java.nio.file.Path;
import java.util.List;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertThrows;
import static org.junit.Assert.assertTrue;
/** A dimension's {@code importedFeatures} as packs have always written it, read into {@link ImportedFeaturesSettings}. */
public class VanillaFeaturesSettingsDecodingTest {
private static final String DIMENSION = """
{"importedFeatures": {
"enabled": true,
"disabled": ["minecraft:ore", "minecraft:trees_plains"],
"steps": ["UNDERGROUND_ORES", "VEGETAL_DECORATION"],
"disabledSteps": ["VEGETAL_DECORATION"]
}}
""";
@Rule
public TemporaryFolder folder = new TemporaryFolder();
private LoadedPack pack;
private ModuleSettingsDecoder decoder;
@Before
public void loadBuiltIns() throws IOException {
Path packFolder = folder.newFolder("pack").toPath();
pack = LoadedPack.load(packFolder, ModuleHost.of(BuiltInPack.allBuiltIns())
.describingHostTypesIn(IrisModuleHost.HOST_TYPE_PACKAGE).copyingJarsTo(folder.newFolder("copies").toPath()));
decoder = new ModuleSettingsDecoder(pack.catalog(), packFolder, Gson::new);
}
@After
public void closePack() {
pack.close();
}
@Test
public void everyOptionReadsAsPacksWroteIt() {
ImportedFeaturesSettings settings = settings(DIMENSION);
assertTrue(settings.enabled());
assertEquals(List.of("minecraft:ore", "minecraft:trees_plains"), settings.disabled());
assertEquals(List.of(DecorationStep.UNDERGROUND_ORES, DecorationStep.VEGETAL_DECORATION), settings.steps());
assertEquals(List.of(DecorationStep.VEGETAL_DECORATION), settings.disabledSteps());
}
@Test
public void emptySettingsAreOffAndTheFeatureIdIsNotAKey() {
ImportedFeaturesSettings defaults = settings("{\"importedFeatures\": {}}");
JSONObject byId = new JSONObject("{\"iris:vanilla-features\": {\"enabled\": true}}");
assertFalse(defaults.enabled());
assertEquals(List.of(), defaults.disabled());
assertEquals(List.of(), defaults.steps());
assertEquals(List.of(), defaults.disabledSteps());
assertSame(ModuleSettings.NONE, decoder.decode(Target.DIMENSION, byId, "dimension overworld"));
assertTrue(decoder.keys(Target.DIMENSION).contains("importedFeatures"));
}
@Test
public void aBareSwitchIsRefusedNamingTheKey() {
JSONObject bare = new JSONObject("{\"importedFeatures\": true}");
IllegalArgumentException refused = assertThrows(IllegalArgumentException.class,
() -> decoder.decode(Target.DIMENSION, bare, "dimension overworld"));
assertEquals("Cannot read settings iris:vanilla-features under \"importedFeatures\" in dimension overworld:"
+ " write the settings as an object, {\"<option>\": ...}", refused.getMessage());
}
private ImportedFeaturesSettings settings(String dimensionJson) {
return decoder.decode(Target.DIMENSION, new JSONObject(dimensionJson), "dimension overworld")
.find(ImportedFeaturesSettings.class).orElseThrow();
}
}
@@ -1,91 +0,0 @@
/*
* Iris is a World Generator for Minecraft Servers
* Copyright (c) 2026 Arcane Arts (Volmit Software)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package art.arcane.iris.core.project;
import art.arcane.iris.engine.object.decoration.IrisDecorationStep;
import art.arcane.iris.engine.object.decoration.IrisImportedFeatureControl;
import art.arcane.iris.engine.object.annotations.Desc;
import art.arcane.volmlib.util.json.JSONArray;
import art.arcane.volmlib.util.json.JSONObject;
import org.junit.Test;
import java.util.ArrayList;
import java.util.List;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
public class ImportedFeatureControlSchemaTest {
@Test
public void everyDecorationStepIsSchemaDescribed() throws NoSuchFieldException {
assertNotNull(IrisDecorationStep.class.getAnnotation(Desc.class));
for (IrisDecorationStep step : IrisDecorationStep.values()) {
assertNotNull(step.name(),
IrisDecorationStep.class.getField(step.name()).getAnnotation(Desc.class));
}
}
@Test
public void controlSchemaExposesEnabledFlagAndStepEnums() {
JSONObject schema = new SchemaBuilder(IrisImportedFeatureControl.class, null).construct();
JSONObject properties = schema.getJSONObject("properties");
assertEquals("boolean", properties.getJSONObject("enabled").getString("type"));
assertEquals("array", properties.getJSONObject("disabled").getString("type"));
assertEquals(1, properties.getJSONObject("disabled").getInt("minItems"));
for (String field : List.of("steps", "disabledSteps")) {
JSONObject list = properties.getJSONObject(field);
assertEquals("array", list.getString("type"));
String definitionKey = list.getJSONObject("items")
.getString("$ref").substring("#/definitions/".length());
JSONArray values = schema.getJSONObject("definitions")
.getJSONObject(definitionKey)
.getJSONArray("oneOf");
List<String> constants = new ArrayList<>();
for (int index = 0; index < values.length(); index++) {
JSONObject entry = values.getJSONObject(index);
constants.add(entry.getString("const"));
assertTrue(field + " " + entry.getString("const"),
entry.getString("description").length() > 0);
}
List<String> expected = new ArrayList<>();
for (IrisDecorationStep step : IrisDecorationStep.values()) {
expected.add(step.name());
}
assertEquals(expected, constants);
}
}
@Test
public void dimensionSchemaCarriesTheControlBlock() {
JSONObject schema = new SchemaBuilder(ControlHolder.class, null).construct();
JSONObject importedFeatures = schema.getJSONObject("properties").getJSONObject("importedFeatures");
assertTrue(importedFeatures.has("$ref") || importedFeatures.has("properties")
|| importedFeatures.has("anyOf"));
}
@Desc("Schema model for the imported feature control block.")
public static class ControlHolder {
@Desc("Controls native placed feature generation.")
private IrisImportedFeatureControl importedFeatures = new IrisImportedFeatureControl();
}
}
@@ -1,39 +0,0 @@
package art.arcane.iris.core.project;
import art.arcane.iris.engine.object.structure.vanilla.NativeStructureSuppression;
import art.arcane.iris.engine.object.annotations.Desc;
import art.arcane.volmlib.util.json.JSONArray;
import art.arcane.volmlib.util.json.JSONObject;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
public class NativeStructureSuppressionSchemaTest {
@Test
public void suppressionTypeAndValuesAreSchemaDescribed() throws NoSuchFieldException {
assertNotNull(NativeStructureSuppression.class.getAnnotation(Desc.class));
assertNotNull(NativeStructureSuppression.class.getField("NONE").getAnnotation(Desc.class));
assertNotNull(NativeStructureSuppression.class.getField("REPLACE_SOURCE").getAnnotation(Desc.class));
JSONObject schema = new SchemaBuilder(SuppressionModel.class, null).construct();
JSONObject suppression = schema.getJSONObject("properties").getJSONObject("suppression");
String definitionKey = suppression.getString("$ref").substring("#/definitions/".length());
JSONArray values = schema.getJSONObject("definitions")
.getJSONObject(definitionKey)
.getJSONArray("oneOf");
assertEquals("NONE", values.getJSONObject(0).getString("const"));
assertEquals("Leaves native generation enabled alongside this Iris structure placement.",
values.getJSONObject(0).getString("description"));
assertEquals("REPLACE_SOURCE", values.getJSONObject(1).getString("const"));
assertEquals("Suppresses the structure's vanillaSource when used by a validated dimension-level replacement placement.",
values.getJSONObject(1).getString("description"));
}
@Desc("Schema model for native structure suppression.")
public static class SuppressionModel {
@Desc("Native structure suppression behavior.")
private NativeStructureSuppression suppression = NativeStructureSuppression.NONE;
}
}
@@ -29,7 +29,6 @@ import art.arcane.iris.engine.object.noise.expression.IrisExpression;
import art.arcane.iris.engine.object.world.biome.IrisBiome; import art.arcane.iris.engine.object.world.biome.IrisBiome;
import art.arcane.iris.engine.object.world.dimension.IrisDimension; import art.arcane.iris.engine.object.world.dimension.IrisDimension;
import art.arcane.iris.engine.object.structure.IrisStructure; import art.arcane.iris.engine.object.structure.IrisStructure;
import art.arcane.iris.engine.object.structure.IrisStructurePlacement;
import art.arcane.iris.engine.object.annotations.ArrayType; import art.arcane.iris.engine.object.annotations.ArrayType;
import art.arcane.iris.engine.object.annotations.Desc; import art.arcane.iris.engine.object.annotations.Desc;
import art.arcane.iris.engine.object.annotations.MaxNumber; import art.arcane.iris.engine.object.annotations.MaxNumber;
@@ -44,7 +43,6 @@ import art.arcane.iris.engine.object.annotations.RegistryListSpecialEntity;
import art.arcane.iris.engine.object.annotations.RegistryListVanillaStructure; import art.arcane.iris.engine.object.annotations.RegistryListVanillaStructure;
import art.arcane.iris.engine.object.annotations.functions.LootTableKeyFunction; import art.arcane.iris.engine.object.annotations.functions.LootTableKeyFunction;
import art.arcane.iris.spi.IrisPlatform; import art.arcane.iris.spi.IrisPlatform;
import art.arcane.iris.engine.object.structure.vanilla.IrisNativeStructure;
import art.arcane.iris.spi.IrisPlatforms; import art.arcane.iris.spi.IrisPlatforms;
import art.arcane.iris.spi.LogLevel; import art.arcane.iris.spi.LogLevel;
import art.arcane.iris.spi.PlatformBiome; import art.arcane.iris.spi.PlatformBiome;
@@ -76,6 +74,7 @@ import com.volmit.host.ModuleHost;
import com.volmit.host.schema.PackSchema; import com.volmit.host.schema.PackSchema;
import com.volmit.stage.Stage; import com.volmit.stage.Stage;
import com.volmit.stage.StageGraph; import com.volmit.stage.StageGraph;
import com.volmit.vanilla.DecorationStep;
import org.junit.After; import org.junit.After;
import org.junit.Before; import org.junit.Before;
import org.junit.Test; import org.junit.Test;
@@ -87,8 +86,10 @@ import java.nio.file.Files;
import java.nio.file.Path; import java.nio.file.Path;
import java.util.regex.Pattern; import java.util.regex.Pattern;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Arrays;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.Stream; import java.util.stream.Stream;
import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertEquals;
@@ -168,8 +169,10 @@ public class SchemaBuilderParityTest {
@Test @Test
public void structurePlacementSchemaIncludesFoundationSettingsAndOmitsUnsupportedTransforms() { public void structurePlacementSchemaIncludesFoundationSettingsAndOmitsUnsupportedTransforms() {
JSONObject schema = new SchemaBuilder(IrisStructurePlacement.class, structureSchemaData()).construct(); JSONObject schema = new SchemaBuilder(IrisBiome.class, structureSchemaData()).construct();
JSONObject properties = schema.getJSONObject("properties"); JSONObject structures = rootProperties(schema).getJSONObject("structures");
JSONObject properties = schema.getJSONObject("definitions")
.getJSONObject(definitionKey(structures.getJSONObject("items"))).getJSONObject("properties");
JSONObject stilt = properties.getJSONObject("stilt"); JSONObject stilt = properties.getJSONObject("stilt");
JSONObject stiltDefinition = schema.getJSONObject("definitions") JSONObject stiltDefinition = schema.getJSONObject("definitions")
.getJSONObject(stilt.getString("$ref").substring("#/definitions/".length())); .getJSONObject(stilt.getString("$ref").substring("#/definitions/".length()));
@@ -203,7 +206,7 @@ public class SchemaBuilderParityTest {
assertEquals(1D, lobeFrequency.getDouble("maximum"), 0D); assertEquals(1D, lobeFrequency.getDouble("maximum"), 0D);
assertEquals(0D, lobeStrength.getDouble("minimum"), 0D); assertEquals(0D, lobeStrength.getDouble("minimum"), 0D);
assertEquals(1D, lobeStrength.getDouble("maximum"), 0D); assertEquals(1D, lobeStrength.getDouble("maximum"), 0D);
assertEquals("object", stilt.getString("type")); assertEquals("module-art-arcane-iris-builtin-structure-structurestilts", definitionKey(stilt));
assertTrue(stiltProperties.has("palette")); assertTrue(stiltProperties.has("palette"));
assertTrue(stiltProperties.has("supportNonOccluding")); assertTrue(stiltProperties.has("supportNonOccluding"));
assertEquals(1, maxDepth.getInt("minimum")); assertEquals(1, maxDepth.getInt("minimum"));
@@ -265,9 +268,13 @@ public class SchemaBuilderParityTest {
IrisPlatforms.unbind(); IrisPlatforms.unbind();
IrisPlatforms.bind(new FakePlatform(hooks)); IrisPlatforms.bind(new FakePlatform(hooks));
JSONObject schema = new SchemaBuilder(IrisNativeStructure.class, structureSchemaData()).construct(); JSONObject schema = new SchemaBuilder(IrisDimension.class, structureSchemaData()).construct();
JSONObject definitions = schema.getJSONObject("definitions"); JSONObject definitions = schema.getJSONObject("definitions");
JSONObject jigsaw = definitions.getJSONObject(definitionKey(schema.getJSONObject("properties").getJSONObject("jigsaw"))) JSONObject placement = definitions.getJSONObject(definitionKey(rootProperties(schema).getJSONObject("structures")
.getJSONObject("items"))).getJSONObject("properties");
JSONObject source = definitions.getJSONObject(definitionKey(placement.getJSONObject("nativeStructures")
.getJSONObject("items"))).getJSONObject("properties");
JSONObject jigsaw = definitions.getJSONObject(definitionKey(source.getJSONObject("jigsaw")))
.getJSONObject("properties"); .getJSONObject("properties");
assertEquals("enum-native-jigsaw-pool", definitionKey(jigsaw.getJSONObject("startPool"))); assertEquals("enum-native-jigsaw-pool", definitionKey(jigsaw.getJSONObject("startPool")));
@@ -275,6 +282,29 @@ public class SchemaBuilderParityTest {
values(definitions.getJSONObject("enum-native-jigsaw-pool").getJSONArray("enum"))); values(definitions.getJSONObject("enum-native-jigsaw-pool").getJSONArray("enum")));
} }
/** {@code importedFeatures} comes from {@code iris:vanilla-features}; its steps keep the descriptions studio showed. */
@Test
public void importedFeaturesListTheDecorationStepsWithTheirDescriptions() throws IOException {
JSONObject schema = new SchemaBuilder(IrisDimension.class, structureSchemaData()).construct();
JSONObject definitions = schema.getJSONObject("definitions");
JSONObject settings = definitions.getJSONObject(definitionKey(rootProperties(schema).getJSONObject("importedFeatures")))
.getJSONObject("properties");
assertEquals("boolean", settings.getJSONObject("enabled").getString("type"));
assertEquals(1, settings.getJSONObject("disabled").getInt("minItems"));
for (String field : List.of("steps", "disabledSteps")) {
JSONObject items = settings.getJSONObject(field).getJSONObject("items");
JSONObject steps = items.has("$ref") ? definitions.getJSONObject(definitionKey(items)) : items;
assertEquals(1, settings.getJSONObject(field).getInt("minItems"));
assertEquals(Arrays.stream(DecorationStep.values()).map(step -> "\"" + step.name() + "\"").collect(Collectors.joining(",")),
steps.getJSONArray("enum").join(","));
JSONArray descriptions = steps.getJSONArray("enumDescriptions");
for (int index = 0; index < descriptions.length(); index++) {
assertFalse(field + " " + index, descriptions.getString(index).isBlank());
}
}
}
@Test @Test
public void structureSettingsRenderTheirFitsWithTheModulesDefinitions() throws IOException { public void structureSettingsRenderTheirFitsWithTheModulesDefinitions() throws IOException {
JSONObject schema = new SchemaBuilder(IrisDimension.class, structureSchemaData(structureSettingsSchema())).construct(); JSONObject schema = new SchemaBuilder(IrisDimension.class, structureSchemaData(structureSettingsSchema())).construct();
@@ -1,71 +0,0 @@
package art.arcane.iris.core.structure;
import art.arcane.volmlib.util.collection.KList;
import org.junit.Test;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
public class StructureSchemaKeysTest {
@Test
public void exposesOnlyExistingIrisStructureResources() {
KList<String> result = StructureSchemaKeys.collect(
Arrays.asList("minecraft_stronghold", "custom/cool_tower"),
Collections.emptyList());
assertEquals(Arrays.asList("custom/cool_tower", "minecraft_stronghold"), result);
}
@Test
public void nativeRegistryKeysAreNotSynthesized() {
KList<String> result = StructureSchemaKeys.collect(
Collections.singletonList("custom/castle"),
Collections.emptyList());
assertFalse(result.contains("minecraft_stronghold"));
assertFalse(result.contains("minecraft:stronghold"));
assertTrue(result.contains("custom/castle"));
}
@Test
public void jigsawComponentPiecesAreExcluded() {
List<String> pieces = Arrays.asList(
"village/taiga/houses/taiga_small_house_5",
"trial_chambers/corridor/straight_1");
KList<String> result = StructureSchemaKeys.collect(
Arrays.asList("village/taiga/houses/taiga_small_house_5", "custom/castle"),
pieces);
assertFalse(result.contains("village/taiga/houses/taiga_small_house_5"));
assertTrue(result.contains("custom/castle"));
}
@Test
public void resultIsSortedAndDeduplicated() {
KList<String> result = StructureSchemaKeys.collect(
Arrays.asList("zeta", "alpha", "zeta"),
Collections.emptyList());
assertEquals(Arrays.asList("alpha", "zeta"), result);
}
@Test
public void nullCollectionsAreHandled() {
assertTrue(StructureSchemaKeys.collect(null, null).isEmpty());
}
@Test
public void blankAndNullEntriesAreIgnored() {
KList<String> result = StructureSchemaKeys.collect(
Arrays.asList("custom_one", "", null, " "),
Arrays.asList("", null));
assertEquals(Collections.singletonList("custom_one"), result);
}
}
@@ -32,27 +32,33 @@ import art.arcane.iris.engine.object.structure.jigsaw.IrisJigsawConnector;
import art.arcane.iris.engine.object.structure.jigsaw.IrisJigsawPiece; import art.arcane.iris.engine.object.structure.jigsaw.IrisJigsawPiece;
import art.arcane.iris.engine.object.structure.jigsaw.IrisJigsawPieceEntry; import art.arcane.iris.engine.object.structure.jigsaw.IrisJigsawPieceEntry;
import art.arcane.iris.engine.object.structure.jigsaw.IrisJigsawPool; import art.arcane.iris.engine.object.structure.jigsaw.IrisJigsawPool;
import art.arcane.iris.engine.object.structure.vanilla.IrisNativeStructure; import art.arcane.iris.builtin.structure.NativeStructureSource;
import art.arcane.iris.engine.object.prefab.IrisObject; import art.arcane.iris.engine.object.prefab.IrisObject;
import art.arcane.iris.engine.object.value.IrisPosition; import art.arcane.iris.engine.object.value.IrisPosition;
import art.arcane.iris.engine.object.world.region.IrisRegion; import art.arcane.iris.engine.object.world.region.IrisRegion;
import art.arcane.iris.engine.object.structure.IrisStructure; import art.arcane.iris.engine.object.structure.IrisStructure;
import art.arcane.iris.engine.object.structure.IrisStructureAnchorMode; import art.arcane.iris.builtin.structure.StructureAnchorMode;
import art.arcane.iris.engine.object.structure.IrisStructurePlacement; import art.arcane.iris.builtin.structure.StructurePlacement;
import art.arcane.iris.engine.object.structure.vanilla.NativeStructureSuppression; import art.arcane.iris.builtin.structure.NativeStructureSuppression;
import art.arcane.iris.engine.object.structure.StructureDistribution; import art.arcane.iris.builtin.structure.StructureDistribution;
import art.arcane.volmlib.util.collection.KList; import art.arcane.volmlib.util.collection.KList;
import art.arcane.volmlib.util.math.RNG; import art.arcane.volmlib.util.math.RNG;
import com.volmit.host.ModuleLogs; import com.volmit.host.ModuleLogs;
import org.junit.Test; import org.junit.Test;
import java.util.Set; import java.util.Set;
import art.arcane.iris.engine.object.TestSettings;
import static art.arcane.iris.engine.framework.StructurePlacementFixtures.placement;
import static art.arcane.iris.engine.framework.StructurePlacementFixtures.nativeSource;
import static art.arcane.iris.engine.framework.StructurePlacementFixtures.declaring;
import static art.arcane.iris.engine.framework.StructurePlacementFixtures.withAdded;
import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNotSame; import static org.junit.Assert.assertNotSame;
import static org.junit.Assert.assertNull; import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertTrue; import static org.junit.Assert.assertTrue;
import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyInt; import static org.mockito.ArgumentMatchers.anyInt;
@@ -77,6 +83,7 @@ public class IrisStructureLocatorContractTest {
@Test @Test
public void isPlacedIsFalseForNullOrEmptyKey() { public void isPlacedIsFalseForNullOrEmptyKey() {
Engine engine = mock(Engine.class); Engine engine = mock(Engine.class);
when(engine.getGeneration()).thenReturn(new EngineGeneration(engine));
assertFalse(IrisStructureLocator.isPlaced(engine, null)); assertFalse(IrisStructureLocator.isPlaced(engine, null));
assertFalse(IrisStructureLocator.isPlaced(engine, "")); assertFalse(IrisStructureLocator.isPlaced(engine, ""));
} }
@@ -98,11 +105,11 @@ public class IrisStructureLocatorContractTest {
@Test @Test
public void locatablePlacementsExcludeEveryDistributionOutsideWorldHeight() { public void locatablePlacementsExcludeEveryDistributionOutsideWorldHeight() {
Engine randomSpread = densityEngine(1.0, false, -64, 384, 400, 500); Engine randomSpread = densityEngine(1.0, false, -64, 384, 400, 500);
randomSpread.getDimension().getStructures().get(0) TestSettings.with(StructurePlacementScope.placementsOf(randomSpread.getDimension()).get(0),
.setDistribution(StructureDistribution.RANDOM_SPREAD); "distribution", StructureDistribution.RANDOM_SPREAD);
Engine concentricRings = densityEngine(1.0, false, -64, 384, 400, 500); Engine concentricRings = densityEngine(1.0, false, -64, 384, 400, 500);
concentricRings.getDimension().getStructures().get(0) TestSettings.with(StructurePlacementScope.placementsOf(concentricRings.getDimension()).get(0),
.setDistribution(StructureDistribution.CONCENTRIC_RINGS); "distribution", StructureDistribution.CONCENTRIC_RINGS);
assertFalse(IrisStructureLocator.hasLocatablePlacement(randomSpread, "test:density")); assertFalse(IrisStructureLocator.hasLocatablePlacement(randomSpread, "test:density"));
assertFalse(IrisStructureLocator.hasLocatablePlacement(concentricRings, "test:density")); assertFalse(IrisStructureLocator.hasLocatablePlacement(concentricRings, "test:density"));
@@ -116,21 +123,21 @@ public class IrisStructureLocatorContractTest {
structure.setVanillaSource("source:city"); structure.setVanillaSource("source:city");
ModuleResourceFixture.of(data).resource(StructureResources.STRUCTURES, "test:city_definition", structure); ModuleResourceFixture.of(data).resource(StructureResources.STRUCTURES, "test:city_definition", structure);
IrisStructurePlacement editable = new IrisStructurePlacement(); StructurePlacement editable = new StructurePlacement();
editable.getStructures().add("test:city_definition"); withAdded(editable, "structures", "test:city_definition");
IrisStructurePlacement nativePlacement = new IrisStructurePlacement(); StructurePlacement nativePlacement = new StructurePlacement();
nativePlacement.getNativeStructures().add(new IrisNativeStructure() withAdded(nativePlacement, "nativeStructures", nativeSource("source:native_city"));
.setStructure("source:native_city"));
IrisDimension dimension = mock(IrisDimension.class); IrisDimension dimension = mock(IrisDimension.class);
KList<IrisStructurePlacement> placements = new KList<>(); KList<StructurePlacement> placements = new KList<>();
placements.add(editable); placements.add(editable);
placements.add(nativePlacement); placements.add(nativePlacement);
Engine engine = mock(Engine.class); Engine engine = mock(Engine.class);
when(engine.getGeneration()).thenReturn(new EngineGeneration(engine));
when(engine.getData()).thenReturn(data); when(engine.getData()).thenReturn(data);
when(engine.getDimension()).thenReturn(dimension); when(engine.getDimension()).thenReturn(dimension);
when(engine.getMinHeight()).thenReturn(-64); when(engine.getMinHeight()).thenReturn(-64);
when(engine.getHeight()).thenReturn(384); when(engine.getHeight()).thenReturn(384);
when(dimension.getStructures()).thenReturn(placements); when(dimension.getModuleSettings()).thenReturn(declaring(placements));
when(dimension.getAllRegions(engine)).thenReturn(new KList<>()); when(dimension.getAllRegions(engine)).thenReturn(new KList<>());
when(dimension.getReachableBiomes(engine)).thenReturn(new KList<>()); when(dimension.getReachableBiomes(engine)).thenReturn(new KList<>());
@@ -154,16 +161,15 @@ public class IrisStructureLocatorContractTest {
public void nativeStructureReplacementSuppressesOnlyItsRegisteredSource() { public void nativeStructureReplacementSuppressesOnlyItsRegisteredSource() {
IrisData data = mock(IrisData.class); IrisData data = mock(IrisData.class);
Engine engine = mock(Engine.class); Engine engine = mock(Engine.class);
when(engine.getGeneration()).thenReturn(new EngineGeneration(engine));
IrisDimension dimension = mock(IrisDimension.class); IrisDimension dimension = mock(IrisDimension.class);
IrisStructurePlacement placement = new IrisStructurePlacement() StructurePlacement placement = placement("nativeSuppression", NativeStructureSuppression.REPLACE_SOURCE);
.setNativeSuppression(NativeStructureSuppression.REPLACE_SOURCE); withAdded(placement, "nativeStructures", nativeSource("minecraft:ancient_city"));
placement.getNativeStructures().add(new IrisNativeStructure() KList<StructurePlacement> placements = new KList<>();
.setStructure("minecraft:ancient_city"));
KList<IrisStructurePlacement> placements = new KList<>();
placements.add(placement); placements.add(placement);
when(engine.getData()).thenReturn(data); when(engine.getData()).thenReturn(data);
when(engine.getDimension()).thenReturn(dimension); when(engine.getDimension()).thenReturn(dimension);
when(dimension.getStructures()).thenReturn(placements); when(dimension.getModuleSettings()).thenReturn(declaring(placements));
when(dimension.getAllRegions(engine)).thenReturn(new KList<>()); when(dimension.getAllRegions(engine)).thenReturn(new KList<>());
when(dimension.getReachableBiomes(engine)).thenReturn(new KList<>()); when(dimension.getReachableBiomes(engine)).thenReturn(new KList<>());
@@ -175,6 +181,7 @@ public class IrisStructureLocatorContractTest {
@Test @Test
public void suppressesVanillaIsFalseForNullOrEmptyKey() { public void suppressesVanillaIsFalseForNullOrEmptyKey() {
Engine engine = mock(Engine.class); Engine engine = mock(Engine.class);
when(engine.getGeneration()).thenReturn(new EngineGeneration(engine));
assertFalse(IrisStructureLocator.suppressesVanilla(engine, null)); assertFalse(IrisStructureLocator.suppressesVanilla(engine, null));
assertFalse(IrisStructureLocator.suppressesVanilla(engine, "")); assertFalse(IrisStructureLocator.suppressesVanilla(engine, ""));
} }
@@ -188,23 +195,25 @@ public class IrisStructureLocatorContractTest {
ModuleResourceFixture.of(data).resource(StructureResources.STRUCTURES, "test:city", structure); ModuleResourceFixture.of(data).resource(StructureResources.STRUCTURES, "test:city", structure);
registerSinglePieceGraph(data, structure, "test:city"); registerSinglePieceGraph(data, structure, "test:city");
IrisStructurePlacement placement = new IrisStructurePlacement(); StructurePlacement placement = new StructurePlacement();
placement.getStructures().add("test:city"); withAdded(placement, "structures", "test:city");
IrisDimension dimension = mock(IrisDimension.class); IrisDimension dimension = mock(IrisDimension.class);
KList<IrisStructurePlacement> placements = new KList<>(); KList<StructurePlacement> placements = new KList<>();
placements.add(placement); placements.add(placement);
when(dimension.getStructures()).thenReturn(placements); when(dimension.getModuleSettings()).thenReturn(declaring(placements));
when(dimension.getAllRegions(any())).thenReturn(new KList<>()); when(dimension.getAllRegions(any())).thenReturn(new KList<>());
when(dimension.getReachableBiomes(any())).thenReturn(new KList<>()); when(dimension.getReachableBiomes(any())).thenReturn(new KList<>());
Engine engine = mock(Engine.class); Engine engine = mock(Engine.class);
when(engine.getGeneration()).thenReturn(new EngineGeneration(engine));
when(engine.getData()).thenReturn(data); when(engine.getData()).thenReturn(data);
when(engine.getDimension()).thenReturn(dimension); when(engine.getDimension()).thenReturn(dimension);
assertTrue(IrisStructureLocator.isPlaced(engine, "minecraft:ancient_city")); assertTrue(IrisStructureLocator.isPlaced(engine, "minecraft:ancient_city"));
assertFalse(IrisStructureLocator.suppressesVanilla(engine, "minecraft:ancient_city")); assertFalse(IrisStructureLocator.suppressesVanilla(engine, "minecraft:ancient_city"));
placement.setNativeSuppression(NativeStructureSuppression.REPLACE_SOURCE); TestSettings.with(placement, "nativeSuppression", NativeStructureSuppression.REPLACE_SOURCE);
IrisStructureLocator.invalidate(engine); when(engine.getGeneration()).thenReturn(new EngineGeneration(engine));
assertTrue(IrisStructureLocator.suppressesVanilla(engine, "minecraft:ancient_city")); assertTrue(IrisStructureLocator.suppressesVanilla(engine, "minecraft:ancient_city"));
} }
@@ -217,17 +226,19 @@ public class IrisStructureLocatorContractTest {
ModuleResourceFixture.of(data).resource(StructureResources.STRUCTURES, "test:city", structure); ModuleResourceFixture.of(data).resource(StructureResources.STRUCTURES, "test:city", structure);
registerSinglePieceGraph(data, structure, "test:city"); registerSinglePieceGraph(data, structure, "test:city");
IrisStructurePlacement placement = new IrisStructurePlacement(); StructurePlacement placement = new StructurePlacement();
placement.getStructures().add("test:city"); withAdded(placement, "structures", "test:city");
placement.setNativeSuppression(NativeStructureSuppression.REPLACE_SOURCE); TestSettings.with(placement, "nativeSuppression", NativeStructureSuppression.REPLACE_SOURCE);
IrisRegion region = mock(IrisRegion.class); IrisRegion region = mock(IrisRegion.class);
when(region.getStructures()).thenReturn(new KList<IrisStructurePlacement>().qadd(placement)); when(region.getModuleSettings()).thenReturn(declaring(new KList<StructurePlacement>().qadd(placement)));
IrisDimension dimension = mock(IrisDimension.class); IrisDimension dimension = mock(IrisDimension.class);
when(dimension.getStructures()).thenReturn(new KList<>()); when(dimension.getModuleSettings()).thenReturn(declaring(new KList<>()));
when(dimension.getAllRegions(any())).thenReturn(new KList<IrisRegion>().qadd(region)); when(dimension.getAllRegions(any())).thenReturn(new KList<IrisRegion>().qadd(region));
when(dimension.getReachableBiomes(any())).thenReturn(new KList<>()); when(dimension.getReachableBiomes(any())).thenReturn(new KList<>());
Engine engine = mock(Engine.class); Engine engine = mock(Engine.class);
when(engine.getGeneration()).thenReturn(new EngineGeneration(engine));
when(engine.getData()).thenReturn(data); when(engine.getData()).thenReturn(data);
when(engine.getDimension()).thenReturn(dimension); when(engine.getDimension()).thenReturn(dimension);
@@ -282,14 +293,14 @@ public class IrisStructureLocatorContractTest {
when(data.load(IrisObject.class, "test:target-object", false)).thenReturn(targetObject); when(data.load(IrisObject.class, "test:target-object", false)).thenReturn(targetObject);
assertFalse(StructureGraphCatalog.compile(data, structure, ModuleLogs.discarding()).isAssemblyViable()); assertFalse(StructureGraphCatalog.compile(data, structure, ModuleLogs.discarding()).isAssemblyViable());
IrisStructurePlacement placement = new IrisStructurePlacement() StructurePlacement placement = placement("nativeSuppression", NativeStructureSuppression.REPLACE_SOURCE);
.setNativeSuppression(NativeStructureSuppression.REPLACE_SOURCE); withAdded(placement, "structures", "test:city");
placement.getStructures().add("test:city");
IrisDimension dimension = mock(IrisDimension.class); IrisDimension dimension = mock(IrisDimension.class);
when(dimension.getStructures()).thenReturn(new KList<IrisStructurePlacement>().qadd(placement)); when(dimension.getModuleSettings()).thenReturn(declaring(new KList<StructurePlacement>().qadd(placement)));
when(dimension.getAllRegions(any())).thenReturn(new KList<>()); when(dimension.getAllRegions(any())).thenReturn(new KList<>());
when(dimension.getReachableBiomes(any())).thenReturn(new KList<>()); when(dimension.getReachableBiomes(any())).thenReturn(new KList<>());
Engine engine = mock(Engine.class); Engine engine = mock(Engine.class);
when(engine.getGeneration()).thenReturn(new EngineGeneration(engine));
when(engine.getData()).thenReturn(data); when(engine.getData()).thenReturn(data);
when(engine.getDimension()).thenReturn(dimension); when(engine.getDimension()).thenReturn(dimension);
@@ -305,14 +316,14 @@ public class IrisStructureLocatorContractTest {
structure.setLoadKey("test:city"); structure.setLoadKey("test:city");
ModuleResourceFixture.of(data).resource(StructureResources.STRUCTURES, "test:city", structure); ModuleResourceFixture.of(data).resource(StructureResources.STRUCTURES, "test:city", structure);
registerSinglePieceGraph(data, structure, "test:city"); registerSinglePieceGraph(data, structure, "test:city");
IrisStructurePlacement placement = new IrisStructurePlacement() StructurePlacement placement = placement("nativeSuppression", NativeStructureSuppression.REPLACE_SOURCE);
.setNativeSuppression(NativeStructureSuppression.REPLACE_SOURCE); withAdded(placement, "structures", "test:city");
placement.getStructures().add("test:city");
IrisDimension dimension = mock(IrisDimension.class); IrisDimension dimension = mock(IrisDimension.class);
when(dimension.getStructures()).thenReturn(new KList<IrisStructurePlacement>().qadd(placement)); when(dimension.getModuleSettings()).thenReturn(declaring(new KList<StructurePlacement>().qadd(placement)));
when(dimension.getAllRegions(any())).thenReturn(new KList<>()); when(dimension.getAllRegions(any())).thenReturn(new KList<>());
when(dimension.getReachableBiomes(any())).thenReturn(new KList<>()); when(dimension.getReachableBiomes(any())).thenReturn(new KList<>());
Engine engine = mock(Engine.class); Engine engine = mock(Engine.class);
when(engine.getGeneration()).thenReturn(new EngineGeneration(engine));
when(engine.getData()).thenReturn(data); when(engine.getData()).thenReturn(data);
when(engine.getDimension()).thenReturn(dimension); when(engine.getDimension()).thenReturn(dimension);
@@ -325,13 +336,14 @@ public class IrisStructureLocatorContractTest {
public void missingNonReplacementStructureFailsInsteadOfBeingSkipped() { public void missingNonReplacementStructureFailsInsteadOfBeingSkipped() {
IrisData data = mock(IrisData.class); IrisData data = mock(IrisData.class);
ModuleResourceFixture.serve(data); ModuleResourceFixture.serve(data);
IrisStructurePlacement placement = new IrisStructurePlacement(); StructurePlacement placement = new StructurePlacement();
placement.getStructures().add("test:missing"); withAdded(placement, "structures", "test:missing");
IrisDimension dimension = mock(IrisDimension.class); IrisDimension dimension = mock(IrisDimension.class);
when(dimension.getStructures()).thenReturn(new KList<IrisStructurePlacement>().qadd(placement)); when(dimension.getModuleSettings()).thenReturn(declaring(new KList<StructurePlacement>().qadd(placement)));
when(dimension.getAllRegions(any())).thenReturn(new KList<>()); when(dimension.getAllRegions(any())).thenReturn(new KList<>());
when(dimension.getReachableBiomes(any())).thenReturn(new KList<>()); when(dimension.getReachableBiomes(any())).thenReturn(new KList<>());
Engine engine = mock(Engine.class); Engine engine = mock(Engine.class);
when(engine.getGeneration()).thenReturn(new EngineGeneration(engine));
when(engine.getData()).thenReturn(data); when(engine.getData()).thenReturn(data);
when(engine.getDimension()).thenReturn(dimension); when(engine.getDimension()).thenReturn(dimension);
@@ -343,15 +355,14 @@ public class IrisStructureLocatorContractTest {
@Test @Test
public void placementResolutionRejectsAnUnboundEngine() { public void placementResolutionRejectsAnUnboundEngine() {
assertReplacementFailure( assertReplacementFailure(
() -> IrisStructureLocator.resolvePlacement(null, new IrisStructurePlacement(), 0, 0), () -> IrisStructureLocator.resolvePlacement(null, new StructurePlacement(), 0, 0),
"fully bound engine"); "fully bound engine");
} }
@Test @Test
public void replacementOutputFailureIncludesStructureAndChunkContext() { public void replacementOutputFailureIncludesStructureAndChunkContext() {
IrisStructurePlacement placement = new IrisStructurePlacement() StructurePlacement placement = placement("nativeSuppression", NativeStructureSuppression.REPLACE_SOURCE);
.setNativeSuppression(NativeStructureSuppression.REPLACE_SOURCE); withAdded(placement, "structures", "test:city");
placement.getStructures().add("test:city");
assertReplacementFailure( assertReplacementFailure(
() -> IrisStructureLocator.requirePlacementOutput( () -> IrisStructureLocator.requirePlacementOutput(
@@ -361,8 +372,8 @@ public class IrisStructureLocatorContractTest {
@Test @Test
public void nonReplacementOutputAbsenceRemainsSkippable() { public void nonReplacementOutputAbsenceRemainsSkippable() {
IrisStructurePlacement placement = new IrisStructurePlacement(); StructurePlacement placement = new StructurePlacement();
placement.getStructures().add("test:city"); withAdded(placement, "structures", "test:city");
assertFalse(IrisStructureLocator.requirePlacementOutput( assertFalse(IrisStructureLocator.requirePlacementOutput(
placement, "test:city", 12, -7, false, "runtime assembly produced no pieces")); placement, "test:city", 12, -7, false, "runtime assembly produced no pieces"));
@@ -384,6 +395,7 @@ public class IrisStructureLocatorContractTest {
@Test @Test
public void locateReturnsNotFoundForNullOrEmptyKey() { public void locateReturnsNotFoundForNullOrEmptyKey() {
Engine engine = mock(Engine.class); Engine engine = mock(Engine.class);
when(engine.getGeneration()).thenReturn(new EngineGeneration(engine));
assertEquals(IrisStructureLocator.LocateStatus.NOT_FOUND, assertEquals(IrisStructureLocator.LocateStatus.NOT_FOUND,
IrisStructureLocator.locate(engine, null, 0, 0, 100).status()); IrisStructureLocator.locate(engine, null, 0, 0, 100).status());
assertEquals(IrisStructureLocator.LocateStatus.NOT_FOUND, assertEquals(IrisStructureLocator.LocateStatus.NOT_FOUND,
@@ -453,7 +465,7 @@ public class IrisStructureLocatorContractTest {
Engine engine = densityEngine(1.0, false, -64, 384, -2032, 2032); Engine engine = densityEngine(1.0, false, -64, 384, -2032, 2032);
when(engine.getHeight(anyInt(), anyInt(), eq(true))).thenReturn(128); when(engine.getHeight(anyInt(), anyInt(), eq(true))).thenReturn(128);
when(engine.getDimension().getFluidHeight()).thenReturn(63); when(engine.getDimension().getFluidHeight()).thenReturn(63);
IrisStructurePlacement placement = engine.getDimension().getStructures().get(0); StructurePlacement placement = StructurePlacementScope.placementsOf(engine.getDimension()).get(0);
NearestScenario scenario = nearestEqualChunkDistanceScenario(engine, placement); NearestScenario scenario = nearestEqualChunkDistanceScenario(engine, placement);
assertNotNull(scenario); assertNotNull(scenario);
@@ -478,40 +490,36 @@ public class IrisStructureLocatorContractTest {
@Test @Test
public void searchableDensityRequiresPositiveProbabilityAndWorldHeightOverlap() { public void searchableDensityRequiresPositiveProbabilityAndWorldHeightOverlap() {
Engine engine = mock(Engine.class); Engine engine = mock(Engine.class);
when(engine.getGeneration()).thenReturn(new EngineGeneration(engine));
when(engine.getMinHeight()).thenReturn(-64); when(engine.getMinHeight()).thenReturn(-64);
when(engine.getHeight()).thenReturn(384); when(engine.getHeight()).thenReturn(384);
IrisStructurePlacement placement = new IrisStructurePlacement(); StructurePlacement placement = new StructurePlacement();
placement.setDistribution(StructureDistribution.DENSITY); TestSettings.with(placement, "distribution", StructureDistribution.DENSITY);
placement.setMinHeight(-32); TestSettings.with(placement, "minHeight", -32);
placement.setMaxHeight(128); TestSettings.with(placement, "maxHeight", 128);
placement.setDensity(Double.NaN); TestSettings.with(placement, "density", Double.NaN);
assertFalse(IrisStructureLocator.isSearchableDensityPlacement(engine, placement)); assertFalse(IrisStructureLocator.isSearchableDensityPlacement(engine, placement));
placement.setDensity(0.0); TestSettings.with(placement, "density", 0.0);
assertFalse(IrisStructureLocator.isSearchableDensityPlacement(engine, placement)); assertFalse(IrisStructureLocator.isSearchableDensityPlacement(engine, placement));
placement.setDensity(0.01); TestSettings.with(placement, "density", 0.01);
assertTrue(IrisStructureLocator.isSearchableDensityPlacement(engine, placement)); assertTrue(IrisStructureLocator.isSearchableDensityPlacement(engine, placement));
placement.setMinHeight(400); TestSettings.with(placement, "minHeight", 400);
placement.setMaxHeight(500); TestSettings.with(placement, "maxHeight", 500);
assertFalse(IrisStructureLocator.isSearchableDensityPlacement(engine, placement)); assertFalse(IrisStructureLocator.isSearchableDensityPlacement(engine, placement));
} }
@Test @Test
public void invalidateIsNullSafe() { public void placementIndexIsKeptPerWorld() {
IrisStructureLocator.invalidate(null);
}
@Test
public void placementIndexIsScopedAndInvalidatedPerEngine() {
IrisData sharedData = mock(IrisData.class); IrisData sharedData = mock(IrisData.class);
Engine firstEngine = emptyEngine(sharedData); Engine firstEngine = emptyEngine(sharedData);
Engine secondEngine = emptyEngine(sharedData); Engine secondEngine = emptyEngine(sharedData);
Set<String> firstIndex = IrisStructureLocator.placedKeys(firstEngine); Set<String> firstIndex = IrisStructureLocator.placedKeys(firstEngine);
Set<String> secondIndex = IrisStructureLocator.placedKeys(secondEngine); assertSame(firstIndex, IrisStructureLocator.placedKeys(firstEngine));
assertNotSame(firstIndex, secondIndex); assertNotSame(firstIndex, IrisStructureLocator.placedKeys(secondEngine));
IrisStructureLocator.invalidate(firstEngine); when(firstEngine.getGeneration()).thenReturn(new EngineGeneration(firstEngine));
assertNotSame(firstIndex, IrisStructureLocator.placedKeys(firstEngine)); assertNotSame("a new world builds its own index", firstIndex, IrisStructureLocator.placedKeys(firstEngine));
} }
@Test @Test
@@ -536,9 +544,9 @@ public class IrisStructureLocatorContractTest {
@Test @Test
public void selectedStructureKeyDoesNotMatchUnselectedPlacementMember() { public void selectedStructureKeyDoesNotMatchUnselectedPlacementMember() {
IrisStructurePlacement placement = new IrisStructurePlacement(); StructurePlacement placement = new StructurePlacement();
placement.getStructures().add("test:first"); withAdded(placement, "structures", "test:first");
placement.getStructures().add("test:second"); withAdded(placement, "structures", "test:second");
RNG selectsLast = new RNG(1L) { RNG selectsLast = new RNG(1L) {
@Override @Override
public int nextInt(int bound) { public int nextInt(int bound) {
@@ -560,10 +568,10 @@ public class IrisStructureLocatorContractTest {
@Test @Test
public void undergroundAssemblyIsShiftedToFitOrRejectedWhole() { public void undergroundAssemblyIsShiftedToFitOrRejectedWhole() {
IrisStructurePlacement placement = new IrisStructurePlacement(); StructurePlacement placement = new StructurePlacement();
placement.setUnderground(true); TestSettings.with(placement, "underground", true);
placement.setMinHeight(-10); TestSettings.with(placement, "minHeight", -10);
placement.setMaxHeight(10); TestSettings.with(placement, "maxHeight", 10);
KList<PlacedStructurePiece> movable = new KList<>(); KList<PlacedStructurePiece> movable = new KList<>();
movable.add(piece(-4, -10, -4, 4, 5, 4)); movable.add(piece(-4, -10, -4, 4, 5, 4));
@@ -573,7 +581,7 @@ public class IrisStructureLocatorContractTest {
tooTall.add(piece(-4, -100, -4, 4, 400, 4)); tooTall.add(piece(-4, -100, -4, 4, 400, 4));
assertNull(IrisStructureLocator.resolveVerticalShift(tooTall, placement, 0, 0, 319)); assertNull(IrisStructureLocator.resolveVerticalShift(tooTall, placement, 0, 0, 319));
placement.setUnderground(false); TestSettings.with(placement, "underground", false);
KList<PlacedStructurePiece> clippedSurface = new KList<>(); KList<PlacedStructurePiece> clippedSurface = new KList<>();
clippedSurface.add(piece(-4, 300, -4, 4, 330, 4)); clippedSurface.add(piece(-4, 300, -4, 4, 330, 4));
assertNull(IrisStructureLocator.resolveVerticalShift(clippedSurface, placement, 300, -64, 319)); assertNull(IrisStructureLocator.resolveVerticalShift(clippedSurface, placement, 300, -64, 319));
@@ -583,19 +591,19 @@ public class IrisStructureLocatorContractTest {
public void caveAssemblyBoundsAlignToTheRequestedAnchorFace() { public void caveAssemblyBoundsAlignToTheRequestedAnchorFace() {
KList<PlacedStructurePiece> pieces = new KList<>(); KList<PlacedStructurePiece> pieces = new KList<>();
pieces.add(piece(-2, 10, -2, 2, 14, 2)); pieces.add(piece(-2, 10, -2, 2, 14, 2));
IrisStructurePlacement placement = new IrisStructurePlacement(); StructurePlacement placement = new StructurePlacement();
placement.setAnchor(IrisStructureAnchorMode.CAVE_FLOOR); TestSettings.with(placement, "anchor", StructureAnchorMode.CAVE_FLOOR);
KList<PlacedStructurePiece> floor = IrisStructureLocator.alignCavePieces(pieces, placement, 40); KList<PlacedStructurePiece> floor = IrisStructureLocator.alignCavePieces(pieces, placement, 40);
assertEquals(40, floor.getFirst().getMinY()); assertEquals(40, floor.getFirst().getMinY());
assertEquals(44, floor.getFirst().getMaxY()); assertEquals(44, floor.getFirst().getMaxY());
placement.setAnchor(IrisStructureAnchorMode.CAVE_CEILING); TestSettings.with(placement, "anchor", StructureAnchorMode.CAVE_CEILING);
KList<PlacedStructurePiece> ceiling = IrisStructureLocator.alignCavePieces(pieces, placement, 40); KList<PlacedStructurePiece> ceiling = IrisStructureLocator.alignCavePieces(pieces, placement, 40);
assertEquals(36, ceiling.getFirst().getMinY()); assertEquals(36, ceiling.getFirst().getMinY());
assertEquals(40, ceiling.getFirst().getMaxY()); assertEquals(40, ceiling.getFirst().getMaxY());
placement.setAnchor(IrisStructureAnchorMode.CAVE_CENTER); TestSettings.with(placement, "anchor", StructureAnchorMode.CAVE_CENTER);
KList<PlacedStructurePiece> center = IrisStructureLocator.alignCavePieces(pieces, placement, 40); KList<PlacedStructurePiece> center = IrisStructureLocator.alignCavePieces(pieces, placement, 40);
assertEquals(38, center.getFirst().getMinY()); assertEquals(38, center.getFirst().getMinY());
assertEquals(42, center.getFirst().getMaxY()); assertEquals(42, center.getFirst().getMaxY());
@@ -604,42 +612,39 @@ public class IrisStructureLocatorContractTest {
@Test @Test
public void caveSearchabilityReservesVerticalBoundaryCells() { public void caveSearchabilityReservesVerticalBoundaryCells() {
Engine engine = mock(Engine.class); Engine engine = mock(Engine.class);
when(engine.getGeneration()).thenReturn(new EngineGeneration(engine));
when(engine.getMinHeight()).thenReturn(-64); when(engine.getMinHeight()).thenReturn(-64);
when(engine.getHeight()).thenReturn(384); when(engine.getHeight()).thenReturn(384);
IrisStructurePlacement placement = new IrisStructurePlacement() StructurePlacement placement = placement("distribution", StructureDistribution.DENSITY, "density", 1D, "anchor", StructureAnchorMode.CAVE_FLOOR, "minHeight", 319, "maxHeight", 319);
.setDistribution(StructureDistribution.DENSITY)
.setDensity(1D)
.setAnchor(IrisStructureAnchorMode.CAVE_FLOOR)
.setMinHeight(319)
.setMaxHeight(319);
assertFalse(IrisStructureLocator.isSearchableDensityPlacement(engine, placement)); assertFalse(IrisStructureLocator.isSearchableDensityPlacement(engine, placement));
placement.setMinHeight(318).setMaxHeight(318); TestSettings.with(placement, "minHeight", 318, "maxHeight", 318);
assertTrue(IrisStructureLocator.isSearchableDensityPlacement(engine, placement)); assertTrue(IrisStructureLocator.isSearchableDensityPlacement(engine, placement));
when(engine.getHeight()).thenReturn(2); when(engine.getHeight()).thenReturn(2);
placement.setMinHeight(-2032).setMaxHeight(2032); TestSettings.with(placement, "minHeight", -2032, "maxHeight", 2032);
assertFalse(IrisStructureLocator.isSearchableDensityPlacement(engine, placement)); assertFalse(IrisStructureLocator.isSearchableDensityPlacement(engine, placement));
} }
@Test @Test
public void undergroundAssemblyIsShiftedBelowEveryTerrainColumn() { public void undergroundAssemblyIsShiftedBelowEveryTerrainColumn() {
Engine engine = mock(Engine.class); Engine engine = mock(Engine.class);
when(engine.getGeneration()).thenReturn(new EngineGeneration(engine));
when(engine.getMinHeight()).thenReturn(-64); when(engine.getMinHeight()).thenReturn(-64);
when(engine.getHeight(anyInt(), anyInt(), eq(true))) when(engine.getHeight(anyInt(), anyInt(), eq(true)))
.thenAnswer(invocation -> invocation.<Integer>getArgument(0) == 1 ? 140 : 164); .thenAnswer(invocation -> invocation.<Integer>getArgument(0) == 1 ? 140 : 164);
IrisStructurePlacement placement = new IrisStructurePlacement(); StructurePlacement placement = new StructurePlacement();
placement.setUnderground(true); TestSettings.with(placement, "underground", true);
placement.setMinHeight(-64); TestSettings.with(placement, "minHeight", -64);
placement.setMaxHeight(100); TestSettings.with(placement, "maxHeight", 100);
KList<PlacedStructurePiece> pieces = new KList<>(); KList<PlacedStructurePiece> pieces = new KList<>();
pieces.add(piece(0, 60, 0, 1, 80, 0)); pieces.add(piece(0, 60, 0, 1, 80, 0));
assertEquals(Integer.valueOf(-5), IrisStructureLocator.resolveUndergroundBurialShift( assertEquals(Integer.valueOf(-5), IrisStructureLocator.resolveUndergroundBurialShift(
engine, pieces, placement, 60, -63, 319)); engine, pieces, placement, 60, -63, 319));
placement.setMinHeight(60); TestSettings.with(placement, "minHeight", 60);
placement.setMaxHeight(60); TestSettings.with(placement, "maxHeight", 60);
assertNull(IrisStructureLocator.resolveUndergroundBurialShift( assertNull(IrisStructureLocator.resolveUndergroundBurialShift(
engine, pieces, placement, 60, -63, 319)); engine, pieces, placement, 60, -63, 319));
} }
@@ -647,28 +652,29 @@ public class IrisStructureLocatorContractTest {
@Test @Test
public void undergroundBurialIncludesForceCarveCeiling() { public void undergroundBurialIncludesForceCarveCeiling() {
Engine engine = mock(Engine.class); Engine engine = mock(Engine.class);
when(engine.getGeneration()).thenReturn(new EngineGeneration(engine));
when(engine.getMinHeight()).thenReturn(-64); when(engine.getMinHeight()).thenReturn(-64);
when(engine.getHeight(anyInt(), anyInt(), eq(true))).thenReturn(164); when(engine.getHeight(anyInt(), anyInt(), eq(true))).thenReturn(164);
IrisStructurePlacement placement = new IrisStructurePlacement(); StructurePlacement placement = new StructurePlacement();
placement.setUnderground(true); TestSettings.with(placement, "underground", true);
placement.setMinHeight(-64); TestSettings.with(placement, "minHeight", -64);
placement.setMaxHeight(100); TestSettings.with(placement, "maxHeight", 100);
placement.setTerrain(forceCarve("\"horizontalPadding\":2,\"ceilingPadding\":20,\"shape\":\"ERODED\"")); TestSettings.with(placement, "terrain", forceCarve("\"horizontalPadding\":2,\"ceilingPadding\":20,\"shape\":\"ERODED\""));
KList<PlacedStructurePiece> pieces = new KList<>(); KList<PlacedStructurePiece> pieces = new KList<>();
pieces.add(piece(0, 60, 0, 1, 80, 1)); pieces.add(piece(0, 60, 0, 1, 80, 1));
assertEquals(Integer.valueOf(-14), IrisStructureLocator.resolveUndergroundBurialShift( assertEquals(Integer.valueOf(-14), IrisStructureLocator.resolveUndergroundBurialShift(
engine, pieces, placement, 60, -63, 319)); engine, pieces, placement, 60, -63, 319));
placement.setTerrain(forceCarve("\"horizontalPadding\":2,\"ceilingPadding\":20,\"shape\":\"ERODED\",\"erosionStrength\":0")); TestSettings.with(placement, "terrain", forceCarve("\"horizontalPadding\":2,\"ceilingPadding\":20,\"shape\":\"ERODED\",\"erosionStrength\":0"));
assertEquals(Integer.valueOf(-1), IrisStructureLocator.resolveUndergroundBurialShift( assertEquals(Integer.valueOf(-1), IrisStructureLocator.resolveUndergroundBurialShift(
engine, pieces, placement, 60, -63, 319)); engine, pieces, placement, 60, -63, 319));
placement.setTerrain(forceCarve("\"horizontalPadding\":2,\"ceilingPadding\":20,\"shape\":\"ROUNDED\",\"erosionStrength\":0")); TestSettings.with(placement, "terrain", forceCarve("\"horizontalPadding\":2,\"ceilingPadding\":20,\"shape\":\"ROUNDED\",\"erosionStrength\":0"));
assertEquals(Integer.valueOf(-1), IrisStructureLocator.resolveUndergroundBurialShift( assertEquals(Integer.valueOf(-1), IrisStructureLocator.resolveUndergroundBurialShift(
engine, pieces, placement, 60, -63, 319)); engine, pieces, placement, 60, -63, 319));
placement.setTerrain(forceCarve("\"horizontalPadding\":2,\"ceilingPadding\":0,\"shape\":\"ROUNDED\",\"erosionStrength\":0")); TestSettings.with(placement, "terrain", forceCarve("\"horizontalPadding\":2,\"ceilingPadding\":0,\"shape\":\"ROUNDED\",\"erosionStrength\":0"));
assertEquals(Integer.valueOf(0), IrisStructureLocator.resolveUndergroundBurialShift( assertEquals(Integer.valueOf(0), IrisStructureLocator.resolveUndergroundBurialShift(
engine, pieces, placement, 60, -63, 319)); engine, pieces, placement, 60, -63, 319));
} }
@@ -676,13 +682,10 @@ public class IrisStructureLocatorContractTest {
@Test @Test
public void zeroForceCarvePaddingDoesNotExpandTheBurialEnvelope() { public void zeroForceCarvePaddingDoesNotExpandTheBurialEnvelope() {
Engine engine = mock(Engine.class); Engine engine = mock(Engine.class);
when(engine.getGeneration()).thenReturn(new EngineGeneration(engine));
when(engine.getMinHeight()).thenReturn(-64); when(engine.getMinHeight()).thenReturn(-64);
when(engine.getHeight(anyInt(), anyInt(), eq(true))).thenReturn(164); when(engine.getHeight(anyInt(), anyInt(), eq(true))).thenReturn(164);
IrisStructurePlacement placement = new IrisStructurePlacement() StructurePlacement placement = placement("underground", true, "minHeight", -64, "maxHeight", 100, "terrain", forceCarve("\"shape\":\"ROUNDED\",\"horizontalPadding\":0,\"ceilingPadding\":0"));
.setUnderground(true)
.setMinHeight(-64)
.setMaxHeight(100)
.setTerrain(forceCarve("\"shape\":\"ROUNDED\",\"horizontalPadding\":0,\"ceilingPadding\":0"));
KList<PlacedStructurePiece> pieces = new KList<>(); KList<PlacedStructurePiece> pieces = new KList<>();
pieces.add(piece(4, 60, 7, 4, 80, 7)); pieces.add(piece(4, 60, 7, 4, 80, 7));
@@ -693,7 +696,7 @@ public class IrisStructureLocatorContractTest {
@Test @Test
public void exactYOnlyCoversPlacementPathsWithResolvedAbsoluteAnchors() { public void exactYOnlyCoversPlacementPathsWithResolvedAbsoluteAnchors() {
IrisStructurePlacement placement = new IrisStructurePlacement(); StructurePlacement placement = new StructurePlacement();
IrisStructure structure = new IrisStructure(); IrisStructure structure = new IrisStructure();
structure.setPlaceMode(ObjectPlaceMode.CENTER_HEIGHT); structure.setPlaceMode(ObjectPlaceMode.CENTER_HEIGHT);
KList<PlacedStructurePiece> onePiece = new KList<>(); KList<PlacedStructurePiece> onePiece = new KList<>();
@@ -704,10 +707,10 @@ public class IrisStructureLocatorContractTest {
assertTrue(IrisStructureLocator.hasExactY(placement, structure, onePiece)); assertTrue(IrisStructureLocator.hasExactY(placement, structure, onePiece));
structure.setPlaceMode(ObjectPlaceMode.CENTER_HEIGHT); structure.setPlaceMode(ObjectPlaceMode.CENTER_HEIGHT);
placement.setUnderground(true); TestSettings.with(placement, "underground", true);
assertTrue(IrisStructureLocator.hasExactY(placement, structure, onePiece)); assertTrue(IrisStructureLocator.hasExactY(placement, structure, onePiece));
placement.setUnderground(false); TestSettings.with(placement, "underground", false);
KList<PlacedStructurePiece> multiplePieces = new KList<>(onePiece); KList<PlacedStructurePiece> multiplePieces = new KList<>(onePiece);
multiplePieces.add(piece(5, 1, -4, 12, 20, 4)); multiplePieces.add(piece(5, 1, -4, 12, 20, 4));
assertTrue(IrisStructureLocator.hasExactY(placement, structure, multiplePieces)); assertTrue(IrisStructureLocator.hasExactY(placement, structure, multiplePieces));
@@ -730,7 +733,7 @@ public class IrisStructureLocatorContractTest {
} }
private NearestScenario nearestEqualChunkDistanceScenario( private NearestScenario nearestEqualChunkDistanceScenario(
Engine engine, IrisStructurePlacement placement) { Engine engine, StructurePlacement placement) {
int[][] chunks = { int[][] chunks = {
{-1, -1}, {-1, 0}, {-1, 1}, {0, -1}, {-1, -1}, {-1, 0}, {-1, 1}, {0, -1},
{0, 1}, {1, -1}, {1, 0}, {1, 1} {0, 1}, {1, -1}, {1, 0}, {1, 1}
@@ -781,10 +784,11 @@ public class IrisStructureLocatorContractTest {
private Engine emptyEngine(IrisData data) { private Engine emptyEngine(IrisData data) {
Engine engine = mock(Engine.class); Engine engine = mock(Engine.class);
when(engine.getGeneration()).thenReturn(new EngineGeneration(engine));
IrisDimension dimension = mock(IrisDimension.class); IrisDimension dimension = mock(IrisDimension.class);
when(engine.getData()).thenReturn(data); when(engine.getData()).thenReturn(data);
when(engine.getDimension()).thenReturn(dimension); when(engine.getDimension()).thenReturn(dimension);
when(dimension.getStructures()).thenReturn(new KList<>()); when(dimension.getModuleSettings()).thenReturn(declaring(new KList<>()));
when(dimension.getAllRegions(engine)).thenReturn(new KList<>()); when(dimension.getAllRegions(engine)).thenReturn(new KList<>());
when(dimension.getReachableBiomes(engine)).thenReturn(new KList<>()); when(dimension.getReachableBiomes(engine)).thenReturn(new KList<>());
return engine; return engine;
@@ -798,24 +802,26 @@ public class IrisStructureLocatorContractTest {
ModuleResourceFixture.of(data).resource(StructureResources.STRUCTURES, "test:density", structure); ModuleResourceFixture.of(data).resource(StructureResources.STRUCTURES, "test:density", structure);
registerSinglePieceGraph(data, structure, "test:density"); registerSinglePieceGraph(data, structure, "test:density");
IrisStructurePlacement placement = new IrisStructurePlacement(); StructurePlacement placement = new StructurePlacement();
placement.getStructures().add("test:density"); withAdded(placement, "structures", "test:density");
placement.setDistribution(StructureDistribution.DENSITY); TestSettings.with(placement, "distribution", StructureDistribution.DENSITY);
placement.setDensity(density); TestSettings.with(placement, "density", density);
placement.setUnderground(underground); TestSettings.with(placement, "underground", underground);
placement.setMinHeight(placementMin); TestSettings.with(placement, "minHeight", placementMin);
placement.setMaxHeight(placementMax); TestSettings.with(placement, "maxHeight", placementMax);
Engine engine = mock(Engine.class); Engine engine = mock(Engine.class);
when(engine.getGeneration()).thenReturn(new EngineGeneration(engine));
IrisDimension dimension = mock(IrisDimension.class); IrisDimension dimension = mock(IrisDimension.class);
KList<IrisStructurePlacement> placements = new KList<>(); KList<StructurePlacement> placements = new KList<>();
placements.add(placement); placements.add(placement);
when(engine.getData()).thenReturn(data); when(engine.getData()).thenReturn(data);
when(engine.getDimension()).thenReturn(dimension); when(engine.getDimension()).thenReturn(dimension);
when(engine.getSeedManager()).thenReturn(new SeedManager(77L)); when(engine.getSeedManager()).thenReturn(new SeedManager(77L));
when(engine.getMinHeight()).thenReturn(worldMin); when(engine.getMinHeight()).thenReturn(worldMin);
when(engine.getHeight()).thenReturn(worldHeight); when(engine.getHeight()).thenReturn(worldHeight);
when(dimension.getStructures()).thenReturn(placements); when(dimension.getModuleSettings()).thenReturn(declaring(placements));
when(dimension.getAllRegions(engine)).thenReturn(new KList<>()); when(dimension.getAllRegions(engine)).thenReturn(new KList<>());
when(dimension.getReachableBiomes(engine)).thenReturn(new KList<>()); when(dimension.getReachableBiomes(engine)).thenReturn(new KList<>());
return engine; return engine;
@@ -2,14 +2,18 @@ package art.arcane.iris.engine.framework;
import art.arcane.iris.core.loader.IrisData; import art.arcane.iris.core.loader.IrisData;
import art.arcane.iris.engine.object.world.dimension.IrisDimension; import art.arcane.iris.engine.object.world.dimension.IrisDimension;
import art.arcane.iris.engine.object.structure.vanilla.IrisNativeStructure; import art.arcane.iris.builtin.structure.NativeStructureSource;
import art.arcane.iris.engine.object.structure.IrisStructurePlacement; import art.arcane.iris.builtin.structure.StructurePlacement;
import art.arcane.iris.engine.object.structure.StructureDistribution; import art.arcane.iris.builtin.structure.StructureDistribution;
import art.arcane.volmlib.util.collection.KList; import art.arcane.volmlib.util.collection.KList;
import org.junit.Test; import org.junit.Test;
import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicBoolean;
import static art.arcane.iris.engine.framework.StructurePlacementFixtures.placement;
import static art.arcane.iris.engine.framework.StructurePlacementFixtures.nativeSource;
import static art.arcane.iris.engine.framework.StructurePlacementFixtures.declaring;
import static art.arcane.iris.engine.framework.StructurePlacementFixtures.withAdded;
import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue; import static org.junit.Assert.assertTrue;
@@ -23,11 +27,11 @@ public class IrisStructurePlacementRingLocatorTest {
@Test @Test
public void zeroVanillaRingSearchesTheOriginPlacementCell() { public void zeroVanillaRingSearchesTheOriginPlacementCell() {
IrisStructurePlacement placement = randomPlacement("origin-cell", 24, 6); StructurePlacement placement = randomPlacement("origin-cell", 24, 6);
Engine engine = engine(placement); Engine engine = engine(placement);
long seed = engine.getSeedManager().getMantle(); long seed = engine.getSeedManager().getMantle();
int[] expected = StructurePlacementGrid.randomSpreadCellChunk( int[] expected = StructurePlacementGrid.randomSpreadCellChunk(
0, 0, placement.getSpacing(), placement.getSeparation(), 0, 0, placement.spacing(), placement.separation(),
StructurePlacementGrid.placementSalt(placement), seed); StructurePlacementGrid.placementSalt(placement), seed);
assertTrue(expected[0] != 0 || expected[1] != 0); assertTrue(expected[0] != 0 || expected[1] != 0);
@@ -45,8 +49,8 @@ public class IrisStructurePlacementRingLocatorTest {
@Test @Test
public void mixedSpacingPlacementsShareTheSameVanillaRingIndex() { public void mixedSpacingPlacementsShareTheSameVanillaRingIndex() {
IrisStructurePlacement small = randomPlacement("small-grid", 8, 2); StructurePlacement small = randomPlacement("small-grid", 8, 2);
IrisStructurePlacement large = randomPlacement("large-grid", 40, 10); StructurePlacement large = randomPlacement("large-grid", 40, 10);
Engine engine = engine(small, large); Engine engine = engine(small, large);
long seed = engine.getSeedManager().getMantle(); long seed = engine.getSeedManager().getMantle();
int[] smallRingZero = candidate(small, seed, 0, 0); int[] smallRingZero = candidate(small, seed, 0, 0);
@@ -74,14 +78,9 @@ public class IrisStructurePlacementRingLocatorTest {
@Test @Test
public void concentricPlacementsIgnoreTheRandomSpreadRingRadius() { public void concentricPlacementsIgnoreTheRandomSpreadRingRadius() {
IrisStructurePlacement placement = new IrisStructurePlacement() StructurePlacement placement = placement("placementId", "concentric", "distribution", StructureDistribution.CONCENTRIC_RINGS, "ringCount", 1, "ringDistance", 32, "ringSpread", 1);
.setPlacementId("concentric") withAdded(placement, "nativeStructures",
.setDistribution(StructureDistribution.CONCENTRIC_RINGS) nativeSource(STRUCTURE_KEY));
.setRingCount(1)
.setRingDistance(32)
.setRingSpread(1);
placement.getNativeStructures().add(
new IrisNativeStructure().setStructure(STRUCTURE_KEY));
Engine engine = engine(placement); Engine engine = engine(placement);
IrisStructureLocator.LocateResult result = IrisStructureLocator.LocateResult result =
@@ -96,12 +95,9 @@ public class IrisStructurePlacementRingLocatorTest {
@Test @Test
public void sparseDensityPlacementRingSearchStopsAtTheCandidateBudget() { public void sparseDensityPlacementRingSearchStopsAtTheCandidateBudget() {
IrisStructurePlacement placement = new IrisStructurePlacement() StructurePlacement placement = placement("placementId", "density", "distribution", StructureDistribution.DENSITY, "density", 1.0);
.setPlacementId("density") withAdded(placement, "nativeStructures",
.setDistribution(StructureDistribution.DENSITY) nativeSource(STRUCTURE_KEY));
.setDensity(1.0);
placement.getNativeStructures().add(
new IrisNativeStructure().setStructure(STRUCTURE_KEY));
Engine engine = engine(placement); Engine engine = engine(placement);
IrisStructureLocator.LocateResult result = IrisStructureLocator.LocateResult result =
@@ -114,14 +110,9 @@ public class IrisStructurePlacementRingLocatorTest {
@Test @Test
public void concentricPlacementRingSearchStopsAtTheSharedCandidateBudget() { public void concentricPlacementRingSearchStopsAtTheSharedCandidateBudget() {
IrisStructurePlacement placement = new IrisStructurePlacement() StructurePlacement placement = placement("placementId", "unbounded-concentric-rings", "distribution", StructureDistribution.CONCENTRIC_RINGS, "ringCount", Integer.MAX_VALUE, "ringDistance", 32, "ringSpread", 1);
.setPlacementId("unbounded-concentric-rings") withAdded(placement, "nativeStructures",
.setDistribution(StructureDistribution.CONCENTRIC_RINGS) nativeSource(STRUCTURE_KEY));
.setRingCount(Integer.MAX_VALUE)
.setRingDistance(32)
.setRingSpread(1);
placement.getNativeStructures().add(
new IrisNativeStructure().setStructure(STRUCTURE_KEY));
Engine engine = engine(placement); Engine engine = engine(placement);
IrisStructureLocator.LocateResult result = IrisStructureLocator.locateInPlacementRings( IrisStructureLocator.LocateResult result = IrisStructureLocator.locateInPlacementRings(
@@ -132,14 +123,9 @@ public class IrisStructurePlacementRingLocatorTest {
@Test @Test
public void concentricChunkRadiusSearchStopsAtTheSharedCandidateBudget() { public void concentricChunkRadiusSearchStopsAtTheSharedCandidateBudget() {
IrisStructurePlacement placement = new IrisStructurePlacement() StructurePlacement placement = placement("placementId", "unbounded-concentric-chunks", "distribution", StructureDistribution.CONCENTRIC_RINGS, "ringCount", Integer.MAX_VALUE, "ringDistance", 32, "ringSpread", 1);
.setPlacementId("unbounded-concentric-chunks") withAdded(placement, "nativeStructures",
.setDistribution(StructureDistribution.CONCENTRIC_RINGS) nativeSource(STRUCTURE_KEY));
.setRingCount(Integer.MAX_VALUE)
.setRingDistance(32)
.setRingSpread(1);
placement.getNativeStructures().add(
new IrisNativeStructure().setStructure(STRUCTURE_KEY));
Engine engine = engine(placement); Engine engine = engine(placement);
IrisStructureLocator.LocateResult result = IrisStructureLocator.locate( IrisStructureLocator.LocateResult result = IrisStructureLocator.locate(
@@ -149,30 +135,27 @@ public class IrisStructurePlacementRingLocatorTest {
} }
private static int[] candidate( private static int[] candidate(
IrisStructurePlacement placement, long seed, int cellX, int cellZ) { StructurePlacement placement, long seed, int cellX, int cellZ) {
return StructurePlacementGrid.randomSpreadCellChunk( return StructurePlacementGrid.randomSpreadCellChunk(
cellX, cellZ, placement.getSpacing(), placement.getSeparation(), cellX, cellZ, placement.spacing(), placement.separation(),
StructurePlacementGrid.placementSalt(placement), seed); StructurePlacementGrid.placementSalt(placement), seed);
} }
private static IrisStructurePlacement randomPlacement( private static StructurePlacement randomPlacement(
String placementId, int spacing, int separation) { String placementId, int spacing, int separation) {
IrisStructurePlacement placement = new IrisStructurePlacement() StructurePlacement placement = placement("placementId", placementId, "distribution", StructureDistribution.RANDOM_SPREAD, "spacing", spacing, "separation", separation);
.setPlacementId(placementId) withAdded(placement, "nativeStructures",
.setDistribution(StructureDistribution.RANDOM_SPREAD) nativeSource(STRUCTURE_KEY));
.setSpacing(spacing)
.setSeparation(separation);
placement.getNativeStructures().add(
new IrisNativeStructure().setStructure(STRUCTURE_KEY));
return placement; return placement;
} }
private static Engine engine(IrisStructurePlacement... placements) { private static Engine engine(StructurePlacement... placements) {
IrisData data = mock(IrisData.class); IrisData data = mock(IrisData.class);
IrisDimension dimension = mock(IrisDimension.class); IrisDimension dimension = mock(IrisDimension.class);
Engine engine = mock(Engine.class); Engine engine = mock(Engine.class);
KList<IrisStructurePlacement> configured = new KList<>(); when(engine.getGeneration()).thenReturn(new EngineGeneration(engine));
for (IrisStructurePlacement placement : placements) { KList<StructurePlacement> configured = new KList<>();
for (StructurePlacement placement : placements) {
configured.add(placement); configured.add(placement);
} }
when(engine.getData()).thenReturn(data); when(engine.getData()).thenReturn(data);
@@ -183,7 +166,7 @@ public class IrisStructurePlacementRingLocatorTest {
when(engine.getHeight()).thenReturn(384); when(engine.getHeight()).thenReturn(384);
when(engine.getHeight(anyInt(), anyInt(), anyBoolean())).thenReturn(128); when(engine.getHeight(anyInt(), anyInt(), anyBoolean())).thenReturn(128);
when(dimension.getFluidHeight()).thenReturn(63); when(dimension.getFluidHeight()).thenReturn(63);
when(dimension.getStructures()).thenReturn(configured); when(dimension.getModuleSettings()).thenReturn(declaring(configured));
when(dimension.getAllRegions(engine)).thenReturn(new KList<>()); when(dimension.getAllRegions(engine)).thenReturn(new KList<>());
when(dimension.getReachableBiomes(engine)).thenReturn(new KList<>()); when(dimension.getReachableBiomes(engine)).thenReturn(new KList<>());
return engine; return engine;
@@ -18,102 +18,163 @@
package art.arcane.iris.engine.framework; package art.arcane.iris.engine.framework;
import art.arcane.iris.builtin.vanillafeatures.ImportedFeaturesSettings;
import art.arcane.iris.core.loader.IrisData;
import art.arcane.iris.core.modules.BuiltInPack;
import art.arcane.iris.core.modules.ModuleSettings;
import art.arcane.iris.engine.object.TestSettings;
import art.arcane.iris.engine.object.world.biome.IrisBiome; import art.arcane.iris.engine.object.world.biome.IrisBiome;
import art.arcane.iris.engine.object.decoration.IrisDecorationStep;
import art.arcane.iris.engine.object.world.dimension.IrisDimension; import art.arcane.iris.engine.object.world.dimension.IrisDimension;
import art.arcane.iris.engine.object.decoration.IrisImportedFeatureControl;
import art.arcane.iris.engine.object.decoration.NativeFeatureGenerationStatus;
import art.arcane.volmlib.util.collection.KList; import art.arcane.volmlib.util.collection.KList;
import com.volmit.FeatureRegistry;
import com.volmit.IrisModule;
import com.volmit.ModuleInfo;
import com.volmit.host.LoadedPack;
import com.volmit.resource.ResourceId;
import com.volmit.service.VanillaFeatures;
import com.volmit.stage.StageGraph;
import com.volmit.vanilla.DecorationStep;
import com.volmit.world.PackWorld;
import org.junit.After;
import org.junit.Rule;
import org.junit.Test; import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.Optional;
import java.util.concurrent.atomic.AtomicInteger;
import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertThrows;
import static org.junit.Assert.assertTrue; import static org.junit.Assert.assertTrue;
import static org.mockito.Mockito.mock; import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when; import static org.mockito.Mockito.when;
/** The platform's placed features as the pack's modules decide them through {@link VanillaFeatures}, kept per world. */
public class NativeFeatureGenerationPolicyTest { public class NativeFeatureGenerationPolicyTest {
private static Engine engineWith(IrisDimension dimension) { private static final int UNDERGROUND_ORES = DecorationStep.UNDERGROUND_ORES.ordinal();
Engine engine = mock(Engine.class); private static final int VEGETAL_DECORATION = DecorationStep.VEGETAL_DECORATION.ordinal();
when(engine.getDimension()).thenReturn(dimension);
return engine; @Rule
public TemporaryFolder folder = new TemporaryFolder();
private final List<LoadedPack> packs = new ArrayList<>();
@After
public void closePacks() {
packs.forEach(LoadedPack::close);
} }
@Test @Test
public void dimensionDefaultsToFeaturesOff() { public void aDimensionWithoutImportedFeaturesRunsNone() throws IOException {
Engine engine = engineWith(new IrisDimension()); Engine engine = engine(ModuleSettings.NONE, List.of());
assertFalse(NativeFeatureGenerationPolicy.isEnabled(engine)); assertFalse(NativeFeatureGenerationPolicy.isEnabled(engine));
assertFalse(NativeFeatureGenerationPolicy.shouldGenerateStep(engine, assertFalse(NativeFeatureGenerationPolicy.shouldGenerateStep(engine, UNDERGROUND_ORES));
IrisDecorationStep.UNDERGROUND_ORES)); assertFalse(NativeFeatureGenerationPolicy.shouldGenerate(engine, "minecraft:ore_diamond"));
assertEquals(NativeFeatureGenerationStatus.FEATURES_DISABLED,
NativeFeatureGenerationPolicy.resolve(engine, "minecraft:ore_diamond",
IrisDecorationStep.UNDERGROUND_ORES));
} }
@Test @Test
public void enabledDimensionResolvesThroughItsControl() { public void theDimensionsImportedFeaturesDecideThroughTheBuiltInModule() throws IOException {
KList<String> disabled = new KList<>(); Engine engine = engine(BuiltInPack.settings(TestSettings.with(new ImportedFeaturesSettings(),
disabled.add("minecraft:trees"); "enabled", true, "disabled", List.of("minecraft:trees"), "disabledSteps", List.of(DecorationStep.LAKES))), List.of());
IrisDimension dimension = new IrisDimension();
dimension.setImportedFeatures(new IrisImportedFeatureControl()
.setEnabled(true)
.setDisabled(disabled));
Engine engine = engineWith(dimension);
assertTrue(NativeFeatureGenerationPolicy.isEnabled(engine)); assertTrue(NativeFeatureGenerationPolicy.isEnabled(engine));
assertEquals(NativeFeatureGenerationStatus.GENERATE_NATIVE, assertTrue(NativeFeatureGenerationPolicy.shouldGenerateStep(engine, UNDERGROUND_ORES));
NativeFeatureGenerationPolicy.resolve(engine, "minecraft:ore_diamond", assertFalse(NativeFeatureGenerationPolicy.shouldGenerateStep(engine, DecorationStep.LAKES.ordinal()));
IrisDecorationStep.UNDERGROUND_ORES)); assertTrue(NativeFeatureGenerationPolicy.shouldGenerate(engine, "minecraft:ore_diamond"));
assertEquals(NativeFeatureGenerationStatus.DISABLED_BY_PACK, assertFalse(NativeFeatureGenerationPolicy.shouldGenerate(engine, "minecraft:trees_plains"));
NativeFeatureGenerationPolicy.resolve(engine, "minecraft:trees_plains", assertFalse("a blank key is no feature", NativeFeatureGenerationPolicy.shouldGenerate(engine, " "));
IrisDecorationStep.VEGETAL_DECORATION));
} }
@Test @Test
public void missingEngineOrDimensionFailsLoudly() { public void aStepPastTheOnesTheApiNamesGeneratesUnlessTheStepsWereNarrowed() throws IOException {
assertTrue(assertThrows(NullPointerException.class, Engine open = engine(BuiltInPack.settings(TestSettings.with(new ImportedFeaturesSettings(), "enabled", true)), List.of());
() -> NativeFeatureGenerationPolicy.control(null)) Engine narrowed = engine(BuiltInPack.settings(TestSettings.with(new ImportedFeaturesSettings(),
.getMessage().contains("requires an engine")); "enabled", true, "steps", List.of(DecorationStep.UNDERGROUND_ORES))), List.of());
assertTrue(assertThrows(NullPointerException.class, int newerStep = DecorationStep.values().length;
() -> NativeFeatureGenerationPolicy.control(engineWith(null)))
.getMessage().contains("requires a bound dimension"));
}
/** assertTrue(NativeFeatureGenerationPolicy.shouldGenerateStep(open, newerStep));
* The field initializer gives every dimension a control block, but an explicit assertFalse(NativeFeatureGenerationPolicy.shouldGenerateStep(narrowed, newerStep));
* {@code "importedFeatures": null} in dimension JSON overwrites it - Gson assigns what the document says. This
* policy is consulted per feature decision on the generation path, so a stray null must disable native features,
* not fail the chunk.
*/
@Test
public void nullControlBlockDisablesNativeFeaturesInsteadOfFailingGeneration() {
IrisDimension dimension = new IrisDimension();
dimension.setImportedFeatures(null);
Engine engine = engineWith(dimension);
assertFalse(NativeFeatureGenerationPolicy.isEnabled(engine));
assertFalse(NativeFeatureGenerationPolicy.shouldGenerateStep(engine, IrisDecorationStep.VEGETAL_DECORATION));
assertEquals(NativeFeatureGenerationStatus.FEATURES_DISABLED,
NativeFeatureGenerationPolicy.resolve(engine, "minecraft:ore_diamond",
IrisDecorationStep.UNDERGROUND_ORES));
} }
@Test @Test
public void generationStatusMessagesAreSharedAcrossPlatforms() { public void aPackModuleMayTurnFeaturesOnAndAnyModuleMayRefuseAStepOrAFeature() throws IOException {
assertEquals("Native feature minecraft:ore_diamond is disabled by this dimension's" VanillaFeatures packModule = new VanillaFeatures() {
+ " importedFeatures.disabled list.", @Override
NativeFeatureGenerationPolicy.generationStatusMessage("minecraft:ore_diamond", public boolean generates(PackWorld world) {
NativeFeatureGenerationStatus.DISABLED_BY_PACK)); return true;
assertEquals("Native feature minecraft:ore_diamond does not generate because this dimension's" }
+ " importedFeatures.enabled is false.",
NativeFeatureGenerationPolicy.generationStatusMessage("minecraft:ore_diamond", @Override
NativeFeatureGenerationStatus.FEATURES_DISABLED)); public boolean generatesStep(PackWorld world, Optional<DecorationStep> step) {
assertEquals("Native feature minecraft:ore_diamond does not generate because its decoration step is" return !step.equals(Optional.of(DecorationStep.VEGETAL_DECORATION));
+ " excluded by importedFeatures.", }
NativeFeatureGenerationPolicy.generationStatusMessage("minecraft:ore_diamond",
NativeFeatureGenerationStatus.STEP_DISABLED)); @Override
public boolean generatesFeature(PackWorld world, ResourceId feature) {
return !feature.path().startsWith("ore_");
}
};
Engine engine = engine(BuiltInPack.settings(TestSettings.with(new ImportedFeaturesSettings(),
"disabled", List.of("minecraft:spring"))), List.of(new ProviderModule(packModule)));
assertTrue(NativeFeatureGenerationPolicy.isEnabled(engine));
assertFalse(NativeFeatureGenerationPolicy.shouldGenerateStep(engine, VEGETAL_DECORATION));
assertTrue(NativeFeatureGenerationPolicy.shouldGenerateStep(engine, UNDERGROUND_ORES));
assertFalse(NativeFeatureGenerationPolicy.shouldGenerate(engine, "minecraft:ore_diamond"));
assertFalse("the dimension's own list still applies", NativeFeatureGenerationPolicy.shouldGenerate(engine, "minecraft:spring_water"));
assertTrue(NativeFeatureGenerationPolicy.shouldGenerate(engine, "minecraft:trees_plains"));
}
@Test
public void eachStepAndFeatureIsAskedOncePerWorld() throws IOException {
AtomicInteger steps = new AtomicInteger();
AtomicInteger features = new AtomicInteger();
VanillaFeatures counting = new VanillaFeatures() {
@Override
public boolean generates(PackWorld world) {
return true;
}
@Override
public boolean generatesStep(PackWorld world, Optional<DecorationStep> step) {
steps.incrementAndGet();
return true;
}
@Override
public boolean generatesFeature(PackWorld world, ResourceId feature) {
features.incrementAndGet();
return true;
}
};
Engine engine = engine(ModuleSettings.NONE, List.of(new ProviderModule(counting)));
for (int chunk = 0; chunk < 3; chunk++) {
NativeFeatureGenerationPolicy.shouldGenerateStep(engine, UNDERGROUND_ORES);
NativeFeatureGenerationPolicy.shouldGenerate(engine, "minecraft:ore_diamond");
}
assertEquals(1, steps.get());
assertEquals(1, features.get());
}
/** The platforms convert their decoration steps by index, so a drift here silently mislabels every step gate. */
@Test
public void decorationStepsAreInTheOrderOfTheVanillaTable() {
String[] vanilla = {
"raw_generation", "lakes", "local_modifications", "underground_structures",
"surface_structures", "strongholds", "underground_ores", "underground_decoration",
"fluid_springs", "vegetal_decoration", "top_layer_modification"
};
assertEquals(vanilla.length, DecorationStep.values().length);
for (int index = 0; index < vanilla.length; index++) {
assertEquals(vanilla[index], DecorationStep.values()[index].name().toLowerCase(Locale.ROOT));
}
} }
/** /**
@@ -140,4 +201,37 @@ public class NativeFeatureGenerationPolicyTest {
modded.setDerivative("somemod:alien_waste"); modded.setDerivative("somemod:alien_waste");
assertEquals("somemod:alien_waste", modded.getVanillaDerivativeKey()); assertEquals("somemod:alien_waste", modded.getVanillaDerivativeKey());
} }
/** An engine whose dimension declares {@code dimensionSettings}, its pack loading the built-ins and {@code packModules}. */
private Engine engine(ModuleSettings dimensionSettings, List<IrisModule> packModules) throws IOException {
IrisData data = mock(IrisData.class);
Engine engine = mock(Engine.class);
IrisDimension dimension = mock(IrisDimension.class);
packs.add(BuiltInPack.serveWithResources(data, folder, packModules));
when(engine.getData()).thenReturn(data);
when(engine.getDimension()).thenReturn(dimension);
when(engine.getGeneration()).thenReturn(new EngineGeneration(engine));
when(dimension.getLoadKey()).thenReturn("overworld");
when(dimension.getModuleSettings()).thenReturn(dimensionSettings);
when(dimension.getAllRegions(engine)).thenReturn(new KList<>());
when(dimension.getReachableBiomes(engine)).thenReturn(new KList<>());
return engine;
}
/** A pack module whose only part is a vanilla features provider. */
private record ProviderModule(VanillaFeatures provider) implements IrisModule {
@Override
public ModuleInfo info() {
return ModuleInfo.of("test:features", "Features", "1");
}
@Override
public void install(StageGraph graph) {
}
@Override
public void register(FeatureRegistry registry) {
registry.registerService(VanillaFeatures.class, provider);
}
}
} }
@@ -4,13 +4,12 @@ import art.arcane.iris.core.loader.IrisData;
import art.arcane.iris.builtin.structure.StructureAdjustment; import art.arcane.iris.builtin.structure.StructureAdjustment;
import art.arcane.iris.builtin.structure.StructureSettings; import art.arcane.iris.builtin.structure.StructureSettings;
import art.arcane.iris.core.modules.BuiltInPack; import art.arcane.iris.core.modules.BuiltInPack;
import art.arcane.iris.core.modules.ModuleSettings;
import art.arcane.iris.core.modules.IrisPackResources; import art.arcane.iris.core.modules.IrisPackResources;
import art.arcane.iris.engine.object.world.dimension.IrisDimension; import art.arcane.iris.engine.object.world.dimension.IrisDimension;
import art.arcane.iris.engine.object.structure.vanilla.IrisNativeStructure; import art.arcane.iris.builtin.structure.NativeStructureSource;
import art.arcane.iris.engine.object.world.region.IrisRegion; import art.arcane.iris.engine.object.world.region.IrisRegion;
import art.arcane.iris.engine.object.structure.IrisStructurePlacement; import art.arcane.iris.builtin.structure.StructurePlacement;
import art.arcane.iris.engine.object.structure.vanilla.NativeStructureSuppression; import art.arcane.iris.builtin.structure.NativeStructureSuppression;
import art.arcane.volmlib.util.collection.KList; import art.arcane.volmlib.util.collection.KList;
import com.volmit.FeatureRegistry; import com.volmit.FeatureRegistry;
import com.volmit.IrisModule; import com.volmit.IrisModule;
@@ -38,6 +37,10 @@ import java.util.List;
import java.util.Optional; import java.util.Optional;
import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicInteger;
import static art.arcane.iris.engine.framework.StructurePlacementFixtures.nativeSource;
import static art.arcane.iris.engine.framework.StructurePlacementFixtures.placementSettings;
import static art.arcane.iris.engine.framework.StructurePlacementFixtures.declaring;
import static art.arcane.iris.engine.framework.StructurePlacementFixtures.withAdded;
import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertThrows; import static org.junit.Assert.assertThrows;
@@ -106,9 +109,9 @@ public class NativeStructureGenerationPolicyTest {
/** Suppression comes from the iris:structure module's rule. */ /** Suppression comes from the iris:structure module's rule. */
@Test @Test
public void aStructureAnIrisPlacementReplacesIsBlockedByTheStructureModule() throws IOException { public void aStructureAnIrisPlacementReplacesIsBlockedByTheStructureModule() throws IOException {
IrisStructurePlacement replacement = new IrisStructurePlacement().setNativeSuppression(NativeStructureSuppression.REPLACE_SOURCE); StructurePlacement replacement = StructurePlacementFixtures.placement("nativeSuppression", NativeStructureSuppression.REPLACE_SOURCE);
replacement.getNativeStructures().add(new IrisNativeStructure().setStructure("minecraft:village_plains")); withAdded(replacement, "nativeStructures", nativeSource("minecraft:village_plains"));
KList<IrisStructurePlacement> dimensionPlacements = new KList<>(); KList<StructurePlacement> dimensionPlacements = new KList<>();
dimensionPlacements.add(replacement); dimensionPlacements.add(replacement);
Engine engine = engine(allowingEverything(), new KList<>(), dimensionPlacements, List.of()); Engine engine = engine(allowingEverything(), new KList<>(), dimensionPlacements, List.of());
@@ -223,31 +226,30 @@ public class NativeStructureGenerationPolicyTest {
return new StructureSettings(); return new StructureSettings();
} }
private static KList<IrisStructurePlacement> regionPlacement(String placedKey) { private static KList<StructurePlacement> regionPlacement(String placedKey) {
IrisStructurePlacement placement = new IrisStructurePlacement(); StructurePlacement placement = new StructurePlacement();
placement.getNativeStructures().add(new IrisNativeStructure().setStructure(placedKey)); withAdded(placement, "nativeStructures", nativeSource(placedKey));
KList<IrisStructurePlacement> placements = new KList<>(); KList<StructurePlacement> placements = new KList<>();
placements.add(placement); placements.add(placement);
return placements; return placements;
} }
/** An engine whose pack serves Iris's built-in modules and {@code packModules}, with the given structure placements. */ /** An engine whose pack serves Iris's built-in modules and {@code packModules}, with the given structure placements. */
private Engine engine(StructureSettings settings, KList<IrisStructurePlacement> regionPlacements, private Engine engine(StructureSettings settings, KList<StructurePlacement> regionPlacements,
KList<IrisStructurePlacement> dimensionPlacements, List<IrisModule> packModules) throws IOException { KList<StructurePlacement> dimensionPlacements, List<IrisModule> packModules) throws IOException {
IrisData data = mock(IrisData.class); IrisData data = mock(IrisData.class);
Engine engine = mock(Engine.class); Engine engine = mock(Engine.class);
when(engine.getGeneration()).thenReturn(new EngineGeneration(engine));
IrisDimension dimension = mock(IrisDimension.class); IrisDimension dimension = mock(IrisDimension.class);
IrisRegion region = mock(IrisRegion.class); IrisRegion region = mock(IrisRegion.class);
when(region.getStructures()).thenReturn(regionPlacements); when(region.getModuleSettings()).thenReturn(declaring(regionPlacements));
when(region.getModuleSettings()).thenReturn(ModuleSettings.NONE);
KList<IrisRegion> regions = new KList<>(); KList<IrisRegion> regions = new KList<>();
regions.add(region); regions.add(region);
packs.add(BuiltInPack.serveWithResources(data, folder, packModules)); packs.add(BuiltInPack.serveWithResources(data, folder, packModules));
when(engine.getData()).thenReturn(data); when(engine.getData()).thenReturn(data);
when(engine.getDimension()).thenReturn(dimension); when(engine.getDimension()).thenReturn(dimension);
when(dimension.getModuleSettings()).thenReturn(BuiltInPack.settings(settings)); when(dimension.getModuleSettings()).thenReturn(BuiltInPack.settings(settings, placementSettings(dimensionPlacements)));
when(dimension.getStructures()).thenReturn(dimensionPlacements);
when(dimension.getAllRegions(engine)).thenReturn(regions); when(dimension.getAllRegions(engine)).thenReturn(regions);
when(dimension.getReachableBiomes(engine)).thenReturn(new KList<>()); when(dimension.getReachableBiomes(engine)).thenReturn(new KList<>());
return engine; return engine;
@@ -2,12 +2,12 @@ package art.arcane.iris.engine.framework;
import art.arcane.iris.core.loader.IrisData; import art.arcane.iris.core.loader.IrisData;
import art.arcane.iris.core.modules.BuiltInPack; import art.arcane.iris.core.modules.BuiltInPack;
import art.arcane.iris.core.modules.ModuleSettings;
import art.arcane.iris.builtin.structure.StructureStilts; import art.arcane.iris.builtin.structure.StructureStilts;
import art.arcane.iris.builtin.structure.StructureTerrain; import art.arcane.iris.builtin.structure.StructureTerrain;
import art.arcane.iris.engine.object.structure.IrisStructurePlacement; import art.arcane.iris.builtin.structure.StructurePlacement;
import art.arcane.iris.engine.object.structure.StructureDistribution; import art.arcane.iris.builtin.structure.StructureDistribution;
import art.arcane.iris.engine.object.structure.vanilla.IrisNativeStructure; import art.arcane.iris.builtin.structure.NativeStructureSource;
import art.arcane.iris.engine.object.TestSettings;
import art.arcane.iris.engine.object.world.dimension.IrisDimension; import art.arcane.iris.engine.object.world.dimension.IrisDimension;
import art.arcane.volmlib.util.collection.KList; import art.arcane.volmlib.util.collection.KList;
import com.google.gson.Gson; import com.google.gson.Gson;
@@ -22,6 +22,9 @@ import java.io.IOException;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
import static art.arcane.iris.engine.framework.StructurePlacementFixtures.nativeSource;
import static art.arcane.iris.engine.framework.StructurePlacementFixtures.declaring;
import static art.arcane.iris.engine.framework.StructurePlacementFixtures.withAdded;
import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull; import static org.junit.Assert.assertNull;
import static org.mockito.ArgumentMatchers.anyInt; import static org.mockito.ArgumentMatchers.anyInt;
@@ -107,7 +110,7 @@ public class NativeStructureStartsTest {
@Test @Test
public void startsMatchThePlannersForAFixedSeed() throws IOException { public void startsMatchThePlannersForAFixedSeed() throws IOException {
KList<IrisStructurePlacement> placements = new KList<>(); KList<StructurePlacement> placements = new KList<>();
placements.add(placement("villages", false, -64, 320, 0.2D, source("minecraft:village_plains", 3), placements.add(placement("villages", false, -64, 320, 0.2D, source("minecraft:village_plains", 3),
source("minecraft:pillager_outpost", 1))); source("minecraft:pillager_outpost", 1)));
placements.add(placement("cities", true, -50, -10, 0.15D, source("minecraft:ancient_city", 1))); placements.add(placement("cities", true, -50, -10, 0.15D, source("minecraft:ancient_city", 1)));
@@ -136,9 +139,9 @@ public class NativeStructureStartsTest {
+ "\"palette\":{\"palette\":[{\"block\":\"minecraft:stone_bricks\"}]}}", StructureStilts.class); + "\"palette\":{\"palette\":[{\"block\":\"minecraft:stone_bricks\"}]}}", StructureStilts.class);
JigsawOverrides jigsaw = JigsawOverrides.none().withStartPool("minecraft:village/plains/town_centers") JigsawOverrides jigsaw = JigsawOverrides.none().withStartPool("minecraft:village/plains/town_centers")
.withMaxDepth(5).withHeightmap(JigsawOverrides.Heightmap.OCEAN_FLOOR_WG).withExpansionHack(false); .withMaxDepth(5).withHeightmap(JigsawOverrides.Heightmap.OCEAN_FLOOR_WG).withExpansionHack(false);
IrisStructurePlacement fitted = placement("fitted", true, -40, -20, 1D, source("minecraft:ancient_city", 1) StructurePlacement fitted = TestSettings.with(placement("fitted", true, -40, -20, 1D,
.setJigsaw(jigsaw)).setTerrain(terrain).setStilt(stilt); TestSettings.with(source("minecraft:ancient_city", 1), "jigsaw", jigsaw)), "terrain", terrain, "stilt", stilt);
KList<IrisStructurePlacement> placements = new KList<>(); KList<StructurePlacement> placements = new KList<>();
placements.add(fitted); placements.add(fitted);
Engine engine = engine(placements); Engine engine = engine(placements);
@@ -151,28 +154,26 @@ public class NativeStructureStartsTest {
assertNull(NativeStructureStarts.matchingPlan(engine, "minecraft:stronghold", 0, 0)); assertNull(NativeStructureStarts.matchingPlan(engine, "minecraft:stronghold", 0, 0));
} }
private static IrisNativeStructure source(String structure, int weight) { private static NativeStructureSource source(String structure, int weight) {
return new IrisNativeStructure().setStructure(structure).setWeight(weight); return nativeSource(structure, weight);
} }
private static IrisStructurePlacement placement(String id, boolean underground, int minHeight, int maxHeight, double density, private static StructurePlacement placement(String id, boolean underground, int minHeight, int maxHeight, double density,
IrisNativeStructure... sources) { NativeStructureSource... sources) {
IrisStructurePlacement placement = new IrisStructurePlacement().setPlacementId(id) StructurePlacement placement = StructurePlacementFixtures.placement("placementId", id, "distribution", StructureDistribution.DENSITY, "density", density, "underground", underground, "minHeight", minHeight, "maxHeight", maxHeight);
.setDistribution(StructureDistribution.DENSITY).setDensity(density) for (NativeStructureSource source : sources) {
.setUnderground(underground).setMinHeight(minHeight).setMaxHeight(maxHeight); withAdded(placement, "nativeStructures", source);
for (IrisNativeStructure source : sources) {
placement.getNativeStructures().add(source);
} }
return placement; return placement;
} }
private static String placementId(KList<IrisStructurePlacement> placements, long identity) { private static String placementId(KList<StructurePlacement> placements, long identity) {
return placements.stream().filter(placement -> StructurePlacementGrid.placementIdentity(placement) == identity) return placements.stream().filter(placement -> StructurePlacementGrid.placementIdentity(placement) == identity)
.findFirst().orElseThrow().getPlacementId(); .findFirst().orElseThrow().placementId();
} }
/** An engine whose pack serves the built-in modules, with terrain heights that vary per column and a high sea. */ /** An engine whose pack serves the built-in modules, with terrain heights that vary per column and a high sea. */
private Engine engine(KList<IrisStructurePlacement> placements) throws IOException { private Engine engine(KList<StructurePlacement> placements) throws IOException {
IrisData data = mock(IrisData.class); IrisData data = mock(IrisData.class);
Engine engine = mock(Engine.class); Engine engine = mock(Engine.class);
IrisDimension dimension = mock(IrisDimension.class); IrisDimension dimension = mock(IrisDimension.class);
@@ -190,8 +191,7 @@ public class NativeStructureStartsTest {
}); });
when(engine.getDimension()).thenReturn(dimension); when(engine.getDimension()).thenReturn(dimension);
when(dimension.getFluidHeight()).thenReturn(127); when(dimension.getFluidHeight()).thenReturn(127);
when(dimension.getModuleSettings()).thenReturn(ModuleSettings.NONE); when(dimension.getModuleSettings()).thenReturn(declaring(placements));
when(dimension.getStructures()).thenReturn(placements);
when(dimension.getAllRegions(engine)).thenReturn(new KList<>()); when(dimension.getAllRegions(engine)).thenReturn(new KList<>());
when(dimension.getReachableBiomes(engine)).thenReturn(new KList<>()); when(dimension.getReachableBiomes(engine)).thenReturn(new KList<>());
return engine; return engine;
@@ -57,12 +57,12 @@ public class NativeStructureVolumeSuppressionTest {
StructureSettings settings = new StructureSettings(List.of("minecraft:village"), List.of(), 0, true, List.of(), List.of()); StructureSettings settings = new StructureSettings(List.of("minecraft:village"), List.of(), 0, true, List.of(), List.of());
IrisDimension dimension = mock(IrisDimension.class); IrisDimension dimension = mock(IrisDimension.class);
Engine engine = mock(Engine.class); Engine engine = mock(Engine.class);
when(engine.getGeneration()).thenReturn(new EngineGeneration(engine));
IrisData data = mock(IrisData.class); IrisData data = mock(IrisData.class);
packs.add(BuiltInPack.serveWithResources(data, folder, List.of())); packs.add(BuiltInPack.serveWithResources(data, folder, List.of()));
when(engine.getData()).thenReturn(data); when(engine.getData()).thenReturn(data);
when(engine.getDimension()).thenReturn(dimension); when(engine.getDimension()).thenReturn(dimension);
when(dimension.getModuleSettings()).thenReturn(BuiltInPack.settings(settings)); when(dimension.getModuleSettings()).thenReturn(BuiltInPack.settings(settings));
when(dimension.getStructures()).thenReturn(new KList<>());
when(dimension.getAllRegions(engine)).thenReturn(new KList<>()); when(dimension.getAllRegions(engine)).thenReturn(new KList<>());
when(dimension.getReachableBiomes(engine)).thenReturn(new KList<>()); when(dimension.getReachableBiomes(engine)).thenReturn(new KList<>());
return engine; return engine;
@@ -1,10 +1,16 @@
package art.arcane.iris.engine.framework; package art.arcane.iris.engine.framework;
import art.arcane.iris.builtin.structure.StructureAnchorMode;
import art.arcane.iris.builtin.structure.StructurePlacement;
import art.arcane.iris.engine.object.world.dimension.IrisDimension; import art.arcane.iris.engine.object.world.dimension.IrisDimension;
import art.arcane.iris.engine.object.structure.IrisStructureAnchorMode; import art.arcane.iris.spi.IrisPlatform;
import art.arcane.iris.engine.object.structure.IrisStructurePlacement; import art.arcane.iris.spi.IrisPlatforms;
import art.arcane.iris.spi.PlatformBlockState;
import art.arcane.iris.spi.PlatformRegistries;
import art.arcane.volmlib.util.math.RNG; import art.arcane.volmlib.util.math.RNG;
import art.arcane.volmlib.util.matter.MatterCavern; import art.arcane.volmlib.util.matter.MatterCavern;
import org.junit.After;
import org.junit.Before;
import org.junit.Test; import org.junit.Test;
import java.util.Arrays; import java.util.Arrays;
@@ -12,6 +18,7 @@ import java.util.HashSet;
import java.util.Set; import java.util.Set;
import java.util.function.IntPredicate; import java.util.function.IntPredicate;
import static art.arcane.iris.engine.framework.StructurePlacementFixtures.placement;
import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertFalse;
@@ -19,6 +26,7 @@ import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull; import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue; import static org.junit.Assert.assertTrue;
import static org.mockito.ArgumentMatchers.anyInt; import static org.mockito.ArgumentMatchers.anyInt;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.eq; import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.RETURNS_DEEP_STUBS; import static org.mockito.Mockito.RETURNS_DEEP_STUBS;
import static org.mockito.Mockito.mock; import static org.mockito.Mockito.mock;
@@ -27,16 +35,32 @@ import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when; import static org.mockito.Mockito.when;
public class StructureCaveAnchorResolverTest { public class StructureCaveAnchorResolverTest {
@Before
public void bindPlatform() {
IrisPlatforms.unbind();
PlatformBlockState block = mock(PlatformBlockState.class);
PlatformRegistries registries = mock(PlatformRegistries.class);
when(registries.block(anyString())).thenReturn(block);
IrisPlatform platform = mock(IrisPlatform.class);
when(platform.registries()).thenReturn(registries);
IrisPlatforms.bind(platform);
}
@After
public void unbindPlatform() {
IrisPlatforms.unbind();
}
@Test @Test
public void floorRequiresSolidBoundaryAndUpwardClearance() { public void floorRequiresSolidBoundaryAndUpwardClearance() {
IntPredicate carved = carvedAt(10, 11, 12, 13); IntPredicate carved = carvedAt(10, 11, 12, 13);
assertTrue(StructureCaveAnchorResolver.matchesGeometry( assertTrue(StructureCaveAnchorResolver.matchesGeometry(
carved, IrisStructureAnchorMode.CAVE_FLOOR, 10, 3)); carved, StructureAnchorMode.CAVE_FLOOR, 10, 3));
assertFalse(StructureCaveAnchorResolver.matchesGeometry( assertFalse(StructureCaveAnchorResolver.matchesGeometry(
carved, IrisStructureAnchorMode.CAVE_FLOOR, 11, 3)); carved, StructureAnchorMode.CAVE_FLOOR, 11, 3));
assertFalse(StructureCaveAnchorResolver.matchesGeometry( assertFalse(StructureCaveAnchorResolver.matchesGeometry(
carved, IrisStructureAnchorMode.CAVE_FLOOR, 10, 5)); carved, StructureAnchorMode.CAVE_FLOOR, 10, 5));
} }
@Test @Test
@@ -44,9 +68,9 @@ public class StructureCaveAnchorResolverTest {
IntPredicate carved = carvedAt(20, 21, 22, 23); IntPredicate carved = carvedAt(20, 21, 22, 23);
assertTrue(StructureCaveAnchorResolver.matchesGeometry( assertTrue(StructureCaveAnchorResolver.matchesGeometry(
carved, IrisStructureAnchorMode.CAVE_CEILING, 23, 4)); carved, StructureAnchorMode.CAVE_CEILING, 23, 4));
assertFalse(StructureCaveAnchorResolver.matchesGeometry( assertFalse(StructureCaveAnchorResolver.matchesGeometry(
carved, IrisStructureAnchorMode.CAVE_CEILING, 22, 4)); carved, StructureAnchorMode.CAVE_CEILING, 22, 4));
} }
@Test @Test
@@ -54,13 +78,13 @@ public class StructureCaveAnchorResolverTest {
IntPredicate carved = carvedAt(30, 31, 32, 33, 34); IntPredicate carved = carvedAt(30, 31, 32, 33, 34);
assertTrue(StructureCaveAnchorResolver.matchesGeometry( assertTrue(StructureCaveAnchorResolver.matchesGeometry(
carved, IrisStructureAnchorMode.CAVE_CENTER, 32, 5)); carved, StructureAnchorMode.CAVE_CENTER, 32, 5));
assertFalse(StructureCaveAnchorResolver.matchesGeometry( assertFalse(StructureCaveAnchorResolver.matchesGeometry(
carved, IrisStructureAnchorMode.CAVE_CENTER, 31, 3)); carved, StructureAnchorMode.CAVE_CENTER, 31, 3));
assertFalse(StructureCaveAnchorResolver.matchesGeometry( assertFalse(StructureCaveAnchorResolver.matchesGeometry(
carved, IrisStructureAnchorMode.CAVE_CENTER, 33, 3)); carved, StructureAnchorMode.CAVE_CENTER, 33, 3));
assertFalse(StructureCaveAnchorResolver.matchesGeometry( assertFalse(StructureCaveAnchorResolver.matchesGeometry(
carvedAt(32, 33, 34), IrisStructureAnchorMode.CAVE_CENTER, 32, 3)); carvedAt(32, 33, 34), StructureAnchorMode.CAVE_CENTER, 32, 3));
} }
@Test @Test
@@ -68,21 +92,21 @@ public class StructureCaveAnchorResolverTest {
IntPredicate carved = carvedAt(30, 31, 32, 33); IntPredicate carved = carvedAt(30, 31, 32, 33);
assertTrue(StructureCaveAnchorResolver.matchesGeometry( assertTrue(StructureCaveAnchorResolver.matchesGeometry(
carved, IrisStructureAnchorMode.CAVE_CENTER, 31, 4)); carved, StructureAnchorMode.CAVE_CENTER, 31, 4));
assertTrue(StructureCaveAnchorResolver.matchesGeometry( assertTrue(StructureCaveAnchorResolver.matchesGeometry(
carved, IrisStructureAnchorMode.CAVE_CENTER, 32, 4)); carved, StructureAnchorMode.CAVE_CENTER, 32, 4));
assertFalse(StructureCaveAnchorResolver.matchesGeometry( assertFalse(StructureCaveAnchorResolver.matchesGeometry(
carved, IrisStructureAnchorMode.CAVE_CENTER, 30, 4)); carved, StructureAnchorMode.CAVE_CENTER, 30, 4));
} }
@Test @Test
public void anyRequiresClearanceAroundTheAlignedCenter() { public void anyRequiresClearanceAroundTheAlignedCenter() {
assertTrue(StructureCaveAnchorResolver.matchesGeometry( assertTrue(StructureCaveAnchorResolver.matchesGeometry(
carvedAt(39, 40, 41), IrisStructureAnchorMode.CAVE_ANY, 40, 3)); carvedAt(39, 40, 41), StructureAnchorMode.CAVE_ANY, 40, 3));
assertTrue(StructureCaveAnchorResolver.matchesGeometry( assertTrue(StructureCaveAnchorResolver.matchesGeometry(
carvedAt(48, 49, 50, 51), IrisStructureAnchorMode.CAVE_ANY, 49, 4)); carvedAt(48, 49, 50, 51), StructureAnchorMode.CAVE_ANY, 49, 4));
assertFalse(StructureCaveAnchorResolver.matchesGeometry( assertFalse(StructureCaveAnchorResolver.matchesGeometry(
carvedAt(60, 61, 62), IrisStructureAnchorMode.CAVE_ANY, 60, 3)); carvedAt(60, 61, 62), StructureAnchorMode.CAVE_ANY, 60, 3));
} }
@Test @Test
@@ -177,15 +201,8 @@ public class StructureCaveAnchorResolverTest {
return engine; return engine;
} }
private static IrisStructurePlacement floorPlacement(boolean underwater) { private static StructurePlacement floorPlacement(boolean underwater) {
return new IrisStructurePlacement() return placement("anchor", StructureAnchorMode.CAVE_FLOOR, "minHeight", -54, "maxHeight", -54, "caveAnchorAttempts", 1, "caveAnchorScanStep", 1, "caveMinimumClearance", 3, "underwater", underwater);
.setAnchor(IrisStructureAnchorMode.CAVE_FLOOR)
.setMinHeight(-54)
.setMaxHeight(-54)
.setCaveAnchorAttempts(1)
.setCaveAnchorScanStep(1)
.setCaveMinimumClearance(3)
.setUnderwater(underwater);
} }
private static IntPredicate carvedAt(Integer... values) { private static IntPredicate carvedAt(Integer... values) {
@@ -0,0 +1,80 @@
package art.arcane.iris.engine.framework;
import art.arcane.iris.builtin.structure.NativeStructureSource;
import art.arcane.iris.builtin.structure.StructurePlacement;
import art.arcane.iris.builtin.structure.StructurePlacementSettings;
import art.arcane.iris.core.loader.IrisRegistrant;
import art.arcane.iris.core.modules.BuiltInPack;
import art.arcane.iris.core.modules.ModuleSettings;
import art.arcane.iris.engine.object.TestSettings;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
/** Structure placements as packs write them, for tests: {@code placement("structures", List.of("test:city"))}. */
public final class StructurePlacementFixtures {
private StructurePlacementFixtures() {
}
/** A placement with the options {@code namesAndValues} set, the others at their defaults. */
public static StructurePlacement placement(Object... namesAndValues) {
return TestSettings.with(new StructurePlacement(), namesAndValues);
}
/** A placement that assembles the pack's structures {@code keys}. */
public static StructurePlacement assembling(String... keys) {
return placement("structures", new ArrayList<>(Arrays.asList(keys)));
}
/** A placement that starts the platform's structures {@code sources} natively. */
public static StructurePlacement starting(NativeStructureSource... sources) {
return placement("nativeStructures", new ArrayList<>(Arrays.asList(sources)));
}
public static NativeStructureSource nativeSource(String structure) {
return TestSettings.with(new NativeStructureSource(), "structure", structure);
}
public static NativeStructureSource nativeSource(String structure, int weight) {
return TestSettings.with(new NativeStructureSource(), "structure", structure, "weight", weight);
}
/** {@code placement} with {@code value} appended to its list option {@code name}, as a pack listing one more would have it. */
public static StructurePlacement withAdded(StructurePlacement placement, String name, Object value) {
List<Object> values = new ArrayList<>(currentList(placement, name));
values.add(value);
return TestSettings.with(placement, name, values);
}
private static List<?> currentList(StructurePlacement placement, String name) {
try {
java.lang.reflect.Field field = StructurePlacement.class.getDeclaredField(name);
field.setAccessible(true);
Object value = field.get(placement);
return value == null ? List.of() : (List<?>) value;
} catch (ReflectiveOperationException failure) {
throw new IllegalArgumentException("No list option " + name + " in a structure placement", failure);
}
}
/** The {@code "structures"} settings listing {@code placements}. */
public static StructurePlacementSettings placementSettings(List<StructurePlacement> placements) {
return TestSettings.with(new StructurePlacementSettings(), "placements", new ArrayList<>(placements));
}
/** The module settings of a dimension, region or biome whose {@code "structures"} are {@code placements}. */
public static ModuleSettings declaring(List<StructurePlacement> placements) {
return BuiltInPack.settings(placementSettings(placements));
}
public static ModuleSettings declaring(StructurePlacement... placements) {
return declaring(Arrays.asList(placements));
}
/** {@code owner}, now declaring {@code placements} in its {@code "structures"}. */
public static <T extends IrisRegistrant> T declare(T owner, StructurePlacement... placements) {
owner.setModuleSettings(declaring(placements));
return owner;
}
}
@@ -18,11 +18,13 @@
package art.arcane.iris.engine.framework; package art.arcane.iris.engine.framework;
import art.arcane.iris.engine.object.structure.IrisStructurePlacement; import art.arcane.iris.builtin.structure.StructurePlacement;
import art.arcane.iris.engine.object.structure.IrisStructureAnchorMode; import art.arcane.iris.builtin.structure.StructureAnchorMode;
import art.arcane.iris.engine.object.structure.StructureDistribution; import art.arcane.iris.builtin.structure.StructureDistribution;
import org.junit.Test; import org.junit.Test;
import art.arcane.iris.engine.object.TestSettings;
import static art.arcane.iris.engine.framework.StructurePlacementFixtures.withAdded;
import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotEquals; import static org.junit.Assert.assertNotEquals;
@@ -109,11 +111,11 @@ public class StructurePlacementGridTest {
@Test @Test
public void densityStartIsDeterministicAndPlacementIdScoped() { public void densityStartIsDeterministicAndPlacementIdScoped() {
IrisStructurePlacement placement = placement(StructureDistribution.DENSITY); StructurePlacement placement = placement(StructureDistribution.DENSITY);
placement.setDensity(0.35); TestSettings.with(placement, "density", 0.35);
IrisStructurePlacement secondPlacement = placement(StructureDistribution.DENSITY); StructurePlacement secondPlacement = placement(StructureDistribution.DENSITY);
secondPlacement.setDensity(0.35); TestSettings.with(secondPlacement, "density", 0.35);
secondPlacement.setPlacementId("second"); TestSettings.with(secondPlacement, "placementId", "second");
boolean differsById = false; boolean differsById = false;
for (int cx = -32; cx <= 32; cx++) { for (int cx = -32; cx <= 32; cx++) {
for (int cz = -32; cz <= 32; cz++) { for (int cz = -32; cz <= 32; cz++) {
@@ -129,22 +131,22 @@ public class StructurePlacementGridTest {
@Test @Test
public void densityBoundariesNeverAndAlwaysStart() { public void densityBoundariesNeverAndAlwaysStart() {
IrisStructurePlacement placement = placement(StructureDistribution.DENSITY); StructurePlacement placement = placement(StructureDistribution.DENSITY);
placement.setDensity(0.0); TestSettings.with(placement, "density", 0.0);
assertFalse(StructurePlacementGrid.startsInChunk(placement, 4, -9, 77L)); assertFalse(StructurePlacementGrid.startsInChunk(placement, 4, -9, 77L));
placement.setDensity(1.0); TestSettings.with(placement, "density", 1.0);
assertTrue(StructurePlacementGrid.startsInChunk(placement, 4, -9, 77L)); assertTrue(StructurePlacementGrid.startsInChunk(placement, 4, -9, 77L));
} }
@Test @Test
public void concentricRingCountIsFiniteTotalPlacementCount() { public void concentricRingCountIsFiniteTotalPlacementCount() {
IrisStructurePlacement placement = placement(StructureDistribution.CONCENTRIC_RINGS); StructurePlacement placement = placement(StructureDistribution.CONCENTRIC_RINGS);
placement.setRingCount(10); TestSettings.with(placement, "ringCount", 10);
placement.setRingSpread(3); TestSettings.with(placement, "ringSpread", 3);
placement.setRingDistance(12); TestSettings.with(placement, "ringDistance", 12);
long seed = 484848L; long seed = 484848L;
int lastRing = Math.ceilDiv(placement.getRingCount(), placement.getRingSpread()); int lastRing = Math.ceilDiv(placement.ringCount(), placement.ringSpread());
int scanRadius = (lastRing + 2) * placement.getRingDistance(); int scanRadius = (lastRing + 2) * placement.ringDistance();
int starts = 0; int starts = 0;
for (int cx = -scanRadius; cx <= scanRadius; cx++) { for (int cx = -scanRadius; cx <= scanRadius; cx++) {
for (int cz = -scanRadius; cz <= scanRadius; cz++) { for (int cz = -scanRadius; cz <= scanRadius; cz++) {
@@ -153,16 +155,16 @@ public class StructurePlacementGridTest {
} }
} }
} }
assertEquals(placement.getRingCount(), starts); assertEquals(placement.ringCount(), starts);
assertNull(StructurePlacementGrid.concentricRingChunk(placement, placement.getRingCount(), seed)); assertNull(StructurePlacementGrid.concentricRingChunk(placement, placement.ringCount(), seed));
} }
@Test @Test
public void placementRngIsStableAndPlacementIdScoped() { public void placementRngIsStableAndPlacementIdScoped() {
IrisStructurePlacement placement = placement(StructureDistribution.RANDOM_SPREAD); StructurePlacement placement = placement(StructureDistribution.RANDOM_SPREAD);
long first = StructurePlacementGrid.placementRng(placement, 7, -11, 123L).getSeed(); long first = StructurePlacementGrid.placementRng(placement, 7, -11, 123L).getSeed();
long repeated = StructurePlacementGrid.placementRng(placement, 7, -11, 123L).getSeed(); long repeated = StructurePlacementGrid.placementRng(placement, 7, -11, 123L).getSeed();
placement.setPlacementId("second"); TestSettings.with(placement, "placementId", "second");
long secondPlacement = StructurePlacementGrid.placementRng(placement, 7, -11, 123L).getSeed(); long secondPlacement = StructurePlacementGrid.placementRng(placement, 7, -11, 123L).getSeed();
assertEquals(first, repeated); assertEquals(first, repeated);
assertNotEquals(first, secondPlacement); assertNotEquals(first, secondPlacement);
@@ -170,24 +172,24 @@ public class StructurePlacementGridTest {
@Test @Test
public void authoredPlacementIdSeparatesRandomSpreadStarts() { public void authoredPlacementIdSeparatesRandomSpreadStarts() {
IrisStructurePlacement first = placement(StructureDistribution.RANDOM_SPREAD); StructurePlacement first = placement(StructureDistribution.RANDOM_SPREAD);
first.setPlacementId("first"); TestSettings.with(first, "placementId", "first");
IrisStructurePlacement second = placement(StructureDistribution.RANDOM_SPREAD); StructurePlacement second = placement(StructureDistribution.RANDOM_SPREAD);
second.setPlacementId("second"); TestSettings.with(second, "placementId", "second");
int[] firstStart = StructurePlacementGrid.randomSpreadCellChunk( int[] firstStart = StructurePlacementGrid.randomSpreadCellChunk(
8, -3, first.getSpacing(), first.getSeparation(), StructurePlacementGrid.placementSalt(first), 31337L); 8, -3, first.spacing(), first.separation(), StructurePlacementGrid.placementSalt(first), 31337L);
int[] secondStart = StructurePlacementGrid.randomSpreadCellChunk( int[] secondStart = StructurePlacementGrid.randomSpreadCellChunk(
8, -3, second.getSpacing(), second.getSeparation(), StructurePlacementGrid.placementSalt(second), 31337L); 8, -3, second.spacing(), second.separation(), StructurePlacementGrid.placementSalt(second), 31337L);
assertFalse(firstStart[0] == secondStart[0] && firstStart[1] == secondStart[1]); assertFalse(firstStart[0] == secondStart[0] && firstStart[1] == secondStart[1]);
} }
@Test @Test
public void blankIdsDeriveDistinctStableRandomSpreadGridsFromContent() { public void blankIdsDeriveDistinctStableRandomSpreadGridsFromContent() {
IrisStructurePlacement first = placement(StructureDistribution.RANDOM_SPREAD); StructurePlacement first = placement(StructureDistribution.RANDOM_SPREAD);
IrisStructurePlacement recreatedFirst = placement(StructureDistribution.RANDOM_SPREAD); StructurePlacement recreatedFirst = placement(StructureDistribution.RANDOM_SPREAD);
IrisStructurePlacement second = placement(StructureDistribution.RANDOM_SPREAD); StructurePlacement second = placement(StructureDistribution.RANDOM_SPREAD);
second.getStructures().clear(); TestSettings.with(second, "structures", new java.util.ArrayList<>());
second.getStructures().add("test:other"); withAdded(second, "structures", "test:other");
assertEquals(StructurePlacementGrid.placementSalt(first), assertEquals(StructurePlacementGrid.placementSalt(first),
StructurePlacementGrid.placementSalt(recreatedFirst)); StructurePlacementGrid.placementSalt(recreatedFirst));
@@ -196,10 +198,10 @@ public class StructurePlacementGridTest {
boolean differs = false; boolean differs = false;
for (int cell = -8; cell <= 8; cell++) { for (int cell = -8; cell <= 8; cell++) {
int[] firstStart = StructurePlacementGrid.randomSpreadCellChunk( int[] firstStart = StructurePlacementGrid.randomSpreadCellChunk(
cell, cell + 3, first.getSpacing(), first.getSeparation(), cell, cell + 3, first.spacing(), first.separation(),
StructurePlacementGrid.placementSalt(first), 31337L); StructurePlacementGrid.placementSalt(first), 31337L);
int[] secondStart = StructurePlacementGrid.randomSpreadCellChunk( int[] secondStart = StructurePlacementGrid.randomSpreadCellChunk(
cell, cell + 3, second.getSpacing(), second.getSeparation(), cell, cell + 3, second.spacing(), second.separation(),
StructurePlacementGrid.placementSalt(second), 31337L); StructurePlacementGrid.placementSalt(second), 31337L);
differs |= firstStart[0] != secondStart[0] || firstStart[1] != secondStart[1]; differs |= firstStart[0] != secondStart[0] || firstStart[1] != secondStart[1];
} }
@@ -208,12 +210,12 @@ public class StructurePlacementGridTest {
@Test @Test
public void anonymousIdentityPreservesAuthoredSourceOrder() { public void anonymousIdentityPreservesAuthoredSourceOrder() {
IrisStructurePlacement first = placement(StructureDistribution.RANDOM_SPREAD); StructurePlacement first = placement(StructureDistribution.RANDOM_SPREAD);
first.getStructures().add("test:second"); withAdded(first, "structures", "test:second");
IrisStructurePlacement reordered = placement(StructureDistribution.RANDOM_SPREAD); StructurePlacement reordered = placement(StructureDistribution.RANDOM_SPREAD);
reordered.getStructures().clear(); TestSettings.with(reordered, "structures", new java.util.ArrayList<>());
reordered.getStructures().add("test:second"); withAdded(reordered, "structures", "test:second");
reordered.getStructures().add("test:structure"); withAdded(reordered, "structures", "test:structure");
assertNotEquals(StructurePlacementGrid.placementIdentity(first), assertNotEquals(StructurePlacementGrid.placementIdentity(first),
StructurePlacementGrid.placementIdentity(reordered)); StructurePlacementGrid.placementIdentity(reordered));
@@ -225,17 +227,17 @@ public class StructurePlacementGridTest {
@Test @Test
public void blankIdsDeriveDistinctStableConcentricRingsFromContent() { public void blankIdsDeriveDistinctStableConcentricRingsFromContent() {
IrisStructurePlacement first = placement(StructureDistribution.CONCENTRIC_RINGS); StructurePlacement first = placement(StructureDistribution.CONCENTRIC_RINGS);
IrisStructurePlacement recreatedFirst = placement(StructureDistribution.CONCENTRIC_RINGS); StructurePlacement recreatedFirst = placement(StructureDistribution.CONCENTRIC_RINGS);
IrisStructurePlacement second = placement(StructureDistribution.CONCENTRIC_RINGS); StructurePlacement second = placement(StructureDistribution.CONCENTRIC_RINGS);
second.getStructures().clear(); TestSettings.with(second, "structures", new java.util.ArrayList<>());
second.getStructures().add("test:other"); withAdded(second, "structures", "test:other");
first.setRingCount(12); TestSettings.with(first, "ringCount", 12);
recreatedFirst.setRingCount(12); TestSettings.with(recreatedFirst, "ringCount", 12);
second.setRingCount(12); TestSettings.with(second, "ringCount", 12);
boolean differs = false; boolean differs = false;
for (int index = 0; index < first.getRingCount(); index++) { for (int index = 0; index < first.ringCount(); index++) {
int[] firstPoint = StructurePlacementGrid.concentricRingChunk(first, index, 77123L); int[] firstPoint = StructurePlacementGrid.concentricRingChunk(first, index, 77123L);
int[] recreatedPoint = StructurePlacementGrid.concentricRingChunk(recreatedFirst, index, 77123L); int[] recreatedPoint = StructurePlacementGrid.concentricRingChunk(recreatedFirst, index, 77123L);
int[] secondPoint = StructurePlacementGrid.concentricRingChunk(second, index, 77123L); int[] secondPoint = StructurePlacementGrid.concentricRingChunk(second, index, 77123L);
@@ -248,9 +250,9 @@ public class StructurePlacementGridTest {
@Test @Test
public void derivedPlacementIdentityIncludesPlacementSettings() { public void derivedPlacementIdentityIncludesPlacementSettings() {
IrisStructurePlacement first = placement(StructureDistribution.DENSITY); StructurePlacement first = placement(StructureDistribution.DENSITY);
IrisStructurePlacement second = placement(StructureDistribution.DENSITY); StructurePlacement second = placement(StructureDistribution.DENSITY);
second.setMinHeight(first.getMinHeight() + 1); TestSettings.with(second, "minHeight", first.minHeight() + 1);
long firstSeed = StructurePlacementGrid.placementRng(first, 9, 14, 42L).getSeed(); long firstSeed = StructurePlacementGrid.placementRng(first, 9, 14, 42L).getSeed();
long secondSeed = StructurePlacementGrid.placementRng(second, 9, 14, 42L).getSeed(); long secondSeed = StructurePlacementGrid.placementRng(second, 9, 14, 42L).getSeed();
assertNotEquals(firstSeed, secondSeed); assertNotEquals(firstSeed, secondSeed);
@@ -258,9 +260,8 @@ public class StructurePlacementGridTest {
@Test @Test
public void legacyAnchorDoesNotMoveExistingPlacements() { public void legacyAnchorDoesNotMoveExistingPlacements() {
IrisStructurePlacement implicit = placement(StructureDistribution.RANDOM_SPREAD); StructurePlacement implicit = placement(StructureDistribution.RANDOM_SPREAD);
IrisStructurePlacement explicit = placement(StructureDistribution.RANDOM_SPREAD) StructurePlacement explicit = TestSettings.with(placement(StructureDistribution.RANDOM_SPREAD), "anchor", StructureAnchorMode.LEGACY);
.setAnchor(IrisStructureAnchorMode.LEGACY);
assertEquals(StructurePlacementGrid.placementIdentity(implicit), assertEquals(StructurePlacementGrid.placementIdentity(implicit),
StructurePlacementGrid.placementIdentity(explicit)); StructurePlacementGrid.placementIdentity(explicit));
@@ -270,10 +271,8 @@ public class StructurePlacementGridTest {
@Test @Test
public void caveAnchorConfigurationParticipatesInAnonymousIdentity() { public void caveAnchorConfigurationParticipatesInAnonymousIdentity() {
IrisStructurePlacement floor = placement(StructureDistribution.RANDOM_SPREAD) StructurePlacement floor = TestSettings.with(placement(StructureDistribution.RANDOM_SPREAD), "anchor", StructureAnchorMode.CAVE_FLOOR);
.setAnchor(IrisStructureAnchorMode.CAVE_FLOOR); StructurePlacement ceiling = TestSettings.with(placement(StructureDistribution.RANDOM_SPREAD), "anchor", StructureAnchorMode.CAVE_CEILING);
IrisStructurePlacement ceiling = placement(StructureDistribution.RANDOM_SPREAD)
.setAnchor(IrisStructureAnchorMode.CAVE_CEILING);
assertNotEquals(StructurePlacementGrid.placementIdentity(floor), assertNotEquals(StructurePlacementGrid.placementIdentity(floor),
StructurePlacementGrid.placementIdentity(ceiling)); StructurePlacementGrid.placementIdentity(ceiling));
@@ -283,14 +282,9 @@ public class StructurePlacementGridTest {
@Test @Test
public void unusedCaveSettingsDoNotMoveExplicitSurfacePlacements() { public void unusedCaveSettingsDoNotMoveExplicitSurfacePlacements() {
IrisStructurePlacement first = placement(StructureDistribution.RANDOM_SPREAD) StructurePlacement first = TestSettings.with(placement(StructureDistribution.RANDOM_SPREAD), "anchor", StructureAnchorMode.SURFACE);
.setAnchor(IrisStructureAnchorMode.SURFACE); StructurePlacement second = TestSettings.with(placement(StructureDistribution.RANDOM_SPREAD), "anchor", StructureAnchorMode.SURFACE, "caveAnchorAttempts", 64, "caveAnchorScanStep", 16, "caveMinimumClearance", 64);
IrisStructurePlacement second = placement(StructureDistribution.RANDOM_SPREAD) withAdded(second, "caveBiomes", "unused");
.setAnchor(IrisStructureAnchorMode.SURFACE)
.setCaveAnchorAttempts(64)
.setCaveAnchorScanStep(16)
.setCaveMinimumClearance(64);
second.getCaveBiomes().add("unused");
assertEquals(StructurePlacementGrid.placementIdentity(first), assertEquals(StructurePlacementGrid.placementIdentity(first),
StructurePlacementGrid.placementIdentity(second)); StructurePlacementGrid.placementIdentity(second));
@@ -300,16 +294,14 @@ public class StructurePlacementGridTest {
@Test @Test
public void caveBiomeAllowlistIdentityIgnoresOrderCaseWhitespaceAndDuplicates() { public void caveBiomeAllowlistIdentityIgnoresOrderCaseWhitespaceAndDuplicates() {
IrisStructurePlacement first = placement(StructureDistribution.RANDOM_SPREAD) StructurePlacement first = TestSettings.with(placement(StructureDistribution.RANDOM_SPREAD), "anchor", StructureAnchorMode.CAVE_CENTER);
.setAnchor(IrisStructureAnchorMode.CAVE_CENTER); withAdded(first, "caveBiomes", "crystal");
first.getCaveBiomes().add("crystal"); withAdded(first, "caveBiomes", "deep");
first.getCaveBiomes().add("deep"); StructurePlacement second = TestSettings.with(placement(StructureDistribution.RANDOM_SPREAD), "anchor", StructureAnchorMode.CAVE_CENTER);
IrisStructurePlacement second = placement(StructureDistribution.RANDOM_SPREAD) withAdded(second, "caveBiomes", " DEEP ");
.setAnchor(IrisStructureAnchorMode.CAVE_CENTER); withAdded(second, "caveBiomes", "CRYSTAL");
second.getCaveBiomes().add(" DEEP "); withAdded(second, "caveBiomes", "crystal");
second.getCaveBiomes().add("CRYSTAL"); withAdded(second, "caveBiomes", " ");
second.getCaveBiomes().add("crystal");
second.getCaveBiomes().add(" ");
assertEquals(StructurePlacementGrid.placementIdentity(first), assertEquals(StructurePlacementGrid.placementIdentity(first),
StructurePlacementGrid.placementIdentity(second)); StructurePlacementGrid.placementIdentity(second));
@@ -319,22 +311,22 @@ public class StructurePlacementGridTest {
@Test @Test
public void explicitPlacementIdentityKeepsRngStableAcrossSettingEdits() { public void explicitPlacementIdentityKeepsRngStableAcrossSettingEdits() {
IrisStructurePlacement first = placement(StructureDistribution.DENSITY); StructurePlacement first = placement(StructureDistribution.DENSITY);
first.setPlacementId("stable"); TestSettings.with(first, "placementId", "stable");
IrisStructurePlacement second = placement(StructureDistribution.DENSITY); StructurePlacement second = placement(StructureDistribution.DENSITY);
second.setPlacementId("stable"); TestSettings.with(second, "placementId", "stable");
second.setMinHeight(first.getMinHeight() + 1); TestSettings.with(second, "minHeight", first.minHeight() + 1);
second.setDensity(0.75); TestSettings.with(second, "density", 0.75);
long firstSeed = StructurePlacementGrid.placementRng(first, 9, 14, 42L).getSeed(); long firstSeed = StructurePlacementGrid.placementRng(first, 9, 14, 42L).getSeed();
long secondSeed = StructurePlacementGrid.placementRng(second, 9, 14, 42L).getSeed(); long secondSeed = StructurePlacementGrid.placementRng(second, 9, 14, 42L).getSeed();
assertEquals(firstSeed, secondSeed); assertEquals(firstSeed, secondSeed);
} }
private IrisStructurePlacement placement(StructureDistribution distribution) { private StructurePlacement placement(StructureDistribution distribution) {
IrisStructurePlacement placement = new IrisStructurePlacement(); StructurePlacement placement = new StructurePlacement();
placement.setDistribution(distribution); TestSettings.with(placement, "distribution", distribution);
placement.getStructures().add("test:structure"); withAdded(placement, "structures", "test:structure");
placement.setSalt(31415926); TestSettings.with(placement, "salt", 31415926);
return placement; return placement;
} }
} }
@@ -4,11 +4,14 @@ import art.arcane.iris.engine.IrisComplex;
import art.arcane.iris.engine.object.world.biome.IrisBiome; import art.arcane.iris.engine.object.world.biome.IrisBiome;
import art.arcane.iris.engine.object.world.dimension.IrisDimension; import art.arcane.iris.engine.object.world.dimension.IrisDimension;
import art.arcane.iris.engine.object.world.region.IrisRegion; import art.arcane.iris.engine.object.world.region.IrisRegion;
import art.arcane.iris.engine.object.structure.IrisStructureAnchorMode; import art.arcane.iris.builtin.structure.StructureAnchorMode;
import art.arcane.iris.engine.object.structure.IrisStructurePlacement; import art.arcane.iris.builtin.structure.StructurePlacement;
import art.arcane.volmlib.util.collection.KList; import art.arcane.volmlib.util.collection.KList;
import org.junit.Test; import org.junit.Test;
import static art.arcane.iris.engine.framework.StructurePlacementFixtures.placement;
import static art.arcane.iris.engine.framework.StructurePlacementFixtures.declare;
import static art.arcane.iris.engine.framework.StructurePlacementFixtures.declaring;
import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue; import static org.junit.Assert.assertTrue;
@@ -21,25 +24,20 @@ import static org.mockito.Mockito.when;
public class StructurePlacementScopeTest { public class StructurePlacementScopeTest {
@Test @Test
public void caveBiomeContributesOnlyCaveAnchoredPlacements() { public void caveBiomeContributesOnlyCaveAnchoredPlacements() {
IrisStructurePlacement surfacePlacement = new IrisStructurePlacement(); StructurePlacement surfacePlacement = new StructurePlacement();
IrisStructurePlacement cavePlacement = new IrisStructurePlacement() StructurePlacement cavePlacement = placement("anchor", StructureAnchorMode.CAVE_FLOOR);
.setAnchor(IrisStructureAnchorMode.CAVE_FLOOR); StructurePlacement invalidCaveScopePlacement = placement("anchor", StructureAnchorMode.SURFACE);
IrisStructurePlacement invalidCaveScopePlacement = new IrisStructurePlacement() StructurePlacement regionPlacement = new StructurePlacement();
.setAnchor(IrisStructureAnchorMode.SURFACE); StructurePlacement dimensionPlacement = new StructurePlacement();
IrisStructurePlacement regionPlacement = new IrisStructurePlacement();
IrisStructurePlacement dimensionPlacement = new IrisStructurePlacement();
IrisBiome surfaceBiome = new IrisBiome(); IrisBiome surfaceBiome = declare(new IrisBiome(), surfacePlacement);
surfaceBiome.getStructures().add(surfacePlacement); IrisBiome caveBiome = declare(new IrisBiome(), cavePlacement, invalidCaveScopePlacement);
IrisBiome caveBiome = new IrisBiome(); IrisRegion region = declare(new IrisRegion(), regionPlacement);
caveBiome.getStructures().add(cavePlacement);
caveBiome.getStructures().add(invalidCaveScopePlacement);
IrisRegion region = new IrisRegion();
region.getStructures().add(regionPlacement);
Engine engine = mock(Engine.class, RETURNS_DEEP_STUBS); Engine engine = mock(Engine.class, RETURNS_DEEP_STUBS);
when(engine.getGeneration()).thenReturn(new EngineGeneration(engine));
IrisComplex complex = engine.getComplex(); IrisComplex complex = engine.getComplex();
IrisDimension dimension = mock(IrisDimension.class); IrisDimension dimension = mock(IrisDimension.class);
KList<IrisStructurePlacement> dimensionStructures = new KList<>(); KList<StructurePlacement> dimensionStructures = new KList<>();
dimensionStructures.add(dimensionPlacement); dimensionStructures.add(dimensionPlacement);
dimensionStructures.add(cavePlacement); dimensionStructures.add(cavePlacement);
KList<IrisRegion> allRegions = new KList<>(); KList<IrisRegion> allRegions = new KList<>();
@@ -49,13 +47,13 @@ public class StructurePlacementScopeTest {
allBiomes.add(caveBiome); allBiomes.add(caveBiome);
when(engine.getDimension()).thenReturn(dimension); when(engine.getDimension()).thenReturn(dimension);
when(engine.getAllBiomes()).thenReturn(allBiomes); when(engine.getAllBiomes()).thenReturn(allBiomes);
when(dimension.getStructures()).thenReturn(dimensionStructures); when(dimension.getModuleSettings()).thenReturn(declaring(dimensionStructures));
when(dimension.getAllRegions(engine)).thenReturn(allRegions); when(dimension.getAllRegions(engine)).thenReturn(allRegions);
when(complex.getTrueBiomeStream().get(8, 8)).thenReturn(surfaceBiome); when(complex.getTrueBiomeStream().get(8, 8)).thenReturn(surfaceBiome);
when(complex.getCaveBiomeStream().get(8, 8)).thenReturn(caveBiome); when(complex.getCaveBiomeStream().get(8, 8)).thenReturn(caveBiome);
when(complex.getRegionStream().get(8, 8)).thenReturn(region); when(complex.getRegionStream().get(8, 8)).thenReturn(region);
KList<IrisStructurePlacement> placements = StructurePlacementScope.placementsAt(engine, 0, 0); KList<StructurePlacement> placements = StructurePlacementScope.placementsAt(engine, 0, 0);
assertEquals(4, placements.size()); assertEquals(4, placements.size());
assertTrue(placements.contains(surfacePlacement)); assertTrue(placements.contains(surfacePlacement));
@@ -67,18 +65,19 @@ public class StructurePlacementScopeTest {
@Test @Test
public void dimensionOnlyPlacementsDoNotResolveBiomeScopes() { public void dimensionOnlyPlacementsDoNotResolveBiomeScopes() {
IrisStructurePlacement dimensionPlacement = new IrisStructurePlacement(); StructurePlacement dimensionPlacement = new StructurePlacement();
Engine engine = mock(Engine.class, RETURNS_DEEP_STUBS); Engine engine = mock(Engine.class, RETURNS_DEEP_STUBS);
when(engine.getGeneration()).thenReturn(new EngineGeneration(engine));
IrisComplex complex = engine.getComplex(); IrisComplex complex = engine.getComplex();
IrisDimension dimension = mock(IrisDimension.class); IrisDimension dimension = mock(IrisDimension.class);
KList<IrisStructurePlacement> dimensionStructures = new KList<>(); KList<StructurePlacement> dimensionStructures = new KList<>();
dimensionStructures.add(dimensionPlacement); dimensionStructures.add(dimensionPlacement);
when(engine.getDimension()).thenReturn(dimension); when(engine.getDimension()).thenReturn(dimension);
when(engine.getAllBiomes()).thenReturn(new KList<>()); when(engine.getAllBiomes()).thenReturn(new KList<>());
when(dimension.getStructures()).thenReturn(dimensionStructures); when(dimension.getModuleSettings()).thenReturn(declaring(dimensionStructures));
when(dimension.getAllRegions(engine)).thenReturn(new KList<>()); when(dimension.getAllRegions(engine)).thenReturn(new KList<>());
KList<IrisStructurePlacement> placements = StructurePlacementScope.placementsAt(engine, 0, 0); KList<StructurePlacement> placements = StructurePlacementScope.placementsAt(engine, 0, 0);
assertEquals(1, placements.size()); assertEquals(1, placements.size());
assertTrue(placements.contains(dimensionPlacement)); assertTrue(placements.contains(dimensionPlacement));
@@ -87,12 +87,6 @@ public class StructureReachabilityContractTest {
() -> StructureReachability.missingBiomeKeys(engine, "minecraft:village_taiga")); () -> StructureReachability.missingBiomeKeys(engine, "minecraft:village_taiga"));
} }
@Test
public void invalidateIsNullSafe() {
StructureReachability.invalidate(null);
StructureReachability.invalidate(mock(Engine.class));
}
@Test @Test
public void failedReachabilityBuildIsNotCachedAsEmpty() { public void failedReachabilityBuildIsNotCachedAsEmpty() {
Engine engine = mock(Engine.class); Engine engine = mock(Engine.class);
@@ -102,6 +96,7 @@ public class StructureReachabilityContractTest {
PlatformStructureHooks hooks = mock(PlatformStructureHooks.class); PlatformStructureHooks hooks = mock(PlatformStructureHooks.class);
IllegalStateException cause = new IllegalStateException("registry unavailable"); IllegalStateException cause = new IllegalStateException("registry unavailable");
when(engine.getData()).thenReturn(mock(IrisData.class)); when(engine.getData()).thenReturn(mock(IrisData.class));
when(engine.getGeneration()).thenReturn(new EngineGeneration(engine));
when(engine.getWorld()).thenReturn(world); when(engine.getWorld()).thenReturn(world);
when(world.platformWorld()).thenReturn(platformWorld); when(world.platformWorld()).thenReturn(platformWorld);
when(platform.structureHooks()).thenReturn(hooks); when(platform.structureHooks()).thenReturn(hooks);
@@ -115,7 +110,6 @@ public class StructureReachabilityContractTest {
assertThrows(IllegalStateException.class, () -> StructureReachability.reachableKeys(engine)); assertThrows(IllegalStateException.class, () -> StructureReachability.reachableKeys(engine));
assertTrue(StructureReachability.reachableKeys(engine).contains("minecraft:monument")); assertTrue(StructureReachability.reachableKeys(engine).contains("minecraft:monument"));
} finally { } finally {
StructureReachability.invalidate(engine);
IrisPlatforms.unbind(); IrisPlatforms.unbind();
} }
} }
@@ -1,6 +1,8 @@
package art.arcane.iris.engine.framework.structure; package art.arcane.iris.engine.framework.structure;
import art.arcane.iris.core.loader.IrisData;
import art.arcane.iris.engine.framework.Engine; import art.arcane.iris.engine.framework.Engine;
import art.arcane.iris.engine.framework.EngineGeneration;
import art.arcane.iris.engine.framework.SeedManager; import art.arcane.iris.engine.framework.SeedManager;
import art.arcane.iris.engine.framework.StructurePlacementGrid; import art.arcane.iris.engine.framework.StructurePlacementGrid;
import art.arcane.iris.builtin.structure.StructureStilts; import art.arcane.iris.builtin.structure.StructureStilts;
@@ -8,22 +10,27 @@ import art.arcane.iris.builtin.structure.StructureTerrain;
import art.arcane.iris.builtin.structure.StructureTerrainMode; import art.arcane.iris.builtin.structure.StructureTerrainMode;
import com.google.gson.Gson; import com.google.gson.Gson;
import com.volmit.vanilla.JigsawOverrides; import com.volmit.vanilla.JigsawOverrides;
import art.arcane.iris.engine.object.structure.vanilla.NativeStructureSuppression; import art.arcane.iris.builtin.structure.NativeStructureSuppression;
import com.volmit.resource.ResourceId; import com.volmit.resource.ResourceId;
import com.volmit.vanilla.VanillaStructureStart; import com.volmit.vanilla.VanillaStructureStart;
import java.util.List; import java.util.List;
import java.util.Optional; import java.util.Optional;
import java.util.OptionalInt; import java.util.OptionalInt;
import art.arcane.iris.engine.object.structure.vanilla.IrisNativeStructure; import art.arcane.iris.builtin.structure.NativeStructureSource;
import art.arcane.iris.engine.object.world.dimension.IrisDimension; import art.arcane.iris.engine.object.world.dimension.IrisDimension;
import art.arcane.iris.engine.object.structure.IrisStructureAnchorMode; import art.arcane.iris.builtin.structure.StructureAnchorMode;
import art.arcane.iris.engine.object.structure.IrisStructurePlacement; import art.arcane.iris.builtin.structure.StructurePlacement;
import art.arcane.iris.engine.object.structure.StructureDistribution; import art.arcane.iris.builtin.structure.StructureDistribution;
import art.arcane.volmlib.util.collection.KList; import art.arcane.volmlib.util.collection.KList;
import art.arcane.volmlib.util.math.RNG; import art.arcane.volmlib.util.math.RNG;
import org.junit.Test; import org.junit.Test;
import art.arcane.iris.engine.object.TestSettings;
import static art.arcane.iris.engine.framework.StructurePlacementFixtures.placement;
import static art.arcane.iris.engine.framework.StructurePlacementFixtures.nativeSource;
import static art.arcane.iris.engine.framework.StructurePlacementFixtures.declaring;
import static art.arcane.iris.engine.framework.StructurePlacementFixtures.withAdded;
import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull; import static org.junit.Assert.assertNull;
@@ -38,17 +45,14 @@ public class NativeStartPlannerTest {
@Test @Test
public void undergroundPlanIsDeterministicAndUsesConfiguredBand() { public void undergroundPlanIsDeterministicAndUsesConfiguredBand() {
Engine engine = engine(982374L, -64, 384, 90); Engine engine = engine(982374L, -64, 384, 90);
IrisStructurePlacement placement = nativePlacement() StructurePlacement placement = TestSettings.with(nativePlacement(), "underground", true, "minHeight", -45, "maxHeight", -20);
.setUnderground(true)
.setMinHeight(-45)
.setMaxHeight(-20);
NativeStartPlanner.Plan first = NativeStartPlanner.planAt(engine, placement, 12, -7); NativeStartPlanner.Plan first = NativeStartPlanner.planAt(engine, placement, 12, -7);
NativeStartPlanner.Plan second = NativeStartPlanner.planAt(engine, placement, 12, -7); NativeStartPlanner.Plan second = NativeStartPlanner.planAt(engine, placement, 12, -7);
assertNotNull(first); assertNotNull(first);
assertEquals(first, second); assertEquals(first, second);
assertEquals("minecraft:ancient_city", first.source().getStructure()); assertEquals("minecraft:ancient_city", first.source().structure());
assertEquals(12, first.chunkX()); assertEquals(12, first.chunkX());
assertEquals(-7, first.chunkZ()); assertEquals(-7, first.chunkZ());
assertTrue(first.baseY() >= -45 && first.baseY() <= -20); assertTrue(first.baseY() >= -45 && first.baseY() <= -20);
@@ -57,10 +61,7 @@ public class NativeStartPlannerTest {
@Test @Test
public void undergroundBandOutsideWorldBoundsSkipsTheCandidate() { public void undergroundBandOutsideWorldBoundsSkipsTheCandidate() {
Engine engine = engine(982374L, -64, 384, 90); Engine engine = engine(982374L, -64, 384, 90);
IrisStructurePlacement placement = nativePlacement() StructurePlacement placement = TestSettings.with(nativePlacement(), "underground", true, "minHeight", 500, "maxHeight", 600);
.setUnderground(true)
.setMinHeight(500)
.setMaxHeight(600);
assertNull(NativeStartPlanner.planAt(engine, placement, 12, -7)); assertNull(NativeStartPlanner.planAt(engine, placement, 12, -7));
} }
@@ -68,16 +69,14 @@ public class NativeStartPlannerTest {
@Test @Test
public void surfacePlanUsesIrisTerrainAndHonorsHeightGate() { public void surfacePlanUsesIrisTerrainAndHonorsHeightGate() {
Engine engine = engine(77L, -64, 384, 150); Engine engine = engine(77L, -64, 384, 150);
IrisStructurePlacement placement = nativePlacement() StructurePlacement placement = TestSettings.with(nativePlacement(), "minHeight", 80, "maxHeight", 90);
.setMinHeight(80)
.setMaxHeight(90);
NativeStartPlanner.Plan plan = NativeStartPlanner.planAt(engine, placement, 0, 0); NativeStartPlanner.Plan plan = NativeStartPlanner.planAt(engine, placement, 0, 0);
assertNotNull(plan); assertNotNull(plan);
assertEquals(86, plan.baseY()); assertEquals(86, plan.baseY());
placement.setMinHeight(87); TestSettings.with(placement, "minHeight", 87);
assertNull(NativeStartPlanner.planAt(engine, placement, 0, 0)); assertNull(NativeStartPlanner.planAt(engine, placement, 0, 0));
} }
@@ -85,14 +84,10 @@ public class NativeStartPlannerTest {
public void aPlanBecomesAStartWithHeightsAboveTheBottomAndThePlacementsFitAndIdentity() { public void aPlanBecomesAStartWithHeightsAboveTheBottomAndThePlacementsFitAndIdentity() {
Gson json = new Gson(); Gson json = new Gson();
StructureTerrain terrain = json.fromJson("{\"mode\":\"FORCE_CARVE\",\"horizontalPadding\":24}", StructureTerrain.class); StructureTerrain terrain = json.fromJson("{\"mode\":\"FORCE_CARVE\",\"horizontalPadding\":24}", StructureTerrain.class);
IrisStructurePlacement placement = nativePlacement() StructurePlacement placement = TestSettings.with(nativePlacement(), "underground", true, "nativeSuppression", NativeStructureSuppression.REPLACE_SOURCE, "terrain", terrain, "stilt", json.fromJson("{\"spacing\":3}", StructureStilts.class));
.setUnderground(true) TestSettings.with(placement.nativeStructures().getFirst(), "jigsaw", JigsawOverrides.none().withMaxDepth(4));
.setNativeSuppression(NativeStructureSuppression.REPLACE_SOURCE)
.setTerrain(terrain)
.setStilt(json.fromJson("{\"spacing\":3}", StructureStilts.class));
placement.getNativeStructures().getFirst().setJigsaw(JigsawOverrides.none().withMaxDepth(4));
NativeStartPlanner.Plan plan = new NativeStartPlanner.Plan( NativeStartPlanner.Plan plan = new NativeStartPlanner.Plan(
placement, placement.getNativeStructures().getFirst(), 3, 5, -30); placement, placement.nativeStructures().getFirst(), 3, 5, -30);
VanillaStructureStart start = StructureVanillaStructures.start(plan, -64); VanillaStructureStart start = StructureVanillaStructures.start(plan, -64);
@@ -108,45 +103,45 @@ public class NativeStartPlannerTest {
assertEquals(OptionalInt.of(4), start.jigsaw().orElseThrow().maxDepth()); assertEquals(OptionalInt.of(4), start.jigsaw().orElseThrow().maxDepth());
assertEquals("a source without jigsaw overrides has none", Optional.empty(), assertEquals("a source without jigsaw overrides has none", Optional.empty(),
StructureVanillaStructures.start(new NativeStartPlanner.Plan(nativePlacement(), StructureVanillaStructures.start(new NativeStartPlanner.Plan(nativePlacement(),
nativePlacement().getNativeStructures().getFirst(), 0, 0, 70), -64).jigsaw()); nativePlacement().nativeStructures().getFirst(), 0, 0, 70), -64).jigsaw());
} }
@Test @Test
public void underwaterFlagRejectsSubmergedColumnsForSurfaceAndUndergroundPlans() { public void underwaterFlagRejectsSubmergedColumnsForSurfaceAndUndergroundPlans() {
Engine engine = engine(77L, -64, 384, 63); Engine engine = engine(77L, -64, 384, 63);
IrisStructurePlacement placement = nativePlacement(); StructurePlacement placement = nativePlacement();
assertNull(NativeStartPlanner.planAt(engine, placement, 0, 0)); assertNull(NativeStartPlanner.planAt(engine, placement, 0, 0));
placement.setUnderground(true).setMinHeight(-40).setMaxHeight(-20); TestSettings.with(placement, "underground", true, "minHeight", -40, "maxHeight", -20);
assertNull(NativeStartPlanner.planAt(engine, placement, 0, 0)); assertNull(NativeStartPlanner.planAt(engine, placement, 0, 0));
placement.setUnderwater(true); TestSettings.with(placement, "underwater", true);
assertNotNull(NativeStartPlanner.planAt(engine, placement, 0, 0)); assertNotNull(NativeStartPlanner.planAt(engine, placement, 0, 0));
} }
@Test @Test
public void fluidHeightBoundaryIsShoreForPlannerAndLocator() { public void fluidHeightBoundaryIsShoreForPlannerAndLocator() {
Engine engine = engine(77L, -64, 384, 64); Engine engine = engine(77L, -64, 384, 64);
IrisStructurePlacement placement = nativePlacement(); StructurePlacement placement = nativePlacement();
assertTrue(!NativeStartPlanner.isSubmerged(engine, 8, 8)); assertTrue(!NativeStartPlanner.isSubmerged(engine, 8, 8));
assertNotNull(NativeStartPlanner.planAt(engine, placement, 0, 0)); assertNotNull(NativeStartPlanner.planAt(engine, placement, 0, 0));
placement.setUnderground(true).setMinHeight(-40).setMaxHeight(-20); TestSettings.with(placement, "underground", true, "minHeight", -40, "maxHeight", -20);
assertNotNull(NativeStartPlanner.planAt(engine, placement, 0, 0)); assertNotNull(NativeStartPlanner.planAt(engine, placement, 0, 0));
} }
@Test @Test
public void duplicateSelectedStructureUsesOneDeterministicPlan() { public void duplicateSelectedStructureUsesOneDeterministicPlan() {
Engine engine = engine(77L, -64, 384, 150); Engine engine = engine(77L, -64, 384, 150);
IrisStructurePlacement first = nativePlacement().setPlacementId("first"); StructurePlacement first = TestSettings.with(nativePlacement(), "placementId", "first");
IrisStructurePlacement second = nativePlacement().setPlacementId("second"); StructurePlacement second = TestSettings.with(nativePlacement(), "placementId", "second");
bindPlacements(engine, first, second); bindPlacements(engine, first, second);
List<NativeStartPlanner.Plan> plans = NativeStartPlanner.plansAt(engine, 0, 0); List<NativeStartPlanner.Plan> plans = NativeStartPlanner.plansAt(engine, 0, 0);
IrisStructurePlacement expected = Long.compareUnsigned( StructurePlacement expected = Long.compareUnsigned(
StructurePlacementGrid.placementIdentity(first), StructurePlacementGrid.placementIdentity(first),
StructurePlacementGrid.placementIdentity(second)) <= 0 ? first : second; StructurePlacementGrid.placementIdentity(second)) <= 0 ? first : second;
assertEquals(1, plans.size()); assertEquals(1, plans.size());
@@ -155,10 +150,10 @@ public class NativeStartPlannerTest {
@Test @Test
public void weightedNativeSelectionPreservesAuthoredSourceOrder() { public void weightedNativeSelectionPreservesAuthoredSourceOrder() {
KList<IrisNativeStructure> first = new KList<>(); KList<NativeStructureSource> first = new KList<>();
first.add(new IrisNativeStructure().setStructure("test:a").setWeight(1)); first.add(nativeSource("test:a", 1));
first.add(new IrisNativeStructure().setStructure("test:b").setWeight(3)); first.add(nativeSource("test:b", 3));
KList<IrisNativeStructure> reordered = new KList<>(); KList<NativeStructureSource> reordered = new KList<>();
reordered.add(first.get(1)); reordered.add(first.get(1));
reordered.add(first.get(0)); reordered.add(first.get(0));
@@ -169,33 +164,29 @@ public class NativeStartPlannerTest {
} }
}; };
assertEquals("test:a", NativeStartPlanner assertEquals("test:a", NativeStartPlanner
.selectSource(first, selectsFirstWeightSlot).getStructure()); .selectSource(first, selectsFirstWeightSlot).structure());
assertEquals("test:b", NativeStartPlanner assertEquals("test:b", NativeStartPlanner
.selectSource(reordered, selectsFirstWeightSlot).getStructure()); .selectSource(reordered, selectsFirstWeightSlot).structure());
} }
@Test @Test
public void placementMustChooseExactlyOneBackend() { public void placementMustChooseExactlyOneBackend() {
assertInvalid(new IrisStructurePlacement()); assertInvalid(new StructurePlacement());
IrisStructurePlacement mixed = nativePlacement(); StructurePlacement mixed = nativePlacement();
mixed.getStructures().add("legacy"); withAdded(mixed, "structures", "legacy");
assertInvalid(mixed); assertInvalid(mixed);
} }
@Test @Test
public void nativeBackendRejectsEveryExplicitIrisAnchorMode() { public void nativeBackendRejectsEveryExplicitIrisAnchorMode() {
assertUnsupportedAnchor(nativePlacement().setAnchor(IrisStructureAnchorMode.SURFACE)); assertUnsupportedAnchor(TestSettings.with(nativePlacement(), "anchor", StructureAnchorMode.SURFACE));
assertUnsupportedAnchor(nativePlacement().setAnchor(IrisStructureAnchorMode.HEIGHT_BAND)); assertUnsupportedAnchor(TestSettings.with(nativePlacement(), "anchor", StructureAnchorMode.HEIGHT_BAND));
assertUnsupportedAnchor(nativePlacement().setAnchor(IrisStructureAnchorMode.CAVE_FLOOR)); assertUnsupportedAnchor(TestSettings.with(nativePlacement(), "anchor", StructureAnchorMode.CAVE_FLOOR));
} }
private IrisStructurePlacement nativePlacement() { private StructurePlacement nativePlacement() {
IrisStructurePlacement placement = new IrisStructurePlacement() StructurePlacement placement = placement("distribution", StructureDistribution.DENSITY, "density", 1D);
.setDistribution(StructureDistribution.DENSITY) withAdded(placement, "nativeStructures", nativeSource("minecraft:ancient_city", 1));
.setDensity(1D);
placement.getNativeStructures().add(new IrisNativeStructure()
.setStructure("minecraft:ancient_city")
.setWeight(1));
return placement; return placement;
} }
@@ -213,18 +204,16 @@ public class NativeStartPlannerTest {
return engine; return engine;
} }
private void bindPlacements(Engine engine, IrisStructurePlacement... placements) { private void bindPlacements(Engine engine, StructurePlacement... placements) {
IrisDimension dimension = engine.getDimension(); IrisDimension dimension = engine.getDimension();
KList<IrisStructurePlacement> configured = new KList<>(); when(engine.getData()).thenReturn(mock(IrisData.class));
for (IrisStructurePlacement placement : placements) { when(engine.getGeneration()).thenReturn(new EngineGeneration(engine));
configured.add(placement); when(dimension.getModuleSettings()).thenReturn(declaring(placements));
}
when(dimension.getStructures()).thenReturn(configured);
when(dimension.getAllRegions(engine)).thenReturn(new KList<>()); when(dimension.getAllRegions(engine)).thenReturn(new KList<>());
when(dimension.getReachableBiomes(engine)).thenReturn(new KList<>()); when(dimension.getReachableBiomes(engine)).thenReturn(new KList<>());
} }
private void assertInvalid(IrisStructurePlacement placement) { private void assertInvalid(StructurePlacement placement) {
try { try {
NativeStartPlanner.validateBackend(placement); NativeStartPlanner.validateBackend(placement);
fail("Expected an invalid structure backend"); fail("Expected an invalid structure backend");
@@ -233,7 +222,7 @@ public class NativeStartPlannerTest {
} }
} }
private void assertUnsupportedAnchor(IrisStructurePlacement placement) { private void assertUnsupportedAnchor(StructurePlacement placement) {
try { try {
NativeStartPlanner.validateBackend(placement); NativeStartPlanner.validateBackend(placement);
fail("Expected native structure anchor rejection"); fail("Expected native structure anchor rejection");
@@ -7,10 +7,10 @@ import com.volmit.block.BlockState;
import com.volmit.block.BlockTrait; import com.volmit.block.BlockTrait;
import com.volmit.mantle.BlockBox; import com.volmit.mantle.BlockBox;
import com.volmit.resource.ResourceId; import com.volmit.resource.ResourceId;
import com.volmit.vanilla.DecorationStep;
import com.volmit.vanilla.PieceKind; import com.volmit.vanilla.PieceKind;
import com.volmit.vanilla.StartMemo; import com.volmit.vanilla.StartMemo;
import com.volmit.vanilla.StructureFit; import com.volmit.vanilla.StructureFit;
import com.volmit.vanilla.StructureStep;
import com.volmit.vanilla.TemplateCells; import com.volmit.vanilla.TemplateCells;
import com.volmit.vanilla.TerrainAdaptation; import com.volmit.vanilla.TerrainAdaptation;
import com.volmit.world.BlockAccess; import com.volmit.world.BlockAccess;
@@ -241,11 +241,11 @@ final class FitFixture {
} }
/** A start of the structure fit, with the terrain fit JSON a memo would carry and no stilts. */ /** A start of the structure fit, with the terrain fit JSON a memo would carry and no stilts. */
static FitStart start(String terrainJson, TerrainAdaptation adaptation, StructureStep step, Piece... pieces) { static FitStart start(String terrainJson, TerrainAdaptation adaptation, DecorationStep step, Piece... pieces) {
return start(terrainJson, "null", adaptation, step, pieces); return start(terrainJson, "null", adaptation, step, pieces);
} }
static FitStart start(String terrainJson, String stiltsJson, TerrainAdaptation adaptation, StructureStep step, static FitStart start(String terrainJson, String stiltsJson, TerrainAdaptation adaptation, DecorationStep step,
Piece... pieces) { Piece... pieces) {
StartMemo memo = new StartMemo(terrainJson, stiltsJson); StartMemo memo = new StartMemo(terrainJson, stiltsJson);
StructureFit.Start start = new StructureFit.Start() { StructureFit.Start start = new StructureFit.Start() {
@@ -267,7 +267,7 @@ final class FitFixture {
} }
@Override @Override
public StructureStep step() { public DecorationStep step() {
return step; return step;
} }
@@ -1,7 +1,7 @@
package art.arcane.iris.engine.framework.structure.fit; package art.arcane.iris.engine.framework.structure.fit;
import com.volmit.block.BlockState; import com.volmit.block.BlockState;
import com.volmit.vanilla.StructureStep; import com.volmit.vanilla.DecorationStep;
import com.volmit.vanilla.TerrainAdaptation; import com.volmit.vanilla.TerrainAdaptation;
import org.junit.Test; import org.junit.Test;
@@ -184,7 +184,7 @@ public class RigidSupportTest {
} }
private static FitStart start(String terrain, TerrainAdaptation adaptation, FitFixture.Piece... pieces) { private static FitStart start(String terrain, TerrainAdaptation adaptation, FitFixture.Piece... pieces) {
return FitFixture.start(terrain, adaptation, StructureStep.SURFACE_STRUCTURES, pieces); return FitFixture.start(terrain, adaptation, DecorationStep.SURFACE_STRUCTURES, pieces);
} }
private static FitFixture.World supportTerrain(Box columns) { private static FitFixture.World supportTerrain(Box columns) {
@@ -1,7 +1,7 @@
package art.arcane.iris.engine.framework.structure.fit; package art.arcane.iris.engine.framework.structure.fit;
import com.volmit.host.ModuleLogs; import com.volmit.host.ModuleLogs;
import com.volmit.vanilla.StructureStep; import com.volmit.vanilla.DecorationStep;
import com.volmit.vanilla.TerrainAdaptation; import com.volmit.vanilla.TerrainAdaptation;
import org.junit.Test; import org.junit.Test;
@@ -30,14 +30,14 @@ public class SurfaceFittingTest {
@Test @Test
public void sourceBeardAdjustmentsPrepareOnlyAtTheSurfaceStructuresStep() { public void sourceBeardAdjustmentsPrepareOnlyAtTheSurfaceStructuresStep() {
assertTrue(SurfaceFitting.shouldPrepareSurfaceTerrain(TerrainAdaptation.BEARD_THIN, StructureStep.SURFACE_STRUCTURES)); assertTrue(SurfaceFitting.shouldPrepareSurfaceTerrain(TerrainAdaptation.BEARD_THIN, DecorationStep.SURFACE_STRUCTURES));
assertFalse(SurfaceFitting.shouldPrepareSurfaceTerrain(TerrainAdaptation.BEARD_BOX, StructureStep.FLUID_SPRINGS)); assertFalse(SurfaceFitting.shouldPrepareSurfaceTerrain(TerrainAdaptation.BEARD_BOX, DecorationStep.FLUID_SPRINGS));
assertFalse(SurfaceFitting.shouldPrepareSurfaceTerrain(TerrainAdaptation.BEARD_THIN, StructureStep.UNDERGROUND_STRUCTURES)); assertFalse(SurfaceFitting.shouldPrepareSurfaceTerrain(TerrainAdaptation.BEARD_THIN, DecorationStep.UNDERGROUND_STRUCTURES));
assertFalse(SurfaceFitting.shouldPrepareSurfaceTerrain(TerrainAdaptation.BEARD_BOX, StructureStep.UNDERGROUND_DECORATION)); assertFalse(SurfaceFitting.shouldPrepareSurfaceTerrain(TerrainAdaptation.BEARD_BOX, DecorationStep.UNDERGROUND_DECORATION));
assertFalse(SurfaceFitting.shouldPrepareSurfaceTerrain(TerrainAdaptation.BEARD_THIN, StructureStep.STRONGHOLDS)); assertFalse(SurfaceFitting.shouldPrepareSurfaceTerrain(TerrainAdaptation.BEARD_THIN, DecorationStep.STRONGHOLDS));
assertFalse(SurfaceFitting.shouldPrepareSurfaceTerrain(TerrainAdaptation.BURY, StructureStep.SURFACE_STRUCTURES)); assertFalse(SurfaceFitting.shouldPrepareSurfaceTerrain(TerrainAdaptation.BURY, DecorationStep.SURFACE_STRUCTURES));
assertFalse(SurfaceFitting.shouldPrepareSurfaceTerrain(TerrainAdaptation.ENCAPSULATE, StructureStep.SURFACE_STRUCTURES)); assertFalse(SurfaceFitting.shouldPrepareSurfaceTerrain(TerrainAdaptation.ENCAPSULATE, DecorationStep.SURFACE_STRUCTURES));
assertFalse(SurfaceFitting.shouldPrepareSurfaceTerrain(TerrainAdaptation.NONE, StructureStep.FLUID_SPRINGS)); assertFalse(SurfaceFitting.shouldPrepareSurfaceTerrain(TerrainAdaptation.NONE, DecorationStep.FLUID_SPRINGS));
} }
@Test @Test
@@ -45,17 +45,17 @@ public class SurfaceFittingTest {
FitFixture.Piece piece = FitFixture.Piece.fixed(new Box(0, 64, 0, 4, 70, 4)); FitFixture.Piece piece = FitFixture.Piece.fixed(new Box(0, 64, 0, 4, 70, 4));
assertTrue(SurfaceFitting.requiresSurfaceTerrain( assertTrue(SurfaceFitting.requiresSurfaceTerrain(
FitFixture.start(SOURCE, TerrainAdaptation.BEARD_BOX, StructureStep.SURFACE_STRUCTURES, piece))); FitFixture.start(SOURCE, TerrainAdaptation.BEARD_BOX, DecorationStep.SURFACE_STRUCTURES, piece)));
assertFalse(SurfaceFitting.requiresSurfaceTerrain( assertFalse(SurfaceFitting.requiresSurfaceTerrain(
FitFixture.start(PRESERVE, TerrainAdaptation.BEARD_BOX, StructureStep.SURFACE_STRUCTURES, piece))); FitFixture.start(PRESERVE, TerrainAdaptation.BEARD_BOX, DecorationStep.SURFACE_STRUCTURES, piece)));
assertFalse(SurfaceFitting.requiresSurfaceTerrain( assertFalse(SurfaceFitting.requiresSurfaceTerrain(
FitFixture.start(SOURCE, TerrainAdaptation.NONE, StructureStep.SURFACE_STRUCTURES, piece))); FitFixture.start(SOURCE, TerrainAdaptation.NONE, DecorationStep.SURFACE_STRUCTURES, piece)));
assertTrue(SurfaceFitting.requiresSurfaceTerrain( assertTrue(SurfaceFitting.requiresSurfaceTerrain(
FitFixture.start(VACUUM, TerrainAdaptation.NONE, StructureStep.SURFACE_STRUCTURES, piece))); FitFixture.start(VACUUM, TerrainAdaptation.NONE, DecorationStep.SURFACE_STRUCTURES, piece)));
assertTrue(SurfaceFitting.requiresSurfaceTerrain( assertTrue(SurfaceFitting.requiresSurfaceTerrain(
FitFixture.start(VACUUM, TerrainAdaptation.BEARD_BOX, StructureStep.SURFACE_STRUCTURES, piece))); FitFixture.start(VACUUM, TerrainAdaptation.BEARD_BOX, DecorationStep.SURFACE_STRUCTURES, piece)));
assertFalse(TerrainIntegration.clearsLegacyTemplateAir( assertFalse(TerrainIntegration.clearsLegacyTemplateAir(
FitFixture.start(VACUUM, TerrainAdaptation.NONE, StructureStep.SURFACE_STRUCTURES, piece))); FitFixture.start(VACUUM, TerrainAdaptation.NONE, DecorationStep.SURFACE_STRUCTURES, piece)));
} }
@Test @Test
@@ -227,7 +227,7 @@ public class SurfaceFittingTest {
Box area = new Box(0, 54, 0, 15, 72, 15); Box area = new Box(0, 54, 0, 15, 72, 15);
FitFixture.World world = new FitFixture.World(area).flat(area, 60); FitFixture.World world = new FitFixture.World(area).flat(area, 60);
Map<?, ?> before = world.snapshot(); Map<?, ?> before = world.snapshot();
FitStart start = FitFixture.start(VACUUM, TerrainAdaptation.NONE, StructureStep.SURFACE_STRUCTURES, FitStart start = FitFixture.start(VACUUM, TerrainAdaptation.NONE, DecorationStep.SURFACE_STRUCTURES,
FitFixture.Piece.rigid(new Box(0, 66, 0, 0, 70, 0), 1).cell(0, 66, 0, COBBLESTONE)); FitFixture.Piece.rigid(new Box(0, 66, 0, 0, 70, 0), 1).cell(0, 66, 0, COBBLESTONE));
SurfaceFitting.prepareSurfaceStructures(world.fitBlocks(), area, List.of(start), (x, z) -> 60, 1, ModuleLogs.discarding()); SurfaceFitting.prepareSurfaceStructures(world.fitBlocks(), area, List.of(start), (x, z) -> 60, 1, ModuleLogs.discarding());
@@ -239,7 +239,7 @@ public class SurfaceFittingTest {
public void vacuumRaisesTheTerrainToAFloatingFoundationAndRepairsItsGapAfterPlacement() { public void vacuumRaisesTheTerrainToAFloatingFoundationAndRepairsItsGapAfterPlacement() {
Box area = new Box(0, 54, 0, 3, 74, 3); Box area = new Box(0, 54, 0, 3, 74, 3);
FitFixture.World world = new FitFixture.World(area).flat(area, 60); FitFixture.World world = new FitFixture.World(area).flat(area, 60);
FitStart start = FitFixture.start(VACUUM, TerrainAdaptation.NONE, StructureStep.SURFACE_STRUCTURES, FitStart start = FitFixture.start(VACUUM, TerrainAdaptation.NONE, DecorationStep.SURFACE_STRUCTURES,
FitFixture.Piece.rigid(new Box(0, 65, 0, 0, 72, 0), 1).cell(0, 65, 0, COBBLESTONE)); FitFixture.Piece.rigid(new Box(0, 65, 0, 0, 72, 0), 1).cell(0, 65, 0, COBBLESTONE));
SurfaceFitting.VacuumFoundationPlan plan = SurfaceFitting.prepareSurfaceStructures( SurfaceFitting.VacuumFoundationPlan plan = SurfaceFitting.prepareSurfaceStructures(
@@ -7,9 +7,9 @@ import art.arcane.iris.engine.framework.structure.NativeStructureFit;
import art.arcane.iris.engine.mantle.components.StructureCarvingFootprint; import art.arcane.iris.engine.mantle.components.StructureCarvingFootprint;
import com.google.gson.Gson; import com.google.gson.Gson;
import com.volmit.block.BlockState; import com.volmit.block.BlockState;
import com.volmit.vanilla.DecorationStep;
import com.volmit.vanilla.PieceKind; import com.volmit.vanilla.PieceKind;
import com.volmit.vanilla.StartMemo; import com.volmit.vanilla.StartMemo;
import com.volmit.vanilla.StructureStep;
import com.volmit.vanilla.TerrainAdaptation; import com.volmit.vanilla.TerrainAdaptation;
import org.junit.Test; import org.junit.Test;
@@ -419,7 +419,7 @@ public class TerrainIntegrationTest {
} }
private static FitStart start(String terrainJson, TerrainAdaptation adaptation, FitFixture.Piece... pieces) { private static FitStart start(String terrainJson, TerrainAdaptation adaptation, FitFixture.Piece... pieces) {
return FitFixture.start(terrainJson, adaptation, StructureStep.STRONGHOLDS, pieces); return FitFixture.start(terrainJson, adaptation, DecorationStep.STRONGHOLDS, pieces);
} }
private static TerrainIntegration.SourceTerrainSnapshot snapshot(FitFixture.World world, Box area) { private static TerrainIntegration.SourceTerrainSnapshot snapshot(FitFixture.World world, Box area) {
@@ -0,0 +1,124 @@
/*
* Iris is a World Generator for Minecraft Servers
* Copyright (c) 2026 Arcane Arts (Volmit Software)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package art.arcane.iris.engine.framework.vanillafeatures;
import art.arcane.iris.builtin.vanillafeatures.ImportedFeaturesSettings;
import art.arcane.iris.engine.object.TestSettings;
import com.volmit.FeatureAttachment.Target;
import com.volmit.IrisFeature;
import com.volmit.config.FeatureSettings.Entry;
import com.volmit.config.PackSettings;
import com.volmit.resource.ResourceId;
import com.volmit.vanilla.DecorationStep;
import com.volmit.world.PackWorld;
import org.junit.Test;
import java.util.List;
import java.util.Optional;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
/** What a dimension's {@code importedFeatures} decide about the platform's own placed features. */
public class ImportedFeaturesTest {
private static final ResourceId DIAMONDS = ResourceId.parse("minecraft:ore_diamond");
private static final ResourceId PLAINS_TREES = ResourceId.parse("minecraft:trees_plains");
private static final ImportedFeatures FEATURES = new ImportedFeatures();
@Test
public void aDimensionWithoutTheSettingsRunsNoFeatures() {
assertFalse(FEATURES.generates(worldWith(null)));
assertFalse(FEATURES.generates(worldWith(new ImportedFeaturesSettings())));
}
@Test
public void enabledSettingsWithoutFiltersAllowEveryStepAndFeature() {
PackWorld world = worldWith(enabled(List.of(), List.of(), List.of()));
assertTrue(FEATURES.generates(world));
for (DecorationStep step : DecorationStep.values()) {
assertTrue(step.name(), FEATURES.generatesStep(world, Optional.of(step)));
}
assertTrue(FEATURES.generatesFeature(world, DIAMONDS));
}
@Test
public void disabledPatternsMatchWholeFamiliesAtABoundaryOnly() {
PackWorld world = worldWith(enabled(List.of("minecraft:ore", "minecraft:trees"), List.of(), List.of()));
assertFalse(FEATURES.generatesFeature(world, DIAMONDS));
assertFalse(FEATURES.generatesFeature(world, PLAINS_TREES));
assertTrue(FEATURES.generatesFeature(world, ResourceId.parse("minecraft:orefoo")));
assertTrue(FEATURES.generatesFeature(world, ResourceId.parse("minecraft:spring_water")));
}
@Test
public void stepsNarrowGenerationAndDisabledStepsApplyAfterThem() {
PackWorld narrowed = worldWith(enabled(List.of(), List.of(DecorationStep.UNDERGROUND_ORES), List.of()));
PackWorld overruled = worldWith(enabled(List.of(),
List.of(DecorationStep.UNDERGROUND_ORES, DecorationStep.VEGETAL_DECORATION), List.of(DecorationStep.VEGETAL_DECORATION)));
assertTrue(FEATURES.generatesStep(narrowed, Optional.of(DecorationStep.UNDERGROUND_ORES)));
assertFalse(FEATURES.generatesStep(narrowed, Optional.of(DecorationStep.VEGETAL_DECORATION)));
assertFalse(FEATURES.generatesStep(narrowed, Optional.of(DecorationStep.LAKES)));
assertTrue(FEATURES.generatesStep(overruled, Optional.of(DecorationStep.UNDERGROUND_ORES)));
assertFalse(FEATURES.generatesStep(overruled, Optional.of(DecorationStep.VEGETAL_DECORATION)));
}
@Test
public void aStepTheApiDoesNotNameGeneratesUnlessTheStepsWereNarrowed() {
PackWorld open = worldWith(enabled(List.of(), List.of(), List.of()));
PackWorld narrowed = worldWith(enabled(List.of(), List.of(DecorationStep.UNDERGROUND_ORES), List.of()));
assertTrue(FEATURES.generatesStep(open, Optional.empty()));
assertFalse(FEATURES.generatesStep(narrowed, Optional.empty()));
}
@Test
public void listsWrittenAsNullReadAsEmpty() {
PackWorld world = worldWith(enabled(null, null, null));
assertTrue(FEATURES.generatesStep(world, Optional.of(DecorationStep.LAKES)));
assertTrue(FEATURES.generatesFeature(world, DIAMONDS));
}
private static ImportedFeaturesSettings enabled(List<String> disabled, List<DecorationStep> steps,
List<DecorationStep> disabledSteps) {
return TestSettings.with(new ImportedFeaturesSettings(),
"enabled", true, "disabled", disabled, "steps", steps, "disabledSteps", disabledSteps);
}
/** A world whose dimension declares {@code settings}, or nothing when null. */
private static PackWorld worldWith(ImportedFeaturesSettings settings) {
PackWorld world = mock(PackWorld.class);
when(world.settings()).thenReturn(new PackSettings() {
@Override
@SuppressWarnings("unchecked")
public <F extends IrisFeature> List<Entry<F>> declared(Class<F> featureType) {
if (settings == null || featureType != ImportedFeaturesSettings.class) {
return List.of();
}
return List.of((Entry<F>) new Entry<>(Target.DIMENSION, ResourceId.parse("test:overworld"), settings));
}
});
return world;
}
}
@@ -3,13 +3,15 @@ package art.arcane.iris.engine.mantle.components;
import art.arcane.iris.engine.framework.IrisStructureLocator; import art.arcane.iris.engine.framework.IrisStructureLocator;
import art.arcane.iris.engine.framework.PlacedStructurePiece; import art.arcane.iris.engine.framework.PlacedStructurePiece;
import art.arcane.iris.engine.object.structure.IrisStructure; import art.arcane.iris.engine.object.structure.IrisStructure;
import art.arcane.iris.engine.object.structure.IrisStructurePlacement; import art.arcane.iris.builtin.structure.StructurePlacement;
import art.arcane.iris.engine.object.structure.vanilla.NativeStructureSuppression; import art.arcane.iris.builtin.structure.NativeStructureSuppression;
import art.arcane.iris.spi.PlatformBlockState; import art.arcane.iris.spi.PlatformBlockState;
import art.arcane.volmlib.util.collection.KList; import art.arcane.volmlib.util.collection.KList;
import art.arcane.volmlib.util.math.RNG; import art.arcane.volmlib.util.math.RNG;
import org.junit.Test; import org.junit.Test;
import static art.arcane.iris.engine.framework.StructurePlacementFixtures.placement;
import static art.arcane.iris.engine.framework.StructurePlacementFixtures.withAdded;
import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotEquals; import static org.junit.Assert.assertNotEquals;
@@ -95,8 +97,8 @@ public class StructurePlacingMarkerTest {
NativeStructureSuppression suppression, NativeStructureSuppression suppression,
KList<PlacedStructurePiece> pieces KList<PlacedStructurePiece> pieces
) { ) {
IrisStructurePlacement placement = new IrisStructurePlacement().setNativeSuppression(suppression); StructurePlacement placement = placement("nativeSuppression", suppression);
placement.getStructures().add("test:city"); withAdded(placement, "structures", "test:city");
IrisStructure structure = new IrisStructure(); IrisStructure structure = new IrisStructure();
structure.setLoadKey("test:city"); structure.setLoadKey("test:city");
return new IrisStructureLocator.ResolvedPlacement( return new IrisStructureLocator.ResolvedPlacement(
@@ -1,189 +0,0 @@
/*
* Iris is a World Generator for Minecraft Servers
* Copyright (c) 2026 Arcane Arts (Volmit Software)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package art.arcane.iris.engine.object.decoration;
import art.arcane.iris.engine.object.decoration.IrisDecorationStep;
import art.arcane.iris.engine.object.decoration.IrisImportedFeatureControl;
import art.arcane.iris.engine.object.decoration.NativeFeatureGenerationStatus;
import art.arcane.volmlib.util.collection.KList;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertThrows;
import static org.junit.Assert.assertTrue;
public class IrisImportedFeatureControlTest {
private static KList<String> keys(String... values) {
KList<String> list = new KList<>();
for (String value : values) {
list.add(value);
}
return list;
}
private static KList<IrisDecorationStep> steps(IrisDecorationStep... values) {
KList<IrisDecorationStep> list = new KList<>();
for (IrisDecorationStep value : values) {
list.add(value);
}
return list;
}
@Test
public void defaultControlIsOffAndGeneratesNothing() {
IrisImportedFeatureControl control = new IrisImportedFeatureControl();
assertFalse(control.isEnabled());
assertFalse(control.shouldGenerateFeatures());
assertFalse(control.shouldGenerate("minecraft:ore_diamond"));
assertFalse(control.shouldGenerateStep(IrisDecorationStep.UNDERGROUND_ORES));
assertEquals(NativeFeatureGenerationStatus.FEATURES_DISABLED,
control.resolve("minecraft:ore_diamond", IrisDecorationStep.UNDERGROUND_ORES));
}
@Test
public void enabledControlGeneratesEveryStepAndKeyByDefault() {
IrisImportedFeatureControl control = new IrisImportedFeatureControl().setEnabled(true);
assertTrue(control.shouldGenerateFeatures());
assertTrue(control.shouldGenerate("minecraft:ore_diamond"));
assertTrue(control.shouldGenerate("somemod:weird_ore"));
for (IrisDecorationStep step : IrisDecorationStep.values()) {
assertTrue(step.name(), control.shouldGenerateStep(step));
}
assertEquals(NativeFeatureGenerationStatus.GENERATE_NATIVE,
control.resolve("minecraft:ore_diamond", IrisDecorationStep.UNDERGROUND_ORES));
}
@Test
public void disabledKeyPrefixMatchesOnFamilyBoundariesOnly() {
IrisImportedFeatureControl control = new IrisImportedFeatureControl()
.setEnabled(true)
.setDisabled(keys("minecraft:ore"));
assertFalse(control.shouldGenerate("minecraft:ore_diamond"));
assertFalse(control.shouldGenerate("minecraft:ore"));
assertFalse(control.shouldGenerate("minecraft:ore/deep"));
assertTrue(control.shouldGenerate("minecraft:orebody"));
assertTrue(control.shouldGenerate("somemod:ore_diamond"));
assertEquals(NativeFeatureGenerationStatus.DISABLED_BY_PACK,
control.resolve("minecraft:ore_diamond", IrisDecorationStep.UNDERGROUND_ORES));
}
@Test
public void stepAllowListNarrowsGenerationToListedStepsOnly() {
IrisImportedFeatureControl control = new IrisImportedFeatureControl()
.setEnabled(true)
.setSteps(steps(IrisDecorationStep.UNDERGROUND_ORES));
assertTrue(control.shouldGenerateStep(IrisDecorationStep.UNDERGROUND_ORES));
assertFalse(control.shouldGenerateStep(IrisDecorationStep.VEGETAL_DECORATION));
assertFalse(control.shouldGenerateStep(IrisDecorationStep.LAKES));
assertEquals(NativeFeatureGenerationStatus.STEP_DISABLED,
control.resolve("minecraft:trees_plains", IrisDecorationStep.VEGETAL_DECORATION));
assertEquals(NativeFeatureGenerationStatus.GENERATE_NATIVE,
control.resolve("minecraft:ore_diamond", IrisDecorationStep.UNDERGROUND_ORES));
}
@Test
public void disabledStepsWinOverTheAllowList() {
IrisImportedFeatureControl control = new IrisImportedFeatureControl()
.setEnabled(true)
.setSteps(steps(IrisDecorationStep.UNDERGROUND_ORES, IrisDecorationStep.VEGETAL_DECORATION))
.setDisabledSteps(steps(IrisDecorationStep.VEGETAL_DECORATION));
assertTrue(control.shouldGenerateStep(IrisDecorationStep.UNDERGROUND_ORES));
assertFalse(control.shouldGenerateStep(IrisDecorationStep.VEGETAL_DECORATION));
}
@Test
public void unknownStepGeneratesUnlessAnAllowListNarrowedGeneration() {
IrisImportedFeatureControl open = new IrisImportedFeatureControl().setEnabled(true);
IrisImportedFeatureControl narrowed = new IrisImportedFeatureControl()
.setEnabled(true)
.setSteps(steps(IrisDecorationStep.UNDERGROUND_ORES));
assertTrue(open.shouldGenerateStep(null));
assertFalse(narrowed.shouldGenerateStep(null));
}
@Test
public void nullStepInResolveSkipsTheStepGate() {
IrisImportedFeatureControl control = new IrisImportedFeatureControl()
.setEnabled(true)
.setSteps(steps(IrisDecorationStep.UNDERGROUND_ORES));
assertEquals(NativeFeatureGenerationStatus.GENERATE_NATIVE,
control.resolve("minecraft:trees_plains", null));
}
@Test
public void blankKeyIsInvalidRatherThanGenerated() {
IrisImportedFeatureControl control = new IrisImportedFeatureControl().setEnabled(true);
assertEquals(NativeFeatureGenerationStatus.INVALID_REGISTRY_KEY, control.resolve(null, null));
assertEquals(NativeFeatureGenerationStatus.INVALID_REGISTRY_KEY, control.resolve(" ", null));
assertFalse(control.shouldGenerate(null));
}
@Test
public void nullCollectionsFailLoudlyNamingTheField() {
IrisImportedFeatureControl nullDisabled = new IrisImportedFeatureControl()
.setEnabled(true).setDisabled(null);
IrisImportedFeatureControl nullSteps = new IrisImportedFeatureControl()
.setEnabled(true).setSteps(null);
IrisImportedFeatureControl nullDisabledSteps = new IrisImportedFeatureControl()
.setEnabled(true).setDisabledSteps(null);
assertTrue(assertThrows(NullPointerException.class,
() -> nullDisabled.shouldGenerate("minecraft:ore_diamond"))
.getMessage().contains("importedFeatures.disabled"));
assertTrue(assertThrows(NullPointerException.class,
() -> nullSteps.shouldGenerateStep(IrisDecorationStep.LAKES))
.getMessage().contains("importedFeatures.steps"));
assertTrue(assertThrows(NullPointerException.class,
() -> nullDisabledSteps.shouldGenerateStep(IrisDecorationStep.LAKES))
.getMessage().contains("importedFeatures.disabledSteps"));
}
@Test
public void decorationStepOrdinalsMatchTheVanillaTable() {
// Verified against MC 26.2 GenerationStep.Decoration. The platform converts by ordinal, so a drift
// here silently mislabels every step gate.
String[] expected = {
"raw_generation", "lakes", "local_modifications", "underground_structures",
"surface_structures", "strongholds", "underground_ores", "underground_decoration",
"fluid_springs", "vegetal_decoration", "top_layer_modification"
};
assertEquals(expected.length, IrisDecorationStep.values().length);
for (int ordinal = 0; ordinal < expected.length; ordinal++) {
IrisDecorationStep step = IrisDecorationStep.byOrdinal(ordinal);
assertEquals(expected[ordinal], step.getSerializedName());
assertEquals(ordinal, step.ordinal());
assertEquals(step, IrisDecorationStep.byKey(expected[ordinal]));
assertEquals(step, IrisDecorationStep.byKey(step.name()));
}
assertEquals(null, IrisDecorationStep.byOrdinal(expected.length));
assertEquals(null, IrisDecorationStep.byOrdinal(-1));
assertEquals(null, IrisDecorationStep.byKey("not_a_step"));
assertEquals(null, IrisDecorationStep.byKey(null));
}
}
@@ -1,35 +0,0 @@
package art.arcane.iris.engine.object.structure;
import art.arcane.iris.engine.object.structure.IrisStructureAnchorMode;
import art.arcane.iris.engine.object.structure.IrisStructurePlacement;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
public class IrisStructureAnchorModeTest {
@Test
public void legacyPreservesUndergroundBehavior() {
IrisStructurePlacement surface = new IrisStructurePlacement();
IrisStructurePlacement underground = new IrisStructurePlacement().setUnderground(true);
assertEquals(IrisStructureAnchorMode.SURFACE, surface.resolvedAnchor());
assertEquals(IrisStructureAnchorMode.HEIGHT_BAND, underground.resolvedAnchor());
assertFalse(surface.isAnchoredUnderground());
assertTrue(underground.isAnchoredUnderground());
}
@Test
public void explicitAnchorOverridesLegacyBoolean() {
IrisStructurePlacement floor = new IrisStructurePlacement()
.setUnderground(false)
.setAnchor(IrisStructureAnchorMode.CAVE_FLOOR);
IrisStructurePlacement surface = new IrisStructurePlacement()
.setUnderground(true)
.setAnchor(IrisStructureAnchorMode.SURFACE);
assertTrue(floor.isAnchoredUnderground());
assertFalse(surface.isAnchoredUnderground());
}
}
@@ -8,16 +8,14 @@ import art.arcane.iris.engine.mantle.components.StructureModule;
import art.arcane.iris.core.loader.IrisData; import art.arcane.iris.core.loader.IrisData;
import art.arcane.iris.engine.framework.Engine; import art.arcane.iris.engine.framework.Engine;
import art.arcane.iris.engine.framework.EngineGeneration; import art.arcane.iris.engine.framework.EngineGeneration;
import art.arcane.iris.engine.framework.IrisStructureLocator;
import art.arcane.iris.engine.mantle.components.StructureModule; import art.arcane.iris.engine.mantle.components.StructureModule;
import art.arcane.iris.engine.framework.StructureReachability;
import art.arcane.iris.engine.object.world.dimension.IrisDimension; import art.arcane.iris.engine.object.world.dimension.IrisDimension;
import art.arcane.iris.engine.object.structure.vanilla.IrisNativeStructure; import art.arcane.iris.builtin.structure.NativeStructureSource;
import art.arcane.iris.engine.object.structure.IrisStructure; import art.arcane.iris.engine.object.structure.IrisStructure;
import art.arcane.iris.engine.object.structure.IrisStructurePlacement; import art.arcane.iris.builtin.structure.StructurePlacement;
import art.arcane.iris.engine.object.world.IrisWorld; import art.arcane.iris.engine.object.world.IrisWorld;
import art.arcane.iris.engine.framework.NativeStructureGenerationStatus; import art.arcane.iris.engine.framework.NativeStructureGenerationStatus;
import art.arcane.iris.engine.object.structure.StructureDistribution; import art.arcane.iris.builtin.structure.StructureDistribution;
import art.arcane.iris.spi.IrisPlatform; import art.arcane.iris.spi.IrisPlatform;
import art.arcane.iris.spi.IrisPlatforms; import art.arcane.iris.spi.IrisPlatforms;
import art.arcane.iris.spi.PlatformStructureHooks; import art.arcane.iris.spi.PlatformStructureHooks;
@@ -32,7 +30,11 @@ import java.nio.file.Path;
import java.util.LinkedHashSet; import java.util.LinkedHashSet;
import java.util.List; import java.util.List;
import java.util.Set; import java.util.Set;
import art.arcane.iris.engine.object.TestSettings;
import static art.arcane.iris.engine.framework.StructurePlacementFixtures.nativeSource;
import static art.arcane.iris.engine.framework.StructurePlacementFixtures.placementSettings;
import static art.arcane.iris.engine.framework.StructurePlacementFixtures.withAdded;
import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertSame; import static org.junit.Assert.assertSame;
@@ -91,7 +93,7 @@ public class StructureHandlerTest {
StructureSettings settings = new StructureSettings(List.of("pack:disabled", "pack:replacement", "pack:dormant_replacement"), StructureSettings settings = new StructureSettings(List.of("pack:disabled", "pack:replacement", "pack:dormant_replacement"),
List.of(), 0, true, List.of(), List.of()); List.of(), 0, true, List.of(), List.of());
KList<IrisStructurePlacement> placements = new KList<>(); KList<StructurePlacement> placements = new KList<>();
placements.add(nativePlacement("pack:replacement", StructureDistribution.RANDOM_SPREAD, 1.0)); placements.add(nativePlacement("pack:replacement", StructureDistribution.RANDOM_SPREAD, 1.0));
placements.add(nativePlacement("pack:dormant_replacement", StructureDistribution.DENSITY, 0.0)); placements.add(nativePlacement("pack:dormant_replacement", StructureDistribution.DENSITY, 0.0));
placements.add(nativePlacement("pack:explicit", StructureDistribution.RANDOM_SPREAD, 1.0)); placements.add(nativePlacement("pack:explicit", StructureDistribution.RANDOM_SPREAD, 1.0));
@@ -116,8 +118,7 @@ public class StructureHandlerTest {
when(engine.getMinHeight()).thenReturn(-64); when(engine.getMinHeight()).thenReturn(-64);
when(engine.getHeight()).thenReturn(384); when(engine.getHeight()).thenReturn(384);
when(world.platformWorld()).thenReturn(platformWorld); when(world.platformWorld()).thenReturn(platformWorld);
when(dimension.getModuleSettings()).thenReturn(BuiltInPack.settings(settings)); when(dimension.getModuleSettings()).thenReturn(BuiltInPack.settings(settings, placementSettings(placements)));
when(dimension.getStructures()).thenReturn(placements);
when(dimension.getAllRegions(engine)).thenReturn(new KList<>()); when(dimension.getAllRegions(engine)).thenReturn(new KList<>());
when(dimension.getReachableBiomes(engine)).thenReturn(new KList<>()); when(dimension.getReachableBiomes(engine)).thenReturn(new KList<>());
when(platform.structureHooks()).thenReturn(hooks); when(platform.structureHooks()).thenReturn(hooks);
@@ -151,8 +152,6 @@ public class StructureHandlerTest {
verify(hooks, times(1)).structureKeys(); verify(hooks, times(1)).structureKeys();
verify(hooks, times(1)).reachableStructureKeys(platformWorld); verify(hooks, times(1)).reachableStructureKeys(platformWorld);
} finally { } finally {
IrisStructureLocator.invalidate(engine);
StructureReachability.invalidate(engine);
IrisPlatforms.unbind(); IrisPlatforms.unbind();
} }
} }
@@ -173,7 +172,7 @@ public class StructureHandlerTest {
IrisStructure replacement = new IrisStructure(); IrisStructure replacement = new IrisStructure();
replacement.setLoadKey("iris:replacement"); replacement.setLoadKey("iris:replacement");
replacement.setVanillaSource("minecraft:replacement"); replacement.setVanillaSource("minecraft:replacement");
KList<IrisStructurePlacement> placements = new KList<>(); KList<StructurePlacement> placements = new KList<>();
placements.add(editablePlacement("iris:editable_definition")); placements.add(editablePlacement("iris:editable_definition"));
placements.add(editablePlacement("iris:replacement_definition")); placements.add(editablePlacement("iris:replacement_definition"));
placements.add(nativePlacement("minecraft:explicit", StructureDistribution.RANDOM_SPREAD, 1.0)); placements.add(nativePlacement("minecraft:explicit", StructureDistribution.RANDOM_SPREAD, 1.0));
@@ -189,8 +188,7 @@ public class StructureHandlerTest {
when(engine.getMinHeight()).thenReturn(-64); when(engine.getMinHeight()).thenReturn(-64);
when(engine.getHeight()).thenReturn(384); when(engine.getHeight()).thenReturn(384);
when(world.platformWorld()).thenReturn(platformWorld); when(world.platformWorld()).thenReturn(platformWorld);
when(dimension.getModuleSettings()).thenReturn(BuiltInPack.settings(settings)); when(dimension.getModuleSettings()).thenReturn(BuiltInPack.settings(settings, placementSettings(placements)));
when(dimension.getStructures()).thenReturn(placements);
when(dimension.getAllRegions(engine)).thenReturn(new KList<>()); when(dimension.getAllRegions(engine)).thenReturn(new KList<>());
when(dimension.getReachableBiomes(engine)).thenReturn(new KList<>()); when(dimension.getReachableBiomes(engine)).thenReturn(new KList<>());
when(platform.structureHooks()).thenReturn(hooks); when(platform.structureHooks()).thenReturn(hooks);
@@ -213,8 +211,6 @@ public class StructureHandlerTest {
assertFalse(possibilities.contains("minecraft:explicit")); assertFalse(possibilities.contains("minecraft:explicit"));
assertFalse(possibilities.contains("minecraft:reachable")); assertFalse(possibilities.contains("minecraft:reachable"));
} finally { } finally {
IrisStructureLocator.invalidate(engine);
StructureReachability.invalidate(engine);
IrisPlatforms.unbind(); IrisPlatforms.unbind();
} }
} }
@@ -258,18 +254,18 @@ public class StructureHandlerTest {
} }
private static IrisStructurePlacement nativePlacement(String key, StructureDistribution distribution, private static StructurePlacement nativePlacement(String key, StructureDistribution distribution,
double density) { double density) {
IrisStructurePlacement placement = new IrisStructurePlacement(); StructurePlacement placement = new StructurePlacement();
placement.getNativeStructures().add(new IrisNativeStructure().setStructure(key)); withAdded(placement, "nativeStructures", nativeSource(key));
placement.setDistribution(distribution); TestSettings.with(placement, "distribution", distribution);
placement.setDensity(density); TestSettings.with(placement, "density", density);
return placement; return placement;
} }
private static IrisStructurePlacement editablePlacement(String key) { private static StructurePlacement editablePlacement(String key) {
IrisStructurePlacement placement = new IrisStructurePlacement(); StructurePlacement placement = new StructurePlacement();
placement.getStructures().add(key); withAdded(placement, "structures", key);
return placement; return placement;
} }