Platform starts fit through a neutral bridge to iris:structure

Core asks the pack's VanillaStructures providers (ModuleVanillaStructures) for rules, starts, the shift of each
platform start and every module's reach, and runs the built-in fit through ModuleStructureFitting, which turns the
platform's chunk into the API's StructureFit. minecraft-common's NativeStructureFitBridge hands Bukkit and the modded
loaders' starts, processed template cells, template columns and legacy air to it; the platform helpers that held the
fit (surface fitter, terrain integrator, support and foundation builders, post processor) are gone. The host only
moves, clamps, wraps and places starts.

Ownership records keep their binary layout: the two texts that held the stilts and terrain JSON now hold the start's
memo, which the module writes in the same JSON, so records written before read the same. A recorded reference
envelope only grows when today's reaches are wider.

Tests: the fit's rules are tested in core against stated cells; the bridge and the fit end to end on the NMS harness;
the object place mode and native structure fit pins stay identical.
This commit is contained in:
piexel committed 2026-10-10 03:50:45 +02:00
1 parent 6a1d2564e2
commit 0b3556f09c
90 files changed
+5278 -7051

No files matched your search

@@ -7,34 +7,29 @@ import art.arcane.iris.engine.framework.IrisStructureLocator;
import art.arcane.iris.engine.framework.NativeStructureOwnershipRecord;
import art.arcane.iris.engine.framework.NativeStructureStartPlan;
import art.arcane.iris.engine.framework.NativeStructureGenerationPolicy;
import art.arcane.iris.engine.framework.NativeStructureLayouts;
import art.arcane.iris.engine.framework.nativefit.NativeStructureFitting;
import art.arcane.iris.engine.IrisEngine;
import art.arcane.iris.engine.platform.BukkitChunkGenerator;
import art.arcane.iris.engine.object.world.dimension.IrisDimension;
import art.arcane.iris.engine.object.terrain.carving.IrisDimensionCarvingResolver;
import art.arcane.iris.engine.object.material.IrisMaterialPalette;
import art.arcane.iris.engine.object.structure.vanilla.IrisNativeStructureDecision;
import art.arcane.iris.nativegen.NativeStructureFitBridge;
import art.arcane.iris.nativegen.NativeStructureGenerationException;
import art.arcane.iris.nativegen.NativeStructureStartInjector;
import art.arcane.iris.nativegen.NativeStructureReferenceEnvelope;
import art.arcane.iris.nativegen.NativeStructureLocateResults;
import art.arcane.iris.nativegen.NativeStructureLocatePersistence;
import art.arcane.iris.nativegen.NativeStructureOwnershipRecovery;
import art.arcane.iris.nativegen.NativeStructurePostProcessor;
import art.arcane.iris.nativegen.NativeStructureReferenceRepair;
import art.arcane.iris.nativegen.NativeStructureSurfaceFitter;
import art.arcane.iris.nativegen.NativeStructureTerrainIntegrator;
import art.arcane.iris.nativegen.NativeStructureVegetationClearer;
import art.arcane.iris.nativegen.NativeStructureVerticalPlacer;
import art.arcane.iris.nativegen.NativeStructureVanillaLocator;
import art.arcane.iris.nativegen.NativeStructureVolumeIndex;
import art.arcane.iris.nativegen.WorldgenTerrainHeightmaps;
import art.arcane.iris.spi.IrisLogging;
import art.arcane.iris.spi.PlatformBlockState;
import art.arcane.iris.util.common.data.IrisCustomData;
import art.arcane.iris.util.common.reflect.WrappedField;
import art.arcane.iris.util.common.reflect.WrappedReturningMethod;
import art.arcane.iris.util.project.context.IrisContext;
import art.arcane.volmlib.util.math.RNG;
import com.mojang.datafixers.util.Pair;
import com.mojang.serialization.MapCodec;
import net.minecraft.core.BlockPos;
@@ -87,9 +82,7 @@ import net.minecraft.world.level.levelgen.structure.StructureStart;
import net.minecraft.world.level.levelgen.structure.templatesystem.StructureTemplateManager;
import org.bukkit.World;
import org.bukkit.craftbukkit.CraftWorld;
import org.bukkit.craftbukkit.block.data.CraftBlockData;
import org.bukkit.craftbukkit.generator.CustomChunkGenerator;
import org.bukkit.block.data.BlockData;
import org.spigotmc.SpigotWorldConfig;
import javax.annotation.Nullable;
@@ -288,9 +281,7 @@ public class IrisChunkGenerator extends CustomChunkGenerator {
throw new IllegalStateException("Native structure filtering received an unregistered structure holder");
}
String key = id.toString();
IrisNativeStructureDecision decision = NativeStructureGenerationPolicy.resolve(engine,
key, NativeStructureVegetationClearer.isUndergroundStep(holder.value().step()));
if (!decision.generate()) {
if (!NativeStructureGenerationPolicy.generates(engine, key)) {
continue;
}
candidates.add(new NativeLocateCandidate(holder, key));
@@ -405,33 +396,32 @@ public class IrisChunkGenerator extends CustomChunkGenerator {
"resolution", null, chunkPos.x(), chunkPos.z());
}
boolean undergroundStep = NativeStructureVegetationClearer.isUndergroundStep(structure.step());
IrisNativeStructureDecision decision;
boolean generates;
try {
decision = NativeStructureGenerationPolicy.resolve(engine,
structureId, undergroundStep);
generates = NativeStructureGenerationPolicy.generates(engine, structureId);
} catch (Throwable error) {
throw NativeStructureGenerationException.failure(
"policy resolution", structureId, chunkPos.x(), chunkPos.z(), error);
}
if (!decision.generate()) {
if (!generates) {
access.setStartForStructure(structure, StructureStart.INVALID_START);
continue;
}
try {
IntBinaryOperator surface = (x, z) -> engine.getHeight(x, z, true) + engine.getMinHeight();
int shift = NativeStructureLayouts.shift(engine, NativeStructureVerticalPlacer.placementOf(
start, structureId, undergroundStep, access.getMinY(), surface));
NativeStructureVerticalPlacer.applyVerticalPlacement(
start,
structureId,
decision.yShift(),
shift,
getSeaLevel(),
access.getMinY(),
access.getMinY() + access.getHeight(),
undergroundStep,
decision.preserveSourceY(),
decision.yBand(),
(x, z) -> engine.getHeight(x, z, true) + engine.getMinHeight());
surface);
StructureStart wrapped = NativeStructureReferenceEnvelope.wrapForPublication(
start, structure, start.getReferences(),
NativeStructureTerrainIntegrator.resolveNativeTerrain(start, decision.terrain()),
NativeStructureLayouts.reaches(engine, structureId, undergroundStep, null),
structureId);
access.setStartForStructure(structure, wrapped);
} catch (Throwable error) {
@@ -822,7 +812,7 @@ public class IrisChunkGenerator extends CustomChunkGenerator {
List<NativePlacementGroup> placementGroups = new ArrayList<>();
List<StructureStart> heightmapStarts = new ArrayList<>();
List<StructureStart> vegetationTargets = new ArrayList<>();
List<NativeStructureTerrainIntegrator.TerrainTarget> terrainTargets = new ArrayList<>();
List<NativeStructureFitBridge.FitTarget> fitTargets = new ArrayList<>();
for (int step = 0; step < steps; step++) {
int index = 0;
for (Structure structure : byStep.get(step)) {
@@ -833,25 +823,20 @@ public class IrisChunkGenerator extends CustomChunkGenerator {
"resolution", null, chunkPos.x(), chunkPos.z());
}
try {
IrisNativeStructureDecision sourceDecision = NativeStructureGenerationPolicy.resolve(engine,
structureId, NativeStructureVegetationClearer.isUndergroundStep(structure.step()));
boolean platformGenerates = NativeStructureGenerationPolicy.generates(engine, structureId);
List<StructureStart> starts = structureManager.startsForStructure(sectionPos, structure);
List<NativePlacement> resolvedPlacements = new ArrayList<>(starts.size());
for (StructureStart start : starts) {
NativeStructureOwnershipRecord ownership =
NativeStructureOwnershipRecovery.resolve(
engine, world.getLevel(), structureId, structure, start);
IrisNativeStructureDecision decision =
ownership == null ? sourceDecision : ownership.restoredDecision();
if (!decision.generate()) {
if (ownership == null && !platformGenerates) {
continue;
}
resolvedPlacements.add(new NativePlacement(start, decision));
resolvedPlacements.add(new NativePlacement(start, ownership != null));
heightmapStarts.add(start);
terrainTargets.add(new NativeStructureTerrainIntegrator.TerrainTarget(
structureId, start,
NativeStructureTerrainIntegrator.resolveNativeTerrain(
start, decision.terrain())));
fitTargets.add(new NativeStructureFitBridge.FitTarget(structureId, start,
ownership == null ? null : ownership.restoredMemo()));
vegetationTargets.add(start);
}
if (!resolvedPlacements.isEmpty()) {
@@ -881,44 +866,29 @@ public class IrisChunkGenerator extends CustomChunkGenerator {
"vegetation cleanup", nativeStructureBatchContext(placementGroups),
chunkPos.x(), chunkPos.z(), error);
}
NativeStructureSurfaceFitter.VacuumFoundationPlan vacuumFoundationPlan;
NativeStructureFitting.Session fit;
try {
vacuumFoundationPlan = NativeStructureSurfaceFitter.prepareSurfaceStructures(
world, area, terrainTargets,
(x, z) -> engine.getHeight(x, z, true) + engine.getMinHeight());
fit = NativeStructureFitting.of(engine).beforePieces(NativeStructureFitBridge.chunk(
world, area, fitTargets, (x, z) -> engine.getHeight(x, z, true) + engine.getMinHeight()));
} catch (Throwable error) {
throw NativeStructureGenerationException.failure(
"terrain integration", nativeStructureBatchContext(placementGroups),
chunkPos.x(), chunkPos.z(), error);
}
try {
NativeStructurePostProcessor.prepareTerrain(
world, area, terrainTargets, this::resolvePaletteBlock);
} catch (Throwable error) {
throw NativeStructureGenerationException.failure(
"terrain preparation", nativeStructureBatchContext(placementGroups),
"terrain fitting", nativeStructureBatchContext(placementGroups),
chunkPos.x(), chunkPos.z(), error);
}
int placed = 0;
for (NativePlacementGroup group : placementGroups) {
random.setFeatureSeed(decoSeed, group.featureIndex(), group.step());
try {
for (NativePlacement placement : group.placements()) {
placeVanillaStructure(world, structureManager, random, area, chunkPos,
group.structureId(), placement.start(), placement.decision());
group.structureId(), placement);
fit.afterPieces(placed++);
}
} catch (Throwable error) {
throw NativeStructureGenerationException.failure(
"placement", group.structureId(), chunkPos.x(), chunkPos.z(), error);
}
}
try {
NativeStructureSurfaceFitter.repairVacuumFoundations(
world, area, vacuumFoundationPlan);
} catch (Throwable error) {
throw NativeStructureGenerationException.failure(
"foundation repair", nativeStructureBatchContext(placementGroups),
chunkPos.x(), chunkPos.z(), error);
}
}
private static String nativeStructureBatchContext(List<NativePlacementGroup> placementGroups) {
@@ -936,20 +906,29 @@ public class IrisChunkGenerator extends CustomChunkGenerator {
}
private void placeVanillaStructure(WorldGenLevel world, StructureManager structureManager, WorldgenRandom random,
BoundingBox area, ChunkPos chunkPos, String structureId, StructureStart start,
IrisNativeStructureDecision decision) {
BoundingBox area, ChunkPos chunkPos, String structureId,
NativePlacement placement) {
WorldGenLevel boundedWorld = NativeStructureWorldgenAccess.create(
world, chunkPos, worldgenSurfaceHeight(), worldgenFloorHeight());
world.setCurrentlyGenerating(() -> "Iris native structure " + structureId);
try {
NativeStructurePostProcessor.place(boundedWorld, structureManager, this, random, area, chunkPos,
structureId, start, decision, this::resolvePaletteBlock,
(x, z) -> engine.getHeight(x, z, true) + engine.getMinHeight());
StructureStart start = placement.start();
NativeStructureVerticalPlacer.ensureMonumentSeaLevelAlignment(start, structureId,
() -> placement.recorded() ? 0 : platformShift(start, structureId, world.getMinY()),
getSeaLevel(), area.minY(), area.maxY() + 1);
start.placeInChunk(boundedWorld, structureManager, this, random, area, chunkPos);
} finally {
world.setCurrentlyGenerating(null);
}
}
/** The shift the pack's modules give the platform's own start, as when the start was published. */
private int platformShift(StructureStart start, String structureId, int bottomY) {
return NativeStructureLayouts.shift(engine, NativeStructureVerticalPlacer.placementOf(start, structureId,
NativeStructureVegetationClearer.isUndergroundStep(start.getStructure().step()), bottomY,
(x, z) -> engine.getHeight(x, z, true) + engine.getMinHeight()));
}
private List<List<Structure>> structuresByStep(Registry<Structure> registry) {
StructureStepCache cached = structureStepCache;
if (cached != null && cached.registry() == registry) {
@@ -977,22 +956,6 @@ public class IrisChunkGenerator extends CustomChunkGenerator {
}
}
private BlockState resolvePaletteBlock(IrisMaterialPalette palette, RNG rng, int x, int y, int z) {
PlatformBlockState platformState = palette.get(rng, x, y, z, engine.getData());
if (platformState == null || !(platformState.nativeHandle() instanceof BlockData blockData)) {
throw new IllegalStateException("Configured native structure palette did not resolve a Bukkit block at "
+ x + "," + y + "," + z);
}
if (blockData instanceof IrisCustomData customData) {
blockData = customData.getBase();
}
if (blockData instanceof CraftBlockData craftBlockData) {
return craftBlockData.getState();
}
throw new IllegalStateException("Configured native structure palette resolved unsupported Bukkit block data "
+ blockData.getClass().getName() + " at " + x + "," + y + "," + z);
}
private BoundingBox writableArea(ChunkAccess chunk) {
ChunkPos cp = chunk.getPos();
int i = cp.getMinBlockX();
@@ -1205,7 +1168,8 @@ public class IrisChunkGenerator extends CustomChunkGenerator {
void publish() throws IllegalAccessException;
}
private record NativePlacement(StructureStart start, IrisNativeStructureDecision decision) {
/** A start placed in the chunk, and whether a module placed it (its ownership record kept its fit). */
private record NativePlacement(StructureStart start, boolean recorded) {
}
private record NativePlacementGroup(String structureId, int featureIndex, int step,
@@ -64,20 +64,18 @@ public class IrisChunkGeneratorFailureContractTest {
assertTrue(adjustment.contains("\"vertical adjustment\""));
assertFalse(adjustment.contains("IrisLogging.reportError"));
assertTrue(placement.contains("\"resolution\""));
assertTrue(placement.contains("\"terrain integration\""));
assertTrue(placement.contains("\"terrain preparation\""));
assertTrue(placement.contains("\"foundation repair\""));
assertTrue(placement.contains("\"terrain fitting\""));
assertFalse(placement.contains("\"terrain carving\""));
assertTrue(placement.contains("\"vegetation cleanup\""));
assertTrue(placement.contains("\"placement\""));
assertTrue(placement.contains("because structure generation is disabled outside the pack"));
assertTrue(placement.contains("prepareSurfaceStructures"));
assertTrue(placement.contains(".beforePieces("));
assertTrue(placement.contains("clearIntersectingVegetation"));
assertTrue(placement.indexOf("clearIntersectingVegetation")
< placement.indexOf("prepareSurfaceStructures"));
assertTrue(placement.indexOf("prepareSurfaceStructures")
< placement.indexOf(".beforePieces("));
assertTrue(placement.indexOf(".beforePieces(")
< placement.indexOf("for (NativePlacementGroup group"));
assertTrue(placement.indexOf("repairVacuumFoundations")
assertTrue(placement.indexOf("fit.afterPieces(")
> placement.indexOf("for (NativePlacementGroup group"));
assertFalse(placement.contains("IrisLogging.reportError"));
}
@@ -215,7 +213,7 @@ public class IrisChunkGeneratorFailureContractTest {
assertEquals(1, occurrences(source, "WorldgenTerrainHeightmaps.primeTerrain("));
assertTrue(placement.contains("WorldgenTerrainHeightmaps.primeStructurePlacement("));
assertTrue(placement.indexOf("WorldgenTerrainHeightmaps.primeStructurePlacement(")
< placement.indexOf("prepareSurfaceStructures"));
< placement.indexOf(".beforePieces("));
assertTrue(fill.contains("requireGenerationLease(\"bukkit_nms_chunk_pipeline\")"));
assertTrue(source.contains("int minY = chunk.getMinY() + 1;"));
}
@@ -443,7 +441,7 @@ public class IrisChunkGeneratorFailureContractTest {
@Test
public void worldgenHeightmapPrimingLivesInTheSharedNativegenSources() throws IOException {
Path nativegen = Path.of(System.getProperty("iris.nativeStructurePostProcessorSource")).getParent();
Path nativegen = Path.of(System.getProperty("iris.nativeStructureFitBridgeSource")).getParent();
Path shared = nativegen.resolve("WorldgenTerrainHeightmaps.java");
assertTrue("Worldgen heightmap priming must be shared with the modded loaders through "
@@ -470,11 +468,11 @@ public class IrisChunkGeneratorFailureContractTest {
String placement = source.substring(placementStart, placementEnd);
int ownershipResolution = placement.indexOf(
"NativeStructureOwnershipRecovery.resolve(");
int persistedDecision = placement.indexOf("ownership.restoredDecision()", ownershipResolution);
int persistedDecision = placement.indexOf("ownership.restoredMemo()", ownershipResolution);
int adjustmentStart = source.indexOf("private void adjustGeneratedStructures");
int adjustmentEnd = source.indexOf("public ChunkGeneratorStructureState createState", adjustmentStart);
String adjustment = source.substring(adjustmentStart, adjustmentEnd);
Path nativegen = Path.of(System.getProperty("iris.nativeStructurePostProcessorSource")).getParent();
Path nativegen = Path.of(System.getProperty("iris.nativeStructureFitBridgeSource")).getParent();
String factory = Files.readString(nativegen.resolve("NativeStructureFactory.java")).replace("\r\n", "\n");
String injector = Files.readString(nativegen.resolve("NativeStructureStartInjector.java")).replace("\r\n", "\n");
String recovery = Files.readString(nativegen.resolve("NativeStructureOwnershipRecovery.java")).replace("\r\n", "\n");
@@ -45,7 +45,7 @@ public class IrisChunkGeneratorMonumentLocateContractTest {
int reachabilityStart = source.indexOf("private Set<String> reachableStructureKeys", filterStart);
assertTrue(reachabilityStart > filterStart);
String filterMethod = source.substring(filterStart, reachabilityStart);
int policyFilter = filterMethod.indexOf("if (!decision.generate())");
int policyFilter = filterMethod.indexOf("if (!NativeStructureGenerationPolicy.generates(engine, key))");
int filterContinue = filterMethod.indexOf("continue;", policyFilter);
int emptyNativePartition = filterMethod.indexOf("if (candidates.isEmpty())", filterContinue);
int reachabilityLookup = filterMethod.indexOf("reachableStructureKeys(level)", emptyNativePartition);
@@ -119,7 +119,7 @@ public class IrisChunkGeneratorMonumentLocateContractTest {
@Test
public void nativePredictionIsReadOnlyUntilTheWinnerIsCommitted() throws IOException {
Path nativegen = Path.of(System.getProperty("iris.nativeStructurePostProcessorSource")).getParent();
Path nativegen = Path.of(System.getProperty("iris.nativeStructureFitBridgeSource")).getParent();
String source = Files.readString(nativegen.resolve("NativeStructureVanillaLocator.java")).replace("\r\n", "\n");
int predictionStart = source.indexOf("private static Candidate predictAt(");
int candidateStart = source.indexOf("public static final class Candidate", predictionStart);
@@ -131,33 +131,10 @@ public class IrisChunkGeneratorMonumentLocateContractTest {
assertTrue(candidate.contains("committed.compareAndSet(false, true)"));
}
@Test
public void stiltSupportUsesPlacedSolidOccupancyWithoutSnapshotDifferenceRequirement() throws IOException {
Path processor = Path.of(System.getProperty("iris.nativeStructurePostProcessorSource"));
String source = Files.readString(processor).replace("\r\n", "\n");
String foundation = Files.readString(
processor.resolveSibling("NativeStructureFoundationBuilder.java")).replace("\r\n", "\n");
int placement = source.indexOf("start.placeInChunk(world, structureManager, generator");
int stiltPlacement = source.indexOf("placeStilts(world, area, structureId, start", placement);
int stiltDefinition = foundation.indexOf("static void placeStilts(");
int occupancyCheck = foundation.indexOf("if (state.isSolid())", stiltDefinition);
int terrainFloor = foundation.indexOf("Math.max(terrainY,", stiltDefinition);
assertTrue(placement >= 0);
assertTrue(stiltPlacement > placement);
assertTrue(stiltDefinition >= 0);
assertTrue(occupancyCheck > stiltDefinition);
assertTrue(terrainFloor > stiltDefinition);
assertFalse(source.contains("state.equals("));
assertFalse(foundation.contains("state.equals("));
assertFalse(source.contains("snapshot.states"));
assertFalse(foundation.contains("snapshot.states"));
}
@Test
public void verticalPlacementMovesPiecesMonumentChildrenJigsawJunctionsAndCachedBoundsTogether() throws IOException {
String source = Files.readString(
Path.of(System.getProperty("iris.nativeStructurePostProcessorSource"))
Path.of(System.getProperty("iris.nativeStructureFitBridgeSource"))
.resolveSibling("NativeStructureVerticalPlacer.java")).replace("\r\n", "\n");
int placementStart = source.indexOf("public static int applyVerticalPlacement");
int shiftStart = source.indexOf("public static int applyVerticalShift", placementStart);
@@ -1,7 +1,7 @@
package art.arcane.iris.nativegen;
import art.arcane.iris.engine.object.structure.jigsaw.IrisJigsawConfiguration;
import art.arcane.iris.engine.object.structure.IrisStructureTerrain;
import art.arcane.iris.engine.framework.NativeJigsawOverrides;
import art.arcane.iris.engine.framework.NativeStructureReach;
import com.mojang.datafixers.util.Either;
import com.mojang.datafixers.util.Pair;
import com.mojang.serialization.MapCodec;
@@ -98,7 +98,8 @@ public class NativeStructureFactoryTest {
new Structure.StructureSettings(HolderSet.empty()));
assertThrows(IllegalStateException.class, () -> NativeStructureFactory.configure(
null, source, new IrisJigsawConfiguration(), false, 80));
null, source, new NativeJigsawOverrides("", "", null, null, null, null,
NativeJigsawOverrides.SOURCE, null, null, NativeJigsawOverrides.SOURCE), false, 80));
}
@Test
@@ -303,11 +304,11 @@ public class NativeStructureFactoryTest {
);
StructureStart boundaryResult = NativeStructureReferenceEnvelope.wrapForPublication(
boundary, source, 0, new IrisStructureTerrain(), "test:boundary_content");
boundary, source, 0, List.of(NativeStructureReach.PLATFORM), "test:boundary_content");
StructureStart result = NativeStructureReferenceEnvelope.wrapForPublication(
oversized, source, 0,
new IrisStructureTerrain(),
List.of(NativeStructureReach.PLATFORM),
"test:oversized_content");
assertTrue(boundaryResult.isValid());
@@ -1,7 +1,7 @@
package art.arcane.iris.nativegen;
import art.arcane.iris.engine.framework.NativeStructureOwnershipRecord;
import art.arcane.iris.engine.object.structure.vanilla.IrisNativeStructureDecision;
import art.arcane.iris.engine.framework.NativeStartMemo;
import art.arcane.iris.engine.framework.nativefit.NativeStructureFitting;
import com.mojang.datafixers.util.Either;
import net.minecraft.SharedConstants;
import net.minecraft.core.BlockPos;
@@ -61,12 +61,15 @@ import static org.junit.Assert.assertTrue;
* starts with real pieces and inline templates, and fit records written the way ownership records persist them. It
* then runs the chunk's fit in the generator's order (terrain fitting for every start, then each start's pieces and
* stilts, then the foundation repair) with a fixed stand-in for the platform's piece placement, and hashes every block
* that differs from the untouched terrain.
* that differs from the untouched terrain. The hashes were taken from the platform-side fit before it moved into the
* structure module; they now run through the platform bridge and the built-in modules.
*/
public class NativeStructureFitPinTest {
private static final long WORLD_SEED = 8675309L;
private static final int SEA_LEVEL = 61;
private static final BoundingBox CHUNK_AREA = new BoundingBox(0, -63, 0, 15, 318, 15);
private static final int WORLD_MIN_Y = -64;
private static final int WORLD_HEIGHT = 384;
private static final BoundingBox CHUNK_AREA = new BoundingBox(0, WORLD_MIN_Y + 1, 0, 15, WORLD_MIN_Y + WORLD_HEIGHT - 2, 15);
private static final String NO_STILTS = "null";
private static final String SOURCE_TERRAIN = "{}";
@@ -117,35 +120,27 @@ public class NativeStructureFitPinTest {
return terrain.changedBlocksHash(CHUNK_AREA);
}
/** The chunk's fit in the order the generators run it; the platform's placement is {@link #placePieces}. */
/**
* The chunk's fit in the order the generators run it, through the platform bridge and the built-in modules: the
* fit before any piece, then each start's pieces ({@link #placePieces}) and its fit after them.
*/
private static void fitChunk(WorldGenLevel world, Scenario scenario) {
IntBinaryOperator surface = TerrainWorld::surfaceY;
List<NativeStructureTerrainIntegrator.TerrainTarget> targets = new ArrayList<>();
List<IrisNativeStructureDecision> decisions = new ArrayList<>();
List<NativeStructureFitBridge.FitTarget> targets = new ArrayList<>();
for (FitTarget target : scenario.targets()) {
IrisNativeStructureDecision decision = new NativeStructureOwnershipRecord.DecisionSnapshot(
target.stiltJson(), target.terrainJson()).restore();
decisions.add(decision);
targets.add(new NativeStructureTerrainIntegrator.TerrainTarget(target.structureId(), target.start(),
NativeStructureTerrainIntegrator.resolveNativeTerrain(target.start(), decision.terrain())));
targets.add(new NativeStructureFitBridge.FitTarget(target.structureId(), target.start(),
new NativeStartMemo(target.terrainJson(), target.stiltJson())));
}
NativeStructureSurfaceFitter.VacuumFoundationPlan plan = NativeStructureSurfaceFitter.prepareSurfaceStructures(
world, CHUNK_AREA, targets, surface);
NativeStructurePostProcessor.prepareTerrain(world, CHUNK_AREA, targets, NativeStructureFitPinTest::noPalette);
NativeStructureFitting.Session fit = BuiltInFitting.FITTING.beforePieces(
NativeStructureFitBridge.chunk(world, CHUNK_AREA, targets, TerrainWorld::surfaceY));
for (int index = 0; index < targets.size(); index++) {
FitTarget target = scenario.targets().get(index);
placePieces(world, target);
if (decisions.get(index).stilt() != null) {
NativeStructureFoundationBuilder.placeStilts(world, CHUNK_AREA, target.structureId(), target.start(),
decisions.get(index).stilt(), NativeStructureFitPinTest::noPalette, surface,
!NativeStructureVegetationClearer.isUndergroundStep(target.start().getStructure().step()));
}
placePieces(world, scenario.targets().get(index));
fit.afterPieces(index);
}
NativeStructureSurfaceFitter.repairVacuumFoundations(world, CHUNK_AREA, plan);
}
private static BlockState noPalette(Object palette, Object rng, int x, int y, int z) {
throw new AssertionError("The pinned scenarios use the default fill blocks, never a palette");
/** The built-in modules load once for every scenario. */
private static final class BuiltInFitting {
private static final NativeStructureFitting FITTING = NativeStructureFitting.builtInModules();
}
/**
@@ -541,7 +536,8 @@ public class NativeStructureFitPinTest {
yield true;
}
case "getSeed" -> WORLD_SEED;
case "getHeight" -> heightmapY((int) arguments[1], (int) arguments[2]);
case "getMinY" -> WORLD_MIN_Y;
case "getHeight" -> arguments == null ? WORLD_HEIGHT : heightmapY((int) arguments[1], (int) arguments[2]);
case "getLevel" -> null;
case "holderLookup" -> BuiltInRegistries.BLOCK;
case "hashCode" -> System.identityHashCode(proxy);
@@ -1,8 +1,6 @@
package art.arcane.iris.nativegen;
import art.arcane.iris.engine.framework.NativeStructureOwnershipRecord;
import art.arcane.iris.engine.object.structure.IrisStructureYBand;
import com.google.gson.Gson;
import art.arcane.iris.engine.framework.NativeStructureReach;
import net.minecraft.SharedConstants;
import net.minecraft.core.HolderSet;
import net.minecraft.server.Bootstrap;
@@ -21,6 +19,7 @@ import org.junit.BeforeClass;
import org.junit.Test;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.function.IntBinaryOperator;
@@ -30,15 +29,18 @@ import static org.junit.Assert.assertEquals;
/**
* Pins where the platform's own starts end up vertically for each adjustment the dimension can give them (shift,
* band, keeping the platform's height, burial under the terrain), and which chunks a start reaches for each terrain
* fit, so both can move without changing what a world generates.
* fit. The values were taken before the fit moved into the structure module; since then the module answers the shift
* and the reach ({@code StartLayoutsPinTest} in core pins those answers for the same starts) and the platform side,
* pinned here, aligns, moves and references the starts with them.
*/
public class NativeStructureLayoutPinTest {
private static final Gson GSON = new Gson();
private static final int SEA_LEVEL = 61;
private static final int WORLD_MIN_Y = -64;
private static final int WORLD_MAX_Y_EXCLUSIVE = 320;
private static final IntBinaryOperator SURFACE = (x, z) -> 62 + Math.floorMod(x * 7 + z * 3, 11) - 5;
private static final int[][] CHUNKS = {{0, 0}, {3, -5}, {-11, 7}};
private static final Map<String, Integer> ADJUSTMENT_SHIFTS = adjustmentShifts();
private static final Map<String, NativeStructureReach> TERRAIN_REACHES = terrainReaches();
private static final List<String> PINNED_SHIFTS = List.of(
"none minecraft:stronghold 0,0 offset 0 minY 50",
@@ -118,63 +120,68 @@ public class NativeStructureLayoutPinTest {
Bootstrap.bootStrap();
}
/**
* The module's shift for a stronghold is the move it makes; for a desert temple, which the platform aligns to the
* terrain itself, it is the adjustment's own shift on top of that alignment.
*/
@Test
public void platformStartsMoveWhereTheirAdjustmentSays() {
List<String> actual = new ArrayList<>();
for (Adjustment adjustment : adjustments()) {
for (int[] chunkXZ : CHUNKS) {
ChunkPos chunk = new ChunkPos(chunkXZ[0], chunkXZ[1]);
for (String structureId : List.of("minecraft:stronghold", "minecraft:desert_pyramid")) {
StructureStart start = start(chunk, structureId.equals("minecraft:stronghold") ? 50 : 64,
TerrainAdjustment.NONE);
int offset = NativeStructureVerticalPlacer.applyVerticalPlacement(start, structureId,
adjustment.yShift(), SEA_LEVEL, WORLD_MIN_Y, WORLD_MAX_Y_EXCLUSIVE, adjustment.underground(),
adjustment.keepsSourceY(), band(adjustment.bandJson()), SURFACE);
actual.add(adjustment.name() + " " + structureId + " " + chunk.x() + "," + chunk.z()
+ " offset " + offset + " minY " + start.getBoundingBox().minY());
}
}
for (String pinned : PINNED_SHIFTS) {
String[] parts = pinned.split(" ");
String structureId = parts[1];
String[] chunkXZ = parts[2].split(",");
ChunkPos chunk = new ChunkPos(Integer.parseInt(chunkXZ[0]), Integer.parseInt(chunkXZ[1]));
boolean stronghold = structureId.equals("minecraft:stronghold");
int moduleShift = stronghold ? Integer.parseInt(parts[4]) : ADJUSTMENT_SHIFTS.get(parts[0]);
StructureStart start = start(chunk, stronghold ? 50 : 64, TerrainAdjustment.NONE);
int offset = NativeStructureVerticalPlacer.applyVerticalPlacement(start, structureId, moduleShift,
SEA_LEVEL, WORLD_MIN_Y, WORLD_MAX_Y_EXCLUSIVE, SURFACE);
actual.add(parts[0] + " " + structureId + " " + parts[2] + " offset " + offset
+ " minY " + start.getBoundingBox().minY());
}
assertEquals("Pinned shifts changed:\n" + String.join("\n", quoted(actual)), PINNED_SHIFTS, actual);
assertEquals(PINNED_SHIFTS, actual);
}
@Test
public void startsReachTheChunksTheirTerrainFitSays() {
List<String> actual = new ArrayList<>();
for (String terrainJson : List.of("{}", "{\"mode\":\"PRESERVE\"}", "{\"mode\":\"VACUUM\"}",
"{\"mode\":\"ENCASE\",\"horizontalPadding\":4}", "{\"mode\":\"BORE\",\"horizontalPadding\":20}",
"{\"mode\":\"FORCE_CARVE\",\"horizontalPadding\":112}", "{\"mode\":\"FORCE_CARVE\",\"horizontalPadding\":0}")) {
for (Map.Entry<String, NativeStructureReach> fit : TERRAIN_REACHES.entrySet()) {
for (TerrainAdjustment adjustment : List.of(TerrainAdjustment.NONE, TerrainAdjustment.BEARD_THIN, TerrainAdjustment.BURY)) {
StructureStart start = start(new ChunkPos(2, -3), 40, adjustment);
BoundingBox bounds = NativeStructureReferenceEnvelope.referenceBounds(start, start.getStructure(),
NativeStructureTerrainIntegrator.resolveNativeTerrain(start,
new NativeStructureOwnershipRecord.DecisionSnapshot("null", terrainJson).restore().terrain()),
"minecraft:village_plains");
actual.add(terrainJson + " " + adjustment + " " + bounds.minX() + "," + bounds.minY() + "," + bounds.minZ()
List.of(fit.getValue()), "minecraft:village_plains");
actual.add(fit.getKey() + " " + adjustment + " " + bounds.minX() + "," + bounds.minY() + "," + bounds.minZ()
+ " " + bounds.maxX() + "," + bounds.maxY() + "," + bounds.maxZ());
}
}
assertEquals("Pinned reaches changed:\n" + String.join("\n", quoted(actual)), PINNED_REACHES, actual);
assertEquals(PINNED_REACHES, actual);
}
private static List<String> quoted(List<String> lines) {
return lines.stream().map(line -> " \"" + line.replace("\"", "\\\"") + "\",").toList();
private static Map<String, Integer> adjustmentShifts() {
Map<String, Integer> shifts = new LinkedHashMap<>();
shifts.put("none", 0);
shifts.put("shift", 5);
shifts.put("burial", -7);
shifts.put("burial-unshifted", 0);
shifts.put("kept", 3);
shifts.put("band", 0);
shifts.put("narrow-band", 4);
shifts.put("kept-over-band", 2);
return shifts;
}
private static List<Adjustment> adjustments() {
return List.of(
new Adjustment("none", 0, null, false, false),
new Adjustment("shift", 5, null, false, false),
new Adjustment("burial", -7, null, false, true),
new Adjustment("burial-unshifted", 0, null, false, true),
new Adjustment("kept", 3, null, true, true),
new Adjustment("band", 0, "{\"min\":-50,\"max\":20}", false, true),
new Adjustment("narrow-band", 4, "{\"min\":10,\"max\":12}", false, false),
new Adjustment("kept-over-band", 2, "{\"min\":-40,\"max\":80}", true, false));
}
private static IrisStructureYBand band(String json) {
return json == null ? null : GSON.fromJson(json, IrisStructureYBand.class);
/** What the structure module answers for each terrain fit (pinned in core by {@code StartLayoutsPinTest}). */
private static Map<String, NativeStructureReach> terrainReaches() {
Map<String, NativeStructureReach> reaches = new LinkedHashMap<>();
reaches.put("{}", NativeStructureReach.PLATFORM);
reaches.put("{\"mode\":\"PRESERVE\"}", new NativeStructureReach(false, 0));
reaches.put("{\"mode\":\"VACUUM\"}", new NativeStructureReach(false, 12));
reaches.put("{\"mode\":\"ENCASE\",\"horizontalPadding\":4}", new NativeStructureReach(false, 4));
reaches.put("{\"mode\":\"BORE\",\"horizontalPadding\":20}", new NativeStructureReach(false, 20));
reaches.put("{\"mode\":\"FORCE_CARVE\",\"horizontalPadding\":112}", new NativeStructureReach(false, 112));
reaches.put("{\"mode\":\"FORCE_CARVE\",\"horizontalPadding\":0}", new NativeStructureReach(false, 0));
return reaches;
}
private static StructureStart start(ChunkPos chunk, int minY, TerrainAdjustment adjustment) {
@@ -184,7 +191,4 @@ public class NativeStructureLayoutPinTest {
piece.move(0, minY - piece.getBoundingBox().minY(), 0);
return new StructureStart(structure, chunk, 0, new PiecesContainer(List.of(piece)));
}
private record Adjustment(String name, int yShift, String bandJson, boolean keepsSourceY, boolean underground) {
}
}
@@ -4,8 +4,8 @@ import art.arcane.iris.engine.framework.NativeStructureOwnershipRecord;
import art.arcane.iris.engine.framework.NativeStructureStartPlan;
import art.arcane.iris.engine.framework.StructurePlacementGrid;
import art.arcane.iris.engine.object.structure.IrisStructurePlacement;
import art.arcane.iris.engine.object.structure.IrisStructureTerrain;
import art.arcane.iris.engine.object.structure.IrisStructureTerrainMode;
import art.arcane.iris.engine.framework.NativeStartMemo;
import art.arcane.iris.engine.framework.NativeStructureReach;
import net.minecraft.SharedConstants;
import net.minecraft.core.BlockPos;
import net.minecraft.core.Direction;
@@ -63,9 +63,7 @@ public class NativeStructureOwnershipFingerprintTest {
NativeStructureVerticalPlacer.alignOceanMonumentToSeaLevel(
generated, 0, 80, -64, 320);
int alignedLocatorY = NativeStructureOwnershipFingerprint.locatorY(generated);
IrisStructureTerrain terrain = new IrisStructureTerrain()
.setMode(IrisStructureTerrainMode.FORCE_CARVE)
.setHorizontalPadding(24);
List<NativeStructureReach> terrain = List.of(new NativeStructureReach(false, 24));
StructureStart wrapped = NativeStructureReferenceEnvelope.wrap(
generated,
structure,
@@ -127,9 +125,7 @@ public class NativeStructureOwnershipFingerprintTest {
StructureStart generated = monumentStart(structure, origin, seed);
NativeStructureVerticalPlacer.alignOceanMonumentToSeaLevel(
generated, 0, 80, -64, 320);
IrisStructureTerrain terrain = new IrisStructureTerrain()
.setMode(IrisStructureTerrainMode.FORCE_CARVE)
.setHorizontalPadding(24);
List<NativeStructureReach> terrain = List.of(new NativeStructureReach(false, 24));
StructureStart wrapped = NativeStructureReferenceEnvelope.wrap(
generated,
structure,
@@ -247,7 +243,7 @@ public class NativeStructureOwnershipFingerprintTest {
private static NativeStructureStartPlan plan(ChunkPos origin, int baseY) {
return new NativeStructureStartPlan("minecraft:monument", origin.x(), origin.z(), baseY, false, false,
StructurePlacementGrid.placementIdentity(new IrisStructurePlacement().setPlacementId("monument-test")),
null, null, new IrisStructureTerrain());
null, new NativeStartMemo("{\"mode\":\"SOURCE\"}", "null"));
}
private static NativeStructureOwnershipRecord ownership(
@@ -257,7 +253,7 @@ public class NativeStructureOwnershipFingerprintTest {
start,
plan(origin, NativeStructureReferenceEnvelope.contentBounds(start).minY()),
NativeStructureReferenceEnvelope.referenceBounds(
start, structure, new IrisStructureTerrain())
start, structure, List.of(NativeStructureReach.PLATFORM))
);
}
@@ -3,9 +3,9 @@ package art.arcane.iris.nativegen;
import art.arcane.iris.engine.framework.NativeStructureOwnershipRecord;
import art.arcane.iris.engine.framework.NativeStructureStartPlan;
import art.arcane.iris.engine.framework.StructurePlacementGrid;
import art.arcane.iris.engine.framework.NativeStartMemo;
import art.arcane.iris.engine.framework.NativeStructureReach;
import art.arcane.iris.engine.object.structure.IrisStructurePlacement;
import art.arcane.iris.engine.object.structure.IrisStructureTerrain;
import art.arcane.iris.engine.object.structure.IrisStructureTerrainMode;
import net.minecraft.SharedConstants;
import net.minecraft.core.Direction;
import net.minecraft.core.HolderSet;
@@ -61,7 +61,7 @@ public class NativeStructureOwnershipRecoveryTest {
NativeStructureOwnershipRecord recovered =
NativeStructureOwnershipRecovery.proveCandidate(
"minecraft:monument", structure, reloaded,
plan, expected, false);
plan, expected, false, reaches(plan));
assertNotNull(recovered);
assertEquals(plan.placementIdentity(),
@@ -69,9 +69,7 @@ public class NativeStructureOwnershipRecoveryTest {
assertEquals(expectedLocatorY, recovered.locatorY());
assertNotEquals(NativeStructureOwnershipFingerprint.locatorY(reloaded),
recovered.locatorY());
assertEquals(IrisStructureTerrainMode.FORCE_CARVE,
recovered.restoredDecision().terrain().resolvedMode());
assertEquals(24, recovered.restoredDecision().terrain().getHorizontalPadding());
assertEquals(plan.memo(), recovered.restoredMemo());
assertTrue(recovered.referenceMinChunkX()
< NativeStructureReferenceEnvelope.contentBounds(reloaded).minX() >> 4);
}
@@ -87,7 +85,7 @@ public class NativeStructureOwnershipRecoveryTest {
NativeStructureOwnershipRecord recovered =
NativeStructureOwnershipRecovery.proveCandidate(
"minecraft:monument", structure, natural,
plan, natural, true);
plan, natural, true, reaches(plan));
assertNull(recovered);
}
@@ -112,10 +110,10 @@ public class NativeStructureOwnershipRecoveryTest {
changedIdentity.placementIdentity());
assertNull(NativeStructureOwnershipRecovery.proveCandidate(
"minecraft:monument", structure, expected,
changedIdentity, expected, false));
changedIdentity, expected, false, reaches(changedIdentity)));
assertNull(NativeStructureOwnershipRecovery.proveCandidate(
"minecraft:monument", structure, changedGeometry,
plan(origin, "geometry-check", 0), expected, false));
plan(origin, "geometry-check", 0), expected, false, reaches(plan(origin, "geometry-check", 0))));
}
@Test
@@ -127,7 +125,7 @@ public class NativeStructureOwnershipRecoveryTest {
NativeStructureOwnershipRecord recovered =
NativeStructureOwnershipRecovery.proveCandidate(
"minecraft:monument", structure, expected,
plan(origin, "fingerprint-check", 16), expected, false);
plan(origin, "fingerprint-check", 16), expected, false, reaches(plan(origin, "fingerprint-check", 16)));
assertNotNull(recovered);
StructureStart moved = monumentStart(structure, origin, seed);
@@ -146,14 +144,14 @@ public class NativeStructureOwnershipRecoveryTest {
OceanMonumentStructure structure = structure();
StructureStart start = monumentStart(structure, origin, seed);
NativeStructureStartPlan plan = plan(
origin, "vacuum-envelope-refresh", IrisStructureTerrainMode.VACUUM, 0);
origin, "vacuum-envelope-refresh", "VACUUM", 0);
BoundingBox content = NativeStructureReferenceEnvelope.contentBounds(start);
NativeStructureOwnershipRecord stale = NativeStructureOwnershipFingerprint.capture(
structureKey, start, plan, content);
NativeStructureOwnershipRecord refreshed =
NativeStructureOwnershipRecovery.refreshReferenceEnvelope(
structureKey, structure, start, stale);
structureKey, structure, start, stale, reaches(plan));
assertNotNull(refreshed);
assertNotEquals(stale, refreshed);
@@ -163,18 +161,16 @@ public class NativeStructureOwnershipRecoveryTest {
assertEquals(stale.baseY(), refreshed.baseY());
assertEquals(stale.locatorY(), refreshed.locatorY());
assertEquals(stale.contentFingerprint(), refreshed.contentFingerprint());
assertEquals(stale.decision(), refreshed.decision());
assertEquals(IrisStructureTerrainMode.VACUUM,
refreshed.restoredDecision().terrain().resolvedMode());
assertEquals(stale.memo(), refreshed.memo());
BoundingBox expected = NativeStructureReferenceEnvelope.referenceBounds(
start, structure, plan.terrain(), structureKey);
start, structure, reaches(plan), structureKey);
assertEquals(expected.minX() >> 4, refreshed.referenceMinChunkX());
assertEquals(expected.maxX() >> 4, refreshed.referenceMaxChunkX());
assertEquals(expected.minZ() >> 4, refreshed.referenceMinChunkZ());
assertEquals(expected.maxZ() >> 4, refreshed.referenceMaxChunkZ());
assertTrue(hasExpandedCoverage(stale, refreshed));
assertSame(refreshed, NativeStructureOwnershipRecovery.refreshReferenceEnvelope(
structureKey, structure, start, refreshed));
structureKey, structure, start, refreshed, reaches(plan)));
}
@Test
@@ -185,7 +181,7 @@ public class NativeStructureOwnershipRecoveryTest {
OceanMonumentStructure structure = structure();
StructureStart expected = monumentStart(structure, origin, seed);
NativeStructureStartPlan plan = plan(
origin, "vacuum-content-check", IrisStructureTerrainMode.VACUUM, 0);
origin, "vacuum-content-check", "VACUUM", 0);
NativeStructureOwnershipRecord stale = NativeStructureOwnershipFingerprint.capture(
structureKey, expected, plan,
NativeStructureReferenceEnvelope.contentBounds(expected));
@@ -195,7 +191,7 @@ public class NativeStructureOwnershipRecoveryTest {
}
assertNull(NativeStructureOwnershipRecovery.refreshReferenceEnvelope(
structureKey, structure, moved, stale));
structureKey, structure, moved, stale, reaches(plan)));
}
@Test
@@ -207,12 +203,27 @@ public class NativeStructureOwnershipRecoveryTest {
StructureStart start = monumentStart(structure, origin, seed);
NativeStructureStartPlan plan = plan(origin, "current-force-carve", 24);
BoundingBox envelope = NativeStructureReferenceEnvelope.referenceBounds(
start, structure, plan.terrain(), structureKey);
start, structure, reaches(plan), structureKey);
NativeStructureOwnershipRecord ownership = NativeStructureOwnershipFingerprint.capture(
structureKey, start, plan, envelope);
assertSame(ownership, NativeStructureOwnershipRecovery.refreshReferenceEnvelope(
structureKey, structure, start, ownership));
structureKey, structure, start, ownership, reaches(plan)));
}
@Test
public void aRecordedEnvelopeWiderThanTodaysReachNeverShrinks() {
String structureKey = "minecraft:monument";
long seed = 927451L;
ChunkPos origin = new ChunkPos(3, 8);
OceanMonumentStructure structure = structure();
StructureStart start = monumentStart(structure, origin, seed);
NativeStructureStartPlan plan = plan(origin, "wide-force-carve", 24);
NativeStructureOwnershipRecord ownership = NativeStructureOwnershipFingerprint.capture(structureKey, start, plan,
NativeStructureReferenceEnvelope.referenceBounds(start, structure, reaches(plan), structureKey));
assertSame(ownership, NativeStructureOwnershipRecovery.refreshReferenceEnvelope(
structureKey, structure, start, ownership, List.of(NativeStructureReach.PLATFORM)));
}
@Test
@@ -230,16 +241,16 @@ public class NativeStructureOwnershipRecoveryTest {
piece.move(shiftX, 0, 0);
}
NativeStructureStartPlan plan = plan(
origin, "clipped-vacuum", IrisStructureTerrainMode.VACUUM, 0);
origin, "clipped-vacuum", "VACUUM", 0);
BoundingBox envelope = NativeStructureReferenceEnvelope.referenceBounds(
start, structure, plan.terrain(), structureKey);
start, structure, reaches(plan), structureKey);
NativeStructureOwnershipRecord ownership = NativeStructureOwnershipFingerprint.capture(
structureKey, start, plan, envelope);
assertEquals(origin.x() + NativeStructureOwnershipRecord.MAX_REFERENCE_DISTANCE_CHUNKS,
ownership.referenceMaxChunkX());
assertSame(ownership, NativeStructureOwnershipRecovery.refreshReferenceEnvelope(
structureKey, structure, start, ownership));
structureKey, structure, start, ownership, reaches(plan)));
}
private static OceanMonumentStructure structure() {
@@ -267,17 +278,15 @@ public class NativeStructureOwnershipRecoveryTest {
private static NativeStructureStartPlan plan(ChunkPos origin,
String placementId,
int horizontalPadding) {
return plan(origin, placementId,
IrisStructureTerrainMode.FORCE_CARVE, horizontalPadding);
return plan(origin, placementId, "FORCE_CARVE", horizontalPadding);
}
/** A start the structure module placed with a terrain fit of {@code terrainMode}, as its memo records it. */
private static NativeStructureStartPlan plan(ChunkPos origin,
String placementId,
IrisStructureTerrainMode terrainMode,
String terrainMode,
int horizontalPadding) {
IrisStructureTerrain terrain = new IrisStructureTerrain()
.setMode(terrainMode)
.setHorizontalPadding(horizontalPadding);
String terrain = "{\"mode\":\"" + terrainMode + "\",\"horizontalPadding\":" + horizontalPadding + "}";
return new NativeStructureStartPlan(
"minecraft:monument",
origin.x(),
@@ -288,11 +297,17 @@ public class NativeStructureOwnershipRecoveryTest {
false,
StructurePlacementGrid.placementIdentity(new IrisStructurePlacement().setPlacementId(placementId)),
null,
null,
terrain
new NativeStartMemo(terrain, "null")
);
}
/** The reach the structure module gives the plan's terrain fit: VACUUM its 12-block falloff, else the padding. */
private static List<NativeStructureReach> reaches(NativeStructureStartPlan plan) {
String terrain = plan.memo().terrain();
int padding = Integer.parseInt(terrain.replaceAll(".*\"horizontalPadding\":(\\d+).*", "$1"));
return List.of(new NativeStructureReach(false, terrain.contains("VACUUM") ? 12 : padding));
}
private static boolean hasExpandedCoverage(
NativeStructureOwnershipRecord stale,
NativeStructureOwnershipRecord refreshed) {
@@ -1,547 +0,0 @@
package art.arcane.iris.nativegen;
import art.arcane.iris.engine.object.material.IrisMaterialPalette;
import art.arcane.iris.engine.object.structure.IrisStructureTerrain;
import art.arcane.iris.engine.object.structure.IrisStructureTerrainMode;
import art.arcane.iris.engine.object.structure.IrisStructureYBand;
import art.arcane.volmlib.util.math.RNG;
import net.minecraft.SharedConstants;
import net.minecraft.core.BlockPos;
import net.minecraft.core.Holder;
import net.minecraft.core.HolderSet;
import net.minecraft.core.registries.Registries;
import net.minecraft.resources.Identifier;
import net.minecraft.resources.ResourceKey;
import net.minecraft.server.Bootstrap;
import net.minecraft.util.RandomSource;
import net.minecraft.world.level.ChunkPos;
import net.minecraft.world.level.Level;
import net.minecraft.world.level.WorldGenLevel;
import net.minecraft.world.level.block.Blocks;
import net.minecraft.world.level.block.Rotation;
import net.minecraft.world.level.block.state.BlockState;
import net.minecraft.world.level.dimension.BuiltinDimensionTypes;
import net.minecraft.world.level.levelgen.GenerationStep;
import net.minecraft.world.level.levelgen.structure.BoundingBox;
import net.minecraft.world.level.levelgen.structure.PoolElementStructurePiece;
import net.minecraft.world.level.levelgen.structure.Structure;
import net.minecraft.world.level.levelgen.structure.StructurePiece;
import net.minecraft.world.level.levelgen.structure.StructureStart;
import net.minecraft.world.level.levelgen.structure.TerrainAdjustment;
import net.minecraft.world.level.levelgen.structure.pieces.PiecesContainer;
import net.minecraft.world.level.levelgen.structure.pools.StructurePoolElement;
import net.minecraft.world.level.levelgen.structure.pools.StructureTemplatePool;
import net.minecraft.world.level.levelgen.structure.structures.DesertPyramidPiece;
import net.minecraft.world.level.levelgen.structure.structures.DesertPyramidStructure;
import net.minecraft.world.level.levelgen.structure.templatesystem.BlockIgnoreProcessor;
import net.minecraft.world.level.levelgen.structure.templatesystem.LiquidSettings;
import net.minecraft.world.level.levelgen.structure.templatesystem.StructureProcessorList;
import org.junit.BeforeClass;
import org.junit.Test;
import java.io.IOException;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Proxy;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.BitSet;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertThrows;
import static org.junit.Assert.assertTrue;
public class NativeStructurePostProcessorEncaseTest {
private static final long TEST_SEED = 1234L;
@BeforeClass
public static void bootstrapMinecraft() {
SharedConstants.tryDetectVersion();
Bootstrap.bootStrap();
}
@Test
public void encaseFillsAirAndLiquidWithoutOverwritingExistingTerrain() {
StructureStart start = start(TerrainAdjustment.BURY, 64);
BoundingBox bounds = start.getPieces().getFirst().getBoundingBox();
BoundingBox area = new BoundingBox(
bounds.minX() - 1, bounds.minY() - 1, bounds.minZ() - 1,
bounds.maxX() + 1, bounds.maxY() + 1, bounds.maxZ() + 1);
Map<BlockPos, BlockState> blocks = new HashMap<>();
put(blocks, bounds.minX(), bounds.minY(), bounds.minZ(), Blocks.DIRT.defaultBlockState());
put(blocks, bounds.maxX(), bounds.minY(), bounds.maxZ(), Blocks.WATER.defaultBlockState());
NativeStructureTerrainIntegrator.integrateTerrain(
world(blocks), area, "minecraft:stronghold", start,
new IrisStructureTerrain()
.setMode(IrisStructureTerrainMode.ENCASE)
.setHorizontalPadding(1)
.setCeilingPadding(1)
.setFloorPadding(1),
null);
assertEquals(Blocks.DIRT.defaultBlockState(),
state(blocks, bounds.minX(), bounds.minY(), bounds.minZ()));
assertEquals(Blocks.STONE.defaultBlockState(),
state(blocks, bounds.maxX(), bounds.minY(), bounds.maxZ()));
assertEquals(Blocks.STONE.defaultBlockState(),
state(blocks, bounds.minX() - 1, bounds.minY() - 1, bounds.minZ() - 1));
assertEquals(Blocks.STONE.defaultBlockState(),
state(blocks, bounds.maxX() + 1, bounds.maxY() + 1, bounds.maxZ() + 1));
}
@Test
public void defaultEncasePaletteSplitsStoneAboveZeroAndDeepslateBelow() {
StructureStart start = start(TerrainAdjustment.BURY, -1);
BoundingBox bounds = start.getPieces().getFirst().getBoundingBox();
Map<BlockPos, BlockState> blocks = new HashMap<>();
NativeStructureTerrainIntegrator.integrateTerrain(
world(blocks), bounds, "minecraft:stronghold", start,
new IrisStructureTerrain().setMode(IrisStructureTerrainMode.ENCASE),
null);
assertEquals(-1, bounds.minY());
assertEquals(Blocks.DEEPSLATE.defaultBlockState(),
state(blocks, bounds.minX(), -1, bounds.minZ()));
assertEquals(Blocks.STONE.defaultBlockState(),
state(blocks, bounds.minX(), 0, bounds.minZ()));
}
@Test
public void defaultEncaseMaterialFollowsVanillaDimensionTerrain() {
assertEquals(Blocks.NETHERRACK.defaultBlockState(),
NativeStructureTerrainIntegrator.defaultEncaseBlock(Level.NETHER, 64));
assertEquals(Blocks.END_STONE.defaultBlockState(),
NativeStructureTerrainIntegrator.defaultEncaseBlock(Level.END, 64));
assertEquals(Blocks.STONE.defaultBlockState(),
NativeStructureTerrainIntegrator.defaultEncaseBlock(Level.OVERWORLD, 64));
}
@Test
public void sourceEncaseMaterialFollowsNearbyIrisTerrain() {
Map<BlockPos, BlockState> blocks = new HashMap<>();
BlockPos fill = new BlockPos(4, 64, 8);
put(blocks, fill.getX() + 3, fill.getY(), fill.getZ(), Blocks.TUFF.defaultBlockState());
assertEquals(Blocks.TUFF.defaultBlockState(),
NativeStructureTerrainIntegrator.sourceEncaseBlock(world(blocks), fill));
}
@Test
public void sourceMaterialSnapshotIgnoresPreviouslyDecoratedAdjacentChunks() {
Map<BlockPos, BlockState> blocks = new HashMap<>();
BlockPos fill = new BlockPos(0, 64, 8);
put(blocks, -1, 64, 8, Blocks.OAK_PLANKS.defaultBlockState());
put(blocks, 3, 64, 8, Blocks.TUFF.defaultBlockState());
WorldGenLevel world = world(blocks);
NativeStructureTerrainIntegrator.SourceTerrainSnapshot sourceTerrain =
sourceSnapshot(world, new BoundingBox(0, 64, 0, 15, 64, 15));
assertEquals(Blocks.TUFF.defaultBlockState(),
NativeStructureTerrainIntegrator.sourceEncaseBlock(
world, fill, sourceTerrain));
}
@Test
public void sourceMaterialSnapshotIsStableAcrossEarlierFillsInTheSameChunk() {
Map<BlockPos, BlockState> blocks = new HashMap<>();
BlockPos fill = new BlockPos(0, 64, 8);
put(blocks, 3, 64, 8, Blocks.TUFF.defaultBlockState());
WorldGenLevel world = world(blocks);
NativeStructureTerrainIntegrator.SourceTerrainSnapshot sourceTerrain =
sourceSnapshot(world, new BoundingBox(0, 64, 0, 15, 64, 15));
put(blocks, 1, 64, 8, Blocks.OAK_PLANKS.defaultBlockState());
assertEquals(Blocks.TUFF.defaultBlockState(),
NativeStructureTerrainIntegrator.sourceEncaseBlock(
world, fill, sourceTerrain));
}
@Test
public void sourceMaterialRejectsStructureBlocksAndOresBeforeDimensionFallback() {
Map<BlockPos, BlockState> blocks = new HashMap<>();
BlockPos fill = new BlockPos(4, -20, 8);
put(blocks, 3, -20, 8, Blocks.OAK_PLANKS.defaultBlockState());
put(blocks, 5, -20, 8, Blocks.STONE_BRICKS.defaultBlockState());
put(blocks, 4, -20, 7, Blocks.IRON_ORE.defaultBlockState());
assertEquals(Blocks.DEEPSLATE.defaultBlockState(),
NativeStructureTerrainIntegrator.sourceEncaseBlock(world(blocks), fill));
}
@Test
public void sourceMaterialSnapshotOnlyAllocatesActualFillLayers() {
StructureStart start = start(TerrainAdjustment.BURY, 64);
BoundingBox area = new BoundingBox(0, -2032, 0, 15, 2030, 15);
NativeStructureTerrainIntegrator.SourceTerrainSnapshot sourceTerrain =
NativeStructureTerrainIntegrator.captureSourceTerrain(
world(new HashMap<>()), area,
List.of(new NativeStructureTerrainIntegrator.TerrainTarget(
"test:bounded-snapshot", start,
new IrisStructureTerrain().setMode(IrisStructureTerrainMode.SOURCE))));
assertNotNull(sourceTerrain);
assertEquals(23 * 16 * 16, sourceTerrain.sampledCells());
}
@Test
public void customDimensionKeyUsesRegisteredVanillaDimensionType() {
ResourceKey<Level> customDimension = ResourceKey.create(
Registries.DIMENSION, Identifier.parse("iris:custom_nether"));
assertEquals(Blocks.NETHERRACK.defaultBlockState(),
NativeStructureTerrainIntegrator.defaultEncaseBlock(
customDimension, BuiltinDimensionTypes.NETHER, null, 64));
assertEquals(Blocks.END_STONE.defaultBlockState(),
NativeStructureTerrainIntegrator.defaultEncaseBlock(
customDimension, BuiltinDimensionTypes.END, null, 64));
}
@Test
public void configuredEncasePaletteReplacesTheDefaultMaterial() {
StructureStart start = start(TerrainAdjustment.BURY, 64);
BoundingBox bounds = start.getPieces().getFirst().getBoundingBox();
Map<BlockPos, BlockState> blocks = new HashMap<>();
IrisMaterialPalette palette = new IrisMaterialPalette().qclear().qadd("minecraft:tuff");
NativeStructureTerrainIntegrator.integrateTerrain(
world(blocks), bounds, "minecraft:stronghold", start,
new IrisStructureTerrain()
.setMode(IrisStructureTerrainMode.ENCASE)
.setEncasePalette(palette),
NativeStructurePostProcessorEncaseTest::tuffBlock);
assertEquals(Blocks.TUFF.defaultBlockState(),
state(blocks, bounds.minX(), bounds.minY(), bounds.minZ()));
}
@Test
public void encaseFillRunsBeforeNativePlacement() throws IOException {
String source = Files.readString(Path.of(System.getProperty("iris.nmsChunkGeneratorSource"))).replace("\r\n", "\n");
int prepareTerrain = source.indexOf("NativeStructurePostProcessor.prepareTerrain(");
int placementLoop = source.indexOf("for (NativePlacementGroup group : placementGroups)", prepareTerrain);
int placement = source.indexOf("placeVanillaStructure(world, structureManager, random", placementLoop);
assertTrue(prepareTerrain >= 0);
assertTrue(placementLoop > prepareTerrain);
assertTrue(placement > placementLoop);
}
@Test
public void omittedTerrainConfigurationRetainsSourceSemantics() {
for (TerrainAdjustment adjustment : TerrainAdjustment.values()) {
IrisStructureTerrain resolved = NativeStructureTerrainIntegrator.resolveNativeTerrain(
start(adjustment, 64), null);
assertEquals(IrisStructureTerrainMode.SOURCE, resolved.resolvedMode());
}
}
@Test
public void sourceBuryUsesTheVanillaSixByTwelveInfluenceEnvelope() {
StructureStart start = start(TerrainAdjustment.BURY, 64);
BoundingBox bounds = start.getPieces().getFirst().getBoundingBox();
int groundY = bounds.minY();
BoundingBox area = new BoundingBox(
bounds.minX() - 7, groundY - 13, bounds.minZ(),
bounds.maxX(), groundY + 13, bounds.maxZ());
Map<BlockPos, BlockState> blocks = new HashMap<>();
NativeStructureTerrainIntegrator.integrateTerrain(
world(blocks), area, "test:bury", start,
new IrisStructureTerrain().setMode(IrisStructureTerrainMode.SOURCE), null);
assertEquals(Blocks.STONE.defaultBlockState(),
state(blocks, bounds.minX() - 5, groundY, bounds.minZ()));
assertEquals(Blocks.STONE.defaultBlockState(),
state(blocks, bounds.minX(), groundY + 11, bounds.minZ()));
assertEquals(Blocks.AIR.defaultBlockState(),
state(blocks, bounds.minX() - 6, groundY, bounds.minZ()));
assertEquals(Blocks.AIR.defaultBlockState(),
state(blocks, bounds.minX(), groundY + 12, bounds.minZ()));
assertEquals(Blocks.AIR.defaultBlockState(),
state(blocks, bounds.minX() - 7, groundY, bounds.minZ()));
assertEquals(Blocks.AIR.defaultBlockState(),
state(blocks, bounds.minX(), groundY + 13, bounds.minZ()));
}
@Test
public void sourceEncapsulateWrapsTheFullPieceBounds() {
StructureStart start = start(TerrainAdjustment.ENCAPSULATE, 64);
BoundingBox bounds = start.getPieces().getFirst().getBoundingBox();
BoundingBox area = new BoundingBox(
bounds.minX() - 13, bounds.minY(), bounds.minZ(),
bounds.maxX(), bounds.maxY() + 13, bounds.maxZ());
Map<BlockPos, BlockState> blocks = new HashMap<>();
NativeStructureTerrainIntegrator.integrateTerrain(
world(blocks), area, "test:encapsulate", start,
new IrisStructureTerrain().setMode(IrisStructureTerrainMode.SOURCE), null);
assertEquals(Blocks.STONE.defaultBlockState(),
state(blocks, bounds.minX() - 11, bounds.minY(), bounds.minZ()));
assertEquals(Blocks.STONE.defaultBlockState(),
state(blocks, bounds.minX(), bounds.maxY() + 11, bounds.minZ()));
assertEquals(Blocks.AIR.defaultBlockState(),
state(blocks, bounds.minX() - 12, bounds.minY(), bounds.minZ()));
assertEquals(Blocks.AIR.defaultBlockState(),
state(blocks, bounds.minX(), bounds.maxY() + 12, bounds.minZ()));
assertEquals(Blocks.AIR.defaultBlockState(),
state(blocks, bounds.minX() - 13, bounds.minY(), bounds.minZ()));
assertEquals(Blocks.AIR.defaultBlockState(),
state(blocks, bounds.minX(), bounds.maxY() + 13, bounds.minZ()));
}
@Test
public void sourceTerrainDensityOnlyUsesRigidPoolPieces() {
PoolElementStructurePiece terrainMatching = poolPiece(StructureTemplatePool.Projection.TERRAIN_MATCHING);
PoolElementStructurePiece rigid = poolPiece(StructureTemplatePool.Projection.RIGID);
assertFalse(NativeStructureTerrainIntegrator.isSourceRigidPiece(terrainMatching));
assertTrue(NativeStructureTerrainIntegrator.isSourceRigidPiece(rigid));
}
@Test
public void sourceJunctionTerrainUsesTheStrictLowerTwelveBlockEnvelope() {
assertTrue(NativeStructureTerrainIntegrator.insideSourceJunctionEnvelope(0, -1, 0));
assertTrue(NativeStructureTerrainIntegrator.insideSourceJunctionEnvelope(0, -11, 0));
assertFalse(NativeStructureTerrainIntegrator.insideSourceJunctionEnvelope(0, 0, 0));
assertFalse(NativeStructureTerrainIntegrator.insideSourceJunctionEnvelope(0, -12, 0));
assertFalse(NativeStructureTerrainIntegrator.insideSourceJunctionEnvelope(12, -1, 0));
}
@Test
public void explicitTerrainConfigurationWinsOverAutoEncase() {
IrisStructureTerrain configured = new IrisStructureTerrain()
.setMode(IrisStructureTerrainMode.PRESERVE);
assertSame(configured, NativeStructureTerrainIntegrator.resolveNativeTerrain(
start(TerrainAdjustment.BURY, 64), configured));
}
@Test
public void legacyTemplateAirIsClearedAfterEveryTerrainFillPath() {
IrisStructureTerrain source = new IrisStructureTerrain()
.setMode(IrisStructureTerrainMode.SOURCE);
IrisStructureTerrain preserve = new IrisStructureTerrain()
.setMode(IrisStructureTerrainMode.PRESERVE);
IrisStructureTerrain encase = new IrisStructureTerrain()
.setMode(IrisStructureTerrainMode.ENCASE);
assertTrue(NativeStructureTerrainIntegrator.clearsLegacyTemplateAir(
start(TerrainAdjustment.BURY, 64), source));
assertTrue(NativeStructureTerrainIntegrator.clearsLegacyTemplateAir(
start(TerrainAdjustment.BEARD_BOX, 64), source));
assertTrue(NativeStructureTerrainIntegrator.clearsLegacyTemplateAir(
start(TerrainAdjustment.NONE, 64), encase));
assertFalse(NativeStructureTerrainIntegrator.clearsLegacyTemplateAir(
start(TerrainAdjustment.NONE, 64), source));
assertFalse(NativeStructureTerrainIntegrator.clearsLegacyTemplateAir(
start(TerrainAdjustment.BURY, 64), preserve));
}
@Test
public void encaseReservesTheNeighborChunkEnvelope() {
StructureStart generated = start(TerrainAdjustment.BURY, 64);
BoundingBox sourceBounds = generated.getBoundingBox();
BoundingBox content = NativeStructureReferenceEnvelope.contentBounds(generated);
IrisStructureTerrain terrain = new IrisStructureTerrain()
.setMode(IrisStructureTerrainMode.ENCASE)
.setHorizontalPadding(4);
StructureStart wrapped = NativeStructureReferenceEnvelope.wrap(
generated,
generated.getStructure(),
0,
terrain);
BoundingBox referenceBounds = NativeStructureReferenceEnvelope.referenceBounds(
wrapped, wrapped.getStructure(), terrain);
assertEquals(sourceBounds, wrapped.getBoundingBox());
assertEquals(content.minX() - 4, referenceBounds.minX());
assertEquals(content.maxX() + 4, referenceBounds.maxX());
assertEquals(content.minZ() - 4, referenceBounds.minZ());
assertEquals(content.maxZ() + 4, referenceBounds.maxZ());
assertEquals(generated.getPieces().size(), wrapped.getPieces().size());
}
@Test
public void referenceEnvelopeRejectsChunkCoordinateOverflow() {
StructureStart generated = start(TerrainAdjustment.NONE, 64);
StructureStart extreme = new StructureStart(
generated.getStructure(), new ChunkPos(Integer.MAX_VALUE, 0), 0,
new PiecesContainer(generated.getPieces()));
assertThrows(IllegalStateException.class, () ->
NativeStructureReferenceEnvelope.referenceBounds(
extreme, extreme.getStructure(), new IrisStructureTerrain()));
}
@Test
public void explicitTerrainEnvelopeDoesNotInheritSourceAdjustment() {
StructureStart generated = start(TerrainAdjustment.BURY, 64);
BoundingBox content = NativeStructureReferenceEnvelope.contentBounds(generated);
IrisStructureTerrain terrain = new IrisStructureTerrain()
.setMode(IrisStructureTerrainMode.ENCASE)
.setHorizontalPadding(112);
StructureStart wrapped = NativeStructureReferenceEnvelope.wrap(
generated, generated.getStructure(), 0, terrain);
BoundingBox referenceBounds = NativeStructureReferenceEnvelope.referenceBounds(
wrapped, wrapped.getStructure(), terrain);
assertEquals(content.minX() - 112, referenceBounds.minX());
assertEquals(content.maxX() + 112, referenceBounds.maxX());
}
@Test
public void yBandRelocatesTheStartMidpointDeterministically() {
IrisStructureYBand band = new IrisStructureYBand().setMin(-120).setMax(-20);
StructureStart first = start(TerrainAdjustment.BURY, 64);
StructureStart second = start(TerrainAdjustment.BURY, 64);
NativeStructureVerticalPlacer.applyVerticalShift(
first, -64, -256, 320, true, false, band, (x, z) -> 40);
NativeStructureVerticalPlacer.applyVerticalShift(
second, -64, -256, 320, true, false, band, (x, z) -> 40);
BoundingBox bounds = first.getBoundingBox();
assertEquals(bounds.minY(), second.getBoundingBox().minY());
assertTrue(bounds.minY() >= -120);
assertTrue(bounds.maxY() <= -20);
int repeated = NativeStructureVerticalPlacer.applyVerticalShift(
first, -64, -256, 320, true, false, band, (x, z) -> 40);
assertEquals(0, repeated);
}
@Test
public void yBandClampsWhenTheBandCannotContainTheStructure() {
IrisStructureYBand band = new IrisStructureYBand().setMin(-50).setMax(-45);
StructureStart start = start(TerrainAdjustment.BURY, 64);
NativeStructureVerticalPlacer.applyVerticalShift(
start, 0, -256, 320, true, false, band, (x, z) -> 40);
BoundingBox bounds = start.getBoundingBox();
int midpoint = bounds.minY() + (bounds.maxY() - bounds.minY()) / 2;
assertTrue(midpoint >= -50);
assertTrue(midpoint <= -45);
}
@Test
public void yBandReplacesBothTheBlindShiftAndBurial() {
IrisStructureYBand band = new IrisStructureYBand().setMin(-64).setMax(-64);
StructureStart start = start(TerrainAdjustment.BURY, 64);
BoundingBox bounds = start.getBoundingBox();
int height = bounds.maxY() - bounds.minY();
NativeStructureVerticalPlacer.applyVerticalShift(
start, -200, -256, 320, true, false, band, (x, z) -> 40);
assertEquals(-64 - height / 2, start.getBoundingBox().minY());
}
@Test
public void preserveSourceYWinsOverTheConfiguredBand() {
IrisStructureYBand band = new IrisStructureYBand().setMin(-120).setMax(-20);
StructureStart start = start(TerrainAdjustment.BURY, 64);
int minY = start.getBoundingBox().minY();
int offset = NativeStructureVerticalPlacer.applyVerticalShift(
start, 0, -256, 320, true, true, band, (x, z) -> 40);
assertEquals(0, offset);
assertEquals(minY, start.getBoundingBox().minY());
}
private static BlockState tuffBlock(IrisMaterialPalette palette, RNG rng, int x, int y, int z) {
assertNotNull(palette);
assertNotNull(rng);
return Blocks.TUFF.defaultBlockState();
}
private static StructureStart start(TerrainAdjustment adjustment, int minY) {
Structure structure = new DesertPyramidStructure(new Structure.StructureSettings(
HolderSet.empty(), Map.of(), GenerationStep.Decoration.STRONGHOLDS, adjustment));
StructurePiece piece = new DesertPyramidPiece(RandomSource.create(7L), 0, 0);
piece.move(0, minY - piece.getBoundingBox().minY(), 0);
return new StructureStart(
structure, new ChunkPos(0, 0), 0, new PiecesContainer(List.of(piece)));
}
private static PoolElementStructurePiece poolPiece(StructureTemplatePool.Projection projection) {
BlockPos position = new BlockPos(0, 64, 0);
StructurePoolElement element = StructurePoolElement.single(
"minecraft:empty",
Holder.direct(new StructureProcessorList(List.of(
BlockIgnoreProcessor.STRUCTURE_AND_AIR))),
LiquidSettings.APPLY_WATERLOGGING
).apply(projection);
return new PoolElementStructurePiece(
null,
element,
position,
0,
Rotation.NONE,
new BoundingBox(position),
LiquidSettings.APPLY_WATERLOGGING);
}
private static WorldGenLevel world(Map<BlockPos, BlockState> blocks) {
InvocationHandler handler = (proxy, method, arguments) -> {
String methodName = method.getName();
if (methodName.equals("getBlockState")) {
BlockPos position = (BlockPos) arguments[0];
return state(blocks, position.getX(), position.getY(), position.getZ());
}
if (methodName.equals("setBlock")) {
BlockPos position = (BlockPos) arguments[0];
BlockState blockState = (BlockState) arguments[1];
put(blocks, position.getX(), position.getY(), position.getZ(), blockState);
return true;
}
if (methodName.equals("getSeed")) {
return TEST_SEED;
}
if (methodName.equals("getLevel")) {
return null;
}
if (methodName.equals("hashCode")) {
return System.identityHashCode(proxy);
}
if (methodName.equals("equals")) {
return proxy == arguments[0];
}
if (methodName.equals("toString")) {
return "encase-test-world";
}
throw new UnsupportedOperationException(method.toString());
};
return (WorldGenLevel) Proxy.newProxyInstance(
WorldGenLevel.class.getClassLoader(), new Class<?>[]{WorldGenLevel.class}, handler);
}
private static NativeStructureTerrainIntegrator.SourceTerrainSnapshot sourceSnapshot(
WorldGenLevel world, BoundingBox area) {
BitSet requiredLayers = new BitSet(area.getYSpan());
requiredLayers.set(0, area.getYSpan());
return NativeStructureTerrainIntegrator.SourceTerrainSnapshot.capture(
world, area, requiredLayers);
}
private static void put(Map<BlockPos, BlockState> blocks,
int x, int y, int z, BlockState state) {
blocks.put(new BlockPos(x, y, z), state);
}
private static BlockState state(Map<BlockPos, BlockState> blocks, int x, int y, int z) {
return blocks.getOrDefault(new BlockPos(x, y, z), Blocks.AIR.defaultBlockState());
}
}
@@ -1,7 +1,6 @@
package art.arcane.iris.nativegen;
import art.arcane.iris.engine.object.structure.IrisStructureTerrain;
import art.arcane.iris.engine.object.structure.IrisStructureTerrainMode;
import art.arcane.iris.engine.framework.NativeStructureReach;
import net.minecraft.SharedConstants;
import net.minecraft.core.Direction;
import net.minecraft.core.HolderSet;
@@ -41,7 +40,7 @@ public class NativeStructurePostProcessorMonumentTest {
StructureStart start = monumentStart(1337L);
int offset = NativeStructureVerticalPlacer.applyVerticalPlacement(
start, "minecraft:monument", 0, 63, -64, 320, false, false, null, (x, z) -> 0);
start, "minecraft:monument", 0, 63, -64, 320, (x, z) -> 0);
assertEquals(0, offset);
assertEquals(39, start.getBoundingBox().minY());
@@ -57,7 +56,7 @@ public class NativeStructurePostProcessorMonumentTest {
BoundingBox cachedBounds = start.getBoundingBox();
int offset = NativeStructureVerticalPlacer.applyVerticalPlacement(
start, "minecraft:monument", 0, 50, -256, 512, false, false, null, (x, z) -> 0);
start, "minecraft:monument", 0, 50, -256, 512, (x, z) -> 0);
assertEquals(-13, offset);
assertSame(cachedBounds, start.getBoundingBox());
@@ -71,7 +70,7 @@ public class NativeStructurePostProcessorMonumentTest {
}
int repeatedOffset = NativeStructureVerticalPlacer.applyVerticalPlacement(
start, "minecraft:monument", 0, 50, -256, 512, false, false, null, (x, z) -> 0);
start, "minecraft:monument", 0, 50, -256, 512, (x, z) -> 0);
assertEquals(0, repeatedOffset);
}
@@ -80,7 +79,7 @@ public class NativeStructurePostProcessorMonumentTest {
StructureStart start = monumentStart(1337L);
int offset = NativeStructureVerticalPlacer.applyVerticalPlacement(
start, "minecraft:monument", 3, 50, -256, 512, false, false, null, (x, z) -> 0);
start, "minecraft:monument", 3, 50, -256, 512, (x, z) -> 0);
assertEquals(-10, offset);
assertEquals(29, start.getBoundingBox().minY());
@@ -94,13 +93,10 @@ public class NativeStructurePostProcessorMonumentTest {
start,
start.getStructure(),
0,
new IrisStructureTerrain()
.setMode(IrisStructureTerrainMode.FORCE_CARVE)
.setHorizontalPadding(4));
List.of(new NativeStructureReach(false, 4)));
int offset = NativeStructureVerticalPlacer.applyVerticalPlacement(
wrapped, "minecraft:monument", 0, 63, -64, 320,
false, false, null, (x, z) -> 0);
wrapped, "minecraft:monument", 0, 63, -64, 320, (x, z) -> 0);
assertEquals(0, offset);
assertEquals(1, wrapped.getPieces().size());
@@ -112,7 +108,7 @@ public class NativeStructurePostProcessorMonumentTest {
ChunkPos chunkPos = new ChunkPos(0, 0);
StructureStart initial = monumentStart(seed);
NativeStructureVerticalPlacer.applyVerticalPlacement(
initial, "minecraft:monument", 0, 50, -256, 512, false, false, null, (x, z) -> 0);
initial, "minecraft:monument", 0, 50, -256, 512, (x, z) -> 0);
PiecesContainer regenerated = OceanMonumentStructure.regeneratePiecesAfterLoad(
chunkPos, seed, new PiecesContainer(initial.getPieces()));
@@ -121,7 +117,7 @@ public class NativeStructurePostProcessorMonumentTest {
assertEquals(39, reloaded.getBoundingBox().minY());
int offset = NativeStructureVerticalPlacer.applyVerticalPlacement(
reloaded, "minecraft:monument", 0, 50, -256, 512, false, false, null, (x, z) -> 0);
reloaded, "minecraft:monument", 0, 50, -256, 512, (x, z) -> 0);
assertEquals(-13, offset);
assertEquals(26, reloaded.getBoundingBox().minY());
assertEquals(48, reloaded.getBoundingBox().maxY());
@@ -133,8 +129,7 @@ public class NativeStructurePostProcessorMonumentTest {
ChunkPos chunkPos = new ChunkPos(0, 0);
StructureStart initial = monumentStart(seed);
NativeStructureVerticalPlacer.applyVerticalPlacement(
initial, "minecraft:monument", 0, 50, -256, 512,
false, false, null, (x, z) -> 0);
initial, "minecraft:monument", 0, 50, -256, 512, (x, z) -> 0);
PiecesContainer regenerated = OceanMonumentStructure.regeneratePiecesAfterLoad(
chunkPos, seed, new PiecesContainer(initial.getPieces()));
StructureStart reloaded = new StructureStart(
@@ -147,7 +142,7 @@ public class NativeStructurePostProcessorMonumentTest {
futures.add(executor.submit(() -> {
release.await();
NativeStructureVerticalPlacer.ensureMonumentSeaLevelAlignment(
reloaded, "minecraft:monument", 0, 50, -256, 512);
reloaded, "minecraft:monument", () -> 0, 50, -256, 512);
return null;
}));
}
@@ -168,7 +163,7 @@ public class NativeStructurePostProcessorMonumentTest {
StructureStart start = monumentStart(1337L);
try {
NativeStructureVerticalPlacer.applyVerticalPlacement(
start, "minecraft:monument", 0, -50, -64, 320, false, false, null, (x, z) -> 0);
start, "minecraft:monument", 0, -50, -64, 320, (x, z) -> 0);
} catch (IllegalStateException error) {
assertTrue(error.getMessage().contains("cannot align"));
return;
@@ -11,6 +11,7 @@ import net.minecraft.world.level.levelgen.structure.ScatteredFeaturePiece;
import net.minecraft.world.level.levelgen.structure.Structure;
import net.minecraft.world.level.levelgen.structure.StructurePiece;
import net.minecraft.world.level.levelgen.structure.StructureStart;
import net.minecraft.world.level.levelgen.structure.TerrainAdjustment;
import net.minecraft.world.level.levelgen.structure.pieces.PiecesContainer;
import net.minecraft.world.level.levelgen.structure.structures.DesertPyramidPiece;
import net.minecraft.world.level.levelgen.structure.structures.DesertPyramidStructure;
@@ -46,8 +47,7 @@ public class NativeStructurePostProcessorScatteredFeatureTest {
BoundingBox footprint = piece.getBoundingBox();
int offset = NativeStructureVerticalPlacer.applyVerticalPlacement(
start, "minecraft:desert_pyramid", 0, 63, -64, 320, false, false, null,
(x, z) -> x == footprint.maxX() && z == footprint.maxZ() ? 64 : 92);
start, "minecraft:desert_pyramid", 0, 63, -64, 320, (x, z) -> x == footprint.maxX() && z == footprint.maxZ() ? 64 : 92);
assertEquals(1, offset);
assertSame(cachedBounds, start.getBoundingBox());
@@ -64,8 +64,7 @@ public class NativeStructurePostProcessorScatteredFeatureTest {
BoundingBox footprint = piece.getBoundingBox();
int offset = NativeStructureVerticalPlacer.applyVerticalPlacement(
start, "minecraft:jungle_pyramid", 4, 63, -64, 320, false, false, null,
(x, z) -> x == footprint.minX() && z == footprint.minZ() ? 88 : 70);
start, "minecraft:jungle_pyramid", 4, 63, -64, 320, (x, z) -> x == footprint.minX() && z == footprint.minZ() ? 88 : 70);
assertEquals(11, offset);
assertEquals(75, piece.getBoundingBox().minY());
@@ -79,9 +78,9 @@ public class NativeStructurePostProcessorScatteredFeatureTest {
StructureStart start = desertStart(piece);
int initialOffset = NativeStructureVerticalPlacer.applyVerticalPlacement(
start, "minecraft:desert_pyramid", 0, 63, -64, 320, false, false, null, (x, z) -> 80);
start, "minecraft:desert_pyramid", 0, 63, -64, 320, (x, z) -> 80);
int repeatedOffset = NativeStructureVerticalPlacer.applyVerticalPlacement(
start, "minecraft:desert_pyramid", 0, 63, -64, 320, false, false, null, (x, z) -> 80);
start, "minecraft:desert_pyramid", 0, 63, -64, 320, (x, z) -> 80);
assertEquals(17, initialOffset);
assertEquals(0, repeatedOffset);
@@ -94,7 +93,7 @@ public class NativeStructurePostProcessorScatteredFeatureTest {
StructureStart start = desertStart(piece);
int offset = NativeStructureVerticalPlacer.applyVerticalPlacement(
start, "minecraft:desert_pyramid", 0, 63, -64, 320, false, false, null, (x, z) -> 318);
start, "minecraft:desert_pyramid", 0, 63, -64, 320, (x, z) -> 318);
assertEquals(241, offset);
assertEquals(305, piece.getBoundingBox().minY());
@@ -110,14 +109,13 @@ public class NativeStructurePostProcessorScatteredFeatureTest {
StructureStart jungleStart = jungleStart(jungle);
StructureStart swampStart = swampStart(swamp);
assertFalse(NativeStructureSurfaceFitter.requiresSurfaceTerrain(desertStart));
assertFalse(NativeStructureSurfaceFitter.requiresSurfaceTerrain(jungleStart));
assertFalse(NativeStructureSurfaceFitter.requiresSurfaceTerrain(swampStart));
assertEquals(TerrainAdjustment.NONE, desertStart.getStructure().terrainAdaptation());
assertEquals(TerrainAdjustment.NONE, jungleStart.getStructure().terrainAdaptation());
assertEquals(TerrainAdjustment.NONE, swampStart.getStructure().terrainAdaptation());
AtomicInteger terrainQueries = new AtomicInteger();
int offset = NativeStructureVerticalPlacer.applyVerticalPlacement(
swampStart, "minecraft:swamp_hut", 0, 63, -64, 320, false, false, null,
(x, z) -> terrainQueries.incrementAndGet());
swampStart, "minecraft:swamp_hut", 0, 63, -64, 320, (x, z) -> terrainQueries.incrementAndGet());
assertEquals(0, offset);
assertEquals(0, terrainQueries.get());
assertEquals(64, swamp.getBoundingBox().minY());
@@ -142,7 +140,7 @@ public class NativeStructurePostProcessorScatteredFeatureTest {
int pyramidMinY = pyramidOverride.getBoundingBox().minY();
int pyramidOffset = NativeStructureVerticalPlacer.applyVerticalPlacement(
pyramidOverride, "minecraft:desert_pyramid", 5,
63, -64, 320, false, false, null, (x, z) -> 200);
63, -64, 320, (x, z) -> 200);
assertEquals(5, pyramidOffset);
assertEquals(pyramidMinY + 5, pyramidOverride.getBoundingBox().minY());
@@ -151,7 +149,7 @@ public class NativeStructurePostProcessorScatteredFeatureTest {
new SwampHutPiece(RandomSource.create(47L), 0, 0));
int monumentMinY = monumentOverride.getBoundingBox().minY();
NativeStructureVerticalPlacer.ensureMonumentSeaLevelAlignment(
monumentOverride, "minecraft:monument", 0, 40, -64, 320);
monumentOverride, "minecraft:monument", () -> 0, 40, -64, 320);
assertEquals(monumentMinY, monumentOverride.getBoundingBox().minY());
}
@@ -173,21 +173,6 @@ public class NativeStructurePostProcessorVegetationTest {
GenerationStep.Decoration.SURFACE_STRUCTURES));
}
@Test
public void undergroundStructuresUseTheLowestTerrainColumn() {
BoundingBox bounds = new BoundingBox(0, 60, 0, 1, 80, 0);
int offset = NativeStructureVerticalPlacer.resolveBuriedOffset(
bounds, 0, -64, 320, (x, z) -> x == 1 ? 76 : 100);
assertEquals(-5, offset);
}
@Test
public void undergroundBurialClampsToTheWorldFloorInsteadOfFailing() {
BoundingBox bounds = new BoundingBox(0, 60, 0, 1, 80, 0);
assertEquals(-2, NativeStructureVerticalPlacer.resolveBuriedOffset(
bounds, 0, 58, 320, (x, z) -> x == 1 ? 76 : 100));
}
private static void clearVegetation(ProtoChunk chunk, StructureStart start) {
NativeStructureVegetationClearer.clearIntersectingVegetation(
world(chunk), chunk, AREA, List.of(start));
@@ -123,8 +123,8 @@ public class NativeStructureVolumeIndexTest {
public void vanillaVolumesAreGatedOnPackPolicy() throws Exception {
String source = Files.readString(Path.of(System.getProperty("iris.nativeStructureVolumeIndexSource")));
assertTrue(source.contains("NativeStructureGenerationPolicy.resolve("));
assertTrue(source.contains("if (!decision.generate())"));
assertTrue(source.contains("if (!NativeStructureGenerationPolicy.generates(engine, structureId))"));
assertTrue(source.contains("NativeStructureLayouts.shift(engine"));
assertTrue(source.contains("isStructureChunk("));
}
@@ -30,9 +30,8 @@ import art.arcane.iris.engine.framework.IrisStructureLocator;
import art.arcane.iris.engine.framework.NativeStructureGenerationPolicy;
import art.arcane.iris.engine.framework.StructureReachability;
import art.arcane.iris.engine.object.world.biome.IrisBiome;
import art.arcane.iris.engine.object.structure.vanilla.IrisNativeStructureDecision;
import art.arcane.iris.engine.object.world.region.IrisRegion;
import art.arcane.iris.engine.object.structure.vanilla.NativeStructureGenerationStatus;
import art.arcane.iris.engine.framework.NativeStructureGenerationStatus;
import art.arcane.iris.engine.platform.EngineBukkitOps;
import art.arcane.iris.platform.bukkit.BukkitPlatform;
import art.arcane.iris.spi.IrisPlatforms;
@@ -144,20 +143,20 @@ public class CommandFind implements DirectorExecutor {
String structureKey = structure == null ? "" : structure.trim();
Structure nativeStructure = resolveNativeStructure(structureKey);
boolean registered = nativeStructure != null;
IrisNativeStructureDecision decision = registered
? NativeStructureGenerationPolicy.resolve(e, structureKey, false)
NativeStructureGenerationStatus status = registered
? NativeStructureGenerationPolicy.resolve(e, structureKey)
: null;
boolean nativePlacement = IrisStructureLocator.hasNativePlacement(e, structureKey);
boolean locatableNativePlacement = IrisStructureLocator.hasLocatableNativePlacement(e, structureKey);
boolean locatableEditablePlacement = ModuleServices.canLocateStructure(e, structureKey);
World targetWorld = target.getWorld();
boolean nativeGenerationEnabled = targetWorld.canGenerateStructures();
boolean requiresReachability = registered && decision.generate()
&& decision.status() != NativeStructureGenerationStatus.REPLACED_BY_IRIS
boolean requiresReachability = registered && status == NativeStructureGenerationStatus.GENERATE_NATIVE
&& status != NativeStructureGenerationStatus.REPLACED_BY_IRIS
&& nativeGenerationEnabled;
boolean reachable = !requiresReachability || StructureReachability.isReachable(e, structureKey);
StructureLookupRoute route = selectStructureLookupRoute(
registered, decision, nativePlacement, locatableNativePlacement,
registered, status, nativePlacement, locatableNativePlacement,
locatableEditablePlacement, nativeGenerationEnabled, reachable);
if (route == StructureLookupRoute.UNKNOWN) {
@@ -166,7 +165,7 @@ public class CommandFind implements DirectorExecutor {
}
if (route == StructureLookupRoute.POLICY_DISABLED) {
commandSender.sendMessage(C.RED + NativeStructureGenerationPolicy.generationStatusMessage(
structureKey, decision.status()));
structureKey, status));
return;
}
if (route == StructureLookupRoute.NO_ACTIVE_PLACEMENT) {
@@ -273,24 +272,24 @@ public class CommandFind implements DirectorExecutor {
for (Map.Entry<String, String> entry : registeredKeys.entrySet()) {
String normalizedKey = entry.getKey();
String key = entry.getValue();
IrisNativeStructureDecision decision = NativeStructureGenerationPolicy.resolve(engine, key, false);
NativeStructureGenerationStatus status = NativeStructureGenerationPolicy.resolve(engine, key);
boolean nativePlacement = IrisStructureLocator.hasNativePlacement(engine, key);
boolean locatableNativePlacement = IrisStructureLocator.hasLocatableNativePlacement(engine, key);
boolean locatableEditablePlacement = ModuleServices.canLocateStructure(engine, key);
StructureLookupRoute route = selectStructureLookupRoute(
true, decision, nativePlacement, locatableNativePlacement,
true, status, nativePlacement, locatableNativePlacement,
locatableEditablePlacement, nativeGenerationEnabled,
reachableKeys.contains(normalizedKey));
if (route == StructureLookupRoute.IRIS || route == StructureLookupRoute.NATIVE) {
continue;
}
List<String> requiredBiomes = needsNativeReachabilityReason(route, decision)
List<String> requiredBiomes = needsNativeReachabilityReason(route, status)
? structureHooks.structureBiomeKeys(key)
: List.of();
exclusions.add(new StructureExclusion(
StructureExclusionKind.EXCLUDED, key, null,
describeStructureExclusion(
route, key, decision.status(), nativePlacement,
route, key, status, nativePlacement,
requiredBiomes, possibleBiomeKeys)));
registeredExcluded++;
}
@@ -418,9 +417,9 @@ public class CommandFind implements DirectorExecutor {
}
private static boolean needsNativeReachabilityReason(
StructureLookupRoute route, IrisNativeStructureDecision decision) {
StructureLookupRoute route, NativeStructureGenerationStatus status) {
return route == StructureLookupRoute.UNREACHABLE
|| route == StructureLookupRoute.NO_ACTIVE_PLACEMENT && decision.generate();
|| route == StructureLookupRoute.NO_ACTIVE_PLACEMENT && status == NativeStructureGenerationStatus.GENERATE_NATIVE;
}
static String describeStructureExclusion(
@@ -529,7 +528,7 @@ public class CommandFind implements DirectorExecutor {
}
static StructureLookupRoute selectStructureLookupRoute(
boolean registered, IrisNativeStructureDecision decision, boolean nativePlacement,
boolean registered, NativeStructureGenerationStatus status, boolean nativePlacement,
boolean locatableNativePlacement, boolean locatableEditablePlacement,
boolean nativeGenerationEnabled, boolean reachable) {
if (!registered) {
@@ -537,14 +536,14 @@ public class CommandFind implements DirectorExecutor {
? StructureLookupRoute.IRIS
: StructureLookupRoute.UNKNOWN;
}
if (decision == null) {
throw new IllegalArgumentException("Registered structure lookup requires a generation decision");
if (status == null) {
throw new IllegalArgumentException("Registered structure lookup requires a generation status");
}
if (!decision.generate()
&& decision.status() != NativeStructureGenerationStatus.REPLACED_BY_IRIS) {
if (status != NativeStructureGenerationStatus.GENERATE_NATIVE
&& status != NativeStructureGenerationStatus.REPLACED_BY_IRIS) {
return StructureLookupRoute.POLICY_DISABLED;
}
if (decision.status() == NativeStructureGenerationStatus.REPLACED_BY_IRIS) {
if (status == NativeStructureGenerationStatus.REPLACED_BY_IRIS) {
if (!nativePlacement) {
return locatableEditablePlacement
? StructureLookupRoute.IRIS
@@ -36,10 +36,9 @@ import art.arcane.iris.engine.framework.StructureReachability;
import art.arcane.iris.engine.framework.structure.StructureAssemblyResult;
import art.arcane.iris.engine.object.placement.IObjectPlacer;
import art.arcane.iris.engine.object.world.dimension.IrisDimension;
import art.arcane.iris.engine.object.structure.vanilla.IrisNativeStructureDecision;
import art.arcane.iris.engine.object.value.IrisPosition;
import art.arcane.iris.engine.object.structure.IrisStructure;
import art.arcane.iris.engine.object.structure.vanilla.NativeStructureGenerationStatus;
import art.arcane.iris.engine.framework.NativeStructureGenerationStatus;
import art.arcane.volmlib.util.collection.KList;
import art.arcane.iris.util.common.director.DirectorExecutor;
import art.arcane.iris.util.common.format.C;
@@ -173,13 +172,13 @@ public class CommandStructure implements DirectorExecutor {
private void runVerification(Engine engine, KList<String> structureKeys, int centerX, int centerZ,
int searchRadius, VolmitSender commandSender, Player target) {
KList<String> messages = new KList<>();
Map<String, IrisNativeStructureDecision> decisions = new HashMap<>(structureKeys.size());
Map<String, NativeStructureGenerationStatus> statuses = new HashMap<>(structureKeys.size());
boolean requiresNativeReachability = false;
for (String keyName : structureKeys) {
IrisNativeStructureDecision decision = NativeStructureGenerationPolicy.resolve(engine, keyName, false);
decisions.put(keyName, decision);
NativeStructureGenerationStatus status = NativeStructureGenerationPolicy.resolve(engine, keyName);
statuses.put(keyName, status);
requiresNativeReachability |= !IrisStructureLocator.isPlaced(engine, keyName)
&& decision.generate();
&& status == NativeStructureGenerationStatus.GENERATE_NATIVE;
}
Set<String> reachable = Set.of();
if (requiresNativeReachability) {
@@ -199,7 +198,7 @@ public class CommandStructure implements DirectorExecutor {
int searchLimited = 0;
int errors = 0;
for (String keyName : structureKeys) {
IrisNativeStructureDecision decision = decisions.get(keyName);
NativeStructureGenerationStatus status = statuses.get(keyName);
if (IrisStructureLocator.isPlaced(engine, keyName)) {
try {
IrisStructureLocator.LocateResult result =
@@ -225,7 +224,7 @@ public class CommandStructure implements DirectorExecutor {
}
continue;
}
if (!decision.generate()) {
if (status != NativeStructureGenerationStatus.GENERATE_NATIVE) {
disabled++;
messages.add(C.GRAY + "[disabled] " + C.WHITE + keyName);
continue;
@@ -1,8 +1,7 @@
package art.arcane.iris.core.commands;
import art.arcane.iris.engine.framework.NativeStructureGenerationPolicy;
import art.arcane.iris.engine.object.structure.vanilla.IrisNativeStructureDecision;
import art.arcane.iris.engine.object.structure.vanilla.NativeStructureGenerationStatus;
import art.arcane.iris.engine.framework.NativeStructureGenerationStatus;
import org.junit.Test;
import java.io.IOException;
@@ -64,11 +63,11 @@ public class IrisStructureLocateCommandContractTest {
false, null, false, false, false, true, true));
assertEquals(CommandFind.StructureLookupRoute.NO_ACTIVE_PLACEMENT,
CommandFind.selectStructureLookupRoute(
true, decision(NativeStructureGenerationStatus.REPLACED_BY_IRIS),
true, NativeStructureGenerationStatus.REPLACED_BY_IRIS,
false, false, false, true, true));
assertEquals(CommandFind.StructureLookupRoute.NO_ACTIVE_PLACEMENT,
CommandFind.selectStructureLookupRoute(
true, decision(NativeStructureGenerationStatus.GENERATE_NATIVE),
true, NativeStructureGenerationStatus.GENERATE_NATIVE,
true, false, false, true, false));
}
@@ -79,7 +78,7 @@ public class IrisStructureLocateCommandContractTest {
false, null, false, false, true, false, false));
assertEquals(CommandFind.StructureLookupRoute.IRIS,
CommandFind.selectStructureLookupRoute(
true, decision(NativeStructureGenerationStatus.REPLACED_BY_IRIS),
true, NativeStructureGenerationStatus.REPLACED_BY_IRIS,
false, false, true, false, false));
}
@@ -87,23 +86,23 @@ public class IrisStructureLocateCommandContractTest {
public void findRequiresWorldGenerationAndReachabilityForNativeRoutes() {
assertEquals(CommandFind.StructureLookupRoute.WORLD_DISABLED,
CommandFind.selectStructureLookupRoute(
true, decision(NativeStructureGenerationStatus.REPLACED_BY_IRIS),
true, NativeStructureGenerationStatus.REPLACED_BY_IRIS,
true, true, false, false, true));
assertEquals(CommandFind.StructureLookupRoute.WORLD_DISABLED,
CommandFind.selectStructureLookupRoute(
true, decision(NativeStructureGenerationStatus.GENERATE_NATIVE),
true, NativeStructureGenerationStatus.GENERATE_NATIVE,
false, false, false, false, true));
assertEquals(CommandFind.StructureLookupRoute.UNREACHABLE,
CommandFind.selectStructureLookupRoute(
true, decision(NativeStructureGenerationStatus.GENERATE_NATIVE),
true, NativeStructureGenerationStatus.GENERATE_NATIVE,
false, false, false, true, false));
assertEquals(CommandFind.StructureLookupRoute.NATIVE,
CommandFind.selectStructureLookupRoute(
true, decision(NativeStructureGenerationStatus.GENERATE_NATIVE),
true, NativeStructureGenerationStatus.GENERATE_NATIVE,
true, true, false, true, false));
assertEquals(CommandFind.StructureLookupRoute.NATIVE,
CommandFind.selectStructureLookupRoute(
true, decision(NativeStructureGenerationStatus.GENERATE_NATIVE),
true, NativeStructureGenerationStatus.GENERATE_NATIVE,
true, false, false, true, true));
}
@@ -111,7 +110,7 @@ public class IrisStructureLocateCommandContractTest {
public void findHonorsPackDisableBeforePlacementRouting() {
assertEquals(CommandFind.StructureLookupRoute.POLICY_DISABLED,
CommandFind.selectStructureLookupRoute(
true, decision(NativeStructureGenerationStatus.DISABLED_BY_PACK),
true, NativeStructureGenerationStatus.DISABLED_BY_PACK,
false, false, true, true, true));
}
@@ -281,7 +280,7 @@ public class IrisStructureLocateCommandContractTest {
int methodStart = source.indexOf("private void runVerification(");
int methodEnd = source.indexOf("private void sendVerificationMessages(", methodStart);
String method = source.substring(methodStart, methodEnd);
int policyResolution = method.indexOf("NativeStructureGenerationPolicy.resolve(engine, keyName, false)");
int policyResolution = method.indexOf("NativeStructureGenerationPolicy.resolve(engine, keyName)");
int nativeRequirement = method.indexOf(
"requiresNativeReachability |= !IrisStructureLocator.isPlaced", policyResolution);
int reachabilityGuard = method.indexOf("if (requiresNativeReachability)", nativeRequirement);
@@ -292,9 +291,4 @@ public class IrisStructureLocateCommandContractTest {
assertTrue(reachabilityGuard > nativeRequirement);
assertTrue(reachabilityLookup > reachabilityGuard);
}
private static IrisNativeStructureDecision decision(NativeStructureGenerationStatus status) {
return new IrisNativeStructureDecision(
status, 0, null, false, null, null);
}
}
@@ -1,9 +1,8 @@
package art.arcane.iris.nativegen;
import art.arcane.iris.engine.framework.NativeJigsawOverrides;
import art.arcane.iris.engine.framework.NativeStructureReach;
import art.arcane.iris.engine.framework.NativeStructureStartPlan;
import art.arcane.iris.engine.object.structure.jigsaw.IrisJigsawConfiguration;
import art.arcane.iris.engine.object.structure.jigsaw.IrisJigsawHeightmap;
import art.arcane.iris.engine.object.structure.jigsaw.IrisJigsawLiquidSettings;
import art.arcane.iris.spi.PlatformStructureHooks.JigsawSourceMetadata;
import net.minecraft.core.Holder;
import net.minecraft.core.RegistryAccess;
@@ -25,17 +24,21 @@ import net.minecraft.world.level.levelgen.structure.StructureStart;
import net.minecraft.world.level.levelgen.structure.structures.JigsawStructure;
import net.minecraft.world.level.levelgen.structure.templatesystem.StructureTemplateManager;
import java.util.List;
import java.util.Locale;
import java.util.Objects;
import java.util.function.IntBinaryOperator;
import java.util.function.Predicate;
public final class NativeStructureFactory {
private static final String NO_HEIGHTMAP = "NONE";
private NativeStructureFactory() {
}
/** The start {@code plan} describes, placed at its height; {@code reaches} are the modules' reaches around it. */
public static StructureStart generate(GenerationContext context, Holder<Structure> sourceHolder,
NativeStructureStartPlan plan, int references) {
NativeStructureStartPlan plan, int references,
List<NativeStructureReach> reaches) {
Structure source = sourceHolder.value();
Structure configured = configure(
context.registryAccess(), source, plan.jigsaw(),
@@ -75,9 +78,6 @@ public final class NativeStructureFactory {
context.seaLevel(),
context.heightAccessor().getMinY(),
Math.addExact(context.heightAccessor().getMinY(), context.heightAccessor().getHeight()),
false,
false,
null,
context.surfaceHeight());
positioned = generated;
}
@@ -88,7 +88,7 @@ public final class NativeStructureFactory {
positioned,
source,
references,
plan.terrain(),
reaches,
plan.structureKey()
);
}
@@ -120,7 +120,7 @@ public final class NativeStructureFactory {
}
static Structure configure(RegistryAccess registryAccess, Structure source,
IrisJigsawConfiguration configuration,
NativeJigsawOverrides configuration,
boolean underground, int baseY) {
Objects.requireNonNull(source, "Native structure source must not be null");
if (!(source instanceof JigsawStructure sourceJigsaw)) {
@@ -162,36 +162,36 @@ public final class NativeStructureFactory {
return structureTag;
}
private static void applyConfiguration(CompoundTag tag, IrisJigsawConfiguration configuration) {
private static void applyConfiguration(CompoundTag tag, NativeJigsawOverrides configuration) {
if (configuration == null) {
return;
}
if (configuration.getStartPool() != null && !configuration.getStartPool().isBlank()) {
tag.putString("start_pool", configuration.getStartPool().trim());
if (configuration.startPool() != null && !configuration.startPool().isBlank()) {
tag.putString("start_pool", configuration.startPool().trim());
}
if (configuration.getStartJigsawName() != null
&& !configuration.getStartJigsawName().isBlank()) {
if ("NONE".equalsIgnoreCase(configuration.getStartJigsawName().trim())) {
if (configuration.startJigsawName() != null
&& !configuration.startJigsawName().isBlank()) {
if ("NONE".equalsIgnoreCase(configuration.startJigsawName().trim())) {
tag.remove("start_jigsaw_name");
} else {
tag.putString("start_jigsaw_name", configuration.getStartJigsawName().trim());
tag.putString("start_jigsaw_name", configuration.startJigsawName().trim());
}
}
if (configuration.getMaxDepth() != null) {
tag.putInt("size", configuration.getMaxDepth());
if (configuration.maxDepth() != null) {
tag.putInt("size", configuration.maxDepth());
}
applyDistance(tag, configuration);
if (configuration.getUseExpansionHack() != null) {
tag.putBoolean("use_expansion_hack", configuration.getUseExpansionHack());
if (configuration.useExpansionHack() != null) {
tag.putBoolean("use_expansion_hack", configuration.useExpansionHack());
}
applyHeightmap(tag, configuration.getProjectStartToHeightmap());
applyHeightmap(tag, configuration.projectStartToHeightmap());
applyDimensionPadding(tag, configuration);
applyLiquidSettings(tag, configuration.getLiquidSettings());
applyLiquidSettings(tag, configuration.liquidSettings());
}
private static void applyDistance(CompoundTag tag, IrisJigsawConfiguration configuration) {
Integer horizontal = configuration.getMaxDistanceHorizontal();
Integer vertical = configuration.getMaxDistanceVertical();
private static void applyDistance(CompoundTag tag, NativeJigsawOverrides configuration) {
Integer horizontal = configuration.maxDistanceHorizontal();
Integer vertical = configuration.maxDistanceVertical();
if (horizontal == null && vertical == null) {
return;
}
@@ -223,20 +223,20 @@ public final class NativeStructureFactory {
return Math.max(0, Math.max(expansion, adjusted.maxZ() - content.maxZ()));
}
private static void applyHeightmap(CompoundTag tag, IrisJigsawHeightmap heightmap) {
if (heightmap == null || heightmap == IrisJigsawHeightmap.SOURCE) {
private static void applyHeightmap(CompoundTag tag, String heightmap) {
if (heightmap == null || heightmap.equals(NativeJigsawOverrides.SOURCE)) {
return;
}
if (heightmap == IrisJigsawHeightmap.NONE) {
if (heightmap.equals(NO_HEIGHTMAP)) {
tag.remove("project_start_to_heightmap");
return;
}
tag.putString("project_start_to_heightmap", heightmap.name());
tag.putString("project_start_to_heightmap", heightmap);
}
private static void applyDimensionPadding(CompoundTag tag, IrisJigsawConfiguration configuration) {
Integer bottom = configuration.getDimensionPaddingBottom();
Integer top = configuration.getDimensionPaddingTop();
private static void applyDimensionPadding(CompoundTag tag, NativeJigsawOverrides configuration) {
Integer bottom = configuration.dimensionPaddingBottom();
Integer top = configuration.dimensionPaddingTop();
if (bottom == null && top == null) {
return;
}
@@ -260,11 +260,11 @@ public final class NativeStructureFactory {
return tag.getIntOr("dimension_padding", 0);
}
private static void applyLiquidSettings(CompoundTag tag, IrisJigsawLiquidSettings settings) {
if (settings == null || settings == IrisJigsawLiquidSettings.SOURCE) {
private static void applyLiquidSettings(CompoundTag tag, String settings) {
if (settings == null || settings.equals(NativeJigsawOverrides.SOURCE)) {
return;
}
tag.putString("liquid_settings", settings.name().toLowerCase(Locale.ROOT));
tag.putString("liquid_settings", settings.toLowerCase(Locale.ROOT));
}
public record GenerationContext(
@@ -0,0 +1,454 @@
package art.arcane.iris.nativegen;
import art.arcane.iris.engine.framework.NativeStartMemo;
import art.arcane.iris.engine.framework.nativefit.NativeFitBlocks;
import art.arcane.iris.engine.framework.nativefit.NativeFitBox;
import art.arcane.iris.engine.framework.nativefit.NativeFitChunk;
import art.arcane.iris.engine.framework.nativefit.NativeFitPiece;
import art.arcane.iris.engine.framework.nativefit.NativeFitStart;
import art.arcane.iris.engine.framework.nativefit.NativeFitTrait;
import art.arcane.iris.engine.framework.nativefit.NativeTemplateCells;
import com.mojang.brigadier.exceptions.CommandSyntaxException;
import net.minecraft.commands.arguments.blocks.BlockStateParser;
import net.minecraft.core.BlockPos;
import net.minecraft.core.Holder;
import net.minecraft.core.Direction;
import net.minecraft.core.registries.BuiltInRegistries;
import net.minecraft.core.registries.Registries;
import net.minecraft.resources.Identifier;
import net.minecraft.resources.ResourceKey;
import net.minecraft.server.level.ServerLevel;
import net.minecraft.tags.BlockTags;
import net.minecraft.tags.TagKey;
import net.minecraft.world.level.Level;
import net.minecraft.world.level.WorldGenLevel;
import net.minecraft.world.level.block.Block;
import net.minecraft.world.level.block.Blocks;
import net.minecraft.world.level.block.Rotation;
import net.minecraft.world.level.block.SupportType;
import net.minecraft.world.level.block.state.BlockState;
import net.minecraft.world.level.dimension.BuiltinDimensionTypes;
import net.minecraft.world.level.dimension.DimensionType;
import net.minecraft.world.level.levelgen.structure.BoundingBox;
import net.minecraft.world.level.levelgen.structure.PoolElementStructurePiece;
import net.minecraft.world.level.levelgen.structure.StructurePiece;
import net.minecraft.world.level.levelgen.structure.StructureStart;
import net.minecraft.world.level.levelgen.structure.pools.JigsawJunction;
import net.minecraft.world.level.levelgen.structure.pools.LegacySinglePoolElement;
import net.minecraft.world.level.levelgen.structure.pools.ListPoolElement;
import net.minecraft.world.level.levelgen.structure.pools.SinglePoolElement;
import net.minecraft.world.level.levelgen.structure.pools.StructurePoolElement;
import net.minecraft.world.level.levelgen.structure.pools.StructureTemplatePool;
import net.minecraft.world.level.levelgen.structure.templatesystem.StructurePlaceSettings;
import net.minecraft.world.level.levelgen.structure.templatesystem.StructureTemplate;
import net.minecraft.world.level.levelgen.structure.templatesystem.StructureTemplateManager;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.IntBinaryOperator;
import java.util.function.Supplier;
/**
* The platform's side of the modules' structure fit: a decorated chunk, its starts and their pieces, read from
* Minecraft's own structures and handed to the modules as host values ({@link NativeFitChunk}). It knows how
* Minecraft builds pieces (templates, processors, jigsaw junctions, legacy template air) but nothing of how a module
* fits them.
*/
public final class NativeStructureFitBridge {
private static final int MAX_TEMPLATE_COLUMN_CELLS = 4_194_304;
private static final List<Block> TEMPLATE_VOID_BLOCKS = List.of(Blocks.AIR, Blocks.STRUCTURE_VOID);
private static final Map<String, TagKey<Block>> TAGS = new ConcurrentHashMap<>();
private NativeStructureFitBridge() {
}
/** One start the platform places in the chunk, with the memo its ownership record kept (null for none). */
public record FitTarget(String structureId, StructureStart start, NativeStartMemo memo) {
}
/**
* The chunk {@code world} decorates in {@code area}, with its starts in the order the platform places them;
* {@code surfaceHeight} gives the terrain's surface per column in world heights.
*/
public static NativeFitChunk<BlockState> chunk(WorldGenLevel world, BoundingBox area, List<FitTarget> targets,
IntBinaryOperator surfaceHeight) {
Supplier<StructureTemplateManager> templates = () -> world.getLevel().getStructureManager();
List<NativeFitStart<BlockState>> starts = new ArrayList<>(targets.size());
for (FitTarget target : targets) {
starts.add(new MinecraftStart(world, target, templates));
}
return new NativeFitChunk<>(new MinecraftBlocks(world), box(area), world.getMinY(),
world.getMinY() + world.getHeight(), world.getSeed(), surfaceHeight, y -> naturalBlock(world, y), starts);
}
/** The block the dimension's natural terrain is made of at world height {@code y}. */
static BlockState naturalBlock(WorldGenLevel world, int y) {
ServerLevel level = world == null ? null : world.getLevel();
if (level == null) {
return overworldBlock(y);
}
Holder<DimensionType> dimensionType = level.dimensionTypeRegistration();
return naturalBlock(level.dimension(), dimensionType.unwrapKey().orElse(null), dimensionType.value(), y);
}
static BlockState naturalBlock(ResourceKey<Level> dimension, ResourceKey<DimensionType> dimensionTypeKey,
DimensionType dimensionType, int y) {
if (Level.NETHER.equals(dimension)) {
return Blocks.NETHERRACK.defaultBlockState();
}
if (Level.END.equals(dimension)) {
return Blocks.END_STONE.defaultBlockState();
}
if (BuiltinDimensionTypes.NETHER.equals(dimensionTypeKey)
|| dimensionType != null && dimensionType.hasCeiling() && !dimensionType.hasSkyLight()) {
return Blocks.NETHERRACK.defaultBlockState();
}
if (BuiltinDimensionTypes.END.equals(dimensionTypeKey)
|| dimensionType != null && (dimensionType.hasEnderDragonFight() || dimensionType.hasEndFlashes())) {
return Blocks.END_STONE.defaultBlockState();
}
return overworldBlock(y);
}
private static BlockState overworldBlock(int y) {
return y < 0 ? Blocks.DEEPSLATE.defaultBlockState() : Blocks.STONE.defaultBlockState();
}
static NativeFitBox box(BoundingBox box) {
return new NativeFitBox(box.minX(), box.minY(), box.minZ(), box.maxX(), box.maxY(), box.maxZ());
}
static BoundingBox boundingBox(NativeFitBox box) {
return new BoundingBox(box.minX(), box.minY(), box.minZ(), box.maxX(), box.maxY(), box.maxZ());
}
/** Logs, wood, stems, hyphae and leaves, by tag or by the block's name. */
static boolean isTreeBlock(BlockState state) {
return isLog(state) || isLeaves(state);
}
private static boolean isLog(BlockState state) {
if (state.is(BlockTags.LOGS)) {
return true;
}
String path = blockPath(state);
return path.endsWith("_log") || path.endsWith("_wood") || path.endsWith("_stem") || path.endsWith("_hyphae");
}
private static boolean isLeaves(BlockState state) {
return state.is(BlockTags.LEAVES) || blockPath(state).endsWith("_leaves");
}
/** Field reads instead of a registry lookup: this runs per block probe on the hottest fit scans. */
private static String blockPath(BlockState state) {
return state.getBlock().builtInRegistryHolder().key().identifier().getPath();
}
private static final class MinecraftBlocks implements NativeFitBlocks<BlockState> {
private final WorldGenLevel world;
private final BlockPos.MutableBlockPos position = new BlockPos.MutableBlockPos();
private MinecraftBlocks(WorldGenLevel world) {
this.world = world;
}
@Override
public BlockState get(int x, int y, int z) {
return world.getBlockState(position.set(x, y, z));
}
@Override
public void set(int x, int y, int z, BlockState state) {
world.setBlock(position.set(x, y, z), state, 2);
}
@Override
public String key(BlockState state) {
return BlockStateParser.serialize(state);
}
@Override
public BlockState state(String key) {
try {
return BlockStateParser.parseForBlock(BuiltInRegistries.BLOCK, key, false).blockState();
} catch (CommandSyntaxException invalid) {
throw new IllegalArgumentException("Block state " + key + " is not one of the platform's: "
+ invalid.getMessage(), invalid);
}
}
@Override
public boolean is(BlockState state, NativeFitTrait trait) {
return switch (trait) {
case AIR -> state.isAir();
case SOLID -> state.isSolid();
case FLUID -> !state.getFluidState().isEmpty();
case LOG -> isLog(state);
case LEAVES -> isLeaves(state);
};
}
@Override
public boolean inTag(BlockState state, String tag) {
return state.is(TAGS.computeIfAbsent(tag, id -> TagKey.create(Registries.BLOCK, Identifier.parse(id))));
}
@Override
public boolean sturdy(int x, int y, int z, String face) {
BlockState state = world.getBlockState(position.set(x, y, z));
return state.isFaceSturdy(world, position, Direction.valueOf(face), SupportType.FULL);
}
@Override
public BlockState fluid(BlockState state) {
return state.getFluidState().createLegacyBlock();
}
}
private static final class MinecraftStart implements NativeFitStart<BlockState> {
private final FitTarget target;
private final List<NativeFitPiece<BlockState>> pieces;
private MinecraftStart(WorldGenLevel world, FitTarget target, Supplier<StructureTemplateManager> templates) {
this.target = target;
StructureStart start = target.start();
BlockPos referencePosition = referencePosition(start);
List<NativeFitPiece<BlockState>> converted = new ArrayList<>(start.getPieces().size());
for (StructurePiece piece : start.getPieces()) {
converted.add(new MinecraftPiece(world, piece, referencePosition, templates));
}
this.pieces = List.copyOf(converted);
}
/** Where template processors measure from: the first piece's center, at its lowest block. */
private static BlockPos referencePosition(StructureStart start) {
BoundingBox bounds = start.getPieces().getFirst().getBoundingBox();
BlockPos center = bounds.getCenter();
return new BlockPos(center.getX(), bounds.minY(), center.getZ());
}
@Override
public String structureKey() {
return target.structureId();
}
@Override
public int chunkX() {
return target.start().getChunkPos().x();
}
@Override
public int chunkZ() {
return target.start().getChunkPos().z();
}
@Override
public String step() {
return target.start().getStructure().step().name();
}
@Override
public String adaptation() {
return target.start().getStructure().terrainAdaptation().name();
}
@Override
public NativeStartMemo memo() {
return target.memo();
}
@Override
public List<NativeFitPiece<BlockState>> pieces() {
return pieces;
}
@Override
public Object key() {
return target.start();
}
}
private static final class MinecraftPiece implements NativeFitPiece<BlockState> {
private final WorldGenLevel world;
private final StructurePiece piece;
private final BlockPos referencePosition;
private final Supplier<StructureTemplateManager> templates;
private MinecraftPiece(WorldGenLevel world, StructurePiece piece, BlockPos referencePosition,
Supplier<StructureTemplateManager> templates) {
this.world = world;
this.piece = piece;
this.referencePosition = referencePosition;
this.templates = templates;
}
@Override
public NativeFitBox box() {
return NativeStructureFitBridge.box(piece.getBoundingBox());
}
@Override
public String kind() {
if (!(piece instanceof PoolElementStructurePiece poolPiece)) {
return "FIXED";
}
return poolPiece.getElement().getProjection() == StructureTemplatePool.Projection.RIGID
? "RIGID" : "TERRAIN_MATCHING";
}
@Override
public int groundLevelDelta() {
return piece instanceof PoolElementStructurePiece poolPiece ? poolPiece.getGroundLevelDelta() : 0;
}
@Override
public List<int[]> junctions() {
if (!(piece instanceof PoolElementStructurePiece poolPiece)) {
return List.of();
}
List<int[]> junctions = new ArrayList<>(poolPiece.getJunctions().size());
for (JigsawJunction junction : poolPiece.getJunctions()) {
junctions.add(new int[]{junction.getSourceX(), junction.getSourceGroundY(), junction.getSourceZ()});
}
return junctions;
}
@Override
public NativeTemplateCells<BlockState> cells(NativeFitBox region) {
if (!(piece instanceof PoolElementStructurePiece poolPiece)) {
return new NativeTemplateCells<>(false, new int[0], new int[0], new int[0], new BlockState[0], 0);
}
BoundingBox processingArea = boundingBox(region);
return NativeStructureTemplateOccupancy.cells(world, poolPiece, referencePosition, processingArea, templates);
}
@Override
public void columns(ColumnVisitor visitor) {
BoundingBox bounds = piece.getBoundingBox();
if (piece instanceof PoolElementStructurePiece poolPiece
&& emitTemplateColumns(pieceTemplates(poolPiece), poolPiece.getPosition(), poolPiece.getRotation(),
bounds, visitor)) {
return;
}
for (int z = bounds.minZ(); z <= bounds.maxZ(); z++) {
for (int x = bounds.minX(); x <= bounds.maxX(); x++) {
visitor.column(x, z, bounds.minY(), bounds.maxY());
}
}
}
@Override
public List<int[]> legacyAir(NativeFitBox clip) {
if (!(piece instanceof PoolElementStructurePiece poolPiece)) {
return List.of();
}
StructurePlaceSettings settings = new StructurePlaceSettings()
.setRotation(poolPiece.getRotation())
.setBoundingBox(boundingBox(clip));
List<int[]> air = new ArrayList<>();
collectLegacyAir(poolPiece.getElement(), poolPiece.getPosition(), settings, air);
return air;
}
private void collectLegacyAir(StructurePoolElement element, BlockPos position, StructurePlaceSettings settings,
List<int[]> air) {
if (element instanceof ListPoolElement listElement) {
for (StructurePoolElement child : listElement.getElements()) {
collectLegacyAir(child, position, settings, air);
}
return;
}
if (!(element instanceof LegacySinglePoolElement legacyElement)) {
return;
}
StructureTemplate template = NativeStructureReflection.resolveTemplate(legacyElement, templates);
for (StructureTemplate.StructureBlockInfo block : template.filterBlocks(position, settings, Blocks.AIR)) {
BlockPos at = block.pos();
air.add(new int[]{at.getX(), at.getY(), at.getZ()});
}
}
private List<StructureTemplate> pieceTemplates(PoolElementStructurePiece poolPiece) {
List<StructureTemplate> resolved = new ArrayList<>(1);
collectElementTemplates(poolPiece.getElement(), resolved);
return resolved;
}
private void collectElementTemplates(StructurePoolElement element, List<StructureTemplate> resolved) {
if (element instanceof ListPoolElement listElement) {
for (StructurePoolElement child : listElement.getElements()) {
collectElementTemplates(child, resolved);
}
return;
}
if (element instanceof SinglePoolElement singleElement) {
resolved.add(NativeStructureReflection.resolveTemplate(singleElement, templates));
}
}
/**
* Per-column vertical extents from the complement of the templates' air and structure-void cells, so a carve
* tracks the actual silhouette instead of the piece's rectangular box. False when there is no template or it
* is too large to read, and the box stands in.
*/
private static boolean emitTemplateColumns(List<StructureTemplate> templates, BlockPos position,
Rotation rotation, BoundingBox bounds,
ColumnVisitor visitor) {
if (templates.isEmpty()) {
return false;
}
int width = bounds.getXSpan();
int depth = bounds.getZSpan();
long cells = (long) width * depth * bounds.getYSpan();
if (cells < 1L || cells > MAX_TEMPLATE_COLUMN_CELLS) {
return false;
}
StructurePlaceSettings settings = new StructurePlaceSettings().setRotation(rotation);
boolean[] voidCells = null;
for (StructureTemplate template : templates) {
boolean[] templateVoid = new boolean[(int) cells];
for (Block ignored : TEMPLATE_VOID_BLOCKS) {
for (StructureTemplate.StructureBlockInfo info : template.filterBlocks(position, settings, ignored)) {
BlockPos voidPosition = info.pos();
if (bounds.isInside(voidPosition)) {
templateVoid[cellIndex(bounds, width, depth,
voidPosition.getX(), voidPosition.getY(), voidPosition.getZ())] = true;
}
}
}
if (voidCells == null) {
voidCells = templateVoid;
continue;
}
for (int cell = 0; cell < voidCells.length; cell++) {
voidCells[cell] &= templateVoid[cell];
}
}
for (int z = bounds.minZ(); z <= bounds.maxZ(); z++) {
for (int x = bounds.minX(); x <= bounds.maxX(); x++) {
int minY = Integer.MAX_VALUE;
int maxY = Integer.MIN_VALUE;
for (int y = bounds.minY(); y <= bounds.maxY(); y++) {
if (voidCells[cellIndex(bounds, width, depth, x, y, z)]) {
continue;
}
if (minY == Integer.MAX_VALUE) {
minY = y;
}
maxY = y;
}
if (minY != Integer.MAX_VALUE) {
visitor.column(x, z, minY, maxY);
}
}
}
return true;
}
private static int cellIndex(BoundingBox bounds, int width, int depth, int x, int y, int z) {
return ((y - bounds.minY()) * depth + z - bounds.minZ()) * width + x - bounds.minX();
}
}
}
@@ -1,212 +0,0 @@
package art.arcane.iris.nativegen;
import art.arcane.iris.engine.object.structure.IrisStructureStiltSettings;
import art.arcane.volmlib.util.math.RNG;
import net.minecraft.core.BlockPos;
import net.minecraft.core.Direction;
import net.minecraft.tags.BlockTags;
import net.minecraft.world.level.WorldGenLevel;
import net.minecraft.world.level.block.Blocks;
import net.minecraft.world.level.block.SupportType;
import net.minecraft.world.level.block.state.BlockState;
import net.minecraft.world.level.levelgen.structure.BoundingBox;
import net.minecraft.world.level.levelgen.structure.PoolElementStructurePiece;
import net.minecraft.world.level.levelgen.structure.StructurePiece;
import net.minecraft.world.level.levelgen.structure.StructureStart;
import java.util.ArrayList;
import java.util.BitSet;
import java.util.List;
import java.util.Objects;
import java.util.function.IntBinaryOperator;
public final class NativeStructureFoundationBuilder {
private static final int FOUNDATION_VERTICAL_TOLERANCE = 1;
private NativeStructureFoundationBuilder() {
}
private static List<FoundationColumn> foundationEnvelope(BoundingBox area, StructureStart start) {
BoundingBox structure = NativeStructureReferenceEnvelope.contentBounds(start);
int minX = Math.max(area.minX(), structure.minX());
int minZ = Math.max(area.minZ(), structure.minZ());
int maxX = Math.min(area.maxX(), structure.maxX());
int maxZ = Math.min(area.maxZ(), structure.maxZ());
if (minX > maxX || minZ > maxZ) {
return List.of();
}
List<StructurePiece> pieces = start.getPieces();
List<FoundationColumn> columns = new ArrayList<>((maxX - minX + 1) * (maxZ - minZ + 1));
BitSet envelope = new BitSet(area.getYSpan());
for (int z = minZ; z <= maxZ; z++) {
for (int x = minX; x <= maxX; x++) {
envelope.clear();
markFoundationEnvelope(envelope, pieces, area, x, z);
int cellCount = envelope.cardinality();
if (cellCount == 0) {
continue;
}
int[] ys = new int[cellCount];
int cell = 0;
for (int bit = envelope.nextSetBit(0); bit >= 0; bit = envelope.nextSetBit(bit + 1)) {
ys[cell++] = area.minY() + bit;
}
columns.add(new FoundationColumn(x, z, ys));
}
}
return List.copyOf(columns);
}
private static void markFoundationEnvelope(BitSet envelope, List<StructurePiece> pieces, BoundingBox area,
int x, int z) {
for (StructurePiece piece : pieces) {
BoundingBox bounds = piece.getBoundingBox();
if (x < bounds.minX() || x > bounds.maxX() || z < bounds.minZ() || z > bounds.maxZ()) {
continue;
}
int groundY = bounds.minY();
if (piece instanceof PoolElementStructurePiece poolPiece) {
groundY += poolPiece.getGroundLevelDelta();
if (groundY < bounds.minY()) {
continue;
}
}
int minY = Math.max(area.minY(), bounds.minY());
int maxY = Math.min(area.maxY(), Math.min(bounds.maxY(), groundY + FOUNDATION_VERTICAL_TOLERANCE));
if (minY <= maxY) {
envelope.set(minY - area.minY(), maxY - area.minY() + 1);
}
}
}
static void placeStilts(WorldGenLevel world, BoundingBox area, String structureId,
StructureStart start, IrisStructureStiltSettings settings,
NativeStructurePostProcessor.PaletteBlockResolver paletteBlockResolver,
IntBinaryOperator surfaceHeight,
boolean surfaceStructure) {
Objects.requireNonNull(surfaceHeight, "Structure stilts require an Iris terrain height resolver");
BlockPos.MutableBlockPos position = new BlockPos.MutableBlockPos();
int structureHash = structureId == null ? 0 : structureId.hashCode();
RNG rng = new RNG(world.getSeed() ^ structureHash);
for (FoundationColumn column : foundationEnvelope(area, start)) {
if (!isStiltColumn(column.x(), column.z(), settings.getSpacing())) {
continue;
}
int foundationY = findFoundationY(world, column, position);
if (foundationY == Integer.MIN_VALUE) {
continue;
}
int terrainY = surfaceStructure
? Math.max(area.minY(), Math.min(
area.maxY(), surfaceHeight.applyAsInt(column.x(), column.z())))
: area.minY() - 1;
int anchorY = findStiltAnchorY(
world, column.x(), column.z(), foundationY,
Math.max(1, settings.getMaxDepth()), terrainY, area.minY(), position);
if (anchorY == Integer.MIN_VALUE) {
continue;
}
for (int y = foundationY - 1; y > anchorY; y--) {
position.set(column.x(), y, column.z());
BlockState stilt = settings.getPalette() == null
? Blocks.COBBLESTONE.defaultBlockState()
: Objects.requireNonNull(
paletteBlockResolver.resolve(
settings.getPalette(), rng, column.x(), y, column.z()),
"Stilt palette returned no block for " + structureId + " at "
+ column.x() + "," + y + "," + column.z());
world.setBlock(position, stilt, 2);
}
}
}
static boolean isStiltColumn(int x, int z, int spacing) {
int resolvedSpacing = Math.max(1, spacing);
return resolvedSpacing == 1
|| Math.floorMod(x, resolvedSpacing) == 0
&& Math.floorMod(z, resolvedSpacing) == 0;
}
static int findStiltAnchorY(
WorldGenLevel world, int x, int z, int foundationY, int maxDepth,
int terrainY, int areaMinY, BlockPos.MutableBlockPos position) {
int minimumAnchorY = Math.max(
areaMinY, Math.max(terrainY, foundationY - maxDepth - 1));
for (int y = foundationY - 1; y >= minimumAnchorY; y--) {
BlockState state = world.getBlockState(position.set(x, y, z));
boolean vegetation = state.is(BlockTags.LOGS) || state.is(BlockTags.LEAVES);
if (!vegetation && state.isFaceSturdy(
world, position, Direction.UP, SupportType.FULL)) {
return y;
}
}
return Integer.MIN_VALUE;
}
public static StiltSupportAudit auditStiltSupport(WorldGenLevel world, BoundingBox area,
StructureStart start, BlockState expectedStilt,
IntBinaryOperator surfaceHeight) {
Objects.requireNonNull(expectedStilt, "Expected stilt state must not be null");
Objects.requireNonNull(surfaceHeight, "Structure stilt audit requires an Iris terrain height resolver");
BlockPos.MutableBlockPos position = new BlockPos.MutableBlockPos();
int baseColumns = 0;
int stiltBlocks = 0;
int stiltColumns = 0;
int unsupportedColumns = 0;
for (FoundationColumn column : foundationEnvelope(area, start)) {
int foundationY = findFoundationY(world, column, position);
if (foundationY == Integer.MIN_VALUE) {
continue;
}
baseColumns++;
int terrainY = Math.max(area.minY(), Math.min(
area.maxY(), surfaceHeight.applyAsInt(column.x(), column.z())));
boolean grounded = foundationY <= terrainY + 1;
boolean stiltColumn = false;
for (int y = foundationY - 1; y >= area.minY(); y--) {
if (y <= terrainY) {
grounded = true;
break;
}
BlockState state = world.getBlockState(position.set(column.x(), y, column.z()));
if (state.is(expectedStilt.getBlock())) {
stiltBlocks++;
stiltColumn = true;
if (y == area.minY()) {
grounded = true;
}
continue;
}
boolean vegetation = state.is(BlockTags.LOGS) || state.is(BlockTags.LEAVES);
grounded = state.isSolid() && !vegetation;
break;
}
if (stiltColumn) {
stiltColumns++;
}
if (!grounded) {
unsupportedColumns++;
}
}
return new StiltSupportAudit(baseColumns, stiltBlocks, stiltColumns, unsupportedColumns);
}
private static int findFoundationY(WorldGenLevel world, FoundationColumn column,
BlockPos.MutableBlockPos position) {
for (int cell = 0; cell < column.ys().length; cell++) {
int y = column.ys()[cell];
BlockState state = world.getBlockState(position.set(column.x(), y, column.z()));
if (state.isSolid()) {
return y;
}
}
return Integer.MIN_VALUE;
}
private record FoundationColumn(int x, int z, int[] ys) {
}
public record StiltSupportAudit(int baseColumns, int stiltBlocks, int stiltColumns,
int unsupportedColumns) {
}
}
@@ -72,7 +72,7 @@ public final class NativeStructureOwnershipFingerprint {
references.minZ() >> 4,
references.maxZ() >> 4,
fingerprint(structureKey, resolvedStart),
resolvedPlan.decision()
resolvedPlan.memo()
);
}
@@ -1,14 +1,15 @@
package art.arcane.iris.nativegen;
import art.arcane.iris.engine.framework.Engine;
import art.arcane.iris.engine.framework.NativeStartMemo;
import art.arcane.iris.engine.framework.NativeStructureGenerationPolicy;
import art.arcane.iris.engine.framework.NativeStructureGenerationStatus;
import art.arcane.iris.engine.framework.NativeStructureLayouts;
import art.arcane.iris.engine.framework.NativeStructureReach;
import art.arcane.iris.engine.framework.NativeStructureOwnershipRecord;
import art.arcane.iris.engine.framework.NativeStructureOwnershipStore;
import art.arcane.iris.engine.framework.NativeStructureStarts;
import art.arcane.iris.engine.framework.NativeStructureStartPlan;
import art.arcane.iris.engine.object.structure.IrisStructureTerrain;
import art.arcane.iris.engine.object.structure.IrisStructureTerrainMode;
import art.arcane.iris.engine.object.structure.vanilla.NativeStructureGenerationStatus;
import net.minecraft.core.Holder;
import net.minecraft.core.Registry;
import net.minecraft.core.registries.Registries;
@@ -22,6 +23,7 @@ import net.minecraft.world.level.levelgen.structure.Structure;
import net.minecraft.world.level.levelgen.structure.StructureStart;
import net.minecraft.world.level.levelgen.structure.placement.StructurePlacement;
import java.util.List;
import java.util.Locale;
import java.util.Objects;
@@ -45,7 +47,8 @@ public final class NativeStructureOwnershipRecovery {
engine, structureKey, origin.x(), origin.z());
if (persisted != null) {
NativeStructureOwnershipRecord refreshed = refreshReferenceEnvelope(
structureKey, activeStructure, start, persisted);
structureKey, activeStructure, start, persisted, reachesOf(engine, structureKey, activeStructure,
persisted.restoredMemo()));
if (refreshed != null) {
if (refreshed != persisted) {
NativeStructureOwnershipStore.record(engine, refreshed);
@@ -67,9 +70,11 @@ public final class NativeStructureOwnershipRecovery {
return null;
}
StructureStart expected = generateExpected(
engine, activeLevel, holder, plan, start.getReferences());
engine, activeLevel, holder, plan, start.getReferences(),
reachesOf(engine, structureKey, activeStructure, plan.memo()));
NativeStructureOwnershipRecord recovered = proveCandidate(
structureKey, activeStructure, start, plan, expected, false);
structureKey, activeStructure, start, plan, expected, false,
reachesOf(engine, structureKey, activeStructure, plan.memo()));
if (recovered == null) {
return null;
}
@@ -77,26 +82,26 @@ public final class NativeStructureOwnershipRecovery {
return recovered;
}
/**
* The record with its reference envelope grown to what today's reaches give its start: a module may reach further
* around its starts than when it recorded one (VACUUM's fixed falloff did), and the start must then be referenced
* from the farther chunks too. An envelope never shrinks, so no chunk that once referenced the start loses it.
*/
static NativeStructureOwnershipRecord refreshReferenceEnvelope(
String structureKey, Structure structure, StructureStart start,
NativeStructureOwnershipRecord ownership) {
NativeStructureOwnershipRecord ownership, List<NativeStructureReach> reaches) {
if (structure == null || start == null || !start.isValid()
|| start.getStructure() != structure || ownership == null
|| !ownership.structureKey().equals(normalize(structureKey))
|| !NativeStructureOwnershipFingerprint.matches(ownership, start)) {
return null;
}
IrisStructureTerrain terrain = NativeStructureTerrainIntegrator.resolveNativeTerrain(
start, ownership.restoredDecision().terrain());
if (terrain.resolvedMode() != IrisStructureTerrainMode.VACUUM) {
return ownership;
}
BoundingBox expected = NativeStructureReferenceEnvelope.referenceBounds(
start, structure, terrain, structureKey);
int referenceMinChunkX = expected.minX() >> 4;
int referenceMaxChunkX = expected.maxX() >> 4;
int referenceMinChunkZ = expected.minZ() >> 4;
int referenceMaxChunkZ = expected.maxZ() >> 4;
start, structure, reaches, structureKey);
int referenceMinChunkX = Math.min(ownership.referenceMinChunkX(), expected.minX() >> 4);
int referenceMaxChunkX = Math.max(ownership.referenceMaxChunkX(), expected.maxX() >> 4);
int referenceMinChunkZ = Math.min(ownership.referenceMinChunkZ(), expected.minZ() >> 4);
int referenceMaxChunkZ = Math.max(ownership.referenceMaxChunkZ(), expected.maxZ() >> 4);
if (ownership.referenceMinChunkX() == referenceMinChunkX
&& ownership.referenceMaxChunkX() == referenceMaxChunkX
&& ownership.referenceMinChunkZ() == referenceMinChunkZ
@@ -111,7 +116,7 @@ public final class NativeStructureOwnershipRecovery {
static NativeStructureOwnershipRecord proveCandidate(
String structureKey, Structure structure, StructureStart persisted,
NativeStructureStartPlan plan, StructureStart expected,
boolean naturalStartAmbiguous) {
boolean naturalStartAmbiguous, List<NativeStructureReach> reaches) {
if (naturalStartAmbiguous || structure == null
|| persisted == null || !persisted.isValid()
|| expected == null || !expected.isValid()
@@ -122,7 +127,7 @@ public final class NativeStructureOwnershipRecovery {
return null;
}
BoundingBox referenceEnvelope = NativeStructureReferenceEnvelope.referenceBounds(
expected, structure, plan.terrain(), structureKey);
expected, structure, reaches, structureKey);
NativeStructureOwnershipRecord candidate = NativeStructureOwnershipFingerprint.capture(
structureKey, expected, plan, referenceEnvelope);
return NativeStructureOwnershipFingerprint.matches(candidate, persisted)
@@ -141,7 +146,7 @@ public final class NativeStructureOwnershipRecovery {
private static StructureStart generateExpected(
Engine engine, ServerLevel level, Holder<Structure> holder,
NativeStructureStartPlan plan, int references) {
NativeStructureStartPlan plan, int references, List<NativeStructureReach> reaches) {
ChunkGeneratorStructureState state = level.getChunkSource().getGeneratorState();
ChunkGenerator generator = level.getChunkSource().getGenerator();
BiomeSource biomeSource = generator.getBiomeSource();
@@ -159,7 +164,7 @@ public final class NativeStructureOwnershipRecovery {
generator.getSeaLevel(),
(x, z) -> engine.getHeight(x, z, true) + engine.getMinHeight()
);
return NativeStructureFactory.generate(generationContext, holder, plan, references);
return NativeStructureFactory.generate(generationContext, holder, plan, references, reaches);
}
private static boolean naturalStartIsAmbiguous(
@@ -169,10 +174,8 @@ public final class NativeStructureOwnershipRecovery {
if (plan.replacesPlatformStart()) {
return false;
}
NativeStructureGenerationStatus sourceStatus = NativeStructureGenerationPolicy.resolve(
engine, structureKey,
NativeStructureVegetationClearer.isUndergroundStep(structure.step())).status();
if (sourceStatus == NativeStructureGenerationStatus.REPLACED_BY_IRIS) {
if (NativeStructureGenerationPolicy.resolve(engine, structureKey)
== NativeStructureGenerationStatus.REPLACED_BY_IRIS) {
return false;
}
for (StructurePlacement placement : state.getPlacementsForStructure(holder)) {
@@ -183,6 +186,12 @@ public final class NativeStructureOwnershipRecovery {
return false;
}
private static List<NativeStructureReach> reachesOf(Engine engine, String structureKey, Structure structure,
NativeStartMemo memo) {
return NativeStructureLayouts.reaches(engine, structureKey,
NativeStructureVegetationClearer.isUndergroundStep(structure.step()), memo);
}
private static String normalize(String structureKey) {
return structureKey == null ? "" : structureKey.trim().toLowerCase(Locale.ROOT);
}
@@ -1,66 +0,0 @@
package art.arcane.iris.nativegen;
import art.arcane.iris.engine.object.material.IrisMaterialPalette;
import art.arcane.iris.engine.object.structure.vanilla.IrisNativeStructureDecision;
import art.arcane.iris.engine.object.structure.IrisStructureStiltSettings;
import art.arcane.volmlib.util.math.RNG;
import net.minecraft.world.level.ChunkPos;
import net.minecraft.world.level.StructureManager;
import net.minecraft.world.level.WorldGenLevel;
import net.minecraft.world.level.block.state.BlockState;
import net.minecraft.world.level.chunk.ChunkGenerator;
import net.minecraft.world.level.levelgen.WorldgenRandom;
import net.minecraft.world.level.levelgen.structure.BoundingBox;
import net.minecraft.world.level.levelgen.structure.StructureStart;
import java.util.List;
import java.util.function.IntBinaryOperator;
public final class NativeStructurePostProcessor {
private NativeStructurePostProcessor() {
}
public static void place(WorldGenLevel world, StructureManager structureManager, ChunkGenerator generator,
WorldgenRandom random, BoundingBox area, ChunkPos chunkPos, String structureId,
StructureStart start, IrisNativeStructureDecision decision,
PaletteBlockResolver paletteBlockResolver,
IntBinaryOperator surfaceHeight) {
IrisStructureStiltSettings stilt = decision.stilt();
NativeStructureVerticalPlacer.ensureMonumentSeaLevelAlignment(start, structureId, decision.yShift(),
generator.getSeaLevel(), area.minY(), area.maxY() + 1);
start.placeInChunk(world, structureManager, generator, random, area, chunkPos);
if (stilt != null) {
NativeStructureFoundationBuilder.placeStilts(world, area, structureId, start, stilt,
paletteBlockResolver, surfaceHeight,
!NativeStructureVegetationClearer.isUndergroundStep(start.getStructure().step()));
}
}
public static void prepareTerrain(WorldGenLevel world, BoundingBox area,
List<NativeStructureTerrainIntegrator.TerrainTarget> targets,
PaletteBlockResolver paletteBlockResolver) {
if (targets == null || targets.isEmpty()) {
return;
}
NativeStructureTerrainIntegrator.SourceTerrainSnapshot sourceTerrain =
NativeStructureTerrainIntegrator.captureSourceTerrain(world, area, targets);
for (NativeStructureTerrainIntegrator.TerrainTarget target : targets) {
NativeStructureTerrainIntegrator.integrateTerrain(world, area, target.structureId(), target.start(),
target.terrain(), paletteBlockResolver, sourceTerrain);
}
for (NativeStructureTerrainIntegrator.TerrainTarget target : targets) {
if (NativeStructureTerrainIntegrator.clearsLegacyTemplateAir(
target.start(), target.terrain())) {
NativeStructureTerrainIntegrator.clearLegacyTemplateAir(
world, area, target.start(), () -> world.getLevel().getStructureManager());
}
}
NativeStructureSurfaceSupportBuilder.bridgeRigidPieceSupport(
world, area, targets, () -> world.getLevel().getStructureManager());
}
@FunctionalInterface
public interface PaletteBlockResolver {
BlockState resolve(IrisMaterialPalette palette, RNG rng, int x, int y, int z);
}
}
@@ -1,7 +1,6 @@
package art.arcane.iris.nativegen;
import art.arcane.iris.engine.object.structure.IrisStructureTerrain;
import art.arcane.iris.engine.object.structure.IrisStructureTerrainMode;
import art.arcane.iris.engine.framework.NativeStructureReach;
import art.arcane.iris.spi.IrisLogging;
import net.minecraft.world.level.ChunkPos;
import net.minecraft.world.level.levelgen.structure.BoundingBox;
@@ -24,13 +23,13 @@ public final class NativeStructureReferenceEnvelope {
}
public static StructureStart wrap(StructureStart generated, Structure source, int references,
IrisStructureTerrain terrain) {
return wrap(generated, source, references, terrain, null);
List<NativeStructureReach> reaches) {
return wrap(generated, source, references, reaches, null);
}
public static StructureStart wrap(StructureStart generated, Structure source, int references,
IrisStructureTerrain terrain, String structureKey) {
referenceBounds(generated, source, terrain, structureKey);
List<NativeStructureReach> reaches, String structureKey) {
referenceBounds(generated, source, reaches, structureKey);
return new StructureStart(
source,
generated.getChunkPos(),
@@ -41,9 +40,9 @@ public final class NativeStructureReferenceEnvelope {
public static StructureStart wrapForPublication(
StructureStart generated, Structure source, int references,
IrisStructureTerrain terrain, String structureKey) {
List<NativeStructureReach> reaches, String structureKey) {
try {
return wrap(generated, source, references, terrain, structureKey);
return wrap(generated, source, references, reaches, structureKey);
} catch (UnrepresentableContentException exception) {
warnSkippedContent(generated, source, structureKey);
return StructureStart.INVALID_START;
@@ -51,22 +50,17 @@ public final class NativeStructureReferenceEnvelope {
}
public static BoundingBox referenceBounds(StructureStart start, Structure source,
IrisStructureTerrain terrain) {
return referenceBounds(start, source, terrain, null);
List<NativeStructureReach> reaches) {
return referenceBounds(start, source, reaches, null);
}
/**
* The blocks a start's references must cover: its pieces and, around them, every module's reach (the area the
* structure's own terrain adaptation covers for a platform reach), clipped to Minecraft's reference range.
*/
public static BoundingBox referenceBounds(StructureStart start, Structure source,
IrisStructureTerrain terrain,
List<NativeStructureReach> reaches,
String structureKey) {
IrisStructureTerrainMode mode = terrain == null
? IrisStructureTerrainMode.PRESERVE : terrain.resolvedMode();
boolean usesEnvelope = mode == IrisStructureTerrainMode.BORE
|| mode == IrisStructureTerrainMode.FORCE_CARVE
|| mode == IrisStructureTerrainMode.VACUUM
|| mode == IrisStructureTerrainMode.ENCASE;
int horizontalPadding = mode == IrisStructureTerrainMode.VACUUM
? NativeStructureSurfaceFitter.surfaceTerrainRadius()
: usesEnvelope ? Math.max(0, terrain.getHorizontalPadding()) : 0;
BoundingBox content = contentBounds(start);
if (!fitsReferenceRange(start.getChunkPos(), content)) {
throw new UnrepresentableContentException("Native structure content at "
@@ -74,22 +68,12 @@ public final class NativeStructureReferenceEnvelope {
+ " exceeds Minecraft's " + MAX_REFERENCE_DISTANCE_CHUNKS
+ "-chunk structure reference range");
}
BoundingBox adjustedEnvelope;
BoundingBox adjustedEnvelope = content;
boolean arithmeticClipped = false;
try {
BoundingBox envelope = horizontalPadding == 0
? content
: new BoundingBox(
Math.subtractExact(content.minX(), horizontalPadding),
content.minY(),
Math.subtractExact(content.minZ(), horizontalPadding),
Math.addExact(content.maxX(), horizontalPadding),
content.maxY(),
Math.addExact(content.maxZ(), horizontalPadding)
);
adjustedEnvelope = mode == IrisStructureTerrainMode.SOURCE
? source.adjustBoundingBox(content) : envelope;
adjustedEnvelope = encapsulating(adjustedEnvelope, content);
for (NativeStructureReach reach : reaches) {
adjustedEnvelope = encapsulating(adjustedEnvelope, reachEnvelope(source, content, reach));
}
} catch (ArithmeticException exception) {
adjustedEnvelope = maximumReferenceBounds(start.getChunkPos(), content);
arithmeticClipped = true;
@@ -102,6 +86,23 @@ public final class NativeStructureReferenceEnvelope {
return adjustedEnvelope;
}
private static BoundingBox reachEnvelope(Structure source, BoundingBox content, NativeStructureReach reach) {
if (reach.platform()) {
return source.adjustBoundingBox(content);
}
int padding = reach.blocks();
if (padding == 0) {
return content;
}
return new BoundingBox(
Math.subtractExact(content.minX(), padding),
content.minY(),
Math.subtractExact(content.minZ(), padding),
Math.addExact(content.maxX(), padding),
content.maxY(),
Math.addExact(content.maxZ(), padding));
}
public static boolean contentFitsReferenceRange(StructureStart start) {
try {
return fitsReferenceRange(start.getChunkPos(), contentBounds(start));
@@ -2,9 +2,10 @@ package art.arcane.iris.nativegen;
import art.arcane.iris.engine.framework.Engine;
import art.arcane.iris.engine.framework.NativeStructureGenerationPolicy;
import art.arcane.iris.engine.framework.NativeStructureGenerationStatus;
import art.arcane.iris.engine.framework.NativeStructureLayouts;
import art.arcane.iris.engine.framework.NativeStructureOwnershipRecord;
import art.arcane.iris.engine.framework.NativeStructureOwnershipStore;
import art.arcane.iris.engine.object.structure.vanilla.IrisNativeStructureDecision;
import art.arcane.iris.spi.IrisLogging;
import it.unimi.dsi.fastutil.longs.LongOpenHashSet;
import it.unimi.dsi.fastutil.longs.LongSet;
@@ -132,15 +133,12 @@ public final class NativeStructureReferenceRepair {
private static boolean naturalPolicyAllows(
Engine engine, String structureKey, Structure structure) {
IrisNativeStructureDecision decision = NativeStructureGenerationPolicy.resolve(
engine, structureKey,
NativeStructureVegetationClearer.isUndergroundStep(structure.step()));
return naturalDecisionAllows(decision);
return naturalStatusAllows(NativeStructureGenerationPolicy.resolve(engine, structureKey));
}
static boolean naturalDecisionAllows(IrisNativeStructureDecision decision) {
return Objects.requireNonNull(
decision, "Native structure decision must not be null").generate();
static boolean naturalStatusAllows(NativeStructureGenerationStatus status) {
return Objects.requireNonNull(status, "Native structure status must not be null")
== NativeStructureGenerationStatus.GENERATE_NATIVE;
}
private static void invalidateStart(
@@ -181,15 +179,13 @@ public final class NativeStructureReferenceRepair {
if (target == null || start == null || !start.isValid()) {
return false;
}
IrisNativeStructureDecision decision = NativeStructureGenerationPolicy.resolve(
engine, structureKey,
NativeStructureVegetationClearer.isUndergroundStep(structure.step()));
if (!decision.generate()) {
if (!NativeStructureGenerationPolicy.generates(engine, structureKey)) {
return false;
}
BoundingBox referenceBounds = NativeStructureReferenceEnvelope.referenceBounds(
start, structure,
NativeStructureTerrainIntegrator.resolveNativeTerrain(start, decision.terrain()),
NativeStructureLayouts.reaches(engine, structureKey,
NativeStructureVegetationClearer.isUndergroundStep(structure.step()), null),
structureKey);
return referenceBounds.intersects(
target.getMinBlockX(), target.getMinBlockZ(),
@@ -2,11 +2,13 @@ package art.arcane.iris.nativegen;
import art.arcane.iris.engine.framework.Engine;
import art.arcane.iris.engine.framework.NativeStructureGenerationPolicy;
import art.arcane.iris.engine.framework.NativeStructureGenerationStatus;
import art.arcane.iris.engine.framework.NativeStructureLayouts;
import art.arcane.iris.engine.framework.NativeStructureOwnershipRecord;
import art.arcane.iris.engine.framework.NativeStructureOwnershipStore;
import art.arcane.iris.engine.framework.NativeStructureReach;
import art.arcane.iris.engine.framework.NativeStructureStarts;
import art.arcane.iris.engine.framework.NativeStructureStartPlan;
import art.arcane.iris.engine.object.structure.vanilla.NativeStructureGenerationStatus;
import art.arcane.iris.spi.IrisLogging;
import net.minecraft.core.Holder;
import net.minecraft.core.Registry;
@@ -27,6 +29,7 @@ import net.minecraft.world.level.levelgen.structure.StructureStart;
import net.minecraft.world.level.levelgen.structure.templatesystem.StructureTemplateManager;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
@@ -67,10 +70,8 @@ public final class NativeStructureStartInjector {
section, structure, chunk);
boolean replacement = plan.replacesPlatformStart();
if (!replacement && existing != null && existing.isValid()) {
NativeStructureGenerationStatus sourceStatus = NativeStructureGenerationPolicy.resolve(
context.engine(), identifier.toString(),
NativeStructureVegetationClearer.isUndergroundStep(structure.step())).status();
replacement = sourceStatus == NativeStructureGenerationStatus.REPLACED_BY_IRIS;
replacement = NativeStructureGenerationPolicy.resolve(context.engine(), identifier.toString())
== NativeStructureGenerationStatus.REPLACED_BY_IRIS;
}
if (!replacement && existing != null && existing.isValid()) {
continue;
@@ -91,8 +92,10 @@ public final class NativeStructureStartInjector {
(x, z) -> context.engine().getHeight(x, z, true)
+ context.engine().getMinHeight()
);
List<NativeStructureReach> reaches = NativeStructureLayouts.reaches(context.engine(), identifier.toString(),
NativeStructureVegetationClearer.isUndergroundStep(structure.step()), plan.memo());
StructureStart generated = NativeStructureFactory.generate(
generationContext, holder, plan, references);
generationContext, holder, plan, references, reaches);
if (!isUsableGeneratedStart(generated)) {
if (replacement) {
context.structureManager().setStartForStructure(
@@ -104,7 +107,7 @@ public final class NativeStructureStartInjector {
continue;
}
BoundingBox referenceBounds = NativeStructureReferenceEnvelope.referenceBounds(
generated, structure, plan.terrain(), identifier.toString());
generated, structure, reaches, identifier.toString());
NativeStructureOwnershipRecord ownership = NativeStructureOwnershipFingerprint.capture(
identifier.toString(), generated, plan, referenceBounds);
NativeStructureOwnershipStore.record(context.engine(), ownership);
@@ -1,921 +0,0 @@
package art.arcane.iris.nativegen;
import art.arcane.iris.engine.object.placement.IrisObjectVacuum;
import art.arcane.iris.engine.object.structure.IrisStructureTerrain;
import art.arcane.iris.engine.object.structure.IrisStructureTerrainMode;
import art.arcane.iris.spi.IrisLogging;
import net.minecraft.core.BlockPos;
import net.minecraft.world.level.WorldGenLevel;
import net.minecraft.world.level.block.Blocks;
import net.minecraft.world.level.block.state.BlockState;
import net.minecraft.world.level.levelgen.GenerationStep;
import net.minecraft.world.level.levelgen.structure.BoundingBox;
import net.minecraft.world.level.levelgen.structure.PoolElementStructurePiece;
import net.minecraft.world.level.levelgen.structure.StructurePiece;
import net.minecraft.world.level.levelgen.structure.StructureStart;
import net.minecraft.world.level.levelgen.structure.TerrainAdjustment;
import net.minecraft.world.level.levelgen.structure.pools.JigsawJunction;
import net.minecraft.world.level.levelgen.structure.pools.StructureTemplatePool;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.IdentityHashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.IntBinaryOperator;
public final class NativeStructureSurfaceFitter {
private static final double SURFACE_TERRAIN_FALLOFF = 2.0;
private static final long SURFACE_TERRAIN_INFLUENCE_SCALE = 1_000_000L;
private static final int SURFACE_TERRAIN_RADIUS = 12;
private static final int MAX_SOURCE_SURFACE_DELTA = 6;
private static final int MAX_SURFACE_TEMPLATE_CELLS = 4_194_304;
private static final Set<String> WARNED_SOURCE_BUDGET =
ConcurrentHashMap.newKeySet();
private static final Set<String> WARNED_VACUUM_BUDGET =
ConcurrentHashMap.newKeySet();
private NativeStructureSurfaceFitter() {
}
public static VacuumFoundationPlan prepareSurfaceStructures(
WorldGenLevel world, BoundingBox area,
List<NativeStructureTerrainIntegrator.TerrainTarget> targets,
IntBinaryOperator surfaceHeight) {
return prepareSurfaceStructures(
world, area, targets, surfaceHeight, MAX_SURFACE_TEMPLATE_CELLS);
}
static VacuumFoundationPlan prepareSurfaceStructures(
WorldGenLevel world, BoundingBox area,
List<NativeStructureTerrainIntegrator.TerrainTarget> targets,
IntBinaryOperator surfaceHeight, int maximumTemplateCells) {
if (targets == null || targets.isEmpty()) {
return VacuumFoundationPlan.empty();
}
Objects.requireNonNull(surfaceHeight, "Surface structure terrain fitting requires an Iris height resolver");
List<SurfaceAnchor> anchors = collectSourceSurfaceAnchors(
world, area, targets, maximumTemplateCells);
if (!anchors.isEmpty()) {
fitSurfaceTerrain(world, area, anchors, surfaceHeight);
}
VacuumFootprint vacuum = collectVacuumFootprint(
world, area, targets, maximumTemplateCells);
if (!vacuum.anchors().isEmpty()) {
fitVacuumTerrain(world, area, vacuum, surfaceHeight);
}
return VacuumFoundationPlan.create(
vacuum.foundationBases(), vacuum.occupiedCells(), area);
}
public static void repairVacuumFoundations(
WorldGenLevel world, BoundingBox area,
VacuumFoundationPlan plan) {
if (plan == null || plan.foundationBases.isEmpty()) {
return;
}
BlockPos.MutableBlockPos position = new BlockPos.MutableBlockPos();
for (long packedBase : plan.foundationBases) {
BlockPos base = BlockPos.of(packedBase);
if (!area.isInside(base)) {
continue;
}
BlockState baseState = world.getBlockState(position.set(base));
if (!NativeStructureTemplateOccupancy.isSolidBase(baseState)) {
continue;
}
int supportY = findVacuumFoundationSupport(
world, area, position, base.getX(), base.getY() - 1, base.getZ());
if (supportY == Integer.MIN_VALUE || supportY == base.getY() - 1) {
continue;
}
if (intersectsVacuumOccupancy(
plan.occupiedCells, base.getX(), base.getZ(),
supportY + 1, base.getY() - 1)) {
continue;
}
BlockState fill = resolveSurfaceMaterials(
world, position, base.getX(), base.getZ(), supportY,
area.minY()).subsurface();
for (int y = supportY + 1; y < base.getY(); y++) {
BlockState existing = world.getBlockState(
position.set(base.getX(), y, base.getZ()));
if (existing.isAir() || !existing.getFluidState().isEmpty()) {
world.setBlock(position, fill, 2);
}
}
}
}
static boolean shouldPrepareSurfaceTerrain(TerrainAdjustment adjustment,
GenerationStep.Decoration step) {
return step == GenerationStep.Decoration.SURFACE_STRUCTURES
&& (adjustment == TerrainAdjustment.BEARD_THIN
|| adjustment == TerrainAdjustment.BEARD_BOX);
}
static int surfaceTerrainRadius() {
return SURFACE_TERRAIN_RADIUS;
}
static int resolveSurfaceTarget(List<SurfaceAnchor> anchors, int worldX, int worldZ,
int originalY) {
return resolveSurface(anchors, worldX, worldZ, originalY).targetY();
}
private static SurfaceResolution resolveSurface(List<SurfaceAnchor> anchors,
int worldX, int worldZ, int originalY) {
int localTargetY = originalY;
SurfaceAnchor selectedLocal = null;
long totalInfluence = 0L;
long weightedTargetY = 0L;
long maximumInfluence = 0L;
for (SurfaceAnchor anchor : anchors) {
int outX = IrisObjectVacuum.outset(worldX, anchor.minX(), anchor.maxX());
int outZ = IrisObjectVacuum.outset(worldZ, anchor.minZ(), anchor.maxZ());
boolean containsColumn = outX == 0 && outZ == 0;
long distanceSquared = (long) outX * outX + (long) outZ * outZ;
long radiusSquared = (long) SURFACE_TERRAIN_RADIUS * SURFACE_TERRAIN_RADIUS;
if (distanceSquared > radiusSquared) {
continue;
}
double distance = Math.sqrt(distanceSquared);
double factor = Math.pow(
1D - distance / SURFACE_TERRAIN_RADIUS, SURFACE_TERRAIN_FALLOFF);
if (factor <= 0D) {
continue;
}
int boundedTargetY = boundedSurfaceTarget(originalY, anchor.meetY());
if (containsColumn) {
if (precedes(anchor, selectedLocal)) {
localTargetY = boundedTargetY;
selectedLocal = anchor;
}
continue;
}
long influence = Math.round(factor * SURFACE_TERRAIN_INFLUENCE_SCALE);
if (influence <= 0L) {
continue;
}
long weightedInfluence = influence * Math.max(1, anchor.strength());
totalInfluence += weightedInfluence;
weightedTargetY += weightedInfluence * boundedTargetY;
maximumInfluence = Math.max(maximumInfluence, influence);
}
if (selectedLocal != null) {
return new SurfaceResolution(
localTargetY,
selectedLocal.strength() > 1
&& localTargetY == selectedLocal.meetY());
}
if (totalInfluence == 0L) {
return new SurfaceResolution(originalY, false);
}
double blendedTargetY = weightedTargetY / (double) totalInfluence;
double factor = maximumInfluence / (double) SURFACE_TERRAIN_INFLUENCE_SCALE;
return new SurfaceResolution(
blendSurfaceTarget(originalY, blendedTargetY, factor), false);
}
private static int boundedSurfaceTarget(int originalY, int meetY) {
int delta = Math.max(
-MAX_SOURCE_SURFACE_DELTA,
Math.min(MAX_SOURCE_SURFACE_DELTA, meetY - originalY));
return originalY + delta;
}
private static int blendSurfaceTarget(int originalY, double targetY, double factor) {
double delta = (targetY - originalY) * factor;
int magnitude = (int) Math.round(Math.abs(delta));
return originalY + (delta < 0D ? -magnitude : magnitude);
}
private static boolean precedes(SurfaceAnchor candidate, SurfaceAnchor selected) {
if (selected == null) {
return true;
}
if (candidate.strength() != selected.strength()) {
return candidate.strength() > selected.strength();
}
if (candidate.meetY() != selected.meetY()) {
return candidate.meetY() < selected.meetY();
}
if (candidate.minX() != selected.minX()) {
return candidate.minX() < selected.minX();
}
if (candidate.minZ() != selected.minZ()) {
return candidate.minZ() < selected.minZ();
}
if (candidate.maxX() != selected.maxX()) {
return candidate.maxX() < selected.maxX();
}
if (candidate.maxZ() != selected.maxZ()) {
return candidate.maxZ() < selected.maxZ();
}
return false;
}
private static List<SurfaceAnchor> collectSourceSurfaceAnchors(
WorldGenLevel world, BoundingBox area,
List<NativeStructureTerrainIntegrator.TerrainTarget> targets,
int maximumTemplateCells) {
BoundingBox influenceArea = new BoundingBox(
area.minX() - SURFACE_TERRAIN_RADIUS, area.minY(),
area.minZ() - SURFACE_TERRAIN_RADIUS,
area.maxX() + SURFACE_TERRAIN_RADIUS, area.maxY(),
area.maxZ() + SURFACE_TERRAIN_RADIUS);
List<SurfaceAnchor> anchors = new ArrayList<>();
Set<StructureStart> seenStarts = Collections.newSetFromMap(
new IdentityHashMap<>());
for (NativeStructureTerrainIntegrator.TerrainTarget target : targets) {
if (!requiresSourceSurfaceTerrain(target)) {
continue;
}
StructureStart start = target.start();
if (!seenStarts.add(start)) {
continue;
}
BoundingBox firstBounds = start.getPieces().getFirst().getBoundingBox();
BlockPos firstCenter = firstBounds.getCenter();
BlockPos referencePosition = new BlockPos(
firstCenter.getX(), firstBounds.minY(), firstCenter.getZ());
TemplateCellBudget budget = new TemplateCellBudget(maximumTemplateCells);
boolean budgetExceeded = false;
for (StructurePiece piece : start.getPieces()) {
if (piece instanceof PoolElementStructurePiece poolPiece) {
StructureTemplatePool.Projection projection =
poolPiece.getElement().getProjection();
if (!budgetExceeded
&& (projection == StructureTemplatePool.Projection.RIGID
|| projection == StructureTemplatePool.Projection.TERRAIN_MATCHING)
&& intersectsHorizontally(poolPiece.getBoundingBox(), influenceArea)) {
try {
List<SurfaceAnchor> pieceAnchors = new ArrayList<>();
addProcessedSurfaceAnchors(
world, influenceArea, poolPiece, referencePosition,
projection, budget, pieceAnchors);
anchors.addAll(pieceAnchors);
} catch (TemplateBudgetExceeded ignored) {
budgetExceeded = true;
warnSourceBudget(target);
}
}
for (JigsawJunction junction : poolPiece.getJunctions()) {
anchors.add(new SurfaceAnchor(
junction.getSourceX(), junction.getSourceX(),
junction.getSourceZ(), junction.getSourceZ(),
junction.getSourceGroundY() - 1, 1));
}
continue;
}
BoundingBox bounds = piece.getBoundingBox();
anchors.add(surfaceAnchor(bounds, bounds.minY(), 2));
}
}
return List.copyOf(anchors);
}
private static void addProcessedSurfaceAnchors(
WorldGenLevel world, BoundingBox influenceArea,
PoolElementStructurePiece piece, BlockPos referencePosition,
StructureTemplatePool.Projection projection,
TemplateCellBudget budget,
List<SurfaceAnchor> anchors) {
NativeStructureTemplateOccupancy.OccupancyResult occupancy =
NativeStructureTemplateOccupancy.resolve(
world, piece, referencePosition, influenceArea,
() -> world.getLevel().getStructureManager(),
influenceArea::isInside, budget::consume);
if (!occupancy.resolved()) {
return;
}
int maximumFoundationY = piece.getBoundingBox().minY()
+ piece.getGroundLevelDelta();
Map<Long, NativeStructureTemplateOccupancy.LowestCell> lowest =
NativeStructureTemplateOccupancy.lowestProcessedSolidCells(occupancy.cells());
for (NativeStructureTemplateOccupancy.LowestCell cell : lowest.values()) {
budget.consume(1);
if (projection == StructureTemplatePool.Projection.RIGID
&& cell.y() > maximumFoundationY) {
continue;
}
int groundY = projection == StructureTemplatePool.Projection.RIGID
? maximumFoundationY : cell.y();
BoundingBox column = new BoundingBox(
cell.x(), groundY, cell.z(), cell.x(), groundY, cell.z());
anchors.add(surfaceAnchor(column, groundY, 2));
}
}
private static void warnSourceBudget(
NativeStructureTerrainIntegrator.TerrainTarget target) {
String structureId = target.structureId() == null
? target.start().getStructure().getClass().getName()
: target.structureId();
if (WARNED_SOURCE_BUDGET.add(structureId)) {
IrisLogging.warn("Native structure SOURCE fitting for '"
+ structureId + "' exceeded its bounded template budget; "
+ "skipping remaining processed footprints for this start");
}
}
private static VacuumFootprint collectVacuumFootprint(
WorldGenLevel world, BoundingBox area,
List<NativeStructureTerrainIntegrator.TerrainTarget> targets,
int maximumTemplateCells) {
BoundingBox influenceArea = new BoundingBox(
area.minX() - SURFACE_TERRAIN_RADIUS, area.minY(),
area.minZ() - SURFACE_TERRAIN_RADIUS,
area.maxX() + SURFACE_TERRAIN_RADIUS, area.maxY(),
area.maxZ() + SURFACE_TERRAIN_RADIUS);
Map<Long, VacuumAnchor> anchors = new HashMap<>();
Map<Long, Integer> columnCaps = new HashMap<>();
Set<Long> foundationBases = new HashSet<>();
Set<Long> occupiedCells = new HashSet<>();
Set<StructureStart> seenStarts = Collections.newSetFromMap(
new IdentityHashMap<>());
for (NativeStructureTerrainIntegrator.TerrainTarget target : targets) {
if (target == null || target.terrain() == null
|| target.terrain().resolvedMode() != IrisStructureTerrainMode.VACUUM
|| target.start() == null || !target.start().isValid()
|| !seenStarts.add(target.start())) {
continue;
}
StructureStart start = target.start();
BoundingBox firstBounds = start.getPieces().getFirst().getBoundingBox();
BlockPos firstCenter = firstBounds.getCenter();
BlockPos referencePosition = new BlockPos(
firstCenter.getX(), firstBounds.minY(), firstCenter.getZ());
Map<Long, VacuumAnchor> targetAnchors = new HashMap<>();
Map<Long, Integer> targetCaps = new HashMap<>();
Set<Long> targetFoundationBases = new HashSet<>();
Set<Long> targetOccupiedCells = new HashSet<>();
TemplateCellBudget budget = new TemplateCellBudget(maximumTemplateCells);
try {
for (StructurePiece piece : start.getPieces()) {
BoundingBox bounds = piece.getBoundingBox();
if (!intersectsHorizontally(bounds, influenceArea)
|| !(piece instanceof PoolElementStructurePiece poolPiece)
|| poolPiece.getElement().getProjection()
!= StructureTemplatePool.Projection.RIGID) {
continue;
}
addVacuumJunctionAnchors(
anchors, influenceArea, poolPiece);
NativeStructureTemplateOccupancy.OccupancyResult occupancy =
NativeStructureTemplateOccupancy.resolve(
world, poolPiece, referencePosition, influenceArea,
() -> world.getLevel().getStructureManager(),
influenceArea::isInside, budget::consume);
if (!occupancy.resolved()) {
continue;
}
targetOccupiedCells.addAll(occupancy.cells().keySet());
Map<Long, NativeStructureTemplateOccupancy.LowestCell> lowest =
NativeStructureTemplateOccupancy.lowestCells(
occupancy.cells());
int groundY = bounds.minY()
+ poolPiece.getGroundLevelDelta() - 1;
for (NativeStructureTemplateOccupancy.LowestCell cell : lowest.values()) {
budget.consume(1);
long column = NativeStructureTemplateOccupancy.columnKey(
cell.x(), cell.z());
targetCaps.merge(
column, Math.min(cell.y(), groundY), Math::min);
if (cell.occupancy().blocker()
|| cell.y() > groundY + 1
|| !NativeStructureTemplateOccupancy.isSolidBase(
cell.occupancy().state())) {
continue;
}
addVacuumAnchor(targetAnchors, cell.x(), cell.z(),
new VacuumAnchor(cell.y() - 1, 2));
targetFoundationBases.add(BlockPos.asLong(
cell.x(), cell.y(), cell.z()));
}
}
} catch (TemplateBudgetExceeded ignored) {
warnVacuumBudget(target);
continue;
}
targetAnchors.forEach((column, anchor) -> anchors.merge(
column, anchor, NativeStructureSurfaceFitter::preferredVacuumAnchor));
targetCaps.forEach((column, cap) -> columnCaps.merge(
column, cap, Math::min));
foundationBases.addAll(targetFoundationBases);
occupiedCells.addAll(targetOccupiedCells);
}
return new VacuumFootprint(
Map.copyOf(anchors), Map.copyOf(columnCaps),
Set.copyOf(foundationBases), Set.copyOf(occupiedCells));
}
private static void addVacuumJunctionAnchors(
Map<Long, VacuumAnchor> anchors, BoundingBox influenceArea,
PoolElementStructurePiece poolPiece) {
for (JigsawJunction junction : poolPiece.getJunctions()) {
if (junction.getSourceX() < influenceArea.minX()
|| junction.getSourceX() > influenceArea.maxX()
|| junction.getSourceZ() < influenceArea.minZ()
|| junction.getSourceZ() > influenceArea.maxZ()) {
continue;
}
addVacuumAnchor(anchors,
junction.getSourceX(), junction.getSourceZ(),
new VacuumAnchor(junction.getSourceGroundY() - 1, 1));
}
}
private static void warnVacuumBudget(
NativeStructureTerrainIntegrator.TerrainTarget target) {
String structureId = target.structureId() == null
? target.start().getStructure().getClass().getName()
: target.structureId();
if (WARNED_VACUUM_BUDGET.add(structureId)) {
IrisLogging.warn("Native structure VACUUM fitting for '"
+ structureId + "' exceeded its bounded template budget; "
+ "using jigsaw junction smoothing for oversized starts");
}
}
private static boolean intersectsHorizontally(
BoundingBox first, BoundingBox second) {
return first.maxX() >= second.minX() && first.minX() <= second.maxX()
&& first.maxZ() >= second.minZ() && first.minZ() <= second.maxZ();
}
private static void addVacuumAnchor(
Map<Long, VacuumAnchor> anchors, int x, int z,
VacuumAnchor candidate) {
anchors.merge(NativeStructureTemplateOccupancy.columnKey(x, z), candidate,
NativeStructureSurfaceFitter::preferredVacuumAnchor);
}
private static VacuumAnchor preferredVacuumAnchor(
VacuumAnchor first, VacuumAnchor second) {
if (first.strength() != second.strength()) {
return first.strength() > second.strength() ? first : second;
}
return first.surfaceY() <= second.surfaceY() ? first : second;
}
static SurfaceAnchor surfaceAnchor(BoundingBox bounds, int groundY, int strength) {
return new SurfaceAnchor(bounds.minX(), bounds.maxX(), bounds.minZ(), bounds.maxZ(),
groundY - 1, strength);
}
static boolean requiresSurfaceTerrain(StructureStart start) {
return requiresSurfaceTerrain(new NativeStructureTerrainIntegrator.TerrainTarget(
null, start, new IrisStructureTerrain().setMode(IrisStructureTerrainMode.SOURCE)));
}
static boolean requiresSurfaceTerrain(NativeStructureTerrainIntegrator.TerrainTarget target) {
if (target == null || target.terrain() == null) {
return false;
}
StructureStart start = target.start();
if (start == null || !start.isValid()) {
return false;
}
IrisStructureTerrainMode mode = target.terrain().resolvedMode();
return mode == IrisStructureTerrainMode.VACUUM
|| requiresSourceSurfaceTerrain(target);
}
private static boolean requiresSourceSurfaceTerrain(
NativeStructureTerrainIntegrator.TerrainTarget target) {
return target != null && target.terrain() != null
&& target.start() != null && target.start().isValid()
&& target.terrain().resolvedMode() == IrisStructureTerrainMode.SOURCE
&& shouldPrepareSurfaceTerrain(
target.start().getStructure().terrainAdaptation(),
target.start().getStructure().step());
}
private static void fitSurfaceTerrain(WorldGenLevel world, BoundingBox area,
List<SurfaceAnchor> anchors,
IntBinaryOperator surfaceHeight) {
int width = area.getXSpan();
int depth = area.getZSpan();
int[] originalHeights = new int[width * depth];
int[] targetHeights = new int[width * depth];
boolean[] rigidBaseSupport = new boolean[width * depth];
for (int z = area.minZ(); z <= area.maxZ(); z++) {
for (int x = area.minX(); x <= area.maxX(); x++) {
int column = (z - area.minZ()) * width + x - area.minX();
int originalY = Math.max(area.minY(), Math.min(
area.maxY(), surfaceHeight.applyAsInt(x, z)));
SurfaceResolution resolution = resolveSurface(anchors, x, z, originalY);
originalHeights[column] = originalY;
targetHeights[column] = Math.max(area.minY(), Math.min(
area.maxY(), resolution.targetY()));
rigidBaseSupport[column] = resolution.rigidBaseSupport();
}
}
BlockPos.MutableBlockPos position = new BlockPos.MutableBlockPos();
for (int z = area.minZ(); z <= area.maxZ(); z++) {
for (int x = area.minX(); x <= area.maxX(); x++) {
int column = (z - area.minZ()) * width + x - area.minX();
applySurfaceColumn(world, position, x, z,
originalHeights[column], targetHeights[column], area.minY(), area.maxY(),
rigidBaseSupport[column]);
}
}
}
private static void fitVacuumTerrain(
WorldGenLevel world, BoundingBox area, VacuumFootprint footprint,
IntBinaryOperator surfaceHeight) {
int width = area.getXSpan();
int depth = area.getZSpan();
int[] originalHeights = new int[width * depth];
int[] targetHeights = new int[width * depth];
boolean[] rigidBaseSupport = new boolean[width * depth];
BlockPos.MutableBlockPos position = new BlockPos.MutableBlockPos();
for (int z = area.minZ(); z <= area.maxZ(); z++) {
for (int x = area.minX(); x <= area.maxX(); x++) {
int column = (z - area.minZ()) * width + x - area.minX();
int nominalY = Math.max(area.minY(), Math.min(
area.maxY(), surfaceHeight.applyAsInt(x, z)));
long columnKey = NativeStructureTemplateOccupancy.columnKey(x, z);
VacuumAnchor local = footprint.anchors().get(columnKey);
Integer cap = footprint.columnCaps().get(columnKey);
boolean suppressed = local != null && local.strength() > 1
&& cap != null && cap < local.surfaceY();
int scanStartY = local != null && local.strength() > 1 && !suppressed
? Math.max(area.minY(), Math.min(area.maxY(), local.surfaceY()))
: nominalY;
int originalY = resolveVacuumSurfaceHeight(
world, position, x, z, scanStartY, area.minY());
SurfaceResolution resolution = resolveVacuumSurface(
footprint, x, z, originalY);
originalHeights[column] = originalY;
targetHeights[column] = Math.max(originalY, Math.min(
area.maxY(), resolution.targetY()));
rigidBaseSupport[column] = resolution.rigidBaseSupport()
&& targetHeights[column] > originalY;
}
}
for (int z = area.minZ(); z <= area.maxZ(); z++) {
for (int x = area.minX(); x <= area.maxX(); x++) {
int column = (z - area.minZ()) * width + x - area.minX();
applySurfaceColumn(world, position, x, z,
originalHeights[column], targetHeights[column],
area.minY(), area.maxY(), rigidBaseSupport[column]);
}
}
}
private static int resolveVacuumSurfaceHeight(
WorldGenLevel world, BlockPos.MutableBlockPos position,
int x, int z, int nominalY, int worldMinY) {
for (int y = nominalY; y >= worldMinY; y--) {
if (isTerrainBlock(world.getBlockState(position.set(x, y, z)))) {
return y;
}
}
return nominalY;
}
private static int findVacuumFoundationSupport(
WorldGenLevel world, BoundingBox area,
BlockPos.MutableBlockPos position, int x, int startY, int z) {
if (startY < area.minY()) {
return Integer.MIN_VALUE;
}
int maximumY = Math.min(area.maxY(), startY);
for (int y = maximumY; y >= area.minY(); y--) {
BlockState state = world.getBlockState(position.set(x, y, z));
if (isTerrainBlock(state)) {
return y;
}
if (!state.isAir() && state.getFluidState().isEmpty()) {
return Integer.MIN_VALUE;
}
}
return Integer.MIN_VALUE;
}
private static boolean intersectsVacuumOccupancy(
Set<Long> occupiedCells, int x, int z, int minimumY, int maximumY) {
for (int y = minimumY; y <= maximumY; y++) {
if (occupiedCells.contains(BlockPos.asLong(x, y, z))) {
return true;
}
}
return false;
}
private static SurfaceResolution resolveVacuumSurface(
VacuumFootprint footprint, int worldX, int worldZ, int originalY) {
long column = NativeStructureTemplateOccupancy.columnKey(worldX, worldZ);
Integer cap = footprint.columnCaps().get(column);
VacuumAnchor local = footprint.anchors().get(column);
if (local != null && local.strength() > 1) {
int localTargetY = cap == null
? local.surfaceY() : Math.min(local.surfaceY(), cap);
if (localTargetY <= originalY) {
return new SurfaceResolution(originalY, false);
}
return new SurfaceResolution(
localTargetY, localTargetY == local.surfaceY());
}
long totalInfluence = 0L;
long weightedSurfaceY = 0L;
long maximumInfluence = 0L;
int radiusSquared = SURFACE_TERRAIN_RADIUS * SURFACE_TERRAIN_RADIUS;
for (int offsetX = -SURFACE_TERRAIN_RADIUS;
offsetX <= SURFACE_TERRAIN_RADIUS; offsetX++) {
for (int offsetZ = -SURFACE_TERRAIN_RADIUS;
offsetZ <= SURFACE_TERRAIN_RADIUS; offsetZ++) {
int horizontalDistanceSquared = offsetX * offsetX + offsetZ * offsetZ;
if (horizontalDistanceSquared > radiusSquared) {
continue;
}
VacuumAnchor anchor = footprint.anchors().get(
NativeStructureTemplateOccupancy.columnKey(
worldX + offsetX, worldZ + offsetZ));
if (anchor == null || anchor.surfaceY() <= originalY) {
continue;
}
int verticalDistance = Math.abs(anchor.surfaceY() + 1 - originalY);
long distanceSquared = horizontalDistanceSquared
+ (long) verticalDistance * verticalDistance;
double factor = 0D;
if (distanceSquared <= radiusSquared) {
factor = surfaceFactor(Math.sqrt(distanceSquared));
}
if (anchor.strength() > 1
&& verticalDistance > SURFACE_TERRAIN_RADIUS) {
double rescueProgress = Math.min(1D,
(verticalDistance - SURFACE_TERRAIN_RADIUS)
/ (double) SURFACE_TERRAIN_RADIUS);
double rescueWeight = rescueProgress * rescueProgress
* (3D - 2D * rescueProgress);
factor = Math.max(factor,
surfaceFactor(Math.sqrt(horizontalDistanceSquared))
* rescueWeight);
}
long influence = Math.round(
factor * SURFACE_TERRAIN_INFLUENCE_SCALE);
if (influence <= 0L) {
continue;
}
long weightedInfluence = influence * Math.max(1, anchor.strength());
totalInfluence += weightedInfluence;
weightedSurfaceY += weightedInfluence * anchor.surfaceY();
maximumInfluence = Math.max(maximumInfluence, influence);
}
}
if (totalInfluence == 0L) {
return new SurfaceResolution(originalY, false);
}
double blendedSurfaceY = weightedSurfaceY / (double) totalInfluence;
double factor = maximumInfluence / (double) SURFACE_TERRAIN_INFLUENCE_SCALE;
int targetY = (int) Math.round(
originalY + ((blendedSurfaceY - originalY) * factor));
if (cap != null) {
targetY = Math.min(targetY, cap);
}
return new SurfaceResolution(Math.max(originalY, targetY), false);
}
private static double surfaceFactor(double distance) {
return Math.pow(1D - distance / SURFACE_TERRAIN_RADIUS,
SURFACE_TERRAIN_FALLOFF);
}
static void applySurfaceColumn(WorldGenLevel world, BlockPos.MutableBlockPos position,
int x, int z, int originalY, int targetY,
int worldMinY, int worldMaxY) {
applySurfaceColumn(world, position, x, z, originalY, targetY,
worldMinY, worldMaxY, false);
}
static void applySurfaceColumn(WorldGenLevel world, BlockPos.MutableBlockPos position,
int x, int z, int originalY, int targetY,
int worldMinY, int worldMaxY,
boolean requireRigidBaseSupport) {
if (targetY == originalY) {
if (requireRigidBaseSupport) {
ensureRigidBaseTerrain(world, position, x, z, targetY, worldMinY);
}
return;
}
SurfaceMaterials materials = resolveSurfaceMaterials(world, position, x, z, originalY, worldMinY);
if (targetY < originalY) {
BlockState clearedState = clearSurfaceDecorationAndResolveFill(
world, position, x, z, originalY, worldMaxY);
for (int y = originalY; y > targetY; y--) {
world.setBlock(position.set(x, y, z), clearedState, 2);
}
world.setBlock(position.set(x, targetY, z), materials.surface(), 2);
if (requireRigidBaseSupport) {
ensureRigidBaseTerrain(world, position, x, z, targetY, worldMinY, materials);
}
return;
}
for (int y = originalY + 1; y < targetY; y++) {
position.set(x, y, z);
if (!NativeStructureVegetationClearer.isTreeBlock(world.getBlockState(position))) {
world.setBlock(position, materials.subsurface(), 2);
}
}
position.set(x, targetY, z);
if (!NativeStructureVegetationClearer.isTreeBlock(world.getBlockState(position))) {
world.setBlock(position, materials.surface(), 2);
}
if (requireRigidBaseSupport) {
ensureRigidBaseTerrain(world, position, x, z, targetY, worldMinY, materials);
}
}
private static void ensureRigidBaseTerrain(WorldGenLevel world,
BlockPos.MutableBlockPos position,
int x, int z, int targetY, int worldMinY) {
int supportY = targetY - 1;
boolean targetIsTerrain = isTerrainBlock(world.getBlockState(position.set(x, targetY, z)));
boolean supportIsTerrain = supportY < worldMinY
|| isTerrainBlock(world.getBlockState(position.set(x, supportY, z)));
if (targetIsTerrain && supportIsTerrain) {
return;
}
SurfaceMaterials materials = resolveSurfaceMaterials(
world, position, x, z, targetY, worldMinY);
ensureRigidBaseTerrain(world, position, x, z, targetY, worldMinY, materials);
}
private static void ensureRigidBaseTerrain(WorldGenLevel world,
BlockPos.MutableBlockPos position,
int x, int z, int targetY, int worldMinY,
SurfaceMaterials materials) {
int supportY = targetY - 1;
position.set(x, targetY, z);
if (!isTerrainBlock(world.getBlockState(position))) {
world.setBlock(position, materials.surface(), 2);
}
if (supportY < worldMinY) {
return;
}
position.set(x, supportY, z);
if (!isTerrainBlock(world.getBlockState(position))) {
world.setBlock(position, materials.subsurface(), 2);
}
}
private static BlockState clearSurfaceDecorationAndResolveFill(
WorldGenLevel world, BlockPos.MutableBlockPos position,
int x, int z, int originalY, int worldMaxY) {
BlockState air = Blocks.AIR.defaultBlockState();
for (int y = originalY + 1; y <= worldMaxY; y++) {
BlockState state = world.getBlockState(position.set(x, y, z));
if (state.isAir()) {
return air;
}
if (!state.getFluidState().isEmpty()) {
BlockState fluid = state.getFluidState().createLegacyBlock();
if (state != fluid) {
world.setBlock(position, fluid, 2);
}
return fluid;
}
if (state.isSolid() || NativeStructureVegetationClearer.isTreeBlock(state)) {
return air;
}
world.setBlock(position, air, 2);
}
return air;
}
private static SurfaceMaterials resolveSurfaceMaterials(WorldGenLevel world,
BlockPos.MutableBlockPos position,
int x, int z, int originalY,
int worldMinY) {
BlockState surface = world.getBlockState(position.set(x, originalY, z));
BlockState subsurface = null;
for (int y = originalY - 1; y >= worldMinY; y--) {
BlockState candidate = world.getBlockState(position.set(x, y, z));
if (isTerrainBlock(candidate)) {
subsurface = candidate;
break;
}
}
if (subsurface == null) {
subsurface = isTerrainBlock(surface) ? surface : Blocks.STONE.defaultBlockState();
}
if (!isTerrainBlock(surface)) {
surface = subsurface;
}
return new SurfaceMaterials(surface, subsurface);
}
private static boolean isTerrainBlock(BlockState state) {
return state.isSolid() && !NativeStructureVegetationClearer.isTreeBlock(state);
}
record SurfaceAnchor(int minX, int maxX, int minZ, int maxZ, int meetY, int strength) {
}
private record SurfaceMaterials(BlockState surface, BlockState subsurface) {
}
private record SurfaceResolution(int targetY, boolean rigidBaseSupport) {
}
private record VacuumFootprint(
Map<Long, VacuumAnchor> anchors, Map<Long, Integer> columnCaps,
Set<Long> foundationBases, Set<Long> occupiedCells) {
}
private record VacuumAnchor(int surfaceY, int strength) {
}
public static final class VacuumFoundationPlan {
private static final VacuumFoundationPlan EMPTY =
new VacuumFoundationPlan(List.of(), Set.of());
private final List<Long> foundationBases;
private final Set<Long> occupiedCells;
private VacuumFoundationPlan(
List<Long> foundationBases, Set<Long> occupiedCells) {
this.foundationBases = foundationBases;
this.occupiedCells = occupiedCells;
}
private static VacuumFoundationPlan empty() {
return EMPTY;
}
private static VacuumFoundationPlan create(
Set<Long> packedBases, Set<Long> packedOccupancy,
BoundingBox area) {
if (packedBases.isEmpty()) {
return EMPTY;
}
List<Long> bases = new ArrayList<>(packedBases.size());
Set<Long> columns = new HashSet<>();
for (long packedBase : packedBases) {
BlockPos base = BlockPos.of(packedBase);
if (!area.isInside(base)) {
continue;
}
bases.add(packedBase);
columns.add(NativeStructureTemplateOccupancy.columnKey(
base.getX(), base.getZ()));
}
if (bases.isEmpty()) {
return EMPTY;
}
bases.sort((first, second) -> {
int yOrder = Integer.compare(
BlockPos.of(first).getY(), BlockPos.of(second).getY());
return yOrder == 0 ? Long.compare(first, second) : yOrder;
});
Set<Long> occupancy = new HashSet<>();
for (long packedCell : packedOccupancy) {
BlockPos cell = BlockPos.of(packedCell);
if (columns.contains(NativeStructureTemplateOccupancy.columnKey(
cell.getX(), cell.getZ()))) {
occupancy.add(packedCell);
}
}
return new VacuumFoundationPlan(
List.copyOf(bases), Set.copyOf(occupancy));
}
}
private static final class TemplateCellBudget {
private final int maximum;
private int consumed;
private TemplateCellBudget(int maximum) {
if (maximum < 0) {
throw new IllegalArgumentException(
"Native structure surface template budget cannot be negative");
}
this.maximum = maximum;
}
private void consume(int amount) {
if (amount < 0 || consumed > maximum - amount) {
throw TemplateBudgetExceeded.INSTANCE;
}
consumed += amount;
}
}
private static final class TemplateBudgetExceeded extends RuntimeException {
private static final TemplateBudgetExceeded INSTANCE =
new TemplateBudgetExceeded();
private TemplateBudgetExceeded() {
super(null, null, false, false);
}
}
}
@@ -1,299 +0,0 @@
package art.arcane.iris.nativegen;
import net.minecraft.core.BlockPos;
import net.minecraft.world.level.WorldGenLevel;
import net.minecraft.world.level.block.state.BlockState;
import net.minecraft.world.level.levelgen.structure.BoundingBox;
import net.minecraft.world.level.levelgen.structure.PoolElementStructurePiece;
import net.minecraft.world.level.levelgen.structure.StructurePiece;
import net.minecraft.world.level.levelgen.structure.StructureStart;
import net.minecraft.world.level.levelgen.structure.pools.StructureTemplatePool;
import net.minecraft.world.level.levelgen.structure.templatesystem.StructureTemplateManager;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.IdentityHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.function.Supplier;
final class NativeStructureSurfaceSupportBuilder {
private static final int MAX_BATCH_CELLS = 524_288;
private static final int MAX_BRIDGE_SPAN = 2;
private NativeStructureSurfaceSupportBuilder() {
}
static Set<Long> bridgeRigidPieceSupport(
WorldGenLevel world, BoundingBox area,
List<NativeStructureTerrainIntegrator.TerrainTarget> targets,
Supplier<StructureTemplateManager> templates) {
if (targets == null || targets.isEmpty()) {
return Set.of();
}
Map<Long, BlockState> planned;
try {
BatchCellBudget budget = new BatchCellBudget();
List<SupportRequest> requests = new ArrayList<>();
Set<StructureStart> seenStarts = Collections.newSetFromMap(
new IdentityHashMap<>());
for (NativeStructureTerrainIntegrator.TerrainTarget target : targets) {
if (target == null
|| !NativeStructureSurfaceFitter.requiresSurfaceTerrain(target)
|| !seenStarts.add(target.start())) {
continue;
}
collectTargetRequests(
world, area, target, templates, budget, requests);
}
planned = planWrites(world, area, requests, budget);
} catch (BatchBudgetExceeded ignored) {
return Set.of();
}
if (planned.isEmpty()) {
return Set.of();
}
List<Map.Entry<Long, BlockState>> ordered = new ArrayList<>(planned.entrySet());
ordered.sort(Map.Entry.comparingByKey());
Set<Long> written = new HashSet<>();
for (Map.Entry<Long, BlockState> entry : ordered) {
BlockPos position = BlockPos.of(entry.getKey());
BlockState existing = world.getBlockState(position);
if (!existing.isSolid()
&& !NativeStructureVegetationClearer.isTreeBlock(existing)
&& existing.getFluidState().isEmpty()
&& world.setBlock(position, entry.getValue(), 2)) {
written.add(entry.getKey());
}
}
return Set.copyOf(written);
}
private static void collectTargetRequests(
WorldGenLevel world, BoundingBox area,
NativeStructureTerrainIntegrator.TerrainTarget target,
Supplier<StructureTemplateManager> templates,
BatchCellBudget budget, List<SupportRequest> requests) {
if (!NativeStructureSurfaceFitter.requiresSurfaceTerrain(target)) {
return;
}
List<RigidAnchor> anchors = rigidAnchors(target.start());
if (anchors.size() < 2) {
return;
}
BlockPos referencePos = referencePosition(target.start());
for (RigidAnchor upper : anchors) {
Map<Long, Integer> lowerMeets = candidateLowerMeets(
area, upper, anchors, budget);
if (lowerMeets.isEmpty()) {
continue;
}
NativeStructureTemplateOccupancy.OccupancyResult occupancy =
NativeStructureTemplateOccupancy.resolve(
world, upper.piece(), referencePos, area, templates,
position -> retain(position, area, lowerMeets), budget::consume);
if (!occupancy.resolved()) {
continue;
}
Map<Long, NativeStructureTemplateOccupancy.LowestCell> lowest =
NativeStructureTemplateOccupancy.lowestCells(occupancy.cells());
for (Map.Entry<Long, NativeStructureTemplateOccupancy.LowestCell> entry
: lowest.entrySet()) {
NativeStructureTemplateOccupancy.LowestCell cell = entry.getValue();
Integer lowerMeet = lowerMeets.get(entry.getKey());
if (lowerMeet == null || cell.occupancy().blocker()
|| !NativeStructureTemplateOccupancy.isSolidBase(
cell.occupancy().state())
|| cell.y() - lowerMeet < 2
|| cell.y() - lowerMeet > MAX_BRIDGE_SPAN) {
continue;
}
budget.consume(1);
requests.add(new SupportRequest(
cell.x(), cell.z(), lowerMeet, cell.y()));
}
}
}
private static List<RigidAnchor> rigidAnchors(StructureStart start) {
List<RigidAnchor> anchors = new ArrayList<>();
for (StructurePiece piece : start.getPieces()) {
if (!(piece instanceof PoolElementStructurePiece poolPiece)
|| poolPiece.getElement().getProjection()
!= StructureTemplatePool.Projection.RIGID) {
continue;
}
BoundingBox bounds = poolPiece.getBoundingBox();
int meetY = bounds.minY() + poolPiece.getGroundLevelDelta() - 1;
anchors.add(new RigidAnchor(poolPiece, bounds, meetY));
}
return List.copyOf(anchors);
}
private static Map<Long, Integer> candidateLowerMeets(
BoundingBox area, RigidAnchor upper, List<RigidAnchor> anchors,
BatchCellBudget budget) {
Map<Long, Integer> lowerMeets = new HashMap<>();
for (RigidAnchor lower : anchors) {
budget.consume(1);
int span = upper.meetY() - lower.meetY();
if (lower.piece() == upper.piece() || span < 1
|| span > MAX_BRIDGE_SPAN
|| lower.meetY() < area.minY() || lower.meetY() > area.maxY()) {
continue;
}
int minimumX = Math.max(area.minX(),
Math.max(upper.bounds().minX(), lower.bounds().minX()));
int maximumX = Math.min(area.maxX(),
Math.min(upper.bounds().maxX(), lower.bounds().maxX()));
int minimumZ = Math.max(area.minZ(),
Math.max(upper.bounds().minZ(), lower.bounds().minZ()));
int maximumZ = Math.min(area.maxZ(),
Math.min(upper.bounds().maxZ(), lower.bounds().maxZ()));
if (minimumX > maximumX || minimumZ > maximumZ) {
continue;
}
for (int x = minimumX; x <= maximumX; x++) {
for (int z = minimumZ; z <= maximumZ; z++) {
budget.consume(1);
lowerMeets.merge(columnKey(x, z), lower.meetY(), Math::max);
}
}
}
return lowerMeets;
}
private static boolean retain(
BlockPos position, BoundingBox area, Map<Long, Integer> lowerMeets) {
if (!area.isInside(position)) {
return false;
}
Integer lowerMeet = lowerMeets.get(columnKey(position.getX(), position.getZ()));
return lowerMeet != null && position.getY() <= lowerMeet + MAX_BRIDGE_SPAN;
}
private static Map<Long, BlockState> planWrites(
WorldGenLevel world, BoundingBox area,
List<SupportRequest> requests, BatchCellBudget budget) {
List<SupportRequest> eligible = new ArrayList<>();
Set<MaterialKey> materialKeys = new HashSet<>();
BlockPos.MutableBlockPos position = new BlockPos.MutableBlockPos();
for (SupportRequest request : requests) {
BlockState lowerTerrain = world.getBlockState(position.set(
request.x(), request.lowerMeetY(), request.z()));
if (!isTerrainSupport(lowerTerrain)
|| !gapIsClear(world, area, position, request, budget)) {
continue;
}
eligible.add(request);
materialKeys.add(new MaterialKey(
request.x(), request.z(), request.lowerMeetY()));
}
Map<MaterialKey, BlockState> materials = new HashMap<>();
for (MaterialKey key : materialKeys) {
materials.put(key, resolveSupportState(
world, position, key.x(), key.z(), key.lowerMeetY(), budget));
}
Map<Long, BlockState> planned = new HashMap<>();
Set<Long> conflicts = new HashSet<>();
eligible.sort(Comparator.comparingInt(SupportRequest::x)
.thenComparingInt(SupportRequest::z)
.thenComparingInt(SupportRequest::lowerMeetY)
.thenComparingInt(SupportRequest::baseY));
for (SupportRequest request : eligible) {
MaterialKey materialKey = new MaterialKey(
request.x(), request.z(), request.lowerMeetY());
BlockState material = materials.get(materialKey);
for (int y = request.lowerMeetY() + 1; y < request.baseY(); y++) {
budget.consume(1);
long positionKey = BlockPos.asLong(request.x(), y, request.z());
if (conflicts.contains(positionKey)) {
continue;
}
BlockState existing = planned.putIfAbsent(positionKey, material);
if (existing != null && !existing.equals(material)) {
planned.remove(positionKey);
conflicts.add(positionKey);
}
}
}
return planned;
}
private static boolean gapIsClear(
WorldGenLevel world, BoundingBox area, BlockPos.MutableBlockPos position,
SupportRequest request, BatchCellBudget budget) {
for (int y = request.lowerMeetY() + 1; y < request.baseY(); y++) {
budget.consume(1);
if (!area.isInside(position.set(request.x(), y, request.z()))) {
return false;
}
BlockState state = world.getBlockState(position);
if (state.isSolid() || NativeStructureVegetationClearer.isTreeBlock(state)
|| !state.getFluidState().isEmpty()) {
return false;
}
}
return true;
}
private static BlockState resolveSupportState(
WorldGenLevel world, BlockPos.MutableBlockPos position,
int x, int z, int lowerMeetY, BatchCellBudget budget) {
budget.consume(1);
BlockState below = world.getBlockState(position.set(x, lowerMeetY - 1, z));
if (isTerrainSupport(below)) {
return below;
}
return world.getBlockState(position.set(x, lowerMeetY, z));
}
private static boolean isTerrainSupport(BlockState state) {
return state.isSolid()
&& !NativeStructureVegetationClearer.isTreeBlock(state)
&& state.getFluidState().isEmpty();
}
private static BlockPos referencePosition(StructureStart start) {
BoundingBox bounds = start.getPieces().getFirst().getBoundingBox();
BlockPos center = bounds.getCenter();
return new BlockPos(center.getX(), bounds.minY(), center.getZ());
}
private static long columnKey(int x, int z) {
return (long) x << 32 ^ z & 0xffffffffL;
}
private record RigidAnchor(
PoolElementStructurePiece piece, BoundingBox bounds, int meetY) {
}
private record SupportRequest(int x, int z, int lowerMeetY, int baseY) {
}
private record MaterialKey(int x, int z, int lowerMeetY) {
}
private static final class BatchCellBudget {
private int consumed;
private void consume(int amount) {
if (amount < 0 || consumed > MAX_BATCH_CELLS - amount) {
throw BatchBudgetExceeded.INSTANCE;
}
consumed += amount;
}
}
private static final class BatchBudgetExceeded extends RuntimeException {
private static final BatchBudgetExceeded INSTANCE = new BatchBudgetExceeded();
private BatchBudgetExceeded() {
super(null, null, false, false);
}
}
}
@@ -1,5 +1,6 @@
package art.arcane.iris.nativegen;
import art.arcane.iris.engine.framework.nativefit.NativeTemplateCells;
import net.minecraft.core.BlockPos;
import net.minecraft.world.level.WorldGenLevel;
import net.minecraft.world.level.block.Blocks;
@@ -74,44 +75,34 @@ final class NativeStructureTemplateOccupancy {
return new OccupancyResult(true, occupancy);
}
static Map<Long, LowestCell> lowestCells(Map<Long, OccupancyCell> occupancy) {
Map<Long, LowestCell> lowest = new HashMap<>();
for (Map.Entry<Long, OccupancyCell> entry : occupancy.entrySet()) {
OccupancyCell cell = entry.getValue();
BlockPos position = BlockPos.of(entry.getKey());
long column = columnKey(position.getX(), position.getZ());
LowestCell current = lowest.get(column);
if (current == null || position.getY() < current.y()) {
lowest.put(column, new LowestCell(
position.getX(), position.getY(), position.getZ(), cell));
}
/**
* The piece's processed template blocks inside {@code region}, processed against the world as it is now, as the
* modules' fit reads them: removed blocks have no state, and the count of template blocks read is reported.
*/
static NativeTemplateCells<BlockState> cells(
WorldGenLevel world, PoolElementStructurePiece piece, BlockPos referencePosition, BoundingBox region,
Supplier<StructureTemplateManager> templates) {
int[] readBlocks = {0};
OccupancyResult occupancy = resolve(world, piece, referencePosition, region, templates, region::isInside,
amount -> readBlocks[0] = Math.addExact(readBlocks[0], amount));
if (!occupancy.resolved()) {
return new NativeTemplateCells<>(false, new int[0], new int[0], new int[0], new BlockState[0], 0);
}
return lowest;
}
static Map<Long, LowestCell> lowestProcessedSolidCells(Map<Long, OccupancyCell> occupancy) {
Map<Long, LowestCell> lowest = new HashMap<>();
for (Map.Entry<Long, OccupancyCell> entry : occupancy.entrySet()) {
OccupancyCell cell = entry.getValue();
if (cell.blocker() || !isSolidBase(cell.state())) {
continue;
}
int size = occupancy.cells().size();
int[] xs = new int[size];
int[] ys = new int[size];
int[] zs = new int[size];
BlockState[] states = new BlockState[size];
int cell = 0;
for (Map.Entry<Long, OccupancyCell> entry : occupancy.cells().entrySet()) {
BlockPos position = BlockPos.of(entry.getKey());
long column = columnKey(position.getX(), position.getZ());
LowestCell current = lowest.get(column);
if (current == null || position.getY() < current.y()) {
lowest.put(column, new LowestCell(
position.getX(), position.getY(), position.getZ(), cell));
}
xs[cell] = position.getX();
ys[cell] = position.getY();
zs[cell] = position.getZ();
states[cell] = entry.getValue().state();
cell++;
}
return lowest;
}
static boolean isSolidBase(BlockState state) {
return state != null && state.isSolid()
&& !state.is(Blocks.STRUCTURE_VOID)
&& !state.is(Blocks.JIGSAW)
&& state.getFluidState().isEmpty();
return new NativeTemplateCells<>(true, xs, ys, zs, states, readBlocks[0]);
}
static long columnKey(int x, int z) {
@@ -154,9 +145,6 @@ final class NativeStructureTemplateOccupancy {
record OccupancyCell(BlockState state, boolean blocker) {
}
record LowestCell(int x, int y, int z, OccupancyCell occupancy) {
}
private record LeafPlacement(
StructurePlaceSettings settings,
List<StructureTemplate.StructureBlockInfo> rawBlocks,
@@ -1,10 +1,8 @@
package art.arcane.iris.nativegen;
import art.arcane.iris.engine.framework.NativeStartPlacement;
import art.arcane.iris.engine.framework.StructureVerticalBounds;
import art.arcane.iris.engine.object.structure.IrisStructureYBand;
import art.arcane.iris.spi.IrisLogging;
import art.arcane.volmlib.util.math.RNG;
import net.minecraft.world.level.ChunkPos;
import net.minecraft.world.level.LevelHeightAccessor;
import net.minecraft.world.level.levelgen.structure.BoundingBox;
import net.minecraft.world.level.levelgen.structure.PoolElementStructurePiece;
@@ -25,33 +23,47 @@ import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.function.IntBinaryOperator;
import java.util.function.IntSupplier;
public final class NativeStructureVerticalPlacer {
private static final String DESERT_PYRAMID_ID = "minecraft:desert_pyramid";
private static final String JUNGLE_PYRAMID_ID = "minecraft:jungle_pyramid";
private static final int MAX_BURIAL_COLUMNS = 2_000_000;
private static final int MONUMENT_BASE_BELOW_SEA_LEVEL = 24;
private static final String OCEAN_MONUMENT_ID = "minecraft:monument";
private static final int UNDERGROUND_SURFACE_CLEARANCE = 1;
private NativeStructureVerticalPlacer() {
}
public static int applyVerticalPlacement(StructureStart start, String structureId, int requestedOffset,
/**
* Moves the platform's start {@code shift} blocks up (negative: down), as the modules asked, inside the world: an
* ocean monument and a desert or jungle temple are aligned first (to the sea level, to the terrain) and shifted from
* there. Returns how far the start moved.
*/
public static int applyVerticalPlacement(StructureStart start, String structureId, int shift,
int seaLevel, int worldMinY, int worldMaxYExclusive,
boolean underground, boolean preserveSourceY,
IrisStructureYBand yBand,
IntBinaryOperator surfaceHeight) {
if (isOceanMonument(start, structureId)) {
return alignOceanMonumentToSeaLevel(
start, requestedOffset, seaLevel, worldMinY, worldMaxYExclusive);
start, shift, seaLevel, worldMinY, worldMaxYExclusive);
}
if (isAdjustedScatteredStructure(start, structureId)) {
return alignScatteredStructureToSurface(
start, structureId, requestedOffset, worldMinY, worldMaxYExclusive, surfaceHeight);
start, structureId, shift, worldMinY, worldMaxYExclusive, surfaceHeight);
}
return applyVerticalShift(start, requestedOffset, worldMinY, worldMaxYExclusive,
underground, preserveSourceY, yBand, surfaceHeight);
return applyVerticalShift(start, structureId, shift, worldMinY, worldMaxYExclusive);
}
/**
* The platform start as the modules see it before it is published: its bounds, whether the platform generates it
* underground and whether the host aligns it itself.
*/
public static NativeStartPlacement placementOf(StructureStart start, String structureId, boolean underground,
int bottomY, IntBinaryOperator surfaceHeight) {
BoundingBox bounds = start.getBoundingBox();
return new NativeStartPlacement(structureId, start.getChunkPos().x(), start.getChunkPos().z(),
bounds.minX(), bounds.minY(), bounds.minZ(), bounds.maxX(), bounds.maxY(), bounds.maxZ(),
underground, isOceanMonument(start, structureId) || isAdjustedScatteredStructure(start, structureId),
bottomY, surfaceHeight);
}
public static StructureStart relocateToMinY(StructureStart start, Structure source, int targetMinY,
@@ -115,15 +127,16 @@ public final class NativeStructureVerticalPlacer {
return offsetY;
}
public static int applyVerticalShift(StructureStart start, int requestedOffset, int worldMinY,
int worldMaxYExclusive, boolean underground,
boolean preserveSourceY, IrisStructureYBand yBand,
IntBinaryOperator surfaceHeight) {
/** Moves the start {@code shift} blocks, less where it would leave the world. Returns how far it moved. */
public static int applyVerticalShift(StructureStart start, String structureId, int shift, int worldMinY,
int worldMaxYExclusive) {
BoundingBox bounds = start.getBoundingBox();
int resolvedOffset = resolveShiftOffset(start, bounds, requestedOffset, worldMinY,
worldMaxYExclusive, underground, preserveSourceY, yBand, surfaceHeight);
int offsetY = StructureVerticalBounds.clampOffset(
bounds.minY(), bounds.maxY(), resolvedOffset, worldMinY, worldMaxYExclusive);
bounds.minY(), bounds.maxY(), shift, worldMinY, worldMaxYExclusive);
if (offsetY != shift) {
IrisLogging.warn("Native structure " + structureId + " at " + bounds.minX() + "," + bounds.minZ()
+ " clamped to the world's height: wanted a shift of " + shift + ", used " + offsetY);
}
if (offsetY == 0) {
return 0;
}
@@ -131,23 +144,6 @@ public final class NativeStructureVerticalPlacer {
return offsetY;
}
private static int resolveShiftOffset(StructureStart start, BoundingBox bounds, int requestedOffset,
int worldMinY, int worldMaxYExclusive, boolean underground,
boolean preserveSourceY, IrisStructureYBand yBand,
IntBinaryOperator surfaceHeight) {
if (preserveSourceY) {
return requestedOffset;
}
if (yBand != null) {
return resolveYBandOffset(bounds, yBand, start.getChunkPos());
}
if (underground) {
return resolveBuriedOffset(
bounds, requestedOffset, worldMinY, worldMaxYExclusive, surfaceHeight);
}
return requestedOffset;
}
static int alignOceanMonumentToSeaLevel(StructureStart start, int configuredOffset, int seaLevel,
int worldMinY, int worldMaxYExclusive) {
OceanMonumentPieces.MonumentBuilding building = requireOceanMonumentBuilding(start);
@@ -169,15 +165,16 @@ public final class NativeStructureVerticalPlacer {
return offsetY;
}
static void ensureMonumentSeaLevelAlignment(StructureStart start, String structureId,
int configuredOffset, int seaLevel,
int worldMinY, int worldMaxYExclusive) {
/** Keeps an ocean monument at the sea level, shifted by {@code shift}, before each chunk places its pieces. */
public static void ensureMonumentSeaLevelAlignment(StructureStart start, String structureId,
IntSupplier shift, int seaLevel,
int worldMinY, int worldMaxYExclusive) {
if (!isOceanMonument(start, structureId)) {
return;
}
synchronized (start) {
alignOceanMonumentToSeaLevel(
start, configuredOffset, seaLevel, worldMinY, worldMaxYExclusive);
start, shift.getAsInt(), seaLevel, worldMinY, worldMaxYExclusive);
}
}
@@ -327,58 +324,4 @@ public final class NativeStructureVerticalPlacer {
}
return List.copyOf(pieces);
}
static int resolveYBandOffset(BoundingBox bounds, IrisStructureYBand yBand, ChunkPos startChunk) {
Objects.requireNonNull(bounds, "Native structure bounds must not be null");
Objects.requireNonNull(startChunk, "Native structure Y band requires a start chunk");
int target = yBandTargetMidpointY(
bounds.minY(), bounds.maxY(), yBand.resolvedMin(), yBand.resolvedMax(), startChunk);
return Math.subtractExact(target, midpointY(bounds.minY(), bounds.maxY()));
}
static int yBandTargetMidpointY(int minY, int maxY, int bandMin, int bandMax, ChunkPos startChunk) {
int height = Math.subtractExact(maxY, minY);
int lowest = Math.addExact(bandMin, height / 2);
int highest = Math.subtractExact(bandMax, height - height / 2);
if (lowest > highest) {
// The band is shorter than the structure, so only its midpoint can be honoured.
return Math.floorDiv(Math.addExact(bandMin, bandMax), 2);
}
int span = highest - lowest + 1;
if (span == 1) {
return lowest;
}
long identity = (long) startChunk.x() * 341873128712L ^ (long) startChunk.z() * 132897987541L;
return lowest + new RNG(identity).nextInt(span);
}
private static int midpointY(int minY, int maxY) {
return minY + (maxY - minY) / 2;
}
static int resolveBuriedOffset(BoundingBox bounds, int requestedOffset, int worldMinY,
int worldMaxYExclusive, IntBinaryOperator surfaceHeight) {
Objects.requireNonNull(bounds, "Native structure bounds must not be null");
Objects.requireNonNull(surfaceHeight, "Underground native structure requires a terrain height resolver");
long width = (long) bounds.maxX() - bounds.minX() + 1L;
long depth = (long) bounds.maxZ() - bounds.minZ() + 1L;
if (width <= 0L || depth <= 0L || width > MAX_BURIAL_COLUMNS / depth) {
throw new IllegalStateException("Underground native structure burial footprint is invalid or exceeds "
+ MAX_BURIAL_COLUMNS + " columns");
}
int maximumOffset = requestedOffset;
for (int x = bounds.minX(); x <= bounds.maxX(); x++) {
for (int z = bounds.minZ(); z <= bounds.maxZ(); z++) {
int allowedTopY = surfaceHeight.applyAsInt(x, z) - UNDERGROUND_SURFACE_CLEARANCE;
maximumOffset = Math.min(maximumOffset, allowedTopY - bounds.maxY());
}
}
int clampedOffset = StructureVerticalBounds.clampOffset(
bounds.minY(), bounds.maxY(), maximumOffset, worldMinY, worldMaxYExclusive);
if (clampedOffset > maximumOffset) {
IrisLogging.warn("Native structure burial at " + bounds.minX() + "," + bounds.minZ()
+ " clamped to world floor: wanted " + maximumOffset + ", used " + clampedOffset);
}
return clampedOffset;
}
}
@@ -2,11 +2,11 @@ package art.arcane.iris.nativegen;
import art.arcane.iris.engine.framework.Engine;
import art.arcane.iris.engine.framework.NativeStructureGenerationPolicy;
import art.arcane.iris.engine.framework.NativeStructureLayouts;
import art.arcane.iris.engine.framework.NativeStructureOwnershipRecord;
import art.arcane.iris.engine.framework.NativeStructureStarts;
import art.arcane.iris.engine.framework.NativeStructureStartPlan;
import art.arcane.iris.engine.framework.NativeStructureVolume;
import art.arcane.iris.engine.object.structure.vanilla.IrisNativeStructureDecision;
import art.arcane.iris.spi.IrisLogging;
import art.arcane.volmlib.util.collection.KList;
import net.minecraft.core.Holder;
@@ -182,10 +182,6 @@ public final class NativeStructureVolumeIndex {
KList<NativeStructureVolume> target = volumes;
for (NativeStructureStartPlan plan : plans) {
IrisNativeStructureDecision decision = plan.decision();
if (!decision.generate()) {
continue;
}
Identifier identifier = Identifier.tryParse(plan.structureKey());
if (identifier == null) {
continue;
@@ -197,7 +193,9 @@ public final class NativeStructureVolumeIndex {
String structureId = identifier.toString();
try {
StructureStart generated = NativeStructureFactory.generate(
generationContext(engine, bindings), registry.wrapAsHolder(structure), plan, 0);
generationContext(engine, bindings), registry.wrapAsHolder(structure), plan, 0,
NativeStructureLayouts.reaches(engine, structureId,
NativeStructureVegetationClearer.isUndergroundStep(structure.step()), plan.memo()));
target = appendPieces(target, structureId, generated);
} catch (RuntimeException | Error error) {
warnOnce(structureId, error);
@@ -229,9 +227,7 @@ public final class NativeStructureVolumeIndex {
String structureId = identifier.toString();
boolean undergroundStep = NativeStructureVegetationClearer.isUndergroundStep(structure.step());
try {
IrisNativeStructureDecision decision = NativeStructureGenerationPolicy.resolve(
engine, structureId, undergroundStep);
if (!decision.generate()) {
if (!NativeStructureGenerationPolicy.generates(engine, structureId)) {
continue;
}
StructureStart generated = structure.generate(
@@ -254,13 +250,11 @@ public final class NativeStructureVolumeIndex {
NativeStructureVerticalPlacer.applyVerticalPlacement(
generated,
structureId,
decision.yShift(),
NativeStructureLayouts.shift(engine, NativeStructureVerticalPlacer.placementOf(
generated, structureId, undergroundStep, worldMinY, surfaceHeight)),
bindings.generator().getSeaLevel(),
worldMinY,
worldMaxYExclusive,
undergroundStep,
decision.preserveSourceY(),
decision.yBand(),
surfaceHeight);
target = appendPieces(target, structureId, generated);
} catch (RuntimeException | Error error) {
@@ -974,7 +974,7 @@ public final class IrisModdedChunkGenerator extends ChunkGenerator {
}
}
Integer worldCheckStructureShift(String structureId, ChunkPos startChunk) {
ModdedNativeStructureStage.WorldCheckShift worldCheckStructureShift(String structureId, ChunkPos startChunk) {
return nativeStructures.worldCheckStructureShift(structureId, startChunk);
}
@@ -21,25 +21,21 @@ package art.arcane.iris.modded;
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.NativeStructureLayouts;
import art.arcane.iris.engine.framework.nativefit.NativeStructureFitting;
import art.arcane.iris.engine.framework.NativeStructureOwnershipRecord;
import art.arcane.iris.engine.framework.NativeStructureStartPlan;
import art.arcane.iris.engine.object.material.IrisMaterialPalette;
import art.arcane.iris.engine.object.structure.vanilla.IrisNativeStructureDecision;
import art.arcane.iris.nativegen.NativeStructureGenerationException;
import art.arcane.iris.nativegen.NativeStructureLocatePersistence;
import art.arcane.iris.nativegen.NativeStructureLocateResults;
import art.arcane.iris.nativegen.NativeStructureOwnershipRecovery;
import art.arcane.iris.nativegen.NativeStructurePostProcessor;
import art.arcane.iris.nativegen.NativeStructureFitBridge;
import art.arcane.iris.nativegen.NativeStructureReferenceEnvelope;
import art.arcane.iris.nativegen.NativeStructureSurfaceFitter;
import art.arcane.iris.nativegen.NativeStructureTerrainIntegrator;
import art.arcane.iris.nativegen.NativeStructureVegetationClearer;
import art.arcane.iris.nativegen.NativeStructureVerticalPlacer;
import art.arcane.iris.nativegen.NativeStructureVanillaLocator;
import art.arcane.iris.nativegen.NativeStructureVolumeIndex;
import art.arcane.iris.nativegen.WorldgenTerrainHeightmaps;
import art.arcane.iris.spi.PlatformBlockState;
import art.arcane.volmlib.util.math.RNG;
import com.mojang.datafixers.util.Pair;
import net.minecraft.core.BlockPos;
import net.minecraft.core.Holder;
@@ -88,7 +84,7 @@ final class ModdedNativeStructureStage {
private static final boolean WORLD_CHECK_ENABLED = Boolean.getBoolean("iris.worldcheck");
private final IrisModdedChunkGenerator generator;
private final ConcurrentHashMap<NativeStructureStartKey, Integer> worldCheckStructureShifts = new ConcurrentHashMap<>();
private final ConcurrentHashMap<NativeStructureStartKey, WorldCheckShift> worldCheckStructureShifts = new ConcurrentHashMap<>();
private volatile StructureStepCache structureStepCache;
ModdedNativeStructureStage(IrisModdedChunkGenerator generator) {
@@ -206,9 +202,8 @@ final class ModdedNativeStructureStage {
throw new IllegalStateException("Native structure filtering received an unregistered structure holder");
}
String key = id.toString();
IrisNativeStructureDecision decision = NativeStructureGenerationPolicy.resolve(current,
key, NativeStructureVegetationClearer.isUndergroundStep(holder.value().step()));
if (!decision.generate() || !generator.structureBiomeSource.isStructureReachable(holder)) {
if (!NativeStructureGenerationPolicy.generates(current, key)
|| !generator.structureBiomeSource.isStructureReachable(holder)) {
continue;
}
kept.add(holder);
@@ -231,7 +226,7 @@ final class ModdedNativeStructureStage {
}
if (configuredStarts.containsKey(structure)) {
recordWorldCheckStructureShift(
configuredStarts.get(structure).structureKey(), start.getChunkPos(), 0);
configuredStarts.get(structure).structureKey(), start.getChunkPos(), 0, 0);
continue;
}
Identifier id = registry.getKey(structure);
@@ -241,34 +236,34 @@ final class ModdedNativeStructureStage {
"resolution", null, chunkPos.x(), chunkPos.z());
}
boolean undergroundStep = NativeStructureVegetationClearer.isUndergroundStep(structure.step());
IrisNativeStructureDecision decision;
boolean generates;
try {
decision = NativeStructureGenerationPolicy.resolve(current,
structureId, undergroundStep);
generates = NativeStructureGenerationPolicy.generates(current, structureId);
} catch (Throwable error) {
throw NativeStructureGenerationException.failure(
"policy resolution", structureId, chunkPos.x(), chunkPos.z(), error);
}
if (!decision.generate()) {
if (!generates) {
chunk.setStartForStructure(structure, StructureStart.INVALID_START);
continue;
}
int shift;
int offsetY;
try {
IntBinaryOperator surface = (x, z) -> current.getHeight(x, z, true) + current.getMinHeight();
shift = NativeStructureLayouts.shift(current, NativeStructureVerticalPlacer.placementOf(
start, structureId, undergroundStep, chunk.getMinY(), surface));
offsetY = NativeStructureVerticalPlacer.applyVerticalPlacement(
start,
structureId,
decision.yShift(),
shift,
generator.getSeaLevel(),
chunk.getMinY(),
chunk.getMinY() + chunk.getHeight(),
undergroundStep,
decision.preserveSourceY(),
decision.yBand(),
(x, z) -> current.getHeight(x, z, true) + current.getMinHeight());
surface);
StructureStart wrapped = NativeStructureReferenceEnvelope.wrapForPublication(
start, structure, start.getReferences(),
NativeStructureTerrainIntegrator.resolveNativeTerrain(start, decision.terrain()),
NativeStructureLayouts.reaches(current, structureId, undergroundStep, null),
structureId);
chunk.setStartForStructure(structure, wrapped);
if (!wrapped.isValid()) {
@@ -278,7 +273,7 @@ final class ModdedNativeStructureStage {
throw NativeStructureGenerationException.failure(
"vertical adjustment", structureId, chunkPos.x(), chunkPos.z(), error);
}
recordWorldCheckStructureShift(structureId, start.getChunkPos(), offsetY);
recordWorldCheckStructureShift(structureId, start.getChunkPos(), shift, offsetY);
}
}
@@ -306,7 +301,7 @@ final class ModdedNativeStructureStage {
List<NativePlacementGroup> placementGroups = new ArrayList<>();
List<StructureStart> heightmapStarts = new ArrayList<>();
List<StructureStart> vegetationTargets = new ArrayList<>();
List<NativeStructureTerrainIntegrator.TerrainTarget> terrainTargets = new ArrayList<>();
List<NativeStructureFitBridge.FitTarget> fitTargets = new ArrayList<>();
for (int step = 0; step < steps; step++) {
int index = 0;
for (Structure structure : byStep.get(step)) {
@@ -317,25 +312,20 @@ final class ModdedNativeStructureStage {
"resolution", null, chunkPos.x(), chunkPos.z());
}
try {
IrisNativeStructureDecision sourceDecision = NativeStructureGenerationPolicy.resolve(current,
structureId, NativeStructureVegetationClearer.isUndergroundStep(structure.step()));
boolean platformGenerates = NativeStructureGenerationPolicy.generates(current, structureId);
List<StructureStart> starts = structureManager.startsForStructure(sectionPos, structure);
List<NativePlacement> resolvedPlacements = new ArrayList<>(starts.size());
for (StructureStart start : starts) {
NativeStructureOwnershipRecord ownership =
NativeStructureOwnershipRecovery.resolve(
current, world.getLevel(), structureId, structure, start);
IrisNativeStructureDecision decision =
ownership == null ? sourceDecision : ownership.restoredDecision();
if (!decision.generate()) {
if (ownership == null && !platformGenerates) {
continue;
}
resolvedPlacements.add(new NativePlacement(start, decision));
resolvedPlacements.add(new NativePlacement(start, ownership != null));
heightmapStarts.add(start);
terrainTargets.add(new NativeStructureTerrainIntegrator.TerrainTarget(
structureId, start,
NativeStructureTerrainIntegrator.resolveNativeTerrain(
start, decision.terrain())));
fitTargets.add(new NativeStructureFitBridge.FitTarget(structureId, start,
ownership == null ? null : ownership.restoredMemo()));
vegetationTargets.add(start);
}
if (!resolvedPlacements.isEmpty()) {
@@ -373,44 +363,29 @@ final class ModdedNativeStructureStage {
"vegetation cleanup", nativeStructureBatchContext(placementGroups),
chunkPos.x(), chunkPos.z(), error);
}
NativeStructureSurfaceFitter.VacuumFoundationPlan vacuumFoundationPlan;
NativeStructureFitting.Session fit;
try {
vacuumFoundationPlan = NativeStructureSurfaceFitter.prepareSurfaceStructures(
world, area, terrainTargets,
(x, z) -> current.getHeight(x, z, true) + current.getMinHeight());
fit = NativeStructureFitting.of(current).beforePieces(NativeStructureFitBridge.chunk(
world, area, fitTargets, (x, z) -> current.getHeight(x, z, true) + current.getMinHeight()));
} catch (Throwable error) {
throw NativeStructureGenerationException.failure(
"terrain integration", nativeStructureBatchContext(placementGroups),
chunkPos.x(), chunkPos.z(), error);
}
try {
NativeStructurePostProcessor.prepareTerrain(
world, area, terrainTargets, this::resolvePaletteBlock);
} catch (Throwable error) {
throw NativeStructureGenerationException.failure(
"terrain preparation", nativeStructureBatchContext(placementGroups),
"terrain fitting", nativeStructureBatchContext(placementGroups),
chunkPos.x(), chunkPos.z(), error);
}
int placed = 0;
for (NativePlacementGroup group : placementGroups) {
random.setFeatureSeed(decorationSeed, group.featureIndex(), group.step());
try {
for (NativePlacement placement : group.placements()) {
placeVanillaStructure(world, structureManager, random, area, chunkPos,
group.structureId(), placement.start(), placement.decision());
group.structureId(), placement);
fit.afterPieces(placed++);
}
} catch (Throwable error) {
throw NativeStructureGenerationException.failure(
"placement", group.structureId(), chunkPos.x(), chunkPos.z(), error);
}
}
try {
NativeStructureSurfaceFitter.repairVacuumFoundations(
world, area, vacuumFoundationPlan);
} catch (Throwable error) {
throw NativeStructureGenerationException.failure(
"foundation repair", nativeStructureBatchContext(placementGroups),
chunkPos.x(), chunkPos.z(), error);
}
}
static void visitExistingPois(ChunkAccess chunk, BiConsumer<BlockPos, BlockState> visitor) {
@@ -433,8 +408,7 @@ final class ModdedNativeStructureStage {
private void placeVanillaStructure(WorldGenLevel world, StructureManager structureManager,
WorldgenRandom random, BoundingBox area, ChunkPos chunkPos,
String structureId, StructureStart start,
IrisNativeStructureDecision decision) {
String structureId, NativePlacement placement) {
Engine current = generator.engine();
int runtimeMinY = world.getMinY();
WorldGenLevel boundedWorld = ModdedNativeStructureWorldgenAccess.create(
@@ -443,15 +417,23 @@ final class ModdedNativeStructureStage {
worldgenFloorHeight(current, runtimeMinY));
world.setCurrentlyGenerating(() -> "Iris native structure " + structureId);
try {
NativeStructurePostProcessor.place(
boundedWorld, structureManager, generator, random, area, chunkPos,
structureId, start, decision, this::resolvePaletteBlock,
(x, z) -> current.getHeight(x, z, true) + current.getMinHeight());
StructureStart start = placement.start();
NativeStructureVerticalPlacer.ensureMonumentSeaLevelAlignment(start, structureId,
() -> placement.recorded() ? 0 : platformShift(current, start, structureId, runtimeMinY),
generator.getSeaLevel(), area.minY(), area.maxY() + 1);
start.placeInChunk(boundedWorld, structureManager, generator, random, area, chunkPos);
} finally {
world.setCurrentlyGenerating(null);
}
}
/** The shift the pack's modules give the platform's own start, as when the start was published. */
private static int platformShift(Engine current, StructureStart start, String structureId, int bottomY) {
return NativeStructureLayouts.shift(current, NativeStructureVerticalPlacer.placementOf(start, structureId,
NativeStructureVegetationClearer.isUndergroundStep(start.getStructure().step()), bottomY,
(x, z) -> current.getHeight(x, z, true) + current.getMinHeight()));
}
private List<List<Structure>> structuresByStep(Registry<Structure> registry) {
StructureStepCache cached = structureStepCache;
if (cached != null && cached.registry() == registry) {
@@ -479,17 +461,19 @@ final class ModdedNativeStructureStage {
}
}
private void recordWorldCheckStructureShift(String structureId, ChunkPos startChunk, int offsetY) {
private void recordWorldCheckStructureShift(String structureId, ChunkPos startChunk, int requestedShift,
int appliedShift) {
if (!WORLD_CHECK_ENABLED || structureId == null) {
return;
}
if (worldCheckStructureShifts.size() >= WORLD_CHECK_SHIFT_RECORD_LIMIT) {
worldCheckStructureShifts.clear();
}
worldCheckStructureShifts.put(new NativeStructureStartKey(structureId, startChunk.pack()), offsetY);
worldCheckStructureShifts.put(new NativeStructureStartKey(structureId, startChunk.pack()),
new WorldCheckShift(requestedShift, appliedShift));
}
Integer worldCheckStructureShift(String structureId, ChunkPos startChunk) {
WorldCheckShift worldCheckStructureShift(String structureId, ChunkPos startChunk) {
if (structureId == null || startChunk == null) {
return null;
}
@@ -500,16 +484,6 @@ final class ModdedNativeStructureStage {
worldCheckStructureShifts.clear();
}
private BlockState resolvePaletteBlock(IrisMaterialPalette palette, RNG rng,
int x, int y, int z) {
PlatformBlockState platformState = palette.get(rng, x, y, z, generator.engine().getData());
if (platformState == null || !(platformState.nativeHandle() instanceof BlockState blockState)) {
throw new IllegalStateException("Configured native structure palette did not resolve a Minecraft block at "
+ x + "," + y + "," + z);
}
return blockState;
}
private BoundingBox writableArea(ChunkAccess chunk) {
ChunkPos chunkPos = chunk.getPos();
int minX = chunkPos.getMinBlockX();
@@ -530,7 +504,12 @@ final class ModdedNativeStructureStage {
private record NativeStructureStartKey(String structureId, long chunkPosition) {
}
private record NativePlacement(StructureStart start, IrisNativeStructureDecision decision) {
/** A start placed in the chunk, and whether a module placed it (its ownership record kept its fit). */
private record NativePlacement(StructureStart start, boolean recorded) {
}
/** The shift the pack's modules asked for a platform start, and the shift generation applied. */
record WorldCheckShift(int requested, int applied) {
}
private record NativePlacementGroup(String structureId, int featureIndex, int step,
@@ -0,0 +1,121 @@
/*
* 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.modded;
import art.arcane.iris.nativegen.NativeStructureReferenceEnvelope;
import net.minecraft.core.BlockPos;
import net.minecraft.tags.BlockTags;
import net.minecraft.world.level.WorldGenLevel;
import net.minecraft.world.level.block.state.BlockState;
import net.minecraft.world.level.levelgen.structure.BoundingBox;
import net.minecraft.world.level.levelgen.structure.PoolElementStructurePiece;
import net.minecraft.world.level.levelgen.structure.StructurePiece;
import net.minecraft.world.level.levelgen.structure.StructureStart;
import java.util.function.IntBinaryOperator;
/**
* The world check's reading of a placed structure's stilts: per column of the structure's foundation (each piece's
* ground level and the block above it), whether the lowest solid foundation block stands on terrain, on stilts of the
* expected block reaching terrain, or on nothing. It reads the generated world, independently of the fit that built
* the stilts.
*/
final class WorldCheckStiltAudit {
private static final int FOUNDATION_VERTICAL_TOLERANCE = 1;
private WorldCheckStiltAudit() {
}
static Result audit(WorldGenLevel world, BoundingBox area, StructureStart start, BlockState expectedStilt,
IntBinaryOperator surfaceHeight) {
BoundingBox structure = NativeStructureReferenceEnvelope.contentBounds(start);
int minX = Math.max(area.minX(), structure.minX());
int minZ = Math.max(area.minZ(), structure.minZ());
int maxX = Math.min(area.maxX(), structure.maxX());
int maxZ = Math.min(area.maxZ(), structure.maxZ());
Result result = Result.NONE;
for (int z = minZ; z <= maxZ; z++) {
for (int x = minX; x <= maxX; x++) {
int foundationY = foundationY(world, area, start, x, z);
if (foundationY != Integer.MIN_VALUE) {
int terrainY = Math.max(area.minY(), Math.min(area.maxY(), surfaceHeight.applyAsInt(x, z)));
result = result.plus(column(world, area, x, z, foundationY, terrainY, expectedStilt));
}
}
}
return result;
}
private static Result column(WorldGenLevel world, BoundingBox area, int x, int z, int foundationY, int terrainY,
BlockState expectedStilt) {
BlockPos.MutableBlockPos position = new BlockPos.MutableBlockPos();
boolean grounded = foundationY <= terrainY + 1;
int stiltBlocks = 0;
for (int y = foundationY - 1; y >= area.minY(); y--) {
if (y <= terrainY) {
grounded = true;
break;
}
BlockState state = world.getBlockState(position.set(x, y, z));
if (state.is(expectedStilt.getBlock())) {
stiltBlocks++;
grounded |= y == area.minY();
continue;
}
grounded = state.isSolid() && !state.is(BlockTags.LOGS) && !state.is(BlockTags.LEAVES);
break;
}
return new Result(1, stiltBlocks, stiltBlocks > 0 ? 1 : 0, grounded ? 0 : 1);
}
/** The lowest solid block of the column inside a piece's ground level band; MIN_VALUE when there is none. */
private static int foundationY(WorldGenLevel world, BoundingBox area, StructureStart start, int x, int z) {
BlockPos.MutableBlockPos position = new BlockPos.MutableBlockPos();
int lowest = Integer.MIN_VALUE;
for (StructurePiece piece : start.getPieces()) {
BoundingBox bounds = piece.getBoundingBox();
if (x < bounds.minX() || x > bounds.maxX() || z < bounds.minZ() || z > bounds.maxZ()) {
continue;
}
int groundY = bounds.minY() + (piece instanceof PoolElementStructurePiece poolPiece
? poolPiece.getGroundLevelDelta() : 0);
int minY = Math.max(area.minY(), bounds.minY());
int maxY = Math.min(area.maxY(), Math.min(bounds.maxY(), groundY + FOUNDATION_VERTICAL_TOLERANCE));
if (groundY < bounds.minY()) {
continue;
}
for (int y = minY; y <= maxY && (lowest == Integer.MIN_VALUE || y < lowest); y++) {
if (world.getBlockState(position.set(x, y, z)).isSolid()) {
lowest = y;
break;
}
}
}
return lowest;
}
record Result(int baseColumns, int stiltBlocks, int stiltColumns, int unsupportedColumns) {
static final Result NONE = new Result(0, 0, 0, 0);
Result plus(Result other) {
return new Result(baseColumns + other.baseColumns, stiltBlocks + other.stiltBlocks,
stiltColumns + other.stiltColumns, unsupportedColumns + other.unsupportedColumns);
}
}
}
@@ -18,10 +18,8 @@
package art.arcane.iris.modded;
import art.arcane.iris.engine.framework.Engine;
import art.arcane.iris.engine.framework.NativeStructureGenerationPolicy;
import art.arcane.iris.engine.object.structure.vanilla.IrisNativeStructureDecision;
import art.arcane.iris.nativegen.NativeStructureFoundationBuilder;
import art.arcane.iris.nativegen.NativeStructureVegetationClearer;
import com.mojang.datafixers.util.Pair;
import net.minecraft.core.BlockPos;
@@ -206,20 +204,20 @@ final class WorldCheckStructureAudit {
return new StructureCheckResult(false, null);
}
IrisNativeStructureDecision decision = NativeStructureGenerationPolicy.resolve(
generator.commandEngine(), foundKey.toString(),
NativeStructureVegetationClearer.isUndergroundStep(structure.step()));
Integer appliedShift = generator.worldCheckStructureShift(foundKey.toString(), start.getChunkPos());
ModdedNativeStructureStage.WorldCheckShift recorded =
generator.worldCheckStructureShift(foundKey.toString(), start.getChunkPos());
int requestedShift = recorded == null ? 0 : recorded.requested();
Integer appliedShift = recorded == null ? null : recorded.applied();
BoundingBox shiftedBounds = start.getBoundingBox();
boolean verticalShiftOk = WorldCheckPredicates.verticalShiftMatches(
decision.yShift(), appliedShift, shiftedBounds.minY(), shiftedBounds.maxY(),
requestedShift, appliedShift, shiftedBounds.minY(), shiftedBounds.maxY(),
level.getMinY(), level.getMaxY());
WorldCheckPredicates.qaEvent("structure_vertical_shift", check.label(), verticalShiftOk,
"configured=" + decision.yShift() + ",applied="
"requested=" + requestedShift + ",applied="
+ (appliedShift == null ? "unrecorded" : appliedShift));
if (!verticalShiftOk) {
ModdedIrisLog.error("[worldcheck] {} expected vertical shift {} but generation recorded {}",
check.label(), decision.yShift(), appliedShift);
check.label(), requestedShift, appliedShift);
}
FootprintAudit footprint = auditFootprint(level, structure, start, check, foundKey);
@@ -571,9 +569,8 @@ final class WorldCheckStructureAudit {
Engine engine = irisGenerator.commandEngine();
IntBinaryOperator surfaceHeight = (x, z) ->
engine.getHeight(x, z, true) + engine.getMinHeight();
NativeStructureFoundationBuilder.StiltSupportAudit foundation =
NativeStructureFoundationBuilder.auditStiltSupport(
level, area, start, Blocks.COBBLESTONE.defaultBlockState(), surfaceHeight);
WorldCheckStiltAudit.Result foundation = WorldCheckStiltAudit.audit(
level, area, start, Blocks.COBBLESTONE.defaultBlockState(), surfaceHeight);
foundationBaseColumns = foundation.baseColumns();
foundationBlocks = foundation.stiltBlocks();
foundationColumns = foundation.stiltColumns();
@@ -26,8 +26,7 @@ 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.StructureReachability;
import art.arcane.iris.engine.object.structure.vanilla.IrisNativeStructureDecision;
import art.arcane.iris.engine.object.structure.vanilla.NativeStructureGenerationStatus;
import art.arcane.iris.engine.framework.NativeStructureGenerationStatus;
import art.arcane.iris.modded.IrisModdedChunkGenerator;
import art.arcane.iris.modded.ModdedEngineBootstrap;
import art.arcane.iris.modded.ModdedServerLevels;
@@ -133,14 +132,14 @@ final class ModdedCommandSuggestions {
for (Identifier identifier : registry.keySet()) {
String key = identifier.toString();
registeredKeys.add(normalizeKey(key));
IrisNativeStructureDecision decision = NativeStructureGenerationPolicy.resolve(engine, key, false);
NativeStructureGenerationStatus status = NativeStructureGenerationPolicy.resolve(engine, key);
boolean nativePlacement = IrisStructureLocator.hasNativePlacement(engine, key);
boolean locatableNativePlacement = nativePlacement
&& IrisStructureLocator.hasLocatableNativePlacement(engine, key);
boolean locatableEditableReplacement = !nativePlacement
&& decision.status() == NativeStructureGenerationStatus.REPLACED_BY_IRIS
&& status == NativeStructureGenerationStatus.REPLACED_BY_IRIS
&& ModuleServices.canLocateStructure(engine, key);
if (isEligibleRegisteredStructure(decision, nativePlacement,
if (isEligibleRegisteredStructure(status, nativePlacement,
locatableNativePlacement, locatableEditableReplacement,
reachableNativeKeys.contains(normalizeKey(key)), nativeGenerationEnabled)) {
nativeKeys.add(key);
@@ -157,17 +156,17 @@ final class ModdedCommandSuggestions {
return builder.buildFuture();
}
static boolean isEligibleRegisteredStructure(IrisNativeStructureDecision decision,
static boolean isEligibleRegisteredStructure(NativeStructureGenerationStatus status,
boolean nativePlacement,
boolean locatableNativePlacement,
boolean locatableEditableReplacement,
boolean reachable,
boolean nativeGenerationEnabled) {
if (decision.status() == NativeStructureGenerationStatus.REPLACED_BY_IRIS) {
if (status == NativeStructureGenerationStatus.REPLACED_BY_IRIS) {
return locatableEditableReplacement
|| nativeGenerationEnabled && nativePlacement && locatableNativePlacement;
}
return nativeGenerationEnabled && decision.generate()
return nativeGenerationEnabled && status == NativeStructureGenerationStatus.GENERATE_NATIVE
&& (reachable || nativePlacement && locatableNativePlacement);
}
@@ -31,9 +31,8 @@ import art.arcane.iris.engine.framework.NativeStructureGenerationPolicy;
import art.arcane.iris.engine.framework.StructureReachability;
import art.arcane.iris.engine.framework.WrongEngineBroException;
import art.arcane.iris.engine.object.world.biome.IrisBiome;
import art.arcane.iris.engine.object.structure.vanilla.IrisNativeStructureDecision;
import art.arcane.iris.engine.object.world.region.IrisRegion;
import art.arcane.iris.engine.object.structure.vanilla.NativeStructureGenerationStatus;
import art.arcane.iris.engine.framework.NativeStructureGenerationStatus;
import art.arcane.iris.modded.IrisModdedChunkGenerator;
import art.arcane.iris.util.project.context.IrisContext;
import art.arcane.volmlib.util.localization.MessageArgument;
@@ -166,21 +165,21 @@ final class ModdedLocateCommands {
return 0;
}
NativeStructureTarget target = resolved.get();
IrisNativeStructureDecision decision = NativeStructureGenerationPolicy.resolve(engine, target.key(), false);
NativeStructureGenerationStatus status = NativeStructureGenerationPolicy.resolve(engine, target.key());
boolean nativeGenerationEnabled =
source.getServer().getWorldGenSettings().options().generateStructures();
boolean nativePlacement = IrisStructureLocator.hasNativePlacement(engine, target.key());
boolean locatableNativePlacement = nativePlacement
&& IrisStructureLocator.hasLocatableNativePlacement(engine, target.key());
boolean locatableEditableReplacement = !nativePlacement
&& decision.status() == NativeStructureGenerationStatus.REPLACED_BY_IRIS
&& status == NativeStructureGenerationStatus.REPLACED_BY_IRIS
&& ModuleServices.canLocateStructure(engine, target.key());
boolean reachable = StructureReachability.isReachable(engine, target.key());
if (!ModdedCommandSuggestions.isEligibleRegisteredStructure(
decision, nativePlacement, locatableNativePlacement, locatableEditableReplacement,
status, nativePlacement, locatableNativePlacement, locatableEditableReplacement,
reachable, nativeGenerationEnabled)) {
IrisModdedCommands.fail(source, registeredStructureUnavailableMessage(
target.key(), target.availability(), decision,
target.key(), target.availability(), status,
nativePlacement, locatableNativePlacement,
nativeGenerationEnabled, reachable));
return 0;
@@ -196,14 +195,14 @@ final class ModdedLocateCommands {
static String registeredStructureUnavailableMessage(
String key, NativeStructureAvailability nativeAvailability,
IrisNativeStructureDecision decision,
NativeStructureGenerationStatus status,
boolean nativePlacement, boolean locatableNativePlacement,
boolean nativeGenerationEnabled, boolean reachable) {
if (!decision.generate()
&& decision.status() != NativeStructureGenerationStatus.REPLACED_BY_IRIS) {
return NativeStructureGenerationPolicy.generationStatusMessage(key, decision.status());
if (status != NativeStructureGenerationStatus.GENERATE_NATIVE
&& status != NativeStructureGenerationStatus.REPLACED_BY_IRIS) {
return NativeStructureGenerationPolicy.generationStatusMessage(key, status);
}
if (decision.status() == NativeStructureGenerationStatus.REPLACED_BY_IRIS) {
if (status == NativeStructureGenerationStatus.REPLACED_BY_IRIS) {
if (nativePlacement && !nativeGenerationEnabled) {
return withInactiveNativePlacement(
nativeUnavailableMessage(key, NativeStructureAvailability.WORLD_DISABLED),
@@ -408,9 +407,9 @@ final class ModdedLocateCommands {
Engine engine, String key,
Holder.Reference<Structure> holder) {
boolean worldEnabled = source.getServer().getWorldGenSettings().options().generateStructures();
IrisNativeStructureDecision decision = NativeStructureGenerationPolicy.resolve(engine, key, false);
boolean selected = decision.status() != NativeStructureGenerationStatus.DISABLED_BY_PACK;
boolean suppressed = decision.status() == NativeStructureGenerationStatus.REPLACED_BY_IRIS;
NativeStructureGenerationStatus status = NativeStructureGenerationPolicy.resolve(engine, key);
boolean selected = status != NativeStructureGenerationStatus.DISABLED_BY_PACK;
boolean suppressed = status == NativeStructureGenerationStatus.REPLACED_BY_IRIS;
boolean biomeFilterEmpty = holder.value().biomes().stream().findAny().isEmpty();
ChunkGenerator chunkGenerator = level.getChunkSource().getGenerator();
boolean biomeReachable = chunkGenerator instanceof IrisModdedChunkGenerator irisGenerator
@@ -24,8 +24,7 @@ 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.StructureReachability;
import art.arcane.iris.engine.object.structure.vanilla.IrisNativeStructureDecision;
import art.arcane.iris.engine.object.structure.vanilla.NativeStructureGenerationStatus;
import art.arcane.iris.engine.framework.NativeStructureGenerationStatus;
import net.minecraft.commands.CommandSourceStack;
import net.minecraft.core.Holder;
import net.minecraft.core.Registry;
@@ -107,16 +106,16 @@ final class ModdedUnregisteredStructures {
key, "The live structure registry contains this key but has no bound structure holder."));
continue;
}
IrisNativeStructureDecision decision = NativeStructureGenerationPolicy.resolve(engine, key, false);
NativeStructureGenerationStatus status = NativeStructureGenerationPolicy.resolve(engine, key);
boolean nativePlacement = IrisStructureLocator.hasNativePlacement(engine, key);
boolean locatableNativePlacement = nativePlacement
&& IrisStructureLocator.hasLocatableNativePlacement(engine, key);
boolean locatableEditableReplacement = !nativePlacement
&& decision.status() == NativeStructureGenerationStatus.REPLACED_BY_IRIS
&& status == NativeStructureGenerationStatus.REPLACED_BY_IRIS
&& ModuleServices.canLocateStructure(engine, key);
boolean reachable = reachableNativeKeys.contains(normalizedKey);
if (ModdedCommandSuggestions.isEligibleRegisteredStructure(
decision, nativePlacement, locatableNativePlacement,
status, nativePlacement, locatableNativePlacement,
locatableEditableReplacement, reachable, nativeGenerationEnabled)) {
eligibleRegisteredKeys.add(normalizedKey);
continue;
@@ -124,7 +123,7 @@ final class ModdedUnregisteredStructures {
ModdedLocateCommands.NativeStructureAvailability availability =
ModdedLocateCommands.nativeAvailability(source, level, engine, key, holder.get());
String reason = ModdedLocateCommands.registeredStructureUnavailableMessage(
key, availability, decision, nativePlacement, locatableNativePlacement,
key, availability, status, nativePlacement, locatableNativePlacement,
nativeGenerationEnabled, reachable);
excluded.put(normalizedKey, new ExcludedStructure(ReportStatus.EXCLUDED, key, reason));
}
@@ -63,22 +63,20 @@ public class NativeStructureFailureContractTest {
int placementEnd = source.indexOf("private static String nativeStructureBatchContext", placementStart);
String placement = source.substring(placementStart, placementEnd);
assertTrue(placement.contains("\"terrain integration\""));
assertTrue(placement.contains("\"terrain preparation\""));
assertTrue(placement.contains("\"foundation repair\""));
assertTrue(placement.contains("\"terrain fitting\""));
assertFalse(placement.contains("\"terrain carving\""));
assertTrue(placement.contains("visitExistingPois(chunk"));
assertTrue(placement.contains("level.updatePOIOnBlockStateChange("));
assertTrue(placement.contains("Blocks.AIR.defaultBlockState(), state"));
assertTrue(placement.indexOf("visitExistingPois(chunk")
< placement.indexOf("WorldgenTerrainHeightmaps.primeStructurePlacement("));
assertTrue(placement.contains("prepareSurfaceStructures"));
assertTrue(placement.contains(".beforePieces("));
assertTrue(placement.contains("clearIntersectingVegetation"));
assertTrue(placement.indexOf("clearIntersectingVegetation")
< placement.indexOf("prepareSurfaceStructures"));
assertTrue(placement.indexOf("prepareSurfaceStructures")
< placement.indexOf(".beforePieces("));
assertTrue(placement.indexOf(".beforePieces(")
< placement.indexOf("for (NativePlacementGroup group"));
assertTrue(placement.indexOf("repairVacuumFoundations")
assertTrue(placement.indexOf("fit.afterPieces(")
> placement.indexOf("for (NativePlacementGroup group"));
}
@@ -94,7 +92,7 @@ public class NativeStructureFailureContractTest {
assertTrue(placement.contains("\"heightmap priming\""));
assertTrue(placement.contains("heightmapStarts.add(start);"));
assertTrue(placement.indexOf("WorldgenTerrainHeightmaps.primeStructurePlacement(")
< placement.indexOf("prepareSurfaceStructures"));
< placement.indexOf(".beforePieces("));
assertTrue(source.contains("generationEngine.getHeight(x, z, false) + runtimeMinY + 1"));
assertTrue(source.contains("generationEngine.getHeight(x, z, true) + runtimeMinY + 1"));
assertTrue(source.contains("int minY = chunk.getMinY() + 1;"));
@@ -108,8 +106,8 @@ public class NativeStructureFailureContractTest {
String placement = source.substring(placementStart, placementEnd);
assertTrue(placement.contains("ModdedNativeStructureWorldgenAccess.create("));
assertTrue(placement.contains("NativeStructurePostProcessor.place(\n boundedWorld"));
assertFalse(placement.contains("NativeStructurePostProcessor.place(world,"));
assertTrue(placement.contains("start.placeInChunk(boundedWorld,"));
assertFalse(placement.contains("start.placeInChunk(world,"));
assertTrue(placement.contains("world.setCurrentlyGenerating(null);"));
}
@@ -1,7 +1,6 @@
package art.arcane.iris.modded.command;
import art.arcane.iris.engine.object.structure.vanilla.IrisNativeStructureDecision;
import art.arcane.iris.engine.object.structure.vanilla.NativeStructureGenerationStatus;
import art.arcane.iris.engine.framework.NativeStructureGenerationStatus;
import art.arcane.iris.nativegen.NativeStructureLocateResults;
import com.mojang.datafixers.util.Pair;
import net.minecraft.core.BlockPos;
@@ -74,11 +73,9 @@ public class IrisModdedStructureCommandTest {
@Test
public void registeredStructureEligibilityMatchesGotoAndSuggestions() {
IrisNativeStructureDecision nativeDecision = decision(NativeStructureGenerationStatus.GENERATE_NATIVE);
IrisNativeStructureDecision replacementDecision = decision(
NativeStructureGenerationStatus.REPLACED_BY_IRIS);
IrisNativeStructureDecision disabledDecision = decision(
NativeStructureGenerationStatus.DISABLED_BY_PACK);
NativeStructureGenerationStatus nativeDecision = NativeStructureGenerationStatus.GENERATE_NATIVE;
NativeStructureGenerationStatus replacementDecision = NativeStructureGenerationStatus.REPLACED_BY_IRIS;
NativeStructureGenerationStatus disabledDecision = NativeStructureGenerationStatus.DISABLED_BY_PACK;
assertTrue(ModdedCommandSuggestions.isEligibleRegisteredStructure(
nativeDecision, false, false, false, true, true));
@@ -161,7 +158,7 @@ public class IrisModdedStructureCommandTest {
String combined = ModdedLocateCommands.registeredStructureUnavailableMessage(
"towns_and_towers:exclusive",
ModdedLocateCommands.NativeStructureAvailability.EMPTY_BIOME_FILTER,
decision(NativeStructureGenerationStatus.GENERATE_NATIVE),
NativeStructureGenerationStatus.GENERATE_NATIVE,
true, false, true, false);
assertTrue(combined.contains("resolves to zero registered biomes"));
assertTrue(combined.contains("matching Iris nativeStructures placement is also configured"));
@@ -203,7 +200,7 @@ public class IrisModdedStructureCommandTest {
assertFalse(method.contains("IrisStructureLocator.locatableKeys(engine)"));
assertTrue(method.contains("ModuleServices.locatableStructures(engine)"));
assertTrue(method.contains("StructureReachability.reachableKeys(engine)"));
assertTrue(method.contains("NativeStructureGenerationPolicy.resolve(engine, key, false)"));
assertTrue(method.contains("NativeStructureGenerationPolicy.resolve(engine, key)"));
assertTrue(method.contains("IrisStructureLocator.hasLocatableNativePlacement(engine, key)"));
assertTrue(method.contains("ModuleServices.canLocateStructure(engine, key)"));
assertTrue(method.contains("reachableNativeKeys.contains(normalizeKey(key))"));
@@ -260,7 +257,7 @@ public class IrisModdedStructureCommandTest {
int editableIrisLookup = method.indexOf(
"ModuleServices.canLocateStructure(engine, key)", nativeResolution);
int policyResolution = method.indexOf(
"NativeStructureGenerationPolicy.resolve(engine, target.key(), false)", editableIrisLookup);
"NativeStructureGenerationPolicy.resolve(engine, target.key())", editableIrisLookup);
int eligibilityCheck = method.indexOf(
"ModdedCommandSuggestions.isEligibleRegisteredStructure(", policyResolution);
int replacementLocate = method.indexOf(
@@ -330,8 +327,4 @@ public class IrisModdedStructureCommandTest {
.resolve("../modded-common/src/main/java")
.normalize();
}
private IrisNativeStructureDecision decision(NativeStructureGenerationStatus status) {
return new IrisNativeStructureDecision(status, 0, null, false, null, null);
}
}
@@ -9,10 +9,8 @@ import art.arcane.iris.engine.framework.NativeStructureOwnershipRecord;
import art.arcane.iris.engine.framework.NativeStructureOwnershipStore;
import art.arcane.iris.engine.framework.NativeStructureStartPlan;
import art.arcane.iris.engine.object.world.dimension.IrisDimension;
import art.arcane.iris.engine.object.structure.vanilla.IrisNativeStructureDecision;
import art.arcane.iris.engine.object.structure.IrisStructureTerrain;
import art.arcane.iris.engine.object.structure.IrisStructureTerrainMode;
import art.arcane.iris.engine.object.structure.vanilla.NativeStructureGenerationStatus;
import art.arcane.iris.engine.framework.NativeStructureReach;
import art.arcane.iris.engine.framework.NativeStructureGenerationStatus;
import com.github.benmanes.caffeine.cache.Cache;
import net.minecraft.SharedConstants;
import net.minecraft.core.Direction;
@@ -56,7 +54,6 @@ import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyBoolean;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.RETURNS_DEEP_STUBS;
import static org.mockito.Mockito.mock;
@@ -81,9 +78,7 @@ public class NativeStructureReferenceRepairTest {
StructureStart generated = monumentStart(structure, origin, seed);
NativeStructureVerticalPlacer.alignOceanMonumentToSeaLevel(
generated, 0, 80, -64, 320);
IrisStructureTerrain terrain = new IrisStructureTerrain()
.setMode(IrisStructureTerrainMode.FORCE_CARVE)
.setHorizontalPadding(24);
List<NativeStructureReach> terrain = List.of(new NativeStructureReach(false, 24));
StructureStart wrapped = NativeStructureReferenceEnvelope.wrap(
generated,
structure,
@@ -108,19 +103,9 @@ public class NativeStructureReferenceRepairTest {
@Test
public void deniedNaturalStartsCannotEnterCollisionArbitration() {
IrisNativeStructureDecision enabled = new IrisNativeStructureDecision(
NativeStructureGenerationStatus.GENERATE_NATIVE,
0, null, false, null, new IrisStructureTerrain());
IrisNativeStructureDecision disabled = new IrisNativeStructureDecision(
NativeStructureGenerationStatus.DISABLED_BY_PACK,
0, null, false, null, new IrisStructureTerrain());
IrisNativeStructureDecision replaced = new IrisNativeStructureDecision(
NativeStructureGenerationStatus.REPLACED_BY_IRIS,
0, null, false, null, new IrisStructureTerrain());
assertTrue(NativeStructureReferenceRepair.naturalDecisionAllows(enabled));
assertFalse(NativeStructureReferenceRepair.naturalDecisionAllows(disabled));
assertFalse(NativeStructureReferenceRepair.naturalDecisionAllows(replaced));
assertTrue(NativeStructureReferenceRepair.naturalStatusAllows(NativeStructureGenerationStatus.GENERATE_NATIVE));
assertFalse(NativeStructureReferenceRepair.naturalStatusAllows(NativeStructureGenerationStatus.DISABLED_BY_PACK));
assertFalse(NativeStructureReferenceRepair.naturalStatusAllows(NativeStructureGenerationStatus.REPLACED_BY_IRIS));
}
@Test
@@ -134,9 +119,7 @@ public class NativeStructureReferenceRepairTest {
StructureStart generated = monumentStart(structure, origin, seed);
NativeStructureVerticalPlacer.alignOceanMonumentToSeaLevel(
generated, 0, 80, -64, 320);
IrisStructureTerrain terrain = new IrisStructureTerrain()
.setMode(IrisStructureTerrainMode.FORCE_CARVE)
.setHorizontalPadding(24);
List<NativeStructureReach> terrain = List.of(new NativeStructureReach(false, 24));
StructureStart start = NativeStructureReferenceEnvelope.wrap(
generated, structure, 0, terrain);
NativeStructureOwnershipRecord ownership = NativeStructureOwnershipFingerprint.capture(
@@ -145,10 +128,9 @@ public class NativeStructureReferenceRepairTest {
plan(origin, NativeStructureReferenceEnvelope.contentBounds(start).minY()),
NativeStructureReferenceEnvelope.referenceBounds(start, structure, terrain));
Engine engine = engine(new IrisDimension(), packWithoutModules());
IrisNativeStructureDecision currentDecision = new IrisNativeStructureDecision(
NativeStructureGenerationStatus.DISABLED_BY_PACK, 0, null, false, null, null);
NativeStructureGenerationStatus currentStatus = NativeStructureGenerationStatus.DISABLED_BY_PACK;
assertFalse(NativeStructureReferenceRepair.naturalDecisionAllows(currentDecision));
assertFalse(NativeStructureReferenceRepair.naturalStatusAllows(currentStatus));
ProtoChunk originChunk = emptyChunk(origin);
originChunk.setStartForStructure(structure, start);
@@ -164,8 +146,8 @@ public class NativeStructureReferenceRepairTest {
installOwnership(engine, ownership);
try (MockedStatic<NativeStructureGenerationPolicy> policy = mockStatic(NativeStructureGenerationPolicy.class)) {
policy.when(() -> NativeStructureGenerationPolicy.resolve(any(), eq(structureKey), anyBoolean()))
.thenReturn(currentDecision);
policy.when(() -> NativeStructureGenerationPolicy.resolve(any(), eq(structureKey)))
.thenReturn(currentStatus);
WorldGenLevel level = worldGenLevel(
registry, serverLevel, originChunk, emptyScannedChunk);
ProtoChunk coveredChunk = emptyChunk(coveredTarget);
@@ -210,7 +192,7 @@ public class NativeStructureReferenceRepairTest {
private static NativeStructureStartPlan plan(ChunkPos origin, int baseY) {
return new NativeStructureStartPlan("minecraft:monument", origin.x(), origin.z(), baseY, false, false,
MONUMENT_PLACEMENT_IDENTITY, null, null, new IrisStructureTerrain());
MONUMENT_PLACEMENT_IDENTITY, null, null);
}
private static ChunkPos outsideLiveBounds(NativeStructureOwnershipRecord ownership,
@@ -1,13 +1,19 @@
package art.arcane.iris.nativegen;
import art.arcane.iris.engine.object.structure.IrisStructureTerrain;
import art.arcane.iris.engine.object.structure.IrisStructureTerrainMode;
import art.arcane.iris.engine.framework.NativeStartMemo;
import art.arcane.iris.engine.framework.nativefit.NativeStructureFitting;
import net.minecraft.SharedConstants;
import net.minecraft.core.BlockPos;
import net.minecraft.core.HolderSet;
import net.minecraft.core.registries.BuiltInRegistries;
import net.minecraft.server.Bootstrap;
import net.minecraft.util.RandomSource;
import net.minecraft.world.level.ChunkPos;
import net.minecraft.world.level.WorldGenLevel;
import net.minecraft.world.level.block.Blocks;
import net.minecraft.world.level.block.state.BlockState;
import net.minecraft.world.level.levelgen.GenerationStep;
import net.minecraft.world.level.levelgen.structure.BoundingBox;
import net.minecraft.world.level.levelgen.structure.Structure;
import net.minecraft.world.level.levelgen.structure.StructureStart;
import net.minecraft.world.level.levelgen.structure.TerrainAdjustment;
@@ -17,13 +23,20 @@ import net.minecraft.world.level.levelgen.structure.structures.DesertPyramidStru
import org.junit.BeforeClass;
import org.junit.Test;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Proxy;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.assertEquals;
/** The modded loaders fit the platform's starts with the same built-in fit as Bukkit, through the shared bridge. */
public class NativeStructureVacuumParityTest {
private static final int SURFACE_Y = 50;
private static final int WORLD_MIN_Y = -64;
private static final int WORLD_HEIGHT = 384;
@BeforeClass
public static void bootstrapMinecraftRegistries() {
SharedConstants.tryDetectVersion();
@@ -31,21 +44,53 @@ public class NativeStructureVacuumParityTest {
}
@Test
public void explicitVacuumUsesNonCarvingSurfaceFittingOnModdedLoaders() {
Structure structure = new DesertPyramidStructure(
new Structure.StructureSettings(
HolderSet.empty(), Map.of(),
GenerationStep.Decoration.SURFACE_STRUCTURES, TerrainAdjustment.NONE));
public void explicitVacuumNeitherCarvesNorInventsFootprintsForPiecesWithoutTemplates() {
Structure structure = new DesertPyramidStructure(new Structure.StructureSettings(
HolderSet.empty(), Map.of(), GenerationStep.Decoration.SURFACE_STRUCTURES, TerrainAdjustment.NONE));
DesertPyramidPiece piece = new DesertPyramidPiece(RandomSource.create(7L), 0, 0);
StructureStart start = new StructureStart(
structure, new ChunkPos(0, 0), 0, new PiecesContainer(List.of(piece)));
NativeStructureTerrainIntegrator.TerrainTarget target =
new NativeStructureTerrainIntegrator.TerrainTarget(
"test:vacuum", start,
new IrisStructureTerrain().setMode(IrisStructureTerrainMode.VACUUM));
StructureStart start = new StructureStart(structure, new ChunkPos(0, 0), 0, new PiecesContainer(List.of(piece)));
BoundingBox bounds = start.getBoundingBox();
BoundingBox area = new BoundingBox(bounds.minX() - 12, 40, bounds.minZ() - 12,
bounds.maxX() + 12, bounds.maxY() + 12, bounds.maxZ() + 12);
Map<BlockPos, BlockState> blocks = flatTerrain(area);
Map<BlockPos, BlockState> original = new HashMap<>(blocks);
assertTrue(NativeStructureSurfaceFitter.requiresSurfaceTerrain(target));
assertFalse(NativeStructureTerrainIntegrator.clearsLegacyTemplateAir(
start, target.terrain()));
NativeStructureFitting.builtInModules().beforePieces(NativeStructureFitBridge.chunk(world(blocks), area,
List.of(new NativeStructureFitBridge.FitTarget("test:vacuum", start,
new NativeStartMemo("{\"mode\":\"VACUUM\"}", "null"))), (x, z) -> SURFACE_Y));
assertEquals(original, blocks);
}
private static Map<BlockPos, BlockState> flatTerrain(BoundingBox area) {
Map<BlockPos, BlockState> blocks = new HashMap<>();
for (int x = area.minX(); x <= area.maxX(); x++) {
for (int z = area.minZ(); z <= area.maxZ(); z++) {
blocks.put(new BlockPos(x, SURFACE_Y - 1, z), Blocks.DIRT.defaultBlockState());
blocks.put(new BlockPos(x, SURFACE_Y, z), Blocks.GRASS_BLOCK.defaultBlockState());
}
}
return blocks;
}
private static WorldGenLevel world(Map<BlockPos, BlockState> blocks) {
InvocationHandler handler = (proxy, method, arguments) -> switch (method.getName()) {
case "getBlockState" -> blocks.getOrDefault(arguments[0], Blocks.AIR.defaultBlockState());
case "setBlock" -> {
blocks.put(((BlockPos) arguments[0]).immutable(), (BlockState) arguments[1]);
yield true;
}
case "getSeed" -> 1L;
case "getMinY" -> WORLD_MIN_Y;
case "getHeight" -> WORLD_HEIGHT;
case "getLevel" -> null;
case "holderLookup" -> BuiltInRegistries.BLOCK;
case "hashCode" -> System.identityHashCode(proxy);
case "equals" -> proxy == arguments[0];
case "toString" -> "vacuum-parity-world";
default -> throw new UnsupportedOperationException(method.toString());
};
return (WorldGenLevel) Proxy.newProxyInstance(
WorldGenLevel.class.getClassLoader(), new Class<?>[]{WorldGenLevel.class}, handler);
}
}
+2 -2
View File
@@ -127,8 +127,8 @@ nmsBindings.each { key, value ->
rootProject.file("adapters/bukkit/nms/${key}/src/main/java/art/arcane/iris/core/nms/${key}/IrisChunkGenerator.java").absolutePath)
systemProperty('iris.nmsBindingSource',
rootProject.file("adapters/bukkit/nms/${key}/src/main/java/art/arcane/iris/core/nms/${key}/NMSBinding.java").absolutePath)
systemProperty('iris.nativeStructurePostProcessorSource',
rootProject.file('adapters/minecraft-common/src/main/java/art/arcane/iris/nativegen/NativeStructurePostProcessor.java').absolutePath)
systemProperty('iris.nativeStructureFitBridgeSource',
rootProject.file('adapters/minecraft-common/src/main/java/art/arcane/iris/nativegen/NativeStructureFitBridge.java').absolutePath)
systemProperty('iris.nativeStructureStartInjectorSource',
rootProject.file('adapters/minecraft-common/src/main/java/art/arcane/iris/nativegen/NativeStructureStartInjector.java').absolutePath)
systemProperty('iris.nativeStructureGenerationKeysSource',
@@ -23,23 +23,14 @@ import art.arcane.iris.engine.object.material.IrisMaterialPalette;
import art.arcane.iris.engine.object.noise.IrisGeneratorStyle;
import art.arcane.iris.engine.object.noise.IrisStyledRange;
import art.arcane.iris.engine.object.noise.NoiseStyle;
import art.arcane.iris.engine.object.structure.IrisStructureStiltSettings;
import art.arcane.iris.engine.object.structure.IrisStructureTerrain;
import art.arcane.iris.engine.object.structure.IrisStructureYBand;
import art.arcane.iris.engine.object.structure.jigsaw.IrisJigsawConfiguration;
import art.arcane.iris.engine.object.value.IrisPosition;
import art.arcane.iris.engine.object.value.IrisRange;
import art.arcane.volmlib.util.collection.KList;
import art.arcane.volmlib.util.collection.KMap;
import com.google.gson.Gson;
import com.volmit.block.BlockSpec;
import com.volmit.block.PaletteSpec;
import com.volmit.config.Range;
import com.volmit.noise.StyledRange;
import com.volmit.vanilla.JigsawOverrides;
import com.volmit.vanilla.StructureStilts;
import com.volmit.vanilla.StructureTerrain;
import com.volmit.vanilla.YBand;
import com.volmit.world.BlockPosition;
import java.util.Map;
@@ -57,12 +48,7 @@ public final class IrisValues {
Map.entry(com.volmit.noise.NoiseStyle.class.getName(), IrisGeneratorStyle.class),
Map.entry(StyledRange.class.getName(), IrisStyledRange.class),
Map.entry(Range.class.getName(), IrisRange.class),
Map.entry(BlockPosition.class.getName(), IrisPosition.class),
Map.entry(StructureTerrain.class.getName(), IrisStructureTerrain.class),
Map.entry(StructureStilts.class.getName(), IrisStructureStiltSettings.class),
Map.entry(YBand.class.getName(), IrisStructureYBand.class),
Map.entry(JigsawOverrides.class.getName(), IrisJigsawConfiguration.class));
private static final Gson SAME_JSON = new Gson();
Map.entry(BlockPosition.class.getName(), IrisPosition.class));
private IrisValues() {
}
@@ -94,30 +80,6 @@ public final class IrisValues {
return new IrisMaterialPalette().setStyle(generatorStyle(spec.style())).setZoom(spec.zoom()).setPalette(blocks);
}
/** {@code terrain} as the terrain fitting Iris's native structure placement applies. */
public static IrisStructureTerrain structureTerrain(StructureTerrain terrain) {
return sameJson(terrain, IrisStructureTerrain.class);
}
/** {@code stilts} as the foundation columns Iris's native structure placement builds. */
public static IrisStructureStiltSettings structureStilts(StructureStilts stilts) {
return sameJson(stilts, IrisStructureStiltSettings.class);
}
public static IrisStructureYBand yBand(YBand band) {
return sameJson(band, IrisStructureYBand.class);
}
/** {@code overrides} as the jigsaw configuration Iris applies to a platform jigsaw definition. */
public static IrisJigsawConfiguration jigsawConfiguration(JigsawOverrides overrides) {
return sameJson(overrides, IrisJigsawConfiguration.class);
}
/** The structure fit classes are plain values whose JSON is the API type's, so the conversion is a JSON round trip. */
private static <T> T sameJson(Object apiValue, Class<T> irisClass) {
return SAME_JSON.fromJson(SAME_JSON.toJsonTree(apiValue), irisClass);
}
/** Iris's maps hold no null values; a JSON null in a map reads as absent, as it does for Iris's own fields. */
private static KMap<String, Object> irisMap(Map<String, ?> values) {
KMap<String, Object> map = new KMap<>();
@@ -0,0 +1,430 @@
/*
* 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.engine.framework.Engine;
import art.arcane.iris.engine.framework.NativeStartMemo;
import art.arcane.iris.engine.framework.nativefit.NativeFitBlocks;
import art.arcane.iris.engine.framework.nativefit.NativeFitBox;
import art.arcane.iris.engine.framework.nativefit.NativeFitChunk;
import art.arcane.iris.engine.framework.nativefit.NativeFitPiece;
import art.arcane.iris.engine.framework.nativefit.NativeFitStart;
import art.arcane.iris.engine.framework.nativefit.NativeFitTrait;
import art.arcane.iris.engine.framework.nativefit.NativeStructureFitting;
import art.arcane.iris.engine.framework.nativefit.NativeTemplateCells;
import com.volmit.block.BlockFace;
import com.volmit.block.BlockState;
import com.volmit.block.BlockTrait;
import com.volmit.host.DiscoveredModule;
import com.volmit.host.LoadedModules;
import com.volmit.host.ServiceRegistration;
import com.volmit.mantle.BlockBox;
import com.volmit.resource.ResourceId;
import com.volmit.service.VanillaStructures;
import com.volmit.vanilla.PieceKind;
import com.volmit.vanilla.StartMemo;
import com.volmit.vanilla.StructureFit;
import com.volmit.vanilla.StructureStep;
import com.volmit.vanilla.TemplateCells;
import com.volmit.vanilla.TerrainAdaptation;
import com.volmit.world.BlockAccess;
import com.volmit.world.BlockPosition;
import com.volmit.world.PackWorld;
import java.util.ArrayList;
import java.util.EnumMap;
import java.util.HashMap;
import java.util.IdentityHashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Supplier;
/**
* The pack's {@link VanillaStructures} providers fitting the platform's starts into a chunk: the platform code's view
* of the chunk ({@link NativeFitChunk}) as an API {@link StructureFit}, its native block states translated to API
* states and back through caches, so a provider can read and write blocks without allocating per block.
*/
public final class ModuleStructureFitting implements NativeStructureFitting {
private static final Map<Object, BlockState> API_STATES = new ConcurrentHashMap<>();
private static final Map<BlockState, Object> NATIVE_STATES = new ConcurrentHashMap<>();
private static final Map<Object, Integer> NATIVE_TRAITS = new ConcurrentHashMap<>();
private static final Map<BlockTrait, NativeFitTrait> TRAITS = new EnumMap<>(Map.of(
BlockTrait.AIR, NativeFitTrait.AIR, BlockTrait.SOLID, NativeFitTrait.SOLID,
BlockTrait.FLUID, NativeFitTrait.FLUID, BlockTrait.LOG, NativeFitTrait.LOG,
BlockTrait.LEAVES, NativeFitTrait.LEAVES));
private final List<ServiceRegistration> providers;
private final Supplier<PackWorld> world;
private ModuleStructureFitting(List<ServiceRegistration> providers, Supplier<PackWorld> world) {
this.providers = providers;
this.world = world;
}
public static NativeStructureFitting of(Engine engine) {
return new ModuleStructureFitting(ModuleVanillaStructures.providersOf(engine.getData()),
() -> engine.getGeneration().world());
}
public static NativeStructureFitting builtInModules() {
List<DiscoveredModule> modules = IrisModuleHost.builtInModules().stream().map(DiscoveredModule::builtIn).toList();
LoadedModules loaded = LoadedModules.load(modules, Map.of(), List.of(IrisModuleHost.HOST_TYPE_PACKAGE), List.of());
return new ModuleStructureFitting(loaded.catalog().registrations(VanillaStructures.class), () -> {
throw new IllegalStateException("The built-in modules fit outside a world here: a start needs its memo"
+ " and a fit without palettes");
});
}
@Override
public <S> Session beforePieces(NativeFitChunk<S> chunk) {
ChunkFit<S> fit = new ChunkFit<>(chunk, world);
for (ServiceRegistration registration : providers) {
ModuleVanillaStructures.ask(registration, "fitting structures into chunk " + fit.chunkName(), provider -> {
provider.beforePieces(fit);
return Boolean.TRUE;
});
}
return startIndex -> {
StructureFit.Start placed = fit.starts().get(startIndex);
for (ServiceRegistration registration : providers) {
ModuleVanillaStructures.ask(registration, "fitting " + placed.structure() + " into chunk " + fit.chunkName(),
provider -> {
provider.afterPieces(fit, placed);
return Boolean.TRUE;
});
}
};
}
@SuppressWarnings("unchecked")
private static <S> S nativeState(NativeFitBlocks<S> blocks, BlockState state) {
return (S) NATIVE_STATES.computeIfAbsent(state, key -> blocks.state(key.key()));
}
private static <S> BlockState apiState(NativeFitBlocks<S> blocks, S state) {
BlockState known = API_STATES.get(state);
if (known != null) {
return known;
}
return API_STATES.computeIfAbsent(state, key -> BlockState.parse(PlatformBlockStates.namespaced(blocks.key(state))));
}
private static <S> boolean nativeTrait(NativeFitBlocks<S> blocks, S state, NativeFitTrait trait) {
int traits = NATIVE_TRAITS.computeIfAbsent(state, key -> {
int bits = 0;
for (NativeFitTrait each : NativeFitTrait.values()) {
if (blocks.is(state, each)) {
bits |= 1 << each.ordinal();
}
}
return bits;
});
return (traits & 1 << trait.ordinal()) != 0;
}
/** One chunk's fit in the API's terms: heights above the dimension's bottom, maxima exclusive. */
private static final class ChunkFit<S> implements StructureFit {
private final NativeFitChunk<S> chunk;
private final Supplier<PackWorld> world;
private final Access<S> blocks;
private final List<StructureFit.Start> starts;
private final Map<Class<?>, Object> states = new HashMap<>();
private ChunkFit(NativeFitChunk<S> chunk, Supplier<PackWorld> world) {
this.chunk = chunk;
this.world = world;
this.blocks = new Access<>(chunk);
List<StructureFit.Start> converted = new ArrayList<>(chunk.starts().size());
for (NativeFitStart<S> start : chunk.starts()) {
converted.add(new HostStart<>(start, chunk));
}
this.starts = List.copyOf(converted);
}
String chunkName() {
return (chunk.area().minX() >> 4) + "," + (chunk.area().minZ() >> 4);
}
@Override
public PackWorld world() {
return world.get();
}
@Override
public long seed() {
return chunk.seed();
}
@Override
public BlockBox area() {
return apiBox(chunk.area(), chunk.bottomY());
}
@Override
public int bottomY() {
return chunk.bottomY();
}
@Override
public BlockAccess blocks() {
return blocks;
}
@Override
public int surfaceY(int x, int z) {
return chunk.surfaceY().applyAsInt(x, z) - chunk.bottomY();
}
@Override
public BlockState naturalBlock(int y) {
return apiState(chunk.blocks(), chunk.naturalBlock().apply(y + chunk.bottomY()));
}
@Override
public List<StructureFit.Start> starts() {
return starts;
}
@Override
public <T> T state(Class<T> type, Supplier<? extends T> create) {
Object known = states.get(type);
if (known == null) {
known = create.get();
states.put(type, known);
}
return type.cast(known);
}
}
/** The chunk column's blocks: the area's columns from the dimension's bottom to its top. */
private static final class Access<S> implements BlockAccess {
private final NativeFitBlocks<S> blocks;
private final int bottomY;
private final BlockBox bounds;
private final Map<BlockState, S> written = new IdentityHashMap<>();
private Access(NativeFitChunk<S> chunk) {
this.blocks = chunk.blocks();
this.bottomY = chunk.bottomY();
NativeFitBox area = chunk.area();
this.bounds = new BlockBox(area.minX(), 0, area.minZ(), area.maxX() + 1, chunk.topY() - bottomY, area.maxZ() + 1);
}
@Override
public BlockBox bounds() {
return bounds;
}
@Override
public BlockState get(int x, int y, int z) {
requireInside(x, y, z);
return apiState(blocks, blocks.get(x, y + bottomY, z));
}
@Override
public void column(int x, int z, int fromY, BlockState[] into) {
for (int index = 0; index < into.length; index++) {
into[index] = get(x, fromY + index, z);
}
}
@Override
public void set(int x, int y, int z, BlockState state) {
requireInside(x, y, z);
blocks.set(x, y + bottomY, z, nativeOf(state));
}
@Override
public boolean is(BlockState state, BlockTrait trait) {
NativeFitTrait nativeTrait = TRAITS.get(trait);
if (nativeTrait == null) {
throw new UnsupportedOperationException("A structure fit answers only " + TRAITS.keySet() + ", not " + trait);
}
return nativeTrait(blocks, nativeOf(state), nativeTrait);
}
@Override
public boolean inTag(BlockState state, ResourceId tag) {
return blocks.inTag(nativeOf(state), tag.toString());
}
@Override
public boolean sturdy(int x, int y, int z, BlockFace face) {
requireInside(x, y, z);
return blocks.sturdy(x, y + bottomY, z, face.name());
}
@Override
public BlockState fluid(BlockState state) {
return apiState(blocks, blocks.fluid(nativeOf(state)));
}
private S nativeOf(BlockState state) {
S known = written.get(state);
if (known == null) {
known = nativeState(blocks, state);
written.put(state, known);
}
return known;
}
private void requireInside(int x, int y, int z) {
if (!bounds.contains(x, y, z)) {
throw new IndexOutOfBoundsException("Block " + x + ", " + y + ", " + z + " is outside the fitted chunk " + bounds);
}
}
}
private static final class HostStart<S> implements StructureFit.Start {
private final NativeFitStart<S> start;
private final ResourceId structure;
private final List<StructureFit.Piece> pieces;
private HostStart(NativeFitStart<S> start, NativeFitChunk<S> chunk) {
this.start = start;
this.structure = ResourceId.parse(start.structureKey());
List<StructureFit.Piece> converted = new ArrayList<>(start.pieces().size());
for (NativeFitPiece<S> piece : start.pieces()) {
converted.add(new HostPiece<>(piece, chunk));
}
this.pieces = List.copyOf(converted);
}
@Override
public ResourceId structure() {
return structure;
}
@Override
public int chunkX() {
return start.chunkX();
}
@Override
public int chunkZ() {
return start.chunkZ();
}
@Override
public StructureStep step() {
return StructureStep.valueOf(start.step());
}
@Override
public TerrainAdaptation adaptation() {
return TerrainAdaptation.valueOf(start.adaptation());
}
@Override
public Optional<StartMemo> memo() {
NativeStartMemo memo = start.memo();
return memo == null ? Optional.empty() : Optional.of(new StartMemo(memo.terrain(), memo.foundation()));
}
@Override
public List<StructureFit.Piece> pieces() {
return pieces;
}
@Override
public Object key() {
return start.key();
}
}
private static final class HostPiece<S> implements StructureFit.Piece {
private final NativeFitPiece<S> piece;
private final NativeFitChunk<S> chunk;
private final int bottomY;
private HostPiece(NativeFitPiece<S> piece, NativeFitChunk<S> chunk) {
this.piece = piece;
this.chunk = chunk;
this.bottomY = chunk.bottomY();
}
@Override
public BlockBox box() {
return apiBox(piece.box(), bottomY);
}
@Override
public PieceKind kind() {
return PieceKind.valueOf(piece.kind());
}
@Override
public int groundLevelDelta() {
return piece.groundLevelDelta();
}
@Override
public List<BlockPosition> junctions() {
List<BlockPosition> junctions = new ArrayList<>(piece.junctions().size());
for (int[] junction : piece.junctions()) {
junctions.add(new BlockPosition(junction[0], junction[1] - bottomY, junction[2]));
}
return junctions;
}
@Override
public TemplateCells cells(BlockBox region) {
NativeTemplateCells<S> cells = piece.cells(nativeBox(region, bottomY));
if (!cells.resolved()) {
return TemplateCells.UNRESOLVED;
}
int size = cells.states().length;
int[] ys = new int[size];
BlockState[] states = new BlockState[size];
for (int cell = 0; cell < size; cell++) {
ys[cell] = cells.ys()[cell] - bottomY;
S state = cells.states()[cell];
states[cell] = state == null ? null : apiState(chunk.blocks(), state);
}
return TemplateCells.of(cells.xs(), ys, cells.zs(), states, cells.readBlocks());
}
@Override
public void columns(StructureFit.ColumnVisitor visitor) {
piece.columns((x, z, minY, maxY) -> visitor.column(x, z, minY - bottomY, maxY - bottomY));
}
@Override
public List<BlockPosition> legacyAir(BlockBox clip) {
List<int[]> air = piece.legacyAir(nativeBox(clip, bottomY));
List<BlockPosition> positions = new ArrayList<>(air.size());
for (int[] position : air) {
positions.add(new BlockPosition(position[0], position[1] - bottomY, position[2]));
}
return positions;
}
}
private static BlockBox apiBox(NativeFitBox box, int bottomY) {
return new BlockBox(box.minX(), box.minY() - bottomY, box.minZ(), box.maxX() + 1, box.maxY() + 1 - bottomY,
box.maxZ() + 1);
}
private static NativeFitBox nativeBox(BlockBox box, int bottomY) {
return new NativeFitBox(box.minX(), box.minY() + bottomY, box.minZ(), box.maxX() - 1, box.maxY() - 1 + bottomY,
box.maxZ() - 1);
}
}
@@ -20,17 +20,24 @@ package art.arcane.iris.core.modules;
import art.arcane.iris.core.loader.IrisData;
import art.arcane.iris.engine.framework.Engine;
import art.arcane.iris.engine.framework.NativeJigsawOverrides;
import art.arcane.iris.engine.framework.NativeStartMemo;
import art.arcane.iris.engine.framework.NativeStartPlacement;
import art.arcane.iris.engine.framework.NativeStructureReach;
import art.arcane.iris.engine.framework.NativeStructureStartPlan;
import art.arcane.iris.engine.object.structure.IrisStructureTerrain;
import art.arcane.iris.engine.object.world.dimension.IrisDimension;
import com.volmit.config.PackSettings;
import com.volmit.host.DiscoveredModule;
import com.volmit.host.VanillaStructureHookRegistration;
import com.volmit.host.ServiceRegistration;
import com.volmit.mantle.BlockBox;
import com.volmit.resource.PackResources;
import com.volmit.resource.ResourceId;
import com.volmit.vanilla.VanillaStructureAdjustment;
import com.volmit.service.VanillaStructures;
import com.volmit.vanilla.JigsawOverrides;
import com.volmit.vanilla.PlatformStart;
import com.volmit.vanilla.StartMemo;
import com.volmit.vanilla.StartReach;
import com.volmit.vanilla.VanillaStructureContext;
import com.volmit.vanilla.VanillaStructureHook;
import com.volmit.vanilla.VanillaStructureRule;
import com.volmit.vanilla.VanillaStructureSetup;
import com.volmit.vanilla.VanillaStructureStart;
@@ -43,31 +50,31 @@ import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.OptionalInt;
import java.util.WeakHashMap;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Function;
/**
* What the pack's modules want for the platform's own structures, asked through their vanilla structure hooks in module
* id order: per structure in one engine's world the combined rule ({@link VanillaStructureRule#and}) and adjustment
* ({@link VanillaStructureAdjustment#then}), kept per engine and pack snapshot so a hotload or a reload of the pack's
* resources asks again; per chunk the starts modules place, converted to the host's plans; and per dimension, before a
* world exists, the combined setup ({@link VanillaStructureSetup#and}). The platform side applies the results on Bukkit
* and the modded platforms alike.
* What the pack's modules want for the platform's own structures, asked through their {@link VanillaStructures}
* providers in module id order: per structure in one engine's world the combined rule ({@link VanillaStructureRule#and}),
* kept per engine and pack snapshot so a hotload or a reload of the pack's resources asks again; per chunk the starts
* modules place, converted to the host's plans; per platform start the shift every module gives it and every module's
* reach; and per dimension, before a world exists, the combined setup ({@link VanillaStructureSetup#and}). The platform
* side applies the results on Bukkit and the modded platforms alike.
*/
public final class ModuleVanillaStructures {
private static final Map<Engine, ModuleVanillaStructures> WORLDS = Collections.synchronizedMap(new WeakHashMap<>());
private static final int START_TERRAIN_REACH_BLOCKS = 8;
private final PackResources snapshot;
private final List<VanillaStructureHookRegistration> hooks;
private final List<ServiceRegistration> providers;
private final VanillaStructureContext world;
private final Map<String, VanillaStructureRule> rules = new ConcurrentHashMap<>();
private final Map<AdjustedStructure, VanillaStructureAdjustment> adjustments = new ConcurrentHashMap<>();
private ModuleVanillaStructures(Engine engine, PackResources snapshot) {
this.snapshot = snapshot;
this.hooks = hooksOf(engine.getData());
this.providers = providersOf(engine.getData());
this.world = new World(snapshot, new IrisPackSettings(engine));
}
@@ -76,45 +83,72 @@ public final class ModuleVanillaStructures {
return of(engine).rule(structureKey);
}
/**
* The combined adjustment of the pack's modules for the platform's own starts of {@code structureKey} in
* {@code engine}'s world; {@code underground} is whether the platform generates it in an underground step.
*/
public static VanillaStructureAdjustment adjustmentFor(Engine engine, String structureKey, boolean underground) {
return of(engine).adjustment(structureKey, underground);
}
/**
* The starts the pack's modules place in chunk {@code chunkX, chunkZ} of {@code engine}'s world, in module id order,
* as the host's plans: world heights, Iris's fit and jigsaw classes.
* as the host's plans: world heights, the platform's jigsaw changes and the modules' memos.
*/
public static List<NativeStructureStartPlan> startsAt(Engine engine, int chunkX, int chunkZ) {
StartContext context = new StartContext(engine.getGeneration().world(),
new IrisTerrainSampler(engine, new PackResourceIds(engine.getData().getDataFolder()),
chunkX << 4, chunkZ << 4, START_TERRAIN_REACH_BLOCKS));
List<NativeStructureStartPlan> plans = new ArrayList<>();
for (VanillaStructureHookRegistration registration : hooksOf(engine.getData())) {
for (ServiceRegistration registration : providersOf(engine.getData())) {
for (VanillaStructureStart start : ask(registration, "placing starts in chunk " + chunkX + "," + chunkZ,
hook -> hook.starts(chunkX, chunkZ, context))) {
provider -> provider.starts(chunkX, chunkZ, context))) {
plans.add(plan(registration.module(), start, chunkX, chunkZ, engine.getMinHeight()));
}
}
return List.copyOf(plans);
}
/** The shifts every module of the pack gives the platform's own start {@code start}, added up. */
public static int shiftOf(Engine engine, NativeStartPlacement start) {
ModuleVanillaStructures structures = of(engine);
Optional<ResourceId> structure = structureId(start.structureKey());
if (structure.isEmpty()) {
return 0;
}
PlatformStart platformStart = new HostPlatformStart(structure.get(), start);
int shift = 0;
for (ServiceRegistration registration : structures.providers) {
shift = Math.addExact(shift, ask(registration, "moving vanilla structure " + structure.get(),
provider -> provider.shift(platformStart, structures.world)));
}
return shift;
}
/** Every module's reach around a start of {@code structureKey}, placed by a module with {@code memo} or by the platform. */
public static List<NativeStructureReach> reachesOf(Engine engine, String structureKey, boolean underground,
NativeStartMemo memo) {
ModuleVanillaStructures structures = of(engine);
Optional<ResourceId> structure = structureId(structureKey);
if (structure.isEmpty()) {
return List.of(NativeStructureReach.PLATFORM);
}
Optional<StartMemo> startMemo = Optional.ofNullable(memo).map(note -> new StartMemo(note.terrain(), note.foundation()));
List<NativeStructureReach> reaches = new ArrayList<>(structures.providers.size());
for (ServiceRegistration registration : structures.providers) {
StartReach reach = ask(registration, "reaching around vanilla structure " + structure.get(),
provider -> provider.reach(structure.get(), underground, startMemo, structures.world));
reaches.add(new NativeStructureReach(reach.platform(), reach.blocks()));
}
return reaches.isEmpty() ? List.of(NativeStructureReach.PLATFORM) : List.copyOf(reaches);
}
/** The combined setup of the pack's modules for {@code dimension} of the pack {@code data} serves, before any world exists. */
public static VanillaStructureSetup setupFor(IrisData data, IrisDimension dimension) {
VanillaStructureContext context = new World(data.getPackResources(), new DimensionSettings(data, dimension));
VanillaStructureSetup combined = VanillaStructureSetup.UNCHANGED;
for (VanillaStructureHookRegistration registration : hooksOf(data)) {
for (ServiceRegistration registration : providersOf(data)) {
combined = combined.and(ask(registration, "setting up the vanilla structures of dimension " + dimension.getLoadKey(),
hook -> hook.setup(context)));
provider -> provider.setup(context)));
}
return combined;
}
private static List<VanillaStructureHookRegistration> hooksOf(IrisData data) {
return data.getModules().pack().catalog().vanillaStructureHooks();
/** The pack's {@link VanillaStructures} providers with the modules that registered them, in module id order. */
static List<ServiceRegistration> providersOf(IrisData data) {
return data.getModules().pack().catalog().registrations(VanillaStructures.class);
}
private static ModuleVanillaStructures of(Engine engine) {
@@ -132,10 +166,6 @@ public final class ModuleVanillaStructures {
return rules.computeIfAbsent(structureKey, this::askRules);
}
private VanillaStructureAdjustment adjustment(String structureKey, boolean underground) {
return adjustments.computeIfAbsent(new AdjustedStructure(structureKey, underground), this::askAdjustments);
}
/** A key that is no resource id names no structure a module could decide over. */
private VanillaStructureRule askRules(String structureKey) {
Optional<ResourceId> structure = structureId(structureKey);
@@ -143,28 +173,14 @@ public final class ModuleVanillaStructures {
return VanillaStructureRule.GENERATE;
}
VanillaStructureRule combined = VanillaStructureRule.GENERATE;
for (VanillaStructureHookRegistration registration : hooks) {
for (ServiceRegistration registration : providers) {
VanillaStructureRule rule = ask(registration, "deciding over vanilla structure " + structure.get(),
hook -> hook.rule(structure.get(), world));
provider -> provider.rule(structure.get(), world));
combined = combined.and(rule);
}
return combined;
}
private VanillaStructureAdjustment askAdjustments(AdjustedStructure adjusted) {
Optional<ResourceId> structure = structureId(adjusted.key());
if (structure.isEmpty()) {
return VanillaStructureAdjustment.NONE;
}
VanillaStructureAdjustment combined = VanillaStructureAdjustment.NONE;
for (VanillaStructureHookRegistration registration : hooks) {
VanillaStructureAdjustment adjustment = ask(registration, "adjusting vanilla structure " + structure.get(),
hook -> hook.adjustment(structure.get(), adjusted.underground(), world));
combined = combined.then(adjustment);
}
return combined;
}
private static Optional<ResourceId> structureId(String structureKey) {
try {
return Optional.of(ResourceId.parse(structureKey));
@@ -173,12 +189,11 @@ public final class ModuleVanillaStructures {
}
}
/** One hook's answer to {@code question}; a hook that throws or answers nothing fails naming its module. */
private static <T> T ask(VanillaStructureHookRegistration registration, String question,
Function<VanillaStructureHook, T> answer) {
/** One provider's answer to {@code question}; a provider that throws or answers nothing fails naming its module. */
static <T> T ask(ServiceRegistration registration, String question, Function<VanillaStructures, T> answer) {
T result;
try {
result = answer.apply(registration.hook());
result = answer.apply((VanillaStructures) registration.provider());
} catch (RuntimeException failure) {
throw new IllegalStateException("Module " + registration.module() + " failed " + question + ": " + failure, failure);
}
@@ -202,18 +217,72 @@ public final class ModuleVanillaStructures {
start.isUnderground(),
start.replacesPlatformStart(),
start.identity(),
start.jigsaw().map(IrisValues::jigsawConfiguration).orElse(null),
start.fit().stilts().map(IrisValues::structureStilts).orElse(null),
start.fit().terrain().map(IrisValues::structureTerrain).orElseGet(IrisStructureTerrain::new));
start.jigsaw().map(ModuleVanillaStructures::jigsaw).orElse(null),
start.memo().map(memo -> new NativeStartMemo(memo.terrain(), memo.foundation())).orElse(null));
}
/** The world the hooks decide for: the engine's pack snapshot and the settings its dimension reaches. */
private static NativeJigsawOverrides jigsaw(JigsawOverrides overrides) {
return new NativeJigsawOverrides(
overrides.startPool(),
overrides.startJigsawName(),
boxed(overrides.maxDepth()),
boxed(overrides.maxDistanceHorizontal()),
boxed(overrides.maxDistanceVertical()),
overrides.useExpansionHack().orElse(null),
overrides.projectStartToHeightmap().name(),
boxed(overrides.dimensionPaddingBottom()),
boxed(overrides.dimensionPaddingTop()),
overrides.liquidSettings().name());
}
private static Integer boxed(OptionalInt value) {
return value.isPresent() ? value.getAsInt() : null;
}
/** The world the providers decide for: the engine's pack snapshot and the settings its dimension reaches. */
private record World(PackResources resources, PackSettings settings) implements VanillaStructureContext {
}
private record StartContext(PackWorld world, TerrainSampler terrain) implements VanillaStructureStartContext {
}
private record AdjustedStructure(String key, boolean underground) {
/** A platform start in the API's heights: above the dimension's bottom, maxima exclusive. */
private record HostPlatformStart(ResourceId structure, NativeStartPlacement start) implements PlatformStart {
@Override
public int chunkX() {
return start.chunkX();
}
@Override
public int chunkZ() {
return start.chunkZ();
}
@Override
public BlockBox bounds() {
int bottom = start.bottomY();
return new BlockBox(start.minX(), start.minY() - bottom, start.minZ(),
start.maxX() + 1, start.maxY() + 1 - bottom, start.maxZ() + 1);
}
@Override
public boolean underground() {
return start.underground();
}
@Override
public boolean aligned() {
return start.aligned();
}
@Override
public int bottomY() {
return start.bottomY();
}
@Override
public int surfaceY(int x, int z) {
return start.surfaceY().applyAsInt(x, z) - start.bottomY();
}
}
}
@@ -0,0 +1,21 @@
package art.arcane.iris.engine.framework;
/**
* Changes a module makes to a jigsaw structure's registered definition before the platform assembles a start of it,
* as the platform code applies them: a blank text or a null value keeps the definition's own. The heightmap and liquid
* settings are the names of the API's {@code JigsawOverrides} constants ({@code SOURCE} keeps the definition's).
*/
public record NativeJigsawOverrides(
String startPool,
String startJigsawName,
Integer maxDepth,
Integer maxDistanceHorizontal,
Integer maxDistanceVertical,
Boolean useExpansionHack,
String projectStartToHeightmap,
Integer dimensionPaddingBottom,
Integer dimensionPaddingTop,
String liquidSettings
) {
public static final String SOURCE = "SOURCE";
}
@@ -0,0 +1,14 @@
package art.arcane.iris.engine.framework;
import java.util.Objects;
/**
* What a module noted about a start it placed, as the host keeps it: two texts in the module's own format, one about
* the start's terrain and one about its foundation. The host never reads them.
*/
public record NativeStartMemo(String terrain, String foundation) {
public NativeStartMemo {
Objects.requireNonNull(terrain, "terrain");
Objects.requireNonNull(foundation, "foundation");
}
}
@@ -0,0 +1,31 @@
package art.arcane.iris.engine.framework;
import java.util.Objects;
import java.util.function.IntBinaryOperator;
/**
* One of the platform's own starts before the host publishes it, as the platform code sees it: its structure, start
* chunk, the box around its pieces in world heights (every bound inclusive), whether the platform generates it in an
* underground step, whether the host aligns it itself (an ocean monument to the sea level, a desert or jungle temple
* to the terrain), the world's bottom height and the terrain's surface height per column in world heights.
*/
public record NativeStartPlacement(
String structureKey,
int chunkX,
int chunkZ,
int minX,
int minY,
int minZ,
int maxX,
int maxY,
int maxZ,
boolean underground,
boolean aligned,
int bottomY,
IntBinaryOperator surfaceY
) {
public NativeStartPlacement {
Objects.requireNonNull(structureKey, "structureKey");
Objects.requireNonNull(surfaceY, "surfaceY");
}
}
@@ -18,44 +18,32 @@
package art.arcane.iris.engine.framework;
import art.arcane.iris.core.modules.IrisValues;
import art.arcane.iris.core.modules.ModuleVanillaStructures;
import art.arcane.iris.engine.object.structure.vanilla.IrisNativeStructureDecision;
import art.arcane.iris.engine.object.structure.vanilla.NativeStructureGenerationStatus;
import com.volmit.vanilla.VanillaStructureAdjustment;
import com.volmit.vanilla.VanillaStructureFit;
import com.volmit.vanilla.VanillaStructureRule;
import java.util.Objects;
/**
* Whether the platform generates one of its own structures in an engine's world, and how its starts are adjusted, the
* same on every platform: the rule and adjustment the pack's modules give the structure through their vanilla
* structure hooks ({@link ModuleVanillaStructures}). A structure a module blocks does not generate; one a module
* places itself is reported as replaced, so find, goto and verify locate the module's placement.
* Whether the platform generates one of its own structures in an engine's world, the same on every platform: the rule
* the pack's modules give the structure through their {@code VanillaStructures} providers
* ({@link ModuleVanillaStructures}). A structure a module blocks does not generate; one a module places itself is
* reported as replaced, so find, goto and verify locate the module's placement.
*/
public final class NativeStructureGenerationPolicy {
private NativeStructureGenerationPolicy() {
}
public static IrisNativeStructureDecision resolve(Engine engine, String structureKey,
boolean undergroundStep) {
public static NativeStructureGenerationStatus resolve(Engine engine, String structureKey) {
Engine activeEngine = Objects.requireNonNull(engine, "Native structure policy requires an engine");
if (structureKey == null || structureKey.isBlank()) {
return decision(NativeStructureGenerationStatus.INVALID_REGISTRY_KEY, VanillaStructureAdjustment.NONE);
return NativeStructureGenerationStatus.INVALID_REGISTRY_KEY;
}
VanillaStructureRule rule = ModuleVanillaStructures.ruleFor(activeEngine, structureKey);
VanillaStructureAdjustment adjustment = ModuleVanillaStructures.adjustmentFor(activeEngine, structureKey, undergroundStep);
return decision(status(rule), adjustment);
return status(ModuleVanillaStructures.ruleFor(activeEngine, structureKey));
}
private static IrisNativeStructureDecision decision(NativeStructureGenerationStatus status,
VanillaStructureAdjustment adjustment) {
VanillaStructureFit fit = adjustment.fit();
return new IrisNativeStructureDecision(status, adjustment.yShift(),
adjustment.yBand().map(IrisValues::yBand).orElse(null), adjustment.keepsSourceY(),
fit.stilts().map(IrisValues::structureStilts).orElse(null),
fit.terrain().map(IrisValues::structureTerrain).orElse(null));
/** Whether the platform generates {@code structureKey} itself in {@code engine}'s world. */
public static boolean generates(Engine engine, String structureKey) {
return resolve(engine, structureKey) == NativeStructureGenerationStatus.GENERATE_NATIVE;
}
private static NativeStructureGenerationStatus status(VanillaStructureRule rule) {
@@ -0,0 +1,26 @@
/*
* 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;
public enum NativeStructureGenerationStatus {
GENERATE_NATIVE,
DISABLED_BY_PACK,
REPLACED_BY_IRIS,
INVALID_REGISTRY_KEY
}
@@ -0,0 +1,29 @@
package art.arcane.iris.engine.framework;
import art.arcane.iris.core.modules.ModuleVanillaStructures;
import java.util.List;
/**
* Where the platform's own starts sit and how far around their pieces the pack's modules change the terrain, as the
* platform code asks before it publishes a start: the shift every module gives a start, added up, and every module's
* reach.
*/
public final class NativeStructureLayouts {
private NativeStructureLayouts() {
}
/** How far the pack's modules move {@code start} up (negative: down), before the platform keeps it inside the world. */
public static int shift(Engine engine, NativeStartPlacement start) {
return ModuleVanillaStructures.shiftOf(engine, start);
}
/**
* How far every module of the pack changes the terrain around a start of {@code structureKey}: a start a module
* placed, with the {@code memo} it gave it, or one of the platform's own (null memo).
*/
public static List<NativeStructureReach> reaches(Engine engine, String structureKey, boolean underground,
NativeStartMemo memo) {
return ModuleVanillaStructures.reachesOf(engine, structureKey, underground, memo);
}
}
@@ -1,10 +1,5 @@
package art.arcane.iris.engine.framework;
import art.arcane.iris.engine.object.structure.vanilla.IrisNativeStructureDecision;
import art.arcane.iris.engine.object.structure.IrisStructureStiltSettings;
import art.arcane.iris.engine.object.structure.IrisStructureTerrain;
import art.arcane.iris.engine.object.structure.vanilla.NativeStructureGenerationStatus;
import com.google.gson.Gson;
import java.io.DataInputStream;
import java.io.DataOutputStream;
@@ -32,7 +27,7 @@ public record NativeStructureOwnershipRecord(
int referenceMinChunkZ,
int referenceMaxChunkZ,
String contentFingerprint,
DecisionSnapshot decision
MemoSnapshot memo
) {
public static final int CURRENT_SCHEMA = 2;
public static final int MAX_REFERENCE_DISTANCE_CHUNKS = 8;
@@ -69,7 +64,7 @@ public record NativeStructureOwnershipRecord(
if (!contentFingerprint.matches("[0-9a-f]{64}")) {
throw new IllegalArgumentException("Native structure content fingerprint must be SHA-256 hex");
}
decision = Objects.requireNonNull(decision, "Native structure decision snapshot must not be null");
memo = Objects.requireNonNull(memo, "Native structure memo snapshot must not be null");
}
public static NativeStructureOwnershipRecord create(String structureKey,
@@ -89,7 +84,7 @@ public record NativeStructureOwnershipRecord(
int referenceMinChunkZ,
int referenceMaxChunkZ,
String contentFingerprint,
IrisNativeStructureDecision decision) {
NativeStartMemo memo) {
return new NativeStructureOwnershipRecord(
CURRENT_SCHEMA,
structureKey,
@@ -109,7 +104,7 @@ public record NativeStructureOwnershipRecord(
referenceMinChunkZ,
referenceMaxChunkZ,
contentFingerprint,
DecisionSnapshot.capture(decision)
MemoSnapshot.of(memo)
);
}
@@ -140,7 +135,7 @@ public record NativeStructureOwnershipRecord(
referenceMinChunkZ,
referenceMaxChunkZ,
contentFingerprint,
decision
memo
);
}
@@ -148,8 +143,9 @@ public record NativeStructureOwnershipRecord(
return new OwnershipKey(structureKey, originChunkX, originChunkZ);
}
public IrisNativeStructureDecision restoredDecision() {
return decision.restore();
/** The memo the module gave the start when it placed it; null when it gave none. */
public NativeStartMemo restoredMemo() {
return memo.restore();
}
void write(DataOutputStream output) throws IOException {
@@ -171,7 +167,7 @@ public record NativeStructureOwnershipRecord(
output.writeInt(referenceMinChunkZ);
output.writeInt(referenceMaxChunkZ);
writeString(output, contentFingerprint, MAX_FINGERPRINT_BYTES, "content fingerprint");
decision.write(output);
memo.write(output);
}
static NativeStructureOwnershipRecord read(DataInputStream input) throws IOException {
@@ -199,7 +195,7 @@ public record NativeStructureOwnershipRecord(
input.readInt(),
input.readInt(),
readString(input, MAX_FINGERPRINT_BYTES, "content fingerprint"),
DecisionSnapshot.read(input)
MemoSnapshot.read(input)
);
} catch (IllegalArgumentException exception) {
throw new IOException("Native structure ownership record is invalid", exception);
@@ -251,56 +247,39 @@ public record NativeStructureOwnershipRecord(
}
}
public record DecisionSnapshot(String stiltJson, String terrainJson) {
private static final Gson GSON = new Gson();
private static final int MAX_JSON_BYTES = 65_536;
/**
* The start's memo as the record stores it: the foundation text, then the terrain text. Records written before
* memos existed hold the JSON of the start's stilts and terrain fit in these two places, which is what the module
* writes as its memo, so they read the same. A start without a memo stores two empty texts.
*/
public record MemoSnapshot(String foundation, String terrain) {
private static final int MAX_MEMO_BYTES = 65_536;
private static final MemoSnapshot NONE = new MemoSnapshot("", "");
public DecisionSnapshot {
stiltJson = Objects.requireNonNull(stiltJson, "Native structure stilt snapshot must not be null");
terrainJson = Objects.requireNonNull(terrainJson, "Native structure terrain snapshot must not be null");
requireUtf8Limit(stiltJson, MAX_JSON_BYTES, "stilt snapshot");
requireUtf8Limit(terrainJson, MAX_JSON_BYTES, "terrain snapshot");
public MemoSnapshot {
foundation = Objects.requireNonNull(foundation, "Native structure foundation memo must not be null");
terrain = Objects.requireNonNull(terrain, "Native structure terrain memo must not be null");
requireUtf8Limit(foundation, MAX_MEMO_BYTES, "foundation memo");
requireUtf8Limit(terrain, MAX_MEMO_BYTES, "terrain memo");
}
public static DecisionSnapshot capture(IrisNativeStructureDecision decision) {
IrisNativeStructureDecision resolved = Objects.requireNonNull(
decision, "Native structure decision must not be null");
if (!resolved.generate()) {
throw new IllegalArgumentException("Only generated native structure decisions can be persisted");
}
return new DecisionSnapshot(
GSON.toJson(resolved.stilt()),
GSON.toJson(Objects.requireNonNullElseGet(
resolved.terrain(), IrisStructureTerrain::new))
);
public static MemoSnapshot of(NativeStartMemo memo) {
return memo == null ? NONE : new MemoSnapshot(memo.foundation(), memo.terrain());
}
public IrisNativeStructureDecision restore() {
IrisStructureStiltSettings stilt = "null".equals(stiltJson)
? null : GSON.fromJson(stiltJson, IrisStructureStiltSettings.class);
IrisStructureTerrain terrain = GSON.fromJson(terrainJson, IrisStructureTerrain.class);
if (terrain == null) {
throw new IllegalStateException("Persisted native structure terrain snapshot is null");
}
return new IrisNativeStructureDecision(
NativeStructureGenerationStatus.GENERATE_NATIVE,
0,
null,
false,
stilt,
terrain
);
public NativeStartMemo restore() {
return equals(NONE) ? null : new NativeStartMemo(terrain, foundation);
}
void write(DataOutputStream output) throws IOException {
writeString(output, stiltJson, MAX_JSON_BYTES, "stilt snapshot");
writeString(output, terrainJson, MAX_JSON_BYTES, "terrain snapshot");
writeString(output, foundation, MAX_MEMO_BYTES, "foundation memo");
writeString(output, terrain, MAX_MEMO_BYTES, "terrain memo");
}
static DecisionSnapshot read(DataInputStream input) throws IOException {
return new DecisionSnapshot(
readString(input, MAX_JSON_BYTES, "stilt snapshot"),
readString(input, MAX_JSON_BYTES, "terrain snapshot")
static MemoSnapshot read(DataInputStream input) throws IOException {
return new MemoSnapshot(
readString(input, MAX_MEMO_BYTES, "foundation memo"),
readString(input, MAX_MEMO_BYTES, "terrain memo")
);
}
}
@@ -0,0 +1,10 @@
package art.arcane.iris.engine.framework;
/**
* How far around a start's pieces a module changes the terrain: the area the platform's own terrain adaptation of the
* structure covers ({@link #platform()}), or a number of blocks around the pieces. The platform code hands the start
* to every chunk any module's reach covers.
*/
public record NativeStructureReach(boolean platform, int blocks) {
public static final NativeStructureReach PLATFORM = new NativeStructureReach(true, 0);
}
@@ -1,19 +1,13 @@
package art.arcane.iris.engine.framework;
import art.arcane.iris.engine.object.structure.IrisStructureStiltSettings;
import art.arcane.iris.engine.object.structure.IrisStructureTerrain;
import art.arcane.iris.engine.object.structure.jigsaw.IrisJigsawConfiguration;
import art.arcane.iris.engine.object.structure.vanilla.IrisNativeStructureDecision;
import art.arcane.iris.engine.object.structure.vanilla.NativeStructureGenerationStatus;
import java.util.Objects;
/**
* One start of a platform structure a module places, as the platform code builds it: the structure key, the start
* chunk, the world base Y (the structure's lowest block when underground, the planned surface otherwise), whether it
* takes the chunk from a platform start of the same structure, the identity of what placed it, and Iris's jigsaw,
* stilt and terrain classes for the module's jigsaw overrides and fit. {@code jigsaw} and {@code stilt} may be null;
* {@code terrain} is never null ({@code SOURCE} when the module states none).
* takes the chunk from a platform start of the same structure, the identity of what placed it, the changes to the
* jigsaw definition it is assembled with (null for none), and the memo the module gave it (null for none), which the
* ownership record keeps for every later chunk of the start.
*/
public record NativeStructureStartPlan(
String structureKey,
@@ -23,17 +17,10 @@ public record NativeStructureStartPlan(
boolean underground,
boolean replacesPlatformStart,
long placementIdentity,
IrisJigsawConfiguration jigsaw,
IrisStructureStiltSettings stilt,
IrisStructureTerrain terrain
NativeJigsawOverrides jigsaw,
NativeStartMemo memo
) {
public NativeStructureStartPlan {
Objects.requireNonNull(structureKey, "Native structure start plan requires a structure key");
Objects.requireNonNull(terrain, "Native structure start plan requires a terrain fit");
}
/** The platform decision this start is generated under: generated natively with the start's own fit. */
public IrisNativeStructureDecision decision() {
return new IrisNativeStructureDecision(NativeStructureGenerationStatus.GENERATE_NATIVE, 0, null, false, stilt, terrain);
}
}
@@ -0,0 +1,29 @@
package art.arcane.iris.engine.framework.nativefit;
/**
* The live blocks of the chunk the platform decorates, in the platform's own block states {@code S}, at world
* coordinates, and the questions a structure fit asks about them.
*/
public interface NativeFitBlocks<S> {
S get(int x, int y, int z);
/** Replaces the block without updating neighbours, the way the platform's decoration writes. */
void set(int x, int y, int z, S state);
/** The state's key with its properties, such as {@code minecraft:oak_stairs[facing=east,half=bottom]}. */
String key(S state);
/** The state {@link #key} names. */
S state(String key);
boolean is(S state, NativeFitTrait trait);
/** Whether the state is in the platform's block tag {@code tag}, such as {@code minecraft:logs}. */
boolean inTag(S state, String tag);
/** Whether the block at the position can carry a full block on its face named {@code face} ({@code UP} ...). */
boolean sturdy(int x, int y, int z, String face);
/** The block of the fluid the state holds; air when it holds none. */
S fluid(S state);
}
@@ -0,0 +1,5 @@
package art.arcane.iris.engine.framework.nativefit;
/** A box of world blocks as the platform measures it: world heights, every bound inclusive. */
public record NativeFitBox(int minX, int minY, int minZ, int maxX, int maxY, int maxZ) {
}
@@ -0,0 +1,31 @@
package art.arcane.iris.engine.framework.nativefit;
import java.util.List;
import java.util.Objects;
import java.util.function.IntBinaryOperator;
import java.util.function.IntFunction;
/**
* One chunk the platform decorates with structure starts, as the platform code hands it to the modules' fit: its live
* blocks, the area it writes ({@code area}, world heights, inclusive), the world's bottom and top heights, the world
* seed, the terrain's surface height per column and the platform's natural block per height (both world heights), and
* the starts in the order the platform places them.
*/
public record NativeFitChunk<S>(
NativeFitBlocks<S> blocks,
NativeFitBox area,
int bottomY,
int topY,
long seed,
IntBinaryOperator surfaceY,
IntFunction<S> naturalBlock,
List<NativeFitStart<S>> starts
) {
public NativeFitChunk {
Objects.requireNonNull(blocks, "blocks");
Objects.requireNonNull(area, "area");
Objects.requireNonNull(surfaceY, "surfaceY");
Objects.requireNonNull(naturalBlock, "naturalBlock");
starts = List.copyOf(starts);
}
}
@@ -0,0 +1,29 @@
package art.arcane.iris.engine.framework.nativefit;
import java.util.List;
/** A piece of a start, as the platform code reads it, in world heights. */
public interface NativeFitPiece<S> {
NativeFitBox box();
/** {@code FIXED}, {@code RIGID} or {@code TERRAIN_MATCHING}, the names of the API's {@code PieceKind}. */
String kind();
int groundLevelDelta();
/** Each jigsaw junction's source X, ground height and Z. */
List<int[]> junctions();
NativeTemplateCells<S> cells(NativeFitBox region);
void columns(ColumnVisitor visitor);
/** The positions ({@code {x, y, z}}) of the legacy template air inside {@code clip}. */
List<int[]> legacyAir(NativeFitBox clip);
/** Receives one vertical span per column, both heights inclusive world heights. */
@FunctionalInterface
interface ColumnVisitor {
void column(int x, int z, int minY, int maxY);
}
}
@@ -0,0 +1,28 @@
package art.arcane.iris.engine.framework.nativefit;
import art.arcane.iris.engine.framework.NativeStartMemo;
import java.util.List;
/** A start the platform places in the chunk it decorates, as the platform code reads it. */
public interface NativeFitStart<S> {
String structureKey();
int chunkX();
int chunkZ();
/** The name of the platform's decoration step, as the API's {@code StructureStep} names it. */
String step();
/** The name of the structure definition's terrain adaptation, as the API's {@code TerrainAdaptation} names it. */
String adaptation();
/** The memo the module that placed the start gave it; null for the platform's own starts. */
NativeStartMemo memo();
List<NativeFitPiece<S>> pieces();
/** The same object for this start every chunk, for as long as the platform keeps the start. */
Object key();
}
@@ -0,0 +1,15 @@
package art.arcane.iris.engine.framework.nativefit;
/** The block questions a structure fit asks the platform about a state. */
public enum NativeFitTrait {
/** Air. */
AIR,
/** What the platform counts as solid. */
SOLID,
/** Holds a fluid: a source, a flowing fluid or a waterlogged block. */
FLUID,
/** A log, wood, stem or hyphae, by tag or by name. */
LOG,
/** Leaves, by tag or by name. */
LEAVES
}
@@ -0,0 +1,32 @@
package art.arcane.iris.engine.framework.nativefit;
import art.arcane.iris.core.modules.ModuleStructureFitting;
import art.arcane.iris.engine.framework.Engine;
/**
* The pack's modules fitting a chunk's structure starts into the terrain, around the platform placing their pieces:
* {@link #beforePieces} once before any piece of the chunk is placed, then {@link Session#afterPieces} after each
* start's pieces, in the order of the chunk's starts.
*/
public interface NativeStructureFitting {
<S> Session beforePieces(NativeFitChunk<S> chunk);
/** The modules of {@code engine}'s pack, fitting in its world. */
static NativeStructureFitting of(Engine engine) {
return ModuleStructureFitting.of(engine);
}
/**
* Iris's built-in modules outside any world, for starts whose fit their memo records and whose fit uses no palette;
* a fit that needs the world or the pack's resources fails. For tools and tests that drive the platform side alone.
*/
static NativeStructureFitting builtInModules() {
return ModuleStructureFitting.builtInModules();
}
/** One chunk's fit, between its starts' placements. */
interface Session {
/** Called after the platform placed the pieces of the chunk's start number {@code startIndex}. */
void afterPieces(int startIndex);
}
}
@@ -0,0 +1,9 @@
package art.arcane.iris.engine.framework.nativefit;
/**
* A piece's processed template blocks inside a region, at world positions: {@code states[i]} is the block at
* {@code (xs[i], ys[i], zs[i])}, null where the processors removed the template's block. {@code resolved} is false for
* a piece without a template. {@code readBlocks} counts the template blocks the platform read and processed.
*/
public record NativeTemplateCells<S>(boolean resolved, int[] xs, int[] ys, int[] zs, S[] states, int readBlocks) {
}
@@ -23,8 +23,7 @@ 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.StructureReachability;
import art.arcane.iris.engine.object.structure.vanilla.IrisNativeStructureDecision;
import art.arcane.iris.engine.object.structure.vanilla.NativeStructureGenerationStatus;
import art.arcane.iris.engine.framework.NativeStructureGenerationStatus;
import art.arcane.iris.spi.IrisPlatforms;
import art.arcane.iris.spi.PlatformStructureHooks;
import art.arcane.iris.util.common.director.DirectorParameterHandler;
@@ -116,27 +115,27 @@ public class StructureHandler implements DirectorParameterHandler<String> {
private static boolean isEligibleRegisteredKey(Engine engine, String key, String normalizedKey,
Set<String> reachableKeys, boolean nativeGenerationEnabled) {
IrisNativeStructureDecision decision = NativeStructureGenerationPolicy.resolve(engine, key, false);
NativeStructureGenerationStatus status = NativeStructureGenerationPolicy.resolve(engine, key);
boolean nativePlacement = IrisStructureLocator.hasNativePlacement(engine, key);
boolean locatableNativePlacement = nativePlacement
&& IrisStructureLocator.hasLocatableNativePlacement(engine, key);
boolean locatableEditableReplacement = !nativePlacement
&& decision.status() == NativeStructureGenerationStatus.REPLACED_BY_IRIS
&& status == NativeStructureGenerationStatus.REPLACED_BY_IRIS
&& ModuleServices.canLocateStructure(engine, key);
return isEligibleRegisteredKey(
decision, nativePlacement, locatableNativePlacement, locatableEditableReplacement,
status, nativePlacement, locatableNativePlacement, locatableEditableReplacement,
reachableKeys.contains(normalizedKey), nativeGenerationEnabled);
}
static boolean isEligibleRegisteredKey(IrisNativeStructureDecision decision, boolean nativePlacement,
static boolean isEligibleRegisteredKey(NativeStructureGenerationStatus status, boolean nativePlacement,
boolean locatableNativePlacement,
boolean locatableEditableReplacement,
boolean reachable, boolean nativeGenerationEnabled) {
if (decision.status() == NativeStructureGenerationStatus.REPLACED_BY_IRIS) {
if (status == NativeStructureGenerationStatus.REPLACED_BY_IRIS) {
return locatableEditableReplacement
|| nativeGenerationEnabled && nativePlacement && locatableNativePlacement;
}
return nativeGenerationEnabled && decision.generate()
return nativeGenerationEnabled && status == NativeStructureGenerationStatus.GENERATE_NATIVE
&& (reachable || (nativePlacement && locatableNativePlacement));
}
@@ -0,0 +1,142 @@
package art.arcane.iris.builtin.structure;
import com.google.gson.Gson;
import com.volmit.config.MaxNumber;
import com.volmit.config.MinNumber;
import org.junit.Test;
import java.lang.reflect.Field;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
/** The terrain fit, stilts and Y band settings of {@code iris:structure} as packs write them. */
public class StructureFitSettingsTest {
private static final Gson JSON = new Gson();
@Test
public void terrainDefaultsToSourceWithBoxCarving() {
StructureTerrain terrain = terrain("{}");
assertEquals(StructureTerrainMode.SOURCE, terrain.resolvedMode());
assertEquals(StructureCarveShape.BOX, terrain.resolvedShape());
assertEquals(0.8D, terrain.resolvedErosionStrength(), 0D);
assertEquals(0.07D, terrain.resolvedErosionFrequency(), 0D);
assertEquals(0.021D, terrain.resolvedLobeFrequency(), 1.0E-12D);
assertEquals(0.85D, terrain.resolvedLobeStrength(), 0D);
assertTrue(terrain.encasePalette().isEmpty());
}
@Test
public void lobeFrequencyAutoDerivesFromErosionFrequencyUntilAuthored() {
assertEquals(0.015D, terrain("{\"erosionFrequency\":0.05}").resolvedLobeFrequency(), 1.0E-12D);
assertEquals(0.015D, terrain("{\"erosionFrequency\":0.05,\"lobeFrequency\":\"NaN\"}").resolvedLobeFrequency(), 1.0E-12D);
assertEquals(0.015D, terrain("{\"erosionFrequency\":0.05,\"lobeFrequency\":-1}").resolvedLobeFrequency(), 1.0E-12D);
assertEquals(0.04D, terrain("{\"erosionFrequency\":0.05,\"lobeFrequency\":0.04}").resolvedLobeFrequency(), 0D);
assertEquals(1D, terrain("{\"erosionFrequency\":0.05,\"lobeFrequency\":2}").resolvedLobeFrequency(), 0D);
}
@Test
public void lobeStrengthClampsToTheAuthoredBand() {
assertEquals(0.85D, terrain("{\"lobeStrength\":\"NaN\"}").resolvedLobeStrength(), 0D);
assertEquals(0D, terrain("{\"lobeStrength\":-1}").resolvedLobeStrength(), 0D);
assertEquals(1D, terrain("{\"lobeStrength\":2}").resolvedLobeStrength(), 0D);
assertEquals(0.4D, terrain("{\"lobeStrength\":0.4}").resolvedLobeStrength(), 0D);
}
@Test
public void carveShapesExposeTheirMaximumCeilingScale() {
assertEquals(1D, StructureCarveShape.BOX.maximumCeilingScale(), 0D);
assertEquals(1D, StructureCarveShape.ROUNDED.maximumCeilingScale(), 0D);
assertEquals(1.8D, StructureCarveShape.ERODED.maximumCeilingScale(), 0D);
assertEquals(10, StructureCarveShape.BOX.maximumCeilingExtension(10));
assertEquals(10, StructureCarveShape.ROUNDED.maximumCeilingExtension(10));
assertEquals(18, StructureCarveShape.ERODED.maximumCeilingExtension(10));
assertEquals(10, StructureCarveShape.ERODED.maximumCeilingExtension(10, 0D));
assertEquals(14, StructureCarveShape.ERODED.maximumCeilingExtension(10, 0.5D));
assertEquals(0, StructureCarveShape.ERODED.maximumCeilingExtension(0));
}
@Test
public void nullAndNonFiniteValuesResolveToDefaults() {
StructureTerrain terrain = terrain("{\"shape\":null,\"erosionStrength\":\"NaN\",\"erosionFrequency\":\"Infinity\"}");
assertEquals(StructureCarveShape.BOX, terrain.resolvedShape());
assertEquals(0.8D, terrain.resolvedErosionStrength(), 0D);
assertEquals(0.07D, terrain.resolvedErosionFrequency(), 0D);
StructureTerrain negative = terrain("{\"erosionStrength\":\"-Infinity\",\"erosionFrequency\":\"NaN\"}");
assertEquals(0.8D, negative.resolvedErosionStrength(), 0D);
assertEquals(0.07D, negative.resolvedErosionFrequency(), 0D);
}
@Test
public void finiteValuesClampToAuthoredBounds() {
StructureTerrain low = terrain("{\"erosionStrength\":-1,\"erosionFrequency\":0}");
StructureTerrain high = terrain("{\"erosionStrength\":2,\"erosionFrequency\":2}");
assertEquals(0D, low.resolvedErosionStrength(), 0D);
assertEquals(0.001D, low.resolvedErosionFrequency(), 0D);
assertEquals(1D, high.resolvedErosionStrength(), 0D);
assertEquals(1D, high.resolvedErosionFrequency(), 0D);
}
@Test
public void encaseModeCarriesAnOptionalPaletteOverride() {
StructureTerrain encase = terrain("{\"mode\":\"ENCASE\",\"encasePalette\":{\"palette\":[{\"block\":\"minecraft:tuff\"}]}}");
assertEquals(StructureTerrainMode.ENCASE, encase.resolvedMode());
assertEquals("minecraft:tuff", encase.encasePalette().orElseThrow().palette().getFirst().block());
}
@Test
public void stiltsDefaultToACobblestoneFoundation() {
StructureStilts stilts = new StructureStilts();
assertEquals(64, stilts.maxDepth());
assertEquals(1, stilts.spacing());
assertFalse(stilts.supportNonOccluding());
assertEquals(1, stilts.palette().orElseThrow().palette().size());
assertEquals("minecraft:cobblestone", stilts.palette().orElseThrow().palette().getFirst().block());
}
@Test
public void bandBoundsResolveInOrderEvenWhenReversed() {
StructureYBand band = JSON.fromJson("{\"min\":-20,\"max\":-120}", StructureYBand.class);
StructureYBand collapsed = JSON.fromJson("{\"min\":-64,\"max\":-64}", StructureYBand.class);
assertEquals(-120, band.resolvedMin());
assertEquals(-20, band.resolvedMax());
assertEquals(-64, collapsed.resolvedMin());
assertEquals(-64, collapsed.resolvedMax());
}
@Test
public void numericSchemaBoundsMatchRuntimeBounds() throws NoSuchFieldException {
assertBounds(StructureTerrain.class, "erosionStrength", 0D, 1D);
assertBounds(StructureTerrain.class, "erosionFrequency", 0.001D, 1D);
assertBounds(StructureTerrain.class, "lobeFrequency", 0D, 1D);
assertBounds(StructureTerrain.class, "lobeStrength", 0D, 1D);
assertBounds(StructureStilts.class, "maxDepth", 1D, 4064D);
assertBounds(StructureStilts.class, "spacing", 1D, 64D);
assertBounds(StructureYBand.class, "min", -4064D, 4064D);
assertBounds(StructureYBand.class, "max", -4064D, 4064D);
}
private static StructureTerrain terrain(String json) {
return JSON.fromJson(json, StructureTerrain.class);
}
private static void assertBounds(Class<?> type, String fieldName, double expectedMinimum, double expectedMaximum)
throws NoSuchFieldException {
Field field = type.getDeclaredField(fieldName);
MinNumber minimum = field.getAnnotation(MinNumber.class);
MaxNumber maximum = field.getAnnotation(MaxNumber.class);
assertNotNull(minimum);
assertNotNull(maximum);
assertEquals(expectedMinimum, minimum.value(), 0D);
assertEquals(expectedMaximum, maximum.value(), 0D);
}
}
@@ -30,7 +30,7 @@ import com.volmit.FeatureAttachment.Target;
import com.volmit.block.BlockSpec;
import com.volmit.host.LoadedPack;
import com.volmit.host.ModuleHost;
import com.volmit.vanilla.StructureTerrain;
import art.arcane.iris.builtin.structure.StructureTerrainMode;
import org.junit.After;
import org.junit.Before;
import org.junit.Rule;
@@ -139,7 +139,7 @@ public class PackBeforeThePortDecodingTest {
assertTrue(structures.datapackOverrides());
assertEquals(4, structures.adjustments().size());
assertEquals(List.of("minecraft:stronghold"), structures.adjustments().getFirst().match());
assertEquals(StructureTerrain.Mode.ENCASE, structures.adjustments().getFirst().terrain().orElseThrow().mode());
assertEquals(StructureTerrainMode.ENCASE, structures.adjustments().getFirst().terrain().orElseThrow().resolvedMode());
assertEquals(-64, structures.adjustments().get(1).yShift());
assertTrue(structures.adjustments().get(2).preserveSourceY());
assertEquals(2, structures.adjustments().get(3).stilt().orElseThrow().maxDepth());
@@ -2,16 +2,14 @@ package art.arcane.iris.core.modules;
import art.arcane.iris.builtin.structure.StructureAdjustment;
import art.arcane.iris.builtin.structure.StructureSettings;
import art.arcane.iris.engine.object.structure.IrisStructureStiltSettings;
import art.arcane.iris.engine.object.structure.IrisStructureTerrain;
import art.arcane.iris.builtin.structure.StructureTerrain;
import art.arcane.iris.builtin.structure.StructureTerrainMode;
import art.arcane.volmlib.util.json.JSONObject;
import com.google.gson.Gson;
import com.volmit.FeatureAttachment.Target;
import com.volmit.block.BlockSpec;
import com.volmit.host.LoadedPack;
import com.volmit.host.ModuleHost;
import com.volmit.vanilla.StructureTerrain;
import com.volmit.vanilla.YBand;
import org.junit.After;
import org.junit.Before;
import org.junit.Rule;
@@ -21,7 +19,6 @@ import org.junit.rules.TemporaryFolder;
import java.io.IOException;
import java.nio.file.Path;
import java.util.List;
import java.util.Optional;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
@@ -93,29 +90,31 @@ public class StructureSettingsDecodingTest {
List<StructureAdjustment> adjustments = settings.adjustments();
assertEquals(4, adjustments.size());
StructureAdjustment stronghold = adjustments.getFirst();
assertEquals(Optional.of(YBand.of(-120, -20)), stronghold.yBand());
assertEquals(-120, stronghold.yBand().orElseThrow().resolvedMin());
assertEquals(-20, stronghold.yBand().orElseThrow().resolvedMax());
StructureTerrain terrain = stronghold.terrain().orElseThrow();
assertEquals(StructureTerrain.Mode.ENCASE, terrain.mode());
assertEquals(StructureTerrainMode.ENCASE, terrain.resolvedMode());
assertEquals(4, terrain.horizontalPadding());
assertEquals(BlockSpec.of("minecraft:stone_bricks").withWeight(6), terrain.encasePalette().orElseThrow().palette().getFirst());
assertEquals(-64, adjustments.get(1).yShift());
assertTrue(adjustments.get(2).preserveSourceY());
assertEquals(2, adjustments.get(3).stilt().orElseThrow().maxDepth());
assertEquals(List.of(BlockSpec.of("minecraft:dirt")), adjustments.get(3).stilt().orElseThrow().palette().palette());
assertEquals(List.of(BlockSpec.of("minecraft:dirt")), adjustments.get(3).stilt().orElseThrow().palette().orElseThrow().palette());
}
/** Starts remember their fit as the JSON of these settings, so the settings must write back what the pack wrote. */
@Test
public void fitsBecomeTheIrisClassesTheOldDimensionFieldReadFromTheSameJson() {
JSONObject json = new JSONObject(MIGRATED_DIMENSION).getJSONObject("importedStructures").getJSONArray("adjustments").getJSONObject(0);
JSONObject stiltJson = new JSONObject(MIGRATED_DIMENSION).getJSONObject("importedStructures").getJSONArray("adjustments")
.getJSONObject(3).getJSONObject("stilt");
List<StructureAdjustment> adjustments = settings(MIGRATED_DIMENSION).adjustments();
public void fitsWriteBackTheJsonThePackWrote() {
JSONObject adjustments = new JSONObject(MIGRATED_DIMENSION).getJSONObject("importedStructures");
JSONObject terrainJson = adjustments.getJSONArray("adjustments").getJSONObject(0).getJSONObject("terrain");
JSONObject stiltJson = adjustments.getJSONArray("adjustments").getJSONObject(3).getJSONObject("stilt");
List<StructureAdjustment> decoded = settings(MIGRATED_DIMENSION).adjustments();
Gson gson = new Gson();
assertEquals(gson.toJson(gson.fromJson(json.getJSONObject("terrain").toString(), IrisStructureTerrain.class)),
gson.toJson(IrisValues.structureTerrain(adjustments.getFirst().terrain().orElseThrow())));
assertEquals(gson.toJson(gson.fromJson(stiltJson.toString(), IrisStructureStiltSettings.class)),
gson.toJson(IrisValues.structureStilts(adjustments.get(3).stilt().orElseThrow())));
assertEquals(gson.toJson(gson.fromJson(terrainJson.toString(), StructureTerrain.class)),
gson.toJson(decoded.getFirst().terrain().orElseThrow()));
assertEquals(gson.toJson(gson.fromJson(stiltJson.toString(), art.arcane.iris.builtin.structure.StructureStilts.class)),
gson.toJson(decoded.get(3).stilt().orElseThrow()));
}
@Test
@@ -183,10 +183,6 @@ public class SchemaBuilderParityTest {
JSONObject erosionFrequency = terrainProperties.getJSONObject("erosionFrequency");
JSONObject lobeFrequency = terrainProperties.getJSONObject("lobeFrequency");
JSONObject lobeStrength = terrainProperties.getJSONObject("lobeStrength");
String carveShapeDefinition = carveShape.getString("$ref")
.substring("#/definitions/".length());
String terrainModeDefinition = terrainMode.getString("$ref")
.substring("#/definitions/".length());
assertTrue(properties.has("structures"));
assertTrue(properties.has("nativeStructures"));
@@ -195,9 +191,8 @@ public class SchemaBuilderParityTest {
"The editable structures backend supports SOURCE, PRESERVE, BORE, and FORCE_CARVE. "
+ "The nativeStructures backend supports every terrain mode."));
assertEquals(List.of("SOURCE", "PRESERVE", "BORE", "FORCE_CARVE", "VACUUM", "ENCASE"),
oneOfValues(schema.getJSONObject("definitions"), terrainModeDefinition));
assertEquals(List.of("BOX", "ROUNDED", "ERODED"), oneOfValues(
schema.getJSONObject("definitions"), carveShapeDefinition));
values(terrainMode.getJSONArray("enum")));
assertEquals(List.of("BOX", "ROUNDED", "ERODED"), values(carveShape.getJSONArray("enum")));
assertEquals(0D, erosionStrength.getDouble("minimum"), 0D);
assertEquals(1D, erosionStrength.getDouble("maximum"), 0D);
assertEquals(0.001D, erosionFrequency.getDouble("minimum"), 0D);
@@ -237,19 +232,18 @@ public class SchemaBuilderParityTest {
}
@Test
public void structureSettingsRenderTheirFitsWithIrisDefinitionsOfTheSameJson() throws IOException {
public void structureSettingsRenderTheirFitsWithTheModulesDefinitions() throws IOException {
JSONObject schema = new SchemaBuilder(IrisDimension.class, structureSchemaData(structureSettingsSchema())).construct();
JSONObject definitions = schema.getJSONObject("definitions");
JSONObject settings = definitions.getJSONObject(definitionKey(rootProperties(schema).getJSONObject("importedStructures")))
.getJSONObject("properties");
JSONObject adjustment = definitions.getJSONObject(definitionKey(settings.getJSONObject("adjustments").getJSONObject("items")))
.getJSONObject("properties");
JSONObject band = irisDefinition(definitions, adjustment.getJSONObject("yBand")).getJSONObject("properties");
JSONObject stilt = irisDefinition(definitions, adjustment.getJSONObject("stilt")).getJSONObject("properties");
JSONObject terrain = irisDefinition(definitions, adjustment.getJSONObject("terrain")).getJSONObject("properties");
JSONObject band = definitions.getJSONObject(definitionKey(adjustment.getJSONObject("yBand"))).getJSONObject("properties");
JSONObject stilt = definitions.getJSONObject(definitionKey(adjustment.getJSONObject("stilt"))).getJSONObject("properties");
JSONObject terrain = definitions.getJSONObject(definitionKey(adjustment.getJSONObject("terrain"))).getJSONObject("properties");
assertEquals("obj-art-arcane-iris-engine-object-structure-irisstructureyband",
definitionKey(definitions.getJSONObject(definitionKey(adjustment.getJSONObject("yBand")))));
assertEquals("module-art-arcane-iris-builtin-structure-structureyband", definitionKey(adjustment.getJSONObject("yBand")));
assertEquals("boolean", adjustment.getJSONObject("preserveSourceY").getString("type"));
assertEquals(-4064, band.getJSONObject("min").getInt("minimum"));
assertEquals(4064, band.getJSONObject("max").getInt("maximum"));
@@ -477,10 +471,6 @@ public class SchemaBuilderParityTest {
}
/** The definition an API value type's reference leads to: the module's, which refers to Iris's own. */
private static JSONObject irisDefinition(JSONObject definitions, JSONObject reference) {
return definitions.getJSONObject(definitionKey(definitions.getJSONObject(definitionKey(reference))));
}
private static String definitionKey(JSONObject reference) {
return reference.getString("$ref").substring("#/definitions/".length());
}
@@ -490,7 +480,10 @@ public class SchemaBuilderParityTest {
}
private static List<String> enumValues(JSONObject definitions, String key) {
JSONArray array = definitions.getJSONObject(key).getJSONArray("enum");
return values(definitions.getJSONObject(key).getJSONArray("enum"));
}
private static List<String> values(JSONArray array) {
List<String> values = new ArrayList<>(array.length());
for (int index = 0; index < array.length(); index++) {
values.add(array.getString(index));
@@ -18,6 +18,9 @@
package art.arcane.iris.engine.framework;
import art.arcane.iris.builtin.structure.StructureTerrain;
import com.google.gson.Gson;
import art.arcane.iris.builtin.anchor.ObjectPlaceMode;
import art.arcane.iris.engine.framework.structure.StructureResources;
import art.arcane.iris.core.modules.ModuleResourceFixture;
@@ -35,10 +38,7 @@ import art.arcane.iris.engine.object.value.IrisPosition;
import art.arcane.iris.engine.object.world.region.IrisRegion;
import art.arcane.iris.engine.object.structure.IrisStructure;
import art.arcane.iris.engine.object.structure.IrisStructureAnchorMode;
import art.arcane.iris.engine.object.structure.IrisStructureCarveShape;
import art.arcane.iris.engine.object.structure.IrisStructurePlacement;
import art.arcane.iris.engine.object.structure.IrisStructureTerrain;
import art.arcane.iris.engine.object.structure.IrisStructureTerrainMode;
import art.arcane.iris.engine.object.structure.vanilla.NativeStructureSuppression;
import art.arcane.iris.engine.object.structure.StructureDistribution;
import art.arcane.volmlib.util.collection.KList;
@@ -652,27 +652,22 @@ public class IrisStructureLocatorContractTest {
placement.setUnderground(true);
placement.setMinHeight(-64);
placement.setMaxHeight(100);
IrisStructureTerrain terrain = new IrisStructureTerrain()
.setMode(IrisStructureTerrainMode.FORCE_CARVE)
.setHorizontalPadding(2)
.setCeilingPadding(20)
.setShape(IrisStructureCarveShape.ERODED);
placement.setTerrain(terrain);
placement.setTerrain(forceCarve("\"horizontalPadding\":2,\"ceilingPadding\":20,\"shape\":\"ERODED\""));
KList<PlacedStructurePiece> pieces = new KList<>();
pieces.add(piece(0, 60, 0, 1, 80, 1));
assertEquals(Integer.valueOf(-14), IrisStructureLocator.resolveUndergroundBurialShift(
engine, pieces, placement, 60, -63, 319));
terrain.setErosionStrength(0D);
placement.setTerrain(forceCarve("\"horizontalPadding\":2,\"ceilingPadding\":20,\"shape\":\"ERODED\",\"erosionStrength\":0"));
assertEquals(Integer.valueOf(-1), IrisStructureLocator.resolveUndergroundBurialShift(
engine, pieces, placement, 60, -63, 319));
terrain.setShape(IrisStructureCarveShape.ROUNDED);
placement.setTerrain(forceCarve("\"horizontalPadding\":2,\"ceilingPadding\":20,\"shape\":\"ROUNDED\",\"erosionStrength\":0"));
assertEquals(Integer.valueOf(-1), IrisStructureLocator.resolveUndergroundBurialShift(
engine, pieces, placement, 60, -63, 319));
terrain.setCeilingPadding(0);
placement.setTerrain(forceCarve("\"horizontalPadding\":2,\"ceilingPadding\":0,\"shape\":\"ROUNDED\",\"erosionStrength\":0"));
assertEquals(Integer.valueOf(0), IrisStructureLocator.resolveUndergroundBurialShift(
engine, pieces, placement, 60, -63, 319));
}
@@ -686,11 +681,7 @@ public class IrisStructureLocatorContractTest {
.setUnderground(true)
.setMinHeight(-64)
.setMaxHeight(100)
.setTerrain(new IrisStructureTerrain()
.setMode(IrisStructureTerrainMode.FORCE_CARVE)
.setShape(IrisStructureCarveShape.ROUNDED)
.setHorizontalPadding(0)
.setCeilingPadding(0));
.setTerrain(forceCarve("\"shape\":\"ROUNDED\",\"horizontalPadding\":0,\"ceilingPadding\":0"));
KList<PlacedStructurePiece> pieces = new KList<>();
pieces.add(piece(4, 60, 7, 4, 80, 7));
@@ -867,4 +858,8 @@ public class IrisStructureLocatorContractTest {
int nearestOriginX,
int nearestOriginZ) {
}
private static StructureTerrain forceCarve(String options) {
return new Gson().fromJson("{\"mode\":\"FORCE_CARVE\"," + options + "}", StructureTerrain.class);
}
}
@@ -8,11 +8,8 @@ import art.arcane.iris.core.modules.ModuleSettings;
import art.arcane.iris.core.modules.IrisPackResources;
import art.arcane.iris.engine.object.world.dimension.IrisDimension;
import art.arcane.iris.engine.object.structure.vanilla.IrisNativeStructure;
import art.arcane.iris.engine.object.structure.vanilla.IrisNativeStructureDecision;
import art.arcane.iris.engine.object.world.region.IrisRegion;
import art.arcane.iris.engine.object.structure.IrisStructurePlacement;
import art.arcane.iris.engine.object.structure.IrisStructureTerrainMode;
import art.arcane.iris.engine.object.structure.vanilla.NativeStructureGenerationStatus;
import art.arcane.iris.engine.object.structure.vanilla.NativeStructureSuppression;
import art.arcane.volmlib.util.collection.KList;
import com.volmit.FeatureRegistry;
@@ -20,16 +17,15 @@ import com.volmit.IrisModule;
import com.volmit.ModuleInfo;
import com.volmit.host.LoadedPack;
import com.volmit.stage.StageGraph;
import com.volmit.block.BlockSpec;
import com.volmit.block.PaletteSpec;
import art.arcane.iris.builtin.structure.StructureTerrain;
import art.arcane.iris.core.modules.ModuleVanillaStructures;
import com.google.gson.Gson;
import com.volmit.resource.ResourceId;
import com.volmit.vanilla.StructureStilts;
import com.volmit.vanilla.StructureTerrain;
import com.volmit.vanilla.VanillaStructureAdjustment;
import com.volmit.service.VanillaStructures;
import com.volmit.vanilla.PlatformStart;
import com.volmit.vanilla.StartMemo;
import com.volmit.vanilla.StartReach;
import com.volmit.vanilla.VanillaStructureContext;
import com.volmit.vanilla.VanillaStructureFit;
import com.volmit.vanilla.VanillaStructureHook;
import com.volmit.vanilla.YBand;
import com.volmit.vanilla.VanillaStructureRule;
import org.junit.After;
import org.junit.Rule;
@@ -39,6 +35,7 @@ import org.junit.rules.TemporaryFolder;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.atomic.AtomicInteger;
import static org.junit.Assert.assertEquals;
@@ -82,17 +79,16 @@ public class NativeStructureGenerationPolicyTest {
Engine engine = engineWithDisabledNamespaceAndRegionPlacement("nova_structures:tavern_oak");
assertEquals(NativeStructureGenerationStatus.REPLACED_BY_IRIS,
NativeStructureGenerationPolicy.resolve(engine, "nova_structures:tavern_oak", false).status());
NativeStructureGenerationPolicy.resolve(engine, "nova_structures:tavern_oak"));
}
@Test
public void disabledKeyWithoutPlacementStaysDisabled() throws IOException {
Engine engine = engineWithDisabledNamespaceAndRegionPlacement("nova_structures:tavern_oak");
IrisNativeStructureDecision decision =
NativeStructureGenerationPolicy.resolve(engine, "nova_structures:witch_villa", false);
assertEquals(NativeStructureGenerationStatus.DISABLED_BY_PACK, decision.status());
assertFalse(decision.generate());
assertEquals(NativeStructureGenerationStatus.DISABLED_BY_PACK,
NativeStructureGenerationPolicy.resolve(engine, "nova_structures:witch_villa"));
assertFalse(NativeStructureGenerationPolicy.generates(engine, "nova_structures:witch_villa"));
}
@Test
@@ -102,12 +98,12 @@ public class NativeStructureGenerationPolicyTest {
Engine engine = engine(settings, regionPlacement("nova_structures:tavern_oak"), new KList<>(), List.of());
assertEquals(NativeStructureGenerationStatus.DISABLED_BY_PACK,
NativeStructureGenerationPolicy.resolve(engine, "minecraft:ruined_portal", false).status());
NativeStructureGenerationPolicy.resolve(engine, "minecraft:ruined_portal"));
assertEquals(NativeStructureGenerationStatus.GENERATE_NATIVE,
NativeStructureGenerationPolicy.resolve(engine, "minecraft:ruined_portal_nether", false).status());
NativeStructureGenerationPolicy.resolve(engine, "minecraft:ruined_portal_nether"));
}
/** The pilot of the vanilla structure hook: suppression now comes from the iris:structure module's rule. */
/** Suppression comes from the iris:structure module's rule. */
@Test
public void aStructureAnIrisPlacementReplacesIsBlockedByTheStructureModule() throws IOException {
IrisStructurePlacement replacement = new IrisStructurePlacement().setNativeSuppression(NativeStructureSuppression.REPLACE_SOURCE);
@@ -116,99 +112,105 @@ public class NativeStructureGenerationPolicyTest {
dimensionPlacements.add(replacement);
Engine engine = engine(allowingEverything(), new KList<>(), dimensionPlacements, List.of());
IrisNativeStructureDecision decision = NativeStructureGenerationPolicy.resolve(engine, "minecraft:village_plains", false);
assertEquals(NativeStructureGenerationStatus.REPLACED_BY_IRIS, decision.status());
assertFalse(decision.generate());
assertEquals(NativeStructureGenerationStatus.REPLACED_BY_IRIS,
NativeStructureGenerationPolicy.resolve(engine, "minecraft:village_plains"));
assertFalse(NativeStructureGenerationPolicy.generates(engine, "minecraft:village_plains"));
assertEquals(NativeStructureGenerationStatus.GENERATE_NATIVE,
NativeStructureGenerationPolicy.resolve(engine, "minecraft:village_desert", false).status());
NativeStructureGenerationPolicy.resolve(engine, "minecraft:village_desert"));
}
@Test
public void aStructureAPlacementAlsoPlacesStillGeneratesNatively() throws IOException {
Engine engine = engine(allowingEverything(), regionPlacement("minecraft:village_plains"), new KList<>(), List.of());
assertTrue(NativeStructureGenerationPolicy.resolve(engine, "minecraft:village_plains", false).generate());
assertTrue(NativeStructureGenerationPolicy.generates(engine, "minecraft:village_plains"));
}
@Test
public void packModulesBlockOrReplaceStructuresThroughTheirHooks() throws IOException {
Engine engine = engine(allowingEverything(), new KList<>(), new KList<>(), List.of(new HookModule((structure, world) ->
public void packModulesBlockOrReplaceStructuresThroughTheirRules() throws IOException {
Engine engine = engine(allowingEverything(), new KList<>(), new KList<>(), List.of(new ProviderModule(ruling((structure, world) ->
switch (structure.path()) {
case "pillager_outpost" -> VanillaStructureRule.BLOCK;
case "igloo" -> VanillaStructureRule.REPLACE;
default -> VanillaStructureRule.GENERATE;
})));
}))));
assertEquals(NativeStructureGenerationStatus.DISABLED_BY_PACK,
NativeStructureGenerationPolicy.resolve(engine, "minecraft:pillager_outpost", false).status());
NativeStructureGenerationPolicy.resolve(engine, "minecraft:pillager_outpost"));
assertEquals(NativeStructureGenerationStatus.REPLACED_BY_IRIS,
NativeStructureGenerationPolicy.resolve(engine, "minecraft:igloo", false).status());
NativeStructureGenerationPolicy.resolve(engine, "minecraft:igloo"));
assertEquals(NativeStructureGenerationStatus.GENERATE_NATIVE,
NativeStructureGenerationPolicy.resolve(engine, "minecraft:mansion", false).status());
NativeStructureGenerationPolicy.resolve(engine, "minecraft:mansion"));
}
@Test
public void hooksAreAskedOncePerStructureAndPackSnapshot() throws IOException {
public void rulesAreAskedOncePerStructureAndPackSnapshot() throws IOException {
AtomicInteger asked = new AtomicInteger();
Engine engine = engine(allowingEverything(), new KList<>(), new KList<>(), List.of(new HookModule((structure, world) -> {
Engine engine = engine(allowingEverything(), new KList<>(), new KList<>(), List.of(new ProviderModule(ruling((structure, world) -> {
asked.incrementAndGet();
return VanillaStructureRule.GENERATE;
})));
}))));
NativeStructureGenerationPolicy.resolve(engine, "minecraft:igloo", false);
NativeStructureGenerationPolicy.resolve(engine, "minecraft:igloo", true);
NativeStructureGenerationPolicy.resolve(engine, "minecraft:igloo");
NativeStructureGenerationPolicy.resolve(engine, "minecraft:igloo");
assertEquals(1, asked.get());
IrisData data = engine.getData();
IrisPackResources reloaded = new IrisPackResources(data);
when(data.getPackResources()).thenReturn(reloaded);
NativeStructureGenerationPolicy.resolve(engine, "minecraft:igloo", false);
NativeStructureGenerationPolicy.resolve(engine, "minecraft:igloo");
assertEquals("a new snapshot asks again", 2, asked.get());
}
@Test
public void aHookThatFailsNamesItsModule() throws IOException {
Engine engine = engine(allowingEverything(), new KList<>(), new KList<>(), List.of(new HookModule((structure, world) -> {
public void aProviderThatFailsNamesItsModule() throws IOException {
Engine engine = engine(allowingEverything(), new KList<>(), new KList<>(), List.of(new ProviderModule(ruling((structure, world) -> {
throw new IllegalArgumentException("broken");
})));
}))));
IllegalStateException failure = assertThrows(IllegalStateException.class,
() -> NativeStructureGenerationPolicy.resolve(engine, "minecraft:igloo", false));
() -> NativeStructureGenerationPolicy.resolve(engine, "minecraft:igloo"));
assertTrue(failure.getMessage(), failure.getMessage().startsWith(
"Module test:hook from host classpath failed deciding over vanilla structure minecraft:igloo: "));
}
@Test
public void adjustmentsOfTheSettingsAndOfPackModulesReachTheDecisionAsIrisClasses() throws IOException {
StructureTerrain bore = StructureTerrain.of(StructureTerrain.Mode.BORE).withPadding(6, 2, 1);
public void shiftsAndReachesOfTheSettingsAndOfPackModulesAddUpPerModule() throws IOException {
StructureTerrain bore = new Gson().fromJson("{\"mode\":\"BORE\",\"horizontalPadding\":6}", StructureTerrain.class);
StructureSettings settings = new StructureSettings(List.of(), List.of(), -32, true, List.of(), List.of(
new StructureAdjustment(List.of("minecraft:stronghold"), 4, YBand.of(-20, -100), false, null, bore)));
StructureStilts stilts = StructureStilts.of(PaletteSpec.of(List.of(BlockSpec.of("minecraft:stone_bricks")))).withSpacing(2);
Engine engine = engine(settings, new KList<>(), new KList<>(), List.of(new HookModule(new VanillaStructureHook() {
new StructureAdjustment(List.of("minecraft:stronghold"), 4, null, true, null, bore)));
Engine engine = engine(settings, new KList<>(), new KList<>(), List.of(new ProviderModule(new VanillaStructures() {
@Override
public VanillaStructureRule rule(ResourceId structure, VanillaStructureContext context) {
return VanillaStructureRule.GENERATE;
public int shift(PlatformStart start, VanillaStructureContext context) {
return -1;
}
@Override
public VanillaStructureAdjustment adjustment(ResourceId structure, boolean underground, VanillaStructureContext context) {
return VanillaStructureAdjustment.NONE.shifted(-1).keepingSourceY()
.withFit(VanillaStructureFit.SOURCE.withStilts(stilts));
public StartReach reach(ResourceId structure, boolean underground, Optional<StartMemo> memo,
VanillaStructureContext context) {
return StartReach.blocks(3);
}
})));
IrisNativeStructureDecision stronghold = NativeStructureGenerationPolicy.resolve(engine, "minecraft:stronghold", true);
assertEquals(-29, ModuleVanillaStructures.shiftOf(engine, placement("minecraft:stronghold", true)));
assertEquals(List.of(new NativeStructureReach(false, 6), new NativeStructureReach(false, 3)),
ModuleVanillaStructures.reachesOf(engine, "minecraft:stronghold", true, null));
assertEquals(-1, ModuleVanillaStructures.shiftOf(engine, placement("minecraft:village_plains", false)));
assertEquals(List.of(NativeStructureReach.PLATFORM, new NativeStructureReach(false, 3)),
ModuleVanillaStructures.reachesOf(engine, "minecraft:village_plains", false, null));
}
assertEquals(-29, stronghold.yShift());
assertTrue(stronghold.preserveSourceY());
assertEquals(-100, stronghold.yBand().resolvedMin());
assertEquals(IrisStructureTerrainMode.BORE, stronghold.terrain().resolvedMode());
assertEquals(6, stronghold.terrain().getHorizontalPadding());
assertEquals(2, stronghold.stilt().getSpacing());
assertEquals("minecraft:stone_bricks", stronghold.stilt().getPalette().getPalette().getFirst().getBlock());
IrisNativeStructureDecision village = NativeStructureGenerationPolicy.resolve(engine, "minecraft:village_plains", false);
assertEquals(-1, village.yShift());
assertEquals(null, village.terrain());
private static NativeStartPlacement placement(String structureKey, boolean underground) {
return new NativeStartPlacement(structureKey, 0, 0, 0, 10, 0, 20, 30, 20, underground, false, -64, (x, z) -> 100);
}
private static VanillaStructures ruling(RuleAnswer rule) {
return new VanillaStructures() {
@Override
public VanillaStructureRule rule(ResourceId structure, VanillaStructureContext context) {
return rule.decide(structure, context);
}
};
}
private Engine engineWithDisabledNamespaceAndRegionPlacement(String placedKey) throws IOException {
@@ -251,8 +253,12 @@ public class NativeStructureGenerationPolicyTest {
return engine;
}
/** A pack module whose only part is a vanilla structure hook. */
private record HookModule(VanillaStructureHook hook) implements IrisModule {
private interface RuleAnswer {
VanillaStructureRule decide(ResourceId structure, VanillaStructureContext context);
}
/** A pack module whose only part is a vanilla structures provider. */
private record ProviderModule(VanillaStructures provider) implements IrisModule {
@Override
public ModuleInfo info() {
return ModuleInfo.of("test:hook", "Hook", "1");
@@ -264,7 +270,7 @@ public class NativeStructureGenerationPolicyTest {
@Override
public void register(FeatureRegistry registry) {
registry.registerVanillaStructureHook(hook);
registry.registerService(VanillaStructures.class, provider);
}
}
}
@@ -1,11 +1,9 @@
package art.arcane.iris.engine.framework;
import art.arcane.iris.engine.object.structure.vanilla.IrisNativeStructureDecision;
import art.arcane.iris.engine.object.structure.IrisStructureCarveShape;
import art.arcane.iris.engine.object.structure.IrisStructureStiltSettings;
import art.arcane.iris.engine.object.structure.IrisStructureTerrain;
import art.arcane.iris.engine.object.structure.IrisStructureTerrainMode;
import art.arcane.iris.engine.object.structure.vanilla.NativeStructureGenerationStatus;
import art.arcane.iris.builtin.structure.StructureCarveShape;
import art.arcane.iris.builtin.structure.StructureTerrainMode;
import art.arcane.iris.engine.framework.structure.NativeStructureFit;
import com.volmit.vanilla.StartMemo;
import org.junit.Test;
import java.io.ByteArrayInputStream;
@@ -45,46 +43,42 @@ public class NativeStructureOwnershipRecordTest {
assertEquals(crypt, restored.find("nova_structures:undead_crypt", 4, -7));
}
/** The stilts and terrain fit JSON records written before memos hold, as the old Iris classes wrote them. */
@Test
public void decisionSnapshotFreezesTerrainAndStiltSettings() {
IrisStructureTerrain terrain = new IrisStructureTerrain()
.setMode(IrisStructureTerrainMode.FORCE_CARVE)
.setHorizontalPadding(9)
.setCeilingPadding(3)
.setFloorPadding(2)
.setShape(IrisStructureCarveShape.ERODED)
.setErosionStrength(0.42D)
.setErosionFrequency(0.17D)
.setLobeFrequency(0.03D)
.setLobeStrength(0.61D);
IrisStructureStiltSettings stilt = new IrisStructureStiltSettings()
.setMaxDepth(91)
.setSpacing(4)
.setSupportNonOccluding(true);
IrisNativeStructureDecision source = new IrisNativeStructureDecision(
NativeStructureGenerationStatus.GENERATE_NATIVE,
0,
null,
false,
stilt,
terrain
);
public void recordsWrittenBeforeMemosReadAsTheStructureModulesMemo() throws Exception {
String stilts = "{\"maxDepth\":91,\"palette\":{\"style\":{\"style\":\"STATIC\",\"cellularFrequency\":0.0,"
+ "\"cellularZoom\":1.0,\"zoom\":1.0,\"multiplier\":1.0,\"exponent\":1.0,\"cacheSize\":0},\"zoom\":5.0,"
+ "\"palette\":[{\"block\":\"minecraft:stone_bricks\",\"debug\":false,\"weight\":2,"
+ "\"data\":{\"waterlogged\":false},\"tileData\":{}}]},\"spacing\":4,\"supportNonOccluding\":true}";
String terrain = "{\"mode\":\"FORCE_CARVE\",\"horizontalPadding\":9,\"ceilingPadding\":3,\"floorPadding\":2,"
+ "\"shape\":\"ERODED\",\"erosionStrength\":0.42,\"erosionFrequency\":0.17,\"lobeFrequency\":0.03,"
+ "\"lobeStrength\":0.61}";
ByteArrayOutputStream encoded = new ByteArrayOutputStream();
new NativeStructureOwnershipRecord.MemoSnapshot(stilts, terrain).write(new DataOutputStream(encoded));
NativeStructureOwnershipRecord.DecisionSnapshot snapshot =
NativeStructureOwnershipRecord.DecisionSnapshot.capture(source);
terrain.setHorizontalPadding(1);
stilt.setMaxDepth(2);
IrisNativeStructureDecision restored = snapshot.restore();
NativeStartMemo memo = NativeStructureOwnershipRecord.MemoSnapshot.read(
new DataInputStream(new ByteArrayInputStream(encoded.toByteArray()))).restore();
NativeStructureFit fit = NativeStructureFit.of(new StartMemo(memo.terrain(), memo.foundation()));
assertTrue(restored.generate());
assertEquals(IrisStructureTerrainMode.FORCE_CARVE, restored.terrain().resolvedMode());
assertEquals(IrisStructureCarveShape.ERODED, restored.terrain().resolvedShape());
assertEquals(9, restored.terrain().getHorizontalPadding());
assertEquals(0.42D, restored.terrain().getErosionStrength(), 0D);
assertNotNull(restored.stilt());
assertEquals(91, restored.stilt().getMaxDepth());
assertEquals(4, restored.stilt().getSpacing());
assertTrue(restored.stilt().isSupportNonOccluding());
assertEquals(StructureTerrainMode.FORCE_CARVE, fit.terrain().resolvedMode());
assertEquals(StructureCarveShape.ERODED, fit.terrain().resolvedShape());
assertEquals(9, fit.terrain().horizontalPadding());
assertEquals(0.42D, fit.terrain().resolvedErosionStrength(), 0D);
assertEquals(0.61D, fit.terrain().resolvedLobeStrength(), 0D);
assertEquals(91, fit.stilts().maxDepth());
assertEquals(4, fit.stilts().spacing());
assertTrue(fit.stilts().supportNonOccluding());
assertEquals("minecraft:stone_bricks", fit.stilts().palette().orElseThrow().palette().getFirst().block());
assertEquals(2, fit.stilts().palette().orElseThrow().palette().getFirst().weight());
}
@Test
public void aStartWithoutAMemoRoundTripsWithoutOne() throws Exception {
ByteArrayOutputStream encoded = new ByteArrayOutputStream();
NativeStructureOwnershipRecord.MemoSnapshot.of(null).write(new DataOutputStream(encoded));
assertNull(NativeStructureOwnershipRecord.MemoSnapshot.read(
new DataInputStream(new ByteArrayInputStream(encoded.toByteArray()))).restore());
}
@Test
@@ -120,7 +114,7 @@ public class NativeStructureOwnershipRecordTest {
assertEquals(original.contentMaxZ(), refreshed.contentMaxZ());
assertEquals(original.locatorY(), refreshed.locatorY());
assertEquals(original.contentFingerprint(), refreshed.contentFingerprint());
assertEquals(original.decision(), refreshed.decision());
assertEquals(original.memo(), refreshed.memo());
assertEquals(-6, refreshed.referenceMinChunkX());
assertEquals(0, refreshed.referenceMaxChunkX());
assertEquals(6, refreshed.referenceMinChunkZ());
@@ -184,8 +178,8 @@ public class NativeStructureOwnershipRecordTest {
Map<NativeStructureOwnershipRecord.OwnershipKey, NativeStructureOwnershipRecord> oversized =
new LinkedHashMap<>();
NativeStructureOwnershipRecord.DecisionSnapshot largeDecision =
new NativeStructureOwnershipRecord.DecisionSnapshot(
NativeStructureOwnershipRecord.MemoSnapshot largeDecision =
new NativeStructureOwnershipRecord.MemoSnapshot(
"null",
"{\"unused\":\"" + "x".repeat(65_000) + "\"}"
);
@@ -298,7 +292,8 @@ public class NativeStructureOwnershipRecordTest {
@Test
public void nullableStiltRoundTripsAsNull() {
NativeStructureOwnershipRecord record = record("test:no_stilt", 0, 0, 1L);
assertNull(record.restoredDecision().stilt());
NativeStartMemo memo = record.restoredMemo();
assertNull(NativeStructureFit.of(new StartMemo(memo.terrain(), memo.foundation())).stilts());
}
@Test
@@ -369,15 +364,8 @@ public class NativeStructureOwnershipRecordTest {
);
}
private static NativeStructureOwnershipRecord.DecisionSnapshot decision() {
return NativeStructureOwnershipRecord.DecisionSnapshot.capture(
new IrisNativeStructureDecision(
NativeStructureGenerationStatus.GENERATE_NATIVE,
0,
null,
false,
null,
new IrisStructureTerrain()
));
private static NativeStructureOwnershipRecord.MemoSnapshot decision() {
StartMemo memo = NativeStructureFit.NONE.memo();
return NativeStructureOwnershipRecord.MemoSnapshot.of(new NativeStartMemo(memo.terrain(), memo.foundation()));
}
}
@@ -1,8 +1,5 @@
package art.arcane.iris.engine.framework;
import art.arcane.iris.engine.object.structure.vanilla.IrisNativeStructureDecision;
import art.arcane.iris.engine.object.structure.IrisStructureTerrain;
import art.arcane.iris.engine.object.structure.vanilla.NativeStructureGenerationStatus;
import org.junit.Test;
import java.util.Map;
@@ -49,9 +46,9 @@ public class NativeStructureOwnershipStoreTest {
Engine engine = engine();
TestStorage storage = new TestStorage();
NativeStructureOwnershipRecord stale = record("test:replacement", 2, 3, 11L,
new IrisStructureTerrain().setHorizontalPadding(2), 8);
terrain(2), 8);
NativeStructureOwnershipRecord current = record("test:replacement", 2, 3, 11L,
new IrisStructureTerrain().setHorizontalPadding(9), 8);
terrain(9), 8);
long origin = NativeStructureOwnershipStore.pack(2, 3);
long target = NativeStructureOwnershipStore.pack(3, 4);
storage.write(origin, current);
@@ -63,7 +60,7 @@ public class NativeStructureOwnershipStoreTest {
3, 4, current.structureKey(), 2, 3);
assertEquals(current, resolved);
assertEquals(9, resolved.restoredDecision().terrain().getHorizontalPadding());
assertEquals(terrain(9), resolved.restoredMemo().terrain());
assertEquals(stale.contentFingerprint(), resolved.contentFingerprint());
assertEquals(stale, storage.find(target, stale));
}
@@ -409,18 +406,18 @@ public class NativeStructureOwnershipStoreTest {
private static NativeStructureOwnershipRecord record(String key, int originX, int originZ,
long placementIdentity) {
return record(key, originX, originZ, placementIdentity, new IrisStructureTerrain(), 8);
return record(key, originX, originZ, placementIdentity, "{}", 8);
}
private static NativeStructureOwnershipRecord record(String key, int originX, int originZ,
long placementIdentity,
int referenceRadius) {
return record(key, originX, originZ, placementIdentity, new IrisStructureTerrain(), referenceRadius);
return record(key, originX, originZ, placementIdentity, "{}", referenceRadius);
}
private static NativeStructureOwnershipRecord record(String key, int originX, int originZ,
long placementIdentity,
IrisStructureTerrain terrain,
String terrain,
int referenceRadius) {
return new NativeStructureOwnershipRecord(
NativeStructureOwnershipRecord.CURRENT_SCHEMA,
@@ -441,18 +438,14 @@ public class NativeStructureOwnershipStoreTest {
originZ - referenceRadius,
originZ + referenceRadius,
FINGERPRINT,
NativeStructureOwnershipRecord.DecisionSnapshot.capture(
new IrisNativeStructureDecision(
NativeStructureGenerationStatus.GENERATE_NATIVE,
0,
null,
false,
null,
terrain
))
new NativeStructureOwnershipRecord.MemoSnapshot("null", terrain)
);
}
private static String terrain(int horizontalPadding) {
return "{\"horizontalPadding\":" + horizontalPadding + "}";
}
private static class TestStorage implements NativeStructureOwnershipStore.Storage {
protected final Map<Long, NativeStructureOwnershipBundle> chunks = new ConcurrentHashMap<>();
protected volatile int flushes;
@@ -3,20 +3,16 @@ package art.arcane.iris.engine.framework;
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.material.IrisMaterialPalette;
import art.arcane.iris.engine.object.structure.IrisStructureCarveShape;
import art.arcane.iris.builtin.structure.StructureStilts;
import art.arcane.iris.builtin.structure.StructureTerrain;
import art.arcane.iris.engine.object.structure.IrisStructurePlacement;
import art.arcane.iris.engine.object.structure.IrisStructureStiltSettings;
import art.arcane.iris.engine.object.structure.IrisStructureTerrain;
import art.arcane.iris.engine.object.structure.IrisStructureTerrainMode;
import art.arcane.iris.engine.object.structure.StructureDistribution;
import art.arcane.iris.engine.object.structure.jigsaw.IrisJigsawConfiguration;
import art.arcane.iris.engine.object.structure.jigsaw.IrisJigsawHeightmap;
import art.arcane.iris.engine.object.structure.vanilla.IrisNativeStructure;
import art.arcane.iris.engine.object.world.dimension.IrisDimension;
import art.arcane.volmlib.util.collection.KList;
import com.google.gson.Gson;
import com.volmit.host.LoadedPack;
import com.volmit.vanilla.JigsawOverrides;
import org.junit.After;
import org.junit.Rule;
import org.junit.Test;
@@ -133,13 +129,13 @@ public class NativeStructureStartsTest {
@Test
public void fitsAndJigsawOverridesReachThePlatformWithTheirJsonUnchanged() throws IOException {
IrisStructureTerrain terrain = new IrisStructureTerrain().setMode(IrisStructureTerrainMode.FORCE_CARVE)
.setShape(IrisStructureCarveShape.ERODED).setHorizontalPadding(12).setErosionStrength(0.4D)
.setEncasePalette(new IrisMaterialPalette().qclear().qadd("minecraft:deepslate").qadd("minecraft:tuff"));
IrisStructureStiltSettings stilt = new IrisStructureStiltSettings().setMaxDepth(40).setSpacing(2)
.setPalette(new IrisMaterialPalette().qclear().qadd("minecraft:stone_bricks"));
IrisJigsawConfiguration jigsaw = new IrisJigsawConfiguration().setStartPool("minecraft:village/plains/town_centers")
.setMaxDepth(5).setProjectStartToHeightmap(IrisJigsawHeightmap.OCEAN_FLOOR_WG).setUseExpansionHack(false);
StructureTerrain terrain = GSON.fromJson("{\"mode\":\"FORCE_CARVE\",\"shape\":\"ERODED\",\"horizontalPadding\":12,"
+ "\"erosionStrength\":0.4,\"encasePalette\":{\"palette\":[{\"block\":\"minecraft:deepslate\"},"
+ "{\"block\":\"minecraft:tuff\"}]}}", StructureTerrain.class);
StructureStilts stilt = GSON.fromJson("{\"maxDepth\":40,\"spacing\":2,"
+ "\"palette\":{\"palette\":[{\"block\":\"minecraft:stone_bricks\"}]}}", StructureStilts.class);
JigsawOverrides jigsaw = JigsawOverrides.none().withStartPool("minecraft:village/plains/town_centers")
.withMaxDepth(5).withHeightmap(JigsawOverrides.Heightmap.OCEAN_FLOOR_WG).withExpansionHack(false);
IrisStructurePlacement fitted = placement("fitted", true, -40, -20, 1D, source("minecraft:ancient_city", 1)
.setJigsaw(jigsaw)).setTerrain(terrain).setStilt(stilt);
KList<IrisStructurePlacement> placements = new KList<>();
@@ -148,11 +144,10 @@ public class NativeStructureStartsTest {
NativeStructureStartPlan plan = NativeStructureStarts.matchingPlan(engine, "MINECRAFT:ANCIENT_CITY", 0, 0);
assertEquals(GSON.toJson(terrain), GSON.toJson(plan.terrain()));
assertEquals(GSON.toJson(stilt), GSON.toJson(plan.stilt()));
assertEquals(GSON.toJson(jigsaw), GSON.toJson(plan.jigsaw()));
assertEquals(GSON.toJson(new NativeStructureStartPlan(plan.structureKey(), 0, 0, plan.baseY(), true, false,
StructurePlacementGrid.placementIdentity(fitted), jigsaw, stilt, terrain).decision()), GSON.toJson(plan.decision()));
assertEquals(new NativeStartMemo(GSON.toJson(terrain), GSON.toJson(stilt)), plan.memo());
assertEquals(new NativeJigsawOverrides("minecraft:village/plains/town_centers", "", 5, null, null, false,
"OCEAN_FLOOR_WG", null, null, NativeJigsawOverrides.SOURCE), plan.jigsaw());
assertEquals(StructurePlacementGrid.placementIdentity(fitted), plan.placementIdentity());
assertNull(NativeStructureStarts.matchingPlan(engine, "minecraft:stronghold", 0, 0));
}
@@ -4,7 +4,6 @@ import art.arcane.iris.builtin.structure.StructureSettings;
import art.arcane.iris.core.loader.IrisData;
import art.arcane.iris.core.modules.BuiltInPack;
import art.arcane.iris.engine.object.world.dimension.IrisDimension;
import art.arcane.iris.engine.object.structure.IrisStructureTerrain;
import art.arcane.volmlib.util.collection.KList;
import com.volmit.host.LoadedPack;
import org.junit.After;
@@ -41,9 +40,9 @@ public class NativeStructureVolumeSuppressionTest {
Engine engine = engine();
assertFalse(NativeStructureGenerationPolicy
.resolve(engine, "minecraft:village_swamp", false).generate());
.generates(engine, "minecraft:village_swamp"));
assertFalse(NativeStructureGenerationPolicy
.resolve(engine, "minecraft:village_plains", false).generate());
.generates(engine, "minecraft:village_plains"));
}
@Test
@@ -51,15 +50,7 @@ public class NativeStructureVolumeSuppressionTest {
Engine engine = engine();
assertTrue(NativeStructureGenerationPolicy
.resolve(engine, "towns_and_towers:village_swamp", false).generate());
}
@Test
public void plannedModuleStartsContributeVolumesThroughTheirOwnDecision() {
NativeStructureStartPlan plan = new NativeStructureStartPlan("minecraft:ancient_city", 3, 5, -30, true, false, 7L,
null, null, new IrisStructureTerrain());
assertTrue(plan.decision().generate());
.generates(engine, "towns_and_towers:village_swamp"));
}
private Engine engine() throws IOException {
@@ -3,26 +3,24 @@ package art.arcane.iris.engine.framework.structure;
import art.arcane.iris.builtin.structure.StructureAdjustment;
import art.arcane.iris.builtin.structure.StructureSetFrequency;
import art.arcane.iris.builtin.structure.StructureSettings;
import com.volmit.block.BlockSpec;
import com.volmit.block.PaletteSpec;
import art.arcane.iris.builtin.structure.StructureStilts;
import art.arcane.iris.builtin.structure.StructureTerrain;
import art.arcane.iris.builtin.structure.StructureTerrainMode;
import art.arcane.iris.builtin.structure.StructureYBand;
import com.volmit.resource.ResourceId;
import com.volmit.vanilla.StructureStilts;
import com.volmit.vanilla.StructureTerrain;
import com.volmit.vanilla.VanillaStructureAdjustment;
import com.volmit.vanilla.YBand;
import com.google.gson.Gson;
import org.junit.Test;
import java.util.List;
import java.util.Optional;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertTrue;
/** What a dimension's iris:structure settings say about the platform's own structures (was IrisImportedStructureControlTest). */
public class ImportedStructuresTest {
private static final StructureStilts COBBLE = StructureStilts.of(PaletteSpec.of(List.of(BlockSpec.of("minecraft:cobblestone"))));
private static final Gson JSON = new Gson();
@Test
public void defaultSettingsGenerateEveryStructureAndChangeNothing() {
@@ -30,7 +28,7 @@ public class ImportedStructuresTest {
assertFalse(defaults.disables("minecraft:village_plains"));
assertFalse(defaults.disables("nova_structures:desert_temple"));
assertEquals(VanillaStructureAdjustment.NONE, defaults.adjustment("minecraft:stronghold", true));
assertEquals(NativeStructureFit.NONE, defaults.adjustment("minecraft:stronghold", true));
assertEquals(1D, defaults.setup().frequency(ResourceId.parse("minecraft:villages")), 0D);
assertFalse(defaults.setup().protectsVanillaDefinitions());
}
@@ -95,31 +93,31 @@ public class ImportedStructuresTest {
@Test
public void theLastMatchingTerrainBandAndStiltWin() {
StructureTerrain encase = StructureTerrain.of(StructureTerrain.Mode.ENCASE).withPadding(4, 0, 0);
StructureStilts deep = COBBLE.withMaxDepth(96);
StructureTerrain encase = terrain("{\"mode\":\"ENCASE\",\"horizontalPadding\":4}");
StructureStilts deep = stilts(96);
StructureYBand band = JSON.fromJson("{\"min\":-120,\"max\":-20}", StructureYBand.class);
ImportedStructures imported = imported(settings(List.of(), List.of(), 0, true, List.of(), List.of(
adjustment(List.of("minecraft:stronghold"), 0, null, false, COBBLE.withMaxDepth(32),
StructureTerrain.of(StructureTerrain.Mode.SOURCE)),
adjustment(List.of("minecraft:stronghold"), 0, YBand.of(-120, -20), false, null, encase),
adjustment(List.of("minecraft:stronghold"), 0, null, false, stilts(32), terrain("{\"mode\":\"SOURCE\"}")),
adjustment(List.of("minecraft:stronghold"), 0, band, false, null, encase),
adjustment(List.of("minecraft:stronghold"), 0, null, false, deep, null))));
VanillaStructureAdjustment stronghold = imported.adjustment("minecraft:stronghold", true);
assertEquals(Optional.of(encase), stronghold.fit().terrain());
assertEquals(Optional.of(deep), stronghold.fit().stilts());
assertEquals(Optional.of(YBand.of(-120, -20)), stronghold.yBand());
assertEquals(VanillaStructureAdjustment.NONE, imported.adjustment("minecraft:trial_chambers", true));
NativeStructureFit stronghold = imported.adjustment("minecraft:stronghold", true);
assertSame(encase, stronghold.terrain());
assertSame(deep, stronghold.stilts());
assertSame(band, stronghold.yBand());
assertEquals(NativeStructureFit.NONE, imported.adjustment("minecraft:trial_chambers", true));
}
@Test
public void aLaterSpecificAdjustmentOverridesANamespaceTerrain() {
ImportedStructures imported = imported(settings(List.of(), List.of(), 0, true, List.of(), List.of(
adjustment(List.of("towns_and_towers:"), 0, null, false, null, StructureTerrain.of(StructureTerrain.Mode.VACUUM)),
adjustment(List.of("towns_and_towers:"), 0, null, false, null, terrain("{\"mode\":\"VACUUM\"}")),
adjustment(List.of("towns_and_towers:village_ocean", "towns_and_towers:mimic_desert"), 0, null, false, null,
StructureTerrain.of(StructureTerrain.Mode.PRESERVE)))));
terrain("{\"mode\":\"PRESERVE\"}")))));
assertEquals(StructureTerrain.Mode.VACUUM, mode(imported, "towns_and_towers:village_forest"));
assertEquals(StructureTerrain.Mode.PRESERVE, mode(imported, "towns_and_towers:village_ocean"));
assertEquals(StructureTerrain.Mode.PRESERVE, mode(imported, "towns_and_towers:mimic_desert"));
assertEquals(StructureTerrainMode.VACUUM, mode(imported, "towns_and_towers:village_forest"));
assertEquals(StructureTerrainMode.PRESERVE, mode(imported, "towns_and_towers:village_ocean"));
assertEquals(StructureTerrainMode.PRESERVE, mode(imported, "towns_and_towers:mimic_desert"));
}
@Test
@@ -127,7 +125,7 @@ public class ImportedStructuresTest {
ImportedStructures imported = imported(settings(List.of(), List.of(), -64, true, List.of(), List.of(
adjustment(List.of("minecraft:mineshaft"), 4, null, true, null, null))));
VanillaStructureAdjustment mesa = imported.adjustment("minecraft:mineshaft_mesa", true);
NativeStructureFit mesa = imported.adjustment("minecraft:mineshaft_mesa", true);
assertTrue(mesa.keepsSourceY());
assertEquals(-60, mesa.yShift());
assertFalse(imported.adjustment("minecraft:stronghold", true).keepsSourceY());
@@ -141,12 +139,20 @@ public class ImportedStructuresTest {
ImportedStructures imported = imported(nulls);
assertFalse(imported.disables("minecraft:monument"));
assertEquals(VanillaStructureAdjustment.NONE, imported.adjustment("minecraft:monument", false));
assertEquals(NativeStructureFit.NONE, imported.adjustment("minecraft:monument", false));
assertTrue(imported.setup().frequencies().isEmpty());
}
private static StructureTerrain.Mode mode(ImportedStructures imported, String key) {
return imported.adjustment(key, false).fit().terrain().orElseThrow().mode();
private static StructureTerrainMode mode(ImportedStructures imported, String key) {
return imported.adjustment(key, false).terrain().resolvedMode();
}
private static StructureTerrain terrain(String json) {
return JSON.fromJson(json, StructureTerrain.class);
}
private static StructureStilts stilts(int maxDepth) {
return JSON.fromJson("{\"maxDepth\":" + maxDepth + "}", StructureStilts.class);
}
private static ImportedStructures imported(StructureSettings settings) {
@@ -159,7 +165,7 @@ public class ImportedStructuresTest {
return new StructureSettings(disabled, disabledExact, undergroundYShift, datapackOverrides, frequencies, adjustments);
}
private static StructureAdjustment adjustment(List<String> match, int yShift, YBand band, boolean preserveSourceY,
private static StructureAdjustment adjustment(List<String> match, int yShift, StructureYBand band, boolean preserveSourceY,
StructureStilts stilt, StructureTerrain terrain) {
return new StructureAdjustment(match, yShift, band, preserveSourceY, stilt, terrain);
}
@@ -3,11 +3,13 @@ package art.arcane.iris.engine.framework.structure;
import art.arcane.iris.engine.framework.Engine;
import art.arcane.iris.engine.framework.SeedManager;
import art.arcane.iris.engine.framework.StructurePlacementGrid;
import art.arcane.iris.engine.object.structure.IrisStructureStiltSettings;
import art.arcane.iris.engine.object.structure.jigsaw.IrisJigsawConfiguration;
import art.arcane.iris.builtin.structure.StructureStilts;
import art.arcane.iris.builtin.structure.StructureTerrain;
import art.arcane.iris.builtin.structure.StructureTerrainMode;
import com.google.gson.Gson;
import com.volmit.vanilla.JigsawOverrides;
import art.arcane.iris.engine.object.structure.vanilla.NativeStructureSuppression;
import com.volmit.resource.ResourceId;
import com.volmit.vanilla.StructureTerrain;
import com.volmit.vanilla.VanillaStructureStart;
import java.util.List;
import java.util.Optional;
@@ -17,8 +19,6 @@ import art.arcane.iris.engine.object.structure.vanilla.IrisNativeStructure;
import art.arcane.iris.engine.object.world.dimension.IrisDimension;
import art.arcane.iris.engine.object.structure.IrisStructureAnchorMode;
import art.arcane.iris.engine.object.structure.IrisStructurePlacement;
import art.arcane.iris.engine.object.structure.IrisStructureTerrain;
import art.arcane.iris.engine.object.structure.IrisStructureTerrainMode;
import art.arcane.iris.engine.object.structure.StructureDistribution;
import art.arcane.volmlib.util.collection.KList;
import art.arcane.volmlib.util.math.RNG;
@@ -83,31 +83,31 @@ public class NativeStartPlannerTest {
@Test
public void aPlanBecomesAStartWithHeightsAboveTheBottomAndThePlacementsFitAndIdentity() {
IrisStructureTerrain terrain = new IrisStructureTerrain()
.setMode(IrisStructureTerrainMode.FORCE_CARVE)
.setHorizontalPadding(24);
Gson json = new Gson();
StructureTerrain terrain = json.fromJson("{\"mode\":\"FORCE_CARVE\",\"horizontalPadding\":24}", StructureTerrain.class);
IrisStructurePlacement placement = nativePlacement()
.setUnderground(true)
.setNativeSuppression(NativeStructureSuppression.REPLACE_SOURCE)
.setTerrain(terrain)
.setStilt(new IrisStructureStiltSettings().setSpacing(3));
placement.getNativeStructures().getFirst().setJigsaw(new IrisJigsawConfiguration().setMaxDepth(4));
.setStilt(json.fromJson("{\"spacing\":3}", StructureStilts.class));
placement.getNativeStructures().getFirst().setJigsaw(JigsawOverrides.none().withMaxDepth(4));
NativeStartPlanner.Plan plan = new NativeStartPlanner.Plan(
placement, placement.getNativeStructures().getFirst(), 3, 5, -30);
VanillaStructureStart start = StructureVanillaHook.start(plan, -64);
VanillaStructureStart start = StructureVanillaStructures.start(plan, -64);
assertEquals(ResourceId.parse("minecraft:ancient_city"), start.structure());
assertEquals(34, start.y());
assertTrue(start.isUnderground());
assertTrue(start.replacesPlatformStart());
assertEquals(StructurePlacementGrid.placementIdentity(placement), start.identity());
assertEquals(StructureTerrain.Mode.FORCE_CARVE, start.fit().terrain().orElseThrow().mode());
assertEquals(24, start.fit().terrain().orElseThrow().horizontalPadding());
assertEquals(3, start.fit().stilts().orElseThrow().spacing());
NativeStructureFit fit = NativeStructureFit.of(start.memo().orElseThrow());
assertEquals(StructureTerrainMode.FORCE_CARVE, fit.terrain().resolvedMode());
assertEquals(24, fit.terrain().horizontalPadding());
assertEquals(3, fit.stilts().spacing());
assertEquals(OptionalInt.of(4), start.jigsaw().orElseThrow().maxDepth());
assertEquals("a source without jigsaw overrides has none", Optional.empty(),
StructureVanillaHook.start(new NativeStartPlanner.Plan(nativePlacement(),
StructureVanillaStructures.start(new NativeStartPlanner.Plan(nativePlacement(),
nativePlacement().getNativeStructures().getFirst(), 0, 0, 70), -64).jigsaw());
}
@@ -0,0 +1,300 @@
package art.arcane.iris.engine.framework.structure.fit;
import art.arcane.iris.engine.framework.structure.NativeStructureFit;
import com.google.gson.Gson;
import com.volmit.block.BlockFace;
import com.volmit.block.BlockState;
import com.volmit.block.BlockTrait;
import com.volmit.mantle.BlockBox;
import com.volmit.resource.ResourceId;
import com.volmit.vanilla.PieceKind;
import com.volmit.vanilla.StartMemo;
import com.volmit.vanilla.StructureFit;
import com.volmit.vanilla.StructureStep;
import com.volmit.vanilla.TemplateCells;
import com.volmit.vanilla.TerrainAdaptation;
import com.volmit.world.BlockAccess;
import com.volmit.world.BlockPosition;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
/**
* Structure fit components outside a platform: an in-memory world in world heights whose block answers follow the
* platform's for the blocks the tests use, and pieces whose template cells the test states the way the platform would
* process them.
*/
final class FitFixture {
static final int BOTTOM_Y = -64;
static final int TOP_Y = 320;
static final BlockState AIR = state("air");
static final BlockState STONE = state("stone");
static final BlockState DIRT = state("dirt");
static final BlockState GRASS = state("grass_block");
static final BlockState COBBLESTONE = state("cobblestone");
static final BlockState WATER = state("water");
static final BlockState OAK_LOG = state("oak_log");
static final BlockState OAK_LEAVES = state("oak_leaves");
private static final Gson JSON = new Gson();
private static final Set<String> NOT_SOLID = Set.of("air", "cave_air", "water", "lava", "short_grass", "dandelion",
"structure_void", "vine", "sculk_vein");
private static final Map<String, Set<String>> TAGS = Map.of(
"minecraft:logs", Set.of("oak_log", "spruce_log", "oak_wood"),
"minecraft:leaves", Set.of("oak_leaves", "spruce_leaves"),
"minecraft:base_stone_overworld", Set.of("stone", "deepslate", "tuff", "granite", "diorite", "andesite"),
"minecraft:dirt", Set.of("dirt", "grass_block", "podzol", "coarse_dirt"),
"minecraft:sand", Set.of("sand", "red_sand"));
private FitFixture() {
}
static BlockState state(String path) {
return new BlockState("minecraft:" + path);
}
/** A world of blocks keyed by world position, air where nothing is set. */
static final class World implements BlockAccess {
private final Map<BlockPosition, BlockState> blocks = new HashMap<>();
private final Box bounds;
World(Box columns) {
this.bounds = new Box(columns.minX(), BOTTOM_Y, columns.minZ(), columns.maxX(), TOP_Y - 1, columns.maxZ());
}
void put(int x, int y, int z, BlockState state) {
blocks.put(new BlockPosition(x, y, z), state);
}
BlockState at(int x, int y, int z) {
return blocks.getOrDefault(new BlockPosition(x, y, z), AIR);
}
Map<BlockPosition, BlockState> snapshot() {
return Map.copyOf(blocks);
}
/** Grass at {@code surfaceY} over a dirt layer, in every column of {@code area}. */
World flat(Box area, int surfaceY) {
for (int x = area.minX(); x <= area.maxX(); x++) {
for (int z = area.minZ(); z <= area.maxZ(); z++) {
put(x, surfaceY - 1, z, DIRT);
put(x, surfaceY, z, GRASS);
}
}
return this;
}
FitBlocks fitBlocks() {
return new FitBlocks(this, BOTTOM_Y);
}
@Override
public BlockBox bounds() {
return bounds.toApi(BOTTOM_Y);
}
@Override
public BlockState get(int x, int y, int z) {
return at(x, y + BOTTOM_Y, z);
}
@Override
public void column(int x, int z, int fromY, BlockState[] into) {
for (int index = 0; index < into.length; index++) {
into[index] = get(x, fromY + index, z);
}
}
@Override
public void set(int x, int y, int z, BlockState state) {
put(x, y + BOTTOM_Y, z, state);
}
@Override
public boolean is(BlockState state, BlockTrait trait) {
String path = state.material().path();
return switch (trait) {
case AIR -> path.endsWith("air");
case SOLID -> !NOT_SOLID.contains(path);
case FLUID -> path.equals("water") || path.equals("lava")
|| "true".equals(state.properties().get("waterlogged"));
case LOG -> path.endsWith("_log") || path.endsWith("_wood") || path.endsWith("_stem");
case LEAVES -> path.endsWith("_leaves");
default -> throw new UnsupportedOperationException(trait.name());
};
}
@Override
public boolean inTag(BlockState state, ResourceId tag) {
return TAGS.getOrDefault(tag.toString(), Set.of()).contains(state.material().path());
}
@Override
public boolean sturdy(int x, int y, int z, BlockFace face) {
BlockState state = get(x, y, z);
return is(state, BlockTrait.SOLID) && !is(state, BlockTrait.LEAVES);
}
@Override
public BlockState fluid(BlockState state) {
return is(state, BlockTrait.FLUID) ? WATER : AIR;
}
}
/** A piece; its cells are the processed template blocks the test states (null for a block a processor removed). */
static final class Piece implements StructureFit.Piece {
private final Box box;
private final PieceKind kind;
private final int groundLevelDelta;
private final List<BlockPosition> junctions = new ArrayList<>();
private final List<Cell> cells = new ArrayList<>();
private final List<BlockPosition> legacyAir = new ArrayList<>();
private boolean template;
Piece(Box box, PieceKind kind, int groundLevelDelta) {
this.box = box;
this.kind = kind;
this.groundLevelDelta = groundLevelDelta;
}
static Piece rigid(Box box, int groundLevelDelta) {
return new Piece(box, PieceKind.RIGID, groundLevelDelta);
}
static Piece fixed(Box box) {
return new Piece(box, PieceKind.FIXED, 0);
}
Piece cell(int x, int y, int z, BlockState state) {
template = true;
cells.add(new Cell(x, y, z, state));
return this;
}
Piece junction(int x, int groundY, int z) {
junctions.add(new BlockPosition(x, groundY - BOTTOM_Y, z));
return this;
}
Piece legacyAir(int x, int y, int z) {
legacyAir.add(new BlockPosition(x, y - BOTTOM_Y, z));
return this;
}
@Override
public BlockBox box() {
return box.toApi(BOTTOM_Y);
}
@Override
public PieceKind kind() {
return kind;
}
@Override
public int groundLevelDelta() {
return groundLevelDelta;
}
@Override
public List<BlockPosition> junctions() {
return List.copyOf(junctions);
}
@Override
public TemplateCells cells(BlockBox region) {
if (!template) {
return TemplateCells.UNRESOLVED;
}
Box worldRegion = Box.of(region, BOTTOM_Y);
List<Cell> inside = cells.stream().filter(cell -> worldRegion.contains(cell.x(), cell.y(), cell.z())).toList();
int[] xs = inside.stream().mapToInt(Cell::x).toArray();
int[] ys = inside.stream().mapToInt(cell -> cell.y() - BOTTOM_Y).toArray();
int[] zs = inside.stream().mapToInt(Cell::z).toArray();
BlockState[] states = inside.stream().map(Cell::state).toArray(BlockState[]::new);
return TemplateCells.of(xs, ys, zs, states, cells.size() * 2);
}
@Override
public void columns(StructureFit.ColumnVisitor visitor) {
for (int z = box.minZ(); z <= box.maxZ(); z++) {
for (int x = box.minX(); x <= box.maxX(); x++) {
visitor.column(x, z, box.minY() - BOTTOM_Y, box.maxY() - BOTTOM_Y);
}
}
}
@Override
public List<BlockPosition> legacyAir(BlockBox clip) {
Box worldClip = Box.of(clip, BOTTOM_Y);
return legacyAir.stream()
.filter(air -> worldClip.contains(air.x(), air.y() + BOTTOM_Y, air.z()))
.toList();
}
}
private record Cell(int x, int y, int z, BlockState state) {
}
/** 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) {
return start(terrainJson, "null", adaptation, step, pieces);
}
static FitStart start(String terrainJson, String stiltsJson, TerrainAdaptation adaptation, StructureStep step,
Piece... pieces) {
StartMemo memo = new StartMemo(terrainJson, stiltsJson);
StructureFit.Start start = new StructureFit.Start() {
private final Object key = new Object();
@Override
public ResourceId structure() {
return ResourceId.parse("test:structure");
}
@Override
public int chunkX() {
return 0;
}
@Override
public int chunkZ() {
return 0;
}
@Override
public StructureStep step() {
return step;
}
@Override
public TerrainAdaptation adaptation() {
return adaptation;
}
@Override
public Optional<StartMemo> memo() {
return Optional.of(memo);
}
@Override
public List<StructureFit.Piece> pieces() {
return List.of(pieces);
}
@Override
public Object key() {
return key;
}
};
return new FitStart(start, NativeStructureFit.of(memo), BOTTOM_Y);
}
static String json(Object value) {
return JSON.toJson(value);
}
}
@@ -0,0 +1,33 @@
package art.arcane.iris.engine.framework.structure.fit;
import org.junit.Test;
import static art.arcane.iris.engine.framework.structure.fit.FitFixture.BOTTOM_Y;
import static art.arcane.iris.engine.framework.structure.fit.FitFixture.state;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
public class FoundationStiltsTest {
private static final Box COLUMN = new Box(0, 0, 0, 0, 0, 0);
@Test
public void sparseStiltGridIsDeterministic() {
assertTrue(FoundationStilts.isStiltColumn(0, 0, 4));
assertTrue(FoundationStilts.isStiltColumn(-4, 8, 4));
assertFalse(FoundationStilts.isStiltColumn(1, 0, 4));
assertTrue(FoundationStilts.isStiltColumn(1, 1, 1));
}
@Test
public void stiltsOnlyAnchorOnSturdyGroundWithinTheirDepth() {
FitFixture.World world = new FitFixture.World(COLUMN);
world.put(0, 7, 0, state("deepslate"));
world.put(0, 8, 0, state("sculk_vein"));
assertEquals(7, FoundationStilts.findStiltAnchorY(world.fitBlocks(), 0, 0, 10, 2, BOTTOM_Y, BOTTOM_Y));
assertEquals(Integer.MIN_VALUE, FoundationStilts.findStiltAnchorY(world.fitBlocks(), 0, 0, 10, 1, BOTTOM_Y, BOTTOM_Y));
assertEquals(Integer.MIN_VALUE, FoundationStilts.findStiltAnchorY(
new FitFixture.World(COLUMN).fitBlocks(), 0, 0, 10, 64, BOTTOM_Y, BOTTOM_Y));
}
}
@@ -0,0 +1,198 @@
package art.arcane.iris.engine.framework.structure.fit;
import com.volmit.block.BlockState;
import com.volmit.vanilla.StructureStep;
import com.volmit.vanilla.TerrainAdaptation;
import org.junit.Test;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import static art.arcane.iris.engine.framework.structure.fit.FitFixture.AIR;
import static art.arcane.iris.engine.framework.structure.fit.FitFixture.COBBLESTONE;
import static art.arcane.iris.engine.framework.structure.fit.FitFixture.DIRT;
import static art.arcane.iris.engine.framework.structure.fit.FitFixture.GRASS;
import static art.arcane.iris.engine.framework.structure.fit.FitFixture.WATER;
import static art.arcane.iris.engine.framework.structure.fit.FitFixture.state;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
/**
* The support bridged between two rigid pieces of one surface start whose ground planes are two blocks apart. Each
* test states the template cells the platform would process for the pieces.
*/
public class RigidSupportTest {
private static final String SOURCE = "{\"mode\":\"SOURCE\"}";
private static final String VACUUM = "{\"mode\":\"VACUUM\"}";
private static final String PRESERVE = "{\"mode\":\"PRESERVE\"}";
@Test
public void upperOccupancyIsSupportedOverTheLowerPiecesGround() {
Box area = new Box(0, 58, 0, 1, 72, 0);
FitFixture.World world = supportTerrain(area);
world.put(1, 63, 0, DIRT);
FitStart start = beard(lower(0, 1, AIR), upper(0, 1, 64, COBBLESTONE));
Set<Long> written = RigidSupport.bridgeRigidPieceSupport(world.fitBlocks(), area, List.of(start));
assertEquals(Set.of(TemplateFootprint.packedPosition(0, 63, 0)), written);
assertEquals(DIRT, world.at(0, 63, 0));
assertEquals(DIRT, world.at(1, 63, 0));
}
@Test
public void lowestAirVoidFluidAndRemovedCellsVetoSupport() {
Box area = new Box(0, 58, 0, 4, 72, 0);
FitFixture.World world = supportTerrain(area);
FitFixture.Piece upper = FitFixture.Piece.rigid(new Box(0, 64, 0, 4, 70, 0), 1)
.cell(0, 64, 0, COBBLESTONE)
.cell(1, 64, 0, AIR)
.cell(2, 64, 0, state("structure_void"))
.cell(3, 64, 0, WATER)
.cell(4, 64, 0, null);
for (int x = 1; x <= 4; x++) {
upper.cell(x, 65, 0, state("stone"));
}
FitStart start = beard(lower(0, 4, AIR), upper);
Set<Long> written = RigidSupport.bridgeRigidPieceSupport(world.fitBlocks(), area, List.of(start));
assertEquals(Set.of(TemplateFootprint.packedPosition(0, 63, 0)), written);
for (int x = 1; x <= 4; x++) {
assertEquals(AIR, world.at(x, 63, 0));
}
}
@Test
public void supportIsChunkClippedAndStableAcrossSplitAreas() {
Box wideArea = new Box(0, 58, 0, 31, 72, 15);
Box westArea = new Box(0, 58, 0, 15, 72, 15);
Box eastArea = new Box(16, 58, 0, 31, 72, 15);
FitFixture.World wide = supportTerrain(new Box(15, 58, 0, 16, 72, 0));
FitFixture.World split = supportTerrain(new Box(15, 58, 0, 16, 72, 0));
FitStart start = beard(lower(15, 16, AIR), upper(15, 16, 64, COBBLESTONE));
Set<Long> wideWritten = RigidSupport.bridgeRigidPieceSupport(wide.fitBlocks(), wideArea, List.of(start));
Set<Long> splitWritten = new HashSet<>(
RigidSupport.bridgeRigidPieceSupport(split.fitBlocks(), westArea, List.of(start)));
assertEquals(AIR, split.at(16, 63, 0));
splitWritten.addAll(RigidSupport.bridgeRigidPieceSupport(split.fitBlocks(), eastArea, List.of(start)));
assertEquals(Set.of(TemplateFootprint.packedPosition(15, 63, 0), TemplateFootprint.packedPosition(16, 63, 0)),
wideWritten);
assertEquals(wideWritten, splitWritten);
assertEquals(wide.snapshot(), split.snapshot());
}
@Test
public void supportNeverPairsRigidAnchorsAcrossStarts() {
Box area = new Box(0, 58, 0, 0, 72, 0);
FitFixture.World world = supportTerrain(area);
assertTrue(RigidSupport.bridgeRigidPieceSupport(world.fitBlocks(), area,
List.of(beard(lower(0, 0, AIR)), beard(upper(0, 0, 64, COBBLESTONE)))).isEmpty());
assertEquals(AIR, world.at(0, 63, 0));
}
@Test
public void vacuumSupportsWithoutAnAuthoredAdaptationButLongMeetGapsStayOpen() {
Box area = new Box(0, 58, 0, 0, 72, 0);
FitFixture.World vacuumWorld = supportTerrain(area);
Set<Long> written = RigidSupport.bridgeRigidPieceSupport(vacuumWorld.fitBlocks(), area,
List.of(start(VACUUM, TerrainAdaptation.NONE, lower(0, 0, AIR), upper(0, 0, 64, COBBLESTONE))));
assertEquals(Set.of(TemplateFootprint.packedPosition(0, 63, 0)), written);
assertTrue(RigidSupport.bridgeRigidPieceSupport(supportTerrain(area).fitBlocks(), area,
List.of(start(SOURCE, TerrainAdaptation.NONE, lower(0, 0, AIR), upper(0, 0, 64, COBBLESTONE)))).isEmpty());
assertTrue(RigidSupport.bridgeRigidPieceSupport(supportTerrain(area).fitBlocks(), area,
List.of(start(VACUUM, TerrainAdaptation.NONE, lower(0, 0, AIR), upper(0, 0, 65, COBBLESTONE)))).isEmpty());
}
@Test
public void threeRigidPlanesCannotBuildAnUpwardSupportChain() {
Box area = new Box(0, 58, 0, 0, 72, 0);
FitFixture.World world = supportTerrain(area);
FitFixture.Piece middle = FitFixture.Piece.rigid(new Box(0, 64, 0, 0, 69, 0), 0).cell(0, 64, 0, COBBLESTONE);
FitFixture.Piece top = FitFixture.Piece.rigid(new Box(0, 65, 0, 0, 70, 0), 0).cell(0, 65, 0, state("stone"));
Set<Long> written = RigidSupport.bridgeRigidPieceSupport(world.fitBlocks(), area,
List.of(beard(lower(0, 0, AIR), middle, top)));
assertEquals(Set.of(TemplateFootprint.packedPosition(0, 63, 0)), written);
assertEquals(DIRT, world.at(0, 63, 0));
assertEquals(AIR, world.at(0, 64, 0));
}
@Test
public void startOrderCannotCreateCrossStartSupportChains() {
Box area = new Box(0, 58, 0, 0, 72, 0);
FitFixture.Piece middle = FitFixture.Piece.rigid(new Box(0, 64, 0, 0, 69, 0), 0).cell(0, 64, 0, COBBLESTONE);
FitFixture.Piece raisedGround = FitFixture.Piece.rigid(new Box(0, 64, 0, 0, 69, 0), 0).cell(0, 64, 0, AIR);
FitFixture.Piece top = FitFixture.Piece.rigid(new Box(0, 65, 0, 0, 70, 0), 0).cell(0, 65, 0, state("stone"));
FitStart lowerStart = beard(lower(0, 0, AIR), middle);
FitStart upperStart = beard(raisedGround, top);
FitFixture.World forward = supportTerrain(area);
FitFixture.World reverse = supportTerrain(area);
Set<Long> forwardWritten = RigidSupport.bridgeRigidPieceSupport(forward.fitBlocks(), area,
List.of(lowerStart, upperStart));
Set<Long> reverseWritten = RigidSupport.bridgeRigidPieceSupport(reverse.fitBlocks(), area,
List.of(upperStart, lowerStart));
assertEquals(Set.of(TemplateFootprint.packedPosition(0, 63, 0)), forwardWritten);
assertEquals(forwardWritten, reverseWritten);
assertEquals(forward.snapshot(), reverse.snapshot());
assertEquals(AIR, forward.at(0, 64, 0));
}
@Test
public void aPreserveDuplicateCannotSuppressVacuumSupport() {
Box area = new Box(0, 58, 0, 0, 72, 0);
FitFixture.World world = supportTerrain(area);
FitFixture.Piece lower = lower(0, 0, AIR);
FitFixture.Piece upper = upper(0, 0, 64, COBBLESTONE);
Set<Long> written = RigidSupport.bridgeRigidPieceSupport(world.fitBlocks(), area, List.of(
start(PRESERVE, TerrainAdaptation.NONE, lower, upper),
start(VACUUM, TerrainAdaptation.NONE, lower, upper)));
assertEquals(Set.of(TemplateFootprint.packedPosition(0, 63, 0)), written);
}
/** A lower rigid piece from {@code minX} to {@code maxX} whose ground (y 62) holds {@code cell}. */
private static FitFixture.Piece lower(int minX, int maxX, BlockState cell) {
FitFixture.Piece piece = FitFixture.Piece.rigid(new Box(minX, 62, 0, maxX, 65, 0), 1);
for (int x = minX; x <= maxX; x++) {
piece.cell(x, 62, 0, cell);
}
return piece;
}
/** An upper rigid piece whose lowest layer, at {@code baseY}, holds {@code cell}; its ground is the layer under it. */
private static FitFixture.Piece upper(int minX, int maxX, int baseY, BlockState cell) {
FitFixture.Piece piece = FitFixture.Piece.rigid(new Box(minX, baseY, 0, maxX, baseY + 6, 0), 1);
for (int x = minX; x <= maxX; x++) {
piece.cell(x, baseY, 0, cell);
}
return piece;
}
private static FitStart beard(FitFixture.Piece... pieces) {
return start(SOURCE, TerrainAdaptation.BEARD_BOX, pieces);
}
private static FitStart start(String terrain, TerrainAdaptation adaptation, FitFixture.Piece... pieces) {
return FitFixture.start(terrain, adaptation, StructureStep.SURFACE_STRUCTURES, pieces);
}
private static FitFixture.World supportTerrain(Box columns) {
FitFixture.World world = new FitFixture.World(columns);
for (int x = columns.minX(); x <= columns.maxX(); x++) {
world.put(x, 61, 0, DIRT);
world.put(x, 62, 0, GRASS);
}
return world;
}
}
@@ -0,0 +1,227 @@
package art.arcane.iris.engine.framework.structure.fit;
import art.arcane.iris.builtin.structure.StructureTerrain;
import art.arcane.iris.builtin.structure.StructureYBand;
import art.arcane.iris.engine.framework.structure.NativeStructureFit;
import com.google.gson.Gson;
import com.volmit.mantle.BlockBox;
import com.volmit.resource.ResourceId;
import com.volmit.vanilla.PlatformStart;
import com.volmit.vanilla.StartReach;
import org.junit.Test;
import java.util.ArrayList;
import java.util.List;
import java.util.function.IntBinaryOperator;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
/**
* Pins the vertical shift {@code iris:structure} asks for a platform start under every adjustment a dimension can
* give it, and how far each terrain fit reaches. The host half (alignment, clamping, moving) is pinned on the platform.
*/
public class StartLayoutsTest {
private static final Gson JSON = new Gson();
private static final int BOTTOM_Y = -64;
private static final int PYRAMID_WIDTH = 21;
private static final int PYRAMID_HEIGHT = 15;
private static final IntBinaryOperator SURFACE = (x, z) -> 62 + Math.floorMod(x * 7 + z * 3, 11) - 5;
private static final int[][] CHUNKS = {{0, 0}, {3, -5}, {-11, 7}};
private static final List<String> PINNED_SHIFTS = List.of(
"none minecraft:stronghold 0,0 shift 0",
"none minecraft:desert_pyramid 0,0 shift 0",
"none minecraft:stronghold 3,-5 shift 0",
"none minecraft:desert_pyramid 3,-5 shift 0",
"none minecraft:stronghold -11,7 shift 0",
"none minecraft:desert_pyramid -11,7 shift 0",
"shift minecraft:stronghold 0,0 shift 5",
"shift minecraft:desert_pyramid 0,0 shift 5",
"shift minecraft:stronghold 3,-5 shift 5",
"shift minecraft:desert_pyramid 3,-5 shift 5",
"shift minecraft:stronghold -11,7 shift 5",
"shift minecraft:desert_pyramid -11,7 shift 5",
"burial minecraft:stronghold 0,0 shift -8",
"burial minecraft:desert_pyramid 0,0 shift -7",
"burial minecraft:stronghold 3,-5 shift -8",
"burial minecraft:desert_pyramid 3,-5 shift -7",
"burial minecraft:stronghold -11,7 shift -8",
"burial minecraft:desert_pyramid -11,7 shift -7",
"burial-unshifted minecraft:stronghold 0,0 shift -8",
"burial-unshifted minecraft:desert_pyramid 0,0 shift 0",
"burial-unshifted minecraft:stronghold 3,-5 shift -8",
"burial-unshifted minecraft:desert_pyramid 3,-5 shift 0",
"burial-unshifted minecraft:stronghold -11,7 shift -8",
"burial-unshifted minecraft:desert_pyramid -11,7 shift 0",
"kept minecraft:stronghold 0,0 shift 3",
"kept minecraft:desert_pyramid 0,0 shift 3",
"kept minecraft:stronghold 3,-5 shift 3",
"kept minecraft:desert_pyramid 3,-5 shift 3",
"kept minecraft:stronghold -11,7 shift 3",
"kept minecraft:desert_pyramid -11,7 shift 3",
"band minecraft:stronghold 0,0 shift -94",
"band minecraft:desert_pyramid 0,0 shift 0",
"band minecraft:stronghold 3,-5 shift -58",
"band minecraft:desert_pyramid 3,-5 shift 0",
"band minecraft:stronghold -11,7 shift -96",
"band minecraft:desert_pyramid -11,7 shift 0",
"narrow-band minecraft:stronghold 0,0 shift -46",
"narrow-band minecraft:desert_pyramid 0,0 shift 4",
"narrow-band minecraft:stronghold 3,-5 shift -46",
"narrow-band minecraft:desert_pyramid 3,-5 shift 4",
"narrow-band minecraft:stronghold -11,7 shift -46",
"narrow-band minecraft:desert_pyramid -11,7 shift 4",
"kept-over-band minecraft:stronghold 0,0 shift 2",
"kept-over-band minecraft:desert_pyramid 0,0 shift 2",
"kept-over-band minecraft:stronghold 3,-5 shift 2",
"kept-over-band minecraft:desert_pyramid 3,-5 shift 2",
"kept-over-band minecraft:stronghold -11,7 shift 2",
"kept-over-band minecraft:desert_pyramid -11,7 shift 2"
);
@Test
public void platformStartsShiftWhereTheirAdjustmentSays() {
List<String> actual = new ArrayList<>();
for (Adjustment adjustment : adjustments()) {
for (int[] chunk : CHUNKS) {
for (String structureId : List.of("minecraft:stronghold", "minecraft:desert_pyramid")) {
boolean aligned = structureId.equals("minecraft:desert_pyramid");
int minY = aligned ? 64 : 50;
BlockBox bounds = new BlockBox(chunk[0] * 16, minY - BOTTOM_Y, chunk[1] * 16,
chunk[0] * 16 + PYRAMID_WIDTH, minY - BOTTOM_Y + PYRAMID_HEIGHT, chunk[1] * 16 + PYRAMID_WIDTH);
PlatformStart start = start(structureId, chunk, bounds, adjustment.underground(), aligned, SURFACE);
actual.add(adjustment.name() + " " + structureId + " " + chunk[0] + "," + chunk[1]
+ " shift " + StartLayouts.shift(start, adjustment.fit()));
}
}
}
assertEquals(PINNED_SHIFTS, actual);
}
@Test
public void burialKeepsTheTopABlockUnderTheLowestTerrainColumn() {
BlockBox bounds = new BlockBox(0, 60 - BOTTOM_Y, 0, 2, 81 - BOTTOM_Y, 1);
PlatformStart start = start("minecraft:stronghold", new int[]{0, 0}, bounds, true, false,
(x, z) -> x == 1 ? 76 : 100);
assertEquals(-5, StartLayouts.shift(start, NativeStructureFit.NONE));
}
@Test
public void startsReachAsFarAsTheirTerrainFitChangesTerrain() {
assertEquals(StartReach.PLATFORM, StartLayouts.reach(terrain("{}")));
assertEquals(StartReach.blocks(0), StartLayouts.reach(terrain("{\"mode\":\"PRESERVE\"}")));
assertEquals(StartReach.blocks(12), StartLayouts.reach(terrain("{\"mode\":\"VACUUM\"}")));
assertEquals(StartReach.blocks(4), StartLayouts.reach(terrain("{\"mode\":\"ENCASE\",\"horizontalPadding\":4}")));
assertEquals(StartReach.blocks(20), StartLayouts.reach(terrain("{\"mode\":\"BORE\",\"horizontalPadding\":20}")));
assertEquals(StartReach.blocks(112),
StartLayouts.reach(terrain("{\"mode\":\"FORCE_CARVE\",\"horizontalPadding\":112}")));
assertEquals(StartReach.blocks(0), StartLayouts.reach(terrain("{\"mode\":\"FORCE_CARVE\",\"horizontalPadding\":0}")));
}
@Test
public void aBandMovesTheMiddleIntoItTheSameWayForTheSameChunk() {
NativeStructureFit fit = fit(-64, "{\"min\":-120,\"max\":-20}", false);
PlatformStart first = pyramidAt(64, false);
PlatformStart second = pyramidAt(64, false);
int shift = StartLayouts.shift(first, fit);
assertEquals(shift, StartLayouts.shift(second, fit));
int middle = 64 + PYRAMID_HEIGHT / 2 + shift;
assertTrue(middle >= -120 && middle <= -20);
}
@Test
public void aBandTooNarrowForTheStructureTakesItsMiddle() {
PlatformStart start = pyramidAt(64, false);
int shift = StartLayouts.shift(start, fit(0, "{\"min\":-50,\"max\":-45}", false));
assertEquals(Math.floorDiv(-50 + -45, 2), 64 + (PYRAMID_HEIGHT - 1) / 2 + shift);
}
@Test
public void aBandReplacesBothTheShiftAndTheBurial() {
PlatformStart start = pyramidAt(64, true);
int shift = StartLayouts.shift(start, fit(-200, "{\"min\":-64,\"max\":-64}", false));
assertEquals(-64 - (PYRAMID_HEIGHT - 1) / 2, 64 + shift);
}
private static StructureTerrain terrain(String json) {
return JSON.fromJson(json, StructureTerrain.class);
}
private static List<Adjustment> adjustments() {
return List.of(
new Adjustment("none", fit(0, null, false), false),
new Adjustment("shift", fit(5, null, false), false),
new Adjustment("burial", fit(-7, null, false), true),
new Adjustment("burial-unshifted", fit(0, null, false), true),
new Adjustment("kept", fit(3, null, true), true),
new Adjustment("band", fit(0, "{\"min\":-50,\"max\":20}", false), true),
new Adjustment("narrow-band", fit(4, "{\"min\":10,\"max\":12}", false), false),
new Adjustment("kept-over-band", fit(2, "{\"min\":-40,\"max\":80}", true), false));
}
private static NativeStructureFit fit(int yShift, String bandJson, boolean keepsSourceY) {
StructureYBand band = bandJson == null ? null : JSON.fromJson(bandJson, StructureYBand.class);
return new NativeStructureFit(yShift, band, keepsSourceY, null, null);
}
private static PlatformStart pyramidAt(int minY, boolean underground) {
BlockBox bounds = new BlockBox(0, minY - BOTTOM_Y, 0, PYRAMID_WIDTH, minY - BOTTOM_Y + PYRAMID_HEIGHT, PYRAMID_WIDTH);
return start("minecraft:stronghold", new int[]{0, 0}, bounds, underground, false, (x, z) -> 40);
}
private static PlatformStart start(String structureId, int[] chunk, BlockBox bounds, boolean underground,
boolean aligned, IntBinaryOperator worldSurface) {
return new PlatformStart() {
@Override
public ResourceId structure() {
return ResourceId.parse(structureId);
}
@Override
public int chunkX() {
return chunk[0];
}
@Override
public int chunkZ() {
return chunk[1];
}
@Override
public BlockBox bounds() {
return bounds;
}
@Override
public boolean underground() {
return underground;
}
@Override
public boolean aligned() {
return aligned;
}
@Override
public int bottomY() {
return BOTTOM_Y;
}
@Override
public int surfaceY(int x, int z) {
return worldSurface.applyAsInt(x, z) - BOTTOM_Y;
}
};
}
private record Adjustment(String name, NativeStructureFit fit, boolean underground) {
}
}
@@ -0,0 +1,261 @@
package art.arcane.iris.engine.framework.structure.fit;
import com.volmit.vanilla.StructureStep;
import com.volmit.vanilla.TerrainAdaptation;
import org.junit.Test;
import java.util.List;
import java.util.Map;
import static art.arcane.iris.engine.framework.structure.fit.FitFixture.AIR;
import static art.arcane.iris.engine.framework.structure.fit.FitFixture.COBBLESTONE;
import static art.arcane.iris.engine.framework.structure.fit.FitFixture.DIRT;
import static art.arcane.iris.engine.framework.structure.fit.FitFixture.GRASS;
import static art.arcane.iris.engine.framework.structure.fit.FitFixture.OAK_LEAVES;
import static art.arcane.iris.engine.framework.structure.fit.FitFixture.OAK_LOG;
import static art.arcane.iris.engine.framework.structure.fit.FitFixture.STONE;
import static art.arcane.iris.engine.framework.structure.fit.FitFixture.WATER;
import static art.arcane.iris.engine.framework.structure.fit.FitFixture.state;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
/** The surface fitting of SOURCE beard and VACUUM starts, on in-memory terrain. */
public class SurfaceFittingTest {
private static final String SOURCE = "{\"mode\":\"SOURCE\"}";
private static final String VACUUM = "{\"mode\":\"VACUUM\"}";
private static final String PRESERVE = "{\"mode\":\"PRESERVE\"}";
@Test
public void sourceBeardAdjustmentsPrepareOnlyAtTheSurfaceStructuresStep() {
assertTrue(SurfaceFitting.shouldPrepareSurfaceTerrain(TerrainAdaptation.BEARD_THIN, StructureStep.SURFACE_STRUCTURES));
assertFalse(SurfaceFitting.shouldPrepareSurfaceTerrain(TerrainAdaptation.BEARD_BOX, StructureStep.FLUID_SPRINGS));
assertFalse(SurfaceFitting.shouldPrepareSurfaceTerrain(TerrainAdaptation.BEARD_THIN, StructureStep.UNDERGROUND_STRUCTURES));
assertFalse(SurfaceFitting.shouldPrepareSurfaceTerrain(TerrainAdaptation.BEARD_BOX, StructureStep.UNDERGROUND_DECORATION));
assertFalse(SurfaceFitting.shouldPrepareSurfaceTerrain(TerrainAdaptation.BEARD_THIN, StructureStep.STRONGHOLDS));
assertFalse(SurfaceFitting.shouldPrepareSurfaceTerrain(TerrainAdaptation.BURY, StructureStep.SURFACE_STRUCTURES));
assertFalse(SurfaceFitting.shouldPrepareSurfaceTerrain(TerrainAdaptation.ENCAPSULATE, StructureStep.SURFACE_STRUCTURES));
assertFalse(SurfaceFitting.shouldPrepareSurfaceTerrain(TerrainAdaptation.NONE, StructureStep.FLUID_SPRINGS));
}
@Test
public void explicitTerrainOverrideDisablesSourceBeardFittingAndVacuumNeedsNoAdaptation() {
FitFixture.Piece piece = FitFixture.Piece.fixed(new Box(0, 64, 0, 4, 70, 4));
assertTrue(SurfaceFitting.requiresSurfaceTerrain(
FitFixture.start(SOURCE, TerrainAdaptation.BEARD_BOX, StructureStep.SURFACE_STRUCTURES, piece)));
assertFalse(SurfaceFitting.requiresSurfaceTerrain(
FitFixture.start(PRESERVE, TerrainAdaptation.BEARD_BOX, StructureStep.SURFACE_STRUCTURES, piece)));
assertFalse(SurfaceFitting.requiresSurfaceTerrain(
FitFixture.start(SOURCE, TerrainAdaptation.NONE, StructureStep.SURFACE_STRUCTURES, piece)));
assertTrue(SurfaceFitting.requiresSurfaceTerrain(
FitFixture.start(VACUUM, TerrainAdaptation.NONE, StructureStep.SURFACE_STRUCTURES, piece)));
assertTrue(SurfaceFitting.requiresSurfaceTerrain(
FitFixture.start(VACUUM, TerrainAdaptation.BEARD_BOX, StructureStep.SURFACE_STRUCTURES, piece)));
assertFalse(TerrainIntegration.clearsLegacyTemplateAir(
FitFixture.start(VACUUM, TerrainAdaptation.NONE, StructureStep.SURFACE_STRUCTURES, piece)));
}
@Test
public void sourceSurfaceAnchorMeetsOneBlockBelowTheAuthoredGroundPlane() {
SurfaceFitting.SurfaceAnchor anchor = SurfaceFitting.surfaceAnchor(new Box(0, 64, 0, 4, 90, 4), 68, 2);
assertEquals(67, anchor.meetY());
assertEquals(0, anchor.minX());
assertEquals(4, anchor.maxX());
assertEquals(0, anchor.minZ());
assertEquals(4, anchor.maxZ());
}
@Test
public void rigidFootprintsBoundTerrainAcrossGapsLargerThanTheBeardKernel() {
assertEquals(46, SurfaceFitting.resolveSurfaceTarget(List.of(anchor(72, 2)), 2, 2, 40));
assertEquals(46, SurfaceFitting.resolveSurfaceTarget(List.of(anchor(72, 1)), 2, 2, 40));
}
@Test
public void beardSkirtBoundsAndGradesUpwardAndDownwardSymmetrically() {
int originalY = 64;
int[] raised = new int[13];
int[] lowered = new int[13];
for (int outset = 0; outset <= 12; outset++) {
raised[outset] = SurfaceFitting.resolveSurfaceTarget(List.of(anchor(96, 2)), 4 + outset, 2, originalY);
lowered[outset] = SurfaceFitting.resolveSurfaceTarget(List.of(anchor(32, 2)), 4 + outset, 2, originalY);
}
assertArrayEquals(new int[]{70, 69, 68, 67, 67, 66, 66, 65, 65, 64, 64, 64, 64}, raised);
assertArrayEquals(new int[]{58, 59, 60, 61, 61, 62, 62, 63, 63, 64, 64, 64, 64}, lowered);
}
@Test
public void surfaceAnchorCapsInsideAndIsUnchangedAtRadius() {
SurfaceFitting.SurfaceAnchor anchor = anchor(72, 2);
assertEquals(70, SurfaceFitting.resolveSurfaceTarget(List.of(anchor), 2, 2, 64));
assertEquals(64, SurfaceFitting.resolveSurfaceTarget(List.of(anchor), 16, 2, 64));
assertEquals(64, SurfaceFitting.resolveSurfaceTarget(List.of(anchor), 17, 2, 64));
}
@Test
public void surfaceAnchorRaisesAndLowersThroughTheTaper() {
assertEquals(65, SurfaceFitting.resolveSurfaceTarget(List.of(anchor(68, 2)), 10, 2, 64));
assertEquals(67, SurfaceFitting.resolveSurfaceTarget(List.of(anchor(64, 2)), 10, 2, 68));
}
@Test
public void containingRigidFloorsHaveDeterministicPriority() {
SurfaceFitting.SurfaceAnchor rigid = anchor(70, 2);
SurfaceFitting.SurfaceAnchor junction = anchor(74, 1);
assertEquals(70, SurfaceFitting.resolveSurfaceTarget(List.of(rigid, junction), 2, 2, 64));
assertEquals(70, SurfaceFitting.resolveSurfaceTarget(List.of(junction, rigid), 2, 2, 64));
SurfaceFitting.SurfaceAnchor weakTie = anchor(58, 1);
SurfaceFitting.SurfaceAnchor strongTie = anchor(70, 2);
assertEquals(70, SurfaceFitting.resolveSurfaceTarget(List.of(weakTie, strongTie), 2, 2, 64));
assertEquals(70, SurfaceFitting.resolveSurfaceTarget(List.of(strongTie, weakTie), 2, 2, 64));
}
@Test
public void containingFootprintOverridesAnAdjacentPiecesFalloff() {
SurfaceFitting.SurfaceAnchor local = new SurfaceFitting.SurfaceAnchor(0, 4, 0, 4, 66, 2);
SurfaceFitting.SurfaceAnchor adjacent = new SurfaceFitting.SurfaceAnchor(5, 9, 0, 4, 70, 2);
assertEquals(69, SurfaceFitting.resolveSurfaceTarget(List.of(adjacent), 4, 2, 64));
assertEquals(66, SurfaceFitting.resolveSurfaceTarget(List.of(local, adjacent), 4, 2, 64));
assertEquals(66, SurfaceFitting.resolveSurfaceTarget(List.of(adjacent, local), 4, 2, 64));
}
@Test
public void opposingFalloffsBlendWithoutAnAbruptMidpointSeam() {
SurfaceFitting.SurfaceAnchor high = new SurfaceFitting.SurfaceAnchor(0, 0, 0, 0, 70, 2);
SurfaceFitting.SurfaceAnchor low = new SurfaceFitting.SurfaceAnchor(12, 12, 0, 0, 58, 2);
int previous = SurfaceFitting.resolveSurfaceTarget(List.of(high, low), 0, 0, 64);
for (int x = 1; x <= 12; x++) {
int forward = SurfaceFitting.resolveSurfaceTarget(List.of(high, low), x, 0, 64);
assertEquals(forward, SurfaceFitting.resolveSurfaceTarget(List.of(low, high), x, 0, 64));
assertTrue(Math.abs(forward - previous) <= 6);
previous = forward;
}
assertEquals(64, SurfaceFitting.resolveSurfaceTarget(List.of(high, low), 6, 0, 64));
}
@Test
public void surfaceColumnsMutateTerrainAndRemoveUnsupportedDecoration() {
FitFixture.World lowered = new FitFixture.World(new Box(0, 0, 0, 0, 0, 0));
lowered.put(0, 61, 0, STONE);
lowered.put(0, 62, 0, DIRT);
lowered.put(0, 63, 0, DIRT);
lowered.put(0, 64, 0, GRASS);
lowered.put(0, 65, 0, state("dandelion"));
SurfaceFitting.applySurfaceColumn(lowered.fitBlocks(), 0, 0, 64, 62, -64, 319, false);
assertEquals(STONE, lowered.at(0, 61, 0));
assertEquals(GRASS, lowered.at(0, 62, 0));
assertEquals(AIR, lowered.at(0, 63, 0));
assertEquals(AIR, lowered.at(0, 64, 0));
assertEquals(AIR, lowered.at(0, 65, 0));
FitFixture.World raised = new FitFixture.World(new Box(0, 0, 0, 0, 0, 0));
raised.put(0, 63, 0, DIRT);
raised.put(0, 64, 0, GRASS);
raised.put(0, 65, 0, state("dandelion"));
SurfaceFitting.applySurfaceColumn(raised.fitBlocks(), 0, 0, 64, 68, -64, 319, false);
assertEquals(DIRT, raised.at(0, 65, 0));
assertEquals(DIRT, raised.at(0, 66, 0));
assertEquals(DIRT, raised.at(0, 67, 0));
assertEquals(GRASS, raised.at(0, 68, 0));
}
@Test
public void rigidSurfaceBaseClosesAOneBlockSubsurfaceGapAndRebuildsAMissingMeetLayer() {
FitFixture.World gap = new FitFixture.World(new Box(0, 0, 0, 0, 0, 0));
gap.put(0, 62, 0, STONE);
gap.put(0, 64, 0, GRASS);
SurfaceFitting.applySurfaceColumn(gap.fitBlocks(), 0, 0, 64, 64, -64, 319, true);
assertEquals(STONE, gap.at(0, 63, 0));
assertEquals(GRASS, gap.at(0, 64, 0));
FitFixture.World missing = new FitFixture.World(new Box(0, 0, 0, 0, 0, 0));
missing.put(0, 62, 0, STONE);
SurfaceFitting.applySurfaceColumn(missing.fitBlocks(), 0, 0, 64, 64, -64, 319, true);
assertEquals(STONE, missing.at(0, 63, 0));
assertEquals(STONE, missing.at(0, 64, 0));
FitFixture.World floor = new FitFixture.World(new Box(0, 0, 0, 0, 0, 0));
SurfaceFitting.applySurfaceColumn(floor.fitBlocks(), 0, 0, -64, -64, -64, 319, true);
assertEquals(STONE, floor.at(0, -64, 0));
}
@Test
public void raisedSurfaceTerrainDoesNotSliceTreeBlocks() {
FitFixture.World world = new FitFixture.World(new Box(0, 0, 0, 0, 0, 0));
world.put(0, 63, 0, DIRT);
world.put(0, 64, 0, GRASS);
world.put(0, 66, 0, OAK_LOG);
world.put(0, 68, 0, OAK_LEAVES);
SurfaceFitting.applySurfaceColumn(world.fitBlocks(), 0, 0, 64, 68, -64, 319, false);
assertEquals(OAK_LOG, world.at(0, 66, 0));
assertEquals(OAK_LEAVES, world.at(0, 68, 0));
}
@Test
public void loweredFluidColumnsRemainFluidFilled() {
FitFixture.World world = new FitFixture.World(new Box(0, 0, 0, 0, 0, 0));
world.put(0, 62, 0, DIRT);
world.put(0, 63, 0, DIRT);
world.put(0, 64, 0, state("gravel"));
world.put(0, 65, 0, WATER);
SurfaceFitting.applySurfaceColumn(world.fitBlocks(), 0, 0, 64, 62, -64, 319, false);
assertEquals(WATER, world.at(0, 63, 0));
assertEquals(WATER, world.at(0, 64, 0));
assertEquals(WATER, world.at(0, 65, 0));
assertEquals(state("gravel"), world.at(0, 62, 0));
}
@Test
public void vacuumBudgetExhaustionSkipsFittingWithoutFailing() {
Box area = new Box(0, 54, 0, 15, 72, 15);
FitFixture.World world = new FitFixture.World(area).flat(area, 60);
Map<?, ?> before = world.snapshot();
FitStart start = FitFixture.start(VACUUM, TerrainAdaptation.NONE, StructureStep.SURFACE_STRUCTURES,
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);
assertEquals(before, world.snapshot());
}
@Test
public void vacuumRaisesTheTerrainToAFloatingFoundationAndRepairsItsGapAfterPlacement() {
Box area = new Box(0, 54, 0, 3, 74, 3);
FitFixture.World world = new FitFixture.World(area).flat(area, 60);
FitStart start = FitFixture.start(VACUUM, TerrainAdaptation.NONE, StructureStep.SURFACE_STRUCTURES,
FitFixture.Piece.rigid(new Box(0, 65, 0, 0, 72, 0), 1).cell(0, 65, 0, COBBLESTONE));
SurfaceFitting.VacuumFoundationPlan plan = SurfaceFitting.prepareSurfaceStructures(
world.fitBlocks(), area, List.of(start), (x, z) -> 60, SurfaceFitting.MAX_SURFACE_TEMPLATE_CELLS);
assertEquals(GRASS, world.at(0, 64, 0));
for (int y = 61; y <= 64; y++) {
world.put(0, y, 0, state("cave_air"));
}
world.put(0, 65, 0, COBBLESTONE);
SurfaceFitting.repairVacuumFoundations(world.fitBlocks(), area, plan);
for (int y = 61; y <= 64; y++) {
assertFalse(world.at(0, y, 0).material().path().endsWith("air"));
}
}
private static SurfaceFitting.SurfaceAnchor anchor(int meetY, int strength) {
return new SurfaceFitting.SurfaceAnchor(0, 4, 0, 4, meetY, strength);
}
}
@@ -0,0 +1,496 @@
package art.arcane.iris.engine.framework.structure.fit;
import art.arcane.iris.builtin.structure.StructureCarveShape;
import art.arcane.iris.builtin.structure.StructureTerrain;
import art.arcane.iris.builtin.structure.StructureTerrainMode;
import art.arcane.iris.engine.framework.structure.NativeStructureFit;
import art.arcane.iris.engine.mantle.components.StructureCarvingFootprint;
import com.google.gson.Gson;
import com.volmit.block.BlockState;
import com.volmit.vanilla.PieceKind;
import com.volmit.vanilla.StartMemo;
import com.volmit.vanilla.StructureStep;
import com.volmit.vanilla.TerrainAdaptation;
import org.junit.Test;
import java.util.ArrayList;
import java.util.BitSet;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.function.IntFunction;
import static art.arcane.iris.engine.framework.structure.fit.FitFixture.AIR;
import static art.arcane.iris.engine.framework.structure.fit.FitFixture.DIRT;
import static art.arcane.iris.engine.framework.structure.fit.FitFixture.OAK_LOG;
import static art.arcane.iris.engine.framework.structure.fit.FitFixture.STONE;
import static art.arcane.iris.engine.framework.structure.fit.FitFixture.WATER;
import static art.arcane.iris.engine.framework.structure.fit.FitFixture.state;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNotSame;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertTrue;
/** The terrain integration of every mode but VACUUM, on in-memory terrain. */
public class TerrainIntegrationTest {
private static final long SEED = 1234L;
private static final long CARVE_SEED = 8675309L;
private static final int SLAB_DEPTH = 128;
private static final int SLAB_MIN_Y = 64;
private static final int SLAB_PADDING = 14;
private static final int SLAB_WIDTH = 16;
private static final Gson JSON = new Gson();
private static final IntFunction<BlockState> NATURAL = y -> y < 0 ? state("deepslate") : STONE;
private static final FitPalettes NO_PALETTES = (palette, seed, x, y, z) -> {
throw new AssertionError("no palette expected");
};
/** The box of a desert pyramid piece at y 64: 21 wide, 15 high. */
private static final Box PYRAMID = new Box(0, 64, 0, 20, 78, 20);
@Test
public void encaseFillsAirAndLiquidWithoutOverwritingExistingTerrain() {
Box bounds = PYRAMID;
Box area = new Box(bounds.minX() - 1, bounds.minY() - 1, bounds.minZ() - 1,
bounds.maxX() + 1, bounds.maxY() + 1, bounds.maxZ() + 1);
FitFixture.World world = new FitFixture.World(area);
world.put(bounds.minX(), bounds.minY(), bounds.minZ(), DIRT);
world.put(bounds.maxX(), bounds.minY(), bounds.maxZ(), WATER);
integrate(world, area, start("{\"mode\":\"ENCASE\",\"horizontalPadding\":1,\"ceilingPadding\":1,\"floorPadding\":1}",
TerrainAdaptation.BURY, FitFixture.Piece.fixed(bounds)));
assertEquals(DIRT, world.at(bounds.minX(), bounds.minY(), bounds.minZ()));
assertEquals(STONE, world.at(bounds.maxX(), bounds.minY(), bounds.maxZ()));
assertEquals(STONE, world.at(bounds.minX() - 1, bounds.minY() - 1, bounds.minZ() - 1));
assertEquals(STONE, world.at(bounds.maxX() + 1, bounds.maxY() + 1, bounds.maxZ() + 1));
}
@Test
public void defaultEncaseUsesTheDimensionsNaturalBlockPerHeight() {
Box bounds = new Box(0, -1, 0, 20, 13, 20);
FitFixture.World world = new FitFixture.World(bounds);
integrate(world, bounds, start("{\"mode\":\"ENCASE\"}", TerrainAdaptation.BURY, FitFixture.Piece.fixed(bounds)));
assertEquals(state("deepslate"), world.at(0, -1, 0));
assertEquals(STONE, world.at(0, 0, 0));
}
@Test
public void configuredEncasePaletteReplacesTheDefaultMaterialSeededPerStructure() {
FitFixture.World world = new FitFixture.World(PYRAMID);
List<Long> seeds = new ArrayList<>();
FitPalettes tuff = (palette, seed, x, y, z) -> {
seeds.add(seed);
return state("tuff");
};
FitStart start = start("{\"mode\":\"ENCASE\",\"encasePalette\":{\"palette\":[{\"block\":\"tuff\"}]}}",
TerrainAdaptation.BURY, FitFixture.Piece.fixed(PYRAMID));
TerrainIntegration.integrateTerrain(world.fitBlocks(), PYRAMID, start, SEED, NATURAL, tuff, null);
assertEquals(state("tuff"), world.at(0, 64, 0));
assertEquals(SEED ^ "test:structure".hashCode(), (long) seeds.getFirst());
}
@Test
public void sourceMaterialFollowsNearbyTerrainAndIgnoresBlocksOutsideTheSnapshot() {
Box area = new Box(0, 64, 0, 15, 64, 15);
FitFixture.World world = new FitFixture.World(area);
world.put(-1, 64, 8, state("oak_planks"));
world.put(3, 64, 8, state("tuff"));
TerrainIntegration.SourceTerrainSnapshot snapshot = snapshot(world, area);
world.put(1, 64, 8, state("oak_planks"));
assertEquals(state("tuff"), TerrainIntegration.sourceEncaseBlock(0, 64, 8, NATURAL, snapshot));
}
@Test
public void sourceMaterialRejectsStructureBlocksAndOresBeforeTheNaturalFallback() {
Box area = new Box(0, -20, 0, 15, -20, 15);
FitFixture.World world = new FitFixture.World(area);
world.put(3, -20, 8, state("oak_planks"));
world.put(5, -20, 8, state("stone_bricks"));
world.put(4, -20, 7, state("iron_ore"));
assertEquals(state("deepslate"), TerrainIntegration.sourceEncaseBlock(4, -20, 8, NATURAL, snapshot(world, area)));
}
@Test
public void sourceMaterialSnapshotOnlyAllocatesActualFillLayers() {
Box area = new Box(0, -2032, 0, 15, 2030, 15);
FitFixture.World world = new FitFixture.World(area);
TerrainIntegration.SourceTerrainSnapshot snapshot = TerrainIntegration.captureSourceTerrain(world.fitBlocks(), area,
List.of(start("{\"mode\":\"SOURCE\"}", TerrainAdaptation.BURY, FitFixture.Piece.fixed(PYRAMID))));
assertNotNull(snapshot);
assertEquals(23 * 16 * 16, snapshot.sampledCells());
}
@Test
public void sourceBuryUsesTheVanillaSixByTwelveInfluenceEnvelope() {
int groundY = PYRAMID.minY();
Box area = new Box(PYRAMID.minX() - 7, groundY - 13, PYRAMID.minZ(), PYRAMID.maxX(), groundY + 13, PYRAMID.maxZ());
FitFixture.World world = new FitFixture.World(area);
integrate(world, area, start("{\"mode\":\"SOURCE\"}", TerrainAdaptation.BURY, FitFixture.Piece.fixed(PYRAMID)));
assertEquals(STONE, world.at(PYRAMID.minX() - 5, groundY, PYRAMID.minZ()));
assertEquals(STONE, world.at(PYRAMID.minX(), groundY + 11, PYRAMID.minZ()));
assertEquals(AIR, world.at(PYRAMID.minX() - 6, groundY, PYRAMID.minZ()));
assertEquals(AIR, world.at(PYRAMID.minX(), groundY + 12, PYRAMID.minZ()));
assertEquals(AIR, world.at(PYRAMID.minX() - 7, groundY, PYRAMID.minZ()));
}
@Test
public void sourceEncapsulateWrapsTheFullPieceBounds() {
Box area = new Box(PYRAMID.minX() - 13, PYRAMID.minY(), PYRAMID.minZ(), PYRAMID.maxX(), PYRAMID.maxY() + 13, PYRAMID.maxZ());
FitFixture.World world = new FitFixture.World(area);
integrate(world, area, start("{\"mode\":\"SOURCE\"}", TerrainAdaptation.ENCAPSULATE, FitFixture.Piece.fixed(PYRAMID)));
assertEquals(STONE, world.at(PYRAMID.minX() - 11, PYRAMID.minY(), PYRAMID.minZ()));
assertEquals(STONE, world.at(PYRAMID.minX(), PYRAMID.maxY() + 11, PYRAMID.minZ()));
assertEquals(AIR, world.at(PYRAMID.minX() - 12, PYRAMID.minY(), PYRAMID.minZ()));
assertEquals(AIR, world.at(PYRAMID.minX(), PYRAMID.maxY() + 12, PYRAMID.minZ()));
}
@Test
public void sourceTerrainDensityOnlyUsesRigidAndFixedPieces() {
assertFalse(new FitPiece(new FitFixture.Piece(PYRAMID, PieceKind.TERRAIN_MATCHING, 0), FitFixture.BOTTOM_Y).isRigidOrFixed());
assertTrue(new FitPiece(new FitFixture.Piece(PYRAMID, PieceKind.RIGID, 0), FitFixture.BOTTOM_Y).isRigidOrFixed());
assertTrue(new FitPiece(new FitFixture.Piece(PYRAMID, PieceKind.FIXED, 0), FitFixture.BOTTOM_Y).isRigidOrFixed());
}
@Test
public void sourceEnvelopesAreTheVanillaOnes() {
assertTrue(TerrainIntegration.insideSourceJunctionEnvelope(0, -1, 0));
assertTrue(TerrainIntegration.insideSourceJunctionEnvelope(0, -11, 0));
assertFalse(TerrainIntegration.insideSourceJunctionEnvelope(0, 0, 0));
assertFalse(TerrainIntegration.insideSourceJunctionEnvelope(0, -12, 0));
assertFalse(TerrainIntegration.insideSourceJunctionEnvelope(12, -1, 0));
assertTrue(TerrainIntegration.insideBurialEnvelope(5, 0, 0));
assertFalse(TerrainIntegration.insideBurialEnvelope(6, 0, 0));
assertTrue(TerrainIntegration.insideEncapsulationEnvelope(11, 0, 0));
assertFalse(TerrainIntegration.insideEncapsulationEnvelope(12, 0, 0));
}
@Test
public void omittedTerrainRetainsSourceSemanticsAndAnExplicitTerrainWins() {
assertEquals(StructureTerrainMode.SOURCE, NativeStructureFit.NONE.resolvedTerrain().resolvedMode());
assertEquals(StructureTerrainMode.PRESERVE,
NativeStructureFit.of(new StartMemo("{\"mode\":\"PRESERVE\"}", "null")).resolvedTerrain().resolvedMode());
}
@Test
public void legacyTemplateAirIsClearedAfterEveryTerrainFillPath() {
FitFixture.Piece piece = FitFixture.Piece.fixed(PYRAMID);
assertTrue(TerrainIntegration.clearsLegacyTemplateAir(start("{\"mode\":\"SOURCE\"}", TerrainAdaptation.BURY, piece)));
assertTrue(TerrainIntegration.clearsLegacyTemplateAir(start("{\"mode\":\"SOURCE\"}", TerrainAdaptation.BEARD_BOX, piece)));
assertTrue(TerrainIntegration.clearsLegacyTemplateAir(start("{\"mode\":\"ENCASE\"}", TerrainAdaptation.NONE, piece)));
assertFalse(TerrainIntegration.clearsLegacyTemplateAir(start("{\"mode\":\"SOURCE\"}", TerrainAdaptation.NONE, piece)));
assertFalse(TerrainIntegration.clearsLegacyTemplateAir(start("{\"mode\":\"PRESERVE\"}", TerrainAdaptation.BURY, piece)));
assertFalse(TerrainIntegration.shouldClearLegacyAir(79, 80, false));
assertTrue(TerrainIntegration.shouldClearLegacyAir(80, 80, false));
assertTrue(TerrainIntegration.shouldClearLegacyAir(96, 80, false));
assertFalse(TerrainIntegration.shouldClearLegacyAir(96, 80, true));
}
@Test
public void legacyTemplateAirClearsAboveTheGroundAndSparesTrees() {
Box area = new Box(0, 70, 0, 15, 90, 15);
FitFixture.World world = new FitFixture.World(area);
world.put(1, 80, 0, DIRT);
world.put(2, 79, 0, DIRT);
world.put(3, 80, 0, OAK_LOG);
FitFixture.Piece piece = FitFixture.Piece.rigid(new Box(0, 79, 0, 4, 85, 0), 1)
.legacyAir(1, 80, 0).legacyAir(2, 79, 0).legacyAir(3, 80, 0);
TerrainIntegration.clearLegacyTemplateAir(world.fitBlocks(), area,
start("{\"mode\":\"SOURCE\"}", TerrainAdaptation.BEARD_THIN, piece));
assertEquals(AIR, world.at(1, 80, 0));
assertEquals(DIRT, world.at(2, 79, 0));
assertEquals(OAK_LOG, world.at(3, 80, 0));
}
@Test
public void vacuumLeavesPieceBlocksForTheSurfaceFitting() {
FitFixture.World world = new FitFixture.World(PYRAMID);
world.put(PYRAMID.minX(), PYRAMID.minY(), PYRAMID.minZ(), STONE);
integrate(world, PYRAMID, start("{\"mode\":\"VACUUM\"}", TerrainAdaptation.NONE, FitFixture.Piece.fixed(PYRAMID)));
assertEquals(STONE, world.at(PYRAMID.minX(), PYRAMID.minY(), PYRAMID.minZ()));
}
@Test
public void forceCarveHonorsConfiguredPadding() {
Box area = new Box(PYRAMID.minX() - 1, PYRAMID.minY(), PYRAMID.minZ() - 1,
PYRAMID.maxX() + 1, PYRAMID.maxY() + 1, PYRAMID.maxZ() + 1);
FitFixture.World world = new FitFixture.World(area);
world.put(PYRAMID.maxX() + 1, PYRAMID.minY(), PYRAMID.maxZ(), STONE);
world.put(PYRAMID.maxX(), PYRAMID.maxY() + 1, PYRAMID.maxZ(), STONE);
integrate(world, area, start("{\"mode\":\"FORCE_CARVE\",\"horizontalPadding\":1,\"ceilingPadding\":1}",
TerrainAdaptation.NONE, FitFixture.Piece.fixed(PYRAMID)));
assertEquals(AIR, world.at(PYRAMID.maxX() + 1, PYRAMID.minY(), PYRAMID.maxZ()));
assertEquals(AIR, world.at(PYRAMID.maxX(), PYRAMID.maxY() + 1, PYRAMID.maxZ()));
}
@Test
public void forceCarveUsesThePieceUnionInsteadOfTheCombinedBounds() {
Box second = new Box(64, 64, 0, 84, 78, 20);
int gapX = (PYRAMID.maxX() + second.minX()) / 2;
Box area = new Box(PYRAMID.minX(), 64, 0, second.maxX(), 64, 0);
FitFixture.World world = new FitFixture.World(area);
world.put(PYRAMID.minX(), 64, 0, STONE);
world.put(gapX, 64, 0, STONE);
integrate(world, area, start("{\"mode\":\"FORCE_CARVE\"}", TerrainAdaptation.NONE,
FitFixture.Piece.fixed(PYRAMID), FitFixture.Piece.fixed(second)));
assertEquals(AIR, world.at(PYRAMID.minX(), 64, 0));
assertEquals(STONE, world.at(gapX, 64, 0));
}
@Test
public void carveFootprintIsComputedOncePerStartAndPadding() {
FitStart start = start("{\"mode\":\"FORCE_CARVE\"}", TerrainAdaptation.NONE, FitFixture.Piece.fixed(PYRAMID));
StructureCarvingFootprint first = CarveFootprints.of(start, 6);
assertSame(first, CarveFootprints.of(start, 6));
assertNotSame(first, CarveFootprints.of(start, 7));
assertNotSame(first, CarveFootprints.of(
start("{\"mode\":\"FORCE_CARVE\"}", TerrainAdaptation.NONE, FitFixture.Piece.fixed(PYRAMID)), 6));
assertEquals(PYRAMID.minX() - 6, first.minX());
assertEquals(0L, first.distanceSquaredAt(PYRAMID.minX(), PYRAMID.minZ()));
assertEquals(PYRAMID.minY(), first.sourceMinYAt(PYRAMID.minX(), PYRAMID.minZ()));
assertEquals(PYRAMID.maxY(), first.sourceMaxYAt(PYRAMID.minX(), PYRAMID.minZ()));
}
@Test
public void concurrentCarveRequestsShareOneFootprintBuild() throws Exception {
FitStart start = start("{\"mode\":\"FORCE_CARVE\"}", TerrainAdaptation.NONE, FitFixture.Piece.fixed(PYRAMID));
int requestCount = 16;
ExecutorService executor = Executors.newFixedThreadPool(requestCount);
CountDownLatch ready = new CountDownLatch(requestCount);
CountDownLatch release = new CountDownLatch(1);
List<Future<StructureCarvingFootprint>> futures = new ArrayList<>();
try {
for (int request = 0; request < requestCount; request++) {
futures.add(executor.submit(() -> {
ready.countDown();
release.await();
return CarveFootprints.of(start, 11);
}));
}
assertTrue(ready.await(5, TimeUnit.SECONDS));
release.countDown();
StructureCarvingFootprint expected = futures.getFirst().get();
for (Future<StructureCarvingFootprint> future : futures) {
assertSame(expected, future.get());
}
} finally {
executor.shutdownNow();
}
}
@Test
public void carveFootprintCacheStaysInsideItsCellBudget() {
for (int index = 0; index < 40; index++) {
CarveFootprints.of(start("{\"mode\":\"FORCE_CARVE\"}", TerrainAdaptation.NONE, FitFixture.Piece.fixed(PYRAMID)), 128);
}
assertTrue(CarveFootprints.cachedCells() <= CarveFootprints.maximumCachedCells());
}
@Test
public void organicCarveNeverCutsBelowTheColumnSupportingFloor() {
Box area = new Box(PYRAMID.minX() - 6, PYRAMID.minY() - 4, PYRAMID.minZ() - 6,
PYRAMID.maxX() + 6, PYRAMID.maxY() + 12, PYRAMID.maxZ() + 6);
FitFixture.World world = filled(area);
TerrainIntegration.carveOrganicColumns(world.fitBlocks(), area, organicCarve(6, 0.85D));
assertEquals(AIR, world.at(PYRAMID.minX() + 10, PYRAMID.minY(), PYRAMID.minZ() + 10));
for (int x = area.minX(); x <= area.maxX(); x++) {
for (int z = area.minZ(); z <= area.maxZ(); z++) {
for (int y = area.minY(); y < PYRAMID.minY(); y++) {
assertEquals(STONE, world.at(x, y, z));
}
}
}
}
@Test
public void lobedCarveStaysInsideTheUniformCarveAndRemovesLess() {
Box area = new Box(PYRAMID.minX() - 10, PYRAMID.minY(), PYRAMID.minZ() - 10,
PYRAMID.maxX() + 10, PYRAMID.maxY() + 12, PYRAMID.maxZ() + 10);
FitFixture.World uniform = filled(area);
FitFixture.World lobed = filled(area);
TerrainIntegration.carveOrganicColumns(uniform.fitBlocks(), area, organicCarve(10, 0D));
TerrainIntegration.carveOrganicColumns(lobed.fitBlocks(), area, organicCarve(10, 0.85D));
int uniformAir = 0;
int lobedAir = 0;
for (int x = area.minX(); x <= area.maxX(); x++) {
for (int z = area.minZ(); z <= area.maxZ(); z++) {
for (int y = area.minY(); y <= area.maxY(); y++) {
boolean uniformCarved = uniform.at(x, y, z).equals(AIR);
boolean lobedCarved = lobed.at(x, y, z).equals(AIR);
assertTrue("lobe carved outside the uniform padding at " + x + "," + y + "," + z,
uniformCarved || !lobedCarved);
uniformAir += uniformCarved ? 1 : 0;
lobedAir += lobedCarved ? 1 : 0;
}
}
}
assertTrue(lobedAir > 0);
assertTrue("uniform " + uniformAir + " lobed " + lobedAir, lobedAir < uniformAir);
}
@Test
public void lobedCarveDepthWandersAlongAStraightFootprintEdge() {
int[] uniform = slabEdgeCarveDepths(0D);
int[] lobed = slabEdgeCarveDepths(0.85D);
assertTrue("uniform depths wander " + span(uniform), span(uniform) <= 2);
assertTrue("lobed depths wander " + span(lobed), span(lobed) >= 6);
for (int depth : lobed) {
assertTrue(depth >= 0 && depth <= SLAB_PADDING);
}
}
@Test
public void organicCarveIsIdenticalAcrossNeighboringChunkContexts() {
Box wide = new Box(PYRAMID.minX() - 6, PYRAMID.minY(), PYRAMID.minZ() - 6,
PYRAMID.maxX() + 6, PYRAMID.maxY() + 12, PYRAMID.maxZ() + 6);
Box narrow = new Box(PYRAMID.maxX() - 3, PYRAMID.minY(), PYRAMID.maxZ() - 3,
PYRAMID.maxX() + 6, PYRAMID.maxY() + 12, PYRAMID.maxZ() + 6);
FitFixture.World wideWorld = filled(wide);
FitFixture.World narrowWorld = filled(narrow);
TerrainIntegration.carveOrganicColumns(wideWorld.fitBlocks(), wide, organicCarve(6, 0.85D));
TerrainIntegration.carveOrganicColumns(narrowWorld.fitBlocks(), narrow, organicCarve(6, 0.85D));
int carved = 0;
for (int x = narrow.minX(); x <= narrow.maxX(); x++) {
for (int z = narrow.minZ(); z <= narrow.maxZ(); z++) {
for (int y = narrow.minY(); y <= narrow.maxY(); y++) {
BlockState expected = wideWorld.at(x, y, z);
assertEquals(expected, narrowWorld.at(x, y, z));
carved += expected.equals(AIR) ? 1 : 0;
}
}
}
assertTrue(carved > 0);
}
@Test
public void erodedForceCarveShrinkwrapsWithoutUnderminingTheFloor() {
Box area = new Box(PYRAMID.minX() - 6, PYRAMID.minY() - 2, PYRAMID.minZ() - 6,
PYRAMID.maxX() + 6, PYRAMID.maxY() + 12, PYRAMID.maxZ() + 6);
FitFixture.World world = filled(area);
int centerX = PYRAMID.minX() + PYRAMID.xSpan() / 2;
int centerZ = PYRAMID.minZ() + PYRAMID.zSpan() / 2;
integrate(world, area, start("{\"mode\":\"FORCE_CARVE\",\"shape\":\"ERODED\",\"horizontalPadding\":6,"
+ "\"ceilingPadding\":8,\"floorPadding\":0,\"erosionStrength\":1.0,\"erosionFrequency\":0.05}",
TerrainAdaptation.NONE, FitFixture.Piece.fixed(PYRAMID)));
assertEquals(AIR, world.at(centerX, PYRAMID.minY(), centerZ));
assertEquals(STONE, world.at(centerX, PYRAMID.minY() - 1, centerZ));
assertEquals(STONE, world.at(area.minX(), area.maxY(), area.minZ()));
}
private static void integrate(FitFixture.World world, Box area, FitStart start) {
TerrainIntegration.prepareTerrain(world.fitBlocks(), area, List.of(start), SEED, NATURAL, NO_PALETTES);
}
private static FitStart start(String terrainJson, TerrainAdaptation adaptation, FitFixture.Piece... pieces) {
return FitFixture.start(terrainJson, adaptation, StructureStep.STRONGHOLDS, pieces);
}
private static TerrainIntegration.SourceTerrainSnapshot snapshot(FitFixture.World world, Box area) {
BitSet layers = new BitSet(area.ySpan());
layers.set(0, area.ySpan());
return TerrainIntegration.SourceTerrainSnapshot.capture(world.fitBlocks(), area, layers);
}
private static FitFixture.World filled(Box area) {
FitFixture.World world = new FitFixture.World(area);
for (int x = area.minX(); x <= area.maxX(); x++) {
for (int z = area.minZ(); z <= area.maxZ(); z++) {
for (int y = area.minY(); y <= area.maxY(); y++) {
world.put(x, y, z, STONE);
}
}
}
return world;
}
private static TerrainIntegration.OrganicCarve organicCarve(int horizontalPadding, double lobeStrength) {
StructureTerrain terrain = erodedTerrain(horizontalPadding, lobeStrength);
FitStart start = start(JSON.toJson(terrain), TerrainAdaptation.NONE, FitFixture.Piece.fixed(PYRAMID));
return TerrainIntegration.organicCarve(CarveFootprints.of(start, horizontalPadding), terrain,
StructureCarveShape.ERODED, CARVE_SEED);
}
private static StructureTerrain erodedTerrain(int horizontalPadding, double lobeStrength) {
return JSON.fromJson("{\"mode\":\"FORCE_CARVE\",\"shape\":\"ERODED\",\"horizontalPadding\":" + horizontalPadding
+ ",\"ceilingPadding\":8,\"floorPadding\":0,\"erosionStrength\":1.0,\"erosionFrequency\":0.05,"
+ "\"lobeStrength\":" + lobeStrength + "}", StructureTerrain.class);
}
/**
* Outward carve depth for every column along the straight +X edge of a slab footprint, measured inside the source
* vertical span so the boundary is decided purely by the horizontal threshold.
*/
private static int[] slabEdgeCarveDepths(double lobeStrength) {
StructureCarvingFootprint footprint = StructureCarvingFootprint.fromColumns(sink -> {
for (int x = 0; x < SLAB_WIDTH; x++) {
for (int z = 0; z < SLAB_DEPTH; z++) {
sink.column(x, z, SLAB_MIN_Y, SLAB_MIN_Y + 8);
}
}
return true;
}, SLAB_PADDING, 1_000_000);
int transectY = SLAB_MIN_Y + 4;
Box area = new Box(SLAB_WIDTH, transectY, 0, SLAB_WIDTH - 1 + SLAB_PADDING, transectY, SLAB_DEPTH - 1);
FitFixture.World world = filled(area);
TerrainIntegration.carveOrganicColumns(world.fitBlocks(), area, TerrainIntegration.organicCarve(
footprint, erodedTerrain(SLAB_PADDING, lobeStrength), StructureCarveShape.ERODED, CARVE_SEED));
int[] depths = new int[SLAB_DEPTH];
for (int z = 0; z < SLAB_DEPTH; z++) {
int depth = 0;
while (depth < SLAB_PADDING && world.at(SLAB_WIDTH + depth, transectY, z).equals(AIR)) {
depth++;
}
depths[z] = depth;
}
return depths;
}
private static int span(int[] values) {
int lowest = Integer.MAX_VALUE;
int highest = Integer.MIN_VALUE;
for (int value : values) {
lowest = Math.min(lowest, value);
highest = Math.max(highest, value);
}
return highest - lowest;
}
}
@@ -1,49 +1,64 @@
package art.arcane.iris.engine.mantle.components;
import art.arcane.iris.core.loader.IrisData;
import art.arcane.iris.engine.UsableBlockPlatform;
import art.arcane.iris.engine.mantle.MantleWriter;
import art.arcane.iris.engine.object.material.IrisMaterialPalette;
import art.arcane.iris.spi.PlatformBlockState;
import art.arcane.iris.spi.IrisPlatform;
import art.arcane.iris.spi.IrisPlatforms;
import art.arcane.iris.spi.PlatformRegistries;
import art.arcane.volmlib.util.matter.MatterCavern;
import art.arcane.volmlib.util.math.RNG;
import com.volmit.block.BlockState;
import com.volmit.block.PaletteSampler;
import org.junit.After;
import org.junit.Test;
import org.mockito.InOrder;
import java.util.ArrayList;
import java.util.List;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyInt;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.inOrder;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verifyNoInteractions;
import static org.mockito.Mockito.when;
public class IrisStructureFoundationWriteTest {
@After
public void unbindPlatform() {
UsableBlockPlatform.unbind();
}
@Test
public void resolvesWorldCoordinatesThenClearsCavernBeforeWritingSupport() {
UsableBlockPlatform.bind();
MantleWriter writer = mock(MantleWriter.class);
IrisMaterialPalette palette = mock(IrisMaterialPalette.class);
RNG rng = new RNG(1337L);
IrisData data = mock(IrisData.class);
PlatformBlockState deepslateBricks = mock(PlatformBlockState.class);
when(palette.get(rng, 12, -247, -18, data)).thenReturn(deepslateBricks);
List<String> asked = new ArrayList<>();
PaletteSampler picker = (x, y, z) -> {
asked.add((int) x + "," + (int) y + "," + (int) z);
return new BlockState("minecraft:deepslate_bricks");
};
StructurePlacing.writeFoundationSupport(
writer, palette, rng, data, 12, 9, -18, -256);
StructurePlacing.writeFoundationSupport(writer, picker, 12, 9, -18, -256);
InOrder order = inOrder(palette, writer);
order.verify(palette).get(rng, 12, -247, -18, data);
assertEquals(List.of("12,-247,-18"), asked);
InOrder order = inOrder(writer);
order.verify(writer).clearData(12, 9, -18, MatterCavern.class);
order.verify(writer).set(12, 9, -18, deepslateBricks);
order.verify(writer).set(eq(12), eq(9), eq(-18), any(art.arcane.iris.spi.PlatformBlockState.class));
}
@Test
public void unresolvedPaletteFailsBeforeChangingCavernOrBlocks() {
UsableBlockPlatform.unbind();
IrisPlatform platform = mock(IrisPlatform.class);
when(platform.registries()).thenReturn(mock(PlatformRegistries.class));
IrisPlatforms.bind(platform);
MantleWriter writer = mock(MantleWriter.class);
IrisMaterialPalette palette = mock(IrisMaterialPalette.class);
RNG rng = new RNG(1337L);
IrisData data = mock(IrisData.class);
try {
StructurePlacing.writeFoundationSupport(
writer, palette, rng, data, 12, 9, -18, -256);
StructurePlacing.writeFoundationSupport(writer, (x, y, z) -> new BlockState("test:unknown"), 12, 9, -18, -256);
} catch (IllegalStateException error) {
assertTrue(error.getMessage().contains("12,-247,-18"));
verifyNoInteractions(writer);
@@ -1,6 +1,6 @@
package art.arcane.iris.engine.mantle.components;
import art.arcane.iris.engine.object.structure.IrisStructureCarveShape;
import art.arcane.iris.builtin.structure.StructureCarveShape;
import art.arcane.iris.util.project.noise.CNG;
import art.arcane.volmlib.util.math.RNG;
import org.junit.Test;
@@ -13,31 +13,31 @@ public class StructureCarveEnvelopeTest {
@Test
public void exactStructureFootprintAlwaysCarves() {
assertTrue(StructureCarveEnvelope.shouldCarveOverboreCell(
IrisStructureCarveShape.ERODED, 0D, 0D, 1D));
StructureCarveShape.ERODED, 0D, 0D, 1D));
assertTrue(StructureCarveEnvelope.shouldCarveOverboreCell(
IrisStructureCarveShape.ROUNDED, 0D, 0D, 1D));
StructureCarveShape.ROUNDED, 0D, 0D, 1D));
}
@Test
public void boxModeKeepsStraightCandidateVolume() {
assertTrue(StructureCarveEnvelope.shouldCarveOverboreCell(
IrisStructureCarveShape.BOX, 100D, 0D, 1D));
StructureCarveShape.BOX, 100D, 0D, 1D));
}
@Test
public void roundedModeStopsAtConfiguredReach() {
assertTrue(StructureCarveEnvelope.shouldCarveOverboreCell(
IrisStructureCarveShape.ROUNDED, 1D, 0D, 1D));
StructureCarveShape.ROUNDED, 1D, 0D, 1D));
assertFalse(StructureCarveEnvelope.shouldCarveOverboreCell(
IrisStructureCarveShape.ROUNDED, 1.000001D, 1D, 0D));
StructureCarveShape.ROUNDED, 1.000001D, 1D, 0D));
}
@Test
public void zeroErosionStrengthMatchesRoundedMode() {
assertTrue(StructureCarveEnvelope.shouldCarveOverboreCell(
IrisStructureCarveShape.ERODED, 1D, 0D, 0D));
StructureCarveShape.ERODED, 1D, 0D, 0D));
assertFalse(StructureCarveEnvelope.shouldCarveOverboreCell(
IrisStructureCarveShape.ERODED, 1.000001D, 1D, 0D));
StructureCarveShape.ERODED, 1.000001D, 1D, 0D));
}
@Test
@@ -68,7 +68,7 @@ public class StructureCarveEnvelopeTest {
CNG roll = CNG.signature(new RNG(4242L));
for (double strength : new double[]{0.25D, 0.5D, 1D}) {
int limit = IrisStructureCarveShape.ERODED.maximumCeilingExtension(10, strength);
int limit = StructureCarveShape.ERODED.maximumCeilingExtension(10, strength);
for (int x = -32; x <= 32; x++) {
for (int z = -32; z <= 32; z++) {
double reach = StructureCarveEnvelope.erodedUpReach(roll, 0.05D, strength, x, z, 10);
@@ -1,149 +0,0 @@
package art.arcane.iris.engine.object.structure;
import art.arcane.iris.engine.object.material.IrisMaterialPalette;
import art.arcane.iris.engine.object.structure.IrisStructureCarveShape;
import art.arcane.iris.engine.object.structure.IrisStructureTerrain;
import art.arcane.iris.engine.object.structure.IrisStructureTerrainMode;
import art.arcane.iris.engine.object.annotations.MaxNumber;
import art.arcane.iris.engine.object.annotations.MinNumber;
import org.junit.Test;
import java.lang.reflect.Field;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertSame;
public class IrisStructurePlacementCarveSettingsTest {
@Test
public void defaultsToSourceTerrainWithBoxCarving() {
IrisStructureTerrain terrain = new IrisStructureTerrain();
assertEquals(IrisStructureTerrainMode.SOURCE, terrain.resolvedMode());
assertEquals(IrisStructureCarveShape.BOX, terrain.getShape());
assertEquals(IrisStructureCarveShape.BOX, terrain.resolvedShape());
assertEquals(0.8D, terrain.getErosionStrength(), 0D);
assertEquals(0.8D, terrain.resolvedErosionStrength(), 0D);
assertEquals(0.07D, terrain.getErosionFrequency(), 0D);
assertEquals(0.07D, terrain.resolvedErosionFrequency(), 0D);
assertEquals(0D, terrain.getLobeFrequency(), 0D);
assertEquals(0.021D, terrain.resolvedLobeFrequency(), 1.0E-12D);
assertEquals(0.85D, terrain.getLobeStrength(), 0D);
assertEquals(0.85D, terrain.resolvedLobeStrength(), 0D);
}
@Test
public void lobeFrequencyAutoDerivesFromErosionFrequencyUntilAuthored() {
IrisStructureTerrain terrain = new IrisStructureTerrain().setErosionFrequency(0.05D);
assertEquals(0.015D, terrain.resolvedLobeFrequency(), 1.0E-12D);
terrain.setLobeFrequency(Double.NaN);
assertEquals(0.015D, terrain.resolvedLobeFrequency(), 1.0E-12D);
terrain.setLobeFrequency(-1D);
assertEquals(0.015D, terrain.resolvedLobeFrequency(), 1.0E-12D);
terrain.setLobeFrequency(0.04D);
assertEquals(0.04D, terrain.resolvedLobeFrequency(), 0D);
terrain.setLobeFrequency(2D);
assertEquals(1D, terrain.resolvedLobeFrequency(), 0D);
}
@Test
public void lobeStrengthClampsToTheAuthoredBand() {
IrisStructureTerrain terrain = new IrisStructureTerrain().setLobeStrength(Double.NaN);
assertEquals(0.85D, terrain.resolvedLobeStrength(), 0D);
terrain.setLobeStrength(-1D);
assertEquals(0D, terrain.resolvedLobeStrength(), 0D);
terrain.setLobeStrength(2D);
assertEquals(1D, terrain.resolvedLobeStrength(), 0D);
terrain.setLobeStrength(0.4D);
assertEquals(0.4D, terrain.resolvedLobeStrength(), 0D);
}
@Test
public void carveShapesExposeTheirMaximumCeilingScale() {
assertEquals(1D, IrisStructureCarveShape.BOX.maximumCeilingScale(), 0D);
assertEquals(1D, IrisStructureCarveShape.ROUNDED.maximumCeilingScale(), 0D);
assertEquals(1.8D, IrisStructureCarveShape.ERODED.maximumCeilingScale(), 0D);
assertEquals(10, IrisStructureCarveShape.BOX.maximumCeilingExtension(10));
assertEquals(10, IrisStructureCarveShape.ROUNDED.maximumCeilingExtension(10));
assertEquals(18, IrisStructureCarveShape.ERODED.maximumCeilingExtension(10));
assertEquals(10, IrisStructureCarveShape.ERODED.maximumCeilingExtension(10, 0D));
assertEquals(14, IrisStructureCarveShape.ERODED.maximumCeilingExtension(10, 0.5D));
assertEquals(0, IrisStructureCarveShape.ERODED.maximumCeilingExtension(0));
}
@Test
public void nullAndNonFiniteValuesResolveToDefaults() {
IrisStructureTerrain terrain = new IrisStructureTerrain()
.setShape(null)
.setErosionStrength(Double.NaN)
.setErosionFrequency(Double.POSITIVE_INFINITY);
assertEquals(IrisStructureCarveShape.BOX, terrain.resolvedShape());
assertEquals(0.8D, terrain.resolvedErosionStrength(), 0D);
assertEquals(0.07D, terrain.resolvedErosionFrequency(), 0D);
terrain.setErosionStrength(Double.NEGATIVE_INFINITY);
terrain.setErosionFrequency(Double.NaN);
assertEquals(0.8D, terrain.resolvedErosionStrength(), 0D);
assertEquals(0.07D, terrain.resolvedErosionFrequency(), 0D);
}
@Test
public void finiteValuesClampToAuthoredBounds() {
IrisStructureTerrain terrain = new IrisStructureTerrain()
.setErosionStrength(-1D)
.setErosionFrequency(0D);
assertEquals(0D, terrain.resolvedErosionStrength(), 0D);
assertEquals(0.001D, terrain.resolvedErosionFrequency(), 0D);
terrain.setErosionStrength(2D);
terrain.setErosionFrequency(2D);
assertEquals(1D, terrain.resolvedErosionStrength(), 0D);
assertEquals(1D, terrain.resolvedErosionFrequency(), 0D);
}
@Test
public void encaseModeCarriesAnOptionalPaletteOverride() {
IrisStructureTerrain terrain = new IrisStructureTerrain()
.setMode(IrisStructureTerrainMode.ENCASE);
assertEquals(IrisStructureTerrainMode.ENCASE, terrain.resolvedMode());
assertNull(terrain.getEncasePalette());
IrisMaterialPalette palette = new IrisMaterialPalette().qclear().qadd("minecraft:tuff");
assertSame(palette, terrain.setEncasePalette(palette).getEncasePalette());
}
@Test
public void numericSchemaBoundsMatchRuntimeBounds() throws NoSuchFieldException {
assertBounds("erosionStrength", 0D, 1D);
assertBounds("erosionFrequency", 0.001D, 1D);
assertBounds("lobeFrequency", 0D, 1D);
assertBounds("lobeStrength", 0D, 1D);
}
private void assertBounds(String fieldName, double expectedMinimum,
double expectedMaximum) throws NoSuchFieldException {
Field field = IrisStructureTerrain.class.getDeclaredField(fieldName);
MinNumber minimum = field.getAnnotation(MinNumber.class);
MaxNumber maximum = field.getAnnotation(MaxNumber.class);
assertNotNull(minimum);
assertNotNull(maximum);
assertEquals(expectedMinimum, minimum.value(), 0D);
assertEquals(expectedMaximum, maximum.value(), 0D);
}
}
@@ -1,50 +0,0 @@
package art.arcane.iris.engine.object.structure;
import art.arcane.iris.engine.object.structure.IrisStructureStiltSettings;
import art.arcane.iris.engine.object.annotations.MaxNumber;
import art.arcane.iris.engine.object.annotations.MinNumber;
import org.junit.Test;
import java.lang.reflect.Field;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
public class IrisStructureStiltSettingsTest {
@Test
public void defaultsToCobblestoneFoundation() {
IrisStructureStiltSettings settings = new IrisStructureStiltSettings();
assertEquals(64, settings.getMaxDepth());
assertEquals(1, settings.getSpacing());
assertFalse(settings.isSupportNonOccluding());
assertNotNull(settings.getPalette());
assertEquals(1, settings.getPalette().getPalette().size());
assertEquals("minecraft:cobblestone", settings.getPalette().getPalette().get(0).getBlock());
}
@Test
public void maxDepthSchemaIsBoundedToTheMaximumWorldHeight() throws NoSuchFieldException {
Field maxDepth = IrisStructureStiltSettings.class.getDeclaredField("maxDepth");
MinNumber minimum = maxDepth.getAnnotation(MinNumber.class);
MaxNumber maximum = maxDepth.getAnnotation(MaxNumber.class);
assertNotNull(minimum);
assertNotNull(maximum);
assertEquals(1.0, minimum.value(), 0.0);
assertEquals(4064.0, maximum.value(), 0.0);
}
@Test
public void spacingSchemaSupportsSparseFoundations() throws NoSuchFieldException {
Field spacing = IrisStructureStiltSettings.class.getDeclaredField("spacing");
MinNumber minimum = spacing.getAnnotation(MinNumber.class);
MaxNumber maximum = spacing.getAnnotation(MaxNumber.class);
assertNotNull(minimum);
assertNotNull(maximum);
assertEquals(1.0, minimum.value(), 0.0);
assertEquals(64.0, maximum.value(), 0.0);
}
}
@@ -1,54 +0,0 @@
package art.arcane.iris.engine.object.structure;
import art.arcane.iris.engine.object.structure.IrisStructureYBand;
import art.arcane.iris.engine.object.annotations.MaxNumber;
import art.arcane.iris.engine.object.annotations.MinNumber;
import org.junit.Test;
import java.lang.reflect.Field;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
public class IrisStructureYBandTest {
@Test
public void authoredBoundsResolveInOrder() {
IrisStructureYBand band = new IrisStructureYBand().setMin(-120).setMax(-20);
assertEquals(-120, band.resolvedMin());
assertEquals(-20, band.resolvedMax());
}
@Test
public void reversedBoundsNormalizeInsteadOfInverting() {
IrisStructureYBand band = new IrisStructureYBand().setMin(-20).setMax(-120);
assertEquals(-120, band.resolvedMin());
assertEquals(-20, band.resolvedMax());
}
@Test
public void collapsedBoundsResolveToASingleY() {
IrisStructureYBand band = new IrisStructureYBand().setMin(-64).setMax(-64);
assertEquals(-64, band.resolvedMin());
assertEquals(-64, band.resolvedMax());
}
@Test
public void numericSchemaBoundsCoverTheWholeBuildRange() throws NoSuchFieldException {
assertBounds("min");
assertBounds("max");
}
private void assertBounds(String fieldName) throws NoSuchFieldException {
Field field = IrisStructureYBand.class.getDeclaredField(fieldName);
MinNumber minimum = field.getAnnotation(MinNumber.class);
MaxNumber maximum = field.getAnnotation(MaxNumber.class);
assertNotNull(minimum);
assertNotNull(maximum);
assertEquals(-4064D, minimum.value(), 0D);
assertEquals(4064D, maximum.value(), 0D);
}
}
@@ -13,11 +13,10 @@ 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.structure.vanilla.IrisNativeStructure;
import art.arcane.iris.engine.object.structure.vanilla.IrisNativeStructureDecision;
import art.arcane.iris.engine.object.structure.IrisStructure;
import art.arcane.iris.engine.object.structure.IrisStructurePlacement;
import art.arcane.iris.engine.object.world.IrisWorld;
import art.arcane.iris.engine.object.structure.vanilla.NativeStructureGenerationStatus;
import art.arcane.iris.engine.framework.NativeStructureGenerationStatus;
import art.arcane.iris.engine.object.structure.StructureDistribution;
import art.arcane.iris.spi.IrisPlatform;
import art.arcane.iris.spi.IrisPlatforms;
@@ -47,9 +46,9 @@ import static org.mockito.Mockito.when;
public class StructureHandlerTest {
@Test
public void registeredEligibilityMatchesFindExecutionTruthTable() {
IrisNativeStructureDecision replacement = decision(NativeStructureGenerationStatus.REPLACED_BY_IRIS);
IrisNativeStructureDecision generated = decision(NativeStructureGenerationStatus.GENERATE_NATIVE);
IrisNativeStructureDecision disabled = decision(NativeStructureGenerationStatus.DISABLED_BY_PACK);
NativeStructureGenerationStatus replacement = NativeStructureGenerationStatus.REPLACED_BY_IRIS;
NativeStructureGenerationStatus generated = NativeStructureGenerationStatus.GENERATE_NATIVE;
NativeStructureGenerationStatus disabled = NativeStructureGenerationStatus.DISABLED_BY_PACK;
assertTrue(StructureHandler.isEligibleRegisteredKey(
replacement, false, false, true, false, false));
@@ -258,9 +257,6 @@ public class StructureHandlerTest {
assertFalse(method.contains("catch ("));
}
private static IrisNativeStructureDecision decision(NativeStructureGenerationStatus status) {
return new IrisNativeStructureDecision(status, 0, null, false, null, null);
}
private static IrisStructurePlacement nativePlacement(String key, StructureDistribution distribution,
double density) {