Merge remote-tracking branch 'origin/master'

This commit is contained in:
SwiftSwamp committed 2026-10-31 17:42:51 -06:00
commit 55bc7365f1
498 files changed
+54571 -1345

No files matched your search

@@ -44,7 +44,7 @@ public class PlatformStateRebindTest {
}
@Test
public void chunkDataAirIsResolvedAgainstTheCurrentlyBoundPlatform() {
public void chunkDataAirIsResolvedAgainstThePlatformBoundWhenTheBufferFirstReadsIt() {
NativeBlockState first = bindPlatform("first");
SectionBuffer holder = new SectionBuffer(384);
@@ -53,7 +53,8 @@ public class PlatformStateRebindTest {
IrisPlatforms.unbind();
NativeBlockState second = bindPlatform("second");
assertSame(second, holder.getRaw(0, -1, 0));
assertSame(first, holder.getRaw(0, -1, 0));
assertSame(second, new SectionBuffer(384).getRaw(0, -1, 0));
}
@Test
@@ -264,6 +264,42 @@ public class SectionBufferTest {
assertEquals(List.of(9, 8, 7), order);
}
@Test
public void columnReadsMatchSingleReadsAcrossEmptySectionsAndBufferEdges() {
SectionBuffer buffer = new SectionBuffer(40);
NativeBlockState stone = mock(NativeBlockState.class);
NativeBlockState dirt = mock(NativeBlockState.class);
buffer.setRaw(3, 2, 9, stone);
buffer.setRaw(3, 33, 9, dirt);
buffer.setRaw(3, 39, 9, stone);
ColumnExtentListeningHunk<NativeBlockState> listening = new ColumnExtentListeningHunk<>(buffer, (x, y, z, state) -> {
});
NativeBlockState[] column = new NativeBlockState[52];
ColumnReadHunk.readColumn(listening, 3, 9, -3, 44, column, 4);
for (int y = -3; y <= 44; y++) {
assertSame("y=" + y, buffer.getRaw(3, y, 9), column[4 + y + 3]);
}
assertNull(column[0]);
assertSame(dirt, column[4 + 33 + 3]);
}
@Test
public void plainHunksAnswerColumnReadsWithSingleReads() {
Hunk<NativeBlockState> array = Hunk.newArrayHunk(16, 32, 16);
NativeBlockState stone = mock(NativeBlockState.class);
array.setRaw(5, 7, 1, stone);
NativeBlockState[] column = new NativeBlockState[10];
ColumnReadHunk.readColumn(array, 5, 1, 6, 8, column, 2);
assertNull(column[2]);
assertSame(stone, column[3]);
assertNull(column[4]);
assertNull(column[5]);
}
private static void assertSameContents(SectionBuffer expected, SectionBuffer actual) {
assertEquals(expected.sectionCount(), actual.sectionCount());
NativeBlockState[] expectedPalette = expected.palette();
@@ -3,6 +3,8 @@ package art.arcane.iris.generation.context;
import art.arcane.iris.generation.runtime.Engine;
import org.junit.Test;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.TimeUnit;
@@ -50,6 +52,42 @@ public class IrisContextIsolationTest {
assertNull(rightAfterClose.get());
}
@Test
public void contextsStayIsolatedWhenThreadsOutnumberTheBindingSlots() throws Exception {
Engine engine = mock(Engine.class);
int threads = 640;
CyclicBarrier allBound = new CyclicBarrier(threads);
AtomicReference<Throwable> failure = new AtomicReference<>();
List<Thread> workers = new ArrayList<>(threads);
for (int index = 0; index < threads; index++) {
long session = index + 1L;
Thread worker = new Thread(() -> {
try (IrisContext.Scope ignored = IrisContext.open(engine, session, null)) {
allBound.await(30L, TimeUnit.SECONDS);
if (IrisContext.get().getGenerationSessionId() != session) {
failure.compareAndSet(null, new AssertionError("Thread observed session "
+ IrisContext.get().getGenerationSessionId() + " instead of " + session));
}
allBound.await(30L, TimeUnit.SECONDS);
} catch (Throwable thrown) {
failure.compareAndSet(null, thrown);
}
if (IrisContext.get() != null) {
failure.compareAndSet(null, new AssertionError("Context survived its scope"));
}
}, "iris-context-crowd-" + index);
workers.add(worker);
worker.start();
}
for (Thread worker : workers) {
worker.join(60000L);
assertFalse("Context worker did not finish.", worker.isAlive());
}
assertNull(failure.get());
assertNull(IrisContext.get());
}
@Test
public void scopeRebindsWorkerWhenEngineChanges() throws Exception {
Engine firstEngine = mock(Engine.class);
@@ -1,80 +0,0 @@
package art.arcane.iris.generation.hydrology.engine;
import art.arcane.iris.generation.hydrology.grid.HeightLattice;
import art.arcane.iris.generation.hydrology.grid.HydrologySampleBuffer;
import art.arcane.iris.generation.hydrology.grid.HydrologyTerrainSource;
import org.junit.Test;
import java.util.concurrent.atomic.AtomicLong;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertThrows;
public class FineLatticeSourceTest {
@Test
public void windowLatticeReadsItsNodesFromTheFineLattice() {
CountingTerrain terrain = new CountingTerrain();
HeightLattice fine = new HeightLattice(terrain, 4, false, 1 << 16);
HeightLattice window = new HeightLattice(new FineLatticeSource(fine, terrain), 8, false, 1 << 16);
fine.fill(0, 0, 64, 64, new HydrologySampleBuffer(64 * 64));
assertEquals(4096L, terrain.samples.get());
HydrologySampleBuffer held = new HydrologySampleBuffer(32 * 32);
window.fill(0, 0, 32, 32, held);
assertEquals(4096L, terrain.samples.get());
assertHeights(held, 0, 0, 32);
HydrologySampleBuffer fresh = new HydrologySampleBuffer(16 * 16);
window.fill(32, 0, 16, 16, fresh);
assertEquals(4096L + 256L, terrain.samples.get());
assertHeights(fresh, 32, 0, 16);
fine.fill(64, 0, 32, 32, new HydrologySampleBuffer(32 * 32));
assertEquals(4096L + 1024L, terrain.samples.get());
FineLatticeSource source = new FineLatticeSource(fine, terrain);
assertThrows(IllegalArgumentException.class, () -> source.sample(new int[]{8}, new int[]{8}, new HydrologySampleBuffer(1), true));
assertThrows(IllegalArgumentException.class, () -> source.sample(new int[]{6}, new int[]{8}, new HydrologySampleBuffer(1), false));
}
private static void assertHeights(HydrologySampleBuffer samples, int cellX0, int cellZ0, int side) {
for (int index = 0; index < side * side; index++) {
int x = (cellX0 + index % side) * 8;
int z = (cellZ0 + index / side) * 8;
assertEquals(x + "," + z, Float.floatToRawIntBits(CountingTerrain.height(x, z)), Float.floatToRawIntBits(samples.height()[index]));
}
}
private static final class CountingTerrain implements HydrologyTerrainSource {
private final AtomicLong samples = new AtomicLong();
private static float height(int x, int z) {
return 64f + (float) Math.sin(x * 0.013D) * 9f + (float) Math.cos(z * 0.021D) * 7f;
}
@Override
public void sample(int[] xs, int[] zs, HydrologySampleBuffer out, boolean baseOnly) {
samples.addAndGet(xs.length);
for (int index = 0; index < xs.length; index++) {
out.height()[index] = height(xs[index], zs[index]);
out.permission()[index] = HydrologySampleBuffer.ALLOW_STREAMS | HydrologySampleBuffer.ALLOW_PONDS;
out.rainfall()[index] = 1f;
out.pondDensity()[index] = 1f;
}
}
@Override
public int seaLevel() {
return 40;
}
@Override
public int minY() {
return 0;
}
@Override
public int maxY() {
return 384;
}
}
}
@@ -67,6 +67,7 @@ import java.util.concurrent.atomic.AtomicReference;
import java.util.function.BooleanSupplier;
import java.util.stream.Stream;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
@@ -215,6 +216,34 @@ public class HydrologyRuntimeTest {
assertEquals(planned + 1L, runtime.previewRevision());
}
@Test(timeout = 180_000L)
public void concurrentDemandsShareOneRasterBuild() throws Exception {
FakePlanners planners = new FakePlanners(settings(0, false));
HydrologyRuntime runtime = runtime(planners, () -> false);
runtime.prepareWindowsAround(0, 0, 0, 0, 1).get(TIMEOUT_SECONDS, TimeUnit.SECONDS);
CountDownLatch gate = new CountDownLatch(1);
planners.naturalGate = gate;
AtomicReference<ChunkWaterRaster> first = new AtomicReference<>();
AtomicReference<ChunkWaterRaster> second = new AtomicReference<>();
Thread leader = new Thread(() -> first.set(runtime.raster(0, 0)));
Thread follower = new Thread(() -> second.set(runtime.raster(0, 0)));
try {
leader.start();
await(() -> planners.naturalSamples.get() > 0, "the first demand starts sampling");
follower.start();
await(() -> follower.getState() == Thread.State.WAITING || follower.getState() == Thread.State.TIMED_WAITING,
"the second demand waits");
assertEquals(0, planners.naturalSamplesOn(follower));
} finally {
gate.countDown();
leader.join(TimeUnit.SECONDS.toMillis(TIMEOUT_SECONDS));
follower.join(TimeUnit.SECONDS.toMillis(TIMEOUT_SECONDS));
}
assertFalse(first.get().provisional());
assertSame(first.get(), second.get());
assertEquals(0, planners.naturalSamplesOn(follower));
}
@Test(timeout = 180_000L)
public void failedRasterDoesNotAdvancePreviewRevision() throws Exception {
FakePlanners planners = new FakePlanners(settings(0, false));
@@ -414,6 +443,35 @@ public class HydrologyRuntimeTest {
assertEquals(3, prefetches.get());
}
@Test(timeout = 180_000L)
public void boundedPregenerationPrefetchesOnlyWindowsItsChunksNeed() {
FakePlanners planners = new FakePlanners(settings());
HydrologyPlanCache cache = spy(new HydrologyPlanCache(planners.settings, planners::region, planners::window,
pool(planners, 2), () -> false));
List<int[]> prepared = Collections.synchronizedList(new ArrayList<>());
doAnswer(invocation -> {
prepared.add(new int[]{invocation.getArgument(0), invocation.getArgument(1), invocation.getArgument(2), invocation.getArgument(3),
invocation.getArgument(4)});
return CompletableFuture.completedFuture(null);
}).when(cache).prepareWindowsAround(anyInt(), anyInt(), anyInt(), anyInt(), anyInt());
HydrologyRuntime runtime = new HydrologyRuntime(planners.settings, cache, planners::natural, () -> false, planners.ticker::get);
runtimes.add(runtime);
int chunks = WindowKey.SIZE >> 4;
HydrologyPregeneration pregeneration = runtime.openPregeneration();
pregeneration.bound(0, 0, 1, 1);
runtime.raster(0, 0);
assertArrayEquals(new int[]{-chunks, -chunks, 3 * chunks - 1, 3 * chunks - 1, 0}, prepared.getLast());
runtime.raster(chunks + 5, chunks + 5);
assertArrayEquals(new int[]{-chunks, -chunks, 3 * chunks - 1, 3 * chunks - 1, 0}, prepared.getLast());
runtime.raster(-3 * chunks, 0);
assertArrayEquals(new int[]{-3 * chunks, 0, -3 * chunks, 0, 2}, prepared.getLast());
pregeneration.close();
runtime.raster(1, 1);
assertArrayEquals(new int[]{1, 1, 1, 1, 2}, prepared.getLast());
}
@Test(timeout = 180_000L)
public void preparePregenerationPlansRegionsInOrder() throws Exception {
FakePlanners planners = new FakePlanners(settings());
@@ -129,6 +129,52 @@ public class IrisHydrologyTerrainSourceTest {
}
}
@Test
public void climateZonesDryOutRainfallAndPondsOutsideOptedOutBiomes() throws Exception {
Path pack = EngineFixture.pack(temporaryFolder.newFolder().toPath());
int[] xs = new int[COLUMNS];
int[] zs = new int[COLUMNS];
columns(xs, zs);
try (EngineFixture.Environment ignored = EngineFixture.environment(); EngineFixture fixture = new EngineFixture(pack)) {
IrisHydrology config = new IrisHydrology().setEnabled(true).setPersist(false);
config.getClimate().setEnabled(true).setDryness(0.5D).setTransition(0D).getStyle().setZoom(4D);
HydrologySettings settings = HydrologySettings.compile(config, EngineFixture.SEED, fixture.dimension.getFluidHeight(), 0,
EngineFixture.HEIGHT);
fixture.data.getBiomeLoader().load("meadow").getHydrologyPolicy().setClimateZones(false);
IrisHydrologyTerrainSource source = new IrisHydrologyTerrainSource(fixture.complex, fixture.dimension, settings, null, 1,
HydrologyBinding.UNBOUND);
HydrologySampleBuffer samples = new HydrologySampleBuffer(COLUMNS);
source.sample(xs, zs, samples, false);
int dry = 0;
int wet = 0;
int kept = 0;
for (int index = 0; index < COLUMNS; index++) {
int x = xs[index];
int z = zs[index];
boolean meadow = fixture.complex.getBaseBiomeStream().get(x, z).getLoadKey().equals("meadow");
boolean alpha = fixture.complex.getRegionStream().get(x, z).getLoadKey().equals("alpha");
String at = x + "," + z;
assertEquals(at, alpha ? "water" : null, source.channelFluid(x, z));
if (meadow) {
assertEquals(at, 2f, samples.rainfall()[index], 0f);
assertEquals(at, alpha ? 3f : 1f, samples.pondDensity()[index], 0f);
kept++;
continue;
}
boolean zoneDry = samples.rainfall()[index] == 0f;
assertEquals(at, zoneDry ? 0f : 0.5f, samples.rainfall()[index], 0f);
assertEquals(at, zoneDry ? 0f : alpha ? 3f : 1f, samples.pondDensity()[index], 0f);
if (zoneDry) {
dry++;
} else {
wet++;
}
}
assertTrue("dry columns " + dry + ", wet columns " + wet + ", opted-out columns " + kept,
dry > COLUMNS / 20 && wet > COLUMNS / 20 && kept > 0);
}
}
private static void assertUnknownFluidRejected(EngineFixture fixture, HydrologySettings settings, int[] xs, int[] zs) {
IrisRegion beta = fixture.data.getRegionLoader().load("beta");
beta.setHydrologyPolicy(new IrisHydrologyPolicy().setFluid("slime"));
@@ -154,10 +200,9 @@ public class IrisHydrologyTerrainSourceTest {
HydrologySampleBuffer rect = new HydrologySampleBuffer(32 * 32);
fine.fill(-600, 400, 32, 32, rect);
assertMatchesScalar(reference, "fine rect", rect, nodes(-600, 400, 32, 1, 4), false);
HeightLattice window = new HeightLattice(new FineLatticeSource(fine, source), 8, false, 1 << 16);
HydrologySampleBuffer strided = new HydrologySampleBuffer(16 * 16);
window.fill(-150, 300, 16, 16, 3, strided);
assertMatchesScalar(reference, "window strided", strided, nodes(-150, 300, 16, 3, 8), false);
fine.fill(-300, 600, 16, 16, 6, strided);
assertMatchesScalar(reference, "fine strided", strided, nodes(-300, 600, 16, 6, 4), false);
HeightLattice coarse = new HeightLattice(source, 64, true, 1 << 12);
HydrologySampleBuffer coarseBase = new HydrologySampleBuffer(16 * 16);
coarse.fill(-8, -8, 16, 16, coarseBase);
@@ -100,6 +100,37 @@ public class HeightLatticeTest {
assertEquals(DISTINCT_ACROSS_NINE, source.samples());
}
@Test
public void evictionToleratesConcurrentTileUse() throws Exception {
HeightLattice lattice = new HeightLattice(new CountingSource(), 1, false, 96 * 1024);
int threads = 12;
CyclicBarrier start = new CyclicBarrier(threads);
ExecutorService pool = Executors.newFixedThreadPool(threads);
try {
List<Future<Void>> results = new ArrayList<>();
for (int thread = 0; thread < threads; thread++) {
long seed = 31L * thread + 7L;
Callable<Void> task = () -> {
Random random = new Random(seed);
HydrologySampleBuffer out = new HydrologySampleBuffer(4);
start.await();
for (int fill = 0; fill < 40_000; fill++) {
int tileX = random.nextInt(24);
int tileZ = random.nextInt(24);
lattice.fill(tileX * 32 + random.nextInt(31), tileZ * 32 + random.nextInt(31), 2, 2, out);
}
return null;
};
results.add(pool.submit(task));
}
for (Future<Void> result : results) {
result.get(120, TimeUnit.SECONDS);
}
} finally {
pool.shutdownNow();
}
}
@Test
public void returnsBitIdenticalValues() {
HeightLattice full = new HeightLattice(new CountingSource(), 8, false, 1 << 16);
@@ -287,6 +318,31 @@ public class HeightLatticeTest {
assertThrows(IllegalArgumentException.class, () -> lattice.fill(cellXs, cellZs, new HydrologySampleBuffer(5)));
}
@Test
public void sampledColumnsAreReadOnceAndMatchTheSource() {
CountingSource source = new CountingSource();
HeightLattice lattice = new HeightLattice(source, 4, false, 1 << 16);
int[] xs = {5, -13, 5, 1027, -13, 6};
int[] zs = {-2, 77, -2, 3, 77, -2};
HydrologySampleBuffer first = new HydrologySampleBuffer(xs.length);
lattice.sampleColumns(xs, zs, first);
assertEquals(4, source.samples());
HydrologySampleBuffer second = new HydrologySampleBuffer(xs.length);
lattice.sampleColumns(xs, zs, second);
assertEquals(4, source.samples());
HydrologySampleBuffer expected = new HydrologySampleBuffer(xs.length);
new CountingSource().sample(xs, zs, expected, false);
for (int index = 0; index < xs.length; index++) {
assertEquals(Float.floatToIntBits(expected.height()[index]), Float.floatToIntBits(first.height()[index]));
assertEquals(Float.floatToIntBits(expected.height()[index]), Float.floatToIntBits(second.height()[index]));
assertEquals(expected.ocean()[index], second.ocean()[index]);
assertEquals(expected.permission()[index], second.permission()[index]);
assertEquals(expected.fluidProfile()[index], second.fluidProfile()[index]);
}
lattice.sampleColumns(new int[0], new int[0], new HydrologySampleBuffer(0));
assertEquals(1, source.calls());
}
private static void fillWindow(HeightLattice lattice, int wx, int wz, int cell, boolean baseOnly) {
assertFill(lattice, cell, baseOnly, (wx - 1) * WINDOW, (wz - 1) * WINDOW, AREA, AREA);
}
@@ -1045,7 +1045,7 @@ public class HydrologyPlanCacheTest {
}
private static WindowPlanner windowPlanner(HydrologySettings settings, SyntheticTerrain terrain) {
return new WindowPlanner(settings, new HeightLattice(terrain, WindowPlanner.CELL, false, HydrologyPlanCache.WINDOW_LATTICE_CELLS),
return new WindowPlanner(settings,
new HeightLattice(terrain, WindowPlanner.FINE_CELL, false, HydrologyPlanCache.FINE_LATTICE_CELLS), new PondPlanner(settings),
new ReachShaper(settings));
}
@@ -81,7 +81,7 @@ public class HydrologyPlanCodecTest {
assertEquals(planned, HydrologyPlanCodec.decodeRegion(settings, HydrologyPlanCodec.encode(settings, planned)).orElseThrow());
regions.add(planned);
}
WindowPlan planned = new WindowPlanner(settings, new HeightLattice(terrain, WindowPlanner.CELL, false, 1 << 18),
WindowPlan planned = new WindowPlanner(settings,
new HeightLattice(terrain, WindowPlanner.FINE_CELL, false, 1 << 21), new PondPlanner(settings), new ReachShaper(settings))
.plan(LAND, regions);
assertFalse(planned.reaches().isEmpty());
@@ -48,6 +48,55 @@ public class HydrologySettingsTest {
@Rule
public final TemporaryFolder temporary = new TemporaryFolder();
@Test
public void climateIsBoundedAndOnlyEnabledZonesChangeThePlanIdentity() {
HydrologySettings plain = compile(new IrisHydrology());
IrisHydrology disabled = new IrisHydrology();
disabled.getClimate().setDryness(0.8D).setTransition(0.3D);
assertEquals(plain.fingerprint(), compile(disabled).fingerprint());
IrisHydrology zoned = new IrisHydrology();
zoned.getClimate().setEnabled(true);
IrisHydrology drier = new IrisHydrology();
drier.getClimate().setEnabled(true).setDryness(0.6D);
IrisHydrology larger = new IrisHydrology();
larger.getClimate().setEnabled(true).getStyle().setZoom(48D);
Set<Long> fingerprints = new HashSet<>(List.of(plain.fingerprint(), compile(zoned).fingerprint(), compile(drier).fingerprint(),
compile(larger).fingerprint()));
assertEquals(4, fingerprints.size());
for (double invalid : new double[]{-0.01D, 1.01D, Double.NaN}) {
IrisHydrology dryness = new IrisHydrology();
dryness.getClimate().setDryness(invalid);
assertRejected(dryness, "climate.dryness");
IrisHydrology transition = new IrisHydrology();
transition.getClimate().setTransition(invalid);
assertRejected(transition, "climate.transition");
IrisHydrology dryRainfall = new IrisHydrology();
dryRainfall.getClimate().setDryRainfall(invalid);
assertRejected(dryRainfall, "climate.dryRainfall");
}
}
@Test
public void climateWetnessFadesFromDryToWetZones() {
HydrologySettings.Climate off = compile(new IrisHydrology()).climate();
assertEquals(1D, off.wetness(0D), 0D);
IrisHydrology sharp = new IrisHydrology();
sharp.getClimate().setEnabled(true).setDryness(0.5D).setTransition(0D);
HydrologySettings.Climate edge = compile(sharp).climate();
assertEquals(0D, edge.wetness(0.49D), 0D);
assertEquals(1D, edge.wetness(0.5D), 0D);
IrisHydrology soft = new IrisHydrology();
soft.getClimate().setEnabled(true).setDryness(0.5D).setTransition(0.2D).setDryRainfall(0.25D);
HydrologySettings.Climate faded = compile(soft).climate();
assertEquals(0.25D, faded.wetness(0.3D), 1e-9D);
assertEquals(0.625D, faded.wetness(0.5D), 1e-9D);
assertEquals(1D, faded.wetness(0.7D), 1e-9D);
assertTrue(faded.wetness(0.45D) < faded.wetness(0.55D));
IrisHydrology wet = new IrisHydrology();
wet.getClimate().setEnabled(true).setDryness(0D);
assertEquals(1D, compile(wet).climate().wetness(0D), 0D);
}
@Test
public void tierForPicksHighestTierBelowCatchment() {
HydrologySettings settings = compile(new IrisHydrology());
@@ -83,7 +83,7 @@ public class WindowPlannerTest {
new int[]{head, head}, new float[]{2f, 2f}, new float[]{2f, 2f}, new ReachStyle[]{ReachStyle.RUN, ReachStyle.RUN}, 1000f);
return new ShapedNetwork(List.of(outlet), List.of(pond.withOutletReachId(outlet.id())));
}).when(shaper).shape(any(), any(), any(), any(), any(), any(), anyLong());
WindowPlanner planner = new WindowPlanner(settings, new HeightLattice(terrain, WindowPlanner.CELL, false, 1 << 18),
WindowPlanner planner = new WindowPlanner(settings,
new HeightLattice(terrain, WindowPlanner.FINE_CELL, false, 1 << 18), ponds, shaper);
WindowComputation settled = planner.compute(ORIGIN, noRegions(ORIGIN));
@@ -587,7 +587,7 @@ public class WindowPlannerTest {
}
return network;
}).when(shaper).shape(any(), any(), any(), any(), any(), any(), anyLong());
return new WindowPlanner(settings, new HeightLattice(terrain, WindowPlanner.CELL, false, 1 << 18),
return new WindowPlanner(settings,
new HeightLattice(terrain, WindowPlanner.FINE_CELL, false, 1 << 21), new PondPlanner(settings), shaper);
}
@@ -715,7 +715,7 @@ public class WindowPlannerTest {
}
private static WindowPlanner planner(HydrologySettings settings, SyntheticTerrain terrain) {
return new WindowPlanner(settings, new HeightLattice(terrain, WindowPlanner.CELL, false, 1 << 18),
return new WindowPlanner(settings,
new HeightLattice(terrain, WindowPlanner.FINE_CELL, false, 1 << 21), new PondPlanner(settings), new ReachShaper(settings));
}
@@ -261,7 +261,7 @@ public class ChunkWaterRasterTest {
assertTrue("the chain ends at or below the first end grade", previous <= 60);
List<IndexedWindow> reversed = new ArrayList<>(scene.windows(31, 34));
Collections.reverse(reversed);
ChunkWaterRaster backward = new ChunkRasterizer(scene.settings).rasterize(31, 34, scene.natural, reversed, scene.regions(31, 34));
ChunkWaterRaster backward = new ChunkRasterizer(scene.settings, ChannelFluids.TIER).rasterize(31, 34, scene.natural::applyAsInt, reversed, scene.regions(31, 34));
for (int lz = 0; lz < 16; lz++) {
for (int lx = 0; lx < 16; lx++) {
assertEquals(scene.raster(31, 34).waterHead(lx, lz), backward.waterHead(lx, lz));
@@ -403,7 +403,7 @@ public class ChunkWaterRasterTest {
SeaInlet inlet = new SeaInlet(71L, xs, zs, halfWidth, SEA_LEVEL, floor, ceiling, 64, 8, 6);
WindowKey key = new WindowKey(0, 0);
IndexedWindow own = new IndexedWindow(new WindowPlan(key, List.of(), List.of(), List.of(inlet)), ReachIndex.build(List.of(), List.of()));
ChunkRasterizer rasterizer = new ChunkRasterizer(settings);
ChunkRasterizer rasterizer = new ChunkRasterizer(settings, ChannelFluids.TIER);
ChunkWaterRaster mouth = rasterizer.rasterize(0, 0, (x, z) -> 70, List.of(own), regions(0, 0, List.of()));
int[] column = new int[2];
int open = 0;
@@ -440,8 +440,8 @@ public class ChunkWaterRasterTest {
samples.incrementAndGet();
return 70;
};
ChunkRasterizer rasterizer = new ChunkRasterizer(settings);
ChunkWaterRaster raster = rasterizer.rasterize(0, 0, natural, List.of(own), regions(0, 0, List.of()));
ChunkRasterizer rasterizer = new ChunkRasterizer(settings, ChannelFluids.TIER);
ChunkWaterRaster raster = rasterizer.rasterize(0, 0, natural::applyAsInt, List.of(own), regions(0, 0, List.of()));
assertTrue(raster.empty());
assertFalse(raster.provisional());
assertEquals("a riverless chunk never samples natural heights", 0, samples.get());
@@ -459,9 +459,94 @@ public class ChunkWaterRasterTest {
assertThrows(IllegalStateException.class, () -> raster.terrainHeight(0, 0));
assertTrue(ChunkWaterRaster.PROVISIONAL.provisional());
assertTrue(ChunkWaterRaster.PROVISIONAL.empty());
assertThrows(IllegalArgumentException.class, () -> rasterizer.rasterize(40, 0, natural, List.of(own), regions(40, 0, List.of())));
assertThrows(IllegalArgumentException.class, () -> rasterizer.rasterize(40, 0, natural::applyAsInt, List.of(own), regions(40, 0, List.of())));
assertFalse("a chunk on the reach is not empty",
rasterizer.rasterize(27, 25, natural, List.of(own), regions(27, 25, List.of())).empty());
rasterizer.rasterize(27, 25, natural::applyAsInt, List.of(own), regions(27, 25, List.of())).empty());
}
@Test
public void channelTakesTheAreaFluidWhereOneIsSet() {
HydrologySettings settings = settings(new IrisHydrology());
Reach reach = line(61L, tier("stream", 1.5f, 0.5f, 0, IrisBankStyle.SMOOTH), 0L, 400f, 400f, 480f, 400f, (x, z) -> 69);
WindowKey key = new WindowKey(0, 0);
IndexedWindow own = new IndexedWindow(new WindowPlan(key, List.of(reach), List.of(), List.of()), ReachIndex.build(List.of(reach), List.of()));
ChannelFluids volcanic = (x, z) -> x < 440 ? "lava" : null;
ChunkWaterRaster raster = new ChunkRasterizer(settings, volcanic).rasterize(27, 25, (x, z) -> 70, List.of(own), regions(27, 25, List.of()));
int lava = 0;
int water = 0;
for (int lz = 0; lz < 16; lz++) {
for (int lx = 0; lx < 16; lx++) {
if (!isChannel(raster.role(lx, lz))) {
continue;
}
boolean inside = 27 * 16 + lx < 440;
assertEquals("column " + lx + "," + lz, inside ? "lava" : "water", raster.fluid(lx, lz));
if (inside) {
lava++;
} else {
water++;
}
}
}
assertTrue("lava columns " + lava + ", water columns " + water, lava > 0 && water > 0);
}
@Test
public void banksNeverDipAwayFromTheWater() {
HydrologySettings settings = settings(new IrisHydrology());
Reach river = line(81L, tier("river", 3f, 0.5f, 32, IrisBankStyle.SMOOTH), 0L, 96f, 256f, 416f, 256f, (x, z) -> 69);
WindowKey key = new WindowKey(0, 0);
IndexedWindow own = new IndexedWindow(new WindowPlan(key, List.of(river), List.of(), List.of()), ReachIndex.build(List.of(river), List.of()));
NaturalHeights natural = (x, z) -> {
double away = Math.abs(z - 256);
if (x < 256) {
return 70D + 8D * Math.min(1D, away / 8D) + 0.15D * Math.max(0D, away - 8D);
}
return 70D + 8D * (1D - Math.exp(-away / 6D)) + (x < 336 ? 0D : 0.15D * away);
};
ChunkRasterizer rasterizer = new ChunkRasterizer(settings, ChannelFluids.TIER);
Map<Long, Integer> terrain = new HashMap<>();
Map<Long, WaterRole> roles = new HashMap<>();
for (int chunkZ = 13; chunkZ <= 18; chunkZ++) {
for (int chunkX = 12; chunkX <= 25; chunkX++) {
ChunkWaterRaster raster = rasterizer.rasterize(chunkX, chunkZ, natural, List.of(own), regions(chunkX, chunkZ, List.of()));
for (int lz = 0; lz < 16; lz++) {
for (int lx = 0; lx < 16; lx++) {
int x = chunkX * 16 + lx;
int z = chunkZ * 16 + lz;
terrain.put(column(x, z), raster.empty() ? (int) Math.round(natural.height(x, z)) : raster.terrainHeight(lx, lz));
roles.put(column(x, z), raster.empty() ? WaterRole.NONE : raster.role(lx, lz));
}
}
}
}
int cut = 0;
List<String> pits = new ArrayList<>();
for (int z = 13 * 16 + 1; z < 19 * 16 - 1; z++) {
for (int x = 12 * 16 + 1; x < 26 * 16 - 1; x++) {
if (roles.get(column(x, z)) != WaterRole.BANK) {
continue;
}
int height = terrain.get(column(x, z));
if (height < (int) Math.round(natural.height(x, z))) {
cut++;
}
int inward = z > 256 ? z - 1 : z + 1;
if (z == 256 || roles.get(column(x, inward)) != WaterRole.BANK) {
continue;
}
int nearer = terrain.get(column(x, inward));
if (height < nearer) {
pits.add(x + "," + z + "@" + height + "<" + nearer);
}
}
}
assertTrue("cut bank columns " + cut, cut > 400);
assertTrue("bank dips " + pits.size() + " " + pits.subList(0, Math.min(10, pits.size())), pits.isEmpty());
}
private static long column(int x, int z) {
return ((long) x << 32) | (z & 0xFFFFFFFFL);
}
@Test
@@ -525,7 +610,7 @@ public class ChunkWaterRasterTest {
ChunkWaterRaster forward = scene.raster(31, 12);
List<IndexedWindow> reversed = new ArrayList<>(scene.windows(31, 12));
Collections.reverse(reversed);
ChunkWaterRaster backward = new ChunkRasterizer(scene.settings).rasterize(31, 12, scene.natural, reversed, scene.regions(31, 12));
ChunkWaterRaster backward = new ChunkRasterizer(scene.settings, ChannelFluids.TIER).rasterize(31, 12, scene.natural::applyAsInt, reversed, scene.regions(31, 12));
for (int lz = 0; lz < 16; lz++) {
for (int lx = 0; lx < 16; lx++) {
assertEquals(forward.waterHead(lx, lz), backward.waterHead(lx, lz));
@@ -837,7 +922,7 @@ public class ChunkWaterRasterTest {
private Scene(HydrologySettings settings, IntBinaryOperator natural) {
this.settings = settings;
this.natural = natural;
this.rasterizer = new ChunkRasterizer(settings);
this.rasterizer = new ChunkRasterizer(settings, ChannelFluids.TIER);
}
private Scene reach(Reach reach) {
@@ -862,7 +947,7 @@ public class ChunkWaterRasterTest {
private ChunkWaterRaster raster(int chunkX, int chunkZ) {
return rasters.computeIfAbsent(pack(chunkX, chunkZ),
key -> rasterizer.rasterize(chunkX, chunkZ, natural, windows(chunkX, chunkZ), regions(chunkX, chunkZ)));
key -> rasterizer.rasterize(chunkX, chunkZ, natural::applyAsInt, windows(chunkX, chunkZ), regions(chunkX, chunkZ)));
}
private List<IndexedWindow> windows(int chunkX, int chunkZ) {
@@ -0,0 +1,95 @@
package art.arcane.iris.generation.hydrology.raster;
import art.arcane.iris.generation.hydrology.config.IrisBankStyle;
import art.arcane.iris.generation.hydrology.config.IrisHydrologyMaterials;
import art.arcane.iris.generation.hydrology.water.HydrologyTier;
import art.arcane.iris.generation.hydrology.water.Reach;
import art.arcane.iris.generation.hydrology.water.ReachStyle;
import org.junit.Test;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.SplittableRandom;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertTrue;
public class ReachSegmentsTest {
private static final HydrologyTier TIER = new HydrologyTier("test", 0f, 1f, 4f, 1f, 0.4f, 1, true, 6, 4, IrisBankStyle.SMOOTH,
false, new IrisHydrologyMaterials(), "water", List.of());
@Test
public void coveredChannelLookupsMatchTheFullScan() {
SplittableRandom random = new SplittableRandom(1337L);
int hits = 0;
for (int trial = 0; trial < 40; trial++) {
int originX = random.nextInt(-2000, 2000) << 4;
int originZ = random.nextInt(-2000, 2000) << 4;
List<Reach> reaches = new ArrayList<>();
int count = 1 + random.nextInt(12);
for (int walk = 0; walk < count; walk++) {
reaches.add(randomWalk(trial * 100L + walk, originX + 8, originZ + 8, random));
}
ReachSegments scanned = segments(reaches, originX, originZ);
ReachSegments covered = segments(reaches, originX, originZ);
covered.coverChannels(originX - 17, originZ - 17, originX + 32, originZ + 32);
ReachCursor scan = new ReachCursor();
ReachCursor cover = new ReachCursor();
for (int z = originZ - 20; z <= originZ + 35; z++) {
for (int x = originX - 20; x <= originX + 35; x++) {
ReachSegments.Scope scope = random.nextInt(4) == 0 ? ReachSegments.Scope.SHORE : ReachSegments.Scope.CHANNEL;
scanned.nearest(x, z, scope, scan);
covered.nearest(x, z, scope, cover);
String at = scope + " at " + x + "," + z;
assertSameChoice(at + " channel", scan.channel, cover.channel);
assertSameChoice(at + " bank", scan.bank, cover.bank);
assertSameChoice(at + " edge", scan.edge, cover.edge);
if (scan.channel.reach != null) {
hits++;
}
}
}
}
assertTrue("random walks cross the covered area, hits=" + hits, hits > 1000);
}
private static void assertSameChoice(String what, ReachCursor.Choice expected, ReachCursor.Choice actual) {
assertSame(what, expected.reach, actual.reach);
assertEquals(what, expected.segment, actual.segment);
assertEquals(what, expected.index, actual.index);
assertEquals(what, Double.doubleToLongBits(expected.t), Double.doubleToLongBits(actual.t));
assertEquals(what, Double.doubleToLongBits(expected.distance), Double.doubleToLongBits(actual.distance));
}
private static ReachSegments segments(List<Reach> reaches, int originX, int originZ) {
ReachSegments segments = new ReachSegments(16);
for (Reach reach : reaches) {
segments.addNear(reach, originX - 1f, originZ - 1f, originX + 16f, originZ + 16f, ChunkWaterRaster.MAX_SHORE_DISTANCE + 1f);
}
return segments;
}
private static Reach randomWalk(long id, int centerX, int centerZ, SplittableRandom random) {
int points = 2 + random.nextInt(30);
float[] xs = new float[points];
float[] zs = new float[points];
float[] halfWidth = new float[points];
xs[0] = centerX + (float) random.nextDouble(-60D, 60D);
zs[0] = centerZ + (float) random.nextDouble(-60D, 60D);
halfWidth[0] = (float) random.nextDouble(0.5D, 9D);
for (int point = 1; point < points; point++) {
xs[point] = xs[point - 1] + (float) random.nextDouble(-12D, 12D);
zs[point] = zs[point - 1] + (float) random.nextDouble(-12D, 12D);
halfWidth[point] = random.nextInt(8) == 0 ? halfWidth[point - 1] : (float) random.nextDouble(0.5D, 9D);
}
int[] grade = new int[points];
float[] depth = new float[points];
ReachStyle[] style = new ReachStyle[points];
Arrays.fill(grade, 64);
Arrays.fill(depth, 1f);
Arrays.fill(style, ReachStyle.RUN);
return new Reach(id, TIER, -1L, xs, zs, grade, halfWidth, depth, style, 100f);
}
}
@@ -15,6 +15,7 @@ import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.Consumer;
import java.util.function.IntFunction;
@@ -50,18 +51,37 @@ public class CavePoolFillerTest {
return 0;
});
for (int chunkX = 0; chunkX < 1024; chunkX++) {
filler.fill(chunkX, 0, carved, writer, SEED);
filler.fill(chunkX, 0, () -> carved, writer, SEED);
}
assertTrue("half density samples approximately half the candidate columns", columns.size() > 3600 && columns.size() < 4500);
Set<Long> repeated = new HashSet<>(columns);
columns.clear();
for (int chunkX = 1023; chunkX >= 0; chunkX--) {
filler.fill(chunkX, 0, carved, writer, SEED);
filler.fill(chunkX, 0, () -> carved, writer, SEED);
}
assertEquals(repeated, columns);
verifyNoInteractions(writer);
}
@Test
public void chunksWithoutAPoolSiteNeverOpenTheirCaves() {
IrisHydrology config = new IrisHydrology().setDensity(0.5D);
config.getUnderground().getCavePools().setDensity(0.05D);
CavePoolFiller filler = new CavePoolFiller(HydrologySettings.compile(config, SEED, 63, 0, 384));
CarvedTerrain carved = mock(CarvedTerrain.class);
MantleWriter writer = mock(MantleWriter.class);
AtomicInteger opened = new AtomicInteger();
int chunks = 1024;
for (int chunkX = 0; chunkX < chunks; chunkX++) {
filler.fill(chunkX, 0, () -> {
opened.incrementAndGet();
return carved;
}, writer, SEED);
}
assertTrue("only chunks drawing a pool site open their caves, opened " + opened.get(), opened.get() > 0 && opened.get() < chunks / 8);
verifyNoInteractions(writer);
}
@Test
public void zeroGlobalDensityDoesNotReadCaves() {
IrisHydrology config = new IrisHydrology().setDensity(0D);
@@ -69,7 +89,7 @@ public class CavePoolFillerTest {
CavePoolFiller filler = new CavePoolFiller(HydrologySettings.compile(config, SEED, 63, 0, 384));
CarvedTerrain carved = mock(CarvedTerrain.class);
MantleWriter writer = mock(MantleWriter.class);
filler.fill(0, 0, carved, writer, SEED);
filler.fill(0, 0, () -> carved, writer, SEED);
verifyNoInteractions(carved, writer);
}
@@ -143,10 +163,10 @@ public class CavePoolFillerTest {
MantleWriter forwardWriter = writer(forward);
MantleWriter reverseWriter = writer(reverse);
for (int index = 0; index < 9; index++) {
new CavePoolFiller(settings).fill(index % 3 - 1, index / 3 - 1, world, forwardWriter, SEED);
new CavePoolFiller(settings).fill(index % 3 - 1, index / 3 - 1, () -> world, forwardWriter, SEED);
}
for (int index = 8; index >= 0; index--) {
new CavePoolFiller(settings).fill(index % 3 - 1, index / 3 - 1, world, reverseWriter, SEED);
new CavePoolFiller(settings).fill(index % 3 - 1, index / 3 - 1, () -> world, reverseWriter, SEED);
}
assertFalse(forward.isEmpty());
@@ -284,7 +304,7 @@ public class CavePoolFillerTest {
private static Map<Long, HydrologyCaveCell> fill(HydrologySettings settings, VoxelWorld world, int chunkX, int chunkZ) {
Map<Long, HydrologyCaveCell> written = new HashMap<>();
new CavePoolFiller(settings).fill(chunkX, chunkZ, world, writer(written), SEED);
new CavePoolFiller(settings).fill(chunkX, chunkZ, () -> world, writer(written), SEED);
return written;
}
@@ -15,6 +15,7 @@ import art.arcane.iris.generation.hydrology.plan.RegionKey;
import art.arcane.iris.generation.hydrology.plan.RegionPlan;
import art.arcane.iris.generation.hydrology.plan.WindowKey;
import art.arcane.iris.generation.hydrology.plan.WindowPlan;
import art.arcane.iris.generation.hydrology.raster.ChannelFluids;
import art.arcane.iris.generation.hydrology.raster.ChunkRasterizer;
import art.arcane.iris.generation.hydrology.raster.ChunkWaterRaster;
import art.arcane.iris.generation.hydrology.raster.ReachIndex;
@@ -656,7 +657,7 @@ public class PondPlannerTest {
private static void assertRasterRimContained(HydrologySettings settings, Pond pond, DoubleBinaryOperator natural) {
Map<Long, ChunkWaterRaster> rasters = new HashMap<>();
ChunkRasterizer rasterizer = new ChunkRasterizer(settings);
ChunkRasterizer rasterizer = new ChunkRasterizer(settings, ChannelFluids.TIER);
int raised = 0;
int[][] sides = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}};
for (int[] wet : wetNodes(pond.mask())) {
@@ -324,7 +324,7 @@ public class MantleCarvedTerrainTest {
for (SeaInlet inlet : complex.getHydrologyRuntime().inlets(0, chunkZ)) {
rasterizer.write(inlet, 0, chunkZ, writer, HydrologyCaveCell.SEA_FLUID, "", SeaInletRasterizer.SubterrainFluid.NOWHERE);
}
new CavePoolFiller(settings).fill(0, chunkZ, new MantleCarvedTerrain(writer, complex, engine, 0, chunkZ), writer, SEED);
new CavePoolFiller(settings).fill(0, chunkZ, () -> new MantleCarvedTerrain(writer, complex, engine, 0, chunkZ), writer, SEED);
}
return cells;
}
@@ -210,11 +210,14 @@ public final class EngineModeTerrainGenerationTest {
when(biome.key()).thenReturn("minecraft:plains");
ProceduralStream<Double> height = mock(ProceduralStream.class);
when(height.getDouble(anyDouble(), anyDouble())).thenReturn(3D);
ProceduralStream<Double> waterHead = mock(ProceduralStream.class);
when(waterHead.getDouble(anyDouble(), anyDouble())).thenReturn(0D);
ProceduralStream<IrisBiome> biomes = mock(ProceduralStream.class);
ProceduralStream<IrisRegion> regions = mock(ProceduralStream.class);
ProceduralStream<NativeBlockState> materials = mock(ProceduralStream.class);
when(materials.get(anyDouble(), anyDouble())).thenReturn(stone);
when(complex.getRawHeightStream()).thenReturn(height);
when(complex.getWaterHeadStream()).thenReturn(waterHead);
when(complex.getTrueBiomeStream()).thenReturn(biomes);
when(complex.getCaveBiomeStream()).thenReturn(biomes);
when(complex.getRegionStream()).thenReturn(regions);
@@ -22,11 +22,13 @@ import org.junit.rules.TemporaryFolder;
import org.mockito.MockedStatic;
import org.mockito.Mockito;
import java.lang.reflect.Field;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.SplittableRandom;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import static org.mockito.Answers.CALLS_REAL_METHODS;
import static org.mockito.ArgumentMatchers.any;
@@ -81,6 +83,24 @@ public class IrisComplexBakeParityTest {
}
}
@Test
public void regionConstantBoundsEqualFullBiomeBoundsBitForBit() throws Exception {
try (Statics ignored = new Statics(); Fixture shortcut = new Fixture(pack()); Fixture full = new Fixture(pack())) {
Field regionBounds = IrisComplex.class.getDeclaredField("regionBounds");
regionBounds.setAccessible(true);
assertNotNull(regionBounds.get(shortcut.complex));
regionBounds.set(full.complex, null);
SplittableRandom random = new SplittableRandom(0x5EEDL);
for (int column = 0; column < 2048; column++) {
int x = random.nextInt(-6400, 6400);
int z = random.nextInt(-6400, 6400);
assertEquals("column " + x + "," + z,
Double.doubleToRawLongBits(full.complex.getBaseTerrainHeightStream().getDouble(x, z)),
Double.doubleToRawLongBits(shortcut.complex.getBaseTerrainHeightStream().getDouble(x, z)));
}
}
}
@Test
public void batchedChunksEvaluateExactlyTheScalarGeneratorSet() throws Exception {
try (Statics ignored = new Statics(); Fixture batched = new Fixture(pack()); Fixture scalar = new Fixture(pack())) {
@@ -243,7 +243,7 @@ public class IrisComplexBoundsBiomeCacheTest {
constructor.setAccessible(true);
Object cache = constructor.newInstance(4096);
Method get = type.getDeclaredMethod("get", double.class, double.class);
Method put = type.getDeclaredMethod("put", double.class, double.class, IrisBiome.class);
Method put = type.getDeclaredMethod("put", double.class, double.class, Object.class);
get.setAccessible(true);
put.setAccessible(true);
IrisBiome first = new IrisBiome();
@@ -266,7 +266,7 @@ public class IrisComplexBoundsBiomeCacheTest {
}
Field values = type.getDeclaredField("values");
values.setAccessible(true);
assertEquals(4096, ((IrisBiome[]) values.get(cache)).length);
assertEquals(4096, ((Object[]) values.get(cache)).length);
}
private static ProceduralStream<IrisBiome> constant(IrisBiome biome) {
@@ -295,7 +295,7 @@ public class IrisComplexBoundsBiomeCacheTest {
constructor.setAccessible(true);
cache = constructor.newInstance();
sample = IrisComplex.class.getDeclaredMethod("sampleBoundsRaw", cacheClass, Engine.class,
IrisInterpolator.class, IrisGenerator[].class, double.class, double.class);
IrisInterpolator.class, int.class, IrisGenerator[].class, double.class, double.class);
sample.setAccessible(true);
boundsConstructor = Class.forName("art.arcane.iris.generation.runtime.IrisComplex$GeneratorBounds")
.getDeclaredConstructor(double.class, double.class);
@@ -313,7 +313,7 @@ public class IrisComplexBoundsBiomeCacheTest {
private NoiseBounds sample(Object gridCache, IrisInterpolator interpolator, double x, double z)
throws ReflectiveOperationException {
return (NoiseBounds) sample.invoke(complex, gridCache, null, interpolator, new IrisGenerator[0], x, z);
return (NoiseBounds) sample.invoke(complex, gridCache, null, interpolator, 0, new IrisGenerator[0], x, z);
}
private Object newGridCache() throws ReflectiveOperationException {
@@ -23,6 +23,10 @@ import art.arcane.iris.testsupport.WaterScene;
import art.arcane.iris.world.history.BoundaryColumnGeometry;
import art.arcane.iris.world.history.BoundaryGeometryInfluence;
import art.arcane.iris.world.history.GenerationBlend;
import art.arcane.iris.world.history.GenerationBoundary;
import art.arcane.iris.world.history.GenerationTransition;
import art.arcane.iris.world.history.SavedTerrainChunk;
import art.arcane.iris.world.history.TerrainBoundarySignatureStore;
import art.arcane.iris.world.history.TransitionGenerationPlan;
import art.arcane.iris.world.history.TransitionGeometryBlender;
import art.arcane.volmlib.nativelib.terrain.NativeBiome;
@@ -43,7 +47,9 @@ import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import org.junit.rules.Timeout;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@@ -533,6 +539,39 @@ public class IrisComplexTransitionTest {
return oldChunkWeight(x, z) == 0D ? 158.3D : 150.3D;
}
@Test
public void transitionedChunkPaintsSeaLayersAtTheHeightOfTheOriginalSea() throws Exception {
NaturalHeights seabed = (x, z) -> 100D;
Hunk<NativeBlockState> original;
SavedTerrainChunk receipt;
try (TransitionStage stage = new TransitionStage(TransitionStage.seamPlan((x, z) -> 1D,
TransitionStage.savedColumn(100, 100, -1)), TransitionStage.seamDisplacement((x, z) -> 1D), false, seabed, 4)) {
original = stage.paint(-1);
receipt = stage.capture(-1, original);
assertSame(stage.ice, original.getRaw(15, 127, 0));
assertSame(stage.ice, original.getRaw(15, 124, 0));
assertSame(stage.water, original.getRaw(15, 123, 0));
}
GenerationBoundary boundary = GenerationBoundary.freeze("boundary", List.of(new GenerationBoundary.ChunkCoordinate(-1, 0)));
TerrainBoundarySignatureStore.Snapshot snapshot = new TerrainBoundarySignatureStore(temporaryFolder.newFolder().toPath())
.publish(2L, boundary, receipt::column);
TransitionGenerationPlan plan = new TransitionGenerationPlan(new TransitionGenerationPlan.Specification(2L, "old", "new",
GenerationTransition.CURRENT_ALGORITHM_VERSION, 32, boundary.identity(), snapshot.identity()), boundary, snapshot);
TransitionDisplacementField displacement = new TransitionDisplacementField(plan,
new TransitionDisplacementField.Sources((x, z) -> 100D, TransitionStage.HEIGHT));
try (TransitionStage stage = new TransitionStage(plan, displacement, false, seabed, 4)) {
Hunk<NativeBlockState> transitioned = stage.blend(0, stage.paint(0));
for (int lz = 0; lz < 16; lz++) {
for (int lx = 0; lx < 16; lx++) {
for (int y = 0; y < TransitionStage.HEIGHT; y++) {
assertEquals(lx + "," + y + "," + lz, stage.key(original.getRaw(15, y, lz)),
stage.key(transitioned.getRaw(lx, y, lz)));
}
}
}
}
}
private static void assertColumn(Hunk<NativeBlockState> painted, Hunk<NativeBlockState> blended, int lx, int lz) {
for (int y = 0; y < TransitionStage.HEIGHT; y++) {
assertSame(lx + "," + y + "," + lz + " was re-blended", painted.getRaw(lx, y, lz), blended.getRaw(lx, y, lz));
@@ -547,8 +586,10 @@ public class IrisComplexTransitionTest {
private final NativeBlockState stone = block("minecraft:stone", false, false);
private final NativeBlockState water = block("minecraft:water[level=0]", false, true);
private final NativeBlockState air = block("minecraft:air", true, false);
private final TransitionDisplacementField displacement = mock(TransitionDisplacementField.class);
private final TransitionGenerationPlan plan = mock(TransitionGenerationPlan.class);
private final NativeBlockState ice = block("minecraft:ice", false, false);
private final TransitionDisplacementField displacement;
private final TransitionGenerationPlan plan;
private final int seaLayers;
private final IrisComplex complex;
private final FakeHydrology hydrology;
@@ -562,13 +603,14 @@ public class IrisComplexTransitionTest {
private TransitionStage(SeamWeights weights, boolean enabled, NaturalHeights natural, BoundaryColumnGeometry oldColumn)
throws Exception {
when(displacement.seamWeight(anyInt(), anyInt())).thenAnswer(invocation ->
weights.weight(invocation.getArgument(0), invocation.getArgument(1)));
when(displacement.fluidHeight(anyInt(), anyInt(), anyDouble())).thenAnswer(invocation -> invocation.getArgument(2));
when(plan.hasTransitionAtChunk(anyInt(), anyInt())).thenReturn(true);
when(plan.geometryAt(anyInt(), anyInt())).thenAnswer(invocation -> new BoundaryGeometryInfluence(
weights.weight(invocation.getArgument(0), invocation.getArgument(1)), 0D,
List.of(new BoundaryGeometryInfluence.Contribution(oldColumn, 1D))));
this(seamPlan(weights, oldColumn), seamDisplacement(weights), enabled, natural, 0);
}
private TransitionStage(TransitionGenerationPlan plan, TransitionDisplacementField displacement, boolean enabled,
NaturalHeights natural, int seaLayers) throws Exception {
this.plan = plan;
this.displacement = displacement;
this.seaLayers = seaLayers;
AtomicReference<IrisComplex> built = new AtomicReference<>();
hydrology = enabled ? new FakeHydrology(() -> false, (x, z) -> built.get().naturalTrueHeight(x, z), 127, 156) : null;
complex = fixture.transitionComplex(enabled ? hydrology.runtime : FakeHydrology.disabled(), plan, displacement);
@@ -581,7 +623,7 @@ public class IrisComplexTransitionTest {
doReturn(mock(IrisImageMapRuntime.class)).when(complex).getImageMapRuntime();
doReturn(water).when(complex).resolveWaterFluid(anyInt(), anyInt());
doReturn(water).when(complex).resolveSeaFluid(anyDouble(), anyDouble());
Map<String, NativeBlockState> blocks = Map.of(stone.key(), stone, water.key(), water, air.key(), air);
Map<String, NativeBlockState> blocks = Map.of(stone.key(), stone, water.key(), water, air.key(), air, ice.key(), ice);
PlatformRegistries registries = mock(PlatformRegistries.class);
when(registries.air()).thenReturn(air);
when(registries.block("AIR")).thenReturn(air);
@@ -594,6 +636,23 @@ public class IrisComplexTransitionTest {
IrisPlatforms.bind(platform);
}
private static TransitionGenerationPlan seamPlan(SeamWeights weights, BoundaryColumnGeometry oldColumn) {
TransitionGenerationPlan plan = mock(TransitionGenerationPlan.class);
when(plan.hasTransitionAtChunk(anyInt(), anyInt())).thenReturn(true);
when(plan.geometryAt(anyInt(), anyInt())).thenAnswer(invocation -> new BoundaryGeometryInfluence(
weights.weight(invocation.getArgument(0), invocation.getArgument(1)), 0D,
List.of(new BoundaryGeometryInfluence.Contribution(oldColumn, 1D))));
return plan;
}
private static TransitionDisplacementField seamDisplacement(SeamWeights weights) {
TransitionDisplacementField displacement = mock(TransitionDisplacementField.class);
when(displacement.seamWeight(anyInt(), anyInt())).thenAnswer(invocation ->
weights.weight(invocation.getArgument(0), invocation.getArgument(1)));
when(displacement.fluidHeight(anyInt(), anyInt(), anyDouble())).thenAnswer(invocation -> invocation.getArgument(2));
return displacement;
}
private ChunkWaterRaster raster(int chunkX) {
return hydrology.runtime.raster(chunkX, 0);
}
@@ -622,7 +681,8 @@ public class IrisComplexTransitionTest {
when(engine.getSeedManager()).thenReturn(mock(SeedManager.class));
when(biome.generateLayers(eq(dimension), anyDouble(), anyDouble(), any(RNG.class), anyInt(), anyInt(), eq(data), same(complex)))
.thenAnswer(invocation -> new KList<>(List.of(stone)));
when(biome.generateSeaLayers(anyDouble(), anyDouble(), any(RNG.class), anyInt(), eq(data))).thenAnswer(invocation -> new KList<>());
when(biome.generateSeaLayers(anyDouble(), anyDouble(), any(RNG.class), anyInt(), eq(data)))
.thenAnswer(invocation -> new KList<>(Collections.nCopies(seaLayers, ice)));
int[] grounds = grounds(chunkX);
ChunkContext context = mock(ChunkContext.class);
when(context.getRoundedHeight(anyInt(), anyInt())).thenAnswer(invocation ->
@@ -712,6 +772,19 @@ public class IrisComplexTransitionTest {
return blocks;
}
private SavedTerrainChunk capture(int chunkX, Hunk<NativeBlockState> blocks) throws IOException {
int[] grounds = grounds(chunkX);
ChunkContext context = mock(ChunkContext.class);
when(context.getComplex()).thenReturn(complex);
when(context.getRoundedHeight(anyInt(), anyInt())).thenAnswer(invocation ->
grounds[invocation.<Integer>getArgument(1) << 4 | invocation.<Integer>getArgument(0)]);
NativeBiome biome = mock(NativeBiome.class);
when(biome.key()).thenReturn("minecraft:frozen_ocean");
Hunk<NativeBiome> biomes = Hunk.newArrayHunk(16, HEIGHT, 16);
biomes.fill(biome);
return IrisTransitionGeometryActuator.capture(chunkX << 4, 0, blocks, biomes, 0, context, true);
}
private BoundaryColumnGeometry geometry(Hunk<NativeBlockState> blocks, int lx, int lz) {
ArrayList<BoundaryColumnGeometry.Voxel> voxels = new ArrayList<>(HEIGHT);
for (int y = 0; y < HEIGHT; y++) {
@@ -123,8 +123,8 @@ public class IrisEngineGenerationRuntimeScopeTest {
AtomicInteger workerNaturals = new AtomicInteger();
doAnswer(invocation -> {
observe(engine, historical, caller, naturals, workerNaturals, foreign);
return (int) Math.round(bowl(invocation.getArgument(0), invocation.getArgument(1)));
}).when(historicalComplex).naturalTrueHeight(anyInt(), anyInt());
return bowl(invocation.getArgument(0), invocation.getArgument(1));
}).when(historicalComplex).naturalHeight(anyInt(), anyInt());
IrisEngine.GenerationRuntimeBinding binding = detachedBinding(engine, historical.runtime);
HydrologyRuntime hydrology;
try (IrisEngine.GenerationRuntimeScope ignored = engine.openGenerationRuntimeScope(binding)) {
@@ -0,0 +1,136 @@
package art.arcane.iris.generation.runtime;
import art.arcane.iris.generation.biome.IrisBiome;
import art.arcane.iris.generation.terrain.InferredType;
import art.arcane.iris.generation.terrain.IrisRegion;
import art.arcane.volmlib.util.interpolation.NoiseBounds;
import org.junit.Test;
import java.util.Collection;
import java.util.IdentityHashMap;
import java.util.List;
import java.util.Map;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertSame;
public class RegionBoundsTest {
private static final NoiseBounds FLAT = new NoiseBounds(0D, 0D);
private static final NoiseBounds HILLS = new NoiseBounds(4D, 30D);
@Test
public void groupsEveryReachableBiomeAgreesOnAreConstantForTheRegion() {
IrisBiome plains = new IrisBiome();
IrisBiome forest = new IrisBiome();
IrisBiome ocean = new IrisBiome();
IrisRegion region = new IrisRegion();
Map<IrisBiome, NoiseBounds[]> bounds = new IdentityHashMap<>();
bounds.put(plains, new NoiseBounds[]{FLAT, HILLS});
bounds.put(forest, new NoiseBounds[]{new NoiseBounds(0D, 0D), new NoiseBounds(2D, 30D)});
bounds.put(ocean, new NoiseBounds[]{FLAT, HILLS});
RegionBounds compiled = RegionBounds.compile(List.of(region), 2,
new Fixed(Map.of(InferredType.LAND, List.of(plains, forest), InferredType.SEA, List.of(ocean)), Map.of()),
(group, biome) -> bounds.get(biome)[group]);
RegionBounds.Constants constants = compiled.of(region);
assertBits(FLAT, constants.any(0));
assertBits(FLAT, constants.typed(InferredType.LAND, 0));
assertBits(FLAT, constants.typed(InferredType.SEA, 0));
assertNull(constants.any(1));
assertNull(constants.typed(InferredType.LAND, 1));
assertSame(HILLS, constants.typed(InferredType.SEA, 1));
assertSame(HILLS, compiled.pick(plains, 1));
assertBits(new NoiseBounds(2D, 30D), compiled.pick(forest, 1));
}
@Test
public void picksAreConstantOnlyWhenEveryDescendantAgrees() {
IrisBiome steppe = new IrisBiome();
IrisBiome meadow = new IrisBiome();
IrisBiome mesa = new IrisBiome();
IrisBiome canyon = new IrisBiome();
IrisRegion region = new IrisRegion();
Map<IrisBiome, NoiseBounds> bounds = new IdentityHashMap<>();
bounds.put(steppe, FLAT);
bounds.put(meadow, new NoiseBounds(0D, 0D));
bounds.put(mesa, FLAT);
bounds.put(canyon, HILLS);
RegionBounds compiled = RegionBounds.compile(List.of(region), 1,
new Fixed(Map.of(InferredType.LAND, List.of(steppe, mesa), InferredType.SEA, List.of()),
descendants(steppe, List.of(steppe, meadow), mesa, List.of(mesa, canyon))),
(group, biome) -> bounds.get(biome));
assertNull(compiled.of(region).typed(InferredType.LAND, 0));
assertSame(FLAT, compiled.pick(steppe, 0));
assertNull(compiled.pick(mesa, 0));
assertNull(compiled.pick(canyon, 0));
}
@Test
public void landAndSeaConstantsOnlyMergeWhenTheirBitsMatch() {
IrisBiome beach = new IrisBiome();
IrisBiome reef = new IrisBiome();
IrisRegion region = new IrisRegion();
Map<IrisBiome, NoiseBounds> bounds = new IdentityHashMap<>();
bounds.put(beach, new NoiseBounds(0D, 0D));
bounds.put(reef, new NoiseBounds(-0D, 0D));
RegionBounds.Constants constants = RegionBounds.compile(List.of(region), 1,
new Fixed(Map.of(InferredType.LAND, List.of(beach), InferredType.SEA, List.of(reef)), Map.of()),
(group, biome) -> bounds.get(biome)).of(region);
assertNull(constants.any(0));
assertSame(bounds.get(beach), constants.typed(InferredType.LAND, 0));
assertSame(bounds.get(reef), constants.typed(InferredType.SEA, 0));
}
@Test
public void emptyBiomeListsAndUnknownRegionsHaveNoConstant() {
IrisRegion region = new IrisRegion();
IrisBiome only = new IrisBiome();
RegionBounds compiled = RegionBounds.compile(List.of(region), 1,
new Fixed(Map.of(InferredType.LAND, List.of(only), InferredType.SEA, List.of()), Map.of()),
(group, biome) -> FLAT);
RegionBounds.Constants constants = compiled.of(region);
assertSame(FLAT, constants.typed(InferredType.LAND, 0));
assertNull(constants.typed(InferredType.SEA, 0));
assertNull(constants.any(0));
assertNull(constants.typed(InferredType.SHORE, 0));
assertNull(constants.typed(InferredType.CAVE, 0));
assertNull(compiled.of(new IrisRegion()));
assertNull(compiled.of(null));
assertNull(compiled.pick(new IrisBiome(), 0));
assertNull(compiled.pick(null, 0));
}
private static Map<IrisBiome, List<IrisBiome>> descendants(IrisBiome first, List<IrisBiome> firstDescendants,
IrisBiome second, List<IrisBiome> secondDescendants) {
Map<IrisBiome, List<IrisBiome>> descendants = new IdentityHashMap<>();
descendants.put(first, firstDescendants);
descendants.put(second, secondDescendants);
return descendants;
}
private static void assertBits(NoiseBounds expected, NoiseBounds actual) {
assertEquals(Double.doubleToRawLongBits(expected.min()), Double.doubleToRawLongBits(actual.min()));
assertEquals(Double.doubleToRawLongBits(expected.max()), Double.doubleToRawLongBits(actual.max()));
}
private record Fixed(Map<InferredType, List<IrisBiome>> picks, Map<IrisBiome, List<IrisBiome>> descendants)
implements RegionBounds.Reach {
@Override
public List<IrisBiome> picks(IrisRegion region, InferredType type) {
return picks.get(type);
}
@Override
public Collection<IrisBiome> descendants(IrisBiome biome) {
List<IrisBiome> known = descendants.get(biome);
return known == null ? List.of(biome) : known;
}
}
}
@@ -0,0 +1,87 @@
package art.arcane.iris.generation.runtime;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
public class SharedBaseHeightsTest {
@Test
public void storedColumnsComeBackWithTheirExactBits() {
SharedBaseHeights cache = new SharedBaseHeights(1 << 10);
double height = Math.nextUp(71.25D);
assertTrue(Double.isNaN(cache.get(12, -40)));
cache.put(12, -40, height);
assertEquals(Double.doubleToRawLongBits(height), Double.doubleToRawLongBits(cache.get(12, -40)));
assertTrue(Double.isNaN(cache.get(-40, 12)));
}
@Test
public void originMissesUntilItIsStored() {
SharedBaseHeights cache = new SharedBaseHeights(2);
assertTrue(Double.isNaN(cache.get(0, 0)));
cache.put(0, 0, -0D);
assertEquals(Double.doubleToRawLongBits(-0D), Double.doubleToRawLongBits(cache.get(0, 0)));
}
@Test
public void nonFiniteHeightsAreNeverStored() {
SharedBaseHeights cache = new SharedBaseHeights(2);
cache.put(3, 4, 64D);
cache.put(3, 4, Double.NaN);
cache.put(3, 4, Double.POSITIVE_INFINITY);
assertEquals(64D, cache.get(3, 4), 0D);
}
@Test
public void fullCoordinateDomainKeepsDistinctColumns() {
int[] coordinates = {0, 1, -1, 1 << 21, -(1 << 21), 30_000_000, -30_000_000,
Integer.MIN_VALUE, Integer.MAX_VALUE};
for (int x : coordinates) {
for (int z : coordinates) {
SharedBaseHeights cache = new SharedBaseHeights(2);
cache.put(x, z, 12D);
for (int otherX : coordinates) {
for (int otherZ : coordinates) {
if (x == otherX && z == otherZ) {
assertEquals(12D, cache.get(otherX, otherZ), 0D);
} else {
assertTrue(Double.isNaN(cache.get(otherX, otherZ)));
}
}
}
}
}
}
@Test
public void aCollidingColumnReplacesTheOldOne() {
SharedBaseHeights cache = new SharedBaseHeights(2);
cache.put(5, 9, 40D);
cache.put(6, 9, 41D);
cache.put(7, 9, 42D);
int stored = 0;
for (int x = 5; x <= 7; x++) {
double value = cache.get(x, 9);
if (!Double.isNaN(value)) {
assertEquals(35D + x, value, 0D);
stored++;
}
}
assertTrue(stored >= 1 && stored <= 2);
}
@Test
public void capacityFollowsTheHeapWithinBounds() {
assertEquals(SharedBaseHeights.MINIMUM_CAPACITY, SharedBaseHeights.capacityFor(0L));
assertEquals(SharedBaseHeights.MAXIMUM_CAPACITY, SharedBaseHeights.capacityFor(Long.MAX_VALUE));
int capacity = SharedBaseHeights.capacityFor(6L << 30);
assertEquals(1, Integer.bitCount(capacity));
assertTrue(capacity >= SharedBaseHeights.MINIMUM_CAPACITY && capacity <= SharedBaseHeights.MAXIMUM_CAPACITY);
}
}
@@ -146,7 +146,7 @@ public class SharedBoundsBiomesTest {
int xi = (int) ((state & Long.MAX_VALUE) % coordinates.length);
int zi = (int) ((state >>> 10) % coordinates.length);
cache.put(coordinates[xi], coordinates[zi], biomes[xi][zi]);
IrisBiome actual = cache.get(coordinates[xi], coordinates[zi]);
Object actual = cache.get(coordinates[xi], coordinates[zi]);
if (actual != null) {
hits.incrementAndGet();
if (actual != biomes[xi][zi]) {
@@ -7,6 +7,7 @@ import art.arcane.iris.world.history.BoundaryColumnGeometry;
import art.arcane.iris.world.history.BoundaryGeometryInfluence;
import art.arcane.iris.world.history.NativeTerrainReceipt;
import art.arcane.iris.world.history.SavedTerrainChunk;
import art.arcane.iris.world.history.TerrainBoundarySignature;
import art.arcane.iris.world.history.TransitionGenerationPlan;
import art.arcane.iris.spi.IrisPlatform;
import art.arcane.iris.spi.IrisPlatforms;
@@ -16,6 +17,7 @@ import art.arcane.iris.spi.PlatformRegistries;
import art.arcane.iris.testsupport.PlatformLeakGuard;
import art.arcane.iris.generation.context.ChunkContext;
import art.arcane.volmlib.util.hunk.Hunk;
import art.arcane.volmlib.util.stream.ProceduralStream;
import org.junit.After;
import org.junit.Before;
import org.junit.ClassRule;
@@ -23,6 +25,7 @@ import org.junit.Test;
import java.util.ArrayList;
import java.util.List;
import java.util.OptionalInt;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertEquals;
@@ -79,6 +82,9 @@ public class IrisTransitionGeometryActuatorTest {
when(biome.key()).thenReturn("minecraft:plains");
biomes.fill(biome);
ChunkContext context = mock(ChunkContext.class);
IrisComplex complex = mock(IrisComplex.class);
when(complex.getWaterHeadStream()).thenReturn(ProceduralStream.ofDouble((x, z) -> 3D));
when(context.getComplex()).thenReturn(complex);
when(context.getRoundedHeight(anyInt(), anyInt())).thenReturn(3);
SavedTerrainChunk captured = IrisTransitionGeometryActuator.capture(0, 0, blocks, biomes, 0, context, true);
@@ -146,6 +152,98 @@ public class IrisTransitionGeometryActuatorTest {
Terrain3DColumn.fromOccupancy(3, 16, y -> y == 0 || y == 3), 6);
}
@Test
public void boundaryReceiptRecordsSeaLayerCapsAtTheWaterHeadAboveTheSeabed() throws Exception {
NativeBlockState water = fluid("minecraft:water[level=0]");
NativeBlockState ice = state("minecraft:ice", false);
Hunk<NativeBlockState> blocks = filled();
for (int x = 0; x < 16; x++) {
for (int z = 0; z < 16; z++) {
int head = z == 15 ? 6 : 12;
int capBottom = z == 0 ? 9 : z == 15 ? 4 : head + 1;
for (int y = 4; y < 16; y++) {
blocks.setRaw(x, y, z, y > head ? air : y >= capBottom ? ice : water);
}
}
}
ChunkContext context = mock(ChunkContext.class);
IrisComplex complex = mock(IrisComplex.class);
when(complex.getWaterHeadStream()).thenReturn(ProceduralStream.ofDouble((x, z) -> z == 15D ? 6D : 12D));
when(context.getComplex()).thenReturn(complex);
when(context.getRoundedHeight(anyInt(), anyInt())).thenReturn(3);
SavedTerrainChunk captured = IrisTransitionGeometryActuator.capture(0, 0, blocks, biomes(), 0, context, true);
SavedTerrainChunk restored = NativeTerrainReceipt.decode(NativeTerrainReceipt.encode(captured, 7, "epoch"),
"minecraft:noise").terrain();
assertWaterColumn(restored.column(0, 0), 3, 12);
assertWaterColumn(restored.column(0, 15), 3, 6);
assertWaterColumn(restored.column(0, 7), 3, 12);
}
@Test
public void transitionKeepsSeaLayerCapsAtTheWaterHeadForDecoration() {
NativeBlockState water = fluid("minecraft:water[level=0]");
NativeBlockState ice = state("minecraft:ice", false);
when(registries.blockOrNull(ice.key())).thenReturn(ice);
for (int capBottom : new int[]{9, 4}) {
ArrayList<BoundaryColumnGeometry.Voxel> historical = new ArrayList<>(16);
for (int y = 0; y < 16; y++) {
historical.add(y <= 3 ? voxel("minecraft:stone", BoundaryColumnGeometry.Phase.SOLID, "")
: y > 12 ? voxel("minecraft:air", BoundaryColumnGeometry.Phase.AIR, "")
: y >= capBottom ? voxel(ice.key(), BoundaryColumnGeometry.Phase.SOLID, "")
: voxel(water.key(), BoundaryColumnGeometry.Phase.FLUID, water.key()));
}
ChunkContext context = context(BoundaryColumnGeometry.fromVoxels(0, historical), 12D);
Hunk<NativeBlockState> blocks = filled();
for (int x = 0; x < 16; x++) {
for (int z = 0; z < 16; z++) {
for (int y = 1; y < 16; y++) {
blocks.setRaw(x, y, z, y < 3 || y > 12 ? air : y == 3 ? stone : y >= capBottom ? ice : water);
}
}
}
new IrisTransitionGeometryActuator(mock(Engine.class)).generate(16, 0, blocks,
Hunk.newArrayHunk(16, 16, 16), false, context);
assertSame(stone, blocks.getRaw(0, 2, 0));
assertSame(ice, blocks.getRaw(0, 12, 0));
assertSame(capBottom == 4 ? ice : water, blocks.getRaw(0, 4, 0));
assertSame(air, blocks.getRaw(0, 13, 0));
int iceBottom = capBottom;
verify(context).setTerrainHeight(0, 0, 3);
verify(context).setTransitionTerrain(0, 0,
Terrain3DColumn.fromOccupancy(3, 16, y -> y <= 3 || y >= iceBottom && y <= 12), 12);
}
}
private static void assertWaterColumn(TerrainBoundarySignature signature, int seabed, int waterSurface) {
assertEquals(seabed, signature.oceanFloorHeight());
assertEquals(OptionalInt.of(waterSurface), signature.fluidHeight());
assertEquals(waterSurface, signature.surfaceHeight());
}
private static BoundaryColumnGeometry.Voxel voxel(String key, BoundaryColumnGeometry.Phase phase, String fluid) {
return new BoundaryColumnGeometry.Voxel(key, phase, fluid, false);
}
private NativeBlockState fluid(String key) {
NativeBlockState state = state(key, false);
when(state.isSolid()).thenReturn(false);
when(state.isFluid()).thenReturn(true);
when(registries.blockOrNull(key)).thenReturn(state);
return state;
}
private static Hunk<NativeBiome> biomes() {
Hunk<NativeBiome> biomes = Hunk.newArrayHunk(16, 16, 16);
NativeBiome biome = mock(NativeBiome.class);
when(biome.key()).thenReturn("minecraft:frozen_ocean");
biomes.fill(biome);
return biomes;
}
private ChunkContext context(String material) {
return context(material, 3);
}
@@ -159,8 +257,12 @@ public class IrisTransitionGeometryActuatorTest {
solid ? BoundaryColumnGeometry.Phase.SOLID : fluid ? BoundaryColumnGeometry.Phase.FLUID : BoundaryColumnGeometry.Phase.AIR,
fluid ? "minecraft:water[level=0]" : "", false));
}
return context(BoundaryColumnGeometry.fromVoxels(0, voxels), 3D);
}
private ChunkContext context(BoundaryColumnGeometry historical, double waterHead) {
BoundaryGeometryInfluence influence = new BoundaryGeometryInfluence(0D, 0D,
List.of(new BoundaryGeometryInfluence.Contribution(BoundaryColumnGeometry.fromVoxels(0, voxels), 1D)));
List.of(new BoundaryGeometryInfluence.Contribution(historical, 1D)));
TransitionGenerationPlan plan = mock(TransitionGenerationPlan.class);
when(plan.geometryAt(anyInt(), anyInt())).thenReturn(influence);
when(plan.hasTransitionAtChunk(anyInt(), anyInt())).thenReturn(true);
@@ -169,6 +271,7 @@ public class IrisTransitionGeometryActuatorTest {
when(plan.terrainSampleAt(anyInt(), anyInt())).thenReturn(sample);
IrisComplex complex = mock(IrisComplex.class);
when(complex.getTransitionGenerationPlan()).thenReturn(plan);
when(complex.getWaterHeadStream()).thenReturn(ProceduralStream.ofDouble((x, z) -> waterHead));
ChunkContext context = mock(ChunkContext.class);
when(context.getComplex()).thenReturn(complex);
when(context.getRoundedHeight(anyInt(), anyInt())).thenReturn(3);
@@ -0,0 +1,102 @@
package art.arcane.iris.generation.validation;
import art.arcane.iris.configuration.IrisSettings;
import art.arcane.volmlib.util.math.ChunkSpiral;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.concurrent.atomic.AtomicInteger;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
public class ChunkSpiralScanTest {
private IrisSettings previousSettings;
@Before
public void setUp() {
previousSettings = IrisSettings.settings;
IrisSettings.settings = new IrisSettings();
}
@After
public void tearDown() {
IrisSettings.settings = previousSettings;
}
@Test
public void singleThreadVisitsTargetsInSpiralOrder() throws Exception {
List<int[]> targets = ChunkSpiral.centerOut(3, -2, 3);
List<String> visited = Collections.synchronizedList(new ArrayList<>());
RecordingListener listener = new RecordingListener();
int failures = ChunkSpiralScan.scan(targets, 1, (int chunkX, int chunkZ) -> visited.add(chunkX + "," + chunkZ), listener);
List<String> expected = new ArrayList<>();
for (int[] target : targets) {
expected.add(target[0] + "," + target[1]);
}
assertEquals(0, failures);
assertEquals("3,-2", visited.getFirst());
assertEquals(expected, visited);
assertEquals(expected, listener.done);
}
@Test
public void parallelScanVisitsEveryTargetOnce() throws Exception {
List<int[]> targets = ChunkSpiral.centerOut(0, 0, 4);
List<String> visited = Collections.synchronizedList(new ArrayList<>());
RecordingListener listener = new RecordingListener();
int failures = ChunkSpiralScan.scan(targets, 4, (int chunkX, int chunkZ) -> visited.add(chunkX + "," + chunkZ), listener);
Set<String> unique = new HashSet<>(visited);
assertEquals(0, failures);
assertEquals(81, visited.size());
assertEquals(81, unique.size());
assertEquals(81, listener.ok.get());
}
@Test
public void failedChunksAreCountedAndReported() throws Exception {
List<int[]> targets = ChunkSpiral.centerOut(0, 0, 1);
RecordingListener listener = new RecordingListener();
int failures = ChunkSpiralScan.scan(targets, 2, (int chunkX, int chunkZ) -> {
if (chunkX == 1) {
throw new IllegalStateException("boom " + chunkX + "," + chunkZ);
}
}, listener);
assertEquals(3, failures);
assertEquals(3, listener.failed.size());
assertEquals(9, listener.done.size());
assertEquals(6, listener.ok.get());
assertTrue(listener.failed.stream().allMatch((String chunk) -> chunk.startsWith("1,")));
}
private static final class RecordingListener implements ChunkSpiralScan.Listener {
private final List<String> done = Collections.synchronizedList(new ArrayList<>());
private final List<String> failed = Collections.synchronizedList(new ArrayList<>());
private final AtomicInteger ok = new AtomicInteger();
@Override
public void chunkDone(int chunkX, int chunkZ, boolean success) {
done.add(chunkX + "," + chunkZ);
if (success) {
ok.incrementAndGet();
}
}
@Override
public void chunkFailed(int chunkX, int chunkZ, Throwable error) {
failed.add(chunkX + "," + chunkZ);
}
}
}
@@ -31,6 +31,17 @@ public class DataVersionTest {
assertEquals(121, DataVersion.V26_3.getPackFormat());
}
@Test
public void exportMetadataMatchesServerVersionJson() {
assertEquals(0, DataVersion.V26_3.getPackFormatMinor());
assertEquals(5023, DataVersion.V26_3.getWorldDataVersion());
assertEquals(1, DataVersion.V26_2.getPackFormatMinor());
assertEquals(4903, DataVersion.V26_2.getWorldDataVersion());
assertEquals(1, DataVersion.V26_1_2.getPackFormatMinor());
assertEquals(4790, DataVersion.V26_1_2.getWorldDataVersion());
assertEquals(3955, DataVersion.V1_21_1.getWorldDataVersion());
}
@Test
public void minSupportedPackFormatIsTheOldestSupportedRuntime() {
assertEquals(48, DataVersion.minSupportedPackFormat());
@@ -0,0 +1,61 @@
package art.arcane.iris.pack.datapack.export;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List;
import java.util.Map;
import java.util.stream.Stream;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertThrows;
import static org.junit.Assert.assertTrue;
public class AtomicDatapackPublisherTest {
private static final String PREFIX = ".iris-worldgen-export-";
@Rule
public TemporaryFolder temporaryFolder = new TemporaryFolder();
@Test
public void stagingDirectoryUsesCallerPrefixAndIsRemoved() throws IOException {
Path parent = temporaryFolder.getRoot().toPath();
Path destination = parent.resolve("worldgen");
byte[] metadata = "{}\n".getBytes(StandardCharsets.UTF_8);
AtomicDatapackPublisher.Publication publication = new AtomicDatapackPublisher().publish(
Map.of("pack.mcmeta", metadata), destination, DatapackExportFormat.DIRECTORY, false, PREFIX);
assertTrue(publication.cleanupWarnings().isEmpty());
assertArrayEquals(metadata, Files.readAllBytes(destination.resolve("pack.mcmeta")));
assertEquals(List.of(), entriesWithPrefix(parent));
}
@Test
public void existingDestinationWithoutReplaceIsLeftUntouched() throws IOException {
Path parent = temporaryFolder.getRoot().toPath();
Path destination = parent.resolve("worldgen.zip");
byte[] original = "original".getBytes(StandardCharsets.UTF_8);
Files.write(destination, original);
assertThrows(IOException.class, () -> new AtomicDatapackPublisher().publish(
Map.of("pack.mcmeta", new byte[]{1}), destination, DatapackExportFormat.ZIP, false, PREFIX));
assertArrayEquals(original, Files.readAllBytes(destination));
assertEquals(List.of(), entriesWithPrefix(parent));
}
private static List<String> entriesWithPrefix(Path parent) throws IOException {
try (Stream<Path> entries = Files.list(parent)) {
return entries.map(path -> path.getFileName().toString())
.filter(name -> name.startsWith(PREFIX))
.toList();
}
}
}
@@ -0,0 +1,78 @@
package art.arcane.iris.pack.datapack.export;
import org.junit.Test;
import java.nio.file.Path;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertThrows;
import static org.junit.Assert.assertTrue;
public class DatapackExportDestinationsTest {
private static final String NAME_MESSAGE =
"Export output must be one file name using letters, numbers, '.', '_', or '-'.";
@Test
public void parsesFormatAliases() {
assertEquals(DatapackExportFormat.ZIP, DatapackExportDestinations.parseFormat("zip"));
assertEquals(DatapackExportFormat.ZIP, DatapackExportDestinations.parseFormat(" ZIP "));
assertEquals(DatapackExportFormat.DIRECTORY, DatapackExportDestinations.parseFormat("directory"));
assertEquals(DatapackExportFormat.DIRECTORY, DatapackExportDestinations.parseFormat("dir"));
assertEquals(DatapackExportFormat.DIRECTORY, DatapackExportDestinations.parseFormat("folder"));
IllegalArgumentException failure = assertThrows(IllegalArgumentException.class,
() -> DatapackExportDestinations.parseFormat("tar"));
assertEquals("Export format must be directory or zip.", failure.getMessage());
}
@Test
public void resolvesOneArtifactInsideExportRoot() {
Path root = Path.of("build", "datapack-exports").toAbsolutePath().normalize();
assertEquals(root.resolve("village.zip"),
DatapackExportDestinations.resolve(root, "village", DatapackExportFormat.ZIP));
assertEquals(root.resolve("village.zip"),
DatapackExportDestinations.resolve(root, "village.zip", DatapackExportFormat.ZIP));
assertEquals(root.resolve("village"),
DatapackExportDestinations.resolve(root, "village", DatapackExportFormat.DIRECTORY));
assertThrows(IllegalArgumentException.class,
() -> DatapackExportDestinations.resolve(root, "", DatapackExportFormat.DIRECTORY));
assertThrows(IllegalArgumentException.class,
() -> DatapackExportDestinations.resolve(root, ".", DatapackExportFormat.DIRECTORY));
assertThrows(IllegalArgumentException.class,
() -> DatapackExportDestinations.resolve(root, " village", DatapackExportFormat.DIRECTORY));
}
@Test
public void rejectsPathSeparatorsInOutput() {
Path root = Path.of("build", "datapack-exports").toAbsolutePath().normalize();
IllegalArgumentException nested = assertThrows(IllegalArgumentException.class,
() -> DatapackExportDestinations.resolve(root, "nested/export", DatapackExportFormat.ZIP));
IllegalArgumentException parent = assertThrows(IllegalArgumentException.class,
() -> DatapackExportDestinations.resolve(root, "../all-exports", DatapackExportFormat.DIRECTORY));
IllegalArgumentException windows = assertThrows(IllegalArgumentException.class,
() -> DatapackExportDestinations.resolve(root, "nested\\export", DatapackExportFormat.ZIP));
assertEquals(NAME_MESSAGE, nested.getMessage());
assertEquals(NAME_MESSAGE, parent.getMessage());
assertEquals(NAME_MESSAGE, windows.getMessage());
}
@Test
public void secondExportToSamePathIsRejected() {
Path destination = Path.of("build", "datapack-exports", "claimed.zip");
Path sameDestination = Path.of("build", "datapack-exports", ".", "claimed.zip").toAbsolutePath();
assertTrue(DatapackExportDestinations.claim(destination));
try {
assertFalse(DatapackExportDestinations.claim(destination));
assertFalse(DatapackExportDestinations.claim(sameDestination));
} finally {
DatapackExportDestinations.release(destination);
}
assertTrue(DatapackExportDestinations.claim(sameDestination));
DatapackExportDestinations.release(sameDestination);
}
}
@@ -0,0 +1,36 @@
package art.arcane.iris.pack.datapack.export;
import art.arcane.iris.generation.noise.IrisGeneratorStyle;
import art.arcane.iris.generation.noise.NoiseStyle;
import art.arcane.iris.pack.datapack.export.compile.noise.NoiseRegistry;
import art.arcane.iris.pack.datapack.export.compile.noise.StyleCompiler;
import art.arcane.iris.pack.datapack.export.ir.Field;
import art.arcane.iris.pack.datapack.export.ir.NoiseDef;
import art.arcane.iris.pack.datapack.export.lower.ExportCapabilities;
import java.util.List;
import java.util.Locale;
public final class ExportTestStyles implements StyleCompiler {
private static final double COHERENT_BLOCKS = 64.0;
private static final double WARP_FREQUENCY = 2.0;
private static final double WARP_AMPLITUDE = 0.35;
private static final List<Double> SINGLE_OCTAVE = List.of(1.0);
@Override
public Field compile(IrisGeneratorStyle style, long seedSalt, NoiseRegistry registry, ExportCapabilities capabilities) {
if (style.isFlat()) {
return new Field.Const(0.5);
}
String name = "test/" + Long.toUnsignedString(seedSalt, 36) + "_" + (style.getStyle() == null ? NoiseStyle.FLAT : style.getStyle()).name().toLowerCase(Locale.ROOT);
String base = registry.register(new NoiseDef(name, 0, SINGLE_OCTAVE));
double scale = 1.0 / (COHERENT_BLOCKS * style.getZoom());
if (style.getFracture() == null) {
return new Field.Noise(base, scale, 0.0, null, null, null);
}
String warp = registry.register(new NoiseDef(name + "_warp", 0, SINGLE_OCTAVE));
Field shiftX = new Field.Binary(Field.BinaryOp.MUL, new Field.Const(WARP_AMPLITUDE), new Field.Noise(warp, scale * WARP_FREQUENCY, 0.0, null, null, null));
Field shiftZ = new Field.Binary(Field.BinaryOp.MUL, new Field.Const(-WARP_AMPLITUDE), new Field.Noise(warp, scale * WARP_FREQUENCY * 1.5, 0.0, null, null, null));
return new Field.Noise(base, scale, 0.0, shiftX, null, shiftZ);
}
}
@@ -0,0 +1,252 @@
package art.arcane.iris.pack.datapack.export;
import art.arcane.iris.generation.block.TileData;
import art.arcane.iris.pack.datapack.DataVersion;
import art.arcane.iris.pack.datapack.export.ir.ExportDiagnostic;
import art.arcane.iris.pack.datapack.export.ir.ExportLimit;
import art.arcane.iris.spi.IrisPlatform;
import art.arcane.iris.spi.IrisPlatforms;
import art.arcane.iris.spi.PlatformRegistries;
import art.arcane.iris.structure.object.IrisObject;
import art.arcane.iris.testsupport.PlatformLeakGuard;
import art.arcane.volmlib.nativelib.terrain.NativeBlockState;
import art.arcane.volmlib.util.collection.KMap;
import art.arcane.volmlib.util.nbt.io.NBTUtil;
import art.arcane.volmlib.util.nbt.mca.MCABlockStateCodecSupport;
import art.arcane.volmlib.util.nbt.tag.ByteTag;
import art.arcane.volmlib.util.nbt.tag.CompoundTag;
import art.arcane.volmlib.util.nbt.tag.IntTag;
import art.arcane.volmlib.util.nbt.tag.ListTag;
import art.arcane.volmlib.util.nbt.tag.LongTag;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.ClassRule;
import org.junit.Test;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.zip.GZIPInputStream;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertTrue;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
public class StructureTemplateEncoderTest {
@ClassRule
public static final PlatformLeakGuard PLATFORM_GUARD = PlatformLeakGuard.clean();
private static final String STAIRS = "minecraft:oak_stairs[facing=north]";
@BeforeClass
public static void bindPlatform() {
IrisPlatforms.unbind();
NativeBlockState stone = blockState("minecraft:stone");
PlatformRegistries registries = mock(PlatformRegistries.class);
when(registries.block(anyString())).thenReturn(stone);
IrisPlatform platform = mock(IrisPlatform.class);
when(platform.registries()).thenReturn(registries);
when(platform.minecraftVersion()).thenReturn("1.21.1");
IrisPlatforms.bind(platform);
}
@AfterClass
public static void unbindPlatform() {
IrisPlatforms.unbind();
}
@Test
public void dataVersionFollowsTarget() throws IOException {
IrisObject object = singleBlock("minecraft:stone");
assertEquals(5023, encode(object, List.of(), DataVersion.V26_3).getInt("DataVersion"));
assertEquals(4903, encode(object, List.of(), DataVersion.V26_2).getInt("DataVersion"));
}
@Test
public void templatesAreCompleteGzipStreams() throws IOException {
IrisObject object = singleBlock(STAIRS);
for (DataVersion target : List.of(DataVersion.V26_3, DataVersion.V26_2)) {
byte[] bytes = new StructureTemplateEncoder().encode(object, List.of(), target);
byte[] inflated;
try (InputStream input = new GZIPInputStream(new ByteArrayInputStream(bytes))) {
inflated = input.readAllBytes();
assertEquals(-1, input.read());
}
CompoundTag root = (CompoundTag) NBTUtil.read(new ByteArrayInputStream(inflated), false).getTag();
assertEquals(target.getWorldDataVersion(), root.getInt("DataVersion"));
}
}
@Test
public void paletteFormatFollowsTarget() throws IOException {
IrisObject object = singleBlock(STAIRS);
VanillaBlockState stairs = VanillaBlockState.parse(STAIRS);
assertEquals(stairs.toNbt(MCABlockStateCodecSupport.Format.LOWERCASE),
encode(object, List.of(), DataVersion.V26_3).getListTag("palette").get(0));
assertEquals(stairs.toNbt(MCABlockStateCodecSupport.Format.CAPITALIZED),
encode(object, List.of(), DataVersion.V26_2).getListTag("palette").get(0));
}
@Test
public void extraBlockOverridesObjectBlockAtSamePosition() throws IOException {
IrisObject object = new IrisObject(2, 1, 1);
object.setUnsigned(0, 0, 0, blockState("minecraft:stone"));
object.setUnsigned(1, 0, 0, blockState("minecraft:stone"));
CompoundTag nbt = new CompoundTag();
nbt.putString("id", "minecraft:jigsaw");
TemplateBlock jigsaw = new TemplateBlock(1, 0, 0,
VanillaBlockState.parse("minecraft:jigsaw[orientation=north_up]"), nbt);
CompoundTag template = encode(object, List.of(jigsaw), DataVersion.V26_3);
ListTag<?> blocks = template.getListTag("blocks");
assertEquals(2, blocks.size());
CompoundTag first = (CompoundTag) blocks.get(0);
CompoundTag second = (CompoundTag) blocks.get(1);
assertEquals(List.of(0, 0, 0), position(first));
assertNull(first.get("nbt"));
assertEquals(List.of(1, 0, 0), position(second));
assertEquals(nbt, second.getCompoundTag("nbt"));
CompoundTag paletteEntry = (CompoundTag) template.getListTag("palette").get(second.getInt("state"));
assertEquals("minecraft:jigsaw", paletteEntry.getString("id"));
assertFalse(first.getInt("state") == second.getInt("state"));
}
@Test
public void tileEntitiesRoundTrip() throws IOException {
IrisObject object = new IrisObject(2, 1, 1);
object.setUnsigned(0, 0, 0, blockState("minecraft:chest[facing=north]"));
object.setUnsigned(1, 0, 0, blockState("minecraft:oak_sign[rotation=4]"));
KMap<String, Object> item = new KMap<>();
item.put("Slot", 3L);
item.put("id", "minecraft:diamond");
item.put("count", 5L);
KMap<String, Object> chest = new KMap<>();
chest.put("Items", new ArrayList<>(List.of(item)));
chest.put("LootTableSeed", 42L);
chest.put("x", 10L);
object.setUnsignedTile(0, 0, 0, new TileData("minecraft:chest", chest));
KMap<String, Object> sign = new KMap<>();
sign.put("nbt", "{front_text:{color:\"black\",has_glowing_text:1b,messages:[\"\\\"a\\\"\",\"\\\"\\\"\",\"\\\"\\\"\",\"\\\"\\\"\"]},is_waxed:0b}");
object.setUnsignedTile(1, 0, 0, new TileData("minecraft:oak_sign", sign));
List<ExportDiagnostic> diagnostics = new ArrayList<>();
TemplateVolume volume = StructureTemplateEncoder.volume(object, "objects/test", diagnostics);
CompoundTag template = decode(new StructureTemplateEncoder().encode(volume, DataVersion.V26_3));
assertTrue(diagnostics.isEmpty());
ListTag<?> blocks = template.getListTag("blocks");
CompoundTag chestNbt = ((CompoundTag) blocks.get(0)).getCompoundTag("nbt");
assertEquals("minecraft:chest", chestNbt.getString("id"));
assertEquals(42L, ((LongTag) chestNbt.get("LootTableSeed")).asLong());
assertFalse(chestNbt.containsKey("x"));
CompoundTag stack = (CompoundTag) chestNbt.getListTag("Items").get(0);
assertEquals(3, ((ByteTag) stack.get("Slot")).asByte());
assertEquals(5, ((IntTag) stack.get("count")).asInt());
assertEquals("minecraft:diamond", stack.getString("id"));
CompoundTag signNbt = ((CompoundTag) blocks.get(1)).getCompoundTag("nbt");
assertEquals("minecraft:sign", signNbt.getString("id"));
assertEquals(1, ((ByteTag) signNbt.getCompoundTag("front_text").get("has_glowing_text")).asByte());
assertEquals(4, signNbt.getCompoundTag("front_text").getListTag("messages").size());
assertEquals(volume.blocks().get(0).nbt(), chestNbt);
}
@Test
public void unknownTileEntityBecomesExportLimit() {
IrisObject object = new IrisObject(1, 1, 1);
object.setUnsigned(0, 0, 0, blockState("minecraft:stone"));
object.setUnsignedTile(0, 0, 0, new TileData("minecraft:stone", new KMap<>()));
List<ExportDiagnostic> diagnostics = new ArrayList<>();
TemplateVolume volume = StructureTemplateEncoder.volume(object, "objects/rock", diagnostics);
assertNull(volume.blocks().getFirst().nbt());
assertEquals(1, diagnostics.size());
assertSame(ExportLimit.TILE_ENTITY, diagnostics.getFirst().limit());
assertEquals("objects/rock", diagnostics.getFirst().resource());
}
@Test
public void customBlocksAreLeftOutWithExportLimit() {
IrisObject object = new IrisObject(2, 1, 1);
object.setUnsigned(0, 0, 0, blockState("minecraft:stone"));
object.setUnsigned(1, 0, 0, blockState("mymod:crystal"));
List<ExportDiagnostic> diagnostics = new ArrayList<>();
TemplateVolume volume = StructureTemplateEncoder.volume(object, "objects/crystal", diagnostics);
assertEquals(1, volume.blocks().size());
assertEquals(1, diagnostics.size());
assertSame(ExportLimit.CUSTOM_BLOCK, diagnostics.getFirst().limit());
}
@Test
public void blocksOutsideTheObjectSizeAreLeftOutWithExportLimit() {
IrisObject object = new IrisObject(2, 2, 1);
object.setUnsigned(0, 0, 0, blockState("minecraft:stone"));
object.setUnsigned(1, -1, 0, blockState("minecraft:dirt"));
object.setUnsigned(-1, 1, 0, blockState("minecraft:dirt"));
List<ExportDiagnostic> diagnostics = new ArrayList<>();
TemplateVolume volume = StructureTemplateEncoder.volume(object, "objects/overhang", diagnostics);
assertEquals(1, volume.blocks().size());
assertEquals(1, diagnostics.size());
assertSame(ExportLimit.OBJECT_BOUNDS, diagnostics.getFirst().limit());
assertEquals("objects/overhang", diagnostics.getFirst().resource());
}
@Test
public void tileEntityMapsKeepTypedArrays() {
KMap<String, Object> profile = new KMap<>();
profile.put("id", new ArrayList<>(List.of(1L, 2L, 3L, 4L)));
profile.put("name", "Notch");
KMap<String, Object> head = new KMap<>();
head.put("profile", profile);
CompoundTag nbt = TileEntityNbt.toNbt("minecraft:player_head", head).orElseThrow();
assertEquals("minecraft:skull", nbt.getString("id"));
assertArrayEquals(new int[]{1, 2, 3, 4}, nbt.getCompoundTag("profile").getIntArray("id"));
assertTrue(TileEntityNbt.toNbt("minecraft:stone", head).isEmpty());
}
private static CompoundTag decode(byte[] bytes) throws IOException {
return (CompoundTag) NBTUtil.read(new ByteArrayInputStream(bytes), true).getTag();
}
private static CompoundTag encode(IrisObject object, List<TemplateBlock> extraBlocks, DataVersion target)
throws IOException {
byte[] bytes = new StructureTemplateEncoder().encode(object, extraBlocks, target);
return (CompoundTag) NBTUtil.read(new ByteArrayInputStream(bytes), true).getTag();
}
private static IrisObject singleBlock(String key) {
IrisObject object = new IrisObject(1, 1, 1);
object.setUnsigned(0, 0, 0, blockState(key));
return object;
}
private static List<Integer> position(CompoundTag block) {
ListTag<?> pos = block.getListTag("pos");
return List.of(((IntTag) pos.get(0)).asInt(), ((IntTag) pos.get(1)).asInt(), ((IntTag) pos.get(2)).asInt());
}
private static NativeBlockState blockState(String key) {
NativeBlockState state = mock(NativeBlockState.class);
when(state.key()).thenReturn(key);
when(state.namespace()).thenReturn(key.substring(0, key.indexOf(':')));
return state;
}
}
@@ -1,4 +1,4 @@
package art.arcane.iris.structure.export;
package art.arcane.iris.pack.datapack.export;
import art.arcane.volmlib.util.nbt.tag.CompoundTag;
import art.arcane.volmlib.util.nbt.mca.MCABlockStateCodecSupport;
@@ -1,4 +1,4 @@
package art.arcane.iris.structure.export;
package art.arcane.iris.pack.datapack.export;
import org.junit.Test;
@@ -63,4 +63,32 @@ public class VanillaResourceIdentifierTest {
assertThrows(IllegalArgumentException.class,
() -> VanillaResourceIdentifier.normalizeConnectorIdentifier("iris:../escape"));
}
@Test
public void requireChecksReturnTheValueAndNameTheRoleOnFailure() {
assertEquals("iris_export", VanillaResourceIdentifier.requireNamespace("iris_export", "export namespace"));
assertEquals("caves/deep", VanillaResourceIdentifier.requirePath("caves/deep", "biome id"));
assertEquals("minecraft:stone", VanillaResourceIdentifier.requireIdentifier("minecraft:stone", "block id"));
IllegalArgumentException path = assertThrows(IllegalArgumentException.class,
() -> VanillaResourceIdentifier.requirePath("Caves", "biome id"));
assertEquals("Invalid biome id 'Caves'", path.getMessage());
IllegalArgumentException namespace = assertThrows(IllegalArgumentException.class,
() -> VanillaResourceIdentifier.requireNamespace(null, "export namespace"));
assertEquals("Invalid export namespace 'null'", namespace.getMessage());
assertThrows(IllegalArgumentException.class,
() -> VanillaResourceIdentifier.requireIdentifier("stone", "block id"));
}
@Test
public void sanitizedPathsAreLowercaseValidAndKeepFolders() {
assertEquals("forest_biomes/dark_oak", VanillaResourceIdentifier.sanitizePath("Forest Biomes/Dark Oak"));
assertEquals("caves/deep", VanillaResourceIdentifier.sanitizePath("caves\\deep"));
assertEquals("a/b", VanillaResourceIdentifier.sanitizePath("/a//b/"));
assertEquals("__/x", VanillaResourceIdentifier.sanitizePath("../x"));
assertEquals("caf_", VanillaResourceIdentifier.sanitizePath("Caf\u00e9"));
assertTrue(VanillaResourceIdentifier.validPath(VanillaResourceIdentifier.sanitizePath("../Odd Name!/x.y")));
assertThrows(IllegalArgumentException.class, () -> VanillaResourceIdentifier.sanitizePath("///"));
assertThrows(IllegalArgumentException.class, () -> VanillaResourceIdentifier.sanitizePath(" "));
}
}
@@ -0,0 +1,479 @@
package art.arcane.iris.pack.datapack.export;
import art.arcane.iris.pack.datapack.DataVersion;
import art.arcane.iris.pack.datapack.export.compile.CompileStage;
import art.arcane.iris.pack.datapack.export.compile.DimensionStage;
import art.arcane.iris.pack.datapack.export.compile.ImageMapStage;
import art.arcane.iris.pack.datapack.export.compile.PackCompileContext;
import art.arcane.iris.pack.datapack.export.compile.PackCompiler;
import art.arcane.iris.pack.datapack.export.compile.biome.BiomeCodes;
import art.arcane.iris.pack.datapack.export.compile.object.ObjectStage;
import art.arcane.iris.pack.datapack.export.emit.WorldgenJsonWriter;
import art.arcane.iris.pack.datapack.export.ir.BiomeDef;
import art.arcane.iris.pack.datapack.export.ir.ClimateLayout;
import art.arcane.iris.pack.datapack.export.ir.ExportDiagnostic;
import art.arcane.iris.pack.datapack.export.ir.ExportIr;
import art.arcane.iris.pack.datapack.export.ir.ExportLimit;
import art.arcane.iris.pack.datapack.export.ir.Field;
import art.arcane.iris.testsupport.CompatTestPlatform;
import art.arcane.iris.testsupport.PlatformLeakGuard;
import org.junit.ClassRule;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.SortedMap;
import java.util.TreeMap;
import java.util.stream.Stream;
import java.util.zip.ZipFile;
import static org.junit.Assert.assertArrayEquals;
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.assertTrue;
public class WorldgenDatapackExporterTest {
@ClassRule
public static final PlatformLeakGuard PLATFORM_GUARD = PlatformLeakGuard.clean();
@Rule
public TemporaryFolder temporaryFolder = new TemporaryFolder();
@Rule
public ExportTestPacks.BoundPlatform platform = new ExportTestPacks.BoundPlatform();
private final List<DataVersion> writerTargets = new ArrayList<>();
@Test
public void existingOutputWithoutReplaceFails() throws Exception {
File pack = ExportTestPacks.basic(temporaryFolder.newFolder("pack"));
Path root = temporaryFolder.newFolder("exports").toPath();
Path existing = root.resolve("taken.zip");
Files.writeString(existing, "keep", StandardCharsets.UTF_8);
WorldgenExportResult result = exporter().export(request(pack, root).output("taken").build(), WorldgenExportProgress.NONE);
assertSame(WorldgenExportResult.Status.REJECTED, result.status());
assertEquals(existing, result.output());
assertTrue(result.message(), result.message().contains("already exists"));
assertEquals("keep", Files.readString(existing, StandardCharsets.UTF_8));
assertTrue(writerTargets.isEmpty());
assertEquals(List.of("taken.zip"), entries(root));
WorldgenExportResult replaced = exporter().export(request(pack, root).output("taken").replace(true).build(), WorldgenExportProgress.NONE);
assertTrue(replaced.message(), replaced.isSuccess());
assertNotNull(summary(existing));
assertEquals(List.of("taken.zip"), entries(root));
}
@Test
public void exportReportsTheLoadKeyOfEveryBiomeId() throws Exception {
File pack = ExportTestPacks.basic(temporaryFolder.newFolder("pack"));
Path root = temporaryFolder.newFolder("exports").toPath();
WorldgenExportResult result = exporter().export(request(pack, root).build(), WorldgenExportProgress.NONE);
assertTrue(result.message(), result.isSuccess());
assertEquals(Map.of("iris_export:forest_land", "Forest Land"), result.loadKeyByBiomeId());
}
@Test
public void claimedDestinationIsRejected() throws Exception {
File pack = ExportTestPacks.basic(temporaryFolder.newFolder("pack"));
Path root = temporaryFolder.newFolder("exports").toPath();
Path destination = DatapackExportDestinations.resolve(root, "busy", DatapackExportFormat.ZIP);
assertTrue(DatapackExportDestinations.claim(destination));
try {
WorldgenExportResult result = exporter().export(request(pack, root).output("busy").build(), WorldgenExportProgress.NONE);
assertSame(WorldgenExportResult.Status.REJECTED, result.status());
assertTrue(result.message(), result.message().contains("already running"));
assertFalse(Files.exists(destination));
} finally {
DatapackExportDestinations.release(destination);
}
}
@Test
public void invalidPackIsRejected() throws Exception {
File pack = ExportTestPacks.withDimension(temporaryFolder.newFolder("pack"), """
{"regions": ["region"], "hydrology": {"enabled": true, "ponds": {"freeboard": [3, 1]}}}
""");
Path root = temporaryFolder.newFolder("exports").toPath();
WorldgenExportResult result = exporter().export(request(pack, root).build(), WorldgenExportProgress.NONE);
assertSame(WorldgenExportResult.Status.REJECTED, result.status());
assertTrue(result.message(), result.message().contains("freeboard"));
assertTrue(writerTargets.isEmpty());
assertTrue(entries(root).isEmpty());
}
@Test
public void exportIsByteIdenticalAcrossRuns() throws Exception {
File pack = ExportTestPacks.basic(temporaryFolder.newFolder("pack"));
Path root = temporaryFolder.newFolder("exports").toPath();
RecordingProgress progress = new RecordingProgress();
WorldgenExportResult first = exporter().export(request(pack, root).build(), progress);
WorldgenExportResult second = exporter().export(request(pack, root).output("second").build(), WorldgenExportProgress.NONE);
assertTrue(first.message(), first.isSuccess());
assertTrue(second.message(), second.isSuccess());
assertEquals("main-26.3.zip", first.output().getFileName().toString());
assertArrayEquals(Files.readAllBytes(first.output()), Files.readAllBytes(second.output()));
assertEquals(List.of(DataVersion.V26_3, DataVersion.V26_3), writerTargets);
assertTrue(summary(first.output()), summary(first.output()).contains("target=26.3"));
assertEquals("validate", progress.stages.getFirst());
assertTrue(progress.stages.toString(), progress.stages.contains("dimension"));
assertEquals(List.of("write", "prune", "publish"), progress.stages.subList(progress.stages.size() - 3, progress.stages.size()));
assertEquals(List.of(2), progress.resourceTotals);
assertEquals(List.of(first.trim()), progress.trims);
assertEquals(2, first.trim().filesBefore());
assertEquals(0, first.trim().filesRemoved());
assertEquals(List.of("main-26.3.zip", "second.zip"), entries(root));
}
@Test
public void imageMapPackExportsWithDiagnostic() throws Exception {
File pack = ExportTestPacks.withImageMaps(temporaryFolder.newFolder("pack"));
Path root = temporaryFolder.newFolder("exports").toPath();
WorldgenExportResult result = exporter().export(request(pack, root).version("26.3").format("directory").build(), WorldgenExportProgress.NONE);
assertTrue(result.message() + " " + result.diagnostics(), result.isSuccess());
assertTrue(Files.isRegularFile(result.output().resolve("summary.txt")));
assertEquals(List.of(DataVersion.V26_3), writerTargets);
List<String> imageMapResources = new ArrayList<>();
for (ExportDiagnostic diagnostic : result.diagnostics()) {
if (diagnostic.limit() == ExportLimit.IMAGE_MAP) {
imageMapResources.add(diagnostic.resource());
}
}
assertEquals(List.of("dimensions/main", "biomes/mapped"), imageMapResources);
}
@Test
public void missingDimensionIsRejected() throws Exception {
File pack = ExportTestPacks.basic(temporaryFolder.newFolder("pack"));
Path root = temporaryFolder.newFolder("exports").toPath();
WorldgenExportResult result = exporter().export(request(pack, root).dimension("absent").build(), WorldgenExportProgress.NONE);
assertSame(WorldgenExportResult.Status.REJECTED, result.status());
assertTrue(result.message(), result.message().contains("'absent'"));
assertTrue(entries(root).isEmpty());
}
@Test
public void argumentErrorsAreRejectedBeforeThePackIsRead() throws Exception {
File pack = ExportTestPacks.basic(temporaryFolder.newFolder("pack"));
Path root = temporaryFolder.newFolder("exports").toPath();
WorldgenExportResult version = exporter().export(request(pack, root).version("1.21.1").build(), WorldgenExportProgress.NONE);
WorldgenExportResult older = exporter().export(request(pack, root).version("26.2").build(), WorldgenExportProgress.NONE);
WorldgenExportResult mode = exporter().export(request(pack, root).mode("flat").build(), WorldgenExportProgress.NONE);
WorldgenExportResult format = exporter().export(request(pack, root).format("tar").build(), WorldgenExportProgress.NONE);
WorldgenExportResult namespace = exporter().export(request(pack, root).namespace("Iris Export").build(), WorldgenExportProgress.NONE);
assertEquals("Unsupported datapack export version '1.21.1'. Supported: 26.3", version.message());
assertEquals("Unsupported datapack export version '26.2'. Supported: 26.3", older.message());
assertEquals("Unknown export mode 'flat'. Expected: preset, dimension, overworld", mode.message());
assertEquals("Export format must be directory or zip.", format.message());
assertEquals("Invalid export namespace 'Iris Export'", namespace.message());
for (WorldgenExportResult result : List.of(version, older, mode, format, namespace)) {
assertSame(WorldgenExportResult.Status.REJECTED, result.status());
}
assertTrue(entries(root).isEmpty());
}
@Test
public void objectsFlagReachesTheCompileContext() throws Exception {
File pack = ExportTestPacks.basic(temporaryFolder.newFolder("pack"));
Path root = temporaryFolder.newFolder("exports").toPath();
List<Boolean> objects = new ArrayList<>();
CompileStage recorder = new CompileStage() {
@Override
public String name() {
return "objects";
}
@Override
public void apply(PackCompileContext context) {
objects.add(context.objects());
}
};
WorldgenDatapackExporter exporter = new WorldgenDatapackExporter(
target -> new SummaryWriter(target, writerTargets),
new PackCompiler(List.of(new DimensionStage(), recorder)));
WorldgenExportResult without = exporter.export(request(pack, root).objects(false).build(), WorldgenExportProgress.NONE);
WorldgenExportResult with = exporter.export(request(pack, root).output("with").build(), WorldgenExportProgress.NONE);
assertTrue(without.message(), without.isSuccess());
assertTrue(with.message(), with.isSuccess());
assertEquals(List.of(false, true), objects);
}
@Test
public void exportReportsGenerationCostAndFlagsClimateRootsOverBudget() throws Exception {
File pack = ExportTestPacks.basic(temporaryFolder.newFolder("pack"));
Path root = temporaryFolder.newFolder("exports").toPath();
CompileStage climate = new CompileStage() {
@Override
public String name() {
return "biomes";
}
@Override
public void apply(PackCompileContext context) {
BiomeCodes base = context.biomeCodes();
Field code = new Field.Noise("minecraft:temperature", 0.25, 0.0, null, null, null);
for (int level = 0; level < 20; level++) {
code = new Field.Shared("climate/level/" + level, new Field.Binary(Field.BinaryOp.MAX, code, code));
}
context.setBiomeCodes(new BiomeCodes(code, base.caveCode(), base.class3d(), base.layout(), base.loadKeyByBiomeId()));
}
};
WorldgenDatapackExporter exporter = new WorldgenDatapackExporter(WorldgenJsonWriter::forTarget,
new PackCompiler(List.of(new DimensionStage(), climate)));
WorldgenExportResult result = exporter.export(request(pack, root).format("directory").build(), WorldgenExportProgress.NONE);
assertTrue(result.message() + " " + result.diagnostics(), result.isSuccess());
GenerationCost.RootCost temperature = result.cost().root(GenerationCost.Root.TEMPERATURE).orElseThrow();
assertEquals(3_145_726.0, temperature.expandedNodes(), 0.0);
assertEquals(3_145_726.0, temperature.worstCaseNodes(), 0.0);
assertEquals(42L, temperature.distinctNodes());
assertTrue(result.cost().root(GenerationCost.Root.FINAL_DENSITY).isPresent());
assertEquals(0.0, result.cost().root(GenerationCost.Root.RIDGES).orElseThrow().expandedNodes(), 0.0);
List<ExportDiagnostic> cost = result.diagnostics().stream().filter(diagnostic -> diagnostic.limit() == ExportLimit.GENERATION_COST).toList();
assertEquals(cost.toString(), 1, cost.size());
assertEquals("noise_settings/" + ExportTestPacks.DIMENSION + "/temperature", cost.getFirst().resource());
assertEquals(densityFunctionBytes(result.output()), result.cost().densityFunctionBytes());
assertTrue(result.cost().densityFunctionBytes() > 0L);
}
private static long densityFunctionBytes(Path output) throws IOException {
long bytes = 0L;
try (Stream<Path> paths = Files.walk(output)) {
for (Path path : paths.filter(Files::isRegularFile).toList()) {
String relative = output.relativize(path).toString().replace(File.separatorChar, '/');
if (relative.contains("/worldgen/density_function/") && relative.endsWith(".json")) {
bytes += Files.size(path);
}
}
}
return bytes;
}
@Test
public void createdExporterWritesTheTargetFileSet() throws Exception {
File pack = ExportTestPacks.basic(temporaryFolder.newFolder("pack"));
Path root = temporaryFolder.newFolder("exports").toPath();
WorldgenDatapackExporter exporter = WorldgenDatapackExporter.create();
WorldgenExportResult current = exporter.export(request(pack, root).format("directory").build(), WorldgenExportProgress.NONE);
assertTrue(current.message() + " " + current.diagnostics(), current.isSuccess());
List<String> shared = List.of(
"data/iris_export/dimension_type/main.json",
"data/iris_export/worldgen/biome/forest_land.json",
"data/iris_export/worldgen/biome/mapped.json",
"data/iris_export/worldgen/biome/ocean.json",
"data/iris_export/worldgen/density_function/main/aquifer/barrier.json",
"data/iris_export/worldgen/density_function/main/aquifer/fluid_level_spread.json",
"data/iris_export/worldgen/density_function/main/aquifer/lava.json",
"data/iris_export/worldgen/density_function/main/final_density.json",
"data/iris_export/worldgen/noise_settings/main.json",
"data/minecraft/dimension/overworld.json",
"pack.mcmeta",
"pack.png");
List<String> currentOnly = List.of(
"data/iris_export/worldgen/density_function/main/chunk_surface_level.json",
"data/iris_export/worldgen/density_function/main/spawn_elevation.json",
"data/iris_export/worldgen/material_rule/main.json");
List<String> currentFiles = files(current.output());
assertTrue(currentFiles.toString(), currentFiles.containsAll(shared));
assertTrue(currentFiles.toString(), currentFiles.containsAll(currentOnly));
assertTrue(current.diagnostics().toString(), current.diagnostics().stream().noneMatch(diagnostic -> diagnostic.severity() == ExportDiagnostic.Severity.ERROR));
}
@Test
public void onlyThePlacedObjectTemplateShips() throws Exception {
File pack = objectPack(temporaryFolder.newFolder("pack"));
Path root = temporaryFolder.newFolder("exports").toPath();
RecordingProgress progress = new RecordingProgress();
List<String> written = new ArrayList<>();
WorldgenDatapackExporter exporter = new WorldgenDatapackExporter(target -> ir -> {
SortedMap<String, byte[]> output = WorldgenJsonWriter.forTarget(target).write(ir);
written.addAll(output.keySet());
return output;
}, new PackCompiler(List.of(new DimensionStage(), new UnreachablePlainsStage(), new ObjectStage())));
WorldgenExportResult result = exporter.export(request(pack, root).format("directory").build(), progress);
assertTrue(result.message() + " " + result.diagnostics(), result.isSuccess());
assertTrue(written.toString(), written.stream().anyMatch(file -> file.endsWith(".nbt") && file.contains("/rocks/pillar")));
assertTrue(written.toString(), written.contains("data/iris_export/worldgen/biome/plains.json"));
assertEquals(written.size(), result.trim().filesBefore());
List<String> files = files(result.output());
List<String> templates = files.stream().filter(file -> file.endsWith(".nbt")).toList();
assertFalse(files.toString(), templates.isEmpty());
assertTrue(templates.toString(), templates.stream().allMatch(file -> file.contains("/rocks/boulder")));
assertTrue(files.toString(), files.stream().noneMatch(file -> file.contains("/rocks/pillar")));
assertTrue(files.toString(), files.contains("data/iris_export/worldgen/biome/forest.json"));
assertFalse(files.toString(), files.contains("data/iris_export/worldgen/biome/plains.json"));
assertTrue(result.trim().toString(), result.trim().filesRemoved() > 0);
assertEquals(files.size(), result.trim().filesAfter());
assertEquals(List.of(result.trim()), progress.trims);
List<ExportDiagnostic> trimmed = result.diagnostics().stream().filter(diagnostic -> diagnostic.limit() == ExportLimit.TRIMMED_CONTENT).toList();
assertEquals(1, trimmed.size());
assertSame(ExportDiagnostic.Severity.INFO, trimmed.getFirst().severity());
assertTrue(trimmed.getFirst().message(), trimmed.getFirst().message().contains(result.trim().filesRemoved() + " of " + result.trim().filesBefore() + " files"));
}
private WorldgenDatapackExporter exporter() {
return new WorldgenDatapackExporter(target -> new SummaryWriter(target, writerTargets),
new PackCompiler(List.of(new DimensionStage(), new ImageMapStage())));
}
private static WorldgenExportRequest.Builder request(File pack, Path root) {
return WorldgenExportRequest.builder()
.pack(pack.toPath())
.dimension(ExportTestPacks.DIMENSION)
.exportRoot(root);
}
private static File objectPack(File pack) throws IOException {
CompatTestPlatform.write(pack, "dimensions/" + ExportTestPacks.DIMENSION + ".json", "{\"regions\":[\"region\"]}");
CompatTestPlatform.write(pack, "regions/region.json", "{\"landBiomes\":[\"forest\",\"plains\"]}");
CompatTestPlatform.write(pack, "biomes/forest.json", """
{"name":"Forest","objects":[{"place":["rocks/boulder"],"chance":0.5,"density":1}]}
""");
CompatTestPlatform.write(pack, "biomes/plains.json", """
{"name":"Plains","objects":[{"place":["rocks/pillar"],"chance":0.5,"density":1}]}
""");
writeObject(pack, "rocks/boulder", "minecraft:stone", "minecraft:grass_block");
writeObject(pack, "rocks/pillar", "minecraft:stone", "minecraft:stone", "minecraft:stone");
return pack;
}
private static void writeObject(File pack, String key, String... column) throws IOException {
File file = new File(pack, "objects/" + key + ".iob");
if (!file.getParentFile().isDirectory() && !file.getParentFile().mkdirs()) {
throw new IOException("Could not create " + file.getParentFile());
}
try (DataOutputStream out = new DataOutputStream(new FileOutputStream(file))) {
out.writeInt(1);
out.writeInt(column.length);
out.writeInt(1);
out.writeUTF("Iris V2 IOB;");
out.writeShort(column.length);
for (String entry : column) {
out.writeUTF(entry);
}
out.writeInt(column.length);
for (int index = 0; index < column.length; index++) {
out.writeShort(0);
out.writeShort(index - column.length / 2);
out.writeShort(0);
out.writeShort(index);
}
out.writeInt(0);
}
}
private static List<String> entries(Path root) throws IOException {
try (Stream<Path> children = Files.list(root)) {
return children.map(path -> path.getFileName().toString()).sorted().toList();
}
}
private static List<String> files(Path directory) throws IOException {
try (Stream<Path> files = Files.walk(directory)) {
return files.filter(Files::isRegularFile).map(file -> directory.relativize(file).toString().replace('\\', '/')).sorted().toList();
}
}
private static String summary(Path zip) throws IOException {
try (ZipFile file = new ZipFile(zip.toFile())) {
return new String(file.getInputStream(file.getEntry("summary.txt")).readAllBytes(), StandardCharsets.UTF_8);
}
}
private record SummaryWriter(DataVersion target, List<DataVersion> targets) implements WorldgenJsonWriter {
@Override
public SortedMap<String, byte[]> write(ExportIr ir) {
assertSame(target, ir.target());
targets.add(target);
String summary = "namespace=" + ir.namespace() + "\n"
+ "target=" + ir.target().getVersion() + "\n"
+ "mode=" + ir.mode() + "\n"
+ "dimension=" + ir.dimension() + "\n"
+ "noises=" + ir.noises() + "\n"
+ "router=" + ir.router() + "\n"
+ "climate=" + ir.climate() + "\n"
+ "biomes=" + ir.biomes() + "\n"
+ "material=" + ir.material() + "\n"
+ "diagnostics=" + ir.diagnostics() + "\n";
SortedMap<String, byte[]> files = new TreeMap<>();
files.put("pack.mcmeta", ("{\"pack\":{\"description\":\"" + ir.namespace() + "\"}}\n").getBytes(StandardCharsets.UTF_8));
files.put("summary.txt", summary.getBytes(StandardCharsets.UTF_8));
return files;
}
}
private static final class UnreachablePlainsStage implements CompileStage {
private static final String FOREST = WorldgenExportRequest.DEFAULT_NAMESPACE + ":forest";
private static final String PLAINS = WorldgenExportRequest.DEFAULT_NAMESPACE + ":plains";
private static final Field ZERO = new Field.Const(0.0);
@Override
public String name() {
return "biomes";
}
@Override
public void apply(PackCompileContext context) {
DataVersion target = context.capabilities().target();
context.setBiomes(List.of(new BiomeDef("forest", ExportIrFixtures.biome()), new BiomeDef("plains", ExportIrFixtures.biome())));
ClimateLayout layout = new ClimateLayout(List.of(new ClimateLayout.ClimateEntry(FOREST, ClimateLayout.ClimateAxis.TEMPERATURE, -1.0, 1.0)));
context.setBiomeCodes(new BiomeCodes(ZERO, ZERO, ZERO, layout, Map.of(FOREST, "forest", PLAINS, "plains")));
}
}
private static final class RecordingProgress implements WorldgenExportProgress {
private final List<String> stages = new ArrayList<>();
private final List<Integer> resourceTotals = new ArrayList<>();
private final List<ContentTrim> trims = new ArrayList<>();
@Override
public void stage(String stage) {
stages.add(stage);
}
@Override
public void resources(int done, int total) {
resourceTotals.add(total);
}
@Override
public void trimmed(ContentTrim trim) {
trims.add(trim);
}
}
}
@@ -0,0 +1,76 @@
package art.arcane.iris.pack.datapack.export;
import org.junit.Test;
import java.nio.file.Path;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertThrows;
import static org.junit.Assert.assertTrue;
public class WorldgenExportRequestTest {
private static final Path PACK = Path.of("packs", "overworld");
private static final Path EXPORT_ROOT = Path.of("exports", "datapacks");
@Test
public void builderDefaults() {
WorldgenExportRequest request = WorldgenExportRequest.builder()
.pack(PACK)
.dimension("overworld")
.exportRoot(EXPORT_ROOT)
.build();
assertEquals(PACK, request.pack());
assertEquals("overworld", request.dimension());
assertEquals("", request.version());
assertEquals("overworld", request.mode());
assertEquals("iris_export", request.namespace());
assertEquals("", request.output());
assertEquals("zip", request.format());
assertTrue(request.objects());
assertFalse(request.replace());
assertEquals(EXPORT_ROOT, request.exportRoot());
}
@Test
public void builderOverridesEveryField() {
WorldgenExportRequest request = WorldgenExportRequest.builder()
.pack(PACK)
.dimension(" overworld ")
.version("26.3")
.mode("dimension")
.namespace("my_pack")
.output("custom")
.format("directory")
.objects(false)
.replace(true)
.exportRoot(EXPORT_ROOT)
.build();
assertEquals("overworld", request.dimension());
assertEquals("26.3", request.version());
assertEquals("dimension", request.mode());
assertEquals("my_pack", request.namespace());
assertEquals("custom", request.output());
assertEquals("directory", request.format());
assertFalse(request.objects());
assertTrue(request.replace());
}
@Test
public void missingPackIsRejected() {
IllegalArgumentException error = assertThrows(IllegalArgumentException.class, () -> WorldgenExportRequest.builder().dimension("overworld").exportRoot(EXPORT_ROOT).build());
assertEquals("Worldgen export request requires a pack directory", error.getMessage());
}
@Test
public void blankDimensionIsRejected() {
IllegalArgumentException error = assertThrows(IllegalArgumentException.class, () -> WorldgenExportRequest.builder().pack(PACK).dimension(" ").exportRoot(EXPORT_ROOT).build());
assertEquals("Worldgen export request requires a dimension", error.getMessage());
}
@Test
public void missingExportRootIsRejected() {
IllegalArgumentException error = assertThrows(IllegalArgumentException.class, () -> WorldgenExportRequest.builder().pack(PACK).dimension("overworld").build());
assertEquals("Worldgen export request requires an export root", error.getMessage());
}
}
@@ -0,0 +1,89 @@
package art.arcane.iris.pack.datapack.export;
import art.arcane.iris.pack.datapack.export.ir.ExportDiagnostic;
import art.arcane.iris.pack.datapack.export.ir.ExportLimit;
import org.junit.Test;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.EnumMap;
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.assertNull;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertThrows;
import static org.junit.Assert.assertTrue;
public class WorldgenExportResultTest {
private static final Path OUTPUT = Path.of("exports", "datapacks", "overworld-26.3.zip");
@Test
public void exportedResultCarriesOutputAndDiagnostics() {
List<ExportDiagnostic> diagnostics = new ArrayList<>();
diagnostics.add(new ExportDiagnostic(ExportDiagnostic.Severity.WARNING, ExportLimit.IMAGE_MAP, "overworld", "Image map layer dropped"));
Map<String, String> loadKeys = new HashMap<>();
loadKeys.put("iris_export:plains", "Plains");
ContentTrim trim = new ContentTrim(12, 4096L, 9, 3000L);
Map<GenerationCost.Root, GenerationCost.RootCost> roots = new EnumMap<>(GenerationCost.Root.class);
roots.put(GenerationCost.Root.TEMPERATURE, new GenerationCost.RootCost(90.0, 120.0, 40L));
GenerationCost cost = new GenerationCost(roots, 4_096L);
roots.clear();
WorldgenExportResult result = WorldgenExportResult.exported(OUTPUT, diagnostics, loadKeys, trim, cost);
diagnostics.clear();
loadKeys.clear();
assertSame(WorldgenExportResult.Status.EXPORTED, result.status());
assertTrue(result.isSuccess());
assertEquals(OUTPUT, result.output());
assertEquals("", result.message());
assertEquals(1, result.diagnostics().size());
assertEquals(Map.of("iris_export:plains", "Plains"), result.loadKeyByBiomeId());
assertSame(trim, result.trim());
assertEquals(3, result.trim().filesRemoved());
assertEquals(1096L, result.trim().bytesRemoved());
assertEquals(120.0, result.cost().root(GenerationCost.Root.TEMPERATURE).orElseThrow().expandedNodes(), 0.0);
assertTrue(result.cost().root(GenerationCost.Root.DEPTH).isEmpty());
assertEquals(4_096L, result.cost().densityFunctionBytes());
}
@Test
public void exportedResultRequiresOutput() {
assertThrows(NullPointerException.class, () -> WorldgenExportResult.exported(null, List.of(), Map.of(), ContentTrim.NONE, GenerationCost.NONE));
}
@Test
public void contentTrimCannotGrow() {
assertThrows(IllegalArgumentException.class, () -> new ContentTrim(1, 10L, 2, 10L));
assertThrows(IllegalArgumentException.class, () -> new ContentTrim(1, 10L, 1, 11L));
assertThrows(IllegalArgumentException.class, () -> new ContentTrim(-1, 0L, -1, 0L));
}
@Test
public void rejectedResultMayOmitOutput() {
WorldgenExportResult result = WorldgenExportResult.rejected(null, "Pack is invalid", List.of());
assertSame(WorldgenExportResult.Status.REJECTED, result.status());
assertFalse(result.isSuccess());
assertNull(result.output());
assertEquals("Pack is invalid", result.message());
assertTrue(result.loadKeyByBiomeId().isEmpty());
assertSame(ContentTrim.NONE, result.trim());
assertSame(GenerationCost.NONE, result.cost());
}
@Test
public void failedResultKeepsMessage() {
WorldgenExportResult result = WorldgenExportResult.failed(OUTPUT, "Publication failed", List.of());
assertSame(WorldgenExportResult.Status.FAILED, result.status());
assertEquals("Publication failed", result.message());
assertSame(ContentTrim.NONE, result.trim());
}
@Test
public void noneProgressIgnoresUpdates() {
WorldgenExportProgress.NONE.stage("compile");
WorldgenExportProgress.NONE.resources(1, 2);
}
}
@@ -0,0 +1,39 @@
package art.arcane.iris.pack.datapack.export;
import org.junit.Test;
import java.nio.file.Path;
import java.util.List;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertThrows;
import static org.junit.Assert.assertTrue;
public class WorldgenExportServicesTest {
@Test
public void serviceDefaultsToTheDatapackExporterAndLatestInstallWins() {
WorldgenExportService fallback = WorldgenExportServices.get();
assertTrue(fallback instanceof WorldgenDatapackExporter);
assertSame(fallback, WorldgenExportServices.get());
WorldgenExportService first = new FixedService("first");
WorldgenExportService second = new FixedService("second");
WorldgenExportServices.install(first);
assertSame(first, WorldgenExportServices.get());
WorldgenExportServices.install(second);
assertSame(second, WorldgenExportServices.get());
}
@Test
public void installRejectsMissingService() {
assertThrows(NullPointerException.class, () -> WorldgenExportServices.install(null));
}
private record FixedService(String message) implements WorldgenExportService {
@Override
public WorldgenExportResult export(WorldgenExportRequest request, WorldgenExportProgress progress) {
return WorldgenExportResult.rejected(Path.of(message), message, List.of());
}
}
}
@@ -0,0 +1,63 @@
package art.arcane.iris.pack.datapack.export;
import art.arcane.iris.pack.datapack.DataVersion;
import org.junit.Test;
import java.util.List;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertThrows;
public class WorldgenExportTargetsTest {
@Test
public void supportedTargetsStartAt26_3() {
assertEquals(List.of(DataVersion.V26_3), WorldgenExportTargets.SUPPORTED);
}
@Test
public void blankResolvesToLatestSupported() {
assertSame(DataVersion.V26_3, WorldgenExportTargets.resolve(""));
assertSame(DataVersion.V26_3, WorldgenExportTargets.resolve(" "));
assertSame(DataVersion.V26_3, WorldgenExportTargets.resolve(null));
}
@Test
public void patchSpellingResolves() {
assertSame(DataVersion.V26_3, WorldgenExportTargets.resolve("26.3.0"));
assertSame(DataVersion.V26_3, WorldgenExportTargets.resolve(" 26.3 "));
}
@Test
public void olderVersionsAreRefused() {
for (String older : List.of("26.2", "26.2.0", "26.1.2", "1.21.1")) {
IllegalArgumentException error = assertThrows(IllegalArgumentException.class, () -> WorldgenExportTargets.resolve(older));
assertEquals("Unsupported datapack export version '" + older + "'. Supported: 26.3", error.getMessage());
}
}
@Test
public void unknownVersionListsSupported() {
IllegalArgumentException error = assertThrows(IllegalArgumentException.class, () -> WorldgenExportTargets.resolve("27.0"));
assertEquals("Unsupported datapack export version '27.0'. Supported: 26.3", error.getMessage());
}
@Test
public void blankModeIsOverworld() {
assertSame(WorldgenExportMode.OVERWORLD, WorldgenExportMode.parse(""));
assertSame(WorldgenExportMode.OVERWORLD, WorldgenExportMode.parse(null));
}
@Test
public void modeParsingIgnoresCase() {
assertSame(WorldgenExportMode.PRESET, WorldgenExportMode.parse("preset"));
assertSame(WorldgenExportMode.DIMENSION, WorldgenExportMode.parse("Dimension"));
assertSame(WorldgenExportMode.OVERWORLD, WorldgenExportMode.parse(" OVERWORLD "));
}
@Test
public void unknownModeMessage() {
IllegalArgumentException error = assertThrows(IllegalArgumentException.class, () -> WorldgenExportMode.parse("nether"));
assertEquals("Unknown export mode 'nether'. Expected: preset, dimension, overworld", error.getMessage());
}
}
@@ -0,0 +1,93 @@
package art.arcane.iris.pack.datapack.export.compile;
import art.arcane.iris.pack.datapack.export.ExportTestPacks;
import art.arcane.iris.pack.datapack.export.VanillaBlockState;
import art.arcane.iris.pack.datapack.export.ir.ExportDiagnostic;
import art.arcane.iris.pack.datapack.export.ir.ExportLimit;
import art.arcane.iris.pack.loading.IrisData;
import art.arcane.iris.spi.PlatformRegistries;
import art.arcane.iris.testsupport.PlatformLeakGuard;
import art.arcane.volmlib.nativelib.terrain.NativeBlockProperty;
import org.junit.ClassRule;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertTrue;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
public class BlockStateResolverTest {
@ClassRule
public static final PlatformLeakGuard PLATFORM_GUARD = PlatformLeakGuard.clean();
@Rule
public TemporaryFolder temporaryFolder = new TemporaryFolder();
@Rule
public ExportTestPacks.BoundPlatform platform = new ExportTestPacks.BoundPlatform();
@Test
public void invalidPropertyExportsDefaultStateWithDiagnostic() throws Exception {
List<ExportDiagnostic> diagnostics = new ArrayList<>();
IrisData data = IrisData.openRuntime(ExportTestPacks.basic(temporaryFolder.newFolder("pack")));
try {
BlockStateResolver resolver = new BlockStateResolver(data, registries(), diagnostics);
Optional<VanillaBlockState> valid = resolver.resolve("oak_log[axis=x]", "biomes/a");
Optional<VanillaBlockState> invalid = resolver.resolve("OAK_LOG[axis=q]", "biomes/a");
assertEquals("minecraft:oak_log[axis=x]", valid.orElseThrow().canonical());
assertEquals("minecraft:oak_log", invalid.orElseThrow().canonical());
assertEquals(1, diagnostics.size());
assertSame(ExportLimit.BLOCK_STATE, diagnostics.getFirst().limit());
assertEquals("biomes/a", diagnostics.getFirst().resource());
resolver.resolve("oak_log[axis=q]", "biomes/a");
assertEquals(1, diagnostics.size());
} finally {
data.close();
}
}
@Test
public void foreignBlocksAreNotExported() throws Exception {
List<ExportDiagnostic> diagnostics = new ArrayList<>();
IrisData data = IrisData.openRuntime(ExportTestPacks.basic(temporaryFolder.newFolder("pack")));
try {
BlockStateResolver resolver = new BlockStateResolver(data, null, diagnostics);
assertTrue(resolver.resolve("somemod:glowing_rock", "biomes/b").isEmpty());
assertEquals(1, diagnostics.size());
assertSame(ExportLimit.BLOCK_STATE, diagnostics.getFirst().limit());
} finally {
data.close();
}
}
@Test
public void legacyNamesFollowTheRenameTable() throws Exception {
IrisData data = IrisData.openRuntime(ExportTestPacks.basic(temporaryFolder.newFolder("pack")));
try {
BlockStateResolver resolver = new BlockStateResolver(data, registries(), new ArrayList<>());
assertEquals("minecraft:short_grass", resolver.resolve("grass", "biomes/c").orElseThrow().canonical());
} finally {
data.close();
}
}
private static PlatformRegistries registries() {
PlatformRegistries registries = mock(PlatformRegistries.class);
when(registries.blockTypeKeys()).thenReturn(List.of("minecraft:oak_log", "minecraft:short_grass", "minecraft:stone"));
when(registries.blockStateProperties()).thenReturn(Map.of("minecraft:oak_log",
List.of(new NativeBlockProperty("axis", "string", "y", List.of("x", "y", "z"), null))));
return registries;
}
}
@@ -0,0 +1,114 @@
package art.arcane.iris.pack.datapack.export.compile;
import art.arcane.iris.pack.datapack.DataVersion;
import art.arcane.iris.pack.datapack.export.ExportTestPacks;
import art.arcane.iris.pack.datapack.export.ir.DimensionDef;
import art.arcane.iris.pack.datapack.export.ir.ExportLimit;
import art.arcane.iris.pack.loading.IrisData;
import art.arcane.iris.testsupport.PlatformLeakGuard;
import com.google.gson.JsonObject;
import org.junit.ClassRule;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import java.io.File;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertThrows;
import static org.junit.Assert.assertTrue;
public class DimensionStageTest {
@ClassRule
public static final PlatformLeakGuard PLATFORM_GUARD = PlatformLeakGuard.clean();
@Rule
public TemporaryFolder temporaryFolder = new TemporaryFolder();
@Rule
public ExportTestPacks.BoundPlatform platform = new ExportTestPacks.BoundPlatform();
@Test
public void dimensionDefFollowsTheIrisDimension() throws Exception {
File pack = ExportTestPacks.basic(temporaryFolder.newFolder("pack"));
IrisData data = IrisData.openRuntime(pack);
try {
PackCompileContext context = ExportTestPacks.context(data, DataVersion.V26_3);
new DimensionStage().apply(context);
DimensionDef dimension = context.dimensionDef();
assertEquals("main", dimension.name());
assertEquals(-64, dimension.minY());
assertEquals(384, dimension.height());
assertEquals(256, dimension.logicalHeight());
assertEquals(63, dimension.fluidHeight());
assertEquals(64, dimension.seaLevel());
assertEquals("minecraft:stone", dimension.defaultBlock());
assertEquals("minecraft:water", dimension.defaultFluid());
JsonObject type = dimension.dimensionType();
assertEquals(-64, type.get("min_y").getAsInt());
assertEquals(384, type.get("height").getAsInt());
assertEquals(256, type.get("logical_height").getAsInt());
assertTrue(context.diagnostics().isEmpty());
} finally {
data.close();
}
}
@Test
public void unalignedHeightsExportAlignedWithDiagnostic() throws Exception {
File pack = ExportTestPacks.withDimension(temporaryFolder.newFolder("pack"), """
{"regions": ["region"], "dimensionHeight": {"min": -60, "max": 250}, "logicalHeight": 310, "fluidHeight": 40}
""");
IrisData data = IrisData.openRuntime(pack);
try {
PackCompileContext context = ExportTestPacks.context(data, DataVersion.V26_3);
new DimensionStage().apply(context);
DimensionDef dimension = context.dimensionDef();
assertEquals(-64, dimension.minY());
assertEquals(320, dimension.height());
assertEquals(320, dimension.logicalHeight());
assertEquals(40, dimension.fluidHeight());
assertEquals(41, dimension.seaLevel());
assertEquals(-64, dimension.dimensionType().get("min_y").getAsInt());
assertEquals(320, dimension.dimensionType().get("height").getAsInt());
assertEquals(1, context.diagnostics().size());
assertSame(ExportLimit.DIMENSION_HEIGHT, context.diagnostics().getFirst().limit());
} finally {
data.close();
}
}
@Test
public void paletteBlocksBecomeNamespacedIds() throws Exception {
File pack = ExportTestPacks.withDimension(temporaryFolder.newFolder("pack"), """
{"regions": ["region"],
"rockPalette": {"palette": [{"block": "DEEPSLATE[axis=y]"}, {"block": "stone"}]},
"fluidPalette": {"palette": [{"block": "minecraft:lava"}]}}
""");
IrisData data = IrisData.openRuntime(pack);
try {
PackCompileContext context = ExportTestPacks.context(data, DataVersion.V26_3);
new DimensionStage().apply(context);
assertEquals("minecraft:deepslate", context.dimensionDef().defaultBlock());
assertEquals("minecraft:lava", context.dimensionDef().defaultFluid());
} finally {
data.close();
}
}
@Test
public void readingTheDimensionDefBeforeTheStageFails() throws Exception {
File pack = ExportTestPacks.basic(temporaryFolder.newFolder("pack"));
IrisData data = IrisData.openRuntime(pack);
try {
PackCompileContext context = ExportTestPacks.context(data, DataVersion.V26_3);
assertThrows(IllegalStateException.class, context::dimensionDef);
} finally {
data.close();
}
}
}
@@ -0,0 +1,81 @@
package art.arcane.iris.pack.datapack.export.compile;
import art.arcane.iris.pack.datapack.DataVersion;
import art.arcane.iris.pack.datapack.export.ExportTestPacks;
import art.arcane.iris.pack.datapack.export.ir.ExportDiagnostic;
import art.arcane.iris.pack.datapack.export.ir.ExportLimit;
import art.arcane.iris.pack.loading.IrisData;
import art.arcane.iris.testsupport.PlatformLeakGuard;
import org.junit.ClassRule;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertTrue;
public class ImageMapStageTest {
@ClassRule
public static final PlatformLeakGuard PLATFORM_GUARD = PlatformLeakGuard.clean();
@Rule
public TemporaryFolder temporaryFolder = new TemporaryFolder();
@Rule
public ExportTestPacks.BoundPlatform platform = new ExportTestPacks.BoundPlatform();
@Test
public void eachAffectedResourceReportsOneDiagnostic() throws Exception {
File pack = ExportTestPacks.withImageMaps(temporaryFolder.newFolder("pack"));
IrisData data = IrisData.openRuntime(pack);
try {
PackCompileContext context = ExportTestPacks.context(data, DataVersion.V26_3);
new ImageMapStage().apply(context);
List<String> resources = new ArrayList<>();
for (ExportDiagnostic diagnostic : context.diagnostics()) {
assertSame(ExportLimit.IMAGE_MAP, diagnostic.limit());
assertSame(ExportDiagnostic.Severity.WARNING, diagnostic.severity());
resources.add(diagnostic.resource());
}
assertEquals(List.of("dimensions/main", "biomes/mapped"), resources);
} finally {
data.close();
}
}
@Test
public void dimensionImageMapLayerIsDropped() throws Exception {
File pack = ExportTestPacks.withImageMaps(temporaryFolder.newFolder("pack"));
IrisData data = IrisData.openRuntime(pack);
try {
PackCompileContext context = ExportTestPacks.context(data, DataVersion.V26_3);
assertEquals(1, context.dimension().getImageMaps().size());
new ImageMapStage().apply(context);
assertTrue(context.dimension().getImageMaps().isEmpty());
} finally {
data.close();
}
}
@Test
public void packWithoutImageMapsReportsNothing() throws Exception {
File pack = ExportTestPacks.basic(temporaryFolder.newFolder("pack"));
IrisData data = IrisData.openRuntime(pack);
try {
PackCompileContext context = ExportTestPacks.context(data, DataVersion.V26_3);
new ImageMapStage().apply(context);
assertTrue(context.diagnostics().toString(), context.diagnostics().isEmpty());
} finally {
data.close();
}
}
}
@@ -0,0 +1,292 @@
package art.arcane.iris.pack.datapack.export.compile;
import art.arcane.iris.generation.noise.IrisGeneratorStyle;
import art.arcane.iris.pack.datapack.DataVersion;
import art.arcane.iris.pack.datapack.export.ExportTestPacks;
import art.arcane.iris.pack.datapack.export.ExportTestStyles;
import art.arcane.iris.pack.datapack.export.WorldgenExportMode;
import art.arcane.iris.pack.datapack.export.WorldgenExportProgress;
import art.arcane.iris.pack.datapack.export.compile.decoration.GenerationStep;
import art.arcane.iris.pack.datapack.export.compile.noise.StyleCompiler;
import art.arcane.iris.pack.datapack.export.ir.AquiferDef;
import art.arcane.iris.pack.datapack.export.ir.Axis;
import art.arcane.iris.pack.datapack.export.ir.BinaryResource;
import art.arcane.iris.pack.datapack.export.ir.BiomeDef;
import art.arcane.iris.pack.datapack.export.ir.ClimateLayout;
import art.arcane.iris.pack.datapack.export.ir.ExportIr;
import art.arcane.iris.pack.datapack.export.ir.Field;
import art.arcane.iris.pack.datapack.export.ir.JsonResource;
import art.arcane.iris.pack.datapack.export.ir.MaterialProgram;
import art.arcane.iris.pack.loading.IrisData;
import art.arcane.iris.testsupport.PlatformLeakGuard;
import com.google.gson.JsonArray;
import com.google.gson.JsonParser;
import org.junit.ClassRule;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import java.io.File;
import java.util.ArrayList;
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.assertSame;
import static org.junit.Assert.assertThrows;
import static org.junit.Assert.assertTrue;
public class PackCompilerTest {
private static final Field Y = new Field.Coord(Axis.Y, Field.Tiling.CLAMP, -64, 320, -64.5, 319.5);
@ClassRule
public static final PlatformLeakGuard PLATFORM_GUARD = PlatformLeakGuard.clean();
@Rule
public TemporaryFolder temporaryFolder = new TemporaryFolder();
@Rule
public ExportTestPacks.BoundPlatform platform = new ExportTestPacks.BoundPlatform();
@Test
public void stagesRunInOrderAndReportProgress() throws Exception {
File pack = ExportTestPacks.basic(temporaryFolder.newFolder("pack"));
IrisData data = IrisData.openRuntime(pack);
try {
List<String> applied = new ArrayList<>();
RecordingProgress progress = new RecordingProgress();
PackCompiler compiler = new PackCompiler(List.of(new DimensionStage(), new NamedStage("first", applied), new NamedStage("second", applied)));
compiler.compile(ExportTestPacks.context(data, DataVersion.V26_3), progress);
assertEquals(List.of("first", "second"), applied);
assertEquals(List.of("dimension", "first", "second", "router"), progress.stages);
} finally {
data.close();
}
}
@Test
public void defaultStagesRunInPipelineOrder() throws Exception {
File pack = ExportTestPacks.basic(temporaryFolder.newFolder("pack"));
IrisData data = IrisData.openRuntime(pack);
try {
RecordingProgress progress = new RecordingProgress();
ExportIr ir = PackCompiler.create().compile(ExportTestPacks.contextBuilder(data, DataVersion.V26_3).styles(new ExportTestStyles()).build(), progress);
assertEquals(List.of("dimension", "image-maps", "biomes", "terrain", "rivers", "caves", "surface", "decoration",
"structures", "subterrain", "objects", "router"), progress.stages);
assertEquals(3, ir.biomes().size());
assertEquals(3, ir.climate().entries().size());
assertFalse(ir.noises().isEmpty());
} finally {
data.close();
}
}
@Test
public void materialDefaultsToRockWithoutSurfaceStage() throws Exception {
File pack = ExportTestPacks.basic(temporaryFolder.newFolder("pack"));
IrisData data = IrisData.openRuntime(pack);
try {
ExportIr ir = new PackCompiler(List.of(new DimensionStage())).compile(ExportTestPacks.context(data, DataVersion.V26_3), WorldgenExportProgress.NONE);
assertEquals(MaterialProgram.rock("minecraft:stone"), ir.material());
} finally {
data.close();
}
}
@Test
public void unfilledSlotsUseTheDefaults() throws Exception {
File pack = ExportTestPacks.basic(temporaryFolder.newFolder("pack"));
IrisData data = IrisData.openRuntime(pack);
try {
ExportIr ir = new PackCompiler(List.of(new DimensionStage(), new ImageMapStage()))
.compile(ExportTestPacks.context(data, DataVersion.V26_3), WorldgenExportProgress.NONE);
Field height = new Field.Const(63.0);
assertEquals("iris_export", ir.namespace());
assertSame(DataVersion.V26_3, ir.target());
assertSame(WorldgenExportMode.PRESET, ir.mode());
assertTrue(ir.noises().isEmpty());
assertEquals(finalDensity(height, new Field.Const(0.0), new Field.Const(1.0e6)), ir.router().finalDensity());
assertEquals(new Field.Grid(height, 16, 1), ir.router().chunkSurfaceLevel());
assertEquals(AquiferDef.dry(height), ir.router().aquifer());
assertEquals(1, ir.biomes().size());
BiomeDef biome = ir.biomes().getFirst();
assertEquals("forest_land", biome.id());
assertTrue(biome.json().toString(), biome.json().has("effects"));
assertEquals(List.of(new ClimateLayout.ClimateEntry("iris_export:forest_land", ClimateLayout.ClimateAxis.TEMPERATURE, -1.0, 1.0)),
ir.climate().entries());
assertEquals(new Field.Const(0.0), ir.router().temperature());
} finally {
data.close();
}
}
@Test
public void defaultBiomeCodesMapTheIdToItsLoadKey() throws Exception {
File pack = ExportTestPacks.basic(temporaryFolder.newFolder("pack"));
IrisData data = IrisData.openRuntime(pack);
try {
PackCompileContext context = ExportTestPacks.context(data, DataVersion.V26_3);
new DimensionStage().apply(context);
assertEquals(Map.of("iris_export:forest_land", "Forest Land"), context.biomeCodes().loadKeyByBiomeId());
assertSame(context.biomes(), context.biomes());
} finally {
data.close();
}
}
@Test
public void filledSlotsReplaceTheDefaults() throws Exception {
File pack = ExportTestPacks.basic(temporaryFolder.newFolder("pack"));
IrisData data = IrisData.openRuntime(pack);
try {
Field height = new Field.Noise("iris_export:height", 1.0, 0.0, null, null, null);
Field volumetric = new Field.Noise("iris_export:terrain3d", 1.0, 1.0, null, null, null);
Field caves = new Field.Noise("iris_export:caves", 1.0, 1.0, null, null, null);
CompileStage terrain = new CompileStage() {
@Override
public String name() {
return "terrain";
}
@Override
public void apply(PackCompileContext context) {
context.setHeight(height);
context.setVolumetric(volumetric);
context.setCaves(caves);
context.setMaterial(MaterialProgram.rock("minecraft:deepslate"));
}
};
ExportIr ir = new PackCompiler(List.of(new DimensionStage(), terrain))
.compile(ExportTestPacks.context(data, DataVersion.V26_3), WorldgenExportProgress.NONE);
assertEquals(finalDensity(height, volumetric, caves), ir.router().finalDensity());
assertEquals(AquiferDef.dry(height), ir.router().aquifer());
assertEquals(MaterialProgram.rock("minecraft:deepslate"), ir.material());
} finally {
data.close();
}
}
@Test
public void heightSlotRejectsThreeDimensionalFields() throws Exception {
File pack = ExportTestPacks.basic(temporaryFolder.newFolder("pack"));
IrisData data = IrisData.openRuntime(pack);
try {
PackCompileContext context = ExportTestPacks.context(data, DataVersion.V26_3);
Field volume = new Field.Noise("iris_export:terrain3d", 1.0, 1.0, null, null, null);
assertThrows(IllegalStateException.class, () -> context.setHeight(volume));
} finally {
data.close();
}
}
@Test
public void compilerCopiesResourcesAndAppliesFeatures() throws Exception {
File pack = ExportTestPacks.basic(temporaryFolder.newFolder("pack"));
IrisData data = IrisData.openRuntime(pack);
try {
JsonResource feature = new JsonResource("data/iris_export/worldgen/feature/tree.json", JsonParser.parseString("{\"type\":\"minecraft:tree\"}"));
BinaryResource template = new BinaryResource("data/iris_export/structure/tree.nbt", new byte[]{10, 0, 0});
CompileStage decoration = new CompileStage() {
@Override
public String name() {
return "decoration";
}
@Override
public void apply(PackCompileContext context) {
context.jsonResources().add(feature);
context.binaryResources().add(template);
context.features().add("iris_export:forest_land", GenerationStep.VEGETAL_DECORATION, "iris_export:tree");
}
};
ExportIr ir = new PackCompiler(List.of(new DimensionStage(), decoration))
.compile(ExportTestPacks.context(data, DataVersion.V26_3), WorldgenExportProgress.NONE);
assertEquals(List.of(feature), ir.jsonResources());
assertEquals(List.of(template), ir.binaryResources());
JsonArray steps = ir.biomes().getFirst().json().getAsJsonArray("features");
assertEquals(GenerationStep.values().length, steps.size());
assertEquals(JsonParser.parseString("[\"iris_export:tree\"]"), steps.get(GenerationStep.VEGETAL_DECORATION.ordinal()));
assertEquals(new JsonArray(), steps.get(GenerationStep.RAW_GENERATION.ordinal()));
} finally {
data.close();
}
}
@Test
public void defaultStyleCompilerThrowsUntilInstalled() throws Exception {
File pack = ExportTestPacks.basic(temporaryFolder.newFolder("pack"));
IrisData data = IrisData.openRuntime(pack);
try {
PackCompileContext context = ExportTestPacks.context(data, DataVersion.V26_3);
StyleCompiler styles = context.styles();
IllegalStateException error = assertThrows(IllegalStateException.class,
() -> styles.compile(new IrisGeneratorStyle(), 0L, context.noises(), context.capabilities()));
assertEquals("No style compiler installed", error.getMessage());
assertTrue(context.objects());
} finally {
data.close();
}
}
@Test
public void builderInstallsStyleCompilerAndObjectsFlag() throws Exception {
File pack = ExportTestPacks.basic(temporaryFolder.newFolder("pack"));
IrisData data = IrisData.openRuntime(pack);
try {
Field compiled = new Field.Const(2.0);
StyleCompiler styles = (style, seedSalt, registry, capabilities) -> compiled;
PackCompileContext context = ExportTestPacks.contextBuilder(data, DataVersion.V26_3)
.styles(styles)
.objects(false)
.build();
assertSame(styles, context.styles());
assertSame(compiled, context.styles().compile(new IrisGeneratorStyle(), 1L, context.noises(), context.capabilities()));
assertFalse(context.objects());
} finally {
data.close();
}
}
private static Field finalDensity(Field height, Field volumetric, Field caves) {
Field ramp = new Field.Binary(Field.BinaryOp.MUL, new Field.Const(1.0), new Field.Binary(Field.BinaryOp.SUB, height, Y));
Field terrain = new Field.Binary(Field.BinaryOp.ADD, ramp, new Field.Grid(volumetric, 4, 8));
return new Field.Binary(Field.BinaryOp.MIN, terrain, caves);
}
private record NamedStage(String name, List<String> applied) implements CompileStage {
@Override
public void apply(PackCompileContext context) {
applied.add(name);
}
}
private static final class RecordingProgress implements WorldgenExportProgress {
private final List<String> stages = new ArrayList<>();
@Override
public void stage(String stage) {
stages.add(stage);
}
@Override
public void resources(int done, int total) {
}
}
}
@@ -0,0 +1,99 @@
package art.arcane.iris.pack.datapack.export.compile;
import art.arcane.iris.pack.datapack.DataVersion;
import art.arcane.iris.pack.datapack.export.compile.biome.BiomeCodes;
import art.arcane.iris.pack.datapack.export.ir.AquiferDef;
import art.arcane.iris.pack.datapack.export.ir.Axis;
import art.arcane.iris.pack.datapack.export.ir.ClimateLayout;
import art.arcane.iris.pack.datapack.export.ir.DimensionDef;
import art.arcane.iris.pack.datapack.export.ir.Field;
import art.arcane.iris.pack.datapack.export.ir.FieldEvaluator;
import art.arcane.iris.pack.datapack.export.ir.RouterDef;
import com.google.gson.JsonObject;
import org.junit.Test;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertThrows;
import static org.junit.Assert.assertTrue;
public class RouterCompilerTest {
private static final Field HEIGHT = new Field.Noise("iris_export:height", 1.0, 0.0, null, null, null);
private static final Field VOLUMETRIC = new Field.Noise("iris_export:terrain3d", 1.0, 1.0, null, null, null);
private static final Field CAVES = new Field.Noise("iris_export:caves", 1.0, 1.0, null, null, null);
private static final Field SURFACE_CODE = new Field.Noise("iris_export:surface_code", 1.0, 0.0, null, null, null);
private static final Field CAVE_CODE = new Field.Noise("iris_export:cave_code", 1.0, 0.0, null, null, null);
private static final Field CLASS_3D = new Field.Noise("iris_export:class3d", 1.0, 1.0, null, null, null);
@Test
public void finalDensityIsTheMinimumOfTerrainAndCaves() {
RouterDef router = RouterCompiler.compile(HEIGHT, VOLUMETRIC, CAVES, AquiferDef.dry(HEIGHT), codes(), dimension());
Field y = new Field.Coord(Axis.Y, Field.Tiling.CLAMP, -64, 320, -64.5, 319.5);
Field ramp = new Field.Binary(Field.BinaryOp.MUL, new Field.Const(1.0), new Field.Binary(Field.BinaryOp.SUB, HEIGHT, y));
Field terrain = new Field.Binary(Field.BinaryOp.ADD, ramp, new Field.Grid(VOLUMETRIC, 4, 8));
assertEquals(new Field.Binary(Field.BinaryOp.MIN, terrain, CAVES), router.finalDensity());
}
@Test
public void topSolidBlockIsTheRoundedHeight() {
for (double height : new double[]{63.0, 63.4, 63.6, -12.2, 150.7}) {
Field surface = new Field.Const(height);
RouterDef router = RouterCompiler.compile(surface, new Field.Const(0.0), new Field.Const(1.0e6), AquiferDef.dry(surface), codes(), dimension());
int top = (int) Math.round(height);
assertTrue(height + " solid at " + top, FieldEvaluator.sample(router.finalDensity(), Map.of(), 0L, DataVersion.V26_3, 0, top, 0) > 0.0);
assertTrue(height + " air at " + (top + 1), FieldEvaluator.sample(router.finalDensity(), Map.of(), 0L, DataVersion.V26_3, 0, top + 1, 0) <= 0.0);
}
}
@Test
public void cavesCarveFarBelowTheSurface() {
Field surface = new Field.Const(100.0);
RouterDef router = RouterCompiler.compile(surface, new Field.Const(0.0), new Field.Const(-0.25), AquiferDef.dry(surface), codes(), dimension());
assertTrue(FieldEvaluator.sample(router.finalDensity(), Map.of(), 0L, DataVersion.V26_3, 0, -40, 0) <= 0.0);
}
@Test
public void chunkSurfaceLevelIsHeightOnASixteenBlockGrid() {
RouterDef router = RouterCompiler.compile(HEIGHT, VOLUMETRIC, CAVES, AquiferDef.dry(HEIGHT), codes(), dimension());
assertEquals(new Field.Grid(HEIGHT, 16, 1), router.chunkSurfaceLevel());
}
@Test
public void biomeCodesDriveTheClimateAxesAndTheAquiferPassesThrough() {
AquiferDef aquifer = AquiferDef.dry(HEIGHT);
RouterDef router = RouterCompiler.compile(HEIGHT, VOLUMETRIC, CAVES, aquifer, codes(), dimension());
assertSame(SURFACE_CODE, router.temperature());
assertSame(CAVE_CODE, router.vegetation());
assertSame(CLASS_3D, router.depth());
assertEquals(new Field.Const(0.0), router.continents());
assertEquals(new Field.Const(0.0), router.erosion());
assertEquals(new Field.Const(0.0), router.ridges());
assertSame(aquifer, router.aquifer());
}
@Test
public void heightMustBeTwoDimensional() {
IllegalStateException failure = assertThrows(IllegalStateException.class,
() -> RouterCompiler.compile(VOLUMETRIC, VOLUMETRIC, CAVES, AquiferDef.dry(HEIGHT), codes(), dimension()));
assertEquals("2D field 'height' depends on Y", failure.getMessage());
}
private static BiomeCodes codes() {
ClimateLayout layout = new ClimateLayout(List.of(
new ClimateLayout.ClimateEntry("iris_export:plains", ClimateLayout.ClimateAxis.TEMPERATURE, -1.0, 1.0)));
return new BiomeCodes(SURFACE_CODE, CAVE_CODE, CLASS_3D, layout, Map.of("iris_export:plains", "plains"));
}
private static DimensionDef dimension() {
return DimensionDef.aligned("overworld", -64, 384, 384, 63, "minecraft:stone", "minecraft:water", new JsonObject(), new ArrayList<>());
}
}
@@ -0,0 +1,93 @@
package art.arcane.iris.pack.datapack.export.compile;
import art.arcane.iris.pack.datapack.DataVersion;
import art.arcane.iris.pack.datapack.export.ExportTestPacks;
import art.arcane.iris.pack.datapack.export.compile.biome.BiomeCodes;
import art.arcane.iris.pack.datapack.export.compile.biome.BiomeIdSanitizer;
import art.arcane.iris.pack.datapack.export.ir.ClimateLayout;
import art.arcane.iris.pack.datapack.export.ir.Field;
import art.arcane.iris.pack.loading.IrisData;
import art.arcane.iris.testsupport.CompatTestPlatform;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.function.Predicate;
public final class StageTestPacks {
public static final String NAMESPACE = "iris_export";
private StageTestPacks() {
}
public static File pack(File folder, String dimensionJson, Map<String, String> biomes) throws IOException {
CompatTestPlatform.write(folder, "dimensions/" + ExportTestPacks.DIMENSION + ".json", dimensionJson);
StringBuilder land = new StringBuilder();
for (String key : biomes.keySet()) {
land.append(land.isEmpty() ? "" : ",").append('"').append(key).append('"');
}
CompatTestPlatform.write(folder, "regions/region.json", "{\"landBiomes\":[" + land + "]}");
for (Map.Entry<String, String> biome : biomes.entrySet()) {
CompatTestPlatform.write(folder, "biomes/" + biome.getKey() + ".json", biome.getValue());
}
return folder;
}
public static PackCompileContext context(IrisData data, DataVersion target, List<String> biomeKeys) {
PackCompileContext context = ExportTestPacks.context(data, target);
new DimensionStage().apply(context);
Map<String, String> loadKeys = new LinkedHashMap<>();
List<ClimateLayout.ClimateEntry> entries = new ArrayList<>(biomeKeys.size());
Set<String> taken = new HashSet<>();
for (int index = 0; index < biomeKeys.size(); index++) {
String id = BiomeIdSanitizer.sanitize(NAMESPACE, biomeKeys.get(index), taken);
loadKeys.put(id, biomeKeys.get(index));
entries.add(new ClimateLayout.ClimateEntry(id, ClimateLayout.ClimateAxis.TEMPERATURE, -1.0 + index * 0.01, -1.0 + (index + 1) * 0.01));
}
Field zero = new Field.Const(0.0);
context.setBiomeCodes(new BiomeCodes(zero, zero, zero, new ClimateLayout(entries), loadKeys));
return context;
}
public static String biomeId(String key) {
return BiomeIdSanitizer.sanitize(NAMESPACE, key, new HashSet<>());
}
public static List<JsonObject> find(JsonElement root, Predicate<JsonObject> predicate) {
List<JsonObject> found = new ArrayList<>();
collect(root, predicate, found);
return found;
}
public static List<JsonObject> ofType(JsonElement root, String type) {
return find(root, object -> object.has("type") && object.get("type").isJsonPrimitive() && type.equals(object.get("type").getAsString()));
}
private static void collect(JsonElement element, Predicate<JsonObject> predicate, List<JsonObject> found) {
if (element.isJsonArray()) {
JsonArray array = element.getAsJsonArray();
for (JsonElement item : array) {
collect(item, predicate, found);
}
return;
}
if (!element.isJsonObject()) {
return;
}
JsonObject object = element.getAsJsonObject();
if (predicate.test(object)) {
found.add(object);
}
for (Map.Entry<String, JsonElement> member : object.entrySet()) {
collect(member.getValue(), predicate, found);
}
}
}
@@ -0,0 +1,41 @@
package art.arcane.iris.pack.datapack.export.compile.biome;
import art.arcane.iris.pack.datapack.export.ir.ClimateLayout;
import art.arcane.iris.pack.datapack.export.ir.Field;
import org.junit.Test;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertThrows;
public class BiomeCodesTest {
private static final Field FLAT = new Field.Noise("iris_export:code", 1.0, 0.0, null, null, null);
private static final Field VOLUME = new Field.Noise("iris_export:class", 1.0, 1.0, null, null, null);
private static final ClimateLayout LAYOUT = new ClimateLayout(List.of(
new ClimateLayout.ClimateEntry("iris_export:plains", ClimateLayout.ClimateAxis.TEMPERATURE, -1.0, 1.0)));
@Test
public void codeRootsAreTwoDimensional() {
IllegalStateException surface = assertThrows(IllegalStateException.class,
() -> new BiomeCodes(VOLUME, FLAT, VOLUME, LAYOUT, Map.of()));
assertEquals("2D field 'surface code' depends on Y", surface.getMessage());
IllegalStateException cave = assertThrows(IllegalStateException.class,
() -> new BiomeCodes(FLAT, VOLUME, VOLUME, LAYOUT, Map.of()));
assertEquals("2D field 'cave code' depends on Y", cave.getMessage());
}
@Test
public void loadKeysAreCopiedInIdOrderAndMustUseFullIds() {
Map<String, String> loadKeys = new HashMap<>();
loadKeys.put("iris_export:zebra", "Zebra");
loadKeys.put("iris_export:alpha", "Alpha");
BiomeCodes codes = new BiomeCodes(FLAT, FLAT, VOLUME, LAYOUT, loadKeys);
loadKeys.clear();
assertEquals(List.of("iris_export:alpha", "iris_export:zebra"), List.copyOf(codes.loadKeyByBiomeId().keySet()));
assertThrows(IllegalArgumentException.class, () -> new BiomeCodes(FLAT, FLAT, VOLUME, LAYOUT, Map.of("plains", "Plains")));
}
}
@@ -0,0 +1,407 @@
package art.arcane.iris.pack.datapack.export.compile.biome;
import art.arcane.iris.generation.noise.IrisGeneratorStyle;
import art.arcane.iris.pack.datapack.DataVersion;
import art.arcane.iris.pack.datapack.export.ExportTestPacks;
import art.arcane.iris.pack.datapack.export.ExportTestStyles;
import art.arcane.iris.pack.datapack.export.compile.DimensionStage;
import art.arcane.iris.pack.datapack.export.compile.PackCompileContext;
import art.arcane.iris.pack.datapack.export.compile.noise.NoiseRegistry;
import art.arcane.iris.pack.datapack.export.compile.noise.StyleCompiler;
import art.arcane.iris.pack.datapack.export.compile.terrain.FieldMacros;
import art.arcane.iris.pack.datapack.export.ir.Axis;
import art.arcane.iris.pack.datapack.export.ir.ClimateLayout;
import art.arcane.iris.pack.datapack.export.ir.CostClass;
import art.arcane.iris.pack.datapack.export.ir.Field;
import art.arcane.iris.pack.datapack.export.ir.FieldEvaluator;
import art.arcane.iris.pack.datapack.export.ir.NoiseDef;
import art.arcane.iris.pack.datapack.export.lower.ExportCapabilities;
import art.arcane.iris.pack.loading.IrisData;
import art.arcane.iris.testsupport.PlatformLeakGuard;
import org.junit.ClassRule;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import java.io.File;
import java.util.ArrayList;
import java.util.Collections;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.IdentityHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
import java.util.TreeSet;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
public class BiomeDecisionCompilerTest {
private static final long WORLD_SEED = 7_331L;
private static final int GRID = 96;
private static final int STRIDE = 24;
@ClassRule
public static final PlatformLeakGuard PLATFORM_GUARD = PlatformLeakGuard.clean();
@Rule
public TemporaryFolder temporaryFolder = new TemporaryFolder();
@Rule
public ExportTestPacks.BoundPlatform platform = new ExportTestPacks.BoundPlatform();
@Test
public void childrenAppliedUpToFourHops() throws Exception {
File pack = SelectionTestPacks.childChain(temporaryFolder.newFolder("pack"));
IrisData data = IrisData.openRuntime(pack);
try {
PackCompileContext context = context(data);
BiomeDecision decision = new BiomeDecisionCompiler(context.styles()).compile(context);
BiomeCodes codes = decision.bind(new Field.Const(context.dimensionDef().fluidHeight() + 100.0));
assertEquals(Set.of("a", "b", "c", "d", "e", "sea"), Set.copyOf(codes.loadKeyByBiomeId().values()));
Map<String, Double> shares = shares(context, codes);
assertEquals(shares.toString(), 0.5, shares.getOrDefault("a", 0.0), 0.15);
assertEquals(shares.toString(), 0.5, shares.getOrDefault("e", 0.0), 0.15);
assertEquals(shares.toString(), 1.0, shares.getOrDefault("a", 0.0) + shares.getOrDefault("e", 0.0), 1.0e-9);
} finally {
data.close();
}
}
@Test
public void selectorsCompileThroughTheSelectorStyles() throws Exception {
File pack = SelectionTestPacks.childChain(temporaryFolder.newFolder("pack"));
IrisData data = IrisData.openRuntime(pack);
try {
PackCompileContext context = context(data);
StyleCompiler selectorsOnly = new StyleCompiler() {
@Override
public Field compile(IrisGeneratorStyle style, long seedSalt, NoiseRegistry registry, ExportCapabilities capabilities) {
throw new AssertionError("Biome selectors compile through the selector styles");
}
@Override
public StyleCompiler selectors() {
return context.styles();
}
};
BiomeCodes codes = new BiomeDecisionCompiler(selectorsOnly).compile(context).base();
assertFalse(codes.surfaceCode() instanceof Field.Const);
} finally {
data.close();
}
}
@Test
public void eachChildHopReadsThePreviousHopOnce() throws Exception {
File pack = SelectionTestPacks.childChainBesideStillBiome(temporaryFolder.newFolder("pack"));
IrisData data = IrisData.openRuntime(pack);
try {
PackCompileContext context = context(data);
Field base = new BiomeDecisionCompiler(context.styles()).compile(context).base().surfaceCode();
Map<String, Field.Shared> shared = new TreeMap<>();
collectShared(base, shared, Collections.newSetFromMap(new IdentityHashMap<>()));
assertTrue(shared.keySet().toString(), shared.containsKey("biome/land/hop2"));
assertEquals(1, references(shared.get("biome/land/hop1").expr(), shared.get("biome/land/pick")));
assertEquals(1, references(shared.get("biome/land/hop2").expr(), shared.get("biome/land/hop1")));
} finally {
data.close();
}
}
@Test
public void codeRootsAreTwoDimensional() throws Exception {
File pack = SelectionTestPacks.threeRegions(temporaryFolder.newFolder("pack"));
IrisData data = IrisData.openRuntime(pack);
try {
PackCompileContext context = context(data);
BiomeDecision decision = new BiomeDecisionCompiler(context.styles()).compile(context);
BiomeCodes bound = decision.bind(height(context));
for (BiomeCodes codes : List.of(decision.base(), bound)) {
assertFalse(codes.surfaceCode().axes().contains(Axis.Y));
assertFalse(codes.caveCode().axes().contains(Axis.Y));
}
assertEquals(EnumSet.of(Axis.X, Axis.Z), bound.surfaceCode().axes());
assertEquals(EnumSet.of(Axis.X, Axis.Z), bound.caveCode().axes());
assertTrue(bound.class3d().axes().contains(Axis.Y));
} finally {
data.close();
}
}
@Test
public void expensiveSubtreesSitUnderMuxOrGate() throws Exception {
File pack = SelectionTestPacks.threeRegions(temporaryFolder.newFolder("pack"));
IrisData data = IrisData.openRuntime(pack);
try {
PackCompileContext context = context(data);
BiomeDecision decision = new BiomeDecisionCompiler(context.styles()).compile(context);
BiomeCodes bound = decision.bind(height(context));
List<String> violations = new ArrayList<>();
for (Field root : List.of(bound.surfaceCode(), bound.caveCode(), bound.class3d(), decision.base().surfaceCode())) {
collectEagerExpensive(root, violations);
}
assertTrue(violations.toString(), violations.isEmpty());
assertEquals(CostClass.EXPENSIVE, bound.surfaceCode().cost());
} finally {
data.close();
}
}
@Test
public void compilationIsDeterministic() throws Exception {
File pack = SelectionTestPacks.threeRegions(temporaryFolder.newFolder("pack"));
IrisData first = IrisData.openRuntime(pack);
IrisData second = IrisData.openRuntime(pack);
try {
PackCompileContext firstContext = context(first);
PackCompileContext secondContext = context(second);
BiomeDecision firstDecision = new BiomeDecisionCompiler(firstContext.styles()).compile(firstContext);
BiomeDecision secondDecision = new BiomeDecisionCompiler(secondContext.styles()).compile(secondContext);
assertEquals(firstDecision.base(), secondDecision.base());
assertEquals(firstDecision.bind(height(firstContext)), secondDecision.bind(height(secondContext)));
assertEquals(firstContext.noises().definitions(), secondContext.noises().definitions());
} finally {
first.close();
second.close();
}
}
@Test
public void layoutPutsSurfaceCodesOnTemperatureAndUndergroundCodesOnDepth() throws Exception {
File pack = SelectionTestPacks.threeRegions(temporaryFolder.newFolder("pack"));
IrisData data = IrisData.openRuntime(pack);
try {
PackCompileContext context = context(data);
BiomeCodes codes = new BiomeDecisionCompiler(context.styles()).compile(context).base();
Map<String, ClimateLayout.ClimateAxis> axes = new TreeMap<>();
for (ClimateLayout.ClimateEntry entry : codes.layout().entries()) {
axes.put(codes.loadKeyByBiomeId().get(entry.biomeId()), entry.axis());
assertTrue(entry.toString(), entry.axis() == ClimateLayout.ClimateAxis.TEMPERATURE
? entry.min() >= -1.0 && entry.max() <= 1.0
: entry.min() >= 1.25 && entry.max() <= 2.0);
}
assertEquals(ClimateLayout.ClimateAxis.TEMPERATURE, axes.get("birch_forest"));
assertEquals(ClimateLayout.ClimateAxis.DEPTH, axes.get("ice_cave"));
assertEquals(ClimateLayout.ClimateAxis.DEPTH, axes.get("deep_dark"));
assertEquals(18, codes.layout().entries().size());
} finally {
data.close();
}
}
@Test
public void shoreRelabelFollowsHeight() throws Exception {
File pack = SelectionTestPacks.threeRegions(temporaryFolder.newFolder("pack"));
IrisData data = IrisData.openRuntime(pack);
try {
PackCompileContext context = context(data);
BiomeDecision decision = new BiomeDecisionCompiler(context.styles()).compile(context);
double fluid = context.dimensionDef().fluidHeight();
Set<String> deep = Set.copyOf(shares(context, decision.bind(new Field.Const(fluid - 20.0))).keySet());
Set<String> coast = Set.copyOf(shares(context, decision.bind(new Field.Const(fluid))).keySet());
Set<String> high = Set.copyOf(shares(context, decision.bind(new Field.Const(fluid + 40.0))).keySet());
assertTrue(deep.toString(), Set.of("frozen_ocean", "warm_ocean", "ocean", "deep_ocean").containsAll(deep));
assertTrue(coast.toString(), Set.of("snowy_beach", "beach").containsAll(coast));
assertTrue(high.toString(), Set.of("tundra", "taiga", "desert", "savanna", "mesa", "plains", "forest", "birch_forest").containsAll(high));
assertTrue(high.toString(), high.contains("birch_forest"));
} finally {
data.close();
}
}
@Test
public void boundCodesReadTheHeightOncePerComparison() throws Exception {
File pack = SelectionTestPacks.threeRegions(temporaryFolder.newFolder("pack"));
IrisData data = IrisData.openRuntime(pack);
try {
PackCompileContext context = context(data);
BiomeDecision decision = new BiomeDecisionCompiler(context.styles()).compile(context);
Field height = height(context);
BiomeCodes bound = decision.bind(height);
assertEquals(2, references(bound.surfaceCode(), height));
assertEquals(1, references(bound.class3d(), height));
assertEquals(0, references(bound.surfaceCode(), decision.base().surfaceCode()));
} finally {
data.close();
}
}
@Test
public void caveGateAndCarvingBandSelectUndergroundBiomes() throws Exception {
File pack = SelectionTestPacks.threeRegions(temporaryFolder.newFolder("pack"));
IrisData data = IrisData.openRuntime(pack);
try {
PackCompileContext context = context(data);
BiomeCodes codes = new BiomeDecisionCompiler(context.styles()).compile(context).bind(new Field.Const(60.0));
Map<String, NoiseDef> noises = noises(context);
Set<String> carving = new TreeSet<>();
Set<String> caves = new TreeSet<>();
Set<String> shallow = new TreeSet<>();
for (int x = 0; x < GRID; x++) {
for (int z = 0; z < GRID; z++) {
carving.add(biomeAt(codes, noises, x * STRIDE, -48, z * STRIDE));
caves.add(biomeAt(codes, noises, x * STRIDE, -20, z * STRIDE));
shallow.add(biomeAt(codes, noises, x * STRIDE, 20, z * STRIDE));
}
}
assertEquals(Set.of("deep_dark"), carving);
assertTrue(caves.toString(), caves.containsAll(Set.of("ice_cave", "lush_cave", "dripstone_cave")));
assertFalse(caves.toString(), caves.contains("deep_dark"));
assertTrue(shallow.toString(), shallow.stream().noneMatch(Set.of("ice_cave", "lush_cave", "dripstone_cave", "deep_dark")::contains));
} finally {
data.close();
}
}
static PackCompileContext context(IrisData data) {
PackCompileContext context = ExportTestPacks.contextBuilder(data, DataVersion.V26_3).styles(new ExportTestStyles()).build();
new DimensionStage().apply(context);
return context;
}
static Field height(PackCompileContext context) {
String noise = context.noises().register(new NoiseDef("test/height", 0, List.of(1.0)));
return new Field.Binary(Field.BinaryOp.ADD, new Field.Const(context.dimensionDef().fluidHeight()),
new Field.Binary(Field.BinaryOp.MUL, new Field.Const(30.0), new Field.Noise(noise, 1.0 / 300.0, 0.0, null, null, null)));
}
static Map<String, NoiseDef> noises(PackCompileContext context) {
Map<String, NoiseDef> noises = new HashMap<>();
for (NoiseDef definition : context.noises().definitions()) {
noises.put(context.namespace() + ":" + definition.id(), definition);
}
return noises;
}
static String biomeAt(BiomeCodes codes, Map<String, NoiseDef> noises, int x, int y, int z) {
double surface = FieldEvaluator.sample(codes.surfaceCode(), noises, WORLD_SEED, DataVersion.V26_3, x, y, z);
double humidity = FieldEvaluator.sample(codes.caveCode(), noises, WORLD_SEED, DataVersion.V26_3, x, y, z);
double depth = FieldEvaluator.sample(codes.class3d(), noises, WORLD_SEED, DataVersion.V26_3, x, y, z);
String best = null;
double bestFitness = Double.POSITIVE_INFINITY;
for (ClimateLayout.ClimateEntry entry : codes.layout().entries()) {
double fitness = switch (entry.axis()) {
case TEMPERATURE -> square(gap(surface, entry)) + square(humidity) + square(depth);
case HUMIDITY -> square(surface) + square(gap(humidity, entry)) + square(depth);
case DEPTH -> square(surface) + square(humidity) + square(gap(depth, entry));
};
if (fitness < bestFitness) {
bestFitness = fitness;
best = entry.biomeId();
}
}
return codes.loadKeyByBiomeId().get(best);
}
private static Map<String, Double> shares(PackCompileContext context, BiomeCodes codes) {
Map<String, NoiseDef> noises = noises(context);
Map<String, Double> shares = new TreeMap<>();
double weight = 1.0 / (GRID * GRID);
for (int x = 0; x < GRID; x++) {
for (int z = 0; z < GRID; z++) {
shares.merge(biomeAt(codes, noises, x * STRIDE, 100, z * STRIDE), weight, Double::sum);
}
}
return shares;
}
private static void collectEagerExpensive(Field field, List<String> violations) {
switch (field) {
case Field.Partition partition -> {
for (Field leaf : partition.leaves()) {
requireNotExpensive(leaf, "partition leaf", violations);
}
collectEagerExpensive(partition.input(), violations);
}
case Field.RangeIf rangeIf -> {
requireNotExpensive(rangeIf.inRange(), "range choice branch", violations);
requireNotExpensive(rangeIf.outOfRange(), "range choice branch", violations);
collectEagerExpensive(rangeIf.input(), violations);
}
case Field.Binary binary -> {
if (binary.op() == Field.BinaryOp.MUL) {
requireNotExpensive(binary.left(), "mul operand", violations);
requireNotExpensive(binary.right(), "mul operand", violations);
}
collectEagerExpensive(binary.left(), violations);
collectEagerExpensive(binary.right(), violations);
}
case Field.Lerp lerp -> {
requireNotExpensive(lerp.first(), "lerp branch", violations);
requireNotExpensive(lerp.second(), "lerp branch", violations);
collectEagerExpensive(lerp.alpha(), violations);
}
case Field.Mux mux -> {
collectEagerExpensive(mux.index(), violations);
for (Field selected : mux.cases()) {
collectEagerExpensive(selected, violations);
}
}
case Field.Gate gate -> {
collectEagerExpensive(gate.condition(), violations);
collectEagerExpensive(gate.expr(), violations);
}
case Field.Shared shared -> collectEagerExpensive(shared.expr(), violations);
case Field.Curve curve -> collectEagerExpensive(curve.input(), violations);
case Field.Unary unary -> collectEagerExpensive(unary.input(), violations);
case Field.Clamp clamp -> collectEagerExpensive(clamp.input(), violations);
case Field.Grid grid -> collectEagerExpensive(grid.expr(), violations);
default -> {
}
}
}
private static void requireNotExpensive(Field field, String role, List<String> violations) {
if (field.cost() == CostClass.EXPENSIVE) {
violations.add(role + " " + field.getClass().getSimpleName());
}
}
private static void collectShared(Field field, Map<String, Field.Shared> found, Set<Field> visited) {
if (!visited.add(field)) {
return;
}
if (field instanceof Field.Shared shared) {
found.put(shared.name(), shared);
}
for (Field child : FieldMacros.children(field)) {
collectShared(child, found, visited);
}
}
private static int references(Field field, Field target) {
if (field == target) {
return 1;
}
int count = 0;
for (Field child : FieldMacros.children(field)) {
count += references(child, target);
}
return count;
}
private static double gap(double value, ClimateLayout.ClimateEntry entry) {
return value < entry.min() ? entry.min() - value : value > entry.max() ? value - entry.max() : 0.0;
}
private static double square(double value) {
return value * value;
}
}
@@ -0,0 +1,203 @@
package art.arcane.iris.pack.datapack.export.compile.biome;
import art.arcane.iris.pack.datapack.DataVersion;
import art.arcane.iris.pack.datapack.export.ExportTestPacks;
import art.arcane.iris.pack.datapack.export.ExportTestStyles;
import art.arcane.iris.pack.datapack.export.compile.DimensionStage;
import art.arcane.iris.pack.datapack.export.compile.PackCompileContext;
import art.arcane.iris.pack.datapack.export.ir.BiomeDef;
import art.arcane.iris.pack.datapack.export.ir.ExportDiagnostic;
import art.arcane.iris.pack.datapack.export.ir.ExportLimit;
import art.arcane.iris.pack.datapack.export.ir.JsonResource;
import art.arcane.iris.pack.loading.IrisData;
import art.arcane.iris.spi.IrisPlatforms;
import art.arcane.iris.testsupport.CompatTestPlatform;
import art.arcane.iris.testsupport.FakeVanillaDataSource;
import art.arcane.iris.testsupport.PlatformLeakGuard;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import org.junit.ClassRule;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.TreeMap;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.mockito.Mockito.doReturn;
public class BiomeDefinitionCompilerTest {
private static final List<String> LEGACY_KEYS = List.of("surface_builder", "depth", "scale", "precipitation", "category", "starts");
private static final String MEADOW = "iris_export:meadow";
private static final String PLAINS_JSON = """
{"has_precipitation": true, "temperature": 0.8, "downfall": 0.4,
"effects": {"water_color": "#3f76e4", "grass_color": "#91bd59"},
"attributes": {
"minecraft:audio/background_music": {"default": {"sound": "minecraft:music.overworld.plains"}},
"minecraft:gameplay/natural_mob_spawns": {"argument": {"spawn_costs": {},
"spawns_by_category": {"creature": [{"type": "minecraft:sheep", "count": 4, "weight": 12}]}}, "modifier": "overlay"}},
"carvers": ["minecraft:cave"],
"features": [["minecraft:lake_lava_underground"]]}
""";
@ClassRule
public static final PlatformLeakGuard PLATFORM_GUARD = PlatformLeakGuard.clean();
@Rule
public TemporaryFolder temporaryFolder = new TemporaryFolder();
@Rule
public ExportTestPacks.BoundPlatform platform = new ExportTestPacks.BoundPlatform();
@Test
public void derivativeSpawnsBakedIntoBiome() throws Exception {
IrisData data = IrisData.openRuntime(pack());
try {
PackCompileContext context = context(data, DataVersion.V26_3);
FakeVanillaDataSource vanilla = FakeVanillaDataSource.of(Map.of(
"data/minecraft/worldgen/biome/plains.json", PLAINS_JSON,
"data/minecraft/tags/worldgen/biome/has_structure/village_plains.json", "{\"values\": [\"minecraft:plains\", \"minecraft:meadow\"]}",
"data/minecraft/tags/worldgen/biome/is_overworld.json", "{\"values\": [{\"id\": \"minecraft:plains\", \"required\": false}, \"#minecraft:is_forest\"]}"));
BiomeDefinitionCompiler.Definitions definitions = new BiomeDefinitionCompiler(Optional.of(vanilla))
.compile(context, Map.of(MEADOW, "meadow"));
JsonObject biome = only(definitions.biomes()).json();
JsonObject attributes = biome.getAsJsonObject("attributes");
JsonArray creatures = attributes.getAsJsonObject("minecraft:gameplay/natural_mob_spawns")
.getAsJsonObject("argument").getAsJsonObject("spawns_by_category").getAsJsonArray("creature");
assertEquals(List.of("minecraft:sheep", "minecraft:fox"), types(creatures));
assertEquals(JsonParser.parseString("{\"type\": \"minecraft:uniform\", \"min_inclusive\": 1, \"max_inclusive\": 2}"), creatures.get(1).getAsJsonObject().get("count"));
assertTrue(attributes.has("minecraft:audio/background_music"));
assertFalse(attributes.has("minecraft:gameplay/creature_world_gen_spawn_probability"));
assertEquals("#112233", attributes.get("minecraft:visual/sky_color").getAsString());
assertEquals("#445566", biome.getAsJsonObject("effects").get("grass_color").getAsString());
assertEquals("#3f76e4", biome.getAsJsonObject("effects").get("water_color").getAsString());
assertEquals(0.3, biome.get("temperature").getAsDouble(), 1.0e-9);
assertEquals(new JsonArray(), biome.get("carvers"));
assertEquals(new JsonArray(), biome.get("features"));
assertNoLegacyKeys(biome);
Map<String, JsonElement> tags = tags(definitions);
assertEquals(List.of("data/minecraft/tags/worldgen/biome/has_structure/village_plains.json",
"data/minecraft/tags/worldgen/biome/is_forest.json",
"data/minecraft/tags/worldgen/biome/is_overworld.json"), List.copyOf(tags.keySet()));
assertEquals(JsonParser.parseString("{\"replace\": false, \"values\": [\"" + MEADOW + "\"]}"),
tags.get("data/minecraft/tags/worldgen/biome/has_structure/village_plains.json"));
assertTrue(context.diagnostics().isEmpty());
} finally {
data.close();
}
}
@Test
public void withoutVanillaDataBiomesComeFromIrisFields() throws Exception {
IrisData data = IrisData.openRuntime(pack());
try {
DataVersion target = DataVersion.V26_3;
PackCompileContext context = context(data, target);
BiomeDefinitionCompiler.Definitions definitions = BiomeDefinitionCompiler.forTarget(target)
.compile(context, Map.of(MEADOW, "meadow", "iris_export:deep", "deep"));
for (BiomeDef biome : definitions.biomes()) {
assertNoLegacyKeys(biome.json());
assertTrue(biome.json().toString(), biome.json().has("effects"));
assertTrue(biome.json().toString(), biome.json().has("temperature"));
assertEquals(new JsonArray(), biome.json().get("carvers"));
}
assertFalse(definitions.biomes().getLast().json().has("spawners"));
assertTrue(tags(definitions).containsKey("data/minecraft/tags/worldgen/biome/is_overworld.json"));
assertTrue(tags(definitions).containsKey("data/minecraft/tags/worldgen/biome/is_forest.json"));
assertEquals(List.of(ExportLimit.VANILLA_BIOME_DATA, ExportLimit.BIOME_VARIANT), limits(context.diagnostics()));
} finally {
data.close();
}
}
@Test
public void runningVersionSuppliesVanillaData() throws Exception {
IrisData data = IrisData.openRuntime(pack());
try {
doReturn("26.3").when(IrisPlatforms.get()).minecraftVersion();
doReturn(FakeVanillaDataSource.of(Map.of("data/minecraft/worldgen/biome/plains.json", PLAINS_JSON))).when(IrisPlatforms.get()).vanillaData();
PackCompileContext current = context(data, DataVersion.V26_3);
PackCompileContext older = context(data, DataVersion.V26_3);
JsonObject biome = only(BiomeDefinitionCompiler.forTarget(DataVersion.V26_3).compile(current, Map.of(MEADOW, "meadow")).biomes()).json();
doReturn("26.2").when(IrisPlatforms.get()).minecraftVersion();
BiomeDefinitionCompiler.forTarget(DataVersion.V26_3).compile(older, Map.of(MEADOW, "meadow"));
assertTrue(biome.getAsJsonObject("attributes").has("minecraft:audio/background_music"));
assertTrue(current.diagnostics().isEmpty());
assertEquals(List.of(ExportLimit.VANILLA_BIOME_DATA), limits(older.diagnostics()));
} finally {
data.close();
}
}
private File pack() throws Exception {
File pack = temporaryFolder.newFolder("pack");
CompatTestPlatform.write(pack, "dimensions/" + ExportTestPacks.DIMENSION + ".json", "{\"regions\": [\"region\"]}");
CompatTestPlatform.write(pack, "regions/region.json", "{\"landBiomes\": [\"meadow\"], \"seaBiomes\": [\"deep\"]}");
CompatTestPlatform.write(pack, "biomes/meadow.json", """
{"name": "Meadow", "derivative": "minecraft:plains",
"customDerivitives": [{"id": "meadow", "temperature": 0.3, "skyColor": "#112233", "grassColor": "#445566",
"tags": ["#minecraft:is_forest"],
"spawns": [{"type": "minecraft:fox", "weight": 3, "minCount": 1, "maxCount": 2, "group": "CREATURE"}]}]}
""");
CompatTestPlatform.write(pack, "biomes/deep.json", """
{"name": "Deep", "derivative": "minecraft:deep_ocean", "biomeScatter": ["minecraft:deep_ocean", "minecraft:ocean"]}
""");
return pack;
}
private static PackCompileContext context(IrisData data, DataVersion target) {
PackCompileContext context = ExportTestPacks.contextBuilder(data, target).styles(new ExportTestStyles()).build();
new DimensionStage().apply(context);
return context;
}
private static BiomeDef only(List<BiomeDef> biomes) {
assertEquals(1, biomes.size());
return biomes.getFirst();
}
private static List<String> types(JsonArray spawns) {
List<String> types = new ArrayList<>();
for (JsonElement spawn : spawns) {
types.add(spawn.getAsJsonObject().get("type").getAsString());
}
return types;
}
private static Map<String, JsonElement> tags(BiomeDefinitionCompiler.Definitions definitions) {
Map<String, JsonElement> tags = new TreeMap<>();
for (JsonResource resource : definitions.tags()) {
tags.put(resource.path(), resource.json());
}
return tags;
}
private static List<ExportLimit> limits(List<ExportDiagnostic> diagnostics) {
List<ExportLimit> limits = new ArrayList<>();
for (ExportDiagnostic diagnostic : diagnostics) {
limits.add(diagnostic.limit());
}
return limits;
}
private static void assertNoLegacyKeys(JsonObject biome) {
for (String key : LEGACY_KEYS) {
assertFalse(key + " in " + biome, biome.has(key));
}
}
}
@@ -0,0 +1,68 @@
package art.arcane.iris.pack.datapack.export.compile.biome;
import art.arcane.iris.pack.datapack.export.VanillaResourceIdentifier;
import org.junit.Test;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertThrows;
import static org.junit.Assert.assertTrue;
public class BiomeIdSanitizerTest {
private static final List<String> KEYS = List.of(
"Forest",
"forest",
"forest_2",
"FOREST",
"caves/Dark Cave",
"Caves/dark cave",
"ocean\\deep",
"Odd Name!");
@Test
public void collidingKeysGetStableSuffixes() {
List<String> first = sanitizeAll(KEYS);
assertEquals(List.of(
"iris_export:forest",
"iris_export:forest_2",
"iris_export:forest_2_2",
"iris_export:forest_3",
"iris_export:caves/dark_cave",
"iris_export:caves/dark_cave_2",
"iris_export:ocean/deep",
"iris_export:odd_name_"), first);
assertEquals(first, sanitizeAll(KEYS));
assertEquals(KEYS.size(), new HashSet<>(first).size());
for (String id : first) {
assertTrue(id, VanillaResourceIdentifier.validIdentifier(id));
}
}
@Test
public void sanitizedIdIsClaimedInTheTakenSet() {
Set<String> taken = new HashSet<>();
String id = BiomeIdSanitizer.sanitize("iris_export", "Plains", taken);
assertEquals("iris_export:plains", id);
assertTrue(taken.contains(id));
}
@Test
public void invalidNamespaceIsRejected() {
assertThrows(IllegalArgumentException.class, () -> BiomeIdSanitizer.sanitize("Iris Export", "plains", new HashSet<>()));
}
private static List<String> sanitizeAll(List<String> keys) {
Set<String> taken = new HashSet<>();
List<String> ids = new ArrayList<>(keys.size());
for (String key : keys) {
ids.add(BiomeIdSanitizer.sanitize("iris_export", key, taken));
}
return ids;
}
}
@@ -0,0 +1,170 @@
package art.arcane.iris.pack.datapack.export.compile.biome;
import art.arcane.iris.generation.terrain.IrisDimension;
import art.arcane.iris.pack.datapack.DataVersion;
import art.arcane.iris.pack.datapack.export.ExportTestPacks;
import art.arcane.iris.pack.datapack.export.ExportTestStyles;
import art.arcane.iris.pack.datapack.export.compile.DimensionStage;
import art.arcane.iris.pack.datapack.export.compile.PackCompileContext;
import art.arcane.iris.pack.datapack.export.ir.ClimateLayout;
import art.arcane.iris.pack.datapack.export.ir.Field;
import art.arcane.iris.pack.datapack.export.ir.FieldEvaluator;
import art.arcane.iris.pack.datapack.export.ir.NoiseDef;
import art.arcane.iris.pack.datapack.export.lower.ExportCapabilities;
import art.arcane.iris.pack.loading.IrisData;
import art.arcane.iris.testsupport.CompatTestPlatform;
import art.arcane.iris.testsupport.PlatformLeakGuard;
import org.junit.Assume;
import org.junit.ClassRule;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import java.io.File;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.TreeMap;
import java.util.TreeSet;
import static org.junit.Assert.assertTrue;
public class BiomeShareTest {
private static final String PROBE_PACK_PROPERTY = "iris.exportProbePack";
private static final String PROBE_DIMENSION = "overworld";
private static final int SAMPLES_PER_AXIS = 1024;
private static final double SHARE_TOLERANCE = 0.05;
private static final long WORLD_SEED = 424_242L;
private static final long IRIS_SEED = 9_876_543L;
private static final int REPORTED_BIOMES = 20;
@ClassRule
public static final PlatformLeakGuard PLATFORM_GUARD = PlatformLeakGuard.clean();
@Rule
public TemporaryFolder temporaryFolder = new TemporaryFolder();
@Rule
public ExportTestPacks.BoundPlatform platform = new ExportTestPacks.BoundPlatform();
@Test
public void biomeShareMatchesIrisWithin0_05() throws Exception {
File pack = SelectionTestPacks.threeRegions(temporaryFolder.newFolder("pack"));
IrisData data = IrisData.openRuntime(pack);
try {
PackCompileContext context = BiomeDecisionCompilerTest.context(data);
Comparison comparison = compare(context, context.dimension(), data, 8);
assertTrue(comparison.report(), comparison.maximumDelta() <= SHARE_TOLERANCE);
assertTrue(comparison.report(), comparison.iris().size() >= 12);
} finally {
data.close();
}
}
@Test
public void overworldBiomeShareMatchesIrisWithin0_05() throws Exception {
String probePack = System.getProperty(PROBE_PACK_PROPERTY);
Assume.assumeTrue("Set -P" + PROBE_PACK_PROPERTY + " to run against a real pack", probePack != null && !probePack.isBlank());
CompatTestPlatform unrestricted = CompatTestPlatform.bind(temporaryFolder.newFolder("platform"), List.of());
try {
IrisData data = IrisData.openRuntime(new File(probePack));
try {
IrisDimension dimension = data.getDimensionLoader().load(PROBE_DIMENSION, false);
PackCompileContext context = PackCompileContext.builder()
.data(data)
.dimension(dimension)
.capabilities(ExportCapabilities.forTarget(DataVersion.V26_3))
.namespace("iris_export")
.styles(new ExportTestStyles())
.build();
new DimensionStage().apply(context);
Comparison comparison = compare(context, dimension, data, 48);
System.out.println(comparison.report());
assertTrue(comparison.report(), comparison.maximumDelta() <= SHARE_TOLERANCE);
} finally {
data.close();
}
} finally {
unrestricted.unbind();
}
}
private static Comparison compare(PackCompileContext context, IrisDimension dimension, IrisData data, int stride) {
BiomeDecision decision = new BiomeDecisionCompiler(context.styles()).compile(context);
Field height = BiomeDecisionCompilerTest.height(context);
BiomeCodes codes = decision.bind(height);
Map<String, NoiseDef> noises = BiomeDecisionCompilerTest.noises(context);
IrisSelectionReference iris = new IrisSelectionReference(dimension, data, IRIS_SEED);
double fluid = context.dimensionDef().fluidHeight();
List<ClimateLayout.ClimateEntry> surface = new ArrayList<>();
for (ClimateLayout.ClimateEntry entry : codes.layout().entries()) {
if (entry.axis() == ClimateLayout.ClimateAxis.TEMPERATURE) {
surface.add(entry);
}
}
surface.sort(Comparator.comparingDouble(ClimateLayout.ClimateEntry::min));
Map<String, Double> irisShares = new TreeMap<>();
Map<String, Double> exportShares = new TreeMap<>();
double weight = 1.0 / ((double) SAMPLES_PER_AXIS * SAMPLES_PER_AXIS);
int origin = -SAMPLES_PER_AXIS / 2 * stride;
for (int column = 0; column < SAMPLES_PER_AXIS; column++) {
int x = origin + column * stride;
for (int row = 0; row < SAMPLES_PER_AXIS; row++) {
int z = origin + row * stride;
double terrain = FieldEvaluator.sample(height, noises, WORLD_SEED, DataVersion.V26_3, x, 0, z);
irisShares.merge(iris.surfaceBiome(x, z, terrain, fluid), weight, Double::sum);
double code = FieldEvaluator.sample(codes.surfaceCode(), noises, WORLD_SEED, DataVersion.V26_3, x, 0, z);
exportShares.merge(codes.loadKeyByBiomeId().get(entryAt(surface, code).biomeId()), weight, Double::sum);
}
}
return new Comparison(irisShares, exportShares);
}
private static ClimateLayout.ClimateEntry entryAt(List<ClimateLayout.ClimateEntry> sorted, double code) {
int low = 0;
int high = sorted.size() - 1;
while (low < high) {
int middle = (low + high + 1) >>> 1;
if (sorted.get(middle).min() <= code) {
low = middle;
} else {
high = middle - 1;
}
}
return sorted.get(low);
}
private record Comparison(Map<String, Double> iris, Map<String, Double> export) {
double maximumDelta() {
double maximum = 0.0;
for (String biome : biomes()) {
maximum = Math.max(maximum, delta(biome));
}
return maximum;
}
String report() {
List<String> biomes = new ArrayList<>(biomes());
biomes.sort(Comparator.comparingDouble((String biome) -> -iris.getOrDefault(biome, 0.0)));
StringBuilder report = new StringBuilder(String.format(Locale.ROOT, "biomes=%d maxDelta=%.4f%n", biomes.size(), maximumDelta()));
for (String biome : biomes.subList(0, Math.min(REPORTED_BIOMES, biomes.size()))) {
report.append(String.format(Locale.ROOT, " %-40s iris=%.4f export=%.4f%n", biome, iris.getOrDefault(biome, 0.0), export.getOrDefault(biome, 0.0)));
}
return report.toString();
}
private TreeSet<String> biomes() {
TreeSet<String> biomes = new TreeSet<>(iris.keySet());
biomes.addAll(export.keySet());
return biomes;
}
private double delta(String biome) {
return Math.abs(iris.getOrDefault(biome, 0.0) - export.getOrDefault(biome, 0.0));
}
}
}
@@ -0,0 +1,146 @@
package art.arcane.iris.pack.datapack.export.compile.biome;
import art.arcane.iris.pack.datapack.export.ExportTestPacks;
import art.arcane.iris.pack.datapack.export.compile.PackCompileContext;
import art.arcane.iris.pack.datapack.export.ir.Axis;
import art.arcane.iris.pack.datapack.export.ir.BiomeDef;
import art.arcane.iris.pack.datapack.export.ir.Field;
import art.arcane.iris.pack.datapack.export.ir.JsonResource;
import art.arcane.iris.pack.datapack.export.ir.NoiseDef;
import art.arcane.iris.pack.loading.IrisData;
import art.arcane.iris.testsupport.PlatformLeakGuard;
import org.junit.ClassRule;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeSet;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotEquals;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertTrue;
public class BiomeStageTest {
@ClassRule
public static final PlatformLeakGuard PLATFORM_GUARD = PlatformLeakGuard.clean();
@Rule
public TemporaryFolder temporaryFolder = new TemporaryFolder();
@Rule
public ExportTestPacks.BoundPlatform platform = new ExportTestPacks.BoundPlatform();
@Test
public void stageFillsCodesBiomesAndTags() throws Exception {
File pack = SelectionTestPacks.threeRegions(temporaryFolder.newFolder("pack"));
IrisData data = IrisData.openRuntime(pack);
try {
PackCompileContext context = BiomeDecisionCompilerTest.context(data);
new BiomeStage().apply(context);
BiomeCodes codes = context.biomeCodes();
Set<String> defined = new TreeSet<>();
for (BiomeDef biome : context.biomes()) {
defined.add(context.namespace() + ":" + biome.id());
}
assertEquals(codes.loadKeyByBiomeId().keySet(), defined);
assertEquals(18, defined.size());
List<String> tagPaths = new ArrayList<>();
for (JsonResource resource : context.jsonResources()) {
tagPaths.add(resource.path());
}
assertTrue(tagPaths.toString(), tagPaths.contains("data/minecraft/tags/worldgen/biome/is_overworld.json"));
assertEquals(new Field.Const(0.0), codes.class3d());
} finally {
data.close();
}
}
@Test
public void codesBindToTheHeightOnceItIsSet() throws Exception {
File pack = SelectionTestPacks.threeRegions(temporaryFolder.newFolder("pack"));
IrisData data = IrisData.openRuntime(pack);
try {
PackCompileContext context = BiomeDecisionCompilerTest.context(data);
new BiomeStage().apply(context);
BiomeCodes base = context.biomeCodes();
Field height = BiomeDecisionCompilerTest.height(context);
context.setHeight(height);
BiomeCodes bound = context.biomeCodes();
assertNotEquals(base.surfaceCode(), bound.surfaceCode());
assertSame(bound, context.biomeCodes());
assertEquals(base.caveCode(), bound.caveCode());
assertEquals(base.layout(), bound.layout());
assertTrue(bound.class3d().axes().contains(Axis.Y));
assertFalse(bound.surfaceCode().axes().contains(Axis.Y));
} finally {
data.close();
}
}
@Test
public void climateHeightDecidesTheBiomesUntilTheHeightIsReplaced() throws Exception {
File pack = SelectionTestPacks.childChain(temporaryFolder.newFolder("pack"));
IrisData data = IrisData.openRuntime(pack);
try {
PackCompileContext context = BiomeDecisionCompilerTest.context(data);
new BiomeStage().apply(context);
int seaLevel = context.dimensionDef().fluidHeight();
Field natural = new Field.Const(seaLevel + 40.0);
Field climate = new Field.Const(seaLevel - 20.0);
Map<String, NoiseDef> noises = BiomeDecisionCompilerTest.noises(context);
int seaFloor = seaLevel - 20;
context.setHeight(natural);
context.setClimateHeight(climate);
assertSame(climate, context.climateHeight());
assertSame(natural, context.height());
assertEquals("sea", BiomeDecisionCompilerTest.biomeAt(context.biomeCodes(), noises, 0, seaFloor, 0));
context.setCarvedHeight(new Field.Const(seaLevel - 30.0));
assertEquals("sea", BiomeDecisionCompilerTest.biomeAt(context.biomeCodes(), noises, 0, seaFloor, 0));
context.setHeight(natural);
assertSame(natural, context.climateHeight());
assertNotEquals("sea", BiomeDecisionCompilerTest.biomeAt(context.biomeCodes(), noises, 0, seaFloor, 0));
} finally {
data.close();
}
}
@Test
public void carvedHeightKeepsTheBiomesOfTheNaturalHeight() throws Exception {
File pack = SelectionTestPacks.childChain(temporaryFolder.newFolder("pack"));
IrisData data = IrisData.openRuntime(pack);
try {
PackCompileContext context = BiomeDecisionCompilerTest.context(data);
new BiomeStage().apply(context);
int seaLevel = context.dimensionDef().fluidHeight();
Field natural = new Field.Const(seaLevel + 40.0);
Field carved = new Field.Const(seaLevel - 20.0);
context.setHeight(natural);
BiomeCodes land = context.biomeCodes();
context.setCarvedHeight(carved);
assertSame(carved, context.height());
assertSame(natural, context.naturalHeight());
assertSame(land, context.biomeCodes());
Map<String, NoiseDef> noises = BiomeDecisionCompilerTest.noises(context);
int riverBed = seaLevel - 20;
assertNotEquals("sea", BiomeDecisionCompilerTest.biomeAt(context.biomeCodes(), noises, 0, riverBed, 0));
context.setHeight(carved);
assertEquals("sea", BiomeDecisionCompilerTest.biomeAt(context.biomeCodes(), noises, 0, riverBed, 0));
} finally {
data.close();
}
}
}
@@ -0,0 +1,136 @@
package art.arcane.iris.pack.datapack.export.compile.biome;
import art.arcane.iris.generation.biome.IrisBiome;
import art.arcane.iris.generation.stream.RarityStream;
import art.arcane.iris.generation.terrain.ContinentGenerator;
import art.arcane.iris.generation.terrain.InferredType;
import art.arcane.iris.generation.terrain.IrisDimension;
import art.arcane.iris.generation.terrain.IrisRegion;
import art.arcane.iris.pack.loading.IrisData;
import art.arcane.iris.pack.value.IrisRaritySelection;
import art.arcane.volmlib.util.collection.KList;
import art.arcane.volmlib.util.math.RNG;
import art.arcane.volmlib.util.noise.CNG;
import java.util.ArrayList;
import java.util.EnumMap;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
final class IrisSelectionReference {
private static final int MAX_IMPLODE = 3;
private final IrisData data;
private final double landChance;
private final RarityStream<IrisRegion> regions;
private final CNG continent;
private final Map<IrisRegion, Map<InferredType, RarityStream<IrisBiome>>> picks = new HashMap<>();
private final Map<String, IrisRaritySelection<IrisBiome>> plans = new HashMap<>();
private final long childStyleSeed;
IrisSelectionReference(IrisDimension dimension, IrisData data, long seed) {
this.data = data;
RNG rng = new RNG(seed);
childStyleSeed = IrisBiome.childStyleSeed(rng, 123);
landChance = dimension.getLandChance();
KList<IrisRegion> loaded = new KList<>();
for (IrisRegion region : data.getRegionLoader().loadAll(dimension.getRegions())) {
if (!region.isCompatExcluded()) {
loaded.add(region);
}
}
regions = new RarityStream<>(dimension.getRegionStyle().create(rng.nextParallelRNG(883), data).stream().zoom(dimension.getRegionZoom()), loaded);
continent = ContinentGenerator.create(dimension, rng, data);
for (IrisRegion region : loaded) {
Map<InferredType, RarityStream<IrisBiome>> streams = new EnumMap<>(InferredType.class);
streams.put(InferredType.LAND, new RarityStream<>(dimension.getLandBiomeStyle().create(rng.nextParallelRNG(InferredType.LAND.ordinal()), data).stream()
.zoom(dimension.getBiomeZoom()).zoom(dimension.getLandZoom()).zoom(region.getLandBiomeZoom()), pool(region.getLandBiomes())));
streams.put(InferredType.SEA, new RarityStream<>(dimension.getSeaBiomeStyle().create(rng.nextParallelRNG(InferredType.SEA.ordinal()), data).stream()
.zoom(dimension.getBiomeZoom()).zoom(dimension.getSeaZoom()).zoom(region.getSeaBiomeZoom()), pool(region.getSeaBiomes())));
streams.put(InferredType.SHORE, new RarityStream<>(dimension.getShoreBiomeStyle().create(rng.nextParallelRNG(InferredType.SHORE.ordinal()), data).stream()
.zoom(dimension.getBiomeZoom()).zoom(region.getShoreBiomeZoom()), pool(region.getShoreBiomes())));
picks.put(region, streams);
}
}
String surfaceBiome(double x, double z, double height, double fluid) {
IrisRegion region = regions.get(x, z);
boolean landBase = continent.noise(x, z) < landChance;
IrisBiome base = implode(pick(region, landBase ? InferredType.LAND : InferredType.SEA, x, z), x, z, MAX_IMPLODE);
InferredType relabel = relabel(height, fluid + region.getShoreHeight(x, z), fluid, landBase);
if (relabel == null) {
return base.getLoadKey();
}
return implode(pick(region, relabel, x, z), x, z, MAX_IMPLODE).getLoadKey();
}
private IrisBiome pick(IrisRegion region, InferredType type, double x, double z) {
IrisBiome picked = picks.get(region).get(type).get(x, z);
if (picked != null) {
return picked;
}
return switch (type) {
case LAND -> picks.get(region).get(InferredType.SEA).get(x, z);
case SEA -> picks.get(region).get(InferredType.LAND).get(x, z);
default -> pick(region, continent.noise(x, z) < landChance ? InferredType.LAND : InferredType.SEA, x, z);
};
}
private IrisBiome implode(IrisBiome biome, double x, double z, int remaining) {
if (remaining < 0 || biome.getChildren().isEmpty()) {
return biome;
}
IrisRaritySelection<IrisBiome> selection = plans.computeIfAbsent(biome.getLoadKey(), ignored -> plan(biome));
long maximum = selection.size() - 1L;
IrisBiome selected = maximum <= 0L
? selection.get(0L)
: selection.get(biome.getChildrenGenerator(childStyleSeed, biome.getChildShrinkFactor()).fit2D(0, (int) maximum, x, z));
if (selected.getLoadKey().equals(biome.getLoadKey())) {
return biome;
}
return implode(selected, x, z, remaining - 1);
}
private IrisRaritySelection<IrisBiome> plan(IrisBiome biome) {
KList<IrisBiome> options = new KList<>();
for (IrisBiome child : biome.getRealChildren(() -> data)) {
if (child != null) {
options.add(child);
}
}
options.add(biome);
return IrisRaritySelection.create(options);
}
private List<IrisBiome> pool(KList<String> keys) {
List<IrisBiome> pool = new ArrayList<>();
for (IrisBiome biome : data.getBiomeLoader().loadAll(keys)) {
if (!biome.isCompatExcluded()) {
pool.add(biome);
}
}
return pool;
}
private static InferredType relabel(double height, double bandTop, double fluid, boolean landBase) {
boolean above = height > bandTop;
if (height >= fluid - 1) {
if (!above) {
return InferredType.SHORE;
}
if (!landBase) {
return InferredType.LAND;
}
} else if (!landBase && above) {
return InferredType.LAND;
}
if (height < fluid && landBase) {
return InferredType.SEA;
}
if (height == fluid) {
return InferredType.SHORE;
}
return null;
}
}
@@ -0,0 +1,109 @@
package art.arcane.iris.pack.datapack.export.compile.biome;
import art.arcane.iris.pack.datapack.export.ExportTestPacks;
import art.arcane.iris.testsupport.CompatTestPlatform;
import java.io.File;
import java.io.IOException;
import java.util.Map;
final class SelectionTestPacks {
private static final String STYLES = """
"regionStyle": {"style": "SIMPLEX"},
"continentalStyle": {"style": "SIMPLEX"},
"landBiomeStyle": {"style": "SIMPLEX"},
"seaBiomeStyle": {"style": "SIMPLEX"},
"shoreBiomeStyle": {"style": "SIMPLEX"},
"caveBiomeStyle": {"style": "SIMPLEX", "fracture": {"style": "SIMPLEX", "multiplier": 20}}
""";
private SelectionTestPacks() {
}
static File threeRegions(File pack) throws IOException {
dimension(pack, """
"regions": ["cold", "warm", "temperate"],
"regionZoom": 4,
"continentZoom": 3,
"landChance": 0.6,
"carving": [{"id": "deep", "biome": "deep_dark", "worldYRange": {"min": -60, "max": -40}}]
""");
CompatTestPlatform.write(pack, "regions/cold.json", """
{"landBiomes": ["tundra", "taiga"], "seaBiomes": ["frozen_ocean"], "shoreBiomes": ["snowy_beach"], "caveBiomes": ["ice_cave"]}
""");
CompatTestPlatform.write(pack, "regions/warm.json", """
{"rarity": 2, "landBiomeZoom": 2, "landBiomes": ["desert", "savanna", "mesa"], "seaBiomes": ["warm_ocean"],
"shoreBiomes": ["beach"], "shoreHeightMin": 2, "shoreHeightMax": 6}
""");
CompatTestPlatform.write(pack, "regions/temperate.json", """
{"landBiomes": ["plains", "forest"], "seaBiomes": ["ocean", "deep_ocean"], "shoreBiomes": ["beach"],
"caveBiomes": ["lush_cave", "dripstone_cave"]}
""");
biomes(pack, Map.ofEntries(
Map.entry("tundra", "\"derivative\": \"minecraft:snowy_plains\""),
Map.entry("taiga", "\"derivative\": \"minecraft:taiga\", \"rarity\": 2"),
Map.entry("frozen_ocean", "\"derivative\": \"minecraft:frozen_ocean\""),
Map.entry("snowy_beach", "\"derivative\": \"minecraft:snowy_beach\""),
Map.entry("ice_cave", "\"derivative\": \"minecraft:frozen_peaks\", \"caveMinDepthBelowSurface\": 20"),
Map.entry("desert", "\"derivative\": \"minecraft:desert\""),
Map.entry("savanna", "\"derivative\": \"minecraft:savanna\""),
Map.entry("mesa", "\"derivative\": \"minecraft:badlands\", \"rarity\": 3"),
Map.entry("warm_ocean", "\"derivative\": \"minecraft:warm_ocean\""),
Map.entry("beach", "\"derivative\": \"minecraft:beach\""),
Map.entry("plains", "\"derivative\": \"minecraft:plains\""),
Map.entry("forest", "\"derivative\": \"minecraft:forest\", \"children\": [\"birch_forest\"], \"childShrinkFactor\": 2"),
Map.entry("birch_forest", "\"derivative\": \"minecraft:birch_forest\""),
Map.entry("ocean", "\"derivative\": \"minecraft:ocean\""),
Map.entry("deep_ocean", "\"derivative\": \"minecraft:deep_ocean\", \"rarity\": 2"),
Map.entry("lush_cave", "\"derivative\": \"minecraft:lush_caves\""),
Map.entry("dripstone_cave", "\"derivative\": \"minecraft:dripstone_caves\", \"rarity\": 2"),
Map.entry("deep_dark", "\"derivative\": \"minecraft:deep_dark\"")));
return pack;
}
static File childChain(File pack) throws IOException {
dimension(pack, """
"regions": ["chain"],
"landChance": 1.5
""");
CompatTestPlatform.write(pack, "regions/chain.json", """
{"landBiomes": ["a"], "seaBiomes": ["sea"], "shoreBiomes": ["sea"]}
""");
biomes(pack, Map.of(
"a", "\"children\": [\"b\"], \"childStyle\": {\"style\": \"SIMPLEX\"}",
"b", "\"children\": [\"c\"], \"childStyle\": {\"style\": \"SIMPLEX\"}",
"c", "\"children\": [\"d\"], \"childStyle\": {\"style\": \"SIMPLEX\"}",
"d", "\"children\": [\"e\"], \"childStyle\": {\"style\": \"SIMPLEX\"}",
"e", "\"children\": [\"f\"], \"childStyle\": {\"style\": \"SIMPLEX\"}",
"f", "\"derivative\": \"minecraft:plains\"",
"sea", "\"derivative\": \"minecraft:ocean\""));
return pack;
}
static File childChainBesideStillBiome(File pack) throws IOException {
dimension(pack, """
"regions": ["chain"],
"landChance": 1.5
""");
CompatTestPlatform.write(pack, "regions/chain.json", """
{"landBiomes": ["a", "still"], "seaBiomes": ["sea"], "shoreBiomes": ["sea"]}
""");
biomes(pack, Map.of(
"a", "\"children\": [\"b\"], \"childStyle\": {\"style\": \"SIMPLEX\"}",
"b", "\"children\": [\"c\"], \"childStyle\": {\"style\": \"SIMPLEX\"}",
"c", "\"derivative\": \"minecraft:plains\"",
"still", "\"derivative\": \"minecraft:forest\"",
"sea", "\"derivative\": \"minecraft:ocean\""));
return pack;
}
private static void dimension(File pack, String body) throws IOException {
CompatTestPlatform.write(pack, "dimensions/" + ExportTestPacks.DIMENSION + ".json", "{" + STYLES + "," + body + "}");
}
private static void biomes(File pack, Map<String, String> bodies) throws IOException {
for (Map.Entry<String, String> biome : bodies.entrySet()) {
CompatTestPlatform.write(pack, "biomes/" + biome.getKey() + ".json", "{\"name\": \"" + biome.getKey() + "\", " + biome.getValue() + "}");
}
}
}
@@ -0,0 +1,208 @@
package art.arcane.iris.pack.datapack.export.compile.cave;
import art.arcane.iris.generation.cave.IrisCaveProfile;
import art.arcane.iris.pack.datapack.export.ExportTestPacks;
import art.arcane.iris.pack.datapack.export.compile.PackCompileContext;
import art.arcane.iris.pack.datapack.export.ir.AquiferDef;
import art.arcane.iris.pack.datapack.export.ir.Axis;
import art.arcane.iris.pack.datapack.export.ir.ExportDiagnostic;
import art.arcane.iris.pack.datapack.export.ir.ExportLimit;
import art.arcane.iris.pack.datapack.export.ir.Field;
import art.arcane.iris.pack.loading.IrisData;
import art.arcane.iris.testsupport.PlatformLeakGuard;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import org.junit.ClassRule;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import java.io.File;
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.assertTrue;
public class AquiferCompilerTest {
private static final Field SURFACE = new Field.Const(120.0);
private static final Field SEA_FLOOR_SLOPE = new Field.Coord(Axis.X, Field.Tiling.CLAMP, -1000, 1000, -100.0, 300.0);
private static final Field HIGH_ESTIMATE = new Field.Const(120.0);
private static final int SEA_X = -275;
private static final int LAND_X = 400;
private static final int DEEP_SEA_X = -800;
private static final int SHORE_X = -165;
private static final int HILL_X = -125;
private static final int SEA_FLOOR = 45;
private static final int FLUID_HEIGHT = 63;
private static final double FULLY_FLOODED = 0.8;
private static final double DRY = -1.0;
private static final double PARTIAL = 0.6;
private static final int FLUID_BAND_HEIGHT = 40;
private static final int FLUID_BAND_CENTER = 20;
@ClassRule
public static final PlatformLeakGuard PLATFORM_GUARD = PlatformLeakGuard.clean();
@Rule
public TemporaryFolder temporaryFolder = new TemporaryFolder();
@Rule
public ExportTestPacks.BoundPlatform platform = new ExportTestPacks.BoundPlatform();
@Test
public void dryProfilesHaveNegativeFloodedness() throws Exception {
PackCompileContext context = compile(CaveTestPacks.dimension(20), CaveTestPacks.constantProfile(-0.1));
AquiferDef aquifer = context.aquifer();
AquiferDef vanilla = AquiferDef.dry(SURFACE);
assertEquals(vanilla.barrier(), aquifer.barrier());
assertEquals(vanilla.spread(), aquifer.spread());
assertEquals(vanilla.lava(), aquifer.lava());
assertEquals(vanilla.exclusion(), aquifer.exclusion());
assertEquals(vanilla.surfaceLevel(), aquifer.surfaceLevel());
for (int y = CaveTestPacks.MIN_Y; y < CaveTestPacks.MAX_Y; y += 8) {
assertEquals(DRY, CaveTestPacks.sample(aquifer.floodedness(), context.noises(), 17, y, -9), 0.0);
}
}
@Test
public void openWaterAboveTheTerrainFloodsToSeaLevel() throws Exception {
PackCompileContext context = compile(CaveTestPacks.dimension(20), CaveTestPacks.constantProfile(-0.1), SEA_FLOOR_SLOPE, SEA_FLOOR_SLOPE);
Field floodedness = context.aquifer().floodedness();
assertTrue(CaveTestPacks.sample(floodedness, context.noises(), SEA_X, SEA_FLOOR + 1, 4) > FULLY_FLOODED);
assertTrue(CaveTestPacks.sample(floodedness, context.noises(), SEA_X, FLUID_HEIGHT, 4) > FULLY_FLOODED);
assertTrue(CaveTestPacks.sample(floodedness, context.noises(), SEA_X, FLUID_HEIGHT + 6, 4) > FULLY_FLOODED);
assertTrue(CaveTestPacks.sample(floodedness, context.noises(), SEA_X, SEA_FLOOR - 4, 4) > FULLY_FLOODED);
assertEquals(DRY, CaveTestPacks.sample(floodedness, context.noises(), SEA_X, SEA_FLOOR - 12, 4), 0.0);
assertEquals(DRY, CaveTestPacks.sample(floodedness, context.noises(), LAND_X, FLUID_HEIGHT - 10, 4), 0.0);
assertEquals(DRY, CaveTestPacks.sample(floodedness, context.noises(), LAND_X, SEA_FLOOR + 1, 4), 0.0);
}
@Test
public void openWaterLiftStaysNearSeaLevel() throws Exception {
PackCompileContext context = compile(CaveTestPacks.dimension(20), CaveTestPacks.constantProfile(-0.1), SEA_FLOOR_SLOPE, SEA_FLOOR_SLOPE);
Field floodedness = context.aquifer().floodedness();
assertEquals(DRY, CaveTestPacks.sample(floodedness, context.noises(), DEEP_SEA_X, FLUID_HEIGHT - 40, 4), 0.0);
assertTrue(CaveTestPacks.sample(floodedness, context.noises(), DEEP_SEA_X, FLUID_HEIGHT - 20, 4) > FULLY_FLOODED);
assertEquals(DRY, CaveTestPacks.sample(floodedness, context.noises(), SEA_X, FLUID_HEIGHT + 12, 4), 0.0);
}
@Test
public void openWaterLiftStopsAtTheShore() throws Exception {
PackCompileContext context = compile(CaveTestPacks.dimension(20), CaveTestPacks.constantProfile(-0.1), SEA_FLOOR_SLOPE, SEA_FLOOR_SLOPE);
Field floodedness = context.aquifer().floodedness();
assertTrue(CaveTestPacks.sample(floodedness, context.noises(), SHORE_X, FLUID_HEIGHT, 4) > FULLY_FLOODED);
assertEquals(DRY, CaveTestPacks.sample(floodedness, context.noises(), HILL_X, FLUID_HEIGHT + 7, 4), 0.0);
}
@Test
public void openWaterLiftSkipsColumnsWithAHighSurfaceEstimate() throws Exception {
PackCompileContext context = compile(CaveTestPacks.dimension(20), CaveTestPacks.constantProfile(-0.1), SEA_FLOOR_SLOPE, HIGH_ESTIMATE);
assertEquals(DRY, CaveTestPacks.sample(context.aquifer().floodedness(), context.noises(), SEA_X, SEA_FLOOR + 1, 4), 0.0);
}
@Test
public void wetCavesBelowTheTerrainKeepPartialFlooding() throws Exception {
PackCompileContext context = compile(CaveTestPacks.dimension(20), CaveTestPacks.constantProfile(-0.1).setAllowFluid(true), SEA_FLOOR_SLOPE, SEA_FLOOR_SLOPE);
Field floodedness = context.aquifer().floodedness();
assertTrue(CaveTestPacks.sample(floodedness, context.noises(), SEA_X, SEA_FLOOR + 6, 4) > FULLY_FLOODED);
assertEquals(PARTIAL, CaveTestPacks.sample(floodedness, context.noises(), SEA_X, SEA_FLOOR - 24, 4), 1.0e-6);
assertEquals(PARTIAL, CaveTestPacks.sample(floodedness, context.noises(), LAND_X, FLUID_HEIGHT - 10, 4), 1.0e-6);
}
@Test
public void lavaAboveMinus10ReportsLimit() throws Exception {
PackCompileContext context = compile(CaveTestPacks.dimension(60), CaveTestPacks.constantProfile(-0.1).setAllowLava(true));
List<ExportDiagnostic> limits = context.diagnostics().stream().filter(diagnostic -> diagnostic.limit() == ExportLimit.LAVA_HEIGHT).toList();
assertEquals(1, limits.size());
assertEquals("dimensions/" + ExportTestPacks.DIMENSION, limits.getFirst().resource());
for (int y = CaveTestPacks.MIN_Y; y < 0; y += 4) {
assertEquals(DRY, CaveTestPacks.sample(context.aquifer().floodedness(), context.noises(), 3, y, 5), 0.0);
}
}
@Test
public void lavaFillsToProfileLavaHeight() throws Exception {
int lavaY = CaveTestPacks.MIN_Y + 20;
PackCompileContext context = compile(CaveTestPacks.dimension(20), CaveTestPacks.constantProfile(-0.1).setAllowLava(true));
AquiferDef aquifer = context.aquifer();
assertFalse(context.diagnostics().stream().anyMatch(diagnostic -> diagnostic.limit() == ExportLimit.LAVA_HEIGHT));
assertEquals(PARTIAL, CaveTestPacks.sample(aquifer.floodedness(), context.noises(), 4, lavaY - 6, 4), 1.0e-6);
assertEquals(PARTIAL, CaveTestPacks.sample(aquifer.floodedness(), context.noises(), 4, lavaY + 12, 4), 1.0e-6);
assertEquals(DRY, CaveTestPacks.sample(aquifer.floodedness(), context.noises(), 4, lavaY + 13, 4), 0.0);
assertEquals(DRY, CaveTestPacks.sample(aquifer.floodedness(), context.noises(), 4, 40, 4), 0.0);
int lavaBand = Math.floorDiv(lavaY + 12, FLUID_BAND_HEIGHT);
for (int band = Math.floorDiv(CaveTestPacks.MIN_Y, FLUID_BAND_HEIGHT); band <= lavaBand; band++) {
double spread = CaveTestPacks.sample(aquifer.spread(), context.noises(), 7, band, -2);
int level = band * FLUID_BAND_HEIGHT + FLUID_BAND_CENTER + (int) Math.floor(spread * 10.0 / 3.0) * 3;
assertTrue("band " + band + " level " + level, level <= lavaY && level >= lavaY - 2);
assertTrue(Math.abs(CaveTestPacks.sample(aquifer.lava(), context.noises(), 7, band, -2)) > 0.3);
}
assertTrue(Math.abs(CaveTestPacks.sample(aquifer.lava(), context.noises(), 7, lavaBand + 1, -2)) <= 0.3);
}
@Test
public void wetProfilesFloodBelowSeaLevel() throws Exception {
PackCompileContext context = compile(CaveTestPacks.dimension(20), CaveTestPacks.constantProfile(-0.1).setAllowFluid(true));
assertEquals(PARTIAL, CaveTestPacks.sample(context.aquifer().floodedness(), context.noises(), 4, 30, 4), 1.0e-6);
assertEquals(DRY, CaveTestPacks.sample(context.aquifer().floodedness(), context.noises(), 4, 100, 4), 0.0);
assertEquals(0.0, CaveTestPacks.sample(context.aquifer().lava(), context.noises(), 4, 0, 4), 0.0);
}
@Test
public void bandProfileDecidesFloodednessInsideItsBand() throws Exception {
JsonObject dimension = CaveTestPacks.dimension(20);
JsonArray carving = new JsonArray();
carving.add(CaveTestPacks.band("deep-band", "cave-band", -60, -30));
dimension.add("carving", carving);
File pack = CaveTestPacks.pack(temporaryFolder.newFolder("pack"), dimension, CaveTestPacks.region(List.of("cave-dry"), null),
Map.of("cave-dry", CaveTestPacks.constantProfile(-0.1), "cave-band", CaveTestPacks.constantProfile(-0.1).setAllowLava(true)));
IrisData data = IrisData.openRuntime(pack);
try {
PackCompileContext context = context(data, "cave-dry");
new CaveStage().apply(context);
assertEquals(PARTIAL, CaveTestPacks.sample(context.aquifer().floodedness(), context.noises(), 4, -50, 4), 1.0e-6);
assertEquals(DRY, CaveTestPacks.sample(context.aquifer().floodedness(), context.noises(), 4, -62, 4), 0.0);
} finally {
data.close();
}
}
private PackCompileContext compile(JsonObject dimension, IrisCaveProfile profile) throws Exception {
return compile(dimension, profile, SURFACE, SURFACE);
}
private PackCompileContext compile(JsonObject dimension, IrisCaveProfile profile, Field height, Field estimate) throws Exception {
File pack = CaveTestPacks.pack(temporaryFolder.newFolder("pack"), dimension, CaveTestPacks.region(List.of("cave-only"), null),
Map.of("cave-only", profile));
IrisData data = IrisData.openRuntime(pack);
try {
PackCompileContext context = context(data, "cave-only");
context.setHeight(height);
context.setSurfaceEstimate(estimate);
new CaveStage().apply(context);
return context;
} finally {
data.close();
}
}
private static PackCompileContext context(IrisData data, String caveBiome) {
PackCompileContext context = CaveTestPacks.context(data, FakeCaveStyles.volumetric());
context.setHeight(SURFACE);
context.setBiomeCodes(CaveTestPacks.codes(CaveTestPacks.xGradient(), List.of(new CaveTestPacks.CodeRange(caveBiome, -1.0, 1.0))));
return context;
}
}
@@ -0,0 +1,550 @@
package art.arcane.iris.pack.datapack.export.compile.cave;
import art.arcane.iris.generation.cave.IrisCaveProfile;
import art.arcane.iris.generation.noise.IrisStyledRange;
import art.arcane.iris.generation.noise.NoiseStyle;
import art.arcane.iris.pack.datapack.DataVersion;
import art.arcane.iris.pack.datapack.export.ExportTestPacks;
import art.arcane.iris.pack.datapack.export.compile.PackCompileContext;
import art.arcane.iris.pack.datapack.export.ir.AquiferDef;
import art.arcane.iris.pack.datapack.export.ir.Axis;
import art.arcane.iris.pack.datapack.export.ir.CostClass;
import art.arcane.iris.pack.datapack.export.ir.ExportDiagnostic;
import art.arcane.iris.pack.datapack.export.ir.ExportLimit;
import art.arcane.iris.pack.datapack.export.ir.Field;
import art.arcane.iris.pack.datapack.export.ir.FieldEvaluator;
import art.arcane.iris.pack.datapack.export.ir.NoiseDef;
import art.arcane.iris.pack.loading.IrisData;
import art.arcane.iris.pack.value.IrisRange;
import art.arcane.iris.testsupport.PlatformLeakGuard;
import art.arcane.volmlib.util.collection.KList;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import org.junit.ClassRule;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
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.assertTrue;
public class CaveFieldCompilerTest {
private static final Field DEEP_SURFACE = new Field.Const(150.0);
private static final double OPEN_SHARE_THRESHOLD = 0.15;
private static final int BAND_HEIGHT = 16;
private static final int FINE_ORIGIN_X = -900;
private static final int BROAD_ORIGIN_X = 120;
private static final int SHELL_BOXES = 6;
private static final int SHELL_BOX = 24;
private static final int SHELL_BOX_HEIGHT = 48;
private static final int SHELL_BOX_Y = -40;
private static final int SHELL_BOX_STEP_X = 130;
private static final int SHELL_BOX_STEP_Z = 230;
private static final long MIN_WALLS = 200L;
private static final double SHELL_TOLERANCE = 0.2;
@ClassRule
public static final PlatformLeakGuard PLATFORM_GUARD = PlatformLeakGuard.clean();
@Rule
public TemporaryFolder temporaryFolder = new TemporaryFolder();
@Rule
public ExportTestPacks.BoundPlatform platform = new ExportTestPacks.BoundPlatform();
@Test
public void profileSelectedByCaveCode() throws Exception {
File pack = CaveTestPacks.pack(temporaryFolder.newFolder("pack"), CaveTestPacks.dimension(8),
CaveTestPacks.region(List.of("cave-open", "cave-closed"), null),
Map.of("cave-open", CaveTestPacks.constantProfile(5.0), "cave-closed", CaveTestPacks.constantProfile(-5.0)));
IrisData data = IrisData.openRuntime(pack);
try {
PackCompileContext context = deepContext(data, FakeCaveStyles.volumetric(), List.of(
new CaveTestPacks.CodeRange("cave-open", -1.0, 0.0),
new CaveTestPacks.CodeRange("cave-closed", 0.0, 1.0)));
new CaveStage().apply(context);
Field caves = context.caves();
assertTrue(CaveTestPacks.caveField(caves) instanceof Field.Grid);
assertTrue(((Field.Grid) CaveTestPacks.caveField(caves)).expr() instanceof Field.Mux);
assertTrue(CaveTestPacks.sample(caves, context.noises(), -500, 0, 0) <= 0.0);
assertTrue(CaveTestPacks.sample(caves, context.noises(), 500, 0, 0) > 0.0);
} finally {
data.close();
}
}
@Test
public void uncoveredCaveCodesUseTheDimensionProfile() throws Exception {
JsonObject dimension = CaveTestPacks.dimension(8);
dimension.add("caveProfile", CaveTestPacks.json(CaveTestPacks.constantProfile(5.0)));
File pack = CaveTestPacks.pack(temporaryFolder.newFolder("pack"), dimension,
CaveTestPacks.region(List.of("cave-closed"), null),
Map.of("cave-closed", CaveTestPacks.constantProfile(-5.0)));
IrisData data = IrisData.openRuntime(pack);
try {
PackCompileContext context = deepContext(data, FakeCaveStyles.volumetric(), List.of(
new CaveTestPacks.CodeRange("cave-closed", 0.0, 1.0)));
new CaveStage().apply(context);
assertTrue(CaveTestPacks.sample(context.caves(), context.noises(), -500, 0, 0) <= 0.0);
assertTrue(CaveTestPacks.sample(context.caves(), context.noises(), 500, 0, 0) > 0.0);
} finally {
data.close();
}
}
@Test
public void wallShellBandHoldsTheOneBlockWallOfTheCaveField() throws Exception {
File pack = CaveTestPacks.pack(temporaryFolder.newFolder("pack"), CaveTestPacks.dimension(8),
CaveTestPacks.region(List.of("cave-noise"), null), Map.of("cave-noise", CaveTestPacks.profile()));
IrisData data = IrisData.openRuntime(pack);
try {
PackCompileContext context = deepContext(data, FakeCaveStyles.volumetric(), List.of(new CaveTestPacks.CodeRange("cave-noise", -1.0, 1.0)));
new CaveStage().apply(context);
double band = context.wallShellBand();
Field field = context.caveField().orElseThrow();
long solid = 0L;
long walls = 0L;
long shell = 0L;
for (int column = 0; column < 64; column++) {
int x = 37 * column - 1200;
int z = 53 * (column % 8) + 400;
for (int y = -40; y < 120; y += 2) {
double value = CaveTestPacks.sample(field, context.noises(), x, y, z);
if (value < 0.0) {
continue;
}
solid++;
if (value < band) {
shell++;
}
if (CaveTestPacks.sample(field, context.noises(), x + 1, y, z) < 0.0 || CaveTestPacks.sample(field, context.noises(), x - 1, y, z) < 0.0
|| CaveTestPacks.sample(field, context.noises(), x, y, z + 1) < 0.0 || CaveTestPacks.sample(field, context.noises(), x, y, z - 1) < 0.0) {
walls++;
}
}
}
assertTrue("band " + band, band > 0.0 && band < 0.5);
assertTrue(walls + " walls of " + solid, walls > 50L);
assertEquals("shell " + shell + " walls " + walls + " solid " + solid, 1.0, shell / (double) walls, 0.25);
} finally {
data.close();
}
}
@Test
public void wallShellPaintsTheOneBlockWallOfEveryProfile() throws Exception {
File pack = CaveTestPacks.pack(temporaryFolder.newFolder("pack"), CaveTestPacks.dimension(8),
CaveTestPacks.region(List.of("cave-fine", "cave-broad"), null), Map.of(
"cave-fine", CaveTestPacks.profile().setBaseDensityStyle(CaveTestPacks.style(NoiseStyle.SIMPLEX, 0.25)),
"cave-broad", CaveTestPacks.profile().setBaseDensityStyle(CaveTestPacks.style(NoiseStyle.SIMPLEX, 1.5))));
IrisData data = IrisData.openRuntime(pack);
try {
PackCompileContext context = deepContext(data, FakeCaveStyles.volumetric(), List.of(
new CaveTestPacks.CodeRange("cave-fine", -1.0, 0.0),
new CaveTestPacks.CodeRange("cave-broad", 0.0, 1.0)));
new CaveStage().apply(context);
Field field = context.caveField().orElseThrow();
double band = context.wallShellBand();
ShellCount fine = shellCount(field, context, band, FINE_ORIGIN_X);
ShellCount broad = shellCount(field, context, band, BROAD_ORIGIN_X);
assertTrue(fine.toString(), fine.walls() > MIN_WALLS);
assertTrue(broad.toString(), broad.walls() > MIN_WALLS);
assertEquals(fine.toString(), 1.0, fine.ratio(), SHELL_TOLERANCE);
assertEquals(broad.toString(), 1.0, broad.ratio(), SHELL_TOLERANCE);
} finally {
data.close();
}
}
@Test
public void caveBiomeWithoutProfileUsesItsRegionProfile() throws Exception {
File pack = CaveTestPacks.pack(temporaryFolder.newFolder("pack"), CaveTestPacks.dimension(8),
CaveTestPacks.region(List.of("cave-plain"), CaveTestPacks.constantProfile(5.0)),
Map.of("cave-plain", new IrisCaveProfile()));
IrisData data = IrisData.openRuntime(pack);
try {
PackCompileContext context = deepContext(data, FakeCaveStyles.volumetric(), List.of(
new CaveTestPacks.CodeRange("cave-plain", -1.0, 1.0)));
new CaveStage().apply(context);
assertTrue(CaveTestPacks.sample(context.caves(), context.noises(), 300, 0, 0) <= 0.0);
} finally {
data.close();
}
}
@Test
public void threeDimensionalCellularOnlyInsideGrid() throws Exception {
IrisCaveProfile profile = CaveTestPacks.profile()
.setBaseDensityStyle(CaveTestPacks.style(NoiseStyle.CELLULAR_IRIS_DOUBLE, 0.7))
.setModules(new KList<>(List.of(CaveTestPacks.module(NoiseStyle.CELLULAR, 0.3, 0.0, false, new IrisRange(0, 256)))));
File pack = CaveTestPacks.pack(temporaryFolder.newFolder("pack"), CaveTestPacks.dimension(8),
CaveTestPacks.region(List.of("cave-cells"), null), Map.of("cave-cells", profile));
IrisData data = IrisData.openRuntime(pack);
try {
PackCompileContext context = deepContext(data, FakeCaveStyles.expensiveCellular(), List.of(
new CaveTestPacks.CodeRange("cave-cells", -1.0, 1.0)));
new CaveStage().apply(context);
List<Field.Noise> outside = new ArrayList<>();
List<Field.Noise> inside = new ArrayList<>();
collectCellular(context.caves(), false, inside, outside);
assertFalse(inside.isEmpty());
assertTrue(outside.toString(), outside.isEmpty());
for (Field.Noise noise : inside) {
assertTrue(noise.axes().contains(Axis.Y));
assertEquals(CostClass.EXPENSIVE, noise.cost());
}
} finally {
data.close();
}
}
@Test
public void lowWeightCellularModulesUseSmoothSubstitutes() throws Exception {
IrisCaveProfile profile = CaveTestPacks.profile().setModules(new KList<>(List.of(
CaveTestPacks.module(NoiseStyle.CELLULAR_BILINEAR, 0.05, 0.0, false, new IrisRange(0, 256)),
CaveTestPacks.module(NoiseStyle.SIMPLEX_VASCULAR, 0.08, 0.1, true, new IrisRange(0, 256)),
CaveTestPacks.module(NoiseStyle.VASCULAR, 0.2, 0.0, false, new IrisRange(0, 256)))));
File pack = CaveTestPacks.pack(temporaryFolder.newFolder("pack"), CaveTestPacks.dimension(8),
CaveTestPacks.region(List.of("cave-mixed"), null), Map.of("cave-mixed", profile));
IrisData data = IrisData.openRuntime(pack);
try {
FakeCaveStyles styles = FakeCaveStyles.volumetric();
PackCompileContext context = deepContext(data, styles, List.of(new CaveTestPacks.CodeRange("cave-mixed", -1.0, 1.0)));
new CaveStage().apply(context);
List<NoiseStyle> requests = styles.requests();
assertFalse(requests.toString(), requests.contains(NoiseStyle.CELLULAR_BILINEAR));
assertFalse(requests.toString(), requests.contains(NoiseStyle.SIMPLEX_VASCULAR));
assertTrue(requests.toString(), requests.contains(NoiseStyle.VASCULAR));
} finally {
data.close();
}
}
@Test
public void planarSmoothStylesLiftToVolume() throws Exception {
IrisCaveProfile profile = CaveTestPacks.profile()
.setDensityThreshold(new IrisStyledRange(-0.1, 0.1, CaveTestPacks.style(NoiseStyle.SIMPLEX, 1.0)));
File pack = CaveTestPacks.pack(temporaryFolder.newFolder("pack"), CaveTestPacks.dimension(8),
CaveTestPacks.region(List.of("cave-smooth"), null), Map.of("cave-smooth", profile));
IrisData data = IrisData.openRuntime(pack);
try {
PackCompileContext context = deepContext(data, FakeCaveStyles.planar(), List.of(new CaveTestPacks.CodeRange("cave-smooth", -1.0, 1.0)));
new CaveStage().apply(context);
Field.Noise base = noiseContaining(context.caves(), "simplex_934447");
Field.Noise threshold = noiseContaining(context.caves(), "simplex_489112");
assertEquals(base.xzScale(), base.yScale(), 0.0);
assertTrue(base.yScale() != 0.0);
assertEquals(0.0, threshold.yScale(), 0.0);
} finally {
data.close();
}
}
@Test
public void planarCellularStylesExportAsSmoothNoise() throws Exception {
IrisCaveProfile profile = CaveTestPacks.profile().setBaseDensityStyle(CaveTestPacks.style(NoiseStyle.CELLULAR_IRIS_DOUBLE, 0.7));
File pack = CaveTestPacks.pack(temporaryFolder.newFolder("pack"), CaveTestPacks.dimension(8),
CaveTestPacks.region(List.of("cave-cells"), null), Map.of("cave-cells", profile));
IrisData data = IrisData.openRuntime(pack);
try {
PackCompileContext context = deepContext(data, FakeCaveStyles.planar(), List.of(new CaveTestPacks.CodeRange("cave-cells", -1.0, 1.0)));
new CaveStage().apply(context);
Field.Noise base = noiseContaining(context.caves(), "simplex_934447");
assertEquals(base.xzScale(), base.yScale(), 0.0);
assertTrue(context.diagnostics().stream().anyMatch(diagnostic -> diagnostic.limit() == ExportLimit.NOISE_STYLE
&& diagnostic.resource().equals("biomes/cave-cells")));
} finally {
data.close();
}
}
@Test
public void caveOpenShareWithinThresholdPerBand() throws Exception {
IrisCaveProfile profile = CaveTestPacks.profile()
.setVerticalRange(new IrisRange(8, 240))
.setVerticalEdgeFade(24)
.setVerticalEdgeFadeStrength(0.2)
.setDetailWeight(0.15)
.setDensityThreshold(new IrisStyledRange(-0.15, 0.02, CaveTestPacks.style(NoiseStyle.SIMPLEX, 1.0)))
.setThresholdBias(0.08)
.setSurfaceClearance(6)
.setAllowSurfaceBreak(true)
.setSurfaceBreakStyle(CaveTestPacks.style(NoiseStyle.SIMPLEX, 0.08))
.setSurfaceBreakNoiseThreshold(0.4)
.setSurfaceBreakDepth(18)
.setSurfaceBreakThresholdBoost(0.2)
.setModules(new KList<>(List.of(
CaveTestPacks.module(NoiseStyle.SIMPLEX, 0.08, 0.1, true, new IrisRange(20, 120)),
CaveTestPacks.module(NoiseStyle.FRACTAL_FBM_SIMPLEX, 0.06, 0.0, false, new IrisRange(0, 256)))));
File pack = CaveTestPacks.pack(temporaryFolder.newFolder("pack"), CaveTestPacks.dimension(8),
CaveTestPacks.region(List.of("cave-real"), null), Map.of("cave-real", profile));
IrisData data = IrisData.openRuntime(pack);
try {
FakeCaveStyles styles = FakeCaveStyles.volumetric();
PackCompileContext context = CaveTestPacks.context(data, styles);
Field height = rollingSurface(context);
context.setHeight(height);
context.setBiomeCodes(CaveTestPacks.codes(CaveTestPacks.xGradient(), List.of(new CaveTestPacks.CodeRange("cave-real", -1.0, 1.0))));
new CaveStage().apply(context);
IrisCaveReference reference = new IrisCaveReference(profile, styles, context.noises(), context.capabilities(), height);
Field caves = context.caves();
double referenceTotal = 0.0;
int bands = 0;
for (int bandMin = CaveTestPacks.MIN_Y; bandMin < CaveTestPacks.MAX_Y; bandMin += BAND_HEIGHT) {
int compiledOpen = 0;
int referenceOpen = 0;
int samples = 0;
for (int x = -300; x < 70; x += 37) {
for (int z = -250; z < 120; z += 37) {
for (int y = bandMin; y < bandMin + BAND_HEIGHT; y += 2) {
if (CaveTestPacks.sample(caves, context.noises(), x, y, z) <= 0.0) {
compiledOpen++;
}
if (reference.carved(x, y, z)) {
referenceOpen++;
}
samples++;
}
}
}
double compiledShare = compiledOpen / (double) samples;
double referenceShare = referenceOpen / (double) samples;
assertEquals("band " + bandMin, referenceShare, compiledShare, OPEN_SHARE_THRESHOLD);
referenceTotal += referenceShare;
bands++;
}
assertTrue("reference carves nothing", referenceTotal / bands > 0.05);
} finally {
data.close();
}
}
@Test
public void deepDarkBandIsMinUnioned() throws Exception {
JsonObject dimension = CaveTestPacks.dimension(8);
JsonArray carving = new JsonArray();
carving.add(CaveTestPacks.band("deep-band", "cave-band", -40, -20));
dimension.add("carving", carving);
File pack = CaveTestPacks.pack(temporaryFolder.newFolder("pack"), dimension,
CaveTestPacks.region(List.of("cave-closed"), null),
Map.of("cave-closed", CaveTestPacks.constantProfile(-5.0), "cave-band", CaveTestPacks.constantProfile(5.0)));
IrisData data = IrisData.openRuntime(pack);
try {
PackCompileContext context = deepContext(data, FakeCaveStyles.volumetric(), List.of(new CaveTestPacks.CodeRange("cave-closed", -1.0, 1.0)));
new CaveStage().apply(context);
Field caves = context.caves();
Field union = ((Field.Grid) CaveTestPacks.caveField(caves)).expr();
assertTrue(union instanceof Field.Binary binary && binary.op() == Field.BinaryOp.MIN);
assertTrue(CaveTestPacks.sample(caves, context.noises(), 40, -30, 40) <= 0.0);
assertTrue(CaveTestPacks.sample(caves, context.noises(), 40, 0, 40) > 0.0);
assertTrue(CaveTestPacks.sample(caves, context.noises(), 40, -60, 40) > 0.0);
} finally {
data.close();
}
}
@Test
public void expensiveSubtreesOnlySelectedThroughMuxOrGate() throws Exception {
IrisCaveProfile lava = demandingProfile().setAllowFluid(true);
JsonObject dimension = CaveTestPacks.dimension(20);
JsonArray carving = new JsonArray();
carving.add(CaveTestPacks.band("deep-band", "cave-band", -50, -20));
dimension.add("carving", carving);
File pack = CaveTestPacks.pack(temporaryFolder.newFolder("pack"), dimension,
CaveTestPacks.region(List.of("cave-lava", "cave-plain"), null),
Map.of("cave-lava", lava, "cave-plain", CaveTestPacks.profile(), "cave-band", demandingProfile()));
IrisData data = IrisData.openRuntime(pack);
try {
PackCompileContext context = CaveTestPacks.context(data, FakeCaveStyles.expensive());
context.setHeight(warpedSurface(context));
context.setBiomeCodes(CaveTestPacks.codes(CaveTestPacks.xGradient(), List.of(
new CaveTestPacks.CodeRange("cave-lava", -1.0, 0.0),
new CaveTestPacks.CodeRange("cave-plain", 0.0, 1.0))));
new CaveStage().apply(context);
AquiferDef aquifer = context.aquifer();
List<Field> roots = List.of(context.caves(), aquifer.barrier(), aquifer.floodedness(), aquifer.spread(), aquifer.lava(), aquifer.exclusion());
boolean expensive = false;
boolean muxed = false;
for (Field root : roots) {
for (Field node : CaveTestPacks.nodes(root)) {
expensive |= node.cost() == CostClass.EXPENSIVE;
muxed |= node instanceof Field.Mux;
for (Field child : CaveTestPacks.eagerChildren(node)) {
assertTrue(node.getClass().getSimpleName() + " evaluates an expensive child eagerly", child.cost() != CostClass.EXPENSIVE);
}
}
}
assertTrue(expensive);
assertTrue(muxed);
} finally {
data.close();
}
}
@Test
public void compiledCavesAreDeterministic() throws Exception {
IrisCaveProfile profile = CaveTestPacks.profile()
.setDensityThreshold(new IrisStyledRange(-0.15, 0.02, CaveTestPacks.style(NoiseStyle.SIMPLEX, 1.0)))
.setAllowSurfaceBreak(true)
.setAllowLava(true)
.setModules(new KList<>(List.of(CaveTestPacks.module(NoiseStyle.SIMPLEX, 0.08, 0.1, true, new IrisRange(20, 120)))));
File pack = CaveTestPacks.pack(temporaryFolder.newFolder("pack"), CaveTestPacks.dimension(20),
CaveTestPacks.region(List.of("cave-one", "cave-two"), null),
Map.of("cave-one", profile, "cave-two", CaveTestPacks.constantProfile(-0.2)));
Compiled first = compileTwoCodes(pack);
Compiled second = compileTwoCodes(pack);
assertEquals(first.caves(), second.caves());
assertEquals(first.aquifer(), second.aquifer());
assertEquals(first.noises(), second.noises());
assertEquals(first.diagnostics(), second.diagnostics());
}
private Compiled compileTwoCodes(File pack) throws IOException {
IrisData data = IrisData.openRuntime(pack);
try {
PackCompileContext context = deepContext(data, FakeCaveStyles.volumetric(), List.of(
new CaveTestPacks.CodeRange("cave-one", -1.0, 0.0),
new CaveTestPacks.CodeRange("cave-two", 0.0, 1.0)));
new CaveStage().apply(context);
return new Compiled(context.caves(), context.aquifer(), context.noises().definitions(), List.copyOf(context.diagnostics()));
} finally {
data.close();
}
}
private static IrisCaveProfile demandingProfile() {
return CaveTestPacks.profile()
.setVerticalRange(new IrisRange(8, 240))
.setVerticalEdgeFade(24)
.setDetailWeight(0.15)
.setDensityThreshold(new IrisStyledRange(-0.15, 0.02, CaveTestPacks.style(NoiseStyle.SIMPLEX, 1.0)))
.setSurfaceClearance(6)
.setAllowSurfaceBreak(true)
.setAllowLava(true)
.setModules(new KList<>(List.of(
CaveTestPacks.module(NoiseStyle.SIMPLEX, 0.08, 0.1, true, new IrisRange(20, 120)),
CaveTestPacks.module(NoiseStyle.CELLULAR, 0.3, 0.0, false, new IrisRange(0, 256)))));
}
private static PackCompileContext deepContext(IrisData data, FakeCaveStyles styles, List<CaveTestPacks.CodeRange> ranges) {
PackCompileContext context = CaveTestPacks.context(data, styles);
context.setHeight(DEEP_SURFACE);
context.setBiomeCodes(CaveTestPacks.codes(CaveTestPacks.xGradient(), ranges));
return context;
}
private static Field rollingSurface(PackCompileContext context) {
String id = context.noises().register(new NoiseDef("cave_test/surface", 0, List.of(1.0)));
Field noise = new Field.Noise(id, 1.0 / 128.0, 0.0, null, null, null);
return new Field.Curve(noise, List.of(
new Field.Knot(-1.0, new Field.Const(50.0), 20.0),
new Field.Knot(1.0, new Field.Const(90.0), 20.0)));
}
private static Field warpedSurface(PackCompileContext context) {
String warp = context.noises().register(new NoiseDef("cave_test/surface_warp", 0, List.of(1.0)));
String id = context.noises().register(new NoiseDef("cave_test/surface", 0, List.of(1.0)));
Field shift = new Field.Noise(warp, 1.0 / 128.0, 0.0, null, null, null);
Field noise = new Field.Shared("height", new Field.Noise(id, 1.0 / 128.0, 0.0, shift, null, shift));
return new Field.Curve(noise, List.of(
new Field.Knot(-1.0, new Field.Const(50.0), 20.0),
new Field.Knot(1.0, new Field.Const(90.0), 20.0)));
}
private static ShellCount shellCount(Field field, PackCompileContext context, double band, int originX) {
Map<String, NoiseDef> noises = CaveTestPacks.noises(context.noises());
long solid = 0L;
long walls = 0L;
long shell = 0L;
for (int box = 0; box < SHELL_BOXES; box++) {
int x0 = originX + box * SHELL_BOX_STEP_X;
int z0 = box * SHELL_BOX_STEP_Z - SHELL_BOX_STEP_Z;
double[][][] values = new double[SHELL_BOX][SHELL_BOX_HEIGHT][SHELL_BOX];
for (int x = 0; x < SHELL_BOX; x++) {
for (int y = 0; y < SHELL_BOX_HEIGHT; y++) {
for (int z = 0; z < SHELL_BOX; z++) {
values[x][y][z] = FieldEvaluator.sample(field, noises, CaveTestPacks.SEED, DataVersion.V26_3, x0 + x, SHELL_BOX_Y + y, z0 + z);
}
}
}
for (int x = 1; x < SHELL_BOX - 1; x++) {
for (int y = 0; y < SHELL_BOX_HEIGHT; y++) {
for (int z = 1; z < SHELL_BOX - 1; z++) {
double value = values[x][y][z];
if (value < 0.0) {
continue;
}
solid++;
if (value < band) {
shell++;
}
if (values[x + 1][y][z] < 0.0 || values[x - 1][y][z] < 0.0 || values[x][y][z + 1] < 0.0 || values[x][y][z - 1] < 0.0) {
walls++;
}
}
}
}
}
return new ShellCount(solid, walls, shell);
}
private static Field.Noise noiseContaining(Field root, String fragment) {
for (Field node : CaveTestPacks.nodes(root)) {
if (node instanceof Field.Noise noise && noise.noiseId().contains(fragment)) {
return noise;
}
}
throw new AssertionError("No noise containing '" + fragment + "' in " + root);
}
private static void collectCellular(Field field, boolean insideGrid, List<Field.Noise> inside, List<Field.Noise> outside) {
if (field instanceof Field.Noise noise && noise.noiseId().contains(FakeCaveStyles.CELLULAR_PREFIX)) {
(insideGrid ? inside : outside).add(noise);
}
boolean childInside = insideGrid || field instanceof Field.Grid;
for (Field child : CaveTestPacks.children(field)) {
collectCellular(child, childInside, inside, outside);
}
}
private record Compiled(Field caves, AquiferDef aquifer, List<NoiseDef> noises, List<ExportDiagnostic> diagnostics) {
}
private record ShellCount(long solid, long walls, long shell) {
private double ratio() {
return shell / (double) walls;
}
}
}
@@ -0,0 +1,96 @@
package art.arcane.iris.pack.datapack.export.compile.cave;
import art.arcane.iris.generation.cave.IrisCaveProfile;
import art.arcane.iris.generation.noise.IrisStyledRange;
import art.arcane.iris.generation.noise.NoiseStyle;
import art.arcane.iris.pack.datapack.export.ExportTestPacks;
import art.arcane.iris.pack.datapack.export.compile.PackCompileContext;
import art.arcane.iris.pack.datapack.export.ir.Axis;
import art.arcane.iris.pack.datapack.export.ir.Field;
import art.arcane.iris.pack.loading.IrisData;
import art.arcane.iris.pack.value.IrisRange;
import art.arcane.iris.testsupport.PlatformLeakGuard;
import art.arcane.volmlib.util.collection.KList;
import org.junit.ClassRule;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import java.io.File;
import java.util.List;
import java.util.Map;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertThrows;
import static org.junit.Assert.assertTrue;
public class CaveProfileCompilerTest {
private static final double GAIN = 3.0;
private static final double TOLERANCE = 1.0e-4;
private static final int FLOOR = CaveTestPacks.MIN_Y + 8;
private static final int CEILING = CaveTestPacks.MIN_Y + 240;
private static final Field SLOPED_SURFACE = new Field.Coord(Axis.X, Field.Tiling.CLAMP, -200, 200, 60, 140);
@ClassRule
public static final PlatformLeakGuard PLATFORM_GUARD = PlatformLeakGuard.clean();
@Rule
public TemporaryFolder temporaryFolder = new TemporaryFolder();
@Rule
public ExportTestPacks.BoundPlatform platform = new ExportTestPacks.BoundPlatform();
@Test
public void gainScalesTheFieldWithoutMovingItsCaves() throws Exception {
IrisCaveProfile profile = CaveTestPacks.profile()
.setVerticalRange(new IrisRange(8, 240))
.setVerticalEdgeFade(24)
.setVerticalEdgeFadeStrength(0.2)
.setDetailWeight(0.15)
.setDensityThreshold(new IrisStyledRange(-0.15, 0.02, CaveTestPacks.style(NoiseStyle.SIMPLEX, 1.0)))
.setThresholdBias(0.08)
.setSurfaceClearance(6)
.setAllowSurfaceBreak(true)
.setSurfaceBreakStyle(CaveTestPacks.style(NoiseStyle.SIMPLEX, 0.08))
.setSurfaceBreakNoiseThreshold(0.4)
.setSurfaceBreakDepth(18)
.setSurfaceBreakThresholdBoost(0.1)
.setModules(new KList<>(List.of(CaveTestPacks.module(NoiseStyle.SIMPLEX, 0.08, 0.1, true, new IrisRange(20, 120)))));
File pack = CaveTestPacks.pack(temporaryFolder.newFolder("pack"), CaveTestPacks.dimension(8),
CaveTestPacks.region(List.of("cave-gain"), null), Map.of("cave-gain", profile));
IrisData data = IrisData.openRuntime(pack);
try {
PackCompileContext context = CaveTestPacks.context(data, FakeCaveStyles.volumetric());
context.setHeight(SLOPED_SURFACE);
CaveInputs inputs = CaveInputs.of(context);
CaveProfileCompiler compiler = new CaveProfileCompiler(context.styles(), inputs);
CaveSource source = new CaveSource("biomes/cave-gain", profile, inputs.minY(), inputs.maxY());
Field unit = compiler.compile(source, 1.0);
Field scaled = compiler.compile(source, GAIN);
int caves = 0;
for (int x = -240; x <= 240; x += 40) {
for (int y = CaveTestPacks.MIN_Y; y < CaveTestPacks.MAX_Y; y += 5) {
for (int z = -90; z <= 90; z += 60) {
double expected = CaveTestPacks.sample(unit, context.noises(), x, y, z);
double actual = CaveTestPacks.sample(scaled, context.noises(), x, y, z);
if (y < FLOOR || y > CEILING) {
assertEquals(x + "," + y + "," + z, CaveProfileCompiler.SOLID, expected, 0.0);
assertEquals(x + "," + y + "," + z, CaveProfileCompiler.SOLID, actual, 0.0);
continue;
}
assertEquals(x + "," + y + "," + z, GAIN * expected, actual, TOLERANCE * Math.max(1.0, Math.abs(actual)));
if (expected < 0.0) {
caves++;
}
}
}
}
assertTrue(String.valueOf(caves), caves > 0);
assertThrows(IllegalArgumentException.class, () -> compiler.compile(source, 0.0));
} finally {
data.close();
}
}
}
@@ -0,0 +1,156 @@
package art.arcane.iris.pack.datapack.export.compile.cave;
import art.arcane.iris.pack.datapack.DataVersion;
import art.arcane.iris.pack.datapack.export.ExportTestPacks;
import art.arcane.iris.pack.datapack.export.ExportTestStyles;
import art.arcane.iris.pack.datapack.export.WorldgenExportProgress;
import art.arcane.iris.pack.datapack.export.compile.CompileStage;
import art.arcane.iris.pack.datapack.export.compile.DimensionStage;
import art.arcane.iris.pack.datapack.export.compile.PackCompileContext;
import art.arcane.iris.pack.datapack.export.compile.PackCompiler;
import art.arcane.iris.pack.datapack.export.compile.biome.BiomeStage;
import art.arcane.iris.pack.datapack.export.ir.AquiferDef;
import art.arcane.iris.pack.datapack.export.ir.BiomeDef;
import art.arcane.iris.pack.datapack.export.ir.ExportIr;
import art.arcane.iris.pack.datapack.export.ir.Field;
import art.arcane.iris.pack.datapack.export.ir.JsonResource;
import art.arcane.iris.pack.loading.IrisData;
import art.arcane.iris.testsupport.PlatformLeakGuard;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import org.junit.ClassRule;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.function.Consumer;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotEquals;
import static org.junit.Assert.assertTrue;
public class CaveStageTest {
private static final Field SURFACE = new Field.Const(120.0);
@ClassRule
public static final PlatformLeakGuard PLATFORM_GUARD = PlatformLeakGuard.clean();
@Rule
public TemporaryFolder temporaryFolder = new TemporaryFolder();
@Rule
public ExportTestPacks.BoundPlatform platform = new ExportTestPacks.BoundPlatform();
@Test
public void noVanillaCarversEmitted() throws Exception {
File pack = CaveTestPacks.pack(temporaryFolder.newFolder("pack"), CaveTestPacks.dimension(8),
CaveTestPacks.region(List.of("cave-open"), null), Map.of("cave-open", CaveTestPacks.constantProfile(0.1)));
IrisData data = IrisData.openRuntime(pack);
try {
CompileStage vanillaBiomes = new FixedStage("biomes", context -> {
JsonObject body = JsonParser.parseString("{\"carvers\":[\"minecraft:cave\",\"minecraft:canyon\"],\"features\":[]}").getAsJsonObject();
context.setBiomes(List.of(new BiomeDef(CaveTestPacks.SURFACE_BIOME, body), new BiomeDef("cave-open", body)));
context.setHeight(SURFACE);
context.setBiomeCodes(CaveTestPacks.codes(CaveTestPacks.xGradient(), List.of(new CaveTestPacks.CodeRange("cave-open", -1.0, 1.0))));
});
PackCompileContext context = ExportTestPacks.contextBuilder(data, DataVersion.V26_3).styles(FakeCaveStyles.volumetric()).build();
ExportIr ir = new PackCompiler(List.of(new DimensionStage(), vanillaBiomes, new CaveStage())).compile(context, WorldgenExportProgress.NONE);
for (BiomeDef biome : ir.biomes()) {
assertEquals(new JsonArray(), biome.json().get("carvers"));
}
for (JsonResource resource : ir.jsonResources()) {
assertFalse(resource.path(), resource.path().contains("carver"));
}
} finally {
data.close();
}
}
@Test
public void defaultPipelineRunsCavesAfterTerrain() throws Exception {
File pack = ExportTestPacks.basic(temporaryFolder.newFolder("pack"));
IrisData data = IrisData.openRuntime(pack);
try {
List<String> stages = new ArrayList<>();
WorldgenExportProgress progress = new WorldgenExportProgress() {
@Override
public void stage(String stage) {
stages.add(stage);
}
@Override
public void resources(int done, int total) {
}
};
PackCompiler.create().compile(ExportTestPacks.contextBuilder(data, DataVersion.V26_3).styles(new ExportTestStyles()).build(), progress);
assertTrue(stages.toString(), stages.indexOf("terrain") >= 0);
assertTrue(stages.toString(), stages.indexOf("terrain") < stages.indexOf("caves"));
} finally {
data.close();
}
}
@Test
public void biomeStageCaveCodesSelectCaveProfiles() throws Exception {
File pack = CaveTestPacks.pack(temporaryFolder.newFolder("pack"), CaveTestPacks.dimension(8),
CaveTestPacks.region(List.of("cave-open"), null), Map.of("cave-open", CaveTestPacks.constantProfile(0.1)));
IrisData data = IrisData.openRuntime(pack);
try {
PackCompileContext context = CaveTestPacks.context(data, FakeCaveStyles.planar());
context.setHeight(SURFACE);
new BiomeStage().apply(context);
new CaveStage().apply(context);
assertNotEquals(new Field.Const(1.0e6), context.caves());
} finally {
data.close();
}
}
@Test
public void disabledCarvingKeepsDefaultSlots() throws Exception {
JsonObject dimension = CaveTestPacks.dimension(20);
dimension.addProperty("carvingEnabled", false);
File pack = CaveTestPacks.pack(temporaryFolder.newFolder("pack"), dimension,
CaveTestPacks.region(List.of("cave-open"), null), Map.of("cave-open", CaveTestPacks.constantProfile(5.0).setAllowLava(true)));
IrisData data = IrisData.openRuntime(pack);
try {
PackCompileContext context = CaveTestPacks.context(data, FakeCaveStyles.volumetric());
context.setHeight(SURFACE);
context.setBiomeCodes(CaveTestPacks.codes(CaveTestPacks.xGradient(), List.of(new CaveTestPacks.CodeRange("cave-open", -1.0, 1.0))));
new CaveStage().apply(context);
assertEquals(new Field.Const(1.0e6), context.caves());
AquiferDef aquifer = context.aquifer();
AquiferDef vanilla = AquiferDef.dry(SURFACE);
assertEquals(vanilla.barrier(), aquifer.barrier());
assertEquals(vanilla.spread(), aquifer.spread());
assertEquals(vanilla.lava(), aquifer.lava());
assertEquals(vanilla.exclusion(), aquifer.exclusion());
assertEquals(vanilla.surfaceLevel(), aquifer.surfaceLevel());
assertEquals(-1.0, CaveTestPacks.sample(aquifer.floodedness(), context.noises(), 4, 40, 4), 0.0);
assertTrue(context.diagnostics().isEmpty());
} finally {
data.close();
}
}
private record FixedStage(String name, Consumer<PackCompileContext> action) implements CompileStage {
@Override
public void apply(PackCompileContext context) {
action.accept(context);
}
}
}
@@ -0,0 +1,274 @@
package art.arcane.iris.pack.datapack.export.compile.cave;
import art.arcane.iris.generation.cave.IrisCaveFieldModule;
import art.arcane.iris.generation.cave.IrisCaveProfile;
import art.arcane.iris.generation.noise.IrisGeneratorStyle;
import art.arcane.iris.generation.noise.IrisStyledRange;
import art.arcane.iris.generation.noise.NoiseStyle;
import art.arcane.iris.pack.datapack.DataVersion;
import art.arcane.iris.pack.datapack.export.ExportTestPacks;
import art.arcane.iris.pack.datapack.export.compile.DimensionStage;
import art.arcane.iris.pack.datapack.export.compile.PackCompileContext;
import art.arcane.iris.pack.datapack.export.compile.biome.BiomeCodes;
import art.arcane.iris.pack.datapack.export.compile.noise.NoiseRegistry;
import art.arcane.iris.pack.datapack.export.compile.noise.StyleCompiler;
import art.arcane.iris.pack.datapack.export.ir.Axis;
import art.arcane.iris.pack.datapack.export.ir.ClimateLayout;
import art.arcane.iris.pack.datapack.export.ir.Field;
import art.arcane.iris.pack.datapack.export.ir.FieldEvaluator;
import art.arcane.iris.pack.datapack.export.ir.NoiseDef;
import art.arcane.iris.pack.loading.IrisData;
import art.arcane.iris.pack.value.IrisRange;
import art.arcane.iris.testsupport.CompatTestPlatform;
import art.arcane.volmlib.util.collection.KList;
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.IdentityHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
final class CaveTestPacks {
static final String NAMESPACE = "iris_export";
static final String SURFACE_BIOME = "surface";
static final long SEED = 1337L;
static final int MIN_Y = -64;
static final int MAX_Y = 192;
private static final Gson GSON = new Gson();
private CaveTestPacks() {
}
static JsonObject dimension(int lavaHeight) {
JsonObject height = new JsonObject();
height.addProperty("min", MIN_Y);
height.addProperty("max", MAX_Y);
JsonArray regions = new JsonArray();
regions.add("region");
JsonObject dimension = new JsonObject();
dimension.add("regions", regions);
dimension.add("dimensionHeight", height);
dimension.addProperty("fluidHeight", 63);
dimension.addProperty("caveLavaHeight", lavaHeight);
return dimension;
}
static JsonObject band(String id, String biome, int min, int max) {
JsonObject range = new JsonObject();
range.addProperty("min", min);
range.addProperty("max", max);
JsonObject entry = new JsonObject();
entry.addProperty("id", id);
entry.addProperty("biome", biome);
entry.add("worldYRange", range);
return entry;
}
static JsonObject region(List<String> caveBiomes, IrisCaveProfile profile) {
JsonArray surface = new JsonArray();
surface.add(SURFACE_BIOME);
JsonArray caves = new JsonArray();
for (String key : caveBiomes) {
caves.add(key);
}
JsonObject region = new JsonObject();
region.add("landBiomes", surface);
region.add("seaBiomes", surface.deepCopy());
region.add("caveBiomes", caves);
if (profile != null) {
region.add("caveProfile", GSON.toJsonTree(profile));
}
return region;
}
static File pack(File folder, JsonObject dimension, JsonObject region, Map<String, IrisCaveProfile> biomes) throws IOException {
CompatTestPlatform.write(folder, "dimensions/" + ExportTestPacks.DIMENSION + ".json", GSON.toJson(dimension));
CompatTestPlatform.write(folder, "regions/region.json", GSON.toJson(region));
CompatTestPlatform.write(folder, "biomes/" + SURFACE_BIOME + ".json", "{\"name\":\"Surface\"}");
for (Map.Entry<String, IrisCaveProfile> entry : new TreeMap<>(biomes).entrySet()) {
JsonObject biome = new JsonObject();
biome.addProperty("name", entry.getKey());
biome.add("caveProfile", GSON.toJsonTree(entry.getValue()));
CompatTestPlatform.write(folder, "biomes/" + entry.getKey() + ".json", GSON.toJson(biome));
}
return folder;
}
static JsonElement json(IrisCaveProfile profile) {
return GSON.toJsonTree(profile);
}
static IrisCaveProfile profile() {
return new IrisCaveProfile()
.setEnabled(true)
.setVerticalRange(new IrisRange(0, MAX_Y - MIN_Y))
.setVerticalEdgeFade(0)
.setBaseDensityStyle(style(NoiseStyle.SIMPLEX, 0.6))
.setDetailDensityStyle(style(NoiseStyle.SIMPLEX, 0.3))
.setBaseWeight(1.0)
.setDetailWeight(0.0)
.setDensityThreshold(new IrisStyledRange(0.0, 0.0, style(NoiseStyle.SIMPLEX, 1.0)))
.setThresholdBias(0.0)
.setSurfaceClearance(0)
.setAllowSurfaceBreak(false)
.setAllowFluid(false)
.setAllowLava(false)
.setModules(new KList<>());
}
static IrisCaveProfile constantProfile(double threshold) {
return profile().setDensityThreshold(new IrisStyledRange(threshold, threshold, style(NoiseStyle.SIMPLEX, 1.0)));
}
static IrisCaveFieldModule module(NoiseStyle style, double weight, double threshold, boolean invert, IrisRange range) {
return new IrisCaveFieldModule()
.setStyle(style(style, 0.5))
.setWeight(weight)
.setThreshold(threshold)
.setInvert(invert)
.setVerticalRange(range);
}
static IrisGeneratorStyle style(NoiseStyle style, double zoom) {
return new IrisGeneratorStyle(style).zoomed(zoom);
}
static PackCompileContext context(IrisData data, StyleCompiler styles) {
PackCompileContext context = ExportTestPacks.contextBuilder(data, DataVersion.V26_3).styles(styles).build();
new DimensionStage().apply(context);
return context;
}
static BiomeCodes codes(Field caveCode, List<CodeRange> ranges) {
List<ClimateLayout.ClimateEntry> entries = new ArrayList<>();
Map<String, String> loadKeys = new TreeMap<>();
String surfaceId = NAMESPACE + ":" + SURFACE_BIOME;
entries.add(new ClimateLayout.ClimateEntry(surfaceId, ClimateLayout.ClimateAxis.TEMPERATURE, -1.0, 1.0));
loadKeys.put(surfaceId, SURFACE_BIOME);
for (CodeRange range : ranges) {
String id = NAMESPACE + ":" + range.loadKey();
entries.add(new ClimateLayout.ClimateEntry(id, ClimateLayout.ClimateAxis.DEPTH, range.min(), range.max()));
loadKeys.put(id, range.loadKey());
}
Field zero = new Field.Const(0.0);
return new BiomeCodes(zero, caveCode, zero, new ClimateLayout(entries), loadKeys);
}
static Field xGradient() {
return new Field.Coord(Axis.X, Field.Tiling.CLAMP, -1000, 1000, -1.0, 1.0);
}
static Map<String, NoiseDef> noises(NoiseRegistry registry) {
Map<String, NoiseDef> noises = new TreeMap<>();
for (NoiseDef definition : registry.definitions()) {
noises.put(registry.namespace() + ":" + definition.id(), definition);
}
return noises;
}
static double sample(Field field, NoiseRegistry registry, int x, int y, int z) {
return FieldEvaluator.sample(field, noises(registry), SEED, DataVersion.V26_3, x, y, z);
}
static List<Field> children(Field field) {
List<Field> children = new ArrayList<>();
switch (field) {
case Field.Const ignored -> {
}
case Field.Coord ignored -> {
}
case Field.Ref ignored -> {
}
case Field.Noise noise -> {
addPresent(children, noise.shiftX());
addPresent(children, noise.shiftY());
addPresent(children, noise.shiftZ());
}
case Field.Binary binary -> {
children.add(binary.left());
children.add(binary.right());
}
case Field.Unary unary -> children.add(unary.input());
case Field.Clamp clamp -> children.add(clamp.input());
case Field.Lerp lerp -> children.addAll(List.of(lerp.alpha(), lerp.first(), lerp.second()));
case Field.Round round -> children.addAll(List.of(round.input(), round.multiple()));
case Field.Curve curve -> {
children.add(curve.input());
for (Field.Knot knot : curve.knots()) {
children.add(knot.value());
}
}
case Field.Partition partition -> {
children.add(partition.input());
children.addAll(partition.leaves());
}
case Field.Mux mux -> {
children.add(mux.index());
children.addAll(mux.cases());
}
case Field.Gate gate -> children.addAll(List.of(gate.condition(), gate.expr()));
case Field.RangeIf rangeIf -> children.addAll(List.of(rangeIf.input(), rangeIf.inRange(), rangeIf.outOfRange()));
case Field.Grid grid -> children.add(grid.expr());
case Field.Shared shared -> children.add(shared.expr());
case Field.Slice slice -> children.add(slice.expr());
case Field.TopSurface topSurface -> children.add(topSurface.density());
}
return children;
}
static List<Field> eagerChildren(Field field) {
return switch (field) {
case Field.Partition partition -> {
List<Field> children = new ArrayList<>();
children.add(partition.input());
children.addAll(partition.leaves());
yield children;
}
case Field.RangeIf rangeIf -> List.of(rangeIf.input(), rangeIf.inRange(), rangeIf.outOfRange());
case Field.Binary binary when binary.op() == Field.BinaryOp.MUL -> List.of(binary.left(), binary.right());
case Field.Lerp lerp -> List.of(lerp.alpha(), lerp.first(), lerp.second());
default -> List.of();
};
}
static Field caveField(Field caves) {
Field field = caves instanceof Field.Binary binary && binary.op() == Field.BinaryOp.MAX ? binary.left() : caves;
if (field instanceof Field.Shared shared && shared.name().equals(DeepCaveCompiler.FIELD)) {
return shared.expr();
}
return caves;
}
static List<Field> nodes(Field root) {
Set<Field> seen = Collections.newSetFromMap(new IdentityHashMap<>());
List<Field> nodes = new ArrayList<>();
List<Field> pending = new ArrayList<>();
pending.add(root);
while (!pending.isEmpty()) {
Field next = pending.removeLast();
if (!seen.add(next)) {
continue;
}
nodes.add(next);
pending.addAll(children(next));
}
return nodes;
}
private static void addPresent(List<Field> children, Field field) {
if (field != null) {
children.add(field);
}
}
record CodeRange(String loadKey, double min, double max) {
}
}
@@ -0,0 +1,131 @@
package art.arcane.iris.pack.datapack.export.compile.cave;
import art.arcane.iris.generation.cave.IrisCaveProfile;
import art.arcane.iris.pack.datapack.DataVersion;
import art.arcane.iris.pack.datapack.export.ExportTestPacks;
import art.arcane.iris.pack.datapack.export.compile.DimensionStage;
import art.arcane.iris.pack.datapack.export.compile.PackCompileContext;
import art.arcane.iris.pack.datapack.export.ir.CostClass;
import art.arcane.iris.pack.datapack.export.ir.ExportDiagnostic;
import art.arcane.iris.pack.datapack.export.ir.ExportLimit;
import art.arcane.iris.pack.datapack.export.ir.Field;
import art.arcane.iris.pack.loading.IrisData;
import art.arcane.iris.testsupport.PlatformLeakGuard;
import org.junit.ClassRule;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import java.io.File;
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.assertSame;
import static org.junit.Assert.assertTrue;
public class DeepCaveCompilerTest {
private static final Field SURFACE = new Field.Const(150.0);
private static final int LAVA_HEIGHT = 2;
private static final int LAVA_Y = CaveTestPacks.MIN_Y + LAVA_HEIGHT;
private static final int ZONE_Y = -58;
private static final int ABOVE_LINE_Y = -40;
@ClassRule
public static final PlatformLeakGuard PLATFORM_GUARD = PlatformLeakGuard.clean();
@Rule
public TemporaryFolder temporaryFolder = new TemporaryFolder();
@Rule
public ExportTestPacks.BoundPlatform platform = new ExportTestPacks.BoundPlatform();
@Test
public void deepCavesStaySolidInFinalDensityAndOpenThroughTheMaterialPass() throws Exception {
PackCompileContext context = compile(CaveTestPacks.constantProfile(5.0).setAllowLava(true), LAVA_HEIGHT, DataVersion.V26_3);
Field opening = context.deepCaves().orElseThrow();
assertTrue(sample(context, context.caves(), ZONE_Y) > 0.0);
assertTrue(sample(context, context.caves(), DeepCaveCompiler.LAVA_LINE - 1) > 0.0);
assertTrue(sample(context, context.caves(), DeepCaveCompiler.LAVA_LINE) <= 0.0);
assertTrue(sample(context, context.caves(), ABOVE_LINE_Y) <= 0.0);
assertTrue(sample(context, context.caves(), LAVA_Y) <= 0.0);
assertEquals(1.0, sample(context, opening, ZONE_Y), 0.0);
assertEquals(1.0, sample(context, opening, LAVA_Y + 1), 0.0);
assertEquals(0.0, sample(context, opening, DeepCaveCompiler.LAVA_LINE), 0.0);
assertEquals(0.0, sample(context, opening, ABOVE_LINE_Y), 0.0);
assertEquals(0.0, sample(context, opening, LAVA_Y), 0.0);
assertTrue(has(context, ExportLimit.DEEP_CAVE_LAYERS));
}
@Test
public void solidDeepRockStaysClosed() throws Exception {
PackCompileContext context = compile(CaveTestPacks.constantProfile(-5.0).setAllowLava(true), LAVA_HEIGHT, DataVersion.V26_3);
Field opening = context.deepCaves().orElseThrow();
assertEquals(0.0, sample(context, opening, ZONE_Y), 0.0);
assertTrue(sample(context, context.caves(), ZONE_Y) > 0.0);
}
@Test
public void lavaFreeCavesOpenDownToTheFloor() throws Exception {
PackCompileContext context = compile(CaveTestPacks.constantProfile(5.0), LAVA_HEIGHT, DataVersion.V26_3);
Field opening = context.deepCaves().orElseThrow();
assertEquals(1.0, sample(context, opening, CaveTestPacks.MIN_Y), 0.0);
assertTrue(sample(context, context.caves(), CaveTestPacks.MIN_Y) > 0.0);
}
@Test
public void lavaAboveTheLineLeavesCavesUnchanged() throws Exception {
PackCompileContext context = compile(CaveTestPacks.constantProfile(5.0).setAllowLava(true), 20, DataVersion.V26_3);
assertTrue(context.deepCaves().isEmpty());
assertSame(context.caveField().orElseThrow(), context.caves());
assertTrue(CaveTestPacks.caveField(context.caves()) instanceof Field.Grid);
assertFalse(has(context, ExportLimit.DEEP_CAVE_LAYERS));
}
@Test
public void expensiveCavesNeverSitUnderEagerNodes() throws Exception {
PackCompileContext context = compile(CaveTestPacks.constantProfile(5.0).setAllowLava(true), LAVA_HEIGHT, DataVersion.V26_3);
for (Field root : List.of(context.caves(), context.deepCaves().orElseThrow())) {
for (Field node : CaveTestPacks.nodes(root)) {
for (Field child : CaveTestPacks.eagerChildren(node)) {
assertTrue(node.getClass().getSimpleName() + " evaluates an expensive child eagerly", child.cost() != CostClass.EXPENSIVE);
}
}
}
}
private PackCompileContext compile(IrisCaveProfile profile, int lavaHeight, DataVersion target) throws Exception {
File pack = CaveTestPacks.pack(temporaryFolder.newFolder("pack"), CaveTestPacks.dimension(lavaHeight),
CaveTestPacks.region(List.of("cave-deep"), null), Map.of("cave-deep", profile));
IrisData data = IrisData.openRuntime(pack);
try {
PackCompileContext context = ExportTestPacks.contextBuilder(data, target).styles(FakeCaveStyles.volumetric()).build();
new DimensionStage().apply(context);
context.setHeight(SURFACE);
context.setBiomeCodes(CaveTestPacks.codes(CaveTestPacks.xGradient(), List.of(new CaveTestPacks.CodeRange("cave-deep", -1.0, 1.0))));
new CaveStage().apply(context);
return context;
} finally {
data.close();
}
}
private static double sample(PackCompileContext context, Field field, int y) {
return CaveTestPacks.sample(field, context.noises(), 40, y, 40);
}
private static boolean has(PackCompileContext context, ExportLimit limit) {
for (ExportDiagnostic diagnostic : context.diagnostics()) {
if (diagnostic.limit() == limit) {
return true;
}
}
return false;
}
}
@@ -0,0 +1,84 @@
package art.arcane.iris.pack.datapack.export.compile.cave;
import art.arcane.iris.generation.noise.IrisGeneratorStyle;
import art.arcane.iris.generation.noise.NoiseStyle;
import art.arcane.iris.pack.datapack.export.compile.noise.NoiseRegistry;
import art.arcane.iris.pack.datapack.export.compile.noise.StyleCompiler;
import art.arcane.iris.pack.datapack.export.ir.Axis;
import art.arcane.iris.pack.datapack.export.ir.Field;
import art.arcane.iris.pack.datapack.export.ir.NoiseDef;
import art.arcane.iris.pack.datapack.export.lower.ExportCapabilities;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
final class FakeCaveStyles implements StyleCompiler {
static final String CELLULAR_PREFIX = "cave_test/cellular/";
private static final String SMOOTH_PREFIX = "cave_test/smooth/";
private static final String WARP_PREFIX = "cave_test/warp/";
private static final double BLOCKS_PER_ZOOM = 64.0;
private static final List<Double> SINGLE_OCTAVE = List.of(1.0);
private final Mode mode;
private final List<NoiseStyle> requests = new ArrayList<>();
private FakeCaveStyles(Mode mode) {
this.mode = mode;
}
static FakeCaveStyles volumetric() {
return new FakeCaveStyles(Mode.VOLUMETRIC);
}
static FakeCaveStyles planar() {
return new FakeCaveStyles(Mode.PLANAR);
}
static FakeCaveStyles expensiveCellular() {
return new FakeCaveStyles(Mode.EXPENSIVE_CELLULAR);
}
static FakeCaveStyles expensive() {
return new FakeCaveStyles(Mode.EXPENSIVE);
}
static boolean cellular(NoiseStyle style) {
String name = style.name();
return name.contains("CELL") || name.contains("VASCULAR") || name.contains("GLOB") || name.contains("HEX");
}
static Field unit(Field signed) {
return new Field.Curve(signed, List.of(
new Field.Knot(-1.0, new Field.Const(0.0), 0.5),
new Field.Knot(1.0, new Field.Const(1.0), 0.5)));
}
List<NoiseStyle> requests() {
return List.copyOf(requests);
}
@Override
public Field compile(IrisGeneratorStyle style, long seedSalt, NoiseRegistry registry, ExportCapabilities capabilities) {
NoiseStyle noiseStyle = style.getStyle();
requests.add(noiseStyle);
boolean cellular = cellular(noiseStyle);
if (cellular && mode == Mode.PLANAR) {
return new Field.Coord(Axis.X, Field.Tiling.REPEAT, 0, 64, 0, 1);
}
String key = noiseStyle.name().toLowerCase(Locale.ROOT) + "_" + seedSalt;
double scale = 1.0 / (BLOCKS_PER_ZOOM * style.getZoom());
double yScale = mode == Mode.PLANAR ? 0.0 : scale;
boolean warped = mode == Mode.EXPENSIVE || cellular && mode == Mode.EXPENSIVE_CELLULAR;
Field shift = warped ? new Field.Noise(registry.register(new NoiseDef(WARP_PREFIX + key, 0, SINGLE_OCTAVE)), scale, yScale, null, null, null) : null;
String id = registry.register(new NoiseDef((cellular ? CELLULAR_PREFIX : SMOOTH_PREFIX) + key, 0, SINGLE_OCTAVE));
return unit(new Field.Noise(id, scale, yScale, shift, null, shift));
}
private enum Mode {
VOLUMETRIC,
PLANAR,
EXPENSIVE_CELLULAR,
EXPENSIVE
}
}
@@ -0,0 +1,159 @@
package art.arcane.iris.pack.datapack.export.compile.cave;
import art.arcane.iris.generation.cave.IrisCaveFieldModule;
import art.arcane.iris.generation.cave.IrisCaveProfile;
import art.arcane.iris.generation.noise.IrisStyledRange;
import art.arcane.iris.pack.datapack.export.compile.noise.NoiseRegistry;
import art.arcane.iris.pack.datapack.export.compile.noise.StyleCompiler;
import art.arcane.iris.pack.datapack.export.ir.Field;
import art.arcane.iris.pack.datapack.export.lower.ExportCapabilities;
import art.arcane.iris.pack.value.IrisRange;
import java.util.ArrayList;
import java.util.List;
final class IrisCaveReference {
private static final long BASE_SALT = 934_447L;
private static final long DETAIL_SALT = 612_991L;
private static final long THRESHOLD_SALT = 489_112L;
private static final long SURFACE_BREAK_SALT = 341_219L;
private static final long MODULE_SALT = 1_000_003L;
private static final long MODULE_SALT_STEP = 65_537L;
private static final int CEILING_FADE_DEPTH = 12;
private static final double CLOSURE_EPSILON = 0.000001D;
private final IrisCaveProfile profile;
private final NoiseRegistry registry;
private final Field height;
private final Field base;
private final Field detail;
private final List<Field> modules;
private final Field threshold;
private final Field surfaceBreak;
private final int worldMinY;
private final int worldHeight;
private final double normalization;
IrisCaveReference(IrisCaveProfile profile, StyleCompiler styles, NoiseRegistry registry, ExportCapabilities capabilities, Field height) {
this.profile = profile;
this.registry = registry;
this.height = height;
this.worldMinY = CaveTestPacks.MIN_Y;
this.worldHeight = CaveTestPacks.MAX_Y - CaveTestPacks.MIN_Y;
base = styles.compile(profile.getBaseDensityStyle(), BASE_SALT, registry, capabilities);
detail = styles.compile(profile.getDetailDensityStyle(), DETAIL_SALT, registry, capabilities);
modules = new ArrayList<>();
double weight = Math.abs(profile.getBaseWeight()) + Math.abs(profile.getDetailWeight());
for (int index = 0; index < profile.getModules().size(); index++) {
IrisCaveFieldModule module = profile.getModules().get(index);
modules.add(styles.compile(module.getStyle(), MODULE_SALT + index * MODULE_SALT_STEP, registry, capabilities));
weight += Math.abs(module.getWeight());
}
normalization = weight <= 0 ? 1D : weight;
IrisStyledRange range = profile.getDensityThreshold();
threshold = range.getMin() == range.getMax() || range.getStyle().isFlat() ? null
: styles.compile(range.getStyle(), THRESHOLD_SALT, registry, capabilities);
surfaceBreak = profile.isAllowSurfaceBreak() ? styles.compile(profile.getSurfaceBreakStyle(), SURFACE_BREAK_SALT, registry, capabilities) : null;
}
boolean carved(int x, int worldY, int z) {
int y = worldY - worldMinY;
IrisRange range = profile.getVerticalRange();
int minY = Math.max(0, (int) Math.floor(range.getMin()));
int maxY = Math.min(worldHeight - 1, (int) Math.ceil(range.getMax()));
if (y < minY || y > maxY) {
return false;
}
int surface = (int) Math.round(sample(height, x, 0, z)) - worldMinY;
int unclampedClearanceTop = surface - Math.max(0, profile.getSurfaceClearance());
int clearanceTop = Math.min(maxY, Math.max(minY, unclampedClearanceTop));
boolean breakColumn = surfaceBreak != null && signed(sample(surfaceBreak, x, 0, z)) >= profile.getSurfaceBreakNoiseThreshold();
int columnTop = breakColumn ? Math.min(maxY, Math.max(minY, surface)) : clearanceTop;
if (y > columnTop) {
return false;
}
double local = columnThreshold(x, z) - profile.getThresholdBias();
if (breakColumn && y >= Math.max(minY, surface - Math.max(0, profile.getSurfaceBreakDepth()))) {
local += Math.max(0, profile.getSurfaceBreakThresholdBoost());
}
local -= edgeFade(y, minY, maxY);
if (!breakColumn && unclampedClearanceTop <= maxY) {
int distance = columnTop - y;
double closure = closure(y);
if (distance >= 0 && distance < CEILING_FADE_DEPTH && local > closure) {
double progress = distance / (double) CEILING_FADE_DEPTH;
double smooth = progress * progress * (3D - (2D * progress));
local = closure + ((local - closure) * smooth);
}
}
return density(x, worldY, z) <= local;
}
private double columnThreshold(int x, int z) {
IrisStyledRange range = profile.getDensityThreshold();
if (range.getMin() == range.getMax()) {
return range.getMin();
}
if (threshold == null) {
return range.getMin() + (range.getMax() - range.getMin()) * 0.5;
}
return range.getMin() + (range.getMax() - range.getMin()) * sample(threshold, x, 0, z);
}
private double density(int x, int worldY, int z) {
int y = worldY - worldMinY;
double density = signed(sample(base, x, worldY, z)) * profile.getBaseWeight();
density += signed(sample(detail, x, worldY, z)) * profile.getDetailWeight();
for (int index = 0; index < modules.size(); index++) {
IrisCaveFieldModule module = profile.getModules().get(index);
if (!active(module, y)) {
continue;
}
double moduleDensity = signed(sample(modules.get(index), x, worldY, z)) - module.getThreshold();
if (module.isInvert()) {
moduleDensity = -moduleDensity;
}
density += moduleDensity * module.getWeight();
}
return density / normalization;
}
private double closure(int y) {
double minimum = -Math.abs(profile.getBaseWeight()) - Math.abs(profile.getDetailWeight());
for (IrisCaveFieldModule module : profile.getModules()) {
if (!active(module, y)) {
continue;
}
double rawMin = module.isInvert() ? module.getThreshold() - 1D : -1D - module.getThreshold();
double rawMax = module.isInvert() ? module.getThreshold() + 1D : 1D - module.getThreshold();
minimum += Math.min(rawMin * module.getWeight(), rawMax * module.getWeight());
}
return minimum / normalization - CLOSURE_EPSILON;
}
private double edgeFade(int y, int minY, int maxY) {
int fadeRange = Math.max(0, profile.getVerticalEdgeFade());
double strength = Math.max(0D, profile.getVerticalEdgeFadeStrength());
if (fadeRange <= 0 || maxY <= minY || strength <= 0D) {
return 0D;
}
int edgeDistance = Math.min(y - minY, maxY - y);
if (edgeDistance >= fadeRange) {
return 0D;
}
double t = Math.max(0D, Math.min(1D, edgeDistance / (double) fadeRange));
return (1D - t * t * (3D - (2D * t))) * strength;
}
private static boolean active(IrisCaveFieldModule module, int y) {
return y >= (int) Math.floor(module.getVerticalRange().getMin()) && y <= (int) Math.ceil(module.getVerticalRange().getMax());
}
private double sample(Field field, int x, int y, int z) {
return CaveTestPacks.sample(field, registry, x, y, z);
}
private static double signed(double unit) {
return unit * 2D - 1D;
}
}
@@ -0,0 +1,47 @@
package art.arcane.iris.pack.datapack.export.compile.cave;
import art.arcane.iris.pack.datapack.DataVersion;
import art.arcane.iris.pack.datapack.export.ir.Axis;
import art.arcane.iris.pack.datapack.export.ir.Field;
import org.junit.Test;
import java.util.Map;
import static org.junit.Assert.assertEquals;
public class WallShellCalibratorTest {
private static final int MIN_Y = -64;
private static final int MAX_Y = 64;
@Test
public void bandHoldsTheOneBlockHorizontalWall() {
double band = WallShellCalibrator.band(new CaveInterior(ridges(0.4), MIN_Y, MAX_Y), Map.of(), DataVersion.V26_3);
assertEquals(0.1, band, 1.0e-6);
}
@Test
public void bandScalesWithTheFieldGradient() {
double band = WallShellCalibrator.band(new CaveInterior(ridges(1.2), MIN_Y, MAX_Y), Map.of(), DataVersion.V26_3);
assertEquals(0.3, band, 1.0e-6);
}
@Test
public void fieldsWithoutCavesHaveAnEmptyBand() {
double band = WallShellCalibrator.band(new CaveInterior(new Field.Const(1.0), MIN_Y, MAX_Y), Map.of(), DataVersion.V26_3);
assertEquals(0.0, band, 0.0);
}
@Test
public void calibrationIsDeterministic() {
CaveInterior interior = new CaveInterior(ridges(1.2), 0, 40);
assertEquals(WallShellCalibrator.band(interior, Map.of(), DataVersion.V26_3), WallShellCalibrator.band(interior, Map.of(), DataVersion.V26_3), 0.0);
}
private static Field ridges(double amplitude) {
return new Field.Coord(Axis.X, Field.Tiling.MIRRORED_REPEAT, 0.0, 8.0, -amplitude, amplitude);
}
}
@@ -0,0 +1,106 @@
package art.arcane.iris.pack.datapack.export.compile.decoration;
import art.arcane.iris.pack.datapack.export.ir.BiomeDef;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import org.junit.Test;
import java.util.ArrayList;
import java.util.List;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertThrows;
public class BiomeFeatureListsTest {
private static final String NAMESPACE = "iris_export";
@Test
public void globalOrderIsSharedAcrossBiomes() {
BiomeFeatureLists lists = new BiomeFeatureLists();
lists.add("iris_export:plains", GenerationStep.VEGETAL_DECORATION, "iris_export:grass");
lists.add("iris_export:plains", GenerationStep.VEGETAL_DECORATION, "iris_export:flowers");
lists.add("iris_export:forest", GenerationStep.VEGETAL_DECORATION, "iris_export:flowers");
lists.add("iris_export:forest", GenerationStep.VEGETAL_DECORATION, "iris_export:grass");
List<BiomeDef> biomes = lists.apply(List.of(biome("plains"), biome("forest")), NAMESPACE);
List<String> expected = List.of("iris_export:grass", "iris_export:flowers");
assertEquals(expected, step(biomes.get(0), GenerationStep.VEGETAL_DECORATION));
assertEquals(expected, step(biomes.get(1), GenerationStep.VEGETAL_DECORATION));
}
@Test
public void biomeListIsFilteredGlobalOrder() {
BiomeFeatureLists lists = new BiomeFeatureLists();
lists.add("iris_export:plains", GenerationStep.UNDERGROUND_ORES, "iris_export:coal");
lists.add("iris_export:desert", GenerationStep.UNDERGROUND_ORES, "iris_export:gold");
lists.add("iris_export:plains", GenerationStep.UNDERGROUND_ORES, "minecraft:ore_iron");
lists.add("iris_export:desert", GenerationStep.UNDERGROUND_ORES, "minecraft:ore_iron");
lists.add("iris_export:desert", GenerationStep.UNDERGROUND_ORES, "iris_export:coal");
List<BiomeDef> biomes = lists.apply(List.of(biome("plains"), biome("desert")), NAMESPACE);
assertEquals(List.of("iris_export:coal", "minecraft:ore_iron"), step(biomes.get(0), GenerationStep.UNDERGROUND_ORES));
assertEquals(List.of("iris_export:coal", "iris_export:gold", "minecraft:ore_iron"), step(biomes.get(1), GenerationStep.UNDERGROUND_ORES));
assertEquals(List.of(), step(biomes.get(0), GenerationStep.VEGETAL_DECORATION));
}
@Test
public void duplicateAddIsNoOp() {
BiomeFeatureLists lists = new BiomeFeatureLists();
lists.add("iris_export:plains", GenerationStep.LAKES, "iris_export:pond");
lists.add("iris_export:plains", GenerationStep.LAKES, "iris_export:pond");
lists.add("iris_export:plains", GenerationStep.FLUID_SPRINGS, "iris_export:pond");
BiomeDef biome = lists.apply(List.of(biome("plains")), NAMESPACE).getFirst();
assertEquals(List.of("iris_export:pond"), step(biome, GenerationStep.LAKES));
assertEquals(List.of("iris_export:pond"), step(biome, GenerationStep.FLUID_SPRINGS));
}
@Test
public void elevenStepArraysAlwaysWritten() {
BiomeFeatureLists lists = new BiomeFeatureLists();
lists.add("iris_export:plains", GenerationStep.TOP_LAYER_MODIFICATION, "minecraft:freeze_top_layer");
BiomeDef source = biome("desert");
List<BiomeDef> biomes = lists.apply(List.of(biome("plains"), source), NAMESPACE);
assertEquals(11, GenerationStep.values().length);
assertEquals(GenerationStep.TOP_LAYER_MODIFICATION, GenerationStep.values()[10]);
JsonArray empty = new JsonArray();
for (int index = 0; index < 11; index++) {
empty.add(new JsonArray());
}
assertEquals(empty, biomes.get(1).json().get("features"));
assertEquals(11, biomes.get(0).json().getAsJsonArray("features").size());
assertEquals(List.of("minecraft:freeze_top_layer"), step(biomes.get(0), GenerationStep.TOP_LAYER_MODIFICATION));
assertEquals(0.8, biomes.get(1).json().get("temperature").getAsDouble(), 0.0);
assertEquals(0, source.json().getAsJsonArray("features").size());
}
@Test
public void featureForUndefinedBiomeIsRejected() {
BiomeFeatureLists lists = new BiomeFeatureLists();
lists.add("iris_export:swamp", GenerationStep.LAKES, "iris_export:pond");
IllegalArgumentException error = assertThrows(IllegalArgumentException.class, () -> lists.apply(List.of(biome("plains")), NAMESPACE));
assertEquals("Feature lists reference undefined biome 'iris_export:swamp'", error.getMessage());
}
private static BiomeDef biome(String id) {
JsonObject json = JsonParser.parseString("{\"temperature\":0.8,\"features\":[]}").getAsJsonObject();
return new BiomeDef(id, json);
}
private static List<String> step(BiomeDef biome, GenerationStep step) {
JsonArray features = biome.json().getAsJsonArray("features").get(step.ordinal()).getAsJsonArray();
List<String> ids = new ArrayList<>(features.size());
for (int index = 0; index < features.size(); index++) {
ids.add(features.get(index).getAsString());
}
return ids;
}
}
@@ -0,0 +1,549 @@
package art.arcane.iris.pack.datapack.export.compile.decoration;
import art.arcane.iris.generation.noise.IrisGeneratorStyle;
import art.arcane.iris.pack.datapack.DataVersion;
import art.arcane.iris.pack.datapack.export.ExportTestPacks;
import art.arcane.iris.pack.datapack.export.compile.PackCompileContext;
import art.arcane.iris.pack.datapack.export.compile.StageTestPacks;
import art.arcane.iris.pack.datapack.export.compile.noise.VanillaNoiseModel;
import art.arcane.iris.pack.datapack.export.compile.surface.MaterialProgramCompiler;
import art.arcane.iris.pack.datapack.export.compile.surface.SurfaceStage;
import art.arcane.iris.pack.datapack.export.ir.BiomeDef;
import art.arcane.iris.pack.datapack.export.ir.ExportDiagnostic;
import art.arcane.iris.pack.datapack.export.ir.ExportLimit;
import art.arcane.iris.pack.datapack.export.ir.Field;
import art.arcane.iris.pack.datapack.export.ir.JsonResource;
import art.arcane.iris.pack.loading.IrisData;
import art.arcane.iris.testsupport.PlatformLeakGuard;
import art.arcane.volmlib.util.math.RNG;
import art.arcane.volmlib.util.noise.CNG;
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import org.junit.ClassRule;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.function.BiPredicate;
import java.util.function.Consumer;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
public class DecorationStageTest {
@ClassRule
public static final PlatformLeakGuard PLATFORM_GUARD = PlatformLeakGuard.clean();
private static final String DIMENSION = "{\"regions\":[\"region\"]}";
private static final Field.Shared CAVE_FIELD = new Field.Shared("cave/field", new Field.Const(1.0));
private static final String COAL = "{\"palette\":[{\"block\":\"coal_ore\"}],\"minHeight\":10,\"maxHeight\":40,\"heightDistribution\":\"UNIFORM\","
+ "\"minPerChunk\":2,\"maxPerChunk\":6,\"minSize\":4,\"maxSize\":12,\"shape\":\"VANILLA_ELLIPSOID\",\"surfaceClearance\":7}";
private static final String IRON = "{\"palette\":[{\"block\":\"iron_ore\"}],\"minHeight\":0,\"maxHeight\":64,\"heightDistribution\":\"TRIANGLE\","
+ "\"minPerChunk\":1,\"maxPerChunk\":3,\"minSize\":6,\"maxSize\":6,\"placementScope\":\"FULL_HEIGHT\"}";
@Rule
public TemporaryFolder temporaryFolder = new TemporaryFolder();
@Rule
public ExportTestPacks.BoundPlatform platform = new ExportTestPacks.BoundPlatform();
@Test
public void featureOrderIsGlobalAndAcyclic() throws Exception {
Map<String, String> biomes = new LinkedHashMap<>();
biomes.put("first", "{\"deposits\":[" + COAL + "," + IRON + "],\"decorators\":[" + decorator("short_grass", 0.2) + "," + decorator("fern", 0.1) + "]}");
biomes.put("second", "{\"deposits\":[" + IRON + "," + COAL + "],\"decorators\":[" + decorator("fern", 0.1) + "," + decorator("short_grass", 0.2) + "]}");
biomes.put("third", "{\"deposits\":[" + IRON + "],\"decorators\":[" + decorator("poppy", 0.05) + "]}");
Result result = decorate(biomes, DataVersion.V26_3, context -> {
});
Map<GenerationStep, List<List<String>>> perStep = new HashMap<>();
for (BiomeDef biome : result.biomes()) {
JsonArray steps = biome.json().getAsJsonArray("features");
assertEquals(GenerationStep.values().length, steps.size());
for (GenerationStep step : GenerationStep.values()) {
List<String> features = new ArrayList<>();
for (JsonElement feature : steps.get(step.ordinal()).getAsJsonArray()) {
features.add(feature.getAsString());
}
perStep.computeIfAbsent(step, ignored -> new ArrayList<>()).add(features);
}
}
for (Map.Entry<GenerationStep, List<List<String>>> step : perStep.entrySet()) {
Map<String, Integer> rank = new HashMap<>();
for (List<String> features : step.getValue()) {
for (int index = 0; index < features.size(); index++) {
for (int later = index + 1; later < features.size(); later++) {
String pair = features.get(later) + ">" + features.get(index);
assertFalse("cycle between " + features.get(index) + " and " + features.get(later), rank.containsKey(pair));
rank.put(features.get(index) + ">" + features.get(later), 1);
}
}
}
}
List<String> firstOres = perStep.get(GenerationStep.UNDERGROUND_ORES).get(0);
List<String> secondOres = perStep.get(GenerationStep.UNDERGROUND_ORES).get(1);
assertEquals(2, firstOres.size());
assertEquals(firstOres, secondOres);
for (List<List<String>> lists : perStep.values()) {
for (List<String> features : lists) {
for (String feature : features) {
assertTrue(feature, feature.startsWith(StageTestPacks.NAMESPACE + ":"));
}
}
}
}
@Test
public void duplicateDecoratorsShareOneFeature() throws Exception {
Map<String, String> biomes = new LinkedHashMap<>();
biomes.put("meadow", "{\"decorators\":[" + decorator("short_grass", 0.2) + "]}");
biomes.put("field", "{\"decorators\":[" + decorator("short_grass", 0.2) + "]}");
Result result = decorate(biomes, DataVersion.V26_3, context -> {
});
List<JsonResource> features = result.under("worldgen/feature/decorator/");
List<JsonResource> placed = result.under("worldgen/placed_feature/decorator/");
assertEquals(1, features.size());
assertEquals(1, placed.size());
assertEquals("data/iris_export/worldgen/feature/decorator/short_grass.json", features.getFirst().path());
String id = "iris_export:decorator/short_grass";
for (BiomeDef biome : result.biomes()) {
assertEquals(List.of(id), step(biome, GenerationStep.VEGETAL_DECORATION));
}
}
@Test
public void fractionalChanceUsesRandomChance() throws Exception {
Map<String, String> biomes = new LinkedHashMap<>();
biomes.put("meadow", "{\"decorators\":[" + decorator("short_grass", 0.3) + "]}");
Result modern = decorate(biomes, DataVersion.V26_3, context -> {
});
JsonObject placed = modern.under("worldgen/placed_feature/decorator/").getFirst().json().getAsJsonObject();
JsonArray placement = placed.getAsJsonArray("placement");
assertEquals("minecraft:cuboid", placement.get(0).getAsJsonObject().get("type").getAsString());
JsonObject chance = StageTestPacks.ofType(placement, "minecraft:random_chance").getFirst();
assertEquals(0.3f, chance.get("chance").getAsFloat(), 0.0f);
assertEquals("{\"type\":\"minecraft:simple_block\",\"to_place\":{\"id\":\"minecraft:short_grass\"}}",
modern.under("worldgen/feature/decorator/").getFirst().json().toString());
}
@Test
public void aquaticDecoratorsPlaceOnlyUnderwater() throws Exception {
Map<String, String> biomes = new LinkedHashMap<>();
biomes.put("reef", "{\"decorators\":[" + decorator("seagrass", 0.2) + ","
+ "{\"palette\":[{\"block\":\"kelp_plant\"}],\"chance\":0.02,\"stackMin\":2,\"stackMax\":6},"
+ "{\"palette\":[{\"block\":\"kelp_plant\"}],\"chance\":0.03,\"stackMin\":2,\"stackMax\":6,\"partOf\":\"SEA_FLOOR\"}]}");
Result result = decorate(biomes, DataVersion.V26_3, context -> {
});
List<JsonResource> placed = result.under("worldgen/placed_feature/decorator/");
assertEquals(3, placed.size());
for (JsonResource resource : placed) {
JsonArray placement = resource.json().getAsJsonObject().getAsJsonArray("placement");
assertEquals(resource.path(), Placements.OCEAN_FLOOR,
StageTestPacks.ofType(placement, "minecraft:heightmap").getFirst().get("heightmap").getAsString());
JsonObject filter = StageTestPacks.ofType(placement, "minecraft:block_predicate_filter").getLast();
assertFalse(resource.path(), StageTestPacks.ofType(filter, "minecraft:matching_fluids").isEmpty());
assertTrue(resource.path(), StageTestPacks.ofType(filter, "minecraft:matching_block_tag").isEmpty());
}
for (JsonResource resource : result.under("worldgen/feature/decorator/")) {
JsonObject feature = resource.json().getAsJsonObject();
if (feature.has("allowed_placement")) {
assertEquals(resource.path(), "minecraft:matching_fluids",
feature.getAsJsonObject("allowed_placement").get("type").getAsString());
}
}
}
@Test
public void shoreDecoratorsGrowOnSolidGroundBesideWater() throws Exception {
Map<String, String> biomes = new LinkedHashMap<>();
biomes.put("beach", "{\"decorators\":[{\"palette\":[{\"block\":\"sugar_cane\"}],\"partOf\":\"SHORE_LINE\",\"chance\":0.5,"
+ "\"stackMin\":1,\"stackMax\":4}]}");
Result result = decorate(biomes, DataVersion.V26_3, context -> {
});
JsonArray placement = result.under("worldgen/placed_feature/decorator/").getFirst().json().getAsJsonObject().getAsJsonArray("placement");
JsonObject filter = StageTestPacks.ofType(placement, "minecraft:block_predicate_filter").getLast();
List<String> supports = new ArrayList<>();
for (JsonObject solid : StageTestPacks.ofType(filter, "minecraft:solid")) {
supports.add(solid.get("offset").toString());
}
assertEquals(List.of("[0,-1,0]"), supports);
assertEquals(4, StageTestPacks.ofType(filter, "minecraft:matching_fluids").size());
}
@Test
public void tallPlantsPlaceBothHalves() throws Exception {
Map<String, String> biomes = new LinkedHashMap<>();
biomes.put("reef", "{\"decorators\":[{\"palette\":[{\"block\":\"tall_seagrass\",\"data\":{\"half\":\"lower\"}}],"
+ "\"topPalette\":[{\"block\":\"tall_seagrass\",\"data\":{\"half\":\"upper\"}}],\"partOf\":\"SEA_FLOOR\",\"chance\":0.2}]}");
Result result = decorate(biomes, DataVersion.V26_3, context -> {
});
JsonObject feature = result.under("worldgen/feature/decorator/").getFirst().json().getAsJsonObject();
assertEquals(feature.toString(), "minecraft:simple_block", feature.get("type").getAsString());
assertEquals("{\"id\":\"minecraft:tall_seagrass\",\"properties\":{\"half\":\"lower\"}}", feature.get("to_place").toString());
JsonArray placement = result.under("worldgen/placed_feature/decorator/").getFirst().json().getAsJsonObject().getAsJsonArray("placement");
List<String> water = new ArrayList<>();
for (JsonObject fluid : StageTestPacks.ofType(placement, "minecraft:matching_fluids")) {
water.add(fluid.has("offset") ? fluid.get("offset").toString() : "[0,0,0]");
}
assertEquals(List.of("[0,0,0]", "[0,1,0]"), water);
}
@Test
public void waterlogFollowsWhereTheDecoratorPlaces() throws Exception {
Map<String, String> biomes = new LinkedHashMap<>();
biomes.put("reef", "{\"decorators\":[" + decorator("sea_pickle[pickles=2,waterlogged=false]", 0.2) + ","
+ "{\"palette\":[{\"block\":\"oak_stairs[waterlogged=true]\"},{\"block\":\"short_grass\"}],\"chance\":0.1}]}");
Result result = decorate(biomes, DataVersion.V26_3, context -> {
});
String pickles = result.resource("data/iris_export/worldgen/feature/decorator/sea_pickle.json").toString();
String stairs = result.resource("data/iris_export/worldgen/feature/decorator/oak_stairs.json").toString();
assertTrue(pickles, pickles.contains("\"waterlogged\":\"true\""));
assertTrue(stairs, stairs.contains("\"waterlogged\":\"false\""));
}
@Test
public void paletteEndsCarryHalfWeightLikeIrisRounding() throws Exception {
Map<String, String> biomes = new LinkedHashMap<>();
biomes.put("meadow", "{\"decorators\":[{\"palette\":[{\"block\":\"bush\"},{\"block\":\"air\",\"weight\":4}],\"chance\":0.5},"
+ "{\"palette\":[{\"block\":\"fern\",\"weight\":2},{\"block\":\"short_grass\",\"weight\":3}],\"chance\":0.2,\"partOf\":\"SHORE_LINE\"}]}");
Result result = decorate(biomes, DataVersion.V26_3, context -> {
});
JsonArray placement = placement(result, "data/iris_export/worldgen/placed_feature/decorator/bush.json");
assertEquals(0.5 / 8.0, StageTestPacks.ofType(placement, "minecraft:random_chance").getFirst().get("chance").getAsDouble(), 1.0e-6);
JsonArray weighted = result.resource("data/iris_export/worldgen/feature/decorator/fern.json").getAsJsonObject()
.getAsJsonObject("to_place").getAsJsonArray("entries");
assertEquals(3, weighted.get(0).getAsJsonObject().get("weight").getAsInt());
assertEquals(5, weighted.get(1).getAsJsonObject().get("weight").getAsInt());
}
@Test
public void styledDecoratorPlacesAtStyleCoverage() throws Exception {
String style = "{\"style\":\"SIMPLEX\",\"zoom\":0.2,\"fracture\":{\"style\":\"STATIC\",\"multiplier\":8}}";
Map<String, String> biomes = new LinkedHashMap<>();
biomes.put("meadow", "{\"decorators\":[{\"palette\":[{\"block\":\"poppy\"}],\"chance\":0.2,\"style\":" + style + "}]}");
Result result = decorate(biomes, DataVersion.V26_3, context -> {
});
JsonArray placement = placement(result, "data/iris_export/worldgen/placed_feature/decorator/poppy.json");
double exported = StageTestPacks.ofType(placement, "minecraft:random_chance").getFirst().get("chance").getAsDouble();
double coverage = irisCoverage(style, 0.2);
assertTrue("coverage " + coverage, coverage < 0.1);
assertEquals(coverage, exported, coverage * 0.2);
assertEquals("{\"type\":\"minecraft:simple_block\",\"to_place\":{\"id\":\"minecraft:poppy\"}}",
result.resource("data/iris_export/worldgen/feature/decorator/poppy.json").toString());
}
@Test
public void decoratorWhoseStyleNeverPassesIsLeftOut() throws Exception {
Map<String, String> biomes = new LinkedHashMap<>();
biomes.put("meadow", "{\"decorators\":[{\"palette\":[{\"block\":\"poppy\"}],\"chance\":0.5,\"style\":{\"style\":\"FLAT\"}},"
+ decorator("short_grass", 0.3) + "]}");
Result result = decorate(biomes, DataVersion.V26_3, context -> {
});
assertEquals(List.of("iris_export:decorator/short_grass"), step(result.biomes().getFirst(), GenerationStep.VEGETAL_DECORATION));
}
@Test
public void clusteredStyleFollowsFittedNoisePattern() throws Exception {
String style = "{\"style\":\"SIMPLEX\",\"zoom\":4}";
Map<String, String> biomes = new LinkedHashMap<>();
biomes.put("meadow", "{\"decorators\":[{\"palette\":[{\"block\":\"poppy\"},{\"block\":\"dandelion\",\"weight\":2}],\"chance\":0.3,\"style\":"
+ style + "}]}");
Result result = decorate(biomes, DataVersion.V26_3, context -> {
});
JsonObject provider = result.resource("data/iris_export/worldgen/feature/decorator/poppy.json").getAsJsonObject()
.getAsJsonObject("to_place");
assertEquals("minecraft:noise_threshold", provider.get("type").getAsString());
assertEquals("minecraft:air", provider.getAsJsonObject("default_state").get("id").getAsString());
assertEquals(0.0, provider.get("high_chance").getAsDouble(), 0.0);
List<String> low = new ArrayList<>();
for (JsonElement state : provider.getAsJsonArray("low_states")) {
low.add(state.getAsJsonObject().get("id").getAsString());
}
assertEquals(List.of("minecraft:poppy", "minecraft:dandelion", "minecraft:dandelion", "minecraft:dandelion"), low);
assertTrue(StageTestPacks.ofType(placement(result, "data/iris_export/worldgen/placed_feature/decorator/poppy.json"),
"minecraft:random_chance").isEmpty());
JsonObject noise = provider.getAsJsonObject("noise");
List<Double> amplitudes = new ArrayList<>();
for (JsonElement amplitude : noise.getAsJsonArray("amplitude_modifiers")) {
amplitudes.add(amplitude.getAsDouble());
}
VanillaNoiseModel model = VanillaNoiseModel.create("iris_export:test", noise.get("base_octave").getAsInt(), amplitudes, 99L, DataVersion.V26_3);
double scale = provider.get("scale").getAsDouble();
double threshold = provider.get("threshold").getAsDouble();
GatePattern iris = irisPattern(style, 0.3);
GatePattern vanilla = pattern((x, z) -> model.sample(x * scale, 70.0 * scale, z * scale) < threshold);
assertTrue("iris coverage " + iris.coverage(), iris.coverage() > 0.1 && iris.coverage() < 0.5);
assertEquals(iris.coverage(), vanilla.coverage(), 0.03);
assertTrue("iris patch " + iris.patch() + " vanilla " + vanilla.patch(),
vanilla.patch() > iris.patch() * 0.7 && vanilla.patch() < iris.patch() * 1.4);
}
@Test
public void columnWinnerSharesFollowIrisReservoirPick() {
assertArrayEquals(new double[]{0.5, 0.5}, DecoratorCompiler.columnShares(new double[]{1.0, 1.0}), 1.0e-12);
double[] shares = DecoratorCompiler.columnShares(new double[]{0.5, 0.2});
assertEquals(0.5 * (0.8 + 0.2 / 2.0), shares[0], 1.0e-12);
assertEquals(0.2 * (0.5 + 0.5 / 2.0), shares[1], 1.0e-12);
assertArrayEquals(new double[]{0.5, 1.0}, DecoratorCompiler.sequentialChances(new double[]{0.5, 0.5}), 1.0e-12);
}
@Test
public void depositHeightRangeExact() throws Exception {
Map<String, String> biomes = new LinkedHashMap<>();
biomes.put("hills", "{\"deposits\":[" + COAL + "," + IRON + "]}");
Result result = decorate(biomes, DataVersion.V26_3, context -> {
});
JsonArray coal = placement(result, "data/iris_export/worldgen/placed_feature/deposit/coal_ore.json");
JsonObject coalHeight = StageTestPacks.ofType(coal, "minecraft:height_range").getFirst().getAsJsonObject("height");
assertEquals("{\"type\":\"minecraft:uniform\",\"min_inclusive\":{\"above_bottom\":10},\"max_inclusive\":{\"above_bottom\":40}}", coalHeight.toString());
assertEquals(-8, StageTestPacks.ofType(coal, "minecraft:surface_relative_threshold_filter").getFirst().get("max_inclusive").getAsInt());
assertEquals("{\"type\":\"minecraft:uniform\",\"min_inclusive\":2,\"max_inclusive\":6}",
StageTestPacks.ofType(coal, "minecraft:count").getFirst().get("count").toString());
JsonArray iron = placement(result, "data/iris_export/worldgen/placed_feature/deposit/iron_ore.json");
JsonObject ironHeight = StageTestPacks.ofType(iron, "minecraft:height_range").getFirst().getAsJsonObject("height");
assertEquals("{\"type\":\"minecraft:trapezoid\",\"min_inclusive\":{\"above_bottom\":0},\"max_inclusive\":{\"above_bottom\":64},\"plateau\":0}",
ironHeight.toString());
assertTrue(StageTestPacks.ofType(iron, "minecraft:surface_relative_threshold_filter").isEmpty());
JsonObject ore = result.resource("data/iris_export/worldgen/feature/deposit/coal_ore.json").getAsJsonObject();
assertEquals("minecraft:ore", ore.get("type").getAsString());
assertEquals(8, ore.get("size").getAsInt());
JsonObject target = ore.getAsJsonArray("targets").get(1).getAsJsonObject();
assertEquals("{\"predicate_type\":\"minecraft:tag_match\",\"tag\":\"iris_export:deposit_host\"}", target.get("target").toString());
assertEquals("{\"id\":\"minecraft:coal_ore\"}", target.get("state").toString());
assertNotNull(result.resource("data/iris_export/tags/block/deposit_host.json"));
}
@Test
public void depositOresFollowTheirHostStone() throws Exception {
String explicit = "{\"palette\":[{\"block\":\"deepslate_redstone_ore[lit=false]\"}],\"minHeight\":0,\"maxHeight\":40,"
+ "\"minPerChunk\":1,\"maxPerChunk\":2,\"minSize\":4,\"maxSize\":4,\"replaceableBlocks\":[\"stone\",\"deepslate\",\"tuff\"]}";
Map<String, String> biomes = new LinkedHashMap<>();
biomes.put("hills", "{\"deposits\":[" + COAL + "," + explicit + "]}");
Result result = decorate(biomes, DataVersion.V26_3, context -> {
});
JsonArray coal = result.resource("data/iris_export/worldgen/feature/deposit/coal_ore.json").getAsJsonObject().getAsJsonArray("targets");
assertEquals(2, coal.size());
assertEquals("{\"predicate_type\":\"minecraft:block_match\",\"block\":\"minecraft:deepslate\"}",
coal.get(0).getAsJsonObject().get("target").toString());
assertEquals("{\"id\":\"minecraft:deepslate_coal_ore\"}", coal.get(0).getAsJsonObject().get("state").toString());
assertEquals("{\"id\":\"minecraft:coal_ore\"}", coal.get(1).getAsJsonObject().get("state").toString());
JsonArray redstone = result.resource("data/iris_export/worldgen/feature/deposit/deepslate_redstone_ore.json").getAsJsonObject()
.getAsJsonArray("targets");
Map<String, String> byHost = new LinkedHashMap<>();
for (JsonElement element : redstone) {
JsonObject target = element.getAsJsonObject();
byHost.put(target.getAsJsonObject("target").get("block").getAsString(), target.get("state").toString());
}
assertEquals("{\"id\":\"minecraft:redstone_ore\",\"properties\":{\"lit\":\"false\"}}", byHost.get("minecraft:stone"));
assertEquals("{\"id\":\"minecraft:deepslate_redstone_ore\",\"properties\":{\"lit\":\"false\"}}", byHost.get("minecraft:deepslate"));
assertEquals("{\"id\":\"minecraft:redstone_ore\",\"properties\":{\"lit\":\"false\"}}", byHost.get("minecraft:tuff"));
}
@Test
public void vanillaOreVeinsDisabled() throws Exception {
Map<String, String> biomes = new LinkedHashMap<>();
biomes.put("caves", "{\"deposits\":[" + COAL + "],\"layers\":[{\"palette\":[{\"block\":\"stone\"}]}],\"wall\":{\"palette\":[{\"block\":\"tuff\"}]}}");
DataVersion target = DataVersion.V26_3;
Result result = decorate(biomes, target, context -> {
context.setCaveField(CAVE_FIELD, 0.04);
new SurfaceStage().apply(context);
});
for (BiomeDef biome : result.biomes()) {
for (GenerationStep step : GenerationStep.values()) {
for (String feature : step(biome, step)) {
assertTrue(feature, feature.startsWith(StageTestPacks.NAMESPACE + ":"));
}
}
}
JsonElement rule = result.context().material().rule();
for (JsonObject vein : StageTestPacks.ofType(rule, "minecraft:ore_vein")) {
assertEquals("iris_export:" + MaterialProgramCompiler.WALL_SHELL, vein.get("density").getAsString());
}
assertFalse(rule.toString().contains("ore_vein/"));
assertFalse(rule.toString().contains("minecraft:overworld"));
assertEquals(1, StageTestPacks.ofType(result.context().material().rule(), "minecraft:ore_vein").size());
}
@Test
public void repaintUsesCuboid() throws Exception {
Map<String, String> biomes = new LinkedHashMap<>();
biomes.put("cliffs", "{\"layers\":[{\"palette\":[{\"block\":\"grass_block\"}],\"slopeCondition\":{\"maximumSlope\":3}},"
+ "{\"palette\":[{\"block\":\"stone\"}],\"minHeight\":2,\"maxHeight\":3,\"slopeCondition\":{\"minimumSlope\":3}},"
+ "{\"palette\":[{\"block\":\"dirt\"}],\"minHeight\":2,\"maxHeight\":2}],\"wall\":{\"palette\":[{\"block\":\"andesite\"}]}}");
PackCompileContext[] holder = new PackCompileContext[1];
Result modern = decorate(biomes, DataVersion.V26_3, context -> holder[0] = context);
List<String> repaint = step(modern.biomes().getFirst(), GenerationStep.LOCAL_MODIFICATIONS);
assertEquals(List.of("iris_export:repaint/slope_stone", "iris_export:repaint/wall_andesite"), repaint);
JsonArray slope = placement(modern, "data/iris_export/worldgen/placed_feature/repaint/slope_stone.json");
assertEquals("minecraft:cuboid", slope.get(0).getAsJsonObject().get("type").getAsString());
assertEquals("{\"type\":\"minecraft:inside_world_bounds\",\"offset\":[0,-1,0]}",
slope.get(1).getAsJsonObject().getAsJsonObject("predicate").toString());
assertFalse(StageTestPacks.find(slope, object -> object.has("offset") && object.get("offset").toString().equals("[3,3,0]")).isEmpty());
JsonObject column = modern.resource("data/iris_export/worldgen/feature/repaint/slope_stone.json").getAsJsonObject();
assertEquals("minecraft:block_column", column.get("type").getAsString());
assertEquals("down", column.get("direction").getAsString());
assertEquals("{\"type\":\"minecraft:uniform\",\"min_inclusive\":2,\"max_inclusive\":3}",
column.getAsJsonArray("layers").get(0).getAsJsonObject().get("height").toString());
assertTrue(hasDiagnostic(holder[0], ExportLimit.SLOPE));
}
@Test
public void decorationIsDeterministic() throws Exception {
Map<String, String> biomes = new LinkedHashMap<>();
biomes.put("forest", "{\"deposits\":[" + COAL + "],\"decorators\":[" + decorator("short_grass", 0.4) + "," + decorator("poppy", 0.02)
+ ",{\"palette\":[{\"block\":\"sugar_cane\"}],\"partOf\":\"SHORE_LINE\",\"chance\":0.5,\"stackMin\":2,\"stackMax\":4}],"
+ "\"wall\":{\"palette\":[{\"block\":\"tuff\"}]},\"slab\":{\"palette\":[{\"block\":\"stone_slab\"}]}}");
Result first = decorate(biomes, DataVersion.V26_3, context -> {
});
Result second = decorate(biomes, DataVersion.V26_3, context -> {
});
assertEquals(first.resources().size(), second.resources().size());
for (int index = 0; index < first.resources().size(); index++) {
assertEquals(first.resources().get(index).path(), second.resources().get(index).path());
assertEquals(first.resources().get(index).json().toString(), second.resources().get(index).json().toString());
}
assertEquals(first.biomes().toString(), second.biomes().toString());
}
private Result decorate(Map<String, String> biomes, DataVersion target, Consumer<PackCompileContext> before) throws Exception {
File pack = StageTestPacks.pack(temporaryFolder.newFolder(), DIMENSION, biomes);
IrisData data = IrisData.openRuntime(pack);
try {
PackCompileContext context = StageTestPacks.context(data, target, new ArrayList<>(biomes.keySet()));
before.accept(context);
List<BiomeDef> definitions = new ArrayList<>();
for (String key : biomes.keySet()) {
definitions.add(new BiomeDef(StageTestPacks.biomeId(key).substring(StageTestPacks.NAMESPACE.length() + 1), new JsonObject()));
}
context.setBiomes(definitions);
new DecorationStage().apply(context);
return new Result(context, context.features().apply(context.biomes(), context.namespace()), List.copyOf(context.jsonResources()));
} finally {
data.close();
}
}
private static String decorator(String block, double chance) {
return "{\"palette\":[{\"block\":\"" + block + "\"}],\"chance\":" + chance + "}";
}
private static double irisCoverage(String styleJson, double chance) {
return irisPattern(styleJson, chance).coverage();
}
private static GatePattern irisPattern(String styleJson, double chance) {
IrisGeneratorStyle style = new Gson().fromJson(styleJson, IrisGeneratorStyle.class);
CNG generator = style.create(new RNG(4242L), null);
double zoom = style.getZoom();
return pattern((x, z) -> generator.fitDouble(0.0, 1.0, x / zoom, z / zoom) <= chance);
}
private static GatePattern pattern(BiPredicate<Double, Double> gate) {
int[] lags = {1, 2, 4, 8, 16, 32, 64, 128};
int hits = 0;
int total = 0;
int[] both = new int[lags.length];
for (int i = 0; i < 150; i++) {
for (int j = 0; j < 150; j++) {
double x = i * 197.0 + 3.0;
double z = j * 173.0 - 11.0;
total++;
if (!gate.test(x, z)) {
continue;
}
hits++;
for (int lag = 0; lag < lags.length; lag++) {
both[lag] += gate.test(x + lags[lag], z) ? 1 : 0;
both[lag] += gate.test(x, z + lags[lag]) ? 1 : 0;
}
}
}
double coverage = (double) hits / total;
double previousLag = 0.0;
double previousExcess = 1.0;
for (int lag = 0; lag < lags.length; lag++) {
double excess = ((double) both[lag] / (2.0 * hits) - coverage) / (1.0 - coverage);
if (excess < 0.5) {
double low = previousLag == 0.0 ? 0.0 : Math.log(previousLag);
double fraction = (previousExcess - 0.5) / (previousExcess - excess);
return new GatePattern(coverage, previousLag == 0.0 ? lags[lag] * fraction : Math.exp(low + (Math.log(lags[lag]) - low) * fraction));
}
previousLag = lags[lag];
previousExcess = excess;
}
return new GatePattern(coverage, lags[lags.length - 1]);
}
private record GatePattern(double coverage, double patch) {
}
private static List<String> step(BiomeDef biome, GenerationStep step) {
List<String> features = new ArrayList<>();
for (JsonElement feature : biome.json().getAsJsonArray("features").get(step.ordinal()).getAsJsonArray()) {
features.add(feature.getAsString());
}
return features;
}
private static JsonArray placement(Result result, String path) {
return result.resource(path).getAsJsonObject().getAsJsonArray("placement");
}
private static boolean hasDiagnostic(PackCompileContext context, ExportLimit limit) {
for (ExportDiagnostic diagnostic : context.diagnostics()) {
if (diagnostic.limit() == limit) {
return true;
}
}
return false;
}
private record Result(PackCompileContext context, List<BiomeDef> biomes, List<JsonResource> resources) {
List<JsonResource> under(String folder) {
List<JsonResource> found = new ArrayList<>();
for (JsonResource resource : resources) {
if (resource.path().startsWith("data/iris_export/" + folder)) {
found.add(resource);
}
}
return found;
}
JsonElement resource(String path) {
for (JsonResource resource : resources) {
if (resource.path().equals(path)) {
return resource.json();
}
}
return null;
}
}
}
@@ -0,0 +1,268 @@
package art.arcane.iris.pack.datapack.export.compile.noise;
import art.arcane.iris.generation.noise.IrisGeneratorStyle;
import art.arcane.iris.generation.noise.NoiseStyle;
import art.arcane.iris.pack.datapack.DataVersion;
import art.arcane.iris.pack.datapack.export.ir.Field;
import art.arcane.iris.pack.datapack.export.ir.FieldEvaluator;
import art.arcane.iris.pack.datapack.export.ir.NoiseDef;
import art.arcane.iris.pack.datapack.export.lower.ExportCapabilities;
import art.arcane.volmlib.util.math.RNG;
import art.arcane.volmlib.util.noise.CNG;
import org.junit.Test;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
public class CellularFidelityTest {
private static final String NAMESPACE = "iris_export";
private static final int SIZE = 2048;
private static final int HEX_SIZE = 1024;
private static final int REALIZATIONS = 8;
private static final int DISTRIBUTION_STRIDE = 2;
private static final double HEX_BLOCKS = 32.0D;
private static final double CELL = 64.0D;
private static final long WORLD_SEED = 9137L;
private static final long IRIS_SEED = 9137L;
private static final double TIE_TOLERANCE = 1.0e-4D;
private static final double CENTRE_TOLERANCE = 1.0e-3D;
private static RegionStats vanillaCells;
private static RegionStats irisCells;
@Test
public void cellularFlatAreaWithinHalfPercent() {
assertEquals("Flat area percent", irisCells().flatPercent(), vanillaCells().flatPercent(), 0.5D);
}
@Test
public void cellCountWithin2Percent() {
double iris = irisCells().regions();
assertEquals("Cell count", iris, vanillaCells().regions(), 0.02D * iris);
}
@Test
public void neighbourDegreeWithin0_05() {
assertEquals("Mean neighbour degree", irisCells().meanDegree(), vanillaCells().meanDegree(), 0.05D);
}
@Test
public void vascularDistributionW1Within2Percent() {
double distance = styleDistance(NoiseStyle.VASCULAR);
assertTrue("VASCULAR W1 is " + distance + " of the Iris deviation", distance <= 0.02D);
}
@Test
public void globDistributionW1Within2Percent() {
double distance = styleDistance(NoiseStyle.GLOB);
assertTrue("GLOB W1 is " + distance + " of the Iris deviation", distance <= 0.02D);
}
@Test
public void hexCentresMatchExceptTies() {
NoiseRegistry registry = new NoiseRegistry(NAMESPACE);
HexLattice.Centers centers = HexLattice.centers("fidelity/hex", HEX_BLOCKS, null, null);
Map<String, NoiseDef> noises = FieldWalk.noiseDefinitions(registry);
double rootThree = Math.sqrt(3.0D);
int mismatches = 0;
for (int z = 0; z < HEX_SIZE; z++) {
for (int x = 0; x < HEX_SIZE; x++) {
double hexX = x / HEX_BLOCKS;
double hexZ = z / HEX_BLOCKS;
double[] iris = irisCentre(hexX, hexZ, rootThree);
double vanillaX = sample(centers.x(), noises, x, z);
double vanillaZ = sample(centers.z(), noises, x, z);
boolean same = Math.abs(vanillaX - iris[0]) <= CENTRE_TOLERANCE && Math.abs(vanillaZ - iris[1]) <= CENTRE_TOLERANCE;
double vanillaDistance = squared(hexX - vanillaX) + squared(hexZ - vanillaZ);
double irisDistance = squared(hexX - iris[0]) + squared(hexZ - iris[1]);
if (!same && Math.abs(vanillaDistance - irisDistance) > TIE_TOLERANCE) {
mismatches++;
}
}
}
assertTrue("Hex centres differ on " + mismatches + " pixels", mismatches <= 0.0005D * HEX_SIZE * HEX_SIZE);
}
private static synchronized RegionStats vanillaCells() {
if (vanillaCells == null) {
NoiseRegistry registry = new NoiseRegistry(NAMESPACE);
Field value = CellularLibrary.build("fidelity/cellular", CELL, null, null, CellularMode.GRID_3X3, registry).cellValue();
Map<String, NoiseDef> noises = FieldWalk.noiseDefinitions(registry);
double[][] grid = new double[SIZE][SIZE];
for (int z = 0; z < SIZE; z++) {
for (int x = 0; x < SIZE; x++) {
grid[z][x] = sample(value, noises, x, z);
}
}
vanillaCells = RegionStats.of(grid);
}
return vanillaCells;
}
private static synchronized RegionStats irisCells() {
if (irisCells == null) {
CNG iris = NoiseStyle.CELLULAR.create(new RNG(IRIS_SEED));
double[][] grid = new double[SIZE][SIZE];
for (int z = 0; z < SIZE; z++) {
for (int x = 0; x < SIZE; x++) {
grid[z][x] = iris.noise(x, z);
}
}
irisCells = RegionStats.of(grid);
}
return irisCells;
}
private static double styleDistance(NoiseStyle style) {
int samplesPerAxis = SIZE / DISTRIBUTION_STRIDE;
int samples = samplesPerAxis * samplesPerAxis;
double[] vanillaValues = new double[samples * REALIZATIONS];
double[] irisValues = new double[samples * REALIZATIONS];
for (int realization = 0; realization < REALIZATIONS; realization++) {
NoiseRegistry registry = new NoiseRegistry(NAMESPACE);
DefaultCellularStyleLowering lowering = new DefaultCellularStyleLowering(new ArrayList<>(), (nested, salt, nestedRegistry, capabilities) -> {
throw new AssertionError("Unexpected nested style " + nested.getStyle());
}, CellularMode.GRID_3X3);
Field field = lowering.lower(new IrisGeneratorStyle(style), realization + 1L, registry, ExportCapabilities.forTarget(DataVersion.V26_3));
Map<String, NoiseDef> noises = FieldWalk.noiseDefinitions(registry);
CNG iris = style.create(new RNG(IRIS_SEED + realization));
int offset = realization * samples;
for (int row = 0; row < samplesPerAxis; row++) {
for (int column = 0; column < samplesPerAxis; column++) {
int x = column * DISTRIBUTION_STRIDE;
int z = row * DISTRIBUTION_STRIDE;
vanillaValues[offset + row * samplesPerAxis + column] = sample(field, noises, x, z);
irisValues[offset + row * samplesPerAxis + column] = iris.noise(x, z);
}
}
}
return wasserstein(irisValues, vanillaValues) / deviation(irisValues);
}
private static double[] irisCentre(double hexX, double hexZ, double rootThree) {
double q = rootThree / 3.0D * hexX - hexZ / 3.0D;
double r = 2.0D / 3.0D * hexZ;
double cube = -q - r;
long roundedQ = Math.round(q);
long roundedR = Math.round(r);
long roundedCube = Math.round(cube);
double qDifference = Math.abs(roundedQ - q);
double rDifference = Math.abs(roundedR - r);
double cubeDifference = Math.abs(roundedCube - cube);
boolean fixQ = qDifference > cubeDifference && qDifference > rDifference;
long centerQ = fixQ ? -roundedCube - roundedR : roundedQ;
long centerR = !fixQ && cubeDifference <= rDifference ? -roundedQ - roundedCube : roundedR;
return new double[]{rootThree * (centerQ + centerR * 0.5D), 1.5D * centerR};
}
private static double sample(Field field, Map<String, NoiseDef> noises, int x, int z) {
return FieldEvaluator.sample(field, noises, WORLD_SEED, DataVersion.V26_3, x, 0, z);
}
private static double wasserstein(double[] first, double[] second) {
double[] left = first.clone();
double[] right = second.clone();
Arrays.sort(left);
Arrays.sort(right);
double sum = 0.0D;
for (int index = 0; index < left.length; index++) {
sum += Math.abs(left[index] - right[index]);
}
return sum / left.length;
}
private static double deviation(double[] values) {
double mean = Arrays.stream(values).average().orElse(0.0D);
double squares = 0.0D;
for (double value : values) {
squares += squared(value - mean);
}
return Math.sqrt(squares / values.length);
}
private static double squared(double value) {
return value * value;
}
private record RegionStats(int regions, double meanDegree, double flatPercent) {
private static RegionStats of(double[][] grid) {
int size = grid.length;
int[][] labels = new int[size][size];
int count = 0;
int[] queue = new int[size * size];
for (int z = 0; z < size; z++) {
for (int x = 0; x < size; x++) {
if (labels[z][x] == 0) {
count++;
flood(grid, labels, queue, x, z, count);
}
}
}
List<Set<Integer>> neighbours = new ArrayList<>(count + 1);
for (int index = 0; index <= count; index++) {
neighbours.add(new HashSet<>());
}
boolean[] border = new boolean[count + 1];
long flat = 0L;
for (int z = 0; z < size; z++) {
for (int x = 0; x < size; x++) {
int label = labels[z][x];
if (x == 0 || z == 0 || x == size - 1 || z == size - 1) {
border[label] = true;
}
if (x + 1 < size && labels[z][x + 1] != label) {
neighbours.get(label).add(labels[z][x + 1]);
neighbours.get(labels[z][x + 1]).add(label);
}
if (z + 1 < size && labels[z + 1][x] != label) {
neighbours.get(label).add(labels[z + 1][x]);
neighbours.get(labels[z + 1][x]).add(label);
}
if (x + 1 < size && z + 1 < size && grid[z][x] == grid[z][x + 1] && grid[z][x] == grid[z + 1][x]) {
flat++;
}
}
}
long degree = 0L;
int interior = 0;
for (int label = 1; label <= count; label++) {
if (!border[label]) {
interior++;
degree += neighbours.get(label).size();
}
}
double flatPercent = 100.0D * flat / ((double) (size - 1) * (size - 1));
return new RegionStats(count, (double) degree / interior, flatPercent);
}
private static void flood(double[][] grid, int[][] labels, int[] queue, int startX, int startZ, int label) {
int size = grid.length;
int head = 0;
int tail = 0;
labels[startZ][startX] = label;
queue[tail++] = startZ * size + startX;
while (head < tail) {
int cell = queue[head++];
int x = cell % size;
int z = cell / size;
double value = grid[z][x];
int[] neighbourX = {x + 1, x - 1, x, x};
int[] neighbourZ = {z, z, z + 1, z - 1};
for (int index = 0; index < 4; index++) {
int nextX = neighbourX[index];
int nextZ = neighbourZ[index];
if (nextX >= 0 && nextZ >= 0 && nextX < size && nextZ < size && labels[nextZ][nextX] == 0 && grid[nextZ][nextX] == value) {
labels[nextZ][nextX] = label;
queue[tail++] = nextZ * size + nextX;
}
}
}
}
}
}
@@ -0,0 +1,259 @@
package art.arcane.iris.pack.datapack.export.compile.noise;
import art.arcane.iris.pack.datapack.export.ir.Axis;
import art.arcane.iris.pack.datapack.export.ir.Field;
import art.arcane.iris.pack.datapack.export.ir.FieldValidator;
import art.arcane.iris.pack.datapack.export.ir.NoiseDef;
import org.junit.Test;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.IdentityHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotEquals;
import static org.junit.Assert.assertThrows;
import static org.junit.Assert.assertTrue;
public class CellularLibraryTest {
private static final String NAMESPACE = "iris_export";
private static final String INSTANCE = "test/cells";
private static final double CELL = 64.0D;
private static final int LATTICE_LIMIT = 798_000;
@Test
public void neighbourCellsShareHash() {
NoiseRegistry registry = new NoiseRegistry(NAMESPACE);
CellularOutputs outputs = CellularLibrary.build(INSTANCE, CELL, null, null, CellularMode.GRID_3X3, registry);
Map<String, Field> bodies = FieldWalk.sharedBodies(roots(outputs));
Field cellX = bodies.get("cell/" + INSTANCE + "/ik");
Field cellZ = bodies.get("cell/" + INSTANCE + "/jk");
List<Field.Noise> hashes = hashSamples(outputs, registry);
assertEquals(9, hashes.size());
for (Field.Noise hash : hashes) {
assertEquals(0.0D, hash.xzScale(), 0.0D);
assertEquals(0.0D, hash.yScale(), 0.0D);
assertTrue(hash.shiftY() instanceof Field.Const);
assertLatticeShift(hash.shiftX(), cellX);
assertLatticeShift(hash.shiftZ(), cellZ);
}
float spacing = (float) CellHashNoise.LATTICE_SPACING;
assertEquals(CellHashNoise.LATTICE_SPACING, spacing, 0.0D);
assertEquals(0.0D, CellHashNoise.LATTICE_SPACING * 8.0D % 1.0D, 0.0D);
for (int cell = -LATTICE_LIMIT; cell <= LATTICE_LIMIT; cell += 997) {
assertNeighbourHashInputs(cell, spacing);
}
for (int cell = -4096; cell <= 4096; cell++) {
assertNeighbourHashInputs(cell, spacing);
}
}
@Test
public void quadrantNeighbourShiftsAreDyadic() {
NoiseRegistry registry = new NoiseRegistry(NAMESPACE);
CellularOutputs outputs = CellularLibrary.build(INSTANCE, CELL, null, null, CellularMode.QUADRANT_2X2, registry);
Map<String, Field> bodies = FieldWalk.sharedBodies(roots(outputs));
Field.Binary shift = (Field.Binary) bodies.get("cell/" + INSTANCE + "/quadrant/ik_s");
assertEquals(Field.BinaryOp.ADD, shift.op());
Field.Binary step = (Field.Binary) shift.right();
assertEquals(Field.BinaryOp.MUL, step.op());
assertEquals(new Field.Const(CellHashNoise.LATTICE_SPACING), step.right());
assertEquals(4, hashSamples(outputs, registry).size());
}
@Test
public void everyRootIsTwoDimensionalExceptVolume() {
for (CellularMode mode : CellularMode.values()) {
NoiseRegistry registry = new NoiseRegistry(NAMESPACE);
CellularOutputs outputs = CellularLibrary.build(INSTANCE, CELL, null, null, mode, registry);
for (Field root : roots(outputs)) {
if (mode == CellularMode.GRID_3X3X3) {
assertTrue(mode + " output should depend on Y", root.axes().contains(Axis.Y));
} else {
FieldValidator.requireTwoDimensional(root, mode.name());
assertTrue(root.axes().contains(Axis.X));
assertTrue(root.axes().contains(Axis.Z));
}
}
}
}
@Test
public void volumeOutputOnlyInsideGrid() {
NoiseRegistry registry = new NoiseRegistry(NAMESPACE);
CellularOutputs outputs = CellularLibrary.build(INSTANCE, CELL, null, null, CellularMode.GRID_3X3X3, registry);
for (Field root : roots(outputs)) {
Field.Grid grid = (Field.Grid) root;
assertEquals(CellularLibrary.VOLUME_CELL_XZ, grid.cellXZ());
assertEquals(CellularLibrary.VOLUME_CELL_Y, grid.cellY());
}
assertEquals(27, hashSamples(outputs, registry).size());
for (Field.Noise hash : hashSamples(outputs, registry)) {
assertTrue(hash.axes().contains(Axis.Y));
}
for (CellularMode mode : List.of(CellularMode.GRID_3X3, CellularMode.QUADRANT_2X2)) {
CellularOutputs planar = CellularLibrary.build(INSTANCE, CELL, null, null, mode, registry);
for (Field root : roots(planar)) {
assertTrue(FieldWalk.nodesOf(root, Field.Grid.class).isEmpty());
}
}
}
@Test
public void tournamentPlaysOneMatchPerEliminatedCandidate() {
assertEquals(8, matches(CellularMode.GRID_3X3));
assertEquals(3, matches(CellularMode.QUADRANT_2X2));
assertEquals(26, matches(CellularMode.GRID_3X3X3));
}
@Test
public void constantsStayWithinLimit() {
for (CellularMode mode : CellularMode.values()) {
for (double cell : new double[]{0.5D, 64.0D, 137.0D, 4096.0D}) {
NoiseRegistry registry = new NoiseRegistry(NAMESPACE);
CellularOutputs outputs = CellularLibrary.build(INSTANCE, cell, null, null, mode, registry);
for (Field root : roots(outputs)) {
FieldWalk.assertConstantsWithinLimit(root);
}
}
}
}
@Test
public void everyNoiseIsRegistered() {
for (CellularMode mode : CellularMode.values()) {
NoiseRegistry registry = new NoiseRegistry(NAMESPACE);
CellularOutputs outputs = CellularLibrary.build(INSTANCE, CELL, null, null, mode, registry);
assertEquals(1, registry.definitions().size());
assertEquals(CellHashNoise.NOISE_ID, registry.definitions().getFirst().id());
for (Field root : roots(outputs)) {
FieldWalk.assertNoisesRegistered(root, registry);
}
}
}
@Test
public void hashSamplesAndOutputsAreShared() {
for (CellularMode mode : CellularMode.values()) {
NoiseRegistry registry = new NoiseRegistry(NAMESPACE);
CellularOutputs outputs = CellularLibrary.build(INSTANCE, CELL, null, null, mode, registry);
Set<Field> sharedBodies = Collections.newSetFromMap(new IdentityHashMap<>());
for (Field root : roots(outputs)) {
Field output = root instanceof Field.Grid grid ? grid.expr() : root;
assertTrue(mode + " output is not shared", output instanceof Field.Shared);
for (Field.Shared shared : FieldWalk.nodesOf(root, Field.Shared.class)) {
sharedBodies.add(shared.expr());
}
}
for (Field.Noise hash : hashSamples(outputs, registry)) {
assertTrue(sharedBodies.contains(hash));
}
}
}
@Test
public void identifiersAreDeterministic() {
for (CellularMode mode : CellularMode.values()) {
CellularOutputs first = CellularLibrary.build(INSTANCE, CELL, null, null, mode, new NoiseRegistry(NAMESPACE));
CellularOutputs second = CellularLibrary.build(INSTANCE, CELL, null, null, mode, new NoiseRegistry(NAMESPACE));
assertEquals(first, second);
assertEquals(FieldWalk.sharedBodies(roots(first)).keySet(), FieldWalk.sharedBodies(roots(second)).keySet());
CellularOutputs other = CellularLibrary.build("test/other", CELL, null, null, mode, new NoiseRegistry(NAMESPACE));
Set<String> overlap = new HashSet<>(FieldWalk.sharedBodies(roots(first)).keySet());
overlap.retainAll(FieldWalk.sharedBodies(roots(other)).keySet());
for (String name : overlap) {
assertTrue("Instance names overlap on " + name, name.startsWith("cell/coord/"));
}
}
assertEquals(CellHashNoise.plane(INSTANCE), CellHashNoise.plane(INSTANCE), 0.0D);
assertNotEquals(CellHashNoise.plane(INSTANCE), CellHashNoise.plane("test/other"), 0.0D);
}
@Test
public void modesOfOneInstanceAgreeOnSharedBodies() {
NoiseRegistry registry = new NoiseRegistry(NAMESPACE);
List<Field> roots = new ArrayList<>();
for (CellularMode mode : CellularMode.values()) {
roots.addAll(roots(CellularLibrary.build(INSTANCE, CELL, null, null, mode, registry)));
}
assertFalse(FieldWalk.sharedBodies(roots).isEmpty());
}
@Test
public void cellSizeAndWarpScaleTheCellCoordinate() {
NoiseRegistry registry = new NoiseRegistry(NAMESPACE);
Field warp = new Field.Noise(registry.register(new NoiseDef("test/warp", -5, List.of(1.0D))), 1.0D, 0.0D, null, null, null);
CellularOutputs outputs = CellularLibrary.build(INSTANCE, 128.0D, warp, null, CellularMode.GRID_3X3, registry);
Map<String, Field> bodies = FieldWalk.sharedBodies(roots(outputs));
Field.Binary xs = (Field.Binary) bodies.get("cell/" + INSTANCE + "/xs");
assertEquals(Field.BinaryOp.ADD, xs.op());
Field.Binary scaled = (Field.Binary) xs.left();
assertEquals(new Field.Const(0.5D), scaled.right());
Field.Binary warped = (Field.Binary) xs.right();
assertEquals(warp, warped.left());
assertEquals(new Field.Const(1.0D / 128.0D), warped.right());
Field.Binary zs = (Field.Binary) bodies.get("cell/" + INSTANCE + "/zs");
assertEquals(Field.BinaryOp.MUL, zs.op());
}
@Test
public void invalidInputsAreRejected() {
NoiseRegistry registry = new NoiseRegistry(NAMESPACE);
assertThrows(IllegalArgumentException.class, () -> CellularLibrary.build("Bad Id", CELL, null, null, CellularMode.GRID_3X3, registry));
assertThrows(IllegalArgumentException.class, () -> CellularLibrary.build(INSTANCE, 0.0D, null, null, CellularMode.GRID_3X3, registry));
assertThrows(IllegalArgumentException.class, () -> CellularLibrary.build(INSTANCE, Double.NaN, null, null, CellularMode.GRID_3X3, registry));
}
private static void assertNeighbourHashInputs(int cell, float spacing) {
float base = (float) cell * spacing;
assertEquals(Float.floatToIntBits((float) (cell + 1) * spacing), Float.floatToIntBits(base + spacing));
assertEquals(Float.floatToIntBits((float) (cell - 1) * spacing), Float.floatToIntBits(base + -spacing));
}
private static void assertLatticeShift(Field shift, Field lattice) {
Field.Shared shared = (Field.Shared) shift;
if (shared.expr().equals(lattice)) {
return;
}
Field.Binary neighbour = (Field.Binary) shared.expr();
assertEquals(Field.BinaryOp.ADD, neighbour.op());
assertEquals(lattice, ((Field.Shared) neighbour.left()).expr());
double offset = ((Field.Const) neighbour.right()).value();
assertEquals(CellHashNoise.LATTICE_SPACING, Math.abs(offset), 0.0D);
}
private static int matches(CellularMode mode) {
NoiseRegistry registry = new NoiseRegistry(NAMESPACE);
CellularOutputs outputs = CellularLibrary.build(INSTANCE, CELL, null, null, mode, registry);
int count = 0;
for (String name : FieldWalk.sharedBodies(roots(outputs)).keySet()) {
if (name.endsWith("_diff")) {
count++;
}
}
return count;
}
private static List<Field.Noise> hashSamples(CellularOutputs outputs, NoiseRegistry registry) {
String hashId = registry.namespace() + ":" + CellHashNoise.NOISE_ID;
List<Field.Noise> hashes = new ArrayList<>();
Set<Field> seen = Collections.newSetFromMap(new IdentityHashMap<>());
for (Field root : roots(outputs)) {
for (Field.Noise noise : FieldWalk.nodesOf(root, Field.Noise.class)) {
if (noise.noiseId().equals(hashId) && seen.add(noise)) {
hashes.add(noise);
}
}
}
return hashes;
}
static List<Field> roots(CellularOutputs outputs) {
return List.of(outputs.cellValue(), outputs.f1(), outputs.f2(), outputs.winnerX(), outputs.winnerZ());
}
}
@@ -0,0 +1,305 @@
package art.arcane.iris.pack.datapack.export.compile.noise;
import art.arcane.iris.generation.noise.IrisGenerator;
import art.arcane.iris.generation.noise.IrisGeneratorStyle;
import art.arcane.iris.generation.noise.NoiseStyle;
import art.arcane.iris.pack.datapack.DataVersion;
import art.arcane.iris.pack.datapack.export.ir.Axis;
import art.arcane.iris.pack.datapack.export.ir.ExportDiagnostic;
import art.arcane.iris.pack.datapack.export.ir.ExportLimit;
import art.arcane.iris.pack.datapack.export.ir.Field;
import art.arcane.iris.pack.datapack.export.ir.FieldEvaluator;
import art.arcane.iris.pack.datapack.export.ir.NoiseDef;
import art.arcane.iris.pack.datapack.export.lower.ExportCapabilities;
import org.junit.Test;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotEquals;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertThrows;
import static org.junit.Assert.assertTrue;
public class DefaultCellularStyleLoweringTest {
private static final String NAMESPACE = "iris_export";
private static final long QUADRANT_SEED = 1337L;
private static final ExportCapabilities MODERN = ExportCapabilities.forTarget(DataVersion.V26_3);
private static final CellularStyleLowering NO_NESTED_STYLES = (style, salt, registry, capabilities) -> {
throw new AssertionError("Unexpected nested style " + style.getStyle());
};
@Test
public void cellularUsesLibraryOn26_3() {
NoiseRegistry registry = new NoiseRegistry(NAMESPACE);
Field field = lowering(new ArrayList<>()).lower(new IrisGeneratorStyle(NoiseStyle.CELLULAR), 7L, registry, MODERN);
assertFalse(FieldWalk.nodesOf(field, Field.Coord.class).isEmpty());
assertEquals(9, noisesNamed(field, CellHashNoise.NOISE_ID).size());
assertTrue(FieldWalk.nodesOf(field, Field.Partition.class).isEmpty());
}
@Test
public void quadrantModeLowersCellValuesFromFourCandidatesUnderTheirOwnNames() {
NoiseRegistry registry = new NoiseRegistry(NAMESPACE);
IrisGeneratorStyle style = new IrisGeneratorStyle(NoiseStyle.CELLULAR_IRIS_DOUBLE);
Field grid = lowering(new ArrayList<>()).lower(style, 7L, registry, MODERN);
Field quadrant = new DefaultCellularStyleLowering(new ArrayList<>(), NO_NESTED_STYLES, CellularMode.QUADRANT_2X2).lower(style, 7L, registry, MODERN);
assertEquals(9, noisesNamed(grid, CellHashNoise.NOISE_ID).size());
assertEquals(4, noisesNamed(quadrant, CellHashNoise.NOISE_ID).size());
FieldWalk.assertTwoDimensional(quadrant);
Map<String, Field> gridBodies = new HashMap<>();
for (Field.Shared shared : FieldWalk.nodesOf(grid, Field.Shared.class)) {
gridBodies.put(shared.name(), shared.expr());
}
for (Field.Shared shared : FieldWalk.nodesOf(quadrant, Field.Shared.class)) {
Field gridBody = gridBodies.get(shared.name());
assertTrue(shared.name(), gridBody == null || gridBody.equals(shared.expr()));
}
}
@Test
public void quadrantCellValuesDrawTheGridCells() {
NoiseRegistry registry = new NoiseRegistry(NAMESPACE);
IrisGeneratorStyle style = new IrisGeneratorStyle(NoiseStyle.CELLULAR_IRIS_DOUBLE).setZoom(0.5D);
Field grid = lowering(new ArrayList<>()).lower(style, 7L, registry, MODERN);
Field quadrant = new DefaultCellularStyleLowering(new ArrayList<>(), NO_NESTED_STYLES, CellularMode.QUADRANT_2X2).lower(style, 7L, registry, MODERN);
Map<String, NoiseDef> noises = FieldWalk.noiseDefinitions(registry);
int points = 0;
int agreeing = 0;
for (int x = -300; x < 300; x += 13) {
for (int z = -300; z < 300; z += 17) {
points++;
double expected = FieldEvaluator.sample(grid, noises, QUADRANT_SEED, DataVersion.V26_3, x, 0, z);
double actual = FieldEvaluator.sample(quadrant, noises, QUADRANT_SEED, DataVersion.V26_3, x, 0, z);
if (Math.abs(expected - actual) < 1.0e-6D) {
agreeing++;
}
}
}
assertTrue(agreeing + " of " + points, agreeing >= 0.9D * points);
}
@Test
public void volumeModeIsRejectedForPlanarCellValues() {
assertThrows(IllegalArgumentException.class, () -> new DefaultCellularStyleLowering(new ArrayList<>(), NO_NESTED_STYLES, CellularMode.GRID_3X3X3));
}
@Test
public void exoticStyleFallsBackWithDiagnostic() {
ExportCapabilities capabilities = MODERN;
List<ExportDiagnostic> diagnostics = new ArrayList<>();
DefaultCellularStyleLowering lowering = lowering(diagnostics);
NoiseRegistry registry = new NoiseRegistry(NAMESPACE);
Field first = lowering.lower(new IrisGeneratorStyle(NoiseStyle.GYROID), 3L, registry, capabilities);
lowering.lower(new IrisGeneratorStyle(NoiseStyle.GYROID), 4L, registry, capabilities);
assertEquals(1, diagnostics.size());
ExportDiagnostic diagnostic = diagnostics.getFirst();
assertEquals(ExportLimit.NOISE_STYLE, diagnostic.limit());
assertEquals(ExportDiagnostic.Severity.WARNING, diagnostic.severity());
assertEquals("noise style GYROID", diagnostic.resource());
FieldWalk.assertTwoDimensional(first);
assertEquals(1, noisesNamed(first, LeafNoise.NOISE_ID).size());
assertTrue(FieldWalk.nodesOf(first, Field.Coord.class).isEmpty());
}
@Test
public void everySupportedStyleLowers() {
ExportCapabilities capabilities = MODERN;
NoiseRegistry registry = new NoiseRegistry(NAMESPACE);
DefaultCellularStyleLowering lowering = lowering(new ArrayList<>());
List<Field> roots = new ArrayList<>();
for (NoiseStyle style : NoiseStyle.values()) {
if (!DefaultCellularStyleLowering.supports(style)) {
continue;
}
Field field = lowering.lower(new IrisGeneratorStyle(style), style.ordinal(), registry, capabilities);
FieldWalk.assertTwoDimensional(field);
FieldWalk.assertConstantsWithinLimit(field);
FieldWalk.assertNoisesRegistered(field, registry);
roots.add(field);
}
FieldWalk.sharedBodies(roots);
}
@Test
public void smoothStylesAreNotCellular() {
assertFalse(DefaultCellularStyleLowering.supports(NoiseStyle.SIMPLEX));
assertFalse(DefaultCellularStyleLowering.supports(NoiseStyle.FLAT));
assertFalse(DefaultCellularStyleLowering.supports(NoiseStyle.CLOVER));
assertTrue(DefaultCellularStyleLowering.supports(NoiseStyle.CELLULAR_IRIS_DOUBLE));
assertTrue(DefaultCellularStyleLowering.supports(NoiseStyle.STATIC));
assertTrue(DefaultCellularStyleLowering.supports(NoiseStyle.HEXAGON));
NoiseRegistry registry = new NoiseRegistry(NAMESPACE);
assertThrows(IllegalArgumentException.class, () -> lowering(new ArrayList<>()).lower(new IrisGeneratorStyle(NoiseStyle.SIMPLEX), 1L, registry, MODERN));
IrisGeneratorStyle expression = new IrisGeneratorStyle(NoiseStyle.CELLULAR).setExpression("example");
assertThrows(IllegalArgumentException.class, () -> lowering(new ArrayList<>()).lower(expression, 1L, registry, MODERN));
}
@Test
public void smoothStyleUnderCellularFractureDropsTheCellularParts() {
List<IrisGeneratorStyle> nestedStyles = new ArrayList<>();
Field marker = new Field.Const(0.25D);
CellularStyleLowering nested = (style, salt, registry, capabilities) -> {
nestedStyles.add(style);
return marker;
};
List<ExportDiagnostic> diagnostics = new ArrayList<>();
IrisGeneratorStyle jitter = new IrisGeneratorStyle(NoiseStyle.STATIC).setMultiplier(1.0D);
IrisGeneratorStyle smooth = new IrisGeneratorStyle(NoiseStyle.FRACTAL_WATER).setZoom(0.15D).setMultiplier(9.0D).setFracture(jitter);
smooth.setCellularFrequency(2.0D);
Field field = new DefaultCellularStyleLowering(diagnostics, nested, CellularMode.GRID_3X3).lower(smooth, 5L, new NoiseRegistry(NAMESPACE), MODERN);
assertSame(marker, field);
assertEquals(1, nestedStyles.size());
assertSame(NoiseStyle.FRACTAL_WATER, nestedStyles.getFirst().getStyle());
assertEquals(0.15D, nestedStyles.getFirst().getZoom(), 0.0D);
assertNull(nestedStyles.getFirst().getFracture());
assertEquals(0.0D, nestedStyles.getFirst().getCellularFrequency(), 0.0D);
assertEquals(1, diagnostics.size());
assertSame(ExportLimit.NOISE_STYLE, diagnostics.getFirst().limit());
}
@Test
public void signatureVariantsCarryTheirWarp() {
NoiseRegistry registry = new NoiseRegistry(NAMESPACE);
DefaultCellularStyleLowering lowering = lowering(new ArrayList<>());
assertEquals(0, noisesNamed(lowering.lower(new IrisGeneratorStyle(NoiseStyle.CELLULAR), 1L, registry, MODERN), LeafNoise.NOISE_ID).size());
assertEquals(6, noisesNamed(lowering.lower(new IrisGeneratorStyle(NoiseStyle.CELLULAR_IRIS), 1L, registry, MODERN), LeafNoise.NOISE_ID).size());
assertEquals(8, noisesNamed(lowering.lower(new IrisGeneratorStyle(NoiseStyle.CELLULAR_IRIS_DOUBLE), 1L, registry, MODERN), LeafNoise.NOISE_ID).size());
assertEquals(2, noisesNamed(lowering.lower(new IrisGeneratorStyle(NoiseStyle.NOWHERE_CELLULAR), 1L, registry, MODERN), LeafNoise.NOISE_ID).size());
assertEquals(6, noisesNamed(lowering.lower(new IrisGeneratorStyle(NoiseStyle.GLOB_IRIS_THICK), 1L, registry, MODERN), LeafNoise.NOISE_ID).size());
}
@Test
public void styleFractureReplacesSignatureWarp() {
AtomicInteger calls = new AtomicInteger();
NoiseRegistry registry = new NoiseRegistry(NAMESPACE);
String fractureNoise = registry.register(new NoiseDef("test/fracture", -6, List.of(1.0D)));
CellularStyleLowering nested = (style, salt, nestedRegistry, capabilities) -> {
calls.incrementAndGet();
assertEquals(6.0D, style.getZoom(), 1.0e-12D);
return new Field.Noise(fractureNoise, 1.0D, 0.0D, null, null, null);
};
IrisGeneratorStyle fracture = new IrisGeneratorStyle(NoiseStyle.SIMPLEX).setZoom(3.0D).setMultiplier(9.0D);
IrisGeneratorStyle style = new IrisGeneratorStyle(NoiseStyle.CELLULAR_IRIS_DOUBLE).setZoom(2.0D).setFracture(fracture);
Field field = new DefaultCellularStyleLowering(new ArrayList<>(), nested, CellularMode.GRID_3X3).lower(style, 5L, registry, MODERN);
assertEquals(2, calls.get());
assertEquals(0, noisesNamed(field, LeafNoise.NOISE_ID).size());
assertEquals(2, noisesNamed(field, "test/fracture").size());
FieldWalk.assertTwoDimensional(field);
}
@Test
public void zoomScalesCellSize() {
NoiseRegistry registry = new NoiseRegistry(NAMESPACE);
Field field = lowering(new ArrayList<>()).lower(new IrisGeneratorStyle(NoiseStyle.CELLULAR).setZoom(2.0D), 1L, registry, MODERN);
Field.Shared xs = sharedEndingWith(field, "/xs");
Field.Binary scaled = (Field.Binary) xs.expr();
assertEquals(Field.BinaryOp.MUL, scaled.op());
assertEquals(new Field.Const(0.5D), scaled.right());
}
@Test
public void exponentAppliesPower() {
NoiseRegistry registry = new NoiseRegistry(NAMESPACE);
DefaultCellularStyleLowering lowering = lowering(new ArrayList<>());
Field squared = lowering.lower(new IrisGeneratorStyle(NoiseStyle.CELLULAR).setExponent(2.0D), 1L, registry, MODERN);
Field.Binary power = (Field.Binary) ((Field.Shared) squared).expr();
assertEquals(Field.BinaryOp.POW, power.op());
assertTrue(power.left() instanceof Field.Clamp);
assertEquals(new Field.Const(2.0D), power.right());
Field thin = lowering.lower(new IrisGeneratorStyle(NoiseStyle.VASCULAR_THIN), 1L, registry, MODERN);
Field.Binary thinPower = (Field.Binary) ((Field.Shared) thin).expr();
assertEquals(new Field.Const(1.0D / 0.65D), thinPower.right());
}
@Test
public void loweringIsDeterministicPerSalt() {
DefaultCellularStyleLowering lowering = lowering(new ArrayList<>());
Field first = lowering.lower(new IrisGeneratorStyle(NoiseStyle.SIMPLEX_VASCULAR), 11L, new NoiseRegistry(NAMESPACE), MODERN);
Field second = lowering.lower(new IrisGeneratorStyle(NoiseStyle.SIMPLEX_VASCULAR), 11L, new NoiseRegistry(NAMESPACE), MODERN);
Field other = lowering.lower(new IrisGeneratorStyle(NoiseStyle.SIMPLEX_VASCULAR), 12L, new NoiseRegistry(NAMESPACE), MODERN);
assertEquals(first, second);
assertEquals(FieldWalk.sharedBodies(List.of(first)).keySet(), FieldWalk.sharedBodies(List.of(second)).keySet());
assertNotEquals(FieldWalk.sharedBodies(List.of(first)).keySet(), FieldWalk.sharedBodies(List.of(other)).keySet());
}
@Test
public void staticUsesBlockHash() {
ExportCapabilities capabilities = MODERN;
NoiseRegistry registry = new NoiseRegistry(NAMESPACE);
Field field = lowering(new ArrayList<>()).lower(new IrisGeneratorStyle(NoiseStyle.STATIC), 1L, registry, capabilities);
List<Field.Noise> hashes = noisesNamed(field, CellHashNoise.NOISE_ID);
assertEquals(1, hashes.size());
assertEquals(CellHashNoise.LATTICE_SPACING, hashes.getFirst().xzScale(), 0.0D);
assertTrue(FieldWalk.nodesOf(field, Field.Grid.class).isEmpty());
}
@Test
public void bilinearCellularInterpolatesOnTheIrisLattice() {
NoiseRegistry registry = new NoiseRegistry(NAMESPACE);
Field field = lowering(new ArrayList<>()).lower(new IrisGeneratorStyle(NoiseStyle.CELLULAR_BILINEAR).setZoom(1.5D), 1L, registry, MODERN);
Field.Grid grid = (Field.Grid) ((Field.Shared) field).expr();
assertEquals(48, grid.cellXZ());
}
@Test
public void hexagonUsesLattice() {
List<ExportDiagnostic> diagnostics = new ArrayList<>();
DefaultCellularStyleLowering lowering = lowering(diagnostics);
Field modern = lowering.lower(new IrisGeneratorStyle(NoiseStyle.HEXAGON), 1L, new NoiseRegistry(NAMESPACE), MODERN);
assertEquals(4, FieldWalk.nodesOf(modern, Field.Round.class).size());
assertTrue(diagnostics.isEmpty());
}
@Test
public void cellCracksSelectRaisedCells() {
DefaultCellularStyleLowering lowering = lowering(new ArrayList<>());
Field value = new Field.Const(0.25D);
IrisGenerator flat = new IrisGenerator();
assertSame(value, lowering.cellCracks(flat, value, 1L, new NoiseRegistry(NAMESPACE), MODERN));
IrisGenerator cracked = new IrisGenerator().setCellFractureHeight(3.0D).setCellPercentSize(0.6D);
ExportCapabilities capabilities = MODERN;
NoiseRegistry registry = new NoiseRegistry(NAMESPACE);
Field.RangeIf crack = (Field.RangeIf) lowering.cellCracks(cracked, value, 1L, registry, capabilities);
assertEquals(0.6D, crack.min(), 0.0D);
assertSame(value, crack.outOfRange());
assertEquals(new Field.Binary(Field.BinaryOp.MUL, value, new Field.Const(3.0D)), crack.inRange());
assertFalse(crack.axes().contains(Axis.Y));
FieldWalk.assertConstantsWithinLimit(crack);
FieldWalk.assertNoisesRegistered(crack, registry);
}
private static DefaultCellularStyleLowering lowering(List<ExportDiagnostic> diagnostics) {
return new DefaultCellularStyleLowering(diagnostics, NO_NESTED_STYLES, CellularMode.GRID_3X3);
}
private static List<Field.Noise> noisesNamed(Field root, String localId) {
List<Field.Noise> matches = new ArrayList<>();
for (Field.Noise noise : FieldWalk.nodesOf(root, Field.Noise.class)) {
if (noise.noiseId().endsWith(":" + localId)) {
matches.add(noise);
}
}
return matches;
}
private static Field.Shared sharedEndingWith(Field root, String suffix) {
for (Field.Shared shared : FieldWalk.nodesOf(root, Field.Shared.class)) {
if (shared.name().endsWith(suffix) && !shared.name().contains("/coord/")) {
return shared;
}
}
throw new AssertionError("No shared field ending with " + suffix);
}
}
@@ -0,0 +1,194 @@
package art.arcane.iris.pack.datapack.export.compile.noise;
import art.arcane.iris.pack.datapack.export.ir.Axis;
import art.arcane.iris.pack.datapack.export.ir.Field;
import art.arcane.iris.pack.datapack.export.ir.NoiseDef;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Deque;
import java.util.HashSet;
import java.util.IdentityHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
final class FieldWalk {
private static final double LIMIT = 1.0e6D;
private FieldWalk() {
}
static List<Field> nodes(Field root) {
Set<Field> seen = Collections.newSetFromMap(new IdentityHashMap<>());
List<Field> ordered = new ArrayList<>();
Deque<Field> pending = new ArrayDeque<>();
pending.push(root);
while (!pending.isEmpty()) {
Field node = pending.pop();
if (!seen.add(node)) {
continue;
}
ordered.add(node);
for (Field child : children(node)) {
pending.push(child);
}
}
return ordered;
}
static List<Field> children(Field field) {
List<Field> children = new ArrayList<>();
switch (field) {
case Field.Const ignored -> {
}
case Field.Coord ignored -> {
}
case Field.Ref ignored -> {
}
case Field.Noise noise -> {
addIfPresent(children, noise.shiftX());
addIfPresent(children, noise.shiftY());
addIfPresent(children, noise.shiftZ());
}
case Field.Binary binary -> {
children.add(binary.left());
children.add(binary.right());
}
case Field.Unary unary -> children.add(unary.input());
case Field.Clamp clamp -> children.add(clamp.input());
case Field.Lerp lerp -> {
children.add(lerp.alpha());
children.add(lerp.first());
children.add(lerp.second());
}
case Field.Round round -> {
children.add(round.input());
children.add(round.multiple());
}
case Field.Curve curve -> {
children.add(curve.input());
for (Field.Knot knot : curve.knots()) {
children.add(knot.value());
}
}
case Field.Partition partition -> {
children.add(partition.input());
children.addAll(partition.leaves());
}
case Field.Mux mux -> {
children.add(mux.index());
children.addAll(mux.cases());
}
case Field.Gate gate -> {
children.add(gate.condition());
children.add(gate.expr());
}
case Field.RangeIf rangeIf -> {
children.add(rangeIf.input());
children.add(rangeIf.inRange());
children.add(rangeIf.outOfRange());
}
case Field.Grid grid -> children.add(grid.expr());
case Field.Shared shared -> children.add(shared.expr());
case Field.Slice slice -> children.add(slice.expr());
case Field.TopSurface topSurface -> children.add(topSurface.density());
}
return children;
}
static <T extends Field> List<T> nodesOf(Field root, Class<T> type) {
List<T> matches = new ArrayList<>();
for (Field node : nodes(root)) {
if (type.isInstance(node)) {
matches.add(type.cast(node));
}
}
return matches;
}
static Map<String, Field> sharedBodies(List<Field> roots) {
Map<String, Field> bodies = new TreeMap<>();
for (Field root : roots) {
for (Field.Shared shared : nodesOf(root, Field.Shared.class)) {
Field existing = bodies.putIfAbsent(shared.name(), shared.expr());
if (existing != null && !existing.equals(shared.expr())) {
fail("Shared field '" + shared.name() + "' has two different bodies");
}
}
}
return bodies;
}
static void assertConstantsWithinLimit(Field root) {
for (Field node : nodes(root)) {
switch (node) {
case Field.Const constant -> assertWithin(constant.value(), "constant");
case Field.Coord coord -> {
assertWithin(coord.fromValue(), "gradient from value");
assertWithin(coord.toValue(), "gradient to value");
}
case Field.Clamp clamp -> {
assertWithin(clamp.min(), "clamp minimum");
assertWithin(clamp.max(), "clamp maximum");
}
case Field.RangeIf rangeIf -> {
assertWithin(rangeIf.min(), "range minimum");
assertWithin(rangeIf.max(), "range maximum");
}
case Field.Curve curve -> {
for (Field.Knot knot : curve.knots()) {
assertWithin(knot.location(), "knot location");
assertWithin(knot.derivative(), "knot derivative");
}
}
case Field.Partition partition -> {
for (double threshold : partition.thresholds()) {
assertWithin(threshold, "partition threshold");
}
}
default -> {
}
}
}
}
static void assertNoisesRegistered(Field root, NoiseRegistry registry) {
Set<String> registered = new HashSet<>();
for (NoiseDef definition : registry.definitions()) {
registered.add(registry.namespace() + ":" + definition.id());
}
for (Field.Noise noise : nodesOf(root, Field.Noise.class)) {
assertTrue("Noise '" + noise.noiseId() + "' is not registered", registered.contains(noise.noiseId()));
}
}
static void assertTwoDimensional(Field root) {
assertTrue("Field depends on Y: " + root.axes(), !root.axes().contains(Axis.Y));
}
static Map<String, NoiseDef> noiseDefinitions(NoiseRegistry registry) {
Map<String, NoiseDef> definitions = new TreeMap<>();
for (NoiseDef definition : registry.definitions()) {
definitions.put(registry.namespace() + ":" + definition.id(), definition);
}
assertEquals(registry.definitions().size(), definitions.size());
return definitions;
}
private static void addIfPresent(List<Field> children, Field child) {
if (child != null) {
children.add(child);
}
}
private static void assertWithin(double value, String role) {
assertTrue(role + " " + value + " exceeds +-1e6", Double.isFinite(value) && Math.abs(value) <= LIMIT);
}
}
@@ -0,0 +1,64 @@
package art.arcane.iris.pack.datapack.export.compile.noise;
import art.arcane.iris.pack.datapack.export.ir.Field;
import art.arcane.iris.pack.datapack.export.ir.FieldValidator;
import org.junit.Test;
import java.util.List;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
public class HexLatticeTest {
private static final String NAMESPACE = "iris_export";
@Test
public void centersSnapToTwoRectangularLattices() {
HexLattice.Centers centers = HexLattice.centers("test/hex", 32.0D, null, null);
FieldValidator.requireTwoDimensional(centers.x(), "hex x");
FieldValidator.requireTwoDimensional(centers.z(), "hex z");
List<Field.Round> rounds = FieldWalk.nodesOf(centers.x(), Field.Round.class);
assertEquals(4, rounds.size());
int columns = 0;
int rows = 0;
for (Field.Round round : rounds) {
assertEquals(Field.RoundMode.ROUND, round.mode());
if (round.multiple().equals(new Field.Const(HexLattice.COLUMN_SPACING))) {
columns++;
} else if (round.multiple().equals(new Field.Const(HexLattice.ROW_SPACING))) {
rows++;
}
}
assertEquals(2, columns);
assertEquals(2, rows);
Field.RangeIf pick = (Field.RangeIf) ((Field.Shared) centers.x()).expr();
assertEquals(0.0D, pick.max(), 0.0D);
FieldWalk.assertConstantsWithinLimit(centers.x());
FieldWalk.assertConstantsWithinLimit(centers.z());
}
@Test
public void valueSamplesRegisteredLeafAtCentre() {
NoiseRegistry registry = new NoiseRegistry(NAMESPACE);
Field value = HexLattice.centerValue("test/hex", 32.0D, null, null, registry);
FieldValidator.requireTwoDimensional(value, "hex value");
FieldWalk.assertNoisesRegistered(value, registry);
FieldWalk.assertConstantsWithinLimit(value);
List<Field.Noise> noises = FieldWalk.nodesOf(value, Field.Noise.class);
assertEquals(1, noises.size());
Field.Noise leaf = noises.getFirst();
assertEquals(0.0D, leaf.xzScale(), 0.0D);
assertEquals(0.0D, leaf.yScale(), 0.0D);
assertTrue(leaf.shiftY() instanceof Field.Const);
HexLattice.Centers centers = HexLattice.centers("test/hex", 32.0D, null, null);
assertEquals(centers.x(), ((Field.Binary) leaf.shiftX()).left());
assertEquals(centers.z(), ((Field.Binary) leaf.shiftZ()).left());
}
@Test
public void latticeIsDeterministic() {
NoiseRegistry registry = new NoiseRegistry(NAMESPACE);
assertEquals(HexLattice.centerValue("test/hex", 48.0D, null, null, registry), HexLattice.centerValue("test/hex", 48.0D, null, null, registry));
FieldWalk.sharedBodies(List.of(HexLattice.centerValue("test/hex", 48.0D, null, null, registry), HexLattice.centers("test/hex", 48.0D, null, null).x()));
}
}
@@ -0,0 +1,87 @@
package art.arcane.iris.pack.datapack.export.compile.noise;
import art.arcane.iris.generation.noise.NoiseStyle;
import art.arcane.iris.pack.datapack.DataVersion;
import art.arcane.iris.pack.datapack.export.WorldgenExportTargets;
import art.arcane.volmlib.util.math.RNG;
import art.arcane.volmlib.util.noise.CNG;
import org.junit.Test;
import java.util.ArrayList;
import java.util.List;
import java.util.function.DoubleBinaryOperator;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
public class IrisSampleFitTest {
private static final int ROWS = 48;
private static final int LENGTH = 512;
private static final int LAGS = 96;
@Test
public void fittedLeafMatchesIrisCorrelationLength() {
List<DoubleBinaryOperator> irisSamplers = new ArrayList<>();
for (long seed = 0L; seed < 4L; seed++) {
CNG simplex = NoiseStyle.SIMPLEX.create(new RNG(77L + seed));
irisSamplers.add(simplex::noise);
}
double iris = correlationLength(irisSamplers);
for (DataVersion target : WorldgenExportTargets.SUPPORTED) {
IrisSampleFit.Profile vanilla = IrisSampleFit.vanilla(target);
double xzScale = LeafNoise.xzScale(vanilla, IrisSampleFit.style(NoiseStyle.SIMPLEX).correlationLength());
List<DoubleBinaryOperator> vanillaSamplers = new ArrayList<>();
for (long seed = 0L; seed < 16L; seed++) {
VanillaNoiseModel model = VanillaNoiseModel.create("iris_export:fit_check", 0, List.of(1.0D), 5L + 101L * seed, target);
vanillaSamplers.add((x, z) -> model.sample(x * xzScale, 3.375D, z * xzScale));
}
double fitted = correlationLength(vanillaSamplers);
assertEquals(target + " fitted correlation length", iris, fitted, 0.1D * iris);
}
}
@Test
public void profilesAreDeterministic() {
IrisSampleFit.Profile first = IrisSampleFit.style(NoiseStyle.VASCULAR);
assertTrue(first.correlationLength() > 0.0D);
assertEquals(first.quantile(0.5D), IrisSampleFit.style(NoiseStyle.VASCULAR).quantile(0.5D), 0.0D);
double[] quantiles = first.quantiles(32);
for (int index = 1; index < quantiles.length; index++) {
assertTrue(quantiles[index] >= quantiles[index - 1]);
}
}
private static double correlationLength(List<DoubleBinaryOperator> samplers) {
double[][] rows = new double[ROWS][LENGTH + LAGS];
double sum = 0.0D;
for (int row = 0; row < ROWS; row++) {
for (int column = 0; column < LENGTH + LAGS; column++) {
rows[row][column] = samplers.get(row % samplers.size()).applyAsDouble(row * 281.0D + column, row * 173.0D);
}
for (int column = 0; column < LENGTH; column++) {
sum += rows[row][column];
}
}
double mean = sum / (ROWS * LENGTH);
double variance = covariance(rows, mean, 0);
double previous = 1.0D;
for (int lag = 1; lag <= LAGS; lag++) {
double correlation = covariance(rows, mean, lag) / variance;
if (correlation < 0.5D) {
return lag - 1 + (previous - 0.5D) / (previous - correlation);
}
previous = correlation;
}
return LAGS;
}
private static double covariance(double[][] rows, double mean, int lag) {
double sum = 0.0D;
for (double[] row : rows) {
for (int column = 0; column < LENGTH; column++) {
sum += (row[column] - mean) * (row[column + lag] - mean);
}
}
return sum / (ROWS * LENGTH);
}
}
@@ -0,0 +1,73 @@
package art.arcane.iris.pack.datapack.export.compile.noise;
import art.arcane.iris.pack.datapack.export.ir.NoiseDef;
import org.junit.Test;
import java.util.List;
import java.util.Map;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertThrows;
public class NoiseRegistryTest {
@Test
public void registerReturnsNamespacedId() {
NoiseRegistry registry = new NoiseRegistry("iris_export");
assertEquals("iris_export:terrain/base", registry.register(new NoiseDef("terrain/base", -7, List.of(1.0, 0.5))));
assertEquals("iris_export", registry.namespace());
}
@Test
public void identicalDefinitionsShareOneEntry() {
NoiseRegistry registry = new NoiseRegistry("iris_export");
String first = registry.register(new NoiseDef("terrain/base", -7, List.of(1.0, 0.5)));
String second = registry.register(new NoiseDef("terrain/base", -7, List.of(1.0, 0.5)));
assertEquals(first, second);
assertEquals(1, registry.definitions().size());
}
@Test
public void sameParametersUnderDifferentIdsStayIndependent() {
NoiseRegistry registry = new NoiseRegistry("iris_export");
String first = registry.register(new NoiseDef("terrain/a", -7, List.of(1.0)));
String second = registry.register(new NoiseDef("terrain/b", -7, List.of(1.0)));
assertEquals("iris_export:terrain/a", first);
assertEquals("iris_export:terrain/b", second);
assertEquals(2, registry.definitions().size());
}
@Test
public void conflictingDefinitionForIdIsRejected() {
NoiseRegistry registry = new NoiseRegistry("iris_export");
registry.register(new NoiseDef("terrain/base", -7, List.of(1.0)));
IllegalArgumentException error = assertThrows(IllegalArgumentException.class, () -> registry.register(new NoiseDef("terrain/base", -6, List.of(1.0))));
assertEquals("Noise 'iris_export:terrain/base' is already registered with different parameters", error.getMessage());
}
@Test
public void definitionsAreSortedById() {
NoiseRegistry registry = new NoiseRegistry("iris_export");
registry.register(new NoiseDef("zeta", 0, List.of(1.0)));
registry.register(new NoiseDef("alpha", 0, List.of(1.0)));
registry.register(new NoiseDef("cell_hash", 0, List.of(1.0)));
assertEquals(List.of("alpha", "cell_hash", "zeta"), registry.definitions().stream().map(NoiseDef::id).toList());
}
@Test
public void byReferenceKeysDefinitionsByNamespacedId() {
NoiseRegistry registry = new NoiseRegistry("iris_export");
NoiseDef base = new NoiseDef("terrain/base", -7, List.of(1.0));
NoiseDef detail = new NoiseDef("terrain/detail", -3, List.of(1.0, 0.5));
registry.register(detail);
registry.register(base);
Map<String, NoiseDef> references = registry.byReference();
assertEquals(List.of("iris_export:terrain/base", "iris_export:terrain/detail"), List.copyOf(references.keySet()));
assertEquals(base, references.get("iris_export:terrain/base"));
assertThrows(UnsupportedOperationException.class, () -> references.put("iris_export:other", base));
}
@Test
public void namespaceIsValidated() {
assertThrows(IllegalArgumentException.class, () -> new NoiseRegistry("Iris Export"));
}
}
@@ -0,0 +1,296 @@
package art.arcane.iris.pack.datapack.export.compile.noise;
import art.arcane.iris.generation.noise.IrisGenerator;
import art.arcane.iris.generation.noise.IrisGeneratorStyle;
import art.arcane.iris.generation.noise.IrisNoiseGenerator;
import art.arcane.iris.generation.noise.IrisStyledRange;
import art.arcane.iris.generation.noise.NoiseStyle;
import art.arcane.iris.pack.datapack.DataVersion;
import art.arcane.iris.pack.datapack.export.ir.ExportDiagnostic;
import art.arcane.iris.pack.datapack.export.ir.ExportLimit;
import art.arcane.iris.pack.datapack.export.ir.Field;
import art.arcane.iris.pack.datapack.export.ir.FieldEvaluator;
import art.arcane.iris.pack.datapack.export.ir.FieldValidator;
import art.arcane.iris.pack.datapack.export.lower.ExportCapabilities;
import art.arcane.volmlib.util.collection.KList;
import org.junit.Test;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertThrows;
import static org.junit.Assert.assertTrue;
public final class NoiseStyleCompilerTest {
private static final DataVersion TARGET = DataVersion.V26_3;
private static final ExportCapabilities CAPABILITIES = ExportCapabilities.forTarget(TARGET);
private static final long SEED = 1_234L;
private static final long SUPER_SEED = 98_765L;
private static final double FLOAT_TOLERANCE = 1.0e-6;
private static final CellularStyleLowering REJECTING = (style, salt, registry, capabilities) -> {
throw new AssertionError("Smooth style " + style.getStyle() + " reached the cellular seam");
};
private static final NoiseStyleCompiler SMOOTH = new NoiseStyleCompiler(REJECTING);
@Test
public void cellularFamilyStylesGoThroughTheSeam() {
Field marker = new Field.Const(0.25);
List<NoiseStyle> seen = new ArrayList<>();
NoiseStyleCompiler compiler = new NoiseStyleCompiler((style, salt, registry, capabilities) -> {
seen.add(style.getStyle());
return marker;
});
NoiseRegistry registry = new NoiseRegistry("iris_export");
List<NoiseStyle> cellular = List.of(NoiseStyle.CELLULAR, NoiseStyle.CELLULAR_IRIS_DOUBLE, NoiseStyle.NOWHERE_CELLULAR,
NoiseStyle.SIMPLEX_CELLS, NoiseStyle.SIMPLEX_VASCULAR, NoiseStyle.STATIC, NoiseStyle.HEXAGON, NoiseStyle.VASCULAR_THIN,
NoiseStyle.GLOB_IRIS_THICK, NoiseStyle.CELLULAR_BILINEAR, NoiseStyle.CELLULAR_HEIGHT);
for (NoiseStyle style : cellular) {
assertSame(marker, compiler.compile(new IrisGeneratorStyle(style), 7L, registry, CAPABILITIES));
}
assertEquals(cellular, seen);
assertTrue(registry.definitions().isEmpty());
}
@Test
public void createdCompilerLowersCellularWithItsOwnNestedStyles() {
List<ExportDiagnostic> diagnostics = new ArrayList<>();
NoiseRegistry registry = new NoiseRegistry("iris_export");
IrisGeneratorStyle fracture = new IrisGeneratorStyle(NoiseStyle.SIMPLEX).setZoom(3.0).setMultiplier(9.0);
IrisGeneratorStyle style = new IrisGeneratorStyle(NoiseStyle.CELLULAR_IRIS_DOUBLE).setZoom(2.0).setFracture(fracture);
style.setCellularFrequency(2.0);
Field field = NoiseStyleCompiler.create(diagnostics).compile(style, 7L, registry, ExportCapabilities.forTarget(DataVersion.V26_3));
FieldValidator.requireTwoDimensional(field, "cellular style");
assertTrue(registry.definitions().toString(), registry.definitions().stream().anyMatch(definition -> definition.id().startsWith("style/")));
assertTrue(diagnostics.toString(), diagnostics.stream().anyMatch(diagnostic -> diagnostic.limit() == ExportLimit.NOISE_STYLE));
}
@Test
public void selectorStylesLowerCellValuesInQuadrants() {
NoiseStyleCompiler compiler = NoiseStyleCompiler.create(new ArrayList<>());
NoiseRegistry registry = new NoiseRegistry("iris_export");
ExportCapabilities current = ExportCapabilities.forTarget(DataVersion.V26_3);
IrisGeneratorStyle style = new IrisGeneratorStyle(NoiseStyle.CELLULAR_IRIS_DOUBLE);
Field terrain = compiler.compile(style, 7L, registry, current);
Field selector = compiler.selectors().compile(style, 7L, registry, current);
assertEquals(9, hashNoises(terrain));
assertEquals(4, hashNoises(selector));
assertSame(compiler.selectors(), compiler.selectors().selectors());
StyleCompiler plain = (ignored, salt, ignoredRegistry, capabilities) -> new Field.Const(0.0);
assertSame(plain, plain.selectors());
assertSame(SMOOTH, SMOOTH.selectors());
}
@Test
public void cellularizedStylesGoThroughTheSeam() {
Field marker = new Field.Const(0.75);
NoiseStyleCompiler compiler = new NoiseStyleCompiler((style, salt, registry, capabilities) -> marker);
IrisGeneratorStyle style = new IrisGeneratorStyle(NoiseStyle.SIMPLEX);
style.setCellularFrequency(2.0);
assertSame(marker, compiler.compile(style, 7L, new NoiseRegistry("iris_export"), CAPABILITIES));
}
@Test
public void smoothStylesStayTwoDimensional() {
NoiseRegistry registry = new NoiseRegistry("iris_export");
Field field = SMOOTH.compile(new IrisGeneratorStyle(NoiseStyle.NOWHERE), 7L, registry, CAPABILITIES);
FieldValidator.requireTwoDimensional(field, "nowhere");
assertEquals(3, registry.definitions().size());
}
@Test
public void expressionStylesAreRejected() {
IrisGeneratorStyle expression = new IrisGeneratorStyle(NoiseStyle.SIMPLEX);
expression.setExpression("strata");
NoiseRegistry registry = new NoiseRegistry("iris_export");
assertThrows(IllegalArgumentException.class, () -> SMOOTH.compile(expression, 7L, registry, CAPABILITIES));
}
@Test
public void imageMapStylesCompileTheirBaseNoise() {
IrisGeneratorStyle image = new IrisGeneratorStyle(NoiseStyle.SIMPLEX);
image.setImageMap("heights");
NoiseRegistry imageRegistry = new NoiseRegistry("iris_export");
NoiseRegistry baseRegistry = new NoiseRegistry("iris_export");
Field imageField = SMOOTH.compile(image, 7L, imageRegistry, CAPABILITIES);
Field baseField = SMOOTH.compile(new IrisGeneratorStyle(NoiseStyle.SIMPLEX), 7L, baseRegistry, CAPABILITIES);
assertEquals(baseField, imageField);
assertEquals(baseRegistry.definitions(), imageRegistry.definitions());
}
@Test
public void flatStyleIsConstant() {
NoiseRegistry registry = new NoiseRegistry("iris_export");
Field field = SMOOTH.compile(new IrisGeneratorStyle(NoiseStyle.FLAT), 7L, registry, CAPABILITIES);
assertEquals(1.0, sample(field, registry, 31, -17), 0.0);
}
@Test
public void layerExponentOffsetAndBezierMatchIris() {
IrisNoiseGenerator layer = flatLayer(0.8, -0.1);
layer.setExponent(1.7);
layer.setBezier(true);
assertLayerMatchesIris(layer, FLOAT_TOLERANCE);
}
@Test
public void layerNegativeAndParametricMatchIris() {
IrisNoiseGenerator layer = flatLayer(0.6, 0.35);
layer.setNegative(true);
layer.setParametric(true);
assertLayerMatchesIris(layer, FLOAT_TOLERANCE);
}
@Test
public void layerSignedExponentMatchesIris() {
IrisNoiseGenerator layer = flatLayer(-0.5, -0.4);
layer.setExponent(2.5);
assertLayerMatchesIris(layer, FLOAT_TOLERANCE);
}
@Test
public void layerSineCentringMatchesIrisWithinSplineTolerance() {
IrisNoiseGenerator layer = flatLayer(0.3, 0.05);
layer.setSinCentered(true);
assertLayerMatchesIris(layer, 1.0e-4);
}
@Test
public void disabledLayerIsItsOffset() {
IrisNoiseGenerator layer = flatLayer(0.5, 0.2);
layer.setEnabled(false);
assertLayerMatchesIris(layer, FLOAT_TOLERANCE);
}
@Test
public void additiveCompositeMatchesIris() {
IrisGenerator generator = generator(false);
assertCompositeMatchesIris(generator);
}
@Test
public void multiplicativeCompositeMatchesIris() {
IrisGenerator generator = generator(true);
assertCompositeMatchesIris(generator);
}
@Test
public void zeroOpacityCompositeIsRejected() {
IrisGenerator generator = new IrisGenerator();
generator.setComposite(new KList<>(List.of(flatLayer(0.0, 0.1))));
assertThrows(IllegalArgumentException.class, () -> SMOOTH.compileComposite(generator, SEED, new NoiseRegistry("iris_export"), CAPABILITIES));
}
@Test
public void layerOffsetsTranslateTheSampledNoise() {
IrisNoiseGenerator plain = new IrisNoiseGenerator();
plain.setStyle(new IrisGeneratorStyle(NoiseStyle.PERLIN));
plain.setZoom(2.0);
IrisNoiseGenerator shifted = new IrisNoiseGenerator();
shifted.setStyle(new IrisGeneratorStyle(NoiseStyle.PERLIN));
shifted.setZoom(2.0);
shifted.setOffsetX(3.0);
shifted.setOffsetZ(-2.0);
NoiseRegistry registry = new NoiseRegistry("iris_export");
Field plainField = SMOOTH.compileLayer(plain, SEED, registry, CAPABILITIES);
Field shiftedField = SMOOTH.compileLayer(shifted, SEED, registry, CAPABILITIES);
for (int x = -40; x <= 40; x += 13) {
for (int z = -40; z <= 40; z += 17) {
assertEquals(sample(plainField, registry, x + 6, z - 4), sample(shiftedField, registry, x, z), 1.0e-9);
}
}
}
@Test
public void styledRangeLerpsBetweenItsBounds() {
NoiseRegistry registry = new NoiseRegistry("iris_export");
IrisStyledRange flat = new IrisStyledRange(10.0, 20.0, new IrisGeneratorStyle(NoiseStyle.FLAT));
assertEquals(15.0, sample(SMOOTH.compileRange(flat, SEED, registry, CAPABILITIES), registry, 0, 0), 0.0);
IrisStyledRange perlin = new IrisStyledRange(10.0, 20.0, new IrisGeneratorStyle(NoiseStyle.PERLIN));
Field range = SMOOTH.compileRange(perlin, SEED, registry, CAPABILITIES);
Field unit = SMOOTH.compile(perlin.getStyle(), SEED, registry, CAPABILITIES);
for (int x = 0; x < 64; x += 9) {
assertEquals(10.0 + 10.0 * sample(unit, registry, x, 3 * x), sample(range, registry, x, 3 * x), 20.0 * FLOAT_TOLERANCE);
}
}
@Test
public void rootWarpExistsOnlyForFracturedStyles() {
NoiseRegistry registry = new NoiseRegistry("iris_export");
Optional<NoiseStyleCompiler.Warp> warp = SMOOTH.compileRootWarp(new IrisGeneratorStyle(NoiseStyle.CELLULAR_IRIS), SEED, registry, CAPABILITIES);
assertTrue(warp.isPresent());
FieldValidator.requireTwoDimensional(warp.get().x(), "warp x");
FieldValidator.requireTwoDimensional(warp.get().z(), "warp z");
assertTrue(SMOOTH.compileRootWarp(new IrisGeneratorStyle(NoiseStyle.PERLIN), SEED, registry, CAPABILITIES).isEmpty());
}
@Test
public void layerFractureUnderCellularStyleIsRejected() {
IrisNoiseGenerator layer = new IrisNoiseGenerator();
layer.setStyle(new IrisGeneratorStyle(NoiseStyle.CELLULAR));
layer.setFracture(new KList<>(List.of(flatLayer(1.0, 0.0))));
NoiseStyleCompiler compiler = new NoiseStyleCompiler((style, salt, registry, capabilities) -> new Field.Const(0.5));
assertThrows(IllegalArgumentException.class, () -> compiler.compileLayer(layer, SEED, new NoiseRegistry("iris_export"), CAPABILITIES));
}
private static void assertLayerMatchesIris(IrisNoiseGenerator layer, double tolerance) {
NoiseRegistry registry = new NoiseRegistry("iris_export");
Field field = SMOOTH.compileLayer(layer, SEED, registry, CAPABILITIES);
for (int x = -20; x <= 20; x += 10) {
assertEquals(layer.getNoise(SUPER_SEED, x, -x, null), sample(field, registry, x, -x), tolerance);
}
}
private static void assertCompositeMatchesIris(IrisGenerator generator) {
NoiseRegistry registry = new NoiseRegistry("iris_export");
Field field = SMOOTH.compileComposite(generator, SEED, registry, CAPABILITIES);
for (int x = -30; x <= 30; x += 15) {
assertEquals(generator.getHeight(x, 2 * x, SUPER_SEED), sample(field, registry, x, 2 * x), FLOAT_TOLERANCE);
}
}
private static IrisGenerator generator(boolean multiplicative) {
IrisNoiseGenerator first = flatLayer(0.5, 0.1);
first.setExponent(2.0);
IrisNoiseGenerator second = flatLayer(1.5, -0.3);
second.setNegative(true);
second.setOffsetY(0.25);
IrisGenerator generator = new IrisGenerator();
generator.setComposite(new KList<>(List.of(first, second)));
generator.setOpacity(2.0);
generator.setZoom(1.5);
generator.setOffsetX(12.0);
generator.setMultiplicitive(multiplicative);
return generator;
}
private static IrisNoiseGenerator flatLayer(double opacity, double offsetY) {
IrisNoiseGenerator layer = new IrisNoiseGenerator();
layer.setStyle(new IrisGeneratorStyle(NoiseStyle.FLAT));
layer.setOpacity(opacity);
layer.setOffsetY(offsetY);
return layer;
}
private static double sample(Field field, NoiseRegistry registry, int x, int z) {
return FieldEvaluator.sample(field, registry.byReference(), SEED, TARGET, x, 0, z);
}
private static int hashNoises(Field root) {
int count = 0;
for (Field.Noise noise : FieldWalk.nodesOf(root, Field.Noise.class)) {
if (noise.noiseId().endsWith(":" + CellHashNoise.NOISE_ID)) {
count++;
}
}
return count;
}
}
@@ -0,0 +1,444 @@
package art.arcane.iris.pack.datapack.export.compile.noise;
import art.arcane.iris.generation.noise.IrisGeneratorStyle;
import art.arcane.iris.generation.noise.IrisNoiseGenerator;
import art.arcane.iris.generation.noise.NoiseStyle;
import art.arcane.iris.pack.datapack.DataVersion;
import art.arcane.iris.pack.datapack.export.ir.Field;
import art.arcane.iris.pack.datapack.export.ir.FieldEvaluator;
import art.arcane.iris.pack.datapack.export.ir.FieldValidator;
import art.arcane.iris.pack.datapack.export.ir.NoiseDef;
import art.arcane.iris.pack.datapack.export.lower.ExportCapabilities;
import art.arcane.volmlib.util.math.RNG;
import art.arcane.volmlib.util.noise.CNG;
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import org.junit.Assume;
import org.junit.Test;
import java.io.IOException;
import java.io.Reader;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.EnumSet;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.function.DoubleBinaryOperator;
import java.util.stream.Stream;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
public final class SmoothNoiseFidelityTest {
private static final int SIZE = 512;
private static final int STRIDE = 23;
private static final double PEAK_SMOOTHING = 0.2;
private static final long IRIS_SEED = 90_210L;
private static final long SALT = 77L;
private static final String NAMESPACE = "iris_export";
private static final String PACK_PROPERTY = "iris.exportProbePack";
private static final DataVersion TARGET = DataVersion.V26_3;
private static final ExportCapabilities CAPABILITIES = ExportCapabilities.forTarget(TARGET);
private static final int[][] WINDOWS = {
{0, 0}, {131_072, 0}, {0, -131_072}, {-262_144, 65_536},
{65_536, 65_536}, {-65_536, -131_072}, {196_608, -65_536}, {-131_072, 196_608}
};
private static final CellularStyleLowering CELLULAR_STUB = (style, salt, registry, capabilities) -> new Field.Const(0.5);
private static final NoiseStyleCompiler COMPILER = new NoiseStyleCompiler(CELLULAR_STUB);
@Test
public void simplexHistogramWithinW1() {
IrisGeneratorStyle style = new IrisGeneratorStyle(NoiseStyle.SIMPLEX);
NoiseRegistry registry = new NoiseRegistry(NAMESPACE);
Field field = COMPILER.compile(style, SALT, registry, CAPABILITIES);
CNG iris = style.createNoCache(new RNG(IRIS_SEED), null);
double[] irisValues = grid((x, z) -> iris.noise(x, z), 0, 0, SIZE, STRIDE);
double[] lowered = new double[0];
for (int window = 0; window < 4; window++) {
DoubleBinaryOperator sampler = lowered(field, registry, worldSeed(window));
lowered = concat(lowered, grid(sampler, WINDOWS[window][0], WINDOWS[window][1], SIZE / 2, STRIDE));
}
double distance = wasserstein(irisValues, lowered) / deviation(irisValues);
assertTrue("SIMPLEX marginal W1 is " + distance + " standard deviations", distance <= 0.03);
}
@Test
public void fbmSpectrumPeakWithin10Percent() {
IrisGeneratorStyle style = new IrisGeneratorStyle(NoiseStyle.QUADOCTAVE_FRACTAL_FBM_SIMPLEX).zoomed(0.5);
NoiseRegistry registry = new NoiseRegistry(NAMESPACE);
Field field = COMPILER.compile(style, SALT, registry, CAPABILITIES);
CNG iris = style.createNoCache(new RNG(IRIS_SEED), null);
double[] irisSpectrum = new double[SIZE / 2];
double[] loweredSpectrum = new double[SIZE / 2];
for (int window = 0; window < WINDOWS.length; window++) {
int originX = WINDOWS[window][0];
int originZ = WINDOWS[window][1];
accumulate(irisSpectrum, spectrum(grid((x, z) -> iris.noise(x, z), originX, originZ, SIZE, 1)));
accumulate(loweredSpectrum, spectrum(grid(lowered(field, registry, worldSeed(window)), originX, originZ, SIZE, 1)));
}
double irisPeak = peak(irisSpectrum);
double loweredPeak = peak(loweredSpectrum);
double ratio = loweredPeak / irisPeak;
assertTrue("FBM dominant frequency " + loweredPeak + " against Iris " + irisPeak, Math.abs(ratio - 1.0) <= 0.10);
}
@Test
public void ridgedUsesAbsFold() {
IrisGeneratorStyle style = new IrisGeneratorStyle(NoiseStyle.TRIOCTAVE_FRACTAL_RM_SIMPLEX);
NoiseRegistry registry = new NoiseRegistry(NAMESPACE);
Field field = COMPILER.compile(style, SALT, registry, CAPABILITIES);
List<Field> nodes = new ArrayList<>();
collect(field, nodes);
long noises = nodes.stream().filter(Field.Noise.class::isInstance).count();
long folds = nodes.stream().filter(node -> node instanceof Field.Unary unary && unary.op() == Field.UnaryOp.ABS).count();
assertEquals(3L, noises);
assertEquals(3L, folds);
assertEquals(3, registry.definitions().size());
for (Field node : nodes) {
if (node instanceof Field.Unary unary && unary.op() == Field.UnaryOp.ABS) {
assertTrue(unary.input() instanceof Field.Curve curve && curve.input() instanceof Field.Noise);
}
}
}
@Test
public void warpedStyleFragmentCountWithin15Percent() {
IrisGeneratorStyle style = new IrisGeneratorStyle(NoiseStyle.NOWHERE).zoomed(0.5);
NoiseRegistry registry = new NoiseRegistry(NAMESPACE);
Field field = COMPILER.compile(style, SALT, registry, CAPABILITIES);
CNG iris = style.createNoCache(new RNG(IRIS_SEED), null);
long irisFragments = 0L;
long loweredFragments = 0L;
for (int window = 0; window < WINDOWS.length; window++) {
int originX = WINDOWS[window][0];
int originZ = WINDOWS[window][1];
irisFragments += fragments(grid((x, z) -> iris.noise(x, z), originX, originZ, SIZE, 1));
loweredFragments += fragments(grid(lowered(field, registry, worldSeed(window)), originX, originZ, SIZE, 1));
}
double ratio = (double) loweredFragments / irisFragments;
assertTrue("NOWHERE fragments " + loweredFragments + " against Iris " + irisFragments, Math.abs(ratio - 1.0) <= 0.15);
}
@Test
public void fittingIsDeterministic() {
IrisGeneratorStyle style = new IrisGeneratorStyle(NoiseStyle.NOWHERE).zoomed(0.75);
NoiseRegistry first = new NoiseRegistry(NAMESPACE);
NoiseRegistry second = new NoiseRegistry(NAMESPACE);
Field firstField = new NoiseStyleCompiler(CELLULAR_STUB).compile(style, SALT, first, CAPABILITIES);
Field secondField = new NoiseStyleCompiler(CELLULAR_STUB).compile(style, SALT, second, CAPABILITIES);
assertEquals(firstField, secondField);
assertEquals(firstField.toString(), secondField.toString());
assertEquals(first.definitions(), second.definitions());
}
@Test
public void everyOverworldStyleCompiles() throws IOException {
String pack = System.getProperty(PACK_PROPERTY);
Assume.assumeTrue("Set -P" + PACK_PROPERTY + " to the overworld pack folder", pack != null && !pack.isBlank());
Path root = Path.of(pack);
Assume.assumeTrue("Pack folder " + root + " is missing", Files.isDirectory(root));
Set<String> styles = new LinkedHashSet<>();
List<JsonObject> generators = new ArrayList<>();
try (Stream<Path> files = Files.walk(root)) {
for (Path file : files.filter(path -> path.toString().endsWith(".json")).sorted().toList()) {
String relative = root.relativize(file).toString();
if (relative.startsWith("jigsaw") || relative.startsWith("objects") || relative.equals("Schema.json")) {
continue;
}
JsonElement json = parse(file);
collectStyles(json, styles);
if (relative.startsWith("generators") && json.isJsonObject()) {
generators.add(json.getAsJsonObject());
}
}
}
Gson gson = new Gson();
Set<NoiseStyle> cellular = EnumSet.noneOf(NoiseStyle.class);
CellularStyleLowering recording = (style, salt, registry, capabilities) -> {
cellular.add(style.getStyle());
return new Field.Const(0.5);
};
NoiseStyleCompiler compiler = new NoiseStyleCompiler(recording);
NoiseRegistry registry = new NoiseRegistry(NAMESPACE);
int compiled = 0;
for (String json : styles) {
IrisGeneratorStyle style = gson.fromJson(json, IrisGeneratorStyle.class);
FieldValidator.requireTwoDimensional(compiler.compile(style, SALT + compiled, registry, CAPABILITIES), json);
compiled++;
}
int layers = 0;
for (JsonObject generator : generators) {
JsonArray composite = generator.has("composite") ? generator.getAsJsonArray("composite") : new JsonArray();
for (JsonElement layer : composite) {
IrisNoiseGenerator noise = gson.fromJson(layer, IrisNoiseGenerator.class);
FieldValidator.requireTwoDimensional(compiler.compileLayer(noise, SALT + layers, registry, CAPABILITIES), layer.toString());
layers++;
}
}
System.out.println("Compiled " + compiled + " overworld styles and " + layers + " generator layers into "
+ registry.definitions().size() + " noise definitions; cellular styles through the seam: " + cellular);
assertTrue(compiled > 0);
assertTrue(layers > 0);
}
private static void collectStyles(JsonElement element, Set<String> styles) {
if (element.isJsonArray()) {
for (JsonElement child : element.getAsJsonArray()) {
collectStyles(child, styles);
}
return;
}
if (!element.isJsonObject()) {
return;
}
JsonObject object = element.getAsJsonObject();
if (isStyle(object)) {
styles.add(object.toString());
}
for (Map.Entry<String, JsonElement> entry : object.entrySet()) {
collectStyles(entry.getValue(), styles);
}
}
private static boolean isStyle(JsonObject object) {
if (object.has("expression") || object.has("imageMap") || !object.has("style") || !object.get("style").isJsonPrimitive()) {
return false;
}
String name = object.get("style").getAsString();
return Arrays.stream(NoiseStyle.values()).anyMatch(style -> style.name().equals(name));
}
private static JsonElement parse(Path file) throws IOException {
try (Reader reader = Files.newBufferedReader(file, StandardCharsets.UTF_8)) {
return JsonParser.parseReader(reader);
}
}
private static void collect(Field field, List<Field> nodes) {
nodes.add(field);
switch (field) {
case Field.Noise noise -> {
for (Field shift : new Field[]{noise.shiftX(), noise.shiftY(), noise.shiftZ()}) {
if (shift != null) {
collect(shift, nodes);
}
}
}
case Field.Binary binary -> {
collect(binary.left(), nodes);
collect(binary.right(), nodes);
}
case Field.Unary unary -> collect(unary.input(), nodes);
case Field.Curve curve -> collect(curve.input(), nodes);
case Field.Shared shared -> collect(shared.expr(), nodes);
default -> {
}
}
}
private static long worldSeed(int window) {
return 4_242L + 7_919L * window;
}
private static DoubleBinaryOperator lowered(Field field, NoiseRegistry registry, long worldSeed) {
Map<String, NoiseDef> noises = registry.byReference();
return (x, z) -> FieldEvaluator.sample(field, noises, worldSeed, TARGET, (int) x, 0, (int) z);
}
private static double[] grid(DoubleBinaryOperator field, int originX, int originZ, int size, int stride) {
double[] values = new double[size * size];
for (int z = 0; z < size; z++) {
for (int x = 0; x < size; x++) {
values[z * size + x] = field.applyAsDouble(originX + x * stride, originZ + z * stride);
}
}
return values;
}
private static double[] concat(double[] first, double[] second) {
double[] joined = Arrays.copyOf(first, first.length + second.length);
System.arraycopy(second, 0, joined, first.length, second.length);
return joined;
}
private static double wasserstein(double[] first, double[] second) {
double[] a = first.clone();
double[] b = second.clone();
Arrays.sort(a);
Arrays.sort(b);
double sum = 0.0;
for (int index = 0; index < a.length; index++) {
int matched = (int) Math.min(b.length - 1, (long) index * b.length / a.length);
sum += Math.abs(a[index] - b[matched]);
}
return sum / a.length;
}
private static double deviation(double[] values) {
double mean = Arrays.stream(values).average().orElse(0.0);
double sum = 0.0;
for (double value : values) {
sum += (value - mean) * (value - mean);
}
return Math.sqrt(sum / values.length);
}
private static long fragments(double[] values) {
double[] sorted = values.clone();
Arrays.sort(sorted);
double low = sorted[(int) (sorted.length * 0.15)];
double high = sorted[(int) (sorted.length * 0.85)];
return components(values, high, true) + components(values, low, false);
}
private static int components(double[] values, double threshold, boolean above) {
boolean[] visited = new boolean[values.length];
ArrayDeque<Integer> queue = new ArrayDeque<>();
int count = 0;
for (int start = 0; start < values.length; start++) {
if (visited[start] || !inside(values[start], threshold, above)) {
continue;
}
count++;
visited[start] = true;
queue.add(start);
while (!queue.isEmpty()) {
int cell = queue.poll();
int x = cell % SIZE;
int z = cell / SIZE;
int[] neighbours = {x > 0 ? cell - 1 : -1, x < SIZE - 1 ? cell + 1 : -1, z > 0 ? cell - SIZE : -1, z < SIZE - 1 ? cell + SIZE : -1};
for (int neighbour : neighbours) {
if (neighbour >= 0 && !visited[neighbour] && inside(values[neighbour], threshold, above)) {
visited[neighbour] = true;
queue.add(neighbour);
}
}
}
}
return count;
}
private static boolean inside(double value, double threshold, boolean above) {
return above ? value > threshold : value < threshold;
}
private static void accumulate(double[] total, double[] addition) {
for (int index = 0; index < total.length; index++) {
total[index] += addition[index];
}
}
private static double[] spectrum(double[] values) {
double mean = Arrays.stream(values).average().orElse(0.0);
double[] real = new double[SIZE * SIZE];
double[] imaginary = new double[SIZE * SIZE];
for (int z = 0; z < SIZE; z++) {
for (int x = 0; x < SIZE; x++) {
real[z * SIZE + x] = (values[z * SIZE + x] - mean) * hann(x) * hann(z);
}
}
for (int row = 0; row < SIZE; row++) {
fft(real, imaginary, row * SIZE, 1);
}
for (int column = 0; column < SIZE; column++) {
fft(real, imaginary, column, SIZE);
}
double total = 0.0;
double[] perOctave = new double[SIZE / 2];
for (int kz = 0; kz < SIZE; kz++) {
for (int kx = 0; kx < SIZE; kx++) {
int fx = kx <= SIZE / 2 ? kx : kx - SIZE;
int fz = kz <= SIZE / 2 ? kz : kz - SIZE;
int radius = (int) Math.round(Math.sqrt(fx * fx + fz * fz));
if (radius == 0 || radius >= perOctave.length) {
continue;
}
int index = kz * SIZE + kx;
double power = (real[index] * real[index] + imaginary[index] * imaginary[index]) * radius;
perOctave[radius] += power;
total += power;
}
}
for (int radius = 0; radius < perOctave.length; radius++) {
perOctave[radius] /= total;
}
return perOctave;
}
private static double peak(double[] spectrum) {
double[] smoothed = new double[spectrum.length];
for (int radius = 2; radius < spectrum.length; radius++) {
double sum = 0.0;
int count = 0;
for (int other = 2; other < spectrum.length; other++) {
if (Math.abs(Math.log((double) other / radius)) <= PEAK_SMOOTHING) {
sum += spectrum[other];
count++;
}
}
smoothed[radius] = sum / count;
}
int best = 3;
for (int radius = 3; radius < spectrum.length - 1; radius++) {
if (smoothed[radius] > smoothed[best]) {
best = radius;
}
}
double left = Math.log(smoothed[best - 1]);
double centre = Math.log(smoothed[best]);
double right = Math.log(smoothed[best + 1]);
double curvature = left - 2.0 * centre + right;
double offset = curvature == 0.0 ? 0.0 : 0.5 * (left - right) / curvature;
return (best + offset) / SIZE;
}
private static double hann(int index) {
return 0.5 - 0.5 * Math.cos(2.0 * Math.PI * index / (SIZE - 1));
}
private static void fft(double[] real, double[] imaginary, int offset, int stride) {
for (int index = 1, swap = 0; index < SIZE; index++) {
int bit = SIZE >> 1;
for (; (swap & bit) != 0; bit >>= 1) {
swap ^= bit;
}
swap ^= bit;
if (index < swap) {
exchange(real, offset + index * stride, offset + swap * stride);
exchange(imaginary, offset + index * stride, offset + swap * stride);
}
}
for (int length = 2; length <= SIZE; length <<= 1) {
double angle = -2.0 * Math.PI / length;
for (int start = 0; start < SIZE; start += length) {
for (int step = 0; step < length / 2; step++) {
double cos = Math.cos(angle * step);
double sin = Math.sin(angle * step);
int even = offset + (start + step) * stride;
int odd = offset + (start + step + length / 2) * stride;
double oddReal = real[odd] * cos - imaginary[odd] * sin;
double oddImaginary = real[odd] * sin + imaginary[odd] * cos;
real[odd] = real[even] - oddReal;
imaginary[odd] = imaginary[even] - oddImaginary;
real[even] += oddReal;
imaginary[even] += oddImaginary;
}
}
}
}
private static void exchange(double[] values, int first, int second) {
double value = values[first];
values[first] = values[second];
values[second] = value;
}
}
@@ -0,0 +1,75 @@
package art.arcane.iris.pack.datapack.export.compile.noise;
import art.arcane.iris.pack.datapack.DataVersion;
import art.arcane.iris.pack.datapack.export.ir.Field;
import art.arcane.iris.pack.datapack.export.ir.FieldEvaluator;
import org.junit.Test;
import java.util.List;
import java.util.Map;
import java.util.SplittableRandom;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertThrows;
import static org.junit.Assert.assertTrue;
public final class ValueDistributionFitTest {
private static final int SAMPLES = 20_000;
@Test
public void curveMapsSourceQuantilesOntoTargetQuantiles() {
SplittableRandom random = new SplittableRandom(5L);
double[] source = new double[SAMPLES];
double[] target = new double[SAMPLES];
for (int index = 0; index < SAMPLES; index++) {
source[index] = random.nextDouble() * 2.0 - 1.0;
double uniform = random.nextDouble();
target[index] = uniform * uniform;
}
List<Field.Knot> knots = ValueDistributionFit.fit(source, target);
for (double input = -0.9; input <= 0.9; input += 0.05) {
double expected = Math.pow((input + 1.0) / 2.0, 2.0);
Field curve = new Field.Curve(new Field.Const(input), knots);
double actual = FieldEvaluator.sample(curve, Map.of(), 0L, DataVersion.V26_3, 0, 0, 0);
assertEquals("quantile map at " + input, expected, actual, 0.02);
}
}
@Test
public void knotsIncreaseAndStayMonotone() {
SplittableRandom random = new SplittableRandom(9L);
double[] source = new double[SAMPLES];
double[] target = new double[SAMPLES];
for (int index = 0; index < SAMPLES; index++) {
source[index] = random.nextGaussian();
target[index] = Math.exp(random.nextGaussian());
}
List<Field.Knot> knots = ValueDistributionFit.fit(source, target);
for (int index = 0; index < knots.size(); index++) {
Field.Knot knot = knots.get(index);
assertTrue(knot.derivative() >= 0.0);
if (index > 0) {
Field.Knot previous = knots.get(index - 1);
assertTrue(knot.location() > previous.location());
assertTrue(((Field.Const) knot.value()).value() >= ((Field.Const) previous.value()).value());
}
}
assertEquals(0.0, knots.getFirst().derivative(), 0.0);
assertEquals(0.0, knots.getLast().derivative(), 0.0);
}
@Test
public void constantSourceIsRejected() {
double[] constant = new double[256];
double[] target = new double[256];
for (int index = 0; index < target.length; index++) {
target[index] = index;
}
assertThrows(IllegalArgumentException.class, () -> ValueDistributionFit.fit(constant, target));
}
@Test
public void tooFewSamplesAreRejected() {
assertThrows(IllegalArgumentException.class, () -> ValueDistributionFit.fit(new double[8], new double[8]));
}
}
@@ -0,0 +1,195 @@
package art.arcane.iris.pack.datapack.export.compile.noise;
import art.arcane.iris.pack.datapack.DataVersion;
import art.arcane.iris.pack.datapack.export.WorldgenExportTargets;
import org.junit.Test;
import java.util.Collections;
import java.util.List;
import java.util.SplittableRandom;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertThrows;
import static org.junit.Assert.assertTrue;
public final class VanillaNoiseModelTest {
private static final int POINTS = 4096;
private static final long WORLD_SEED = 8_675_309L;
private static final String NOISE_ID = "iris_export:model_test";
private static final List<DataVersion> TARGETS = WorldgenExportTargets.SUPPORTED;
private static final List<Double> FBM = List.of(1.0D, 1.0D, 0.5D, 0.25D);
private static final double OCTAVE_DEVIATION = 0.2702247831245211D;
private static final double PERLIN_BOUND = 2.0D;
@Test
public void identicalInputsSampleIdentically() {
for (DataVersion target : TARGETS) {
VanillaNoiseModel first = VanillaNoiseModel.create(NOISE_ID, -8, FBM, WORLD_SEED, target);
VanillaNoiseModel second = VanillaNoiseModel.create(NOISE_ID, -8, FBM, WORLD_SEED, target);
double[][] points = points(11L);
for (double[] point : points) {
assertEquals(Double.doubleToRawLongBits(first.sample(point[0], point[1], point[2])),
Double.doubleToRawLongBits(second.sample(point[0], point[1], point[2])));
}
}
}
@Test
public void seedAndIdentifierSelectDifferentFields() {
for (DataVersion target : TARGETS) {
VanillaNoiseModel base = VanillaNoiseModel.create(NOISE_ID, -8, FBM, WORLD_SEED, target);
VanillaNoiseModel reseeded = VanillaNoiseModel.create(NOISE_ID, -8, FBM, WORLD_SEED + 1L, target);
VanillaNoiseModel renamed = VanillaNoiseModel.create("iris_export:model_test_b", -8, FBM, WORLD_SEED, target);
assertTrue(maxDifference(base, reseeded) > 0.0D);
assertTrue(maxDifference(base, renamed) > 0.0D);
}
}
@Test
public void unqualifiedIdentifierHashesAsDefaultNamespace() {
for (DataVersion target : TARGETS) {
VanillaNoiseModel bare = VanillaNoiseModel.create("model_test", -8, FBM, WORLD_SEED, target);
VanillaNoiseModel qualified = VanillaNoiseModel.create("minecraft:model_test", -8, FBM, WORLD_SEED, target);
assertEquals(0.0D, maxDifference(bare, qualified), 0.0D);
}
}
@Test
public void zeroAmplitudeOctavesAreSkipped() {
for (DataVersion target : TARGETS) {
VanillaNoiseModel padded = VanillaNoiseModel.create(NOISE_ID, -9, List.of(0.0D, 0.0D, 1.0D), WORLD_SEED, target);
VanillaNoiseModel single = VanillaNoiseModel.create(NOISE_ID, -7, List.of(1.0D), WORLD_SEED, target);
double scale = fittedScale(padded, single);
assertTrue(scale > 0.0D);
for (double[] point : points(23L)) {
double expected = scale * single.sample(point[0], point[1], point[2]);
assertEquals(expected, padded.sample(point[0], point[1], point[2]), 1.0E-6D);
}
}
}
@Test
public void zeroAmplitudesSampleZero() {
for (DataVersion target : TARGETS) {
VanillaNoiseModel silent = VanillaNoiseModel.create(NOISE_ID, -6, List.of(0.0D, 0.0D), WORLD_SEED, target);
for (double[] point : points(31L)) {
assertEquals(0.0D, silent.sample(point[0], point[1], point[2]), 0.0D);
}
}
}
@Test
public void modernSamplesStayWithinDeclaredRange() {
VanillaNoiseModel model = VanillaNoiseModel.create(NOISE_ID, -8, FBM, WORLD_SEED, DataVersion.V26_3);
double amplitudeSum = 0.0D;
double squaredDeviation = 0.0D;
for (int index = 0; index < FBM.size(); index++) {
double amplitude = FBM.get(index) / Math.pow(2.0D, index);
amplitudeSum += amplitude;
squaredDeviation += Math.pow(OCTAVE_DEVIATION * amplitude, 2.0D);
}
double normalization = (amplitudeSum / 3.0D) / (Math.sqrt(squaredDeviation) * Math.sqrt(2.0D));
assertWithinRange(model, 2.0D * PERLIN_BOUND * normalization * amplitudeSum * (1.0D + 1.0E-6D));
}
@Test
public void modernSamplesAreSinglePrecision() {
VanillaNoiseModel model = VanillaNoiseModel.create(NOISE_ID, -8, FBM, WORLD_SEED, DataVersion.V26_3);
for (double[] point : points(43L)) {
double value = model.sample(point[0], point[1], point[2]);
assertEquals(value, (float) value, 0.0D);
}
}
@Test
public void baseAmplitudeScalesOutput() {
VanillaNoiseModel.OctaveProfile unit = new VanillaNoiseModel.OctaveProfile(-8, FBM.size(), FBM, 1.0D,
VanillaNoiseModel.Normalization.ENABLED);
VanillaNoiseModel.OctaveProfile doubled = new VanillaNoiseModel.OctaveProfile(-8, FBM.size(), FBM, 2.0D,
VanillaNoiseModel.Normalization.ENABLED);
VanillaNoiseModel first = VanillaNoiseModel.create(NOISE_ID, unit, WORLD_SEED);
VanillaNoiseModel second = VanillaNoiseModel.create(NOISE_ID, doubled, WORLD_SEED);
for (double[] point : points(59L)) {
assertEquals(2.0D * first.sample(point[0], point[1], point[2]), second.sample(point[0], point[1], point[2]), 1.0E-6D);
}
}
@Test
public void mappedProfileUsesUnitAmplitudeWithoutNormalization() {
VanillaNoiseModel.OctaveProfile profile = VanillaNoiseModel.OctaveProfile.fromAmplitudes(-8, FBM);
assertEquals(-8, profile.baseOctave());
assertEquals(FBM.size(), profile.octaveCount());
assertEquals(FBM, profile.amplitudeModifiers());
assertEquals(1.0D, profile.baseAmplitude(), 0.0D);
assertEquals(VanillaNoiseModel.Normalization.DISABLED, profile.normalization());
}
@Test
public void modernDefinitionsOutsideTheCodecAreRejected() {
assertThrows(IllegalArgumentException.class,
() -> VanillaNoiseModel.create(NOISE_ID, 33, List.of(1.0D), WORLD_SEED, DataVersion.V26_3));
assertThrows(IllegalArgumentException.class,
() -> VanillaNoiseModel.create(NOISE_ID, -33, List.of(1.0D), WORLD_SEED, DataVersion.V26_3));
assertThrows(IllegalArgumentException.class,
() -> VanillaNoiseModel.create(NOISE_ID, -8, List.of(1.0D, -0.5D), WORLD_SEED, DataVersion.V26_3));
assertThrows(IllegalArgumentException.class,
() -> VanillaNoiseModel.create(NOISE_ID, -8, List.of(), WORLD_SEED, DataVersion.V26_3));
assertThrows(IllegalArgumentException.class,
() -> VanillaNoiseModel.create(NOISE_ID, -8, Collections.nCopies(33, 1.0D), WORLD_SEED,
DataVersion.V26_3));
assertThrows(IllegalArgumentException.class,
() -> new VanillaNoiseModel.OctaveProfile(-8, 2, List.of(1.0D), 1.0D, VanillaNoiseModel.Normalization.ENABLED));
assertThrows(IllegalArgumentException.class,
() -> new VanillaNoiseModel.OctaveProfile(-8, 1, List.of(), 0.0D, VanillaNoiseModel.Normalization.ENABLED));
}
@Test
public void unsupportedTargetsAreRejected() {
for (DataVersion older : List.of(DataVersion.V1_21_1, DataVersion.V26_2)) {
IllegalArgumentException failure = assertThrows(IllegalArgumentException.class,
() -> VanillaNoiseModel.create(NOISE_ID, -8, FBM, WORLD_SEED, older));
assertTrue(failure.getMessage().contains(older.getVersion()));
}
}
private static void assertWithinRange(VanillaNoiseModel model, double bound) {
double peak = 0.0D;
for (double[] point : points(37L)) {
double value = model.sample(point[0], point[1], point[2]);
assertTrue(Double.isFinite(value));
peak = Math.max(peak, Math.abs(value));
}
assertTrue("peak " + peak + " exceeds " + bound, peak <= bound);
assertTrue("peak " + peak + " is degenerate", peak > bound * 0.05D);
}
private static double fittedScale(VanillaNoiseModel target, VanillaNoiseModel reference) {
double product = 0.0D;
double square = 0.0D;
for (double[] point : points(61L)) {
double referenceValue = reference.sample(point[0], point[1], point[2]);
product += target.sample(point[0], point[1], point[2]) * referenceValue;
square += referenceValue * referenceValue;
}
return product / square;
}
private static double maxDifference(VanillaNoiseModel first, VanillaNoiseModel second) {
double difference = 0.0D;
for (double[] point : points(67L)) {
difference = Math.max(difference,
Math.abs(first.sample(point[0], point[1], point[2]) - second.sample(point[0], point[1], point[2])));
}
return difference;
}
private static double[][] points(long salt) {
SplittableRandom random = new SplittableRandom(salt);
double[][] points = new double[POINTS][];
for (int index = 0; index < POINTS; index++) {
points[index] = new double[]{random.nextDouble(-60_000.0D, 60_000.0D), random.nextDouble(-64.0D, 320.0D),
random.nextDouble(-60_000.0D, 60_000.0D)};
}
return points;
}
}
@@ -0,0 +1,58 @@
package art.arcane.iris.pack.datapack.export.compile.object;
import art.arcane.iris.pack.datapack.export.ir.ExportDiagnostic;
import art.arcane.iris.pack.datapack.export.ir.ExportLimit;
import art.arcane.iris.world.loot.IrisLoot;
import art.arcane.iris.world.loot.IrisLootTable;
import art.arcane.volmlib.util.collection.KList;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import org.junit.Test;
import java.util.ArrayList;
import java.util.List;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
public class LootCompilerTest {
@Test
public void rarityBecomesProportionalWeight() {
IrisLootTable table = table();
List<ExportDiagnostic> diagnostics = new ArrayList<>();
JsonObject json = new LootCompiler("iris_export", null).table(table, diagnostics);
JsonObject pool = json.getAsJsonArray("pools").get(0).getAsJsonObject();
JsonArray entries = pool.getAsJsonArray("entries");
assertEquals(3, entries.size());
assertEquals("minecraft:diamond", entries.get(0).getAsJsonObject().get("name").getAsString());
assertEquals(4, entries.get(0).getAsJsonObject().get("weight").getAsInt());
assertEquals(2, entries.get(1).getAsJsonObject().get("weight").getAsInt());
assertEquals(1, entries.get(2).getAsJsonObject().get("weight").getAsInt());
assertEquals("minecraft:set_count", entries.get(1).getAsJsonObject().getAsJsonArray("modifier").get(0).getAsJsonObject().get("type").getAsString());
JsonObject rolls = pool.getAsJsonObject("rolls");
assertEquals(2, rolls.get("min").getAsInt());
assertEquals(5, rolls.get("max").getAsInt());
assertEquals(1.0 / 3, pool.getAsJsonObject("condition").get("chance").getAsDouble(), 1e-6);
assertEquals("minecraft:chest", json.get("type").getAsString());
assertTrue(diagnostics.stream().anyMatch(diagnostic -> diagnostic.limit() == ExportLimit.CUSTOM_ITEM));
assertTrue(diagnostics.stream().anyMatch(diagnostic -> diagnostic.limit() == ExportLimit.LOOT_RARITY));
}
private static IrisLootTable table() {
IrisLootTable table = new IrisLootTable();
table.setLoadKey("treasure");
table.setName("Treasure");
table.setRarity(3);
table.setMinPicked(2);
table.setMaxPicked(5);
KList<IrisLoot> loot = new KList<>();
loot.add(new IrisLoot().setType("DIAMOND").setRarity(1));
loot.add(new IrisLoot().setType("minecraft:gold_ingot").setRarity(2).setMinAmount(1).setMaxAmount(3));
loot.add(new IrisLoot().setType("emerald").setRarity(4));
loot.add(new IrisLoot().setType("mymod:relic").setRarity(1));
table.setLoot(loot);
return table;
}
}
@@ -0,0 +1,157 @@
package art.arcane.iris.pack.datapack.export.compile.object;
import art.arcane.iris.generation.decoration.tree.TreeGrounding;
import art.arcane.iris.pack.datapack.export.TemplateBlock;
import art.arcane.iris.pack.datapack.export.ir.ExportDiagnostic;
import art.arcane.iris.spi.IrisPlatform;
import art.arcane.iris.spi.IrisPlatforms;
import art.arcane.iris.spi.PlatformRegistries;
import art.arcane.iris.structure.object.IrisObject;
import art.arcane.iris.testsupport.PlatformLeakGuard;
import art.arcane.volmlib.nativelib.terrain.NativeBlockState;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.ClassRule;
import org.junit.Test;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
public class ObjectSourceTest {
@ClassRule
public static final PlatformLeakGuard PLATFORM_GUARD = PlatformLeakGuard.clean();
@BeforeClass
public static void bindPlatform() {
IrisPlatforms.unbind();
NativeBlockState stone = blockState("minecraft:stone");
PlatformRegistries registries = mock(PlatformRegistries.class);
when(registries.block(anyString())).thenReturn(stone);
IrisPlatform platform = mock(IrisPlatform.class);
when(platform.registries()).thenReturn(registries);
when(platform.minecraftVersion()).thenReturn("26.3");
IrisPlatforms.bind(platform);
}
@AfterClass
public static void unbindPlatform() {
IrisPlatforms.unbind();
}
@Test
public void containedObjectKeepsItsBox() {
IrisObject object = new IrisObject(3, 3, 3);
object.setUnsigned(1, 0, 1, blockState("minecraft:oak_log[axis=y]"));
object.setUnsigned(0, 2, 2, blockState("minecraft:oak_leaves[distance=1,persistent=true,waterlogged=false]"));
List<ExportDiagnostic> diagnostics = new ArrayList<>();
ObjectSource source = ObjectSource.of(object, "objects/bush", diagnostics);
assertTrue(diagnostics.isEmpty());
assertEquals(0, source.baseY());
assertEquals(3, source.volume().sizeX());
assertEquals(3, source.volume().sizeY());
assertEquals(3, source.volume().sizeZ());
assertEquals(2, source.volume().blocks().size());
}
@Test
public void waterlogIsLeftToThePlacementSite() {
IrisObject object = new IrisObject(1, 2, 1);
object.setUnsigned(0, 0, 0, blockState("minecraft:tube_coral_block"));
object.setUnsigned(0, 1, 0, blockState("minecraft:sea_pickle[pickles=2,waterlogged=true]"));
ObjectSource source = ObjectSource.of(object, "objects/reef", new ArrayList<>());
TemplateBlock pickle = blockAt(source, 0, 1, 0);
assertEquals("false", pickle.state().properties().get("waterlogged"));
assertEquals("2", pickle.state().properties().get("pickles"));
}
@Test
public void rowsAndColumnsPastTheNominalBoxAreKeptAroundTheCenter() {
IrisObject object = new IrisObject(3, 3, 3);
object.setUnsigned(1, -1, 1, blockState("minecraft:oak_log[axis=y]"));
object.setUnsigned(1, 0, 1, blockState("minecraft:oak_log[axis=y]"));
object.setUnsigned(-1, 1, 1, blockState("minecraft:oak_log[axis=x]"));
List<ExportDiagnostic> diagnostics = new ArrayList<>();
ObjectSource source = ObjectSource.of(object, "objects/tree", diagnostics);
assertTrue(diagnostics.isEmpty());
assertEquals(3, source.volume().blocks().size());
assertEquals(-1, source.baseY());
int centerX = source.volume().sizeX() / 2;
int centerZ = source.volume().sizeZ() / 2;
TemplateBlock root = blockAt(source, centerX, 0, centerZ);
assertEquals("minecraft:oak_log", root.state().name());
TemplateBlock branch = blockAt(source, centerX - 2, 2, centerZ);
assertEquals("x", branch.state().properties().get("axis"));
BakedVariant variant = new ObjectVariantBaker().bake("iris_export:object/tree/a", source, VariantSpec.builder().build());
assertEquals(-1, variant.baseY());
assertEquals(3, variant.volume().blocks().size());
}
@Test
public void treeRootsFollowTheTemplateShift() {
IrisObject object = new IrisObject(3, 3, 3);
NativeBlockState root = blockState("minecraft:oak_wood[axis=y]");
object.setUnsigned(1, -1, 1, root);
object.setUnsigned(0, -2, 1, root);
object.setUnsigned(0, -1, 1, root);
object.setUnsigned(1, 0, 1, blockState("minecraft:oak_log[axis=y]"));
object.setTreeGrounding(TreeGrounding.create(List.of(
new TreeGrounding.Root(0, -2, 0, root),
new TreeGrounding.Root(-1, -3, 0, root),
new TreeGrounding.Root(-1, -2, 0, root)), 3, Set.of()));
ObjectSource source = ObjectSource.of(object, "procedural/tree", new ArrayList<>());
assertEquals(-2, source.baseY());
assertEquals(3, source.roots().reach());
assertEquals(List.of("0,0,1", "1,1,1"), cells(source.roots()));
assertEquals("minecraft:oak_wood", source.roots().cells().getFirst().state().name());
}
@Test
public void objectsWithoutGroundingHaveNoRoots() {
IrisObject object = new IrisObject(1, 1, 1);
object.setUnsigned(0, 0, 0, blockState("minecraft:stone"));
assertFalse(ObjectSource.of(object, "objects/rock", new ArrayList<>()).roots().present());
}
private static List<String> cells(TreeRoots roots) {
List<String> cells = new ArrayList<>();
for (TemplateBlock cell : roots.cells()) {
cells.add(cell.x() + "," + cell.y() + "," + cell.z());
}
return cells;
}
private static TemplateBlock blockAt(ObjectSource source, int x, int y, int z) {
for (TemplateBlock block : source.volume().blocks()) {
if (block.x() == x && block.y() == y && block.z() == z) {
return block;
}
}
throw new AssertionError("No block at " + x + "," + y + "," + z + " in " + source.volume().blocks());
}
private static NativeBlockState blockState(String key) {
NativeBlockState state = mock(NativeBlockState.class);
when(state.key()).thenReturn(key);
when(state.namespace()).thenReturn(key.substring(0, key.indexOf(':')));
return state;
}
}
@@ -0,0 +1,413 @@
package art.arcane.iris.pack.datapack.export.compile.object;
import art.arcane.iris.configuration.IrisSettings;
import art.arcane.iris.generation.terrain.IrisDimension;
import art.arcane.iris.pack.datapack.DataVersion;
import art.arcane.iris.pack.datapack.export.WorldgenExportMode;
import art.arcane.iris.pack.datapack.export.WorldgenExportProgress;
import art.arcane.iris.pack.datapack.export.WorldgenExportRequest;
import art.arcane.iris.pack.datapack.export.compile.CompileStage;
import art.arcane.iris.pack.datapack.export.compile.DimensionStage;
import art.arcane.iris.pack.datapack.export.compile.PackCompileContext;
import art.arcane.iris.pack.datapack.export.compile.PackCompiler;
import art.arcane.iris.pack.datapack.export.compile.biome.BiomeCodes;
import art.arcane.iris.pack.datapack.export.compile.decoration.GenerationStep;
import art.arcane.iris.pack.datapack.export.ir.BinaryResource;
import art.arcane.iris.pack.datapack.export.ir.BiomeDef;
import art.arcane.iris.pack.datapack.export.ir.ClimateLayout;
import art.arcane.iris.pack.datapack.export.ir.ExportIr;
import art.arcane.iris.pack.datapack.export.ir.ExportLimit;
import art.arcane.iris.pack.datapack.export.ir.Field;
import art.arcane.iris.pack.datapack.export.ir.JsonResource;
import art.arcane.iris.pack.datapack.export.lower.ExportCapabilities;
import art.arcane.iris.pack.loading.IrisData;
import art.arcane.iris.spi.IrisPlatforms;
import art.arcane.iris.testsupport.CompatTestPlatform;
import art.arcane.iris.testsupport.PlatformLeakGuard;
import art.arcane.volmlib.util.nbt.io.NBTUtil;
import art.arcane.volmlib.util.nbt.tag.CompoundTag;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import org.junit.ClassRule;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExternalResource;
import org.junit.rules.TemporaryFolder;
import java.io.ByteArrayInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Stream;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotEquals;
import static org.junit.Assert.assertTrue;
import static org.mockito.Mockito.doReturn;
public class ObjectStageTest {
private static final String NAMESPACE = WorldgenExportRequest.DEFAULT_NAMESPACE;
private static final String FOREST = NAMESPACE + ":forest";
private static final String PLAINS = NAMESPACE + ":plains";
private static final Field ZERO = new Field.Const(0.0);
@ClassRule
public static final PlatformLeakGuard PLATFORM_GUARD = PlatformLeakGuard.clean();
@Rule
public TemporaryFolder temporaryFolder = new TemporaryFolder();
@Rule
public BoundPlatform platform = new BoundPlatform();
@Test
public void objectsFalseExportsNoObjects() throws Exception {
File pack = pack();
IrisData data = IrisData.openRuntime(pack);
try {
ExportIr ir = compile(data, DataVersion.V26_3, false);
assertTrue(ir.jsonResources().isEmpty());
assertTrue(ir.binaryResources().isEmpty());
for (BiomeDef biome : ir.biomes()) {
for (JsonElement step : biome.json().getAsJsonArray("features")) {
assertEquals(0, step.getAsJsonArray().size());
}
}
} finally {
data.close();
}
}
@Test
public void objectsExportTemplatesFeaturesAndBiomeLists() throws Exception {
File pack = pack();
IrisData data = IrisData.openRuntime(pack);
try {
ExportIr ir = compile(data, DataVersion.V26_3, true);
assertTrue(paths(ir).stream().anyMatch(path -> path.startsWith("data/iris_export/worldgen/feature/object/")));
assertTrue(paths(ir).stream().anyMatch(path -> path.startsWith("data/iris_export/worldgen/placed_feature/object/")));
assertTrue(paths(ir).stream().noneMatch(path -> path.contains("configured_feature")));
assertFalse(ir.binaryResources().isEmpty());
for (BinaryResource template : ir.binaryResources()) {
assertTrue(template.path(), template.path().startsWith("data/iris_export/structure/object/"));
assertTrue(template.path().endsWith(".nbt"));
CompoundTag root = (CompoundTag) NBTUtil.read(new ByteArrayInputStream(template.bytes()), true).getTag();
assertEquals(5023, root.getInt("DataVersion"));
}
JsonArray forest = features(ir, "forest");
assertEquals(1, forest.get(GenerationStep.VEGETAL_DECORATION.ordinal()).getAsJsonArray().size());
assertEquals(1, forest.get(GenerationStep.SURFACE_STRUCTURES.ordinal()).getAsJsonArray().size());
JsonArray plains = features(ir, "plains");
assertEquals(0, plains.get(GenerationStep.VEGETAL_DECORATION.ordinal()).getAsJsonArray().size());
assertEquals(1, plains.get(GenerationStep.SURFACE_STRUCTURES.ordinal()).getAsJsonArray().size());
Set<String> referenced = new HashSet<>();
for (BiomeDef biome : ir.biomes()) {
for (JsonElement step : biome.json().getAsJsonArray("features")) {
for (JsonElement feature : step.getAsJsonArray()) {
referenced.add("data/iris_export/worldgen/placed_feature/" + feature.getAsString().substring(NAMESPACE.length() + 1) + ".json");
}
}
}
assertTrue(paths(ir).containsAll(referenced));
assertTrue(ir.diagnostics().stream().anyMatch(diagnostic -> diagnostic.limit() == ExportLimit.STRUCTURE_AVOIDANCE));
} finally {
data.close();
}
}
@Test
public void proceduralTreesExportAsTemplates() throws Exception {
File pack = pack();
CompatTestPlatform.write(pack, "biomes/plains.json", """
{"name":"Plains","proceduralObjects":{"trees":[{"name":"field-oak","chance":0.5,"density":2,"variants":2,"seed":7,
"trunk":"minecraft:oak_log","leaves":"minecraft:oak_leaves","heightMin":5,"heightMax":7}]}}
""");
IrisData data = IrisData.openRuntime(pack);
try {
ExportIr ir = compile(data, DataVersion.V26_3, true);
JsonArray plains = features(ir, "plains");
assertEquals(1, plains.get(GenerationStep.VEGETAL_DECORATION.ordinal()).getAsJsonArray().size());
long templates = ir.binaryResources().stream()
.filter(template -> template.path().contains("/procedural/") && template.path().contains("field-oak"))
.count();
assertTrue("procedural templates: " + templates, templates >= 2);
} finally {
data.close();
}
}
@Test
public void proceduralTreeRootsReachDownToTheTerrain() throws Exception {
File pack = pack();
CompatTestPlatform.write(pack, "biomes/plains.json", """
{"name":"Plains","proceduralObjects":{"trees":[{"name":"field-oak","chance":0.5,"density":2,"variants":2,"seed":7,
"trunk":"minecraft:oak_log","leaves":"minecraft:oak_leaves","heightMin":5,"heightMax":7,"rootStyle":"TAPROOT","rootDepth":3}]}}
""");
IrisData data = IrisData.openRuntime(pack);
try {
ExportIr ir = compile(data, DataVersion.V26_3, true);
String placedId = features(ir, "plains").get(GenerationStep.VEGETAL_DECORATION.ordinal()).getAsJsonArray().get(0).getAsString();
JsonObject placed = json(ir, "data/iris_export/worldgen/placed_feature/" + placedId.substring(NAMESPACE.length() + 1) + ".json");
String featureId = placed.get("feature").getAsString();
JsonObject feature = json(ir, "data/iris_export/worldgen/feature/" + featureId.substring(NAMESPACE.length() + 1) + ".json");
assertEquals("minecraft:weighted_random_selector", feature.get("type").getAsString());
Set<String> pillars = new HashSet<>();
for (JsonElement branch : feature.getAsJsonArray("features")) {
JsonObject entry = branch.getAsJsonObject().getAsJsonObject("data");
JsonArray parts = entry.getAsJsonObject("feature").getAsJsonArray("features");
for (int index = 1; index < parts.size(); index++) {
pillars.add(parts.get(index).getAsJsonObject().get("feature").getAsString());
}
}
assertFalse(pillars.isEmpty());
for (String pillar : pillars) {
assertTrue(pillar, paths(ir).contains("data/iris_export/worldgen/feature/" + pillar.substring(NAMESPACE.length() + 1) + ".json"));
}
} finally {
data.close();
}
}
@Test
public void proceduralObjectsSharedByBiomesShareTemplates() throws Exception {
String procedural = """
"proceduralObjects":{"trees":[{"name":"field-oak","chance":0.5,"density":2,"variants":2,"seed":7,
"trunk":"minecraft:oak_log","leaves":"minecraft:oak_leaves","heightMin":5,"heightMax":7}]}""";
File pack = pack();
CompatTestPlatform.write(pack, "biomes/plains.json", "{\"name\":\"Plains\"," + procedural + "}");
CompatTestPlatform.write(pack, "biomes/forest.json", "{\"name\":\"Forest\"," + procedural + "}");
IrisData data = IrisData.openRuntime(pack);
try {
ExportIr ir = compile(data, DataVersion.V26_3, true);
Set<String> objects = new HashSet<>();
for (BinaryResource template : ir.binaryResources()) {
if (template.path().contains("field-oak")) {
objects.add(template.path().substring(0, template.path().lastIndexOf('/')));
}
}
assertEquals(objects.toString(), 2, objects.size());
assertEquals(1, features(ir, "forest").get(GenerationStep.VEGETAL_DECORATION.ordinal()).getAsJsonArray().size());
assertEquals(1, features(ir, "plains").get(GenerationStep.VEGETAL_DECORATION.ordinal()).getAsJsonArray().size());
} finally {
data.close();
}
}
@Test
public void lootBoundPerBiome() throws Exception {
File pack = pack();
IrisData data = IrisData.openRuntime(pack);
try {
ExportIr modern = compile(data, DataVersion.V26_3, true);
String forestHut = features(modern, "forest").get(GenerationStep.SURFACE_STRUCTURES.ordinal()).getAsJsonArray().get(0).getAsString();
String plainsHut = features(modern, "plains").get(GenerationStep.SURFACE_STRUCTURES.ordinal()).getAsJsonArray().get(0).getAsString();
assertNotEquals(forestHut, plainsHut);
String forestTable = appendedLoot(modern, forestHut);
String plainsTable = appendedLoot(modern, plainsHut);
assertNotEquals(forestTable, plainsTable);
assertTrue(lootReferences(modern, forestTable).contains("iris_export:iris/forest_loot"));
assertTrue(lootReferences(modern, plainsTable).contains("iris_export:iris/plains_loot"));
assertTrue(paths(modern).contains("data/iris_export/loot_table/iris/forest_loot.json"));
} finally {
data.close();
}
}
@Test
public void exportIsDeterministic() throws Exception {
File pack = pack();
IrisData data = IrisData.openRuntime(pack);
try {
ExportIr first = compile(data, DataVersion.V26_3, true);
ExportIr second = compile(data, DataVersion.V26_3, true);
assertEquals(first.jsonResources(), second.jsonResources());
assertEquals(first.binaryResources().size(), second.binaryResources().size());
for (int index = 0; index < first.binaryResources().size(); index++) {
assertEquals(first.binaryResources().get(index).path(), second.binaryResources().get(index).path());
assertArrayEquals(first.binaryResources().get(index).bytes(), second.binaryResources().get(index).bytes());
}
assertEquals(first.biomes(), second.biomes());
} finally {
data.close();
}
}
private static ExportIr compile(IrisData data, DataVersion target, boolean objects) {
IrisDimension dimension = data.getDimensionLoader().load("main", false);
PackCompileContext context = PackCompileContext.builder()
.data(data)
.dimension(dimension)
.capabilities(ExportCapabilities.forTarget(target))
.namespace(NAMESPACE)
.mode(WorldgenExportMode.PRESET)
.objects(objects)
.build();
CompileStage biomes = new CompileStage() {
@Override
public String name() {
return "biomes";
}
@Override
public void apply(PackCompileContext context) {
JsonObject body = new JsonObject();
body.addProperty("has_precipitation", true);
context.setBiomes(List.of(new BiomeDef("forest", body), new BiomeDef("plains", body)));
ClimateLayout layout = new ClimateLayout(List.of(
new ClimateLayout.ClimateEntry(FOREST, ClimateLayout.ClimateAxis.TEMPERATURE, -1.0, 0.0),
new ClimateLayout.ClimateEntry(PLAINS, ClimateLayout.ClimateAxis.TEMPERATURE, 0.0, 1.0)));
context.setBiomeCodes(new BiomeCodes(ZERO, ZERO, ZERO, layout, Map.of(FOREST, "forest", PLAINS, "plains")));
}
};
return new PackCompiler(List.of(new DimensionStage(), biomes, new ObjectStage())).compile(context, WorldgenExportProgress.NONE);
}
private File pack() throws IOException {
File pack = temporaryFolder.newFolder("pack");
CompatTestPlatform.write(pack, "dimensions/main.json", "{\"regions\":[\"region\"]}");
CompatTestPlatform.write(pack, "regions/region.json", """
{"landBiomes":["forest","plains"],
"objects":[{"place":["huts/hut"],"chance":0.1,"density":1,"rotation":{"yAxis":{"enabled":true,"interval":45}}}]}
""");
CompatTestPlatform.write(pack, "biomes/forest.json", """
{"name":"Forest","loot":{"tables":["forest_loot"]},
"objects":[{"place":["trees/oak"],"chance":0.5,"density":3,"scale":{"minimumScale":0.75,"maximumScale":1.5,"variations":3}}]}
""");
CompatTestPlatform.write(pack, "biomes/plains.json", "{\"name\":\"Plains\",\"loot\":{\"tables\":[\"plains_loot\"]}}");
CompatTestPlatform.write(pack, "loot/forest_loot.json", "{\"name\":\"Forest\",\"loot\":[{\"type\":\"DIAMOND\",\"rarity\":2}]}");
CompatTestPlatform.write(pack, "loot/plains_loot.json", "{\"name\":\"Plains\",\"loot\":[{\"type\":\"WHEAT\",\"rarity\":1}]}");
writeObject(pack, "trees/oak", "minecraft:oak_log", "minecraft:oak_leaves", "minecraft:oak_leaves");
writeObject(pack, "huts/hut", "minecraft:cobblestone", "minecraft:chest", "minecraft:cobblestone");
return pack;
}
private static void writeObject(File pack, String key, String... column) throws IOException {
File file = new File(pack, "objects/" + key + ".iob");
if (!file.getParentFile().isDirectory() && !file.getParentFile().mkdirs()) {
throw new IOException("Could not create " + file.getParentFile());
}
try (DataOutputStream out = new DataOutputStream(new FileOutputStream(file))) {
out.writeInt(1);
out.writeInt(column.length);
out.writeInt(1);
out.writeUTF("Iris V2 IOB;");
out.writeShort(column.length);
for (String entry : column) {
out.writeUTF(entry);
}
out.writeInt(column.length);
for (int index = 0; index < column.length; index++) {
out.writeShort(0);
out.writeShort(index - column.length / 2);
out.writeShort(0);
out.writeShort(index);
}
out.writeInt(0);
}
}
private static JsonArray features(ExportIr ir, String biome) {
for (BiomeDef definition : ir.biomes()) {
if (definition.id().equals(biome)) {
return definition.json().getAsJsonArray("features");
}
}
throw new AssertionError("No biome " + biome);
}
private static String appendedLoot(ExportIr ir, String placedFeature) {
JsonObject placed = json(ir, "data/iris_export/worldgen/placed_feature/" + placedFeature.substring(NAMESPACE.length() + 1) + ".json");
String featureId = placed.get("feature").getAsString();
JsonObject feature = json(ir, "data/iris_export/worldgen/feature/" + featureId.substring(NAMESPACE.length() + 1) + ".json");
for (JsonElement processor : feature.getAsJsonObject("processors").getAsJsonArray("processors")) {
for (JsonElement rule : processor.getAsJsonObject().getAsJsonArray("rules")) {
JsonObject modifier = rule.getAsJsonObject().getAsJsonObject("block_entity_modifier");
if (modifier != null) {
return modifier.get("loot_table").getAsString();
}
}
}
throw new AssertionError("No append_loot rule in " + featureId);
}
private static List<String> lootReferences(ExportIr ir, String table) {
JsonObject loot = json(ir, "data/iris_export/loot_table/" + table.substring(NAMESPACE.length() + 1) + ".json");
List<String> references = new ArrayList<>();
for (JsonElement pool : loot.getAsJsonArray("pools")) {
for (JsonElement entry : pool.getAsJsonObject().getAsJsonArray("entries")) {
references.add(entry.getAsJsonObject().get("value").getAsString());
}
}
return references;
}
private static JsonObject json(ExportIr ir, String path) {
for (JsonResource resource : ir.jsonResources()) {
if (resource.path().equals(path)) {
return resource.json().getAsJsonObject();
}
}
throw new AssertionError("No resource " + path);
}
private static Set<String> paths(ExportIr ir) {
Set<String> paths = new HashSet<>();
for (JsonResource resource : ir.jsonResources()) {
paths.add(resource.path());
}
for (BinaryResource resource : ir.binaryResources()) {
paths.add(resource.path());
}
return paths;
}
public static final class BoundPlatform extends ExternalResource {
private static final List<String> BLOCKS = List.of("minecraft:air", "minecraft:stone", "minecraft:water",
"minecraft:grass_block", "minecraft:oak_log", "minecraft:oak_leaves", "minecraft:cobblestone", "minecraft:chest");
private IrisSettings previousSettings;
private CompatTestPlatform platform;
private Path folder;
@Override
protected void before() throws IOException {
previousSettings = IrisSettings.settings;
IrisSettings.settings = new IrisSettings();
folder = Files.createTempDirectory("iris-object-export-platform");
platform = CompatTestPlatform.bind(folder.toFile(), BLOCKS);
doReturn("0.9").when(IrisPlatforms.get()).minecraftVersion();
}
@Override
protected void after() {
platform.unbind();
IrisSettings.settings = previousSettings;
try (Stream<Path> paths = Files.walk(folder)) {
for (Path path : paths.sorted(Comparator.reverseOrder()).toList()) {
Files.deleteIfExists(path);
}
} catch (IOException exception) {
throw new IllegalStateException("Could not remove test platform folder " + folder, exception);
}
}
}
}
@@ -0,0 +1,448 @@
package art.arcane.iris.pack.datapack.export.compile.object;
import art.arcane.iris.pack.datapack.DataVersion;
import art.arcane.iris.pack.datapack.export.StructureTemplateEncoder;
import art.arcane.iris.pack.datapack.export.TemplateBlock;
import art.arcane.iris.pack.datapack.export.TemplateVolume;
import art.arcane.iris.pack.datapack.export.VanillaBlockState;
import art.arcane.iris.pack.datapack.export.compile.WeightedState;
import art.arcane.volmlib.util.nbt.tag.CompoundTag;
import org.junit.Test;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotEquals;
import static org.junit.Assert.assertTrue;
public class ObjectVariantBakerTest {
private static final String NAMESPACE = "iris_export";
private static final String LEAVES = "minecraft:oak_leaves[distance=1,persistent=true,waterlogged=false]";
private static final long RIGHT_ANGLE_GOLDEN = 0x5db739a5b940bf1dL;
@Test
public void variantBakingIsDeterministic() throws IOException {
TemplateVolume tree = tree();
ObjectEdit chanceEdit = new ObjectEdit(List.of(VanillaBlockState.parse("minecraft:oak_leaves")), false,
List.of(new WeightedState(VanillaBlockState.parse("minecraft:birch_leaves"), 1),
new WeightedState(VanillaBlockState.parse("minecraft:azalea_leaves"), 3)), 0.5);
VariantSpec spec = VariantSpec.builder()
.scale(1.5)
.rotation(new VariantSpec.Rotation(0, 45, 0))
.warp(new VariantWarp("simplex", 2, (x, y, z) -> Math.sin(x * 0.3) * 2))
.snow(0.6)
.edits(List.of(chanceEdit))
.build();
String id = ObjectVariantBaker.templateId(NAMESPACE, "trees/oak", spec, DataVersion.V26_3);
BakedVariant first = new ObjectVariantBaker().bake(id, new ObjectSource(tree, 0, TreeRoots.NONE), spec);
BakedVariant second = new ObjectVariantBaker().bake(id, new ObjectSource(tree, 0, TreeRoots.NONE), spec);
assertEquals(first, second);
assertEquals(id, ObjectVariantBaker.templateId(NAMESPACE, "trees/oak", spec, DataVersion.V26_3));
assertTrue(id.startsWith("iris_export:object/trees/oak/"));
assertArrayEquals(new StructureTemplateEncoder().encode(first.volume(), DataVersion.V26_3),
new StructureTemplateEncoder().encode(second.volume(), DataVersion.V26_3));
VariantSpec otherAngle = VariantSpec.builder().rotation(new VariantSpec.Rotation(0, 30, 0)).build();
assertNotEquals(id, ObjectVariantBaker.templateId(NAMESPACE, "trees/oak", otherAngle, DataVersion.V26_3));
}
@Test
public void unchangedVariantKeepsSizeAndDropsAir() {
TemplateVolume volume = new TemplateVolume(2, 2, 1, List.of(
block(0, 0, 0, "minecraft:stone"),
block(1, 0, 0, "minecraft:air"),
block(0, 1, 0, "minecraft:cave_air")));
BakedVariant variant = new ObjectVariantBaker()
.bake("iris_export:object/rock/a", new ObjectSource(volume, 0, TreeRoots.NONE), VariantSpec.builder().build());
assertEquals(List.of("minecraft:stone"), states(variant.volume()));
assertEquals(2, variant.volume().sizeX());
assertEquals(2, variant.volume().sizeY());
assertEquals(0, variant.baseY());
}
@Test
public void plantsWithNothingUnderThemAreLeftOut() {
TemplateVolume reef = new TemplateVolume(3, 4, 3, List.of(
block(1, 0, 1, "minecraft:sea_pickle[pickles=1,waterlogged=false]"),
block(0, 0, 0, "minecraft:tube_coral_block"),
block(0, 1, 0, "minecraft:tube_coral_block"),
block(0, 2, 0, "minecraft:sea_pickle[pickles=2,waterlogged=false]"),
block(2, 2, 2, "minecraft:sea_pickle[pickles=3,waterlogged=false]"),
block(2, 1, 0, "minecraft:tube_coral_fan[waterlogged=false]"),
block(1, 1, 0, "minecraft:tube_coral_wall_fan[facing=east,waterlogged=false]"),
block(1, 2, 0, "minecraft:tube_coral_wall_fan[facing=west,waterlogged=false]"),
block(2, 3, 2, "minecraft:tube_coral_block")));
BakedVariant variant = new ObjectVariantBaker()
.bake("iris_export:object/reef/a", new ObjectSource(reef, 0, TreeRoots.NONE), VariantSpec.builder().build());
Set<String> kept = new HashSet<>();
for (TemplateBlock block : variant.volume().blocks()) {
kept.add(block.x() + "," + block.y() + "," + block.z() + " " + block.state().name());
}
assertEquals(Set.of("1,0,1 minecraft:sea_pickle", "0,0,0 minecraft:tube_coral_block", "0,1,0 minecraft:tube_coral_block",
"0,2,0 minecraft:sea_pickle", "1,1,0 minecraft:tube_coral_wall_fan", "2,3,2 minecraft:tube_coral_block"), kept);
}
@Test
public void quarterRotationMovesBlocksAndFacing() {
TemplateVolume volume = new TemplateVolume(3, 1, 3, List.of(
block(1, 0, 1, "minecraft:stone"),
block(1, 0, 0, "minecraft:oak_stairs[facing=north,half=bottom,shape=straight,waterlogged=false]")));
VariantSpec spec = VariantSpec.builder().rotation(new VariantSpec.Rotation(0, 90, 0)).build();
BakedVariant variant = new ObjectVariantBaker().bake("iris_export:object/s/a", new ObjectSource(volume, 0, TreeRoots.NONE), spec);
TemplateBlock stairs = variant.volume().blocks().stream()
.filter(block -> block.state().name().equals("minecraft:oak_stairs")).findFirst().orElseThrow();
assertEquals("west", stairs.state().properties().get("facing"));
assertEquals(0, stairs.x());
assertEquals(0, stairs.z());
}
@Test
public void verticalFlipFlipsHalves() {
TemplateVolume volume = new TemplateVolume(1, 2, 1, List.of(
block(0, 0, 0, "minecraft:stone"),
block(0, 1, 0, "minecraft:oak_slab[type=bottom,waterlogged=false]")));
VariantSpec spec = VariantSpec.builder().rotation(new VariantSpec.Rotation(180, 0, 0)).build();
BakedVariant variant = new ObjectVariantBaker().bake("iris_export:object/f/a", new ObjectSource(volume, 0, TreeRoots.NONE), spec);
TemplateBlock slab = variant.volume().blocks().getFirst();
assertEquals("minecraft:oak_slab", slab.state().name());
assertEquals("top", slab.state().properties().get("type"));
assertEquals(0, slab.y());
}
@Test
public void scaleGrowsTheTemplate() {
TemplateVolume volume = new TemplateVolume(2, 2, 2, List.of(
block(0, 0, 0, "minecraft:oak_log[axis=y]"),
block(1, 1, 1, "minecraft:oak_log[axis=y]")));
VariantSpec scaled = VariantSpec.builder().scale(2).build();
BakedVariant big = new ObjectVariantBaker().bake("iris_export:object/l/a", new ObjectSource(volume, 0, TreeRoots.NONE), scaled);
assertEquals(16, big.volume().blocks().size());
assertEquals(4, big.volume().sizeY());
}
@Test
public void deterministicEditsBakeAndChanceEditsRoll() {
List<TemplateBlock> blocks = new ArrayList<>();
for (int x = 0; x < 16; x++) {
for (int z = 0; z < 16; z++) {
blocks.add(block(x, 0, z, "minecraft:cobblestone"));
}
}
TemplateVolume floor = new TemplateVolume(16, 1, 16, blocks);
ObjectEdit always = new ObjectEdit(List.of(VanillaBlockState.parse("minecraft:cobblestone")), false,
List.of(new WeightedState(VanillaBlockState.parse("minecraft:stone_bricks"), 1)), 1);
ObjectEdit half = new ObjectEdit(List.of(VanillaBlockState.parse("minecraft:stone_bricks")), false,
List.of(new WeightedState(VanillaBlockState.parse("minecraft:mossy_stone_bricks"), 1)), 0.5);
BakedVariant variant = new ObjectVariantBaker().bake("iris_export:object/floor/a", new ObjectSource(floor, 0, TreeRoots.NONE),
VariantSpec.builder().edits(List.of(always, half)).build());
Set<String> names = new HashSet<>();
int mossy = 0;
for (TemplateBlock block : variant.volume().blocks()) {
names.add(block.state().name());
if (block.state().name().equals("minecraft:mossy_stone_bricks")) {
mossy++;
}
}
assertEquals(Set.of("minecraft:stone_bricks", "minecraft:mossy_stone_bricks"), names);
assertTrue(mossy > 96 && mossy < 160);
}
@Test
public void basesAlignAcrossVariants() {
BakedVariant low = new BakedVariant("iris_export:object/a/low", new TemplateVolume(1, 3, 1, List.of(block(0, 0, 0, "minecraft:stone"))), -2, TreeRoots.NONE);
BakedVariant flat = new BakedVariant("iris_export:object/a/flat", new TemplateVolume(1, 1, 1, List.of(block(0, 0, 0, "minecraft:stone"))), 0, TreeRoots.NONE);
List<BakedVariant> aligned = ObjectVariantBaker.alignBases(List.of(low, flat));
assertEquals(low, aligned.get(0));
assertEquals(-2, aligned.get(1).baseY());
assertEquals("iris_export:object/a/flat_lift2", aligned.get(1).id());
assertEquals(2, aligned.get(1).volume().blocks().getFirst().y());
assertEquals(3, aligned.get(1).volume().sizeY());
assertFalse(aligned.get(1).volume().blocks().isEmpty());
}
@Test
public void rootsSurviveAnUnchangedBake() {
TemplateVolume volume = new TemplateVolume(3, 2, 3, List.of(
block(1, 0, 1, "minecraft:oak_wood[axis=y]"),
block(2, 0, 1, "minecraft:oak_wood[axis=y]"),
block(1, 1, 1, "minecraft:oak_log[axis=y]")));
TreeRoots roots = new TreeRoots(List.of(block(1, 0, 1, "minecraft:oak_wood[axis=y]"),
block(2, 0, 1, "minecraft:oak_wood[axis=y]")), 3);
BakedVariant variant = new ObjectVariantBaker()
.bake("iris_export:object/tree/a", new ObjectSource(volume, 0, roots), VariantSpec.builder().build());
assertEquals(roots, variant.roots());
}
@Test
public void rootsTurnWithTheirBlocks() {
TemplateVolume volume = new TemplateVolume(3, 2, 3, List.of(
block(1, 0, 1, "minecraft:oak_wood[axis=y]"),
block(2, 0, 1, "minecraft:spruce_wood[axis=x]"),
block(1, 1, 1, "minecraft:oak_log[axis=y]")));
TreeRoots roots = new TreeRoots(List.of(block(2, 0, 1, "minecraft:spruce_wood[axis=x]")), 2);
VariantSpec spec = VariantSpec.builder().rotation(new VariantSpec.Rotation(0, 90, 0)).build();
BakedVariant variant = new ObjectVariantBaker().bake("iris_export:object/tree/b", new ObjectSource(volume, 0, roots), spec);
TemplateBlock moved = variant.volume().blocks().stream()
.filter(block -> block.state().name().equals("minecraft:spruce_wood")).findFirst().orElseThrow();
assertEquals(1, variant.roots().cells().size());
TemplateBlock root = variant.roots().cells().getFirst();
assertEquals(List.of(moved.x(), moved.y(), moved.z()), List.of(root.x(), root.y(), root.z()));
assertEquals("z", root.state().properties().get("axis"));
assertEquals(2, variant.roots().reach());
}
@Test
public void scaledRootsKeepTheLowestCellPerColumnAndStretchTheirReach() {
TemplateVolume volume = new TemplateVolume(2, 2, 1, List.of(
block(0, 0, 0, "minecraft:oak_wood[axis=y]"),
block(0, 1, 0, "minecraft:oak_log[axis=y]"),
block(1, 1, 0, "minecraft:oak_log[axis=y]")));
TreeRoots roots = new TreeRoots(List.of(block(0, 0, 0, "minecraft:oak_wood[axis=y]")), 3);
BakedVariant variant = new ObjectVariantBaker().bake("iris_export:object/tree/c", new ObjectSource(volume, 0, roots),
VariantSpec.builder().scale(2).build());
assertEquals(6, variant.roots().reach());
assertEquals(4, variant.roots().cells().size());
for (TemplateBlock cell : variant.roots().cells()) {
assertEquals(0, cell.y());
assertEquals("minecraft:oak_wood", cell.state().name());
}
}
@Test
public void alignedBasesLiftRoots() {
TreeRoots roots = new TreeRoots(List.of(block(0, 0, 0, "minecraft:oak_wood[axis=y]")), 2);
BakedVariant low = new BakedVariant("iris_export:object/r/low", new TemplateVolume(1, 3, 1, List.of(block(0, 0, 0, "minecraft:stone"))), -2, TreeRoots.NONE);
BakedVariant rooted = new BakedVariant("iris_export:object/r/rooted", new TemplateVolume(1, 1, 1,
List.of(block(0, 0, 0, "minecraft:oak_wood[axis=y]"))), 0, roots);
BakedVariant lifted = ObjectVariantBaker.alignBases(List.of(low, rooted)).get(1);
assertEquals(2, lifted.roots().cells().getFirst().y());
assertEquals(2, lifted.roots().reach());
}
@Test
public void diagonalTurnsFillSolidCanopiesWithoutHoles() {
for (double degrees : new double[]{45, 135}) {
assertSolid(leafDisc(6, 3), degrees, (x, z) -> x * x + z * z <= 25D);
assertSolid(leafBox(4, 3), degrees, (x, z) -> Math.abs(x) <= 3.75D && Math.abs(z) <= 3.75D);
}
}
@Test
public void diagonalTurnsKeepEveryThinTrunkColumn() {
int[][] columns = {{2, 0}, {0, 2}, {-2, 0}, {3, 1}};
List<TemplateBlock> blocks = new ArrayList<>();
for (int[] column : columns) {
for (int y = 0; y < 6; y++) {
blocks.add(block(column[0] + 3, y, column[1] + 3, "minecraft:oak_log[axis=y]"));
}
}
TemplateVolume trunks = new TemplateVolume(7, 6, 7, blocks);
for (double degrees : new double[]{45, 135, 225, 315}) {
BakedVariant variant = turned(trunks, new VariantSpec.Rotation(0, degrees, 0));
Map<Long, int[]> heights = new HashMap<>();
for (TemplateBlock block : variant.volume().blocks()) {
int x = anchoredX(variant, block);
int z = anchoredZ(variant, block);
heights.computeIfAbsent(cell(x, 0, z), ignored -> new int[]{x, z, 0})[2]++;
}
double cos = Math.cos(Math.toRadians(degrees));
double sin = Math.sin(Math.toRadians(degrees));
for (int[] column : columns) {
long forward = cell((int) Math.round(cos * column[0] + sin * column[1]), 0,
(int) Math.round(-sin * column[0] + cos * column[1]));
boolean kept = false;
for (Map.Entry<Long, int[]> output : heights.entrySet()) {
int[] value = output.getValue();
assertEquals(degrees + " degrees cut a trunk column short", 6, value[2]);
boolean samples = (int) Math.round(cos * value[0] - sin * value[1]) == column[0]
&& (int) Math.round(sin * value[0] + cos * value[1]) == column[1];
kept |= samples || output.getKey() == forward;
}
assertTrue(degrees + " degrees lost the trunk column at " + column[0] + "," + column[1], kept);
}
}
}
@Test
public void rightAngleTurnsKeepTheirExactLayout() {
CompoundTag chest = new CompoundTag();
chest.putString("id", "minecraft:chest");
TemplateVolume volume = new TemplateVolume(4, 4, 4, List.of(
block(0, 0, 0, "minecraft:stone"),
block(3, 0, 1, "minecraft:stone"),
block(1, 1, 2, "minecraft:oak_log[axis=x]"),
block(2, 2, 0, "minecraft:oak_stairs[facing=north,half=bottom,shape=outer_left,waterlogged=false]"),
new TemplateBlock(3, 1, 3, VanillaBlockState.parse("minecraft:chest[facing=east,type=single,waterlogged=false]"), chest),
block(1, 3, 1, "minecraft:oak_leaves[distance=1,persistent=false,waterlogged=false]"),
block(0, 2, 3, "minecraft:oak_slab[type=bottom,waterlogged=false]")));
TreeRoots roots = new TreeRoots(List.of(block(0, 0, 0, "minecraft:stone")), 2);
StringBuilder layout = new StringBuilder();
for (double scale : new double[]{1, 1.5}) {
for (int x = 0; x < 360; x += 90) {
for (int y = 0; y < 360; y += 90) {
for (int z = 0; z < 360; z += 90) {
VariantSpec spec = VariantSpec.builder().scale(scale).rotation(new VariantSpec.Rotation(x, y, z)).build();
describe(layout, new ObjectVariantBaker().bake("iris_export:object/turn/a", new ObjectSource(volume, -1, roots), spec));
}
}
}
}
assertEquals(RIGHT_ANGLE_GOLDEN, fnv(layout));
}
private static void assertSolid(TemplateVolume source, double degrees, Interior interior) {
BakedVariant variant = turned(source, new VariantSpec.Rotation(0, degrees, 0));
Set<Long> covered = new HashSet<>();
for (TemplateBlock block : variant.volume().blocks()) {
assertTrue(degrees + " degrees wrote a cell twice",
covered.add(cell(anchoredX(variant, block), anchoredY(variant, block), anchoredZ(variant, block))));
}
double cos = Math.cos(Math.toRadians(degrees));
double sin = Math.sin(Math.toRadians(degrees));
int reach = Math.max(source.sizeX(), source.sizeZ());
for (int y = 0; y < source.sizeY(); y++) {
for (int x = -reach; x <= reach; x++) {
for (int z = -reach; z <= reach; z++) {
if (interior.contains(cos * x - sin * z, sin * x + cos * z)) {
assertTrue(degrees + " degrees left a hole at " + x + "," + y + "," + z, covered.contains(cell(x, y, z)));
}
}
}
}
}
private static BakedVariant turned(TemplateVolume source, VariantSpec.Rotation rotation) {
return new ObjectVariantBaker().bake("iris_export:object/turn/b", new ObjectSource(source, 0, TreeRoots.NONE),
VariantSpec.builder().rotation(rotation).build());
}
private static int anchoredX(BakedVariant variant, TemplateBlock block) {
return block.x() - (variant.volume().sizeX() - 1) / 2;
}
private static int anchoredY(BakedVariant variant, TemplateBlock block) {
return block.y() + variant.baseY();
}
private static int anchoredZ(BakedVariant variant, TemplateBlock block) {
return block.z() - (variant.volume().sizeZ() - 1) / 2;
}
private static TemplateVolume leafDisc(int radius, int height) {
List<TemplateBlock> blocks = new ArrayList<>();
for (int y = 0; y < height; y++) {
for (int x = -radius; x <= radius; x++) {
for (int z = -radius; z <= radius; z++) {
if (x * x + z * z <= radius * radius) {
blocks.add(block(x + radius, y, z + radius, LEAVES));
}
}
}
}
return new TemplateVolume(radius * 2 + 1, height, radius * 2 + 1, blocks);
}
private static TemplateVolume leafBox(int half, int height) {
List<TemplateBlock> blocks = new ArrayList<>();
for (int y = 0; y < height; y++) {
for (int x = -half; x <= half; x++) {
for (int z = -half; z <= half; z++) {
blocks.add(block(x + half, y, z + half, LEAVES));
}
}
}
return new TemplateVolume(half * 2 + 1, height, half * 2 + 1, blocks);
}
private static void describe(StringBuilder layout, BakedVariant variant) {
TemplateVolume volume = variant.volume();
layout.append(variant.id()).append(' ').append(volume.sizeX()).append('x').append(volume.sizeY()).append('x')
.append(volume.sizeZ()).append(" base=").append(variant.baseY()).append('\n');
for (TemplateBlock block : volume.blocks()) {
layout.append(block.x()).append(',').append(block.y()).append(',').append(block.z()).append(' ')
.append(block.state().canonical()).append(' ')
.append(block.nbt() == null ? "-" : block.nbt().getString("id")).append('\n');
}
layout.append("roots reach=").append(variant.roots().reach()).append('\n');
for (TemplateBlock cell : variant.roots().cells()) {
layout.append(cell.x()).append(',').append(cell.y()).append(',').append(cell.z()).append(' ')
.append(cell.state().canonical()).append('\n');
}
}
private static long fnv(CharSequence text) {
long hash = 0xcbf29ce484222325L;
for (int index = 0; index < text.length(); index++) {
hash ^= text.charAt(index);
hash *= 0x100000001b3L;
}
return hash;
}
private static long cell(int x, int y, int z) {
return (((long) x & 0x1FFFFFL) << 42) | (((long) y & 0x1FFFFFL) << 21) | ((long) z & 0x1FFFFFL);
}
private static TemplateVolume tree() {
List<TemplateBlock> blocks = new ArrayList<>();
for (int y = 0; y < 5; y++) {
blocks.add(block(2, y, 2, "minecraft:oak_log[axis=y]"));
}
for (int x = 0; x < 5; x++) {
for (int z = 0; z < 5; z++) {
if (x != 2 || z != 2) {
blocks.add(block(x, 3, z, "minecraft:oak_leaves[distance=1,persistent=false,waterlogged=false]"));
}
}
}
return new TemplateVolume(5, 5, 5, blocks);
}
private static TemplateBlock block(int x, int y, int z, String state) {
return new TemplateBlock(x, y, z, VanillaBlockState.parse(state), null);
}
private static List<String> states(TemplateVolume volume) {
List<String> states = new ArrayList<>();
for (TemplateBlock block : volume.blocks()) {
states.add(block.state().canonical());
}
return states;
}
private interface Interior {
boolean contains(double x, double z);
}
}
@@ -0,0 +1,966 @@
package art.arcane.iris.pack.datapack.export.compile.object;
import art.arcane.iris.pack.datapack.DataVersion;
import art.arcane.iris.pack.datapack.export.TemplateBlock;
import art.arcane.iris.pack.datapack.export.TemplateVolume;
import art.arcane.iris.pack.datapack.export.VanillaBlockState;
import art.arcane.iris.pack.datapack.export.compile.StageTestPacks;
import art.arcane.iris.pack.datapack.export.compile.decoration.GenerationStep;
import art.arcane.iris.pack.datapack.export.ir.DimensionDef;
import art.arcane.iris.pack.datapack.export.ir.ExportDiagnostic;
import art.arcane.iris.pack.datapack.export.ir.ExportLimit;
import art.arcane.iris.pack.datapack.export.ir.JsonResource;
import art.arcane.iris.pack.datapack.export.lower.ExportCapabilities;
import art.arcane.iris.structure.object.IrisObjectPlacement;
import art.arcane.iris.structure.object.IrisObjectTranslate;
import art.arcane.iris.structure.object.ObjectPlaceMode;
import art.arcane.volmlib.util.collection.KList;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import org.junit.Test;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.Set;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertTrue;
public class PlacementCompilerTest {
private static final String NAMESPACE = "iris_export";
private static final int WINDOW_MIN = -16;
private static final int WINDOW_MAX = 31;
private static final int CHUNK = 16;
private static final DimensionDef DIMENSION = new DimensionDef("main", -64, 384, 384, 63,
"minecraft:stone", "minecraft:water", new JsonObject());
@Test
public void narrowObjectUsesTemplateFeature() {
IrisObjectPlacement placement = placement(ObjectPlaceMode.CENTER_HEIGHT, 0.5, 3);
placement.setTranslate(new IrisObjectTranslate().setY(2));
List<ExportDiagnostic> diagnostics = new ArrayList<>();
CompiledPlacement compiled = compiler(DataVersion.V26_3).compile(input(placement, objects(5, 9), List.of()), diagnostics);
assertSame(GenerationStep.SURFACE_STRUCTURES, compiled.step());
assertEquals(1, compiled.placedFeatures().size());
assertTrue(compiled.structures().isEmpty());
JsonObject feature = feature(compiled, "worldgen/feature/");
assertEquals("minecraft:template", feature.get("type").getAsString());
JsonArray templates = feature.getAsJsonArray("templates");
assertEquals(2, templates.size());
assertEquals(templates.get(0).getAsJsonObject().get("weight"), templates.get(1).getAsJsonObject().get("weight"));
assertFalse(templates.get(0).getAsJsonObject().getAsJsonObject("data").has("rotations"));
JsonObject placed = placed(compiled);
assertEquals(List.of("minecraft:random_chance", "minecraft:count", "minecraft:in_square", "minecraft:heightmap",
"minecraft:block_predicate_filter", "minecraft:block_predicate_filter", "minecraft:offset", "minecraft:biome"), types(placed));
JsonArray modifiers = placed.getAsJsonArray("placement");
assertEquals(0.5, modifiers.get(0).getAsJsonObject().get("chance").getAsDouble(), 1e-6);
assertEquals(3, modifiers.get(1).getAsJsonObject().get("count").getAsInt());
assertEquals("OCEAN_FLOOR_WG", modifiers.get(3).getAsJsonObject().get("heightmap").getAsString());
assertEquals(1, modifiers.get(6).getAsJsonObject().get("y").getAsInt());
assertTrue(StageTestPacks.ofType(placed, "minecraft:volume_match").isEmpty());
assertTrue(diagnostics.isEmpty());
}
@Test
public void surfaceObjectsStandOnTerrainInsteadOfCanopiesOrWater() {
IrisObjectPlacement placement = placement(ObjectPlaceMode.CENTER_HEIGHT, 1, 1);
JsonObject placed = placed(compiler(DataVersion.V26_3).compile(input(placement, objects(5), List.of()), new ArrayList<>()));
JsonObject filter = filters(placed).getFirst();
assertEquals("OCEAN_FLOOR_WG", StageTestPacks.ofType(placed, "minecraft:heightmap").getFirst().get("heightmap").getAsString());
List<String> rejected = new ArrayList<>();
for (JsonObject negated : StageTestPacks.ofType(filter, "minecraft:not")) {
JsonObject inner = negated.getAsJsonObject("predicate");
rejected.add(inner.has("tag") ? inner.get("tag").getAsString() : inner.get("type").getAsString());
}
assertTrue(rejected.toString(), rejected.contains("minecraft:leaves"));
assertTrue(rejected.toString(), rejected.contains("minecraft:logs"));
assertTrue(rejected.toString(), rejected.contains("minecraft:matching_fluids"));
assertFalse(StageTestPacks.ofType(filter, "minecraft:solid").isEmpty());
}
@Test
public void supportFollowsTheObjectBaseInsteadOfAFlatPlane() {
IrisObjectPlacement placement = placement(ObjectPlaceMode.CENTER_HEIGHT, 1, 1);
placement.setSurfaceSupportBuffer(1);
placement.setSurfaceSupportDepth(2);
TemplateBlock trunk = new TemplateBlock(4, 0, 4, VanillaBlockState.parse("minecraft:oak_log[axis=y]"), null);
TemplateBlock crown = new TemplateBlock(0, 5, 0, VanillaBlockState.parse("minecraft:oak_leaves"), null);
BakedVariant tree = new BakedVariant(NAMESPACE + ":object/tree/v", new TemplateVolume(9, 6, 9, List.of(trunk, crown)), 0, TreeRoots.NONE);
List<ObjectTemplates> objects = List.of(new ObjectTemplates("tree", List.of(new TemplateChoice(tree, List.of(0, 1, 2, 3), 1))));
JsonObject support = filters(placed(compiler(DataVersion.V26_3).compile(input(placement, objects, List.of()), new ArrayList<>()))).get(1);
int reach = 0;
int depth = 0;
for (JsonObject solid : StageTestPacks.ofType(support, "minecraft:solid")) {
JsonArray offset = solid.getAsJsonArray("offset");
reach = Math.max(reach, Math.max(Math.abs(offset.get(0).getAsInt()), Math.abs(offset.get(2).getAsInt())));
depth = Math.min(depth, offset.get(1).getAsInt());
}
assertEquals(1, reach);
assertEquals(-16, depth);
assertFalse(StageTestPacks.ofType(support, "minecraft:any_of").isEmpty());
}
@Test
public void supportAcceptsSteepGroundAnywhereInTheScanWindow() {
IrisObjectPlacement placement = placement(ObjectPlaceMode.CENTER_HEIGHT, 1, 1);
placement.setSurfaceSupportBuffer(2);
placement.setSurfaceSupportDepth(2);
TemplateBlock trunk = new TemplateBlock(0, 0, 4, VanillaBlockState.parse("minecraft:spruce_log[axis=y]"), null);
BakedVariant tree = new BakedVariant(NAMESPACE + ":object/tree/v", new TemplateVolume(9, 20, 9, List.of(trunk)), 0, TreeRoots.NONE);
List<ObjectTemplates> objects = List.of(new ObjectTemplates("tree", List.of(new TemplateChoice(tree, List.of(0, 1, 2, 3), 1))));
JsonObject support = filters(placed(compiler(DataVersion.V26_3).compile(input(placement, objects, List.of()), new ArrayList<>()))).get(1);
Set<String> corners = new HashSet<>();
for (JsonObject solid : StageTestPacks.ofType(support, "minecraft:solid")) {
JsonArray offset = solid.getAsJsonArray("offset");
corners.add(offset.get(0).getAsInt() + "," + offset.get(2).getAsInt());
}
assertEquals(Set.of("-6,-6", "-6,6", "6,-6", "6,6"), corners);
Set<String> steepSlope = new HashSet<>();
Set<String> thinLedge = new HashSet<>();
for (String corner : corners) {
for (int y = -12; y >= -40; y--) {
steepSlope.add(cell(corner, y));
}
thinLedge.add(cell(corner, -12));
}
JsonObject predicate = support.getAsJsonObject("predicate");
assertTrue("ground 11 blocks below every corner must support the object", supported(predicate, steepSlope));
assertFalse("a one block ledge is thinner than surfaceSupportDepth", supported(predicate, thinLedge));
assertFalse("open air below every corner must not support the object", supported(predicate, Set.of()));
}
@Test
public void stiltedObjectsRelyOnTheirStiltsInsteadOfCornerSupport() {
IrisObjectPlacement placement = placement(ObjectPlaceMode.FAST_MIN_STILT, 1, 1);
PlacementInput input = new PlacementInput(placement, PlacementInput.Anchor.SURFACE, true, objects(25), List.of(),
List.of(VanillaBlockState.parse("minecraft:dark_oak_wood[axis=y]")), "willow");
List<JsonObject> filters = filters(placed(compiler(DataVersion.V26_3).compile(input, new ArrayList<>())));
assertEquals(1, filters.size());
assertFalse(StageTestPacks.ofType(filters.getFirst(), "minecraft:matching_block_tag").isEmpty());
}
@Test
public void slopeConditionRejectsSteepAnchors() {
IrisObjectPlacement placement = placement(ObjectPlaceMode.CENTER_HEIGHT, 1, 1);
placement.setRequireSurfaceSupport(false);
placement.getSlopeCondition().setMaximumSlope(1.5);
List<ExportDiagnostic> diagnostics = new ArrayList<>();
List<JsonObject> filters = filters(placed(compiler(DataVersion.V26_3).compile(input(placement, objects(5), List.of()), diagnostics)));
assertTrue(diagnostics.stream().anyMatch(diagnostic -> diagnostic.limit() == ExportLimit.SLOPE));
assertEquals(2, filters.size());
JsonObject slope = filters.get(1).getAsJsonObject("predicate");
Set<String> flat = new HashSet<>();
Set<String> cliff = new HashSet<>();
for (int x = -3; x <= 3; x++) {
for (int z = -3; z <= 3; z++) {
for (int y = -20; y <= -1; y++) {
flat.add(x + "," + y + "," + z);
cliff.add(x + "," + y + "," + z);
}
}
}
for (int y = 0; y <= 4; y++) {
cliff.add("3," + y + ",0");
}
assertTrue("flat ground must pass the slope limit", supported(slope, flat));
assertFalse("a wall 3 blocks higher 3 blocks away is steeper than slope 1.5", supported(slope, cliff));
}
@Test
public void forcePlaceIgnoresSlopeCondition() {
IrisObjectPlacement placement = placement(ObjectPlaceMode.CENTER_HEIGHT, 1, 1);
placement.setForcePlace(true);
placement.getSlopeCondition().setMinimumSlope(2);
List<JsonObject> filters = filters(placed(compiler(DataVersion.V26_3).compile(input(placement, objects(5), List.of()), new ArrayList<>())));
assertEquals(1, filters.size());
}
private static String cell(String corner, int y) {
String[] parts = corner.split(",");
return parts[0] + "," + y + "," + parts[1];
}
private static boolean supported(JsonObject predicate, Set<String> solids) {
String type = predicate.get("type").getAsString();
return switch (type) {
case "minecraft:solid" -> {
JsonArray offset = predicate.getAsJsonArray("offset");
yield solids.contains(offset.get(0).getAsInt() + "," + offset.get(1).getAsInt() + "," + offset.get(2).getAsInt());
}
case "minecraft:all_of" -> {
for (JsonElement child : predicate.getAsJsonArray("predicates")) {
if (!supported(child.getAsJsonObject(), solids)) {
yield false;
}
}
yield true;
}
case "minecraft:any_of" -> {
for (JsonElement child : predicate.getAsJsonArray("predicates")) {
if (supported(child.getAsJsonObject(), solids)) {
yield true;
}
}
yield false;
}
case "minecraft:not" -> !supported(predicate.getAsJsonObject("predicate"), solids);
default -> throw new AssertionError("Unexpected support predicate " + type);
};
}
@Test
public void underwaterObjectsNeedWaterAndStayBelowTheSurface() {
IrisObjectPlacement placement = placement(ObjectPlaceMode.CENTER_HEIGHT, 1, 1);
placement.setUnderwater(true);
placement.setTranslate(new IrisObjectTranslate().setY(2));
JsonObject placed = placed(compiler(DataVersion.V26_3).compile(input(placement, columns(7), List.of()), new ArrayList<>()));
List<JsonObject> filters = filters(placed);
assertEquals(2, filters.size());
assertTrue(StageTestPacks.ofType(filters.getFirst(), "minecraft:not").stream()
.noneMatch(negated -> !StageTestPacks.ofType(negated, "minecraft:matching_fluids").isEmpty()));
JsonObject water = StageTestPacks.ofType(filters.getFirst(), "minecraft:matching_fluids").getFirst();
assertFalse(water.toString(), water.has("offset"));
assertEquals(DIMENSION.fluidHeight() - 3 * (7 / 2) - 2, ceiling(placed));
}
@Test
public void underwaterObjectsOfDifferentHeightsKeepTheirOwnDepth() {
IrisObjectPlacement placement = placement(ObjectPlaceMode.CENTER_HEIGHT, 0.6, 2);
placement.setUnderwater(true);
CompiledPlacement compiled = compiler(DataVersion.V26_3).compile(input(placement, columns(4, 9, 4), List.of()), new ArrayList<>());
assertEquals(2, compiled.placedFeatures().size());
List<Integer> ceilings = new ArrayList<>();
double perChunk = 0;
for (JsonResource resource : compiled.resources()) {
if (resource.path().contains("worldgen/placed_feature/")) {
JsonObject placed = resource.json().getAsJsonObject();
ceilings.add(ceiling(placed));
perChunk += expectedPerChunk(placed);
}
}
ceilings.sort(Integer::compareTo);
assertEquals(List.of(DIMENSION.fluidHeight() - 3 * (9 / 2), DIMENSION.fluidHeight() - 3 * (4 / 2)), ceilings);
assertEquals(0.6 * 2, perChunk, 1e-6);
}
@Test
public void onwaterObjectsStandOnTheWaterSurface() {
IrisObjectPlacement placement = placement(ObjectPlaceMode.CENTER_HEIGHT, 1, 1);
placement.setOnwater(true);
JsonObject placed = placed(compiler(DataVersion.V26_3).compile(input(placement, objects(5), List.of()), new ArrayList<>()));
assertEquals("WORLD_SURFACE_WG", StageTestPacks.ofType(placed, "minecraft:heightmap").getFirst().get("heightmap").getAsString());
List<JsonObject> filters = filters(placed);
assertEquals(1, filters.size());
assertTrue(StageTestPacks.ofType(filters.getFirst(), "minecraft:solid").isEmpty());
JsonObject water = StageTestPacks.ofType(filters.getFirst(), "minecraft:matching_fluids").getFirst();
assertEquals("[0,-1,0]", water.get("offset").toString());
assertTrue(StageTestPacks.ofType(placed, "minecraft:not").isEmpty());
}
@Test
public void onwaterPaintDropsOntoTheWaterSurface() {
IrisObjectPlacement placement = placement(ObjectPlaceMode.PAINT, 1, 1);
placement.setOnwater(true);
placement.setTranslate(new IrisObjectTranslate().setY(1));
CompiledPlacement compiled = compiler(DataVersion.V26_3).compile(input(placement, objects(1), List.of()), new ArrayList<>());
JsonObject gravity = feature(compiled, "worldgen/feature/").getAsJsonObject("processors").getAsJsonArray("processors").get(0).getAsJsonObject();
assertEquals("WORLD_SURFACE_WG", gravity.get("heightmap").getAsString());
assertEquals(0, gravity.get("offset").getAsInt());
assertEquals("WORLD_SURFACE_WG", StageTestPacks.ofType(placed(compiled), "minecraft:heightmap").getFirst().get("heightmap").getAsString());
}
@Test
public void wideObjectBecomesSinglePieceStructure() {
IrisObjectPlacement placement = placement(ObjectPlaceMode.CENTER_HEIGHT, 0.02, 1);
List<ExportDiagnostic> diagnostics = new ArrayList<>();
CompiledPlacement compiled = compiler(DataVersion.V26_3).compile(input(placement, objects(40), List.of()), diagnostics);
assertTrue(compiled.placedFeatures().isEmpty());
assertEquals(1, compiled.structures().size());
JsonObject structure = resource(compiled, "worldgen/structure/");
assertEquals("minecraft:jigsaw", structure.get("type").getAsString());
assertEquals(compiled.structures().getFirst(), structure.get("start_pool").getAsString());
assertTrue(structure.get("biomes").getAsString().startsWith("#iris_export:has_structure/object/"));
assertEquals("WORLD_SURFACE_WG", structure.get("project_start_to_heightmap").getAsString());
JsonObject pool = resource(compiled, "worldgen/template_pool/");
JsonArray elements = pool.getAsJsonArray("elements");
assertEquals(1, elements.size());
assertEquals("minecraft:single_pool_element", elements.get(0).getAsJsonObject().getAsJsonObject("element").get("element_type").getAsString());
JsonObject set = resource(compiled, "worldgen/structure_set/");
JsonObject spread = set.getAsJsonObject("placement");
int spacing = spread.get("spacing").getAsInt();
double frequency = spread.has("frequency") ? spread.get("frequency").getAsDouble() : 1;
assertEquals(0.02, frequency / (spacing * spacing), 0.001);
assertTrue(spread.get("separation").getAsInt() < spacing);
assertEquals(1, diagnostics.size());
assertSame(ExportLimit.WIDE_OBJECT, diagnostics.getFirst().limit());
}
@Test
public void mixedPlacementSplitsNarrowAndWideShares() {
IrisObjectPlacement placement = placement(ObjectPlaceMode.CENTER_HEIGHT, 0.4, 2);
CompiledPlacement compiled = compiler(DataVersion.V26_3).compile(input(placement, objects(8, 50), List.of()), new ArrayList<>());
assertEquals(1, compiled.placedFeatures().size());
assertEquals(1, compiled.structures().size());
assertEquals(0.4 * 2 * 0.5, expectedPerChunk(placed(compiled)), 1e-6);
}
@Test
public void writeWindowNeverExceeded() {
DataVersion target = DataVersion.V26_3;
for (ObjectPlaceMode mode : List.of(ObjectPlaceMode.CENTER_HEIGHT, ObjectPlaceMode.STILT, ObjectPlaceMode.PAINT,
ObjectPlaceMode.MIN_HEIGHT, ObjectPlaceMode.FAST_MAX_HEIGHT)) {
for (int footprint = 1; footprint <= 40; footprint++) {
for (int translate : List.of(0, 3, -5, 12)) {
IrisObjectPlacement placement = placement(mode, 1, 1);
placement.setTranslate(new IrisObjectTranslate().setX(translate).setZ(-translate));
List<ObjectTemplates> objects = objects(footprint);
CompiledPlacement compiled = compiler(target).compile(input(placement, objects, List.of()), new ArrayList<>());
if (footprint + 2 * Math.abs(translate) > PlacementCompiler.MAX_FEATURE_WIDTH) {
assertTrue(compiled.placedFeatures().isEmpty());
continue;
}
assertWithinWindow(compiled, objects, target + " " + mode + " footprint " + footprint + " translate " + translate);
}
}
}
}
@Test
public void placementCountMatchesExpectation() {
Random random = new Random(1234);
DataVersion target = DataVersion.V26_3;
for (double chance : List.of(1.0, 0.75, 0.3, 0.004)) {
for (int density : List.of(1, 3, 8)) {
IrisObjectPlacement placement = placement(ObjectPlaceMode.CENTER_HEIGHT, chance, density);
CompiledPlacement compiled = compiler(target).compile(input(placement, objects(6), List.of()), new ArrayList<>());
JsonObject placed = placed(compiled);
double expected = chance * density;
assertEquals(target + " chance " + chance + " density " + density, expected, expectedPerChunk(placed), expected * 0.05);
double simulated = simulatePerChunk(placed, random, 20_000);
assertEquals(target + " simulated chance " + chance + " density " + density, expected, simulated,
Math.max(expected * 0.05, 4 * Math.sqrt(expected * density / 20_000.0)));
}
}
}
@Test
public void paintUsesTemplateProcessors() {
IrisObjectPlacement placement = placement(ObjectPlaceMode.PAINT, 1, 1);
CompiledPlacement compiled = compiler(DataVersion.V26_3).compile(input(placement, objects(9), List.of(rule())), new ArrayList<>());
JsonObject feature = feature(compiled, "worldgen/feature/");
JsonArray processors = feature.getAsJsonObject("processors").getAsJsonArray("processors");
assertEquals(2, processors.size());
assertEquals("minecraft:rule", processors.get(0).getAsJsonObject().get("processor_type").getAsString());
JsonObject gravity = processors.get(1).getAsJsonObject();
assertEquals("minecraft:gravity", gravity.get("processor_type").getAsString());
assertEquals("OCEAN_FLOOR_WG", gravity.get("heightmap").getAsString());
assertEquals(-1, gravity.get("offset").getAsInt());
}
@Test
public void stiltsUseOverlayPillarsOn26_3() {
IrisObjectPlacement placement = placement(ObjectPlaceMode.CENTER_STILT, 1, 1);
PlacementInput input = new PlacementInput(placement, PlacementInput.Anchor.SURFACE, false, objects(20), List.of(),
List.of(VanillaBlockState.parse("minecraft:oak_log[axis=y]")), "hut");
CompiledPlacement compiled = compiler(DataVersion.V26_3).compile(input, new ArrayList<>());
JsonObject feature = feature(compiled, "worldgen/feature/");
assertEquals("minecraft:overlay", feature.get("type").getAsString());
JsonArray features = feature.getAsJsonArray("features");
assertEquals(5, features.size());
assertEquals("minecraft:template", features.get(0).getAsJsonObject().getAsJsonObject("feature").get("type").getAsString());
JsonObject tile = features.get(1).getAsJsonObject();
JsonObject pillar = tile.getAsJsonObject("feature");
assertEquals("minecraft:single_block_pillar", pillar.get("type").getAsString());
assertEquals("down", pillar.get("direction").getAsString());
assertEquals("minecraft:rule_based", pillar.getAsJsonObject("block").get("type").getAsString());
assertEquals(List.of("minecraft:offset", "minecraft:cuboid", "minecraft:block_predicate_filter"), types(tile));
}
@Test
public void caveAnchorScansForFloor() {
IrisObjectPlacement placement = placement(ObjectPlaceMode.CENTER_HEIGHT, 1, 2);
PlacementInput input = new PlacementInput(placement, PlacementInput.Anchor.CAVE, true, objects(5), List.of(), List.of(), "shroom");
CompiledPlacement compiled = compiler(DataVersion.V26_3).compile(input, new ArrayList<>());
assertSame(GenerationStep.VEGETAL_DECORATION, compiled.step());
JsonObject placed = placed(compiled);
assertEquals(List.of("minecraft:count", "minecraft:in_square", "minecraft:height_range", "minecraft:environment_scan", "minecraft:biome"), types(placed));
JsonObject scan = placed.getAsJsonArray("placement").get(3).getAsJsonObject();
assertEquals("down", scan.get("direction_of_search").getAsString());
}
@Test
public void compiledJsonIsDeterministic() {
IrisObjectPlacement placement = placement(ObjectPlaceMode.STILT, 0.3, 2);
CompiledPlacement first = compiler(DataVersion.V26_3).compile(input(placement, objects(6, 12, 45), List.of(rule())), new ArrayList<>());
CompiledPlacement second = compiler(DataVersion.V26_3).compile(input(placement, objects(6, 12, 45), List.of(rule())), new ArrayList<>());
assertEquals(first, second);
assertEquals(first.resources().toString(), second.resources().toString());
}
@Test
public void minHeightScansDownUntilTheWholeFootprintHasGround() {
IrisObjectPlacement placement = placement(ObjectPlaceMode.MIN_HEIGHT, 1, 1);
CompiledPlacement compiled = compiler(DataVersion.V26_3).compile(input(placement, objects(9), List.of()), new ArrayList<>());
JsonObject placed = placed(compiled);
assertEquals(List.of("minecraft:in_square", "minecraft:heightmap", "minecraft:block_predicate_filter",
"minecraft:block_predicate_filter", "minecraft:biome"), types(placed));
JsonObject feature = feature(compiled, "worldgen/feature/");
assertEquals("minecraft:weighted_random_selector", feature.get("type").getAsString());
JsonArray branches = feature.getAsJsonArray("features");
assertEquals(1, branches.size());
JsonObject branch = branches.get(0).getAsJsonObject().getAsJsonObject("data");
assertEquals("minecraft:template", branch.getAsJsonObject("feature").get("type").getAsString());
assertEquals(List.of("minecraft:environment_scan", "minecraft:offset"), types(branch));
JsonObject scan = branch.getAsJsonArray("placement").get(0).getAsJsonObject();
assertEquals("down", scan.get("direction_of_search").getAsString());
assertEquals(32, scan.get("max_steps").getAsInt());
assertEquals(List.of("-4,-1,-4..4,-1,4"), boxes(scan));
JsonObject match = StageTestPacks.ofType(scan, "minecraft:volume_match").getFirst().getAsJsonObject("match");
assertFalse(StageTestPacks.ofType(match, "minecraft:solid").isEmpty());
assertFalse(StageTestPacks.ofType(match, "minecraft:matching_fluids").isEmpty());
assertEquals(-1, branch.getAsJsonArray("placement").get(1).getAsJsonObject().get("y").getAsInt());
}
@Test
public void maxHeightScansUpUntilEveryColumnIsClear() {
IrisObjectPlacement placement = placement(ObjectPlaceMode.MAX_HEIGHT, 1, 1);
placement.setUnderwater(true);
CompiledPlacement compiled = compiler(DataVersion.V26_3).compile(input(placement, objects(9), List.of()), new ArrayList<>());
JsonObject scan = branchScan(feature(compiled, "worldgen/feature/"), 0);
assertEquals("up", scan.get("direction_of_search").getAsString());
assertEquals(List.of("-4,0,-4..4,0,4"), boxes(scan));
JsonObject match = StageTestPacks.ofType(scan, "minecraft:volume_match").getFirst().getAsJsonObject("match");
assertEquals("minecraft:not", match.get("type").getAsString());
assertTrue(StageTestPacks.ofType(match, "minecraft:matching_fluids").isEmpty());
}
@Test
public void fastHeightModesProbeTheRuntimeSamplePoints() {
IrisObjectPlacement placement = placement(ObjectPlaceMode.FAST_MIN_HEIGHT, 1, 1);
CompiledPlacement compiled = compiler(DataVersion.V26_3).compile(input(placement, objects(9), List.of()), new ArrayList<>());
JsonObject scan = branchScan(feature(compiled, "worldgen/feature/"), 0);
assertEquals(List.of("-4,-1,-4..-4,-1,-4", "-4,-1,1..-4,-1,1", "1,-1,-4..1,-1,-4", "1,-1,1..1,-1,1"), boxes(scan));
}
@Test
public void heightScanCoversEveryAllowedQuarter() {
TemplateBlock block = new TemplateBlock(0, 0, 0, VanillaBlockState.parse("minecraft:stone"), null);
BakedVariant wall = new BakedVariant(NAMESPACE + ":object/wall/v", new TemplateVolume(5, 4, 9, List.of(block)), 0, TreeRoots.NONE);
IrisObjectPlacement placement = placement(ObjectPlaceMode.MIN_HEIGHT, 1, 1);
JsonObject turning = feature(compiler(DataVersion.V26_3).compile(input(placement, List.of(new ObjectTemplates("wall",
List.of(new TemplateChoice(wall, List.of(0, 1, 2, 3), 1)))), List.of()), new ArrayList<>()), "worldgen/feature/");
JsonObject fixed = feature(compiler(DataVersion.V26_3).compile(input(placement, List.of(new ObjectTemplates("wall",
List.of(new TemplateChoice(wall, List.of(0), 1)))), List.of()), new ArrayList<>()), "worldgen/feature/");
assertEquals(List.of("-2,-1,-4..2,-1,4", "-4,-1,-2..4,-1,2"), boxes(branchScan(turning, 0)));
assertEquals(List.of("-2,-1,-4..2,-1,4"), boxes(branchScan(fixed, 0)));
}
@Test
public void everyTemplateAnchorsOnItsOwnFootprint() {
IrisObjectPlacement placement = placement(ObjectPlaceMode.MIN_HEIGHT, 1, 1);
JsonObject feature = feature(compiler(DataVersion.V26_3).compile(input(placement, objects(5, 9), List.of()), new ArrayList<>()),
"worldgen/feature/");
JsonArray branches = feature.getAsJsonArray("features");
assertEquals(2, branches.size());
assertEquals(branches.get(0).getAsJsonObject().get("weight"), branches.get(1).getAsJsonObject().get("weight"));
assertEquals(List.of("-2,-1,-2..2,-1,2"), boxes(branchScan(feature, 0)));
assertEquals(List.of("-4,-1,-4..4,-1,4"), boxes(branchScan(feature, 1)));
}
@Test
public void maxStiltsAnchorHighThenStilt() {
IrisObjectPlacement placement = placement(ObjectPlaceMode.STILT, 1, 1);
PlacementInput input = new PlacementInput(placement, PlacementInput.Anchor.SURFACE, false, objects(20), List.of(),
List.of(VanillaBlockState.parse("minecraft:oak_log[axis=y]")), "hut");
JsonObject feature = feature(compiler(DataVersion.V26_3).compile(input, new ArrayList<>()), "worldgen/feature/");
JsonObject branch = feature.getAsJsonArray("features").get(0).getAsJsonObject().getAsJsonObject("data");
assertEquals("up", branchScan(feature, 0).get("direction_of_search").getAsString());
JsonObject stilts = branch.getAsJsonObject("feature");
assertEquals("minecraft:overlay", stilts.get("type").getAsString());
assertEquals(5, stilts.getAsJsonArray("features").size());
assertEquals("minecraft:single_block_pillar", stilts.getAsJsonArray("features").get(1).getAsJsonObject()
.getAsJsonObject("feature").get("type").getAsString());
}
@Test
public void groundedTreesExtendRootsToTheTerrain() {
IrisObjectPlacement placement = placement(ObjectPlaceMode.CENTER_HEIGHT, 1, 1);
CompiledPlacement compiled = compiler(DataVersion.V26_3).compile(tree(placement, rootedTree()), new ArrayList<>());
JsonObject feature = feature(compiled, "worldgen/feature/");
assertEquals("minecraft:weighted_random_selector", feature.get("type").getAsString());
JsonArray branches = feature.getAsJsonArray("features");
assertEquals(4, branches.size());
List<String> rotations = new ArrayList<>();
List<String> roots = new ArrayList<>();
List<String> gaps = new ArrayList<>();
String pillar = null;
for (JsonElement element : branches) {
assertEquals(branches.get(0).getAsJsonObject().get("weight"), element.getAsJsonObject().get("weight"));
JsonObject branch = element.getAsJsonObject().getAsJsonObject("data");
assertEquals(List.of("minecraft:offset", "minecraft:block_predicate_filter"), types(branch));
gaps.addAll(boxes(branch.getAsJsonArray("placement").get(1)));
JsonObject overlay = branch.getAsJsonObject("feature");
assertEquals("minecraft:overlay", overlay.get("type").getAsString());
JsonArray parts = overlay.getAsJsonArray("features");
assertEquals(2, parts.size());
JsonObject template = parts.get(0).getAsJsonObject().getAsJsonObject("feature");
rotations.add(template.getAsJsonArray("templates").get(0).getAsJsonObject().getAsJsonObject("data")
.getAsJsonArray("rotations").get(0).getAsString());
JsonObject root = parts.get(1).getAsJsonObject();
pillar = root.get("feature").getAsString();
JsonObject offset = root.getAsJsonArray("placement").get(0).getAsJsonObject();
roots.add(offset.get("x").getAsInt() + "," + offset.get("y").getAsInt() + "," + offset.get("z").getAsInt());
}
assertEquals(List.of("none", "counterclockwise_90", "180", "clockwise_90"), rotations);
assertEquals(List.of("1,-1,0", "0,-1,-1", "-1,-1,0", "0,-1,1"), roots);
assertEquals(List.of("1,-4,0..1,-1,0", "0,-4,-1..0,-1,-1", "-1,-4,0..-1,-1,0", "0,-4,1..0,-1,1"), gaps);
JsonObject shared = resourceAt(compiled, pillar);
JsonObject gated = shared.getAsJsonArray("features").get(0).getAsJsonObject();
assertEquals("minecraft:block_predicate_filter", gated.getAsJsonArray("placement").get(0).getAsJsonObject().get("type").getAsString());
JsonObject column = gated.getAsJsonObject("feature");
assertEquals("minecraft:single_block_pillar", column.get("type").getAsString());
assertEquals("down", column.get("direction").getAsString());
assertEquals("minecraft:spruce_wood", column.getAsJsonObject("block").get("id").getAsString());
JsonObject cap = column.getAsJsonObject("cap_feature");
assertEquals("minecraft:simple_block", cap.getAsJsonObject("feature").get("type").getAsString());
assertEquals(-1, cap.getAsJsonArray("placement").get(0).getAsJsonObject().get("y").getAsInt());
}
@Test
public void groundedRotationBranchesKeepTheTemplateOdds() {
BakedVariant turning = rootedTree().getFirst().choices().getFirst().variant();
BakedVariant fixed = new BakedVariant(NAMESPACE + ":object/tree/fixed", turning.volume(), 0, turning.roots());
List<ObjectTemplates> objects = List.of(new ObjectTemplates("tree", List.of(
new TemplateChoice(turning, List.of(0, 1, 2, 3), 1),
new TemplateChoice(fixed, List.of(2), 1))));
JsonObject feature = feature(compiler(DataVersion.V26_3).compile(tree(placement(ObjectPlaceMode.CENTER_HEIGHT, 1, 1), objects),
new ArrayList<>()), "worldgen/feature/");
List<Integer> weights = new ArrayList<>();
for (JsonElement branch : feature.getAsJsonArray("features")) {
weights.add(branch.getAsJsonObject().get("weight").getAsInt());
}
assertEquals(List.of(1, 1, 1, 1, 4), weights);
}
@Test
public void groundedTreesReplaceStiltsWithRoots() {
IrisObjectPlacement placement = placement(ObjectPlaceMode.CENTER_STILT, 1, 1);
JsonObject feature = feature(compiler(DataVersion.V26_3).compile(tree(placement, rootedTree()), new ArrayList<>()), "worldgen/feature/");
for (JsonElement element : feature.getAsJsonArray("features")) {
JsonObject overlay = element.getAsJsonObject().getAsJsonObject("data").getAsJsonObject("feature");
assertTrue(StageTestPacks.ofType(overlay, "minecraft:cuboid").isEmpty());
assertEquals(2, overlay.getAsJsonArray("features").size());
}
}
@Test
public void forcedTreesKeepTheirBuiltRoots() {
IrisObjectPlacement placement = placement(ObjectPlaceMode.CENTER_HEIGHT, 1, 1);
placement.setForcePlace(true);
JsonObject feature = feature(compiler(DataVersion.V26_3).compile(tree(placement, rootedTree()), new ArrayList<>()), "worldgen/feature/");
assertEquals("minecraft:template", feature.get("type").getAsString());
}
@Test
public void rootedHeightScansStayInsideTheFeatureWindow() {
IrisObjectPlacement placement = placement(ObjectPlaceMode.FAST_MAX_HEIGHT, 1, 1);
placement.setTranslate(new IrisObjectTranslate().setX(3).setZ(-3));
List<ObjectTemplates> objects = rootedTree();
CompiledPlacement compiled = compiler(DataVersion.V26_3).compile(tree(placement, objects), new ArrayList<>());
assertWithinWindow(compiled, objects, "rooted fast max");
}
private static List<ObjectTemplates> rootedTree() {
List<TemplateBlock> blocks = new ArrayList<>();
for (int y = 1; y < 4; y++) {
blocks.add(new TemplateBlock(2, y, 2, VanillaBlockState.parse("minecraft:oak_log[axis=y]"), null));
}
TemplateBlock root = new TemplateBlock(3, 0, 2, VanillaBlockState.parse("minecraft:spruce_wood[axis=y]"), null);
blocks.add(root);
BakedVariant variant = new BakedVariant(NAMESPACE + ":object/tree/rooted", new TemplateVolume(5, 4, 5, blocks), 0,
new TreeRoots(List.of(root), 3));
return List.of(new ObjectTemplates("tree", List.of(new TemplateChoice(variant, List.of(0, 1, 2, 3), 1))));
}
private static PlacementInput tree(IrisObjectPlacement placement, List<ObjectTemplates> objects) {
return new PlacementInput(placement, PlacementInput.Anchor.SURFACE, true, objects, List.of(),
List.of(VanillaBlockState.parse("minecraft:oak_log[axis=y]")), "tree");
}
private static JsonObject branchScan(JsonObject selector, int index) {
JsonObject branch = selector.getAsJsonArray("features").get(index).getAsJsonObject().getAsJsonObject("data");
return StageTestPacks.ofType(branch, "minecraft:environment_scan").getFirst();
}
private static List<String> boxes(JsonElement root) {
List<String> boxes = new ArrayList<>();
for (JsonObject volume : StageTestPacks.ofType(root, "minecraft:volume_match")) {
JsonArray min = volume.getAsJsonArray("min");
JsonArray max = volume.getAsJsonArray("max");
boxes.add(min.get(0).getAsInt() + "," + min.get(1).getAsInt() + "," + min.get(2).getAsInt() + ".."
+ max.get(0).getAsInt() + "," + max.get(1).getAsInt() + "," + max.get(2).getAsInt());
}
return boxes;
}
private static JsonObject resourceAt(CompiledPlacement compiled, String id) {
String path = "/worldgen/feature/" + id.substring(NAMESPACE.length() + 1) + ".json";
for (JsonResource resource : compiled.resources()) {
if (resource.path().endsWith(path)) {
return resource.json().getAsJsonObject();
}
}
throw new AssertionError("No resource for " + id);
}
private static List<JsonObject> filters(JsonObject placed) {
List<JsonObject> filters = new ArrayList<>();
for (JsonElement element : placed.getAsJsonArray("placement")) {
if (element.getAsJsonObject().get("type").getAsString().equals("minecraft:block_predicate_filter")) {
filters.add(element.getAsJsonObject());
}
}
return filters;
}
private static void assertWithinWindow(CompiledPlacement compiled, List<ObjectTemplates> objects, String label) {
Map<String, Integer> footprints = new HashMap<>();
for (ObjectTemplates object : objects) {
for (TemplateChoice choice : object.choices()) {
footprints.put(choice.variant().id(), choice.variant().volume().footprint());
}
}
int[] offset = probeWindow(placed(compiled).getAsJsonArray("placement"), 0, 0, label);
JsonObject feature = feature(compiled, null);
if (!feature.get("type").getAsString().equals("minecraft:weighted_random_selector")) {
assertFeatureWithinWindow(feature, footprints, offset[0], offset[1], label);
return;
}
for (JsonElement entry : feature.getAsJsonArray("features")) {
JsonObject branch = entry.getAsJsonObject().getAsJsonObject("data");
int[] branchOffset = probeWindow(branch.getAsJsonArray("placement"), offset[0], offset[1], label);
assertFeatureWithinWindow(branch.getAsJsonObject("feature"), footprints, branchOffset[0], branchOffset[1], label);
}
}
private static int[] probeWindow(JsonArray modifiers, int startX, int startZ, String label) {
int offsetX = startX;
int offsetZ = startZ;
for (JsonElement element : modifiers) {
JsonObject modifier = element.getAsJsonObject();
String type = modifier.get("type").getAsString();
if (type.equals("minecraft:offset")) {
offsetX += modifier.get("x").getAsInt();
offsetZ += modifier.get("z").getAsInt();
} else if (type.equals("minecraft:random_offset")) {
offsetX += modifier.get("xz_spread").getAsInt();
offsetZ += modifier.get("xz_spread").getAsInt();
} else if (type.equals("minecraft:block_predicate_filter") || type.equals("minecraft:environment_scan")) {
for (JsonObject probe : StageTestPacks.find(modifier, object -> object.has("offset") || object.has("min"))) {
for (String key : List.of("offset", "min", "max")) {
if (!probe.has(key)) {
continue;
}
JsonArray vector = probe.getAsJsonArray(key);
for (int axis = 0; axis < 3; axis++) {
assertTrue(label + " predicate " + key + " " + vector, Math.abs(vector.get(axis).getAsInt()) <= 16);
}
assertRange(label + " probe x", vector.get(0).getAsInt() + offsetX, vector.get(0).getAsInt() + offsetX);
assertRange(label + " probe z", vector.get(2).getAsInt() + offsetZ, vector.get(2).getAsInt() + offsetZ);
}
}
}
}
return new int[]{offsetX, offsetZ};
}
private static void assertFeatureWithinWindow(JsonObject feature, Map<String, Integer> footprints, int offsetX, int offsetZ, String label) {
String type = feature.get("type").getAsString();
JsonObject body = feature.has("config") ? feature.getAsJsonObject("config") : feature;
if (type.equals("minecraft:fossil")) {
for (JsonElement id : body.getAsJsonArray("fossil_structures")) {
assertTemplate(label, footprints.get(id.getAsString()), offsetX, offsetZ);
}
return;
}
JsonObject template = type.equals("minecraft:overlay")
? body.getAsJsonArray("features").get(0).getAsJsonObject().getAsJsonObject("feature")
: feature;
JsonObject templateBody = template.has("config") ? template.getAsJsonObject("config") : template;
for (JsonElement entry : templateBody.getAsJsonArray("templates")) {
Integer footprint = footprints.get(entry.getAsJsonObject().getAsJsonObject("data").get("id").getAsString());
assertNotNull(label, footprint);
assertTemplate(label, footprint, offsetX, offsetZ);
}
if (!type.equals("minecraft:overlay")) {
return;
}
JsonArray features = body.getAsJsonArray("features");
for (int index = 1; index < features.size(); index++) {
JsonArray part = features.get(index).getAsJsonObject().getAsJsonArray("placement");
int partX = offsetX;
int partZ = offsetZ;
int size = 0;
for (JsonElement element : part) {
JsonObject modifier = element.getAsJsonObject();
String modifierType = modifier.get("type").getAsString();
if (modifierType.equals("minecraft:offset")) {
partX += modifier.get("x").getAsInt();
partZ += modifier.get("z").getAsInt();
} else if (modifierType.equals("minecraft:cuboid")) {
size = modifier.get("xz_size").getAsInt();
}
}
assertRange(label + " part x", partX, partX + size);
assertRange(label + " part z", partZ, partZ + size);
}
}
private static void assertTemplate(String label, int footprint, int offsetX, int offsetZ) {
int low = -(footprint / 2);
int high = footprint - 1 - footprint / 2;
assertRange(label + " template x", low + offsetX, high + offsetX);
assertRange(label + " template z", low + offsetZ, high + offsetZ);
}
private static void assertRange(String label, int low, int high) {
assertTrue(label + " starts at " + low, low >= WINDOW_MIN);
assertTrue(label + " ends at " + (high + CHUNK - 1), high + CHUNK - 1 <= WINDOW_MAX);
}
private static double expectedPerChunk(JsonObject placed) {
double expected = 1;
for (JsonElement element : placed.getAsJsonArray("placement")) {
JsonObject modifier = element.getAsJsonObject();
switch (modifier.get("type").getAsString()) {
case "minecraft:random_chance" -> expected *= modifier.get("chance").getAsDouble();
case "minecraft:count" -> expected *= expectedCount(modifier.get("count"));
default -> {
}
}
}
return expected;
}
private static double expectedCount(JsonElement count) {
if (count.isJsonPrimitive()) {
return count.getAsInt();
}
double total = 0;
double weighted = 0;
for (JsonElement entry : count.getAsJsonObject().getAsJsonArray("distribution")) {
int weight = entry.getAsJsonObject().get("weight").getAsInt();
total += weight;
weighted += weight * entry.getAsJsonObject().get("data").getAsInt();
}
return weighted / total;
}
private static double simulatePerChunk(JsonObject placed, Random random, int chunks) {
long positions = 0;
for (int chunk = 0; chunk < chunks; chunk++) {
int stream = 1;
for (JsonElement element : placed.getAsJsonArray("placement")) {
JsonObject modifier = element.getAsJsonObject();
String type = modifier.get("type").getAsString();
if (type.equals("minecraft:random_chance")) {
int kept = 0;
for (int index = 0; index < stream; index++) {
if (random.nextFloat() < modifier.get("chance").getAsFloat()) {
kept++;
}
}
stream = kept;
} else if (type.equals("minecraft:count")) {
int expanded = 0;
for (int index = 0; index < stream; index++) {
expanded += sampleCount(modifier.get("count"), random);
}
stream = expanded;
}
}
positions += stream;
}
return positions / (double) chunks;
}
private static int sampleCount(JsonElement count, Random random) {
if (count.isJsonPrimitive()) {
return count.getAsInt();
}
JsonArray distribution = count.getAsJsonObject().getAsJsonArray("distribution");
int total = 0;
for (JsonElement entry : distribution) {
total += entry.getAsJsonObject().get("weight").getAsInt();
}
int roll = random.nextInt(total);
for (JsonElement entry : distribution) {
roll -= entry.getAsJsonObject().get("weight").getAsInt();
if (roll < 0) {
return entry.getAsJsonObject().get("data").getAsInt();
}
}
throw new IllegalStateException("Weighted list roll fell through");
}
private static PlacementCompiler compiler(DataVersion target) {
return new PlacementCompiler(NAMESPACE, ExportCapabilities.forTarget(target), DIMENSION);
}
private static IrisObjectPlacement placement(ObjectPlaceMode mode, double chance, int density) {
IrisObjectPlacement placement = new IrisObjectPlacement();
placement.setPlace(new KList<>(List.of("objects/a")));
placement.setMode(mode);
placement.setChance(chance);
placement.setDensity(density);
return placement;
}
private static PlacementInput input(IrisObjectPlacement placement, List<ObjectTemplates> objects, List<JsonObject> processors) {
return new PlacementInput(placement, PlacementInput.Anchor.SURFACE, false, objects, processors, List.of(), "thing");
}
private static List<ObjectTemplates> objects(int... footprints) {
List<ObjectTemplates> objects = new ArrayList<>();
for (int index = 0; index < footprints.length; index++) {
int footprint = footprints[index];
TemplateBlock block = new TemplateBlock(0, 0, 0, VanillaBlockState.parse("minecraft:stone"), null);
BakedVariant variant = new BakedVariant(NAMESPACE + ":object/o" + index + "/v" + footprint,
new TemplateVolume(footprint, 4, footprint, List.of(block)), 0, TreeRoots.NONE);
objects.add(new ObjectTemplates("o" + index, List.of(new TemplateChoice(variant, List.of(0, 1, 2, 3), 1))));
}
return objects;
}
private static List<ObjectTemplates> columns(int... heights) {
List<ObjectTemplates> objects = new ArrayList<>();
for (int index = 0; index < heights.length; index++) {
List<TemplateBlock> blocks = new ArrayList<>();
for (int y = 1; y <= heights[index]; y++) {
blocks.add(new TemplateBlock(1, y, 1, VanillaBlockState.parse("minecraft:tube_coral_block"), null));
}
BakedVariant variant = new BakedVariant(NAMESPACE + ":object/c" + index + "/h" + heights[index],
new TemplateVolume(3, heights[index] + 1, 3, blocks), 0, TreeRoots.NONE);
objects.add(new ObjectTemplates("c" + index, List.of(new TemplateChoice(variant, List.of(0, 1, 2, 3), 1))));
}
return objects;
}
private static int ceiling(JsonObject placed) {
List<JsonObject> ranges = new ArrayList<>();
for (JsonObject filter : filters(placed)) {
ranges.addAll(StageTestPacks.ofType(filter, "minecraft:height_range"));
}
assertEquals(placed.toString(), 1, ranges.size());
return ranges.getFirst().getAsJsonObject("max_inclusive").get("absolute").getAsInt();
}
private static JsonObject rule() {
JsonObject rule = new JsonObject();
rule.addProperty("processor_type", "minecraft:rule");
rule.add("rules", new JsonArray());
return rule;
}
private static JsonObject feature(CompiledPlacement compiled, String folder) {
String featureId = placed(compiled).get("feature").getAsString();
String path = featureId.substring(NAMESPACE.length() + 1) + ".json";
for (JsonResource resource : compiled.resources()) {
if (resource.path().endsWith("/" + path) && !resource.path().contains("placed_feature")
&& (folder == null || resource.path().contains(folder))) {
return resource.json().getAsJsonObject();
}
}
throw new AssertionError("No feature " + featureId + " in " + folder);
}
private static JsonObject placed(CompiledPlacement compiled) {
return resource(compiled, "worldgen/placed_feature/");
}
private static JsonObject resource(CompiledPlacement compiled, String folder) {
JsonObject found = null;
for (JsonResource resource : compiled.resources()) {
if (resource.path().contains(folder)) {
assertNull("Two resources in " + folder, found);
found = resource.json().getAsJsonObject();
}
}
assertNotNull("No resource in " + folder, found);
return found;
}
private static List<String> types(JsonObject placed) {
List<String> types = new ArrayList<>();
for (JsonElement element : placed.getAsJsonArray("placement")) {
types.add(element.getAsJsonObject().get("type").getAsString());
}
return types;
}
}
@@ -0,0 +1,146 @@
package art.arcane.iris.pack.datapack.export.compile.structure;
import art.arcane.iris.pack.datapack.export.ExportTestPacks;
import art.arcane.iris.pack.datapack.export.compile.PackCompileContext;
import art.arcane.iris.pack.datapack.export.ir.ExportDiagnostic;
import art.arcane.iris.pack.datapack.export.ir.ExportLimit;
import art.arcane.iris.pack.loading.IrisData;
import art.arcane.iris.testsupport.PlatformLeakGuard;
import org.junit.ClassRule;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import java.io.File;
import java.util.List;
import java.util.Map;
import java.util.SortedMap;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
public class DatapackBundleTest {
@ClassRule
public static final PlatformLeakGuard PLATFORM_GUARD = PlatformLeakGuard.clean();
@Rule
public TemporaryFolder temporaryFolder = new TemporaryFolder();
@Rule
public ExportTestPacks.BoundPlatform platform = new ExportTestPacks.BoundPlatform();
@Test
public void bundledDatapackFilesAreMerged() throws Exception {
File imports = temporaryFolder.newFolder("imports");
File first = StructureTestPacks.zip(imports, "first.zip", Map.of(
"first/pack.mcmeta", """
{"pack": {"description": "first", "min_format": 107, "max_format": 121},
"overlays": {"entries": [
{"directory": "mc_26_3", "min_format": 121, "max_format": 121},
{"directory": "mc_26_2", "min_format": 107, "max_format": 107}]}}
""",
"first/pack.png", "png",
"first/data/first/structure/hut.nbt", "hut-template",
"first/data/first/worldgen/processor_list/hut.json", "{\"processors\": []}",
"first/mc_26_3/data/first/worldgen/processor_list/hut.json", "{\"processors\": [{\"processor_type\": \"minecraft:nop\"}]}",
"first/mc_26_2/data/first/worldgen/processor_list/old.json", "{\"processors\": []}"));
File second = StructureTestPacks.zip(imports, "second.zip", Map.of(
"pack.mcmeta", StructureTestPacks.metadata(121, 121),
"data/second/worldgen/structure_set/camp.json", "{\"structures\": []}"));
File pack = StructureTestPacks.pack(temporaryFolder.newFolder("pack"), StructureTestPacks.dimension(List.of(first, second), ""), "[]");
IrisData data = IrisData.openRuntime(pack);
try {
PackCompileContext context = StructureTestPacks.compiled(data);
SortedMap<String, String> binaries = StructureTestPacks.binaries(context);
assertEquals("hut-template", binaries.get("data/first/structure/hut.nbt"));
assertEquals("{\"processors\": [{\"processor_type\": \"minecraft:nop\"}]}", binaries.get("data/first/worldgen/processor_list/hut.json"));
assertEquals("{\"structures\": []}", binaries.get("data/second/worldgen/structure_set/camp.json"));
assertFalse(binaries.containsKey("data/first/worldgen/processor_list/old.json"));
for (String path : binaries.keySet()) {
assertTrue(path, path.startsWith("data/"));
}
assertTrue(StructureTestPacks.diagnostics(context, ExportLimit.DATAPACK_VERSION).isEmpty());
assertTrue(StructureTestPacks.diagnostics(context, ExportLimit.DATAPACK_COLLISION).isEmpty());
} finally {
data.close();
}
}
@Test
public void tagFilesAreUnionedRespectingReplace() throws Exception {
File imports = temporaryFolder.newFolder("imports");
File first = StructureTestPacks.zip(imports, "a.zip", Map.of(
"pack.mcmeta", StructureTestPacks.metadata(121, 121),
"data/shared/tags/worldgen/structure/towns.json", "{\"values\": [\"a:one\"]}",
"data/shared/tags/item/loot.json", "{\"values\": [\"a:x\"]}"));
File second = StructureTestPacks.zip(imports, "b.zip", Map.of(
"pack.mcmeta", StructureTestPacks.metadata(121, 121),
"data/shared/tags/worldgen/structure/towns.json", "{\"replace\": false, \"values\": [\"b:two\", \"a:one\"]}",
"data/shared/tags/item/loot.json", "{\"replace\": true, \"values\": [\"b:y\"]}"));
File third = StructureTestPacks.zip(imports, "c.zip", Map.of(
"pack.mcmeta", StructureTestPacks.metadata(121, 121),
"data/shared/tags/item/loot.json", "{\"values\": [{\"id\": \"c:z\", \"required\": false}]}"));
File pack = StructureTestPacks.pack(temporaryFolder.newFolder("pack"), StructureTestPacks.dimension(List.of(first, second, third), ""), "[]");
IrisData data = IrisData.openRuntime(pack);
try {
PackCompileContext context = StructureTestPacks.compiled(data);
assertEquals(StructureTestPacks.parse("{\"replace\": false, \"values\": [\"a:one\", \"b:two\"]}"),
StructureTestPacks.json(context).get("data/shared/tags/worldgen/structure/towns.json"));
assertEquals(StructureTestPacks.parse("{\"replace\": true, \"values\": [\"b:y\", {\"id\": \"c:z\", \"required\": false}]}"),
StructureTestPacks.json(context).get("data/shared/tags/item/loot.json"));
assertFalse(StructureTestPacks.binaries(context).containsKey("data/shared/tags/item/loot.json"));
} finally {
data.close();
}
}
@Test
public void pathCollisionKeepsLaterImportWithDiagnostic() throws Exception {
File imports = temporaryFolder.newFolder("imports");
File first = StructureTestPacks.zip(imports, "a.zip", Map.of(
"pack.mcmeta", StructureTestPacks.metadata(121, 121),
"data/shared/worldgen/processor_list/rot.json", "{\"processors\": [\"first\"]}",
"data/shared/worldgen/processor_list/same.json", "{\"processors\": []}"));
File second = StructureTestPacks.zip(imports, "b.zip", Map.of(
"pack.mcmeta", StructureTestPacks.metadata(121, 121),
"data/shared/worldgen/processor_list/rot.json", "{\"processors\": [\"second\"]}",
"data/shared/worldgen/processor_list/same.json", "{\"processors\": []}"));
File pack = StructureTestPacks.pack(temporaryFolder.newFolder("pack"), StructureTestPacks.dimension(List.of(first, second), ""), "[]");
IrisData data = IrisData.openRuntime(pack);
try {
PackCompileContext context = StructureTestPacks.compiled(data);
assertEquals("{\"processors\": [\"second\"]}", StructureTestPacks.binaries(context).get("data/shared/worldgen/processor_list/rot.json"));
List<ExportDiagnostic> collisions = StructureTestPacks.diagnostics(context, ExportLimit.DATAPACK_COLLISION);
assertEquals(collisions.toString(), 1, collisions.size());
assertEquals("data/shared/worldgen/processor_list/rot.json", collisions.getFirst().resource());
assertTrue(collisions.getFirst().message(), collisions.getFirst().message().contains(first.getName()));
assertTrue(collisions.getFirst().message(), collisions.getFirst().message().contains(second.getName()));
} finally {
data.close();
}
}
@Test
public void unsupportedFormatIsBundledWithDiagnostic() throws Exception {
File imports = temporaryFolder.newFolder("imports");
File old = StructureTestPacks.zip(imports, "old.zip", Map.of(
"pack.mcmeta", "{\"pack\": {\"description\": \"old\", \"pack_format\": 48}}",
"data/old/worldgen/processor_list/rot.json", "{\"processors\": []}"));
File pack = StructureTestPacks.pack(temporaryFolder.newFolder("pack"), StructureTestPacks.dimension(List.of(old), ""), "[]");
IrisData data = IrisData.openRuntime(pack);
try {
PackCompileContext context = StructureTestPacks.compiled(data);
assertTrue(StructureTestPacks.binaries(context).containsKey("data/old/worldgen/processor_list/rot.json"));
List<ExportDiagnostic> versions = StructureTestPacks.diagnostics(context, ExportLimit.DATAPACK_VERSION);
assertEquals(versions.toString(), 1, versions.size());
assertTrue(versions.getFirst().message(), versions.getFirst().message().contains("48.0 to 48.*"));
} finally {
data.close();
}
}
}
@@ -0,0 +1,295 @@
package art.arcane.iris.pack.datapack.export.compile.structure;
import art.arcane.iris.pack.datapack.export.ExportTestPacks;
import art.arcane.iris.pack.datapack.export.compile.PackCompileContext;
import art.arcane.iris.pack.datapack.export.ir.BinaryResource;
import art.arcane.iris.pack.datapack.export.ir.ExportDiagnostic;
import art.arcane.iris.pack.datapack.export.ir.ExportLimit;
import art.arcane.iris.pack.datapack.export.ir.JsonResource;
import art.arcane.iris.pack.loading.IrisData;
import art.arcane.iris.spi.IrisPlatforms;
import art.arcane.iris.testsupport.CompatTestPlatform;
import art.arcane.iris.testsupport.FakeVanillaDataSource;
import art.arcane.iris.testsupport.PlatformLeakGuard;
import art.arcane.volmlib.util.nbt.io.NBTUtil;
import art.arcane.volmlib.util.nbt.tag.CompoundTag;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import org.junit.ClassRule;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.SortedMap;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.mockito.Mockito.doReturn;
public class StructureStageTest {
private static final String TOWER = """
{"type": "minecraft:jigsaw", "biomes": "#bundle:has_structure/tower", "step": "surface_structures",
"spawn_overrides": {}, "start_pool": "bundle:tower/start", "size": 4, "start_height": {"absolute": 0},
"project_start_to_heightmap": "WORLD_SURFACE_WG", "max_distance_from_center": 80, "use_expansion_hack": false}
""";
private static final String MINESHAFT = """
{"type": "minecraft:mineshaft", "biomes": "#minecraft:has_structure/mineshaft", "step": "underground_structures",
"spawn_overrides": {}, "mineshaft_type": "normal"}
""";
private static final String VILLAGE = """
{"type": "minecraft:jigsaw", "biomes": "#minecraft:has_structure/village_plains", "step": "surface_structures",
"spawn_overrides": {}, "start_pool": "minecraft:village/plains/town_centers", "size": 6, "start_height": {"absolute": 0},
"project_start_to_heightmap": "WORLD_SURFACE_WG", "max_distance_from_center": 80, "use_expansion_hack": true}
""";
@ClassRule
public static final PlatformLeakGuard PLATFORM_GUARD = PlatformLeakGuard.clean();
@Rule
public TemporaryFolder temporaryFolder = new TemporaryFolder();
@Rule
public ExportTestPacks.BoundPlatform platform = new ExportTestPacks.BoundPlatform();
@Test
public void exportedBiomesJoinDerivativeTags() throws Exception {
runningVanilla(Map.of(
"data/minecraft/tags/worldgen/biome/has_structure/village_plains.json", "{\"values\": [\"minecraft:plains\"]}",
"data/minecraft/tags/worldgen/biome/has_structure/pillager_outpost.json", "{\"values\": [\"minecraft:plains\", \"minecraft:desert\"]}"));
File towns = StructureTestPacks.zip(temporaryFolder.newFolder("imports"), "towns.zip", Map.of(
"pack.mcmeta", StructureTestPacks.metadata(121, 121),
"data/towns/tags/worldgen/biome/has_structure/village_meadow.json", "{\"values\": [\"minecraft:plains\", \"#minecraft:is_forest\"]}",
"data/minecraft/tags/worldgen/biome/has_structure/village_plains.json", "{\"values\": [\"towns:grove\"]}",
"data/minecraft/tags/worldgen/biome/has_structure/pillager_outpost.json", "{\"replace\": true, \"values\": [\"minecraft:desert\"]}"));
File pack = StructureTestPacks.pack(temporaryFolder.newFolder("pack"), StructureTestPacks.dimension(List.of(towns), ""), "[]");
IrisData data = IrisData.openRuntime(pack);
try {
PackCompileContext context = StructureTestPacks.context(data);
assertEquals(StructureTestPacks.parse("{\"replace\": false, \"values\": [\"" + StructureTestPacks.MAPPED + "\"]}"),
StructureTestPacks.json(context).get("data/minecraft/tags/worldgen/biome/has_structure/village_plains.json"));
new StructureStage().apply(context);
SortedMap<String, JsonElement> json = StructureTestPacks.json(context);
assertEquals(StructureTestPacks.parse("{\"replace\": false, \"values\": [\"minecraft:plains\", \"#minecraft:is_forest\", \""
+ StructureTestPacks.MAPPED + "\"]}"),
json.get("data/towns/tags/worldgen/biome/has_structure/village_meadow.json"));
assertEquals(StructureTestPacks.parse("{\"replace\": false, \"values\": [\"" + StructureTestPacks.MAPPED + "\", \"towns:grove\"]}"),
json.get("data/minecraft/tags/worldgen/biome/has_structure/village_plains.json"));
assertEquals(StructureTestPacks.parse("{\"replace\": true, \"values\": [\"minecraft:desert\", \"" + StructureTestPacks.DESERT + "\"]}"),
json.get("data/minecraft/tags/worldgen/biome/has_structure/pillager_outpost.json"));
} finally {
data.close();
}
}
@Test
public void disabledStructurePointsAtEmptyTag() throws Exception {
runningVanilla(Map.of(
"data/minecraft/worldgen/structure/village_plains.json", VILLAGE,
"data/minecraft/worldgen/structure/mineshaft.json", MINESHAFT));
File bundle = StructureTestPacks.zip(temporaryFolder.newFolder("imports"), "bundle.zip", Map.of(
"pack.mcmeta", StructureTestPacks.metadata(121, 121),
"data/bundle/worldgen/structure/tower.json", TOWER,
"data/bundle/worldgen/structure/tower_big.json", TOWER,
"data/bundle/worldgen/structure/towers.json", TOWER));
File pack = StructureTestPacks.pack(temporaryFolder.newFolder("pack"), StructureTestPacks.dimension(List.of(bundle),
"\"importedStructures\": {\"disabled\": [\"bundle:tower\", \"minecraft:village\"]}"), "[]");
IrisData data = IrisData.openRuntime(pack);
try {
PackCompileContext context = StructureTestPacks.compiled(data);
SortedMap<String, JsonElement> json = StructureTestPacks.json(context);
SortedMap<String, String> binaries = StructureTestPacks.binaries(context);
String disabledTag = "#" + StructureTestPacks.NAMESPACE + ":" + NativeStructureOverrides.DISABLED_TAG;
for (String path : List.of("data/bundle/worldgen/structure/tower.json", "data/bundle/worldgen/structure/tower_big.json",
"data/minecraft/worldgen/structure/village_plains.json")) {
assertEquals(path, disabledTag, json.get(path).getAsJsonObject().get("biomes").getAsString());
assertFalse(path, binaries.containsKey(path));
}
assertEquals("bundle:tower/start", json.get("data/bundle/worldgen/structure/tower.json").getAsJsonObject().get("start_pool").getAsString());
assertTrue(binaries.containsKey("data/bundle/worldgen/structure/towers.json"));
assertFalse(json.containsKey("data/minecraft/worldgen/structure/mineshaft.json"));
assertEquals(StructureTestPacks.parse("{\"replace\": false, \"values\": []}"),
json.get("data/iris_export/tags/worldgen/biome/" + NativeStructureOverrides.DISABLED_TAG + ".json"));
} finally {
data.close();
}
}
@Test
public void adjustmentsShiftJigsawStartsAndReportTheRest() throws Exception {
runningVanilla(Map.of("data/minecraft/worldgen/structure/mineshaft.json", MINESHAFT));
File bundle = StructureTestPacks.zip(temporaryFolder.newFolder("imports"), "bundle.zip", Map.of(
"pack.mcmeta", StructureTestPacks.metadata(121, 121),
"data/bundle/worldgen/structure/tower.json", TOWER));
File pack = StructureTestPacks.pack(temporaryFolder.newFolder("pack"), StructureTestPacks.dimension(List.of(bundle), """
"importedStructures": {"adjustments": [
{"match": ["bundle:"], "yShift": -8},
{"match": ["minecraft:mineshaft"], "yShift": 4, "stilt": {}}]}
"""), "[]");
IrisData data = IrisData.openRuntime(pack);
try {
PackCompileContext context = StructureTestPacks.compiled(data);
JsonObject tower = StructureTestPacks.json(context).get("data/bundle/worldgen/structure/tower.json").getAsJsonObject();
assertEquals(StructureTestPacks.parse("{\"absolute\": -8}"), tower.get("start_height"));
assertEquals("#bundle:has_structure/tower", tower.get("biomes").getAsString());
assertFalse(StructureTestPacks.json(context).containsKey("data/minecraft/worldgen/structure/mineshaft.json"));
List<String> dropped = new ArrayList<>();
for (ExportDiagnostic diagnostic : StructureTestPacks.diagnostics(context, ExportLimit.STRUCTURE_ADJUSTMENT)) {
assertEquals("minecraft:mineshaft", diagnostic.resource());
dropped.add(diagnostic.message());
}
assertEquals(dropped.toString(), 2, dropped.size());
} finally {
data.close();
}
}
@Test
public void nativePlacementScopedToRegionBiomes() throws Exception {
File bundle = StructureTestPacks.zip(temporaryFolder.newFolder("imports"), "bundle.zip", Map.of(
"pack.mcmeta", StructureTestPacks.metadata(121, 121),
"data/bundle/worldgen/structure/tower.json", TOWER));
File pack = StructureTestPacks.pack(temporaryFolder.newFolder("pack"), StructureTestPacks.dimension(List.of(bundle), ""), """
[{"nativeStructures": [{"structure": "bundle:tower", "weight": 3}], "spacing": 24, "separation": 6, "salt": 776215551}]
""");
IrisData data = IrisData.openRuntime(pack);
try {
PackCompileContext context = StructureTestPacks.compiled(data);
SortedMap<String, JsonElement> json = StructureTestPacks.json(context);
String copyId = "iris_export:placement/region/second/0/bundle/tower";
JsonObject copy = json.get("data/iris_export/worldgen/structure/placement/region/second/0/bundle/tower.json").getAsJsonObject();
assertEquals("#iris_export:placement/region/second", copy.get("biomes").getAsString());
assertEquals("bundle:tower/start", copy.get("start_pool").getAsString());
assertEquals(StructureTestPacks.parse("{\"replace\": false, \"values\": [\"" + StructureTestPacks.DESERT + "\", \""
+ StructureTestPacks.OCEAN + "\"]}"), json.get("data/iris_export/tags/worldgen/biome/placement/region/second.json"));
assertEquals(StructureTestPacks.parse("""
{"structures": [{"structure": "%s", "weight": 3}],
"placement": {"type": "minecraft:random_spread", "spacing": 24, "separation": 6, "salt": 776215551}}
""".formatted(copyId)), json.get("data/iris_export/worldgen/structure_set/placement/region/second/0.json"));
assertTrue(StructureTestPacks.binaries(context).containsKey("data/bundle/worldgen/structure/tower.json"));
List<ExportDiagnostic> scope = StructureTestPacks.diagnostics(context, ExportLimit.STRUCTURE_PLACEMENT);
assertEquals(scope.toString(), 1, scope.size());
assertEquals("regions/second/structures[0]", scope.getFirst().resource());
assertTrue(scope.getFirst().message(), scope.getFirst().message().contains(StructureTestPacks.OCEAN));
} finally {
data.close();
}
}
@Test
public void jigsawPlacementUsesIrisGrid() throws Exception {
File pack = StructureTestPacks.pack(temporaryFolder.newFolder("pack"), StructureTestPacks.dimension(List.of(), """
"structures": [{"structures": ["test_structure"], "spacing": 40, "separation": 10, "salt": 91834401}]
"""), "[]");
writeJigsawStructure(pack);
IrisData data = IrisData.openRuntime(pack);
try {
PackCompileContext context = StructureTestPacks.compiled(data);
SortedMap<String, JsonElement> json = StructureTestPacks.json(context);
String resourcePath = "placement/dimension/0/test_structure";
assertEquals(StructureTestPacks.parse("""
{"structures": [{"structure": "iris_export:%s", "weight": 1}],
"placement": {"type": "minecraft:random_spread", "spacing": 40, "separation": 10, "salt": 91834401}}
""".formatted(resourcePath)), json.get("data/iris_export/worldgen/structure_set/placement/dimension/0.json"));
JsonObject structure = json.get("data/iris_export/worldgen/structure/" + resourcePath + ".json").getAsJsonObject();
assertEquals("minecraft:jigsaw", structure.get("type").getAsString());
assertEquals("#iris_export:placement/dimension", structure.get("biomes").getAsString());
assertEquals("iris_export:" + resourcePath + "/pool/pools/start", structure.get("start_pool").getAsString());
assertEquals("WORLD_SURFACE_WG", structure.get("project_start_to_heightmap").getAsString());
assertFalse(json.containsKey("data/iris_export/worldgen/structure_set/" + resourcePath + ".json"));
assertFalse(json.containsKey("data/iris_export/tags/worldgen/biome/" + resourcePath + ".json"));
assertTrue(json.containsKey("data/iris_export/worldgen/template_pool/" + resourcePath + "/pool/pools/start.json"));
assertEquals(StructureTestPacks.parse("{\"replace\": false, \"values\": [\"" + StructureTestPacks.DESERT + "\", \""
+ StructureTestPacks.FOREST + "\", \"" + StructureTestPacks.MAPPED + "\", \"" + StructureTestPacks.OCEAN + "\"]}"),
json.get("data/iris_export/tags/worldgen/biome/placement/dimension.json"));
BinaryResource template = binary(context, "data/iris_export/structure/" + resourcePath + "/piece/pieces/start.nbt");
CompoundTag nbt = (CompoundTag) NBTUtil.read(new ByteArrayInputStream(template.bytes()), true).getTag();
assertEquals(5023, nbt.getInt("DataVersion"));
assertTrue(StructureTestPacks.diagnostics(context, ExportLimit.JIGSAW_STRUCTURE).toString(),
StructureTestPacks.diagnostics(context, ExportLimit.JIGSAW_STRUCTURE).isEmpty());
} finally {
data.close();
}
}
@Test
public void stageOutputIsDeterministic() throws Exception {
File bundle = StructureTestPacks.zip(temporaryFolder.newFolder("imports"), "bundle.zip", Map.of(
"pack.mcmeta", StructureTestPacks.metadata(121, 121),
"data/bundle/worldgen/structure/tower.json", TOWER,
"data/bundle/worldgen/structure/towers.json", TOWER,
"data/bundle/structure/tower.nbt", "template",
"data/bundle/tags/worldgen/biome/has_structure/tower.json", "{\"values\": [\"minecraft:desert\", \"minecraft:plains\"]}"));
File pack = StructureTestPacks.pack(temporaryFolder.newFolder("pack"), StructureTestPacks.dimension(List.of(bundle), """
"importedStructures": {"disabled": ["bundle:towers"]},
"structures": [{"structures": ["test_structure"], "distribution": "DENSITY", "density": 0.05, "underground": true,
"minHeight": -40, "maxHeight": 10}]
"""), """
[{"nativeStructures": [{"structure": "bundle:tower"}], "distribution": "CONCENTRIC_RINGS"}]
""");
writeJigsawStructure(pack);
List<String> first = snapshot(pack);
List<String> second = snapshot(pack);
assertEquals(first, second);
assertTrue(first.toString(), first.stream().anyMatch(line -> line.startsWith("data/iris_export/worldgen/structure_set/placement/dimension/0.json")));
assertTrue(first.toString(), first.stream().anyMatch(line -> line.startsWith("data/iris_export/worldgen/structure_set/placement/region/second/0.json")));
}
private List<String> snapshot(File pack) {
IrisData data = IrisData.openRuntime(pack);
try {
PackCompileContext context = StructureTestPacks.compiled(data);
List<String> lines = new ArrayList<>();
for (JsonResource resource : context.jsonResources()) {
lines.add(resource.path() + " " + resource.json());
}
for (BinaryResource resource : context.binaryResources()) {
lines.add(resource.path() + " " + Arrays.hashCode(resource.bytes()));
}
for (ExportDiagnostic diagnostic : context.diagnostics()) {
lines.add(diagnostic.toString());
}
return lines;
} finally {
data.close();
}
}
private void runningVanilla(Map<String, String> files) {
doReturn("26.3").when(IrisPlatforms.get()).minecraftVersion();
doReturn(FakeVanillaDataSource.of(files)).when(IrisPlatforms.get()).vanillaData();
}
private static void writeJigsawStructure(File pack) throws Exception {
CompatTestPlatform.write(pack, "structures/test_structure.json", """
{"startPool": "pools/start", "maxDepth": 4, "maxSizeChunks": 4,
"compatibility": "VANILLA_PORTABLE", "branchFailurePolicy": "TERMINATE_BRANCH"}
""");
CompatTestPlatform.write(pack, "jigsaw-pools/pools/start.json", "{\"pieces\": [{\"piece\": \"pieces/start\", \"weight\": 1}]}");
CompatTestPlatform.write(pack, "jigsaw-pieces/pieces/start.json", "{\"object\": \"start\"}");
CompatTestPlatform.writeObjectWithBlocks(pack, "start", "minecraft:stone");
}
private static BinaryResource binary(PackCompileContext context, String path) {
for (BinaryResource resource : context.binaryResources()) {
if (resource.path().equals(path)) {
return resource;
}
}
throw new AssertionError("Missing binary resource " + path);
}
}
@@ -0,0 +1,128 @@
package art.arcane.iris.pack.datapack.export.compile.structure;
import art.arcane.iris.pack.datapack.DataVersion;
import art.arcane.iris.pack.datapack.export.ExportTestPacks;
import art.arcane.iris.pack.datapack.export.compile.DimensionStage;
import art.arcane.iris.pack.datapack.export.compile.PackCompileContext;
import art.arcane.iris.pack.datapack.export.compile.biome.BiomeCodes;
import art.arcane.iris.pack.datapack.export.compile.biome.BiomeDefinitionCompiler;
import art.arcane.iris.pack.datapack.export.ir.BinaryResource;
import art.arcane.iris.pack.datapack.export.ir.ClimateLayout;
import art.arcane.iris.pack.datapack.export.ir.ExportDiagnostic;
import art.arcane.iris.pack.datapack.export.ir.ExportLimit;
import art.arcane.iris.pack.datapack.export.ir.Field;
import art.arcane.iris.pack.datapack.export.ir.JsonResource;
import art.arcane.iris.pack.loading.IrisData;
import art.arcane.iris.testsupport.CompatTestPlatform;
import com.google.gson.JsonElement;
import com.google.gson.JsonParser;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.SortedMap;
import java.util.TreeMap;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
final class StructureTestPacks {
static final String NAMESPACE = "iris_export";
static final String FOREST = "iris_export:forest_land";
static final String MAPPED = "iris_export:mapped";
static final String OCEAN = "iris_export:ocean";
static final String DESERT = "iris_export:desert";
static final Map<String, String> EXPORTED = Map.of(FOREST, "Forest Land", MAPPED, "mapped", OCEAN, "ocean", DESERT, "desert");
private static final Field ZERO = new Field.Const(0.0);
private StructureTestPacks() {
}
static File pack(File folder, String dimensionJson, String secondRegionStructures) throws IOException {
File pack = ExportTestPacks.withDimension(folder, dimensionJson);
CompatTestPlatform.write(pack, "regions/second.json",
"{\"landBiomes\":[\"desert\"],\"seaBiomes\":[\"ocean\"],\"structures\":" + secondRegionStructures + "}");
CompatTestPlatform.write(pack, "biomes/Forest Land.json", "{\"name\":\"Forest Land\",\"derivative\":\"minecraft:forest\"}");
CompatTestPlatform.write(pack, "biomes/mapped.json", "{\"name\":\"Mapped\",\"derivative\":\"minecraft:plains\"}");
CompatTestPlatform.write(pack, "biomes/desert.json", "{\"name\":\"Desert\",\"derivative\":\"minecraft:desert\"}");
return pack;
}
static String dimension(List<File> imports, String extra) {
List<String> sources = new ArrayList<>(imports.size());
for (File archive : imports) {
sources.add("\"" + archive.toURI().toASCIIString() + "\"");
}
return "{\"regions\":[\"region\",\"second\"],\"datapackImports\":[" + String.join(",", sources) + "]"
+ (extra.isEmpty() ? "" : "," + extra) + "}";
}
static File zip(File folder, String name, Map<String, String> entries) throws IOException {
File archive = new File(folder, name);
try (ZipOutputStream output = new ZipOutputStream(new FileOutputStream(archive))) {
for (Map.Entry<String, String> entry : new TreeMap<>(entries).entrySet()) {
output.putNextEntry(new ZipEntry(entry.getKey()));
output.write(entry.getValue().getBytes(StandardCharsets.UTF_8));
output.closeEntry();
}
}
return archive;
}
static String metadata(int minimum, int maximum) {
return "{\"pack\":{\"description\":\"test\",\"min_format\":" + minimum + ",\"max_format\":" + maximum + "}}";
}
static PackCompileContext context(IrisData data) {
PackCompileContext context = ExportTestPacks.context(data, DataVersion.V26_3);
new DimensionStage().apply(context);
context.setBiomeCodes(new BiomeCodes(ZERO, ZERO, ZERO, new ClimateLayout(List.of()), EXPORTED));
BiomeDefinitionCompiler.Definitions definitions = BiomeDefinitionCompiler.forTarget(DataVersion.V26_3).compile(context, EXPORTED);
context.setBiomes(definitions.biomes());
context.jsonResources().addAll(definitions.tags());
return context;
}
static PackCompileContext compiled(IrisData data) {
PackCompileContext context = context(data);
new StructureStage().apply(context);
return context;
}
static SortedMap<String, JsonElement> json(PackCompileContext context) {
SortedMap<String, JsonElement> resources = new TreeMap<>();
for (JsonResource resource : context.jsonResources()) {
if (resources.put(resource.path(), resource.json()) != null) {
throw new AssertionError("Duplicate json resource " + resource.path());
}
}
return resources;
}
static SortedMap<String, String> binaries(PackCompileContext context) {
SortedMap<String, String> resources = new TreeMap<>();
for (BinaryResource resource : context.binaryResources()) {
if (resources.put(resource.path(), new String(resource.bytes(), StandardCharsets.UTF_8)) != null) {
throw new AssertionError("Duplicate binary resource " + resource.path());
}
}
return resources;
}
static List<ExportDiagnostic> diagnostics(PackCompileContext context, ExportLimit limit) {
List<ExportDiagnostic> matching = new ArrayList<>();
for (ExportDiagnostic diagnostic : context.diagnostics()) {
if (diagnostic.limit() == limit) {
matching.add(diagnostic);
}
}
return matching;
}
static JsonElement parse(String json) {
return JsonParser.parseString(json);
}
}
@@ -0,0 +1,247 @@
package art.arcane.iris.pack.datapack.export.compile.subterrain;
import art.arcane.iris.generation.subterrain.IrisSubterrainFeature;
import art.arcane.iris.generation.subterrain.SubterrainCell;
import art.arcane.iris.generation.subterrain.SubterrainPlan;
import art.arcane.iris.generation.subterrain.SubterrainPlanner;
import art.arcane.iris.generation.terrain.IrisDimension;
import art.arcane.iris.pack.datapack.DataVersion;
import art.arcane.iris.pack.datapack.export.ExportTestPacks;
import art.arcane.iris.pack.datapack.export.TemplateBlock;
import art.arcane.iris.pack.datapack.export.TemplateVolume;
import art.arcane.iris.pack.datapack.export.VanillaBlockState;
import art.arcane.iris.pack.datapack.export.compile.PackCompileContext;
import art.arcane.iris.pack.datapack.export.ir.ExportDiagnostic;
import art.arcane.iris.pack.datapack.export.ir.ExportLimit;
import art.arcane.iris.pack.loading.IrisData;
import art.arcane.iris.testsupport.PlatformLeakGuard;
import org.junit.ClassRule;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.TreeSet;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
public class SubterrainBakerTest {
private static final long SEED = 7331L;
private static final VanillaBlockState CAVE_AIR = VanillaBlockState.parse("minecraft:cave_air");
private static final VanillaBlockState WATER = VanillaBlockState.parse("minecraft:water");
private static final VanillaBlockState LAVA = VanillaBlockState.parse("minecraft:lava");
private static final VanillaBlockState STONE = VanillaBlockState.parse("minecraft:stone");
private static final VanillaBlockState GRASS = VanillaBlockState.parse("minecraft:grass_block");
@ClassRule
public static final PlatformLeakGuard PLATFORM_GUARD = PlatformLeakGuard.clean();
@Rule
public TemporaryFolder temporaryFolder = new TemporaryFolder();
@Rule
public ExportTestPacks.BoundPlatform platform = new ExportTestPacks.BoundPlatform();
@Test
public void bakedRoomsMatchIrisCells() throws Exception {
IrisData data = IrisData.openRuntime(SubterrainTestPacks.pack(temporaryFolder.newFolder("pack"), SubterrainTestPacks.CENOTE));
try {
IrisSubterrainFeature feature = feature(data, 0);
PackCompileContext context = SubterrainTestPacks.context(data, DataVersion.V26_3);
BakedFeature baked = new SubterrainBaker(context, SEED).bake(feature, "pools").orElseThrow();
assertEquals(SubterrainBaker.VARIANTS, baked.rooms().size());
SubterrainPlanner planner = new SubterrainPlanner(new SubterrainPlanner.Options(List.of(feature), SEED,
SubterrainTestPacks.MIN_Y, SubterrainTestPacks.MAX_Y, (x, z) -> ""));
Set<String> kinds = new TreeSet<>();
for (BakedRoom room : baked.rooms()) {
SubterrainPlan plan = plan(planner, room);
Map<Long, VanillaBlockState> core = index(room.core());
Map<Long, VanillaBlockState> shell = index(room.shell());
assertEquals(plan.centerX() - room.originX(), room.anchorX());
assertEquals(plan.centerY() - room.originY(), room.anchorY());
assertEquals(plan.centerZ() - room.originZ(), room.anchorZ());
for (int x = 0; x < room.core().sizeX(); x++) {
for (int y = 0; y < room.core().sizeY(); y++) {
for (int z = 0; z < room.core().sizeZ(); z++) {
SubterrainCell cell = planner.sample(List.of(plan), room.originX() + x, room.originY() + y, room.originZ() + z);
long key = key(x, y, z);
boolean anchor = x == room.anchorX() && y == room.anchorY() && z == room.anchorZ();
VanillaBlockState expectedCore = switch (cell.kind()) {
case AIR -> CAVE_AIR;
case WATER -> WATER;
case LAVA -> LAVA;
case SOLID -> cell.room().reservedSolid() ? STONE : null;
case OUTSIDE -> null;
};
VanillaBlockState expectedShell = cell.solid() && !cell.room().reservedSolid() ? STONE : null;
kinds.add(cell.kind() + (cell.solid() && cell.room().reservedSolid() ? "_RESERVED" : ""));
if (anchor) {
assertEquals(expectedCore == null ? SubterrainBaker.NO_BLOCK : expectedCore, room.anchorState());
assertFalse(core.containsKey(key));
} else {
assertEquals(x + "," + y + "," + z + " " + cell.kind(), expectedCore, core.get(key));
}
assertEquals(x + "," + y + "," + z + " " + cell.kind(), expectedShell, shell.get(key));
}
}
}
}
assertTrue(kinds.toString(), kinds.containsAll(List.of("AIR", "WATER", "SOLID", "SOLID_RESERVED", "OUTSIDE")));
assertTrue(context.diagnostics().toString(), context.diagnostics().isEmpty());
} finally {
data.close();
}
}
@Test
public void anchorRangeMatchesIrisPlacementBand() throws Exception {
IrisData data = IrisData.openRuntime(SubterrainTestPacks.pack(temporaryFolder.newFolder("pack"), SubterrainTestPacks.CENOTE));
try {
BakedFeature baked = new SubterrainBaker(SubterrainTestPacks.context(data, DataVersion.V26_3), SEED)
.bake(feature(data, 0), "pools").orElseThrow();
int baseDepth = (int) Math.ceil(Math.min(24, 8 * 0.45) * 0.5);
assertEquals(-60 + 12 / 2 + 3 + baseDepth, baked.lowestAnchorY());
assertEquals(40 - (12 - 12 / 2 + 3), baked.highestAnchorY());
for (BakedRoom room : baked.rooms()) {
int center = room.originY() + room.anchorY();
assertTrue(center + " below " + baked.lowestAnchorY(), center >= baked.lowestAnchorY());
assertTrue(center + " above " + baked.highestAnchorY(), center <= baked.highestAnchorY());
}
} finally {
data.close();
}
}
@Test
public void roomBiomePaintsFloorsWallsAndCeilings() throws Exception {
IrisData data = IrisData.openRuntime(SubterrainTestPacks.pack(temporaryFolder.newFolder("pack"), SubterrainTestPacks.ROOM_CENOTE));
try {
BakedFeature baked = new SubterrainBaker(SubterrainTestPacks.context(data, DataVersion.V26_3), SEED)
.bake(feature(data, 0), "grottos").orElseThrow();
for (BakedRoom room : baked.rooms()) {
Map<Long, VanillaBlockState> core = index(room.core());
Set<VanillaBlockState> painted = new TreeSet<>((first, second) -> first.canonical().compareTo(second.canonical()));
for (TemplateBlock block : room.shell().blocks()) {
painted.add(block.state());
if (block.state().equals(GRASS)) {
assertTrue(touchesRoom(core, block, room));
}
}
assertTrue(painted.toString(), painted.contains(GRASS));
assertTrue(painted.toString(), painted.contains(STONE));
}
} finally {
data.close();
}
}
@Test
public void roomsBeyondStructureReachAreClipped() throws Exception {
IrisData data = IrisData.openRuntime(SubterrainTestPacks.pack(temporaryFolder.newFolder("pack"), SubterrainTestPacks.TUBE));
try {
PackCompileContext context = SubterrainTestPacks.context(data, DataVersion.V26_3);
BakedFeature baked = new SubterrainBaker(context, SEED).bake(feature(data, 0), "tubes").orElseThrow();
for (BakedRoom room : baked.rooms()) {
assertTrue(room.anchorX() <= SubterrainBaker.MAX_REACH && room.core().sizeX() - 1 - room.anchorX() <= SubterrainBaker.MAX_REACH);
assertTrue(room.anchorZ() <= SubterrainBaker.MAX_REACH && room.core().sizeZ() - 1 - room.anchorZ() <= SubterrainBaker.MAX_REACH);
assertTrue(Math.max(room.core().sizeX(), room.core().sizeZ()) == 2 * SubterrainBaker.MAX_REACH + 1);
assertTrue(room.core().blocks().stream().anyMatch(block -> block.state().equals(LAVA)));
}
assertTrue(baked.reach() <= SubterrainBaker.MAX_REACH);
List<ExportDiagnostic> bounds = SubterrainTestPacks.diagnostics(context.diagnostics(), ExportLimit.OBJECT_BOUNDS);
assertEquals(1, bounds.size());
assertEquals("tubes", bounds.getFirst().resource());
} finally {
data.close();
}
}
@Test
public void featureThatCannotFitIsNotBaked() throws Exception {
IrisData data = IrisData.openRuntime(SubterrainTestPacks.pack(temporaryFolder.newFolder("pack"), SubterrainTestPacks.SHALLOW));
try {
PackCompileContext context = SubterrainTestPacks.context(data, DataVersion.V26_3);
Optional<BakedFeature> baked = new SubterrainBaker(context, SEED).bake(feature(data, 0), "shallow");
assertFalse(baked.isPresent());
assertEquals(1, SubterrainTestPacks.diagnostics(context.diagnostics(), ExportLimit.STRUCTURE_PLACEMENT).size());
} finally {
data.close();
}
}
@Test
public void bakingIsDeterministic() throws Exception {
IrisData data = IrisData.openRuntime(SubterrainTestPacks.pack(temporaryFolder.newFolder("pack"), SubterrainTestPacks.CENOTE));
try {
IrisSubterrainFeature feature = feature(data, 0);
BakedFeature first = new SubterrainBaker(SubterrainTestPacks.context(data, DataVersion.V26_3), SEED).bake(feature, "pools").orElseThrow();
BakedFeature second = new SubterrainBaker(SubterrainTestPacks.context(data, DataVersion.V26_3), SEED).bake(feature, "pools").orElseThrow();
assertEquals(first, second);
} finally {
data.close();
}
}
private static IrisSubterrainFeature feature(IrisData data, int index) {
IrisDimension dimension = data.getDimensionLoader().load(ExportTestPacks.DIMENSION, false);
assertNotNull(dimension);
return dimension.getSubterrainFeatures().get(index);
}
private static SubterrainPlan plan(SubterrainPlanner planner, BakedRoom room) {
for (SubterrainPlan plan : planner.plansForBounds(room.originX(), room.originZ(),
room.originX() + room.core().sizeX() - 1, room.originZ() + room.core().sizeZ() - 1)) {
if (plan.bounds().minX() == room.originX() && plan.bounds().minY() == room.originY() && plan.bounds().minZ() == room.originZ()) {
return plan;
}
}
throw new AssertionError("No Iris plan starts at " + room.originX() + "," + room.originY() + "," + room.originZ());
}
private static Map<Long, VanillaBlockState> index(TemplateVolume volume) {
Map<Long, VanillaBlockState> blocks = new HashMap<>();
for (TemplateBlock block : volume.blocks()) {
assertTrue(blocks.put(key(block.x(), block.y(), block.z()), block.state()) == null);
}
return blocks;
}
private static boolean touchesRoom(Map<Long, VanillaBlockState> core, TemplateBlock block, BakedRoom room) {
int[][] offsets = {{1, 0, 0}, {-1, 0, 0}, {0, 1, 0}, {0, -1, 0}, {0, 0, 1}, {0, 0, -1}};
for (int[] offset : offsets) {
int x = block.x() + offset[0];
int y = block.y() + offset[1];
int z = block.z() + offset[2];
if (x == room.anchorX() && y == room.anchorY() && z == room.anchorZ()) {
return true;
}
VanillaBlockState neighbor = core.get(key(x, y, z));
if (CAVE_AIR.equals(neighbor) || WATER.equals(neighbor)) {
return true;
}
}
return false;
}
private static long key(int x, int y, int z) {
return ((long) x << 42) ^ ((long) y << 21) ^ z;
}
}
@@ -0,0 +1,305 @@
package art.arcane.iris.pack.datapack.export.compile.subterrain;
import art.arcane.iris.pack.datapack.DataVersion;
import art.arcane.iris.pack.datapack.export.ExportTestPacks;
import art.arcane.iris.pack.datapack.export.compile.PackCompileContext;
import art.arcane.iris.pack.datapack.export.compile.structure.PlacementTags;
import art.arcane.iris.pack.datapack.export.emit.UnusedResourcePruner;
import art.arcane.iris.pack.datapack.export.ir.ExportDiagnostic;
import art.arcane.iris.pack.datapack.export.ir.ExportLimit;
import art.arcane.iris.pack.loading.IrisData;
import art.arcane.iris.testsupport.PlatformLeakGuard;
import art.arcane.volmlib.util.nbt.io.NBTUtil;
import art.arcane.volmlib.util.nbt.tag.CompoundTag;
import art.arcane.volmlib.util.nbt.tag.ListTag;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import org.junit.ClassRule;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.Map;
import java.util.SortedMap;
import java.util.TreeMap;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
public class SubterrainStageTest {
private static final String POOLS_STRUCTURE = "data/iris_export/worldgen/structure/subterrain/pools.json";
private static final String POOLS_SET = "data/iris_export/worldgen/structure_set/subterrain/pools.json";
private static final String POOLS_POOL = "data/iris_export/worldgen/template_pool/subterrain/pools.json";
private static final String TUBES_STRUCTURE = "data/iris_export/worldgen/structure/subterrain/tubes.json";
private static final String TUBES_SET = "data/iris_export/worldgen/structure_set/subterrain/tubes.json";
private static final String TUBES_POOL = "data/iris_export/worldgen/template_pool/subterrain/tubes.json";
private static final String DIMENSION_TAG = "data/iris_export/tags/worldgen/biome/placement/dimension.json";
private static final String SECOND_TAG = "data/iris_export/tags/worldgen/biome/placement/region/second.json";
private static final String ANCHOR = "iris_export:subterrain/anchor";
@ClassRule
public static final PlatformLeakGuard PLATFORM_GUARD = PlatformLeakGuard.clean();
@Rule
public TemporaryFolder temporaryFolder = new TemporaryFolder();
@Rule
public ExportTestPacks.BoundPlatform platform = new ExportTestPacks.BoundPlatform();
@Test
public void roomsExportAsCenteredUndergroundJigsawStructures() throws Exception {
IrisData data = IrisData.openRuntime(SubterrainTestPacks.pack(temporaryFolder.newFolder("pack"), SubterrainTestPacks.CENOTE));
try {
PackCompileContext context = SubterrainTestPacks.context(data, DataVersion.V26_3);
new SubterrainStage().apply(context);
SortedMap<String, JsonElement> json = SubterrainTestPacks.json(context);
JsonObject structure = json.get(POOLS_STRUCTURE).getAsJsonObject();
assertEquals("minecraft:jigsaw", structure.get("type").getAsString());
assertEquals("#iris_export:placement/dimension", structure.get("biomes").getAsString());
assertEquals("underground_structures", structure.get("step").getAsString());
assertEquals("iris_export:subterrain/pools", structure.get("start_pool").getAsString());
assertEquals(ANCHOR, structure.get("start_jigsaw_name").getAsString());
assertEquals("none", structure.get("terrain_adaptation").getAsString());
assertFalse(structure.has("project_start_to_heightmap"));
assertEquals(10, structure.get("max_distance_from_center").getAsInt());
int baseDepth = (int) Math.ceil(Math.min(24, 8 * 0.45) * 0.5);
assertEquals(JsonParser.parseString("{\"type\":\"minecraft:uniform\",\"min_inclusive\":{\"absolute\":"
+ (-60 + 12 / 2 + 3 + baseDepth + 1) + "},\"max_inclusive\":{\"absolute\":" + (40 - (12 - 12 / 2 + 3) + 1) + "}}"),
structure.get("start_height"));
assertEquals(JsonParser.parseString("{\"placement\":{\"type\":\"minecraft:random_spread\",\"salt\":" + salt("pools")
+ ",\"separation\":2,\"spacing\":4},\"structures\":[{\"structure\":\"iris_export:subterrain/pools\",\"weight\":1}]}"),
json.get(POOLS_SET));
JsonArray dimensionBiomes = json.get(DIMENSION_TAG).getAsJsonObject().getAsJsonArray("values");
assertEquals(SubterrainTestPacks.EXPORTED.size(), dimensionBiomes.size());
JsonArray elements = json.get(POOLS_POOL).getAsJsonObject().getAsJsonArray("elements");
assertEquals(SubterrainBaker.VARIANTS, elements.size());
SortedMap<String, byte[]> binaries = SubterrainTestPacks.binaries(context);
for (int index = 0; index < elements.size(); index++) {
JsonObject element = elements.get(index).getAsJsonObject().getAsJsonObject("element");
assertEquals("minecraft:list_pool_element", element.get("element_type").getAsString());
JsonArray parts = element.getAsJsonArray("elements");
assertEquals(2, parts.size());
String core = "iris_export:subterrain/pools/" + index + "_core";
String shell = "iris_export:subterrain/pools/" + index + "_shell";
assertEquals(core, parts.get(0).getAsJsonObject().get("location").getAsString());
assertEquals(shell, parts.get(1).getAsJsonObject().get("location").getAsString());
assertEquals(0, parts.get(0).getAsJsonObject().getAsJsonObject("processors").getAsJsonArray("processors").size());
assertEquals(guard("{\"id\":\"minecraft:cave_air\"}", "{\"id\":\"minecraft:water\"}", "{\"id\":\"minecraft:lava\"}"),
parts.get(1).getAsJsonObject().get("processors"));
CompoundTag coreTemplate = template(binaries, "data/iris_export/structure/subterrain/pools/" + index + "_core.nbt");
assertEquals(DataVersion.V26_3.getWorldDataVersion(), coreTemplate.getInt("DataVersion"));
CompoundTag jigsaw = anchor(coreTemplate);
assertEquals(ANCHOR, jigsaw.getString("name"));
assertEquals("minecraft:empty", jigsaw.getString("pool"));
assertNotNull(template(binaries, "data/iris_export/structure/subterrain/pools/" + index + "_shell.nbt"));
}
assertEquals(1, matching(context, ExportLimit.SUBTERRAIN_VARIANT, "pools"));
assertEquals(1, matching(context, ExportLimit.SUBTERRAIN_TERRAIN, "pools"));
assertEquals(0, matching(context, ExportLimit.SUBTERRAIN_BIOME, "pools"));
} finally {
data.close();
}
}
@Test
public void regionRestrictedRoomsUseTheRegionPlacementTag() throws Exception {
IrisData data = IrisData.openRuntime(SubterrainTestPacks.pack(temporaryFolder.newFolder("pack"), SubterrainTestPacks.TUBE));
try {
PackCompileContext context = SubterrainTestPacks.context(data, DataVersion.V26_3);
new SubterrainStage().apply(context);
SortedMap<String, JsonElement> json = SubterrainTestPacks.json(context);
JsonObject structure = json.get(TUBES_STRUCTURE).getAsJsonObject();
assertEquals("#iris_export:placement/region/second", structure.get("biomes").getAsString());
assertEquals(JsonParser.parseString("{\"replace\":false,\"values\":[\"" + SubterrainTestPacks.DESERT + "\",\""
+ SubterrainTestPacks.OCEAN + "\"]}"), json.get(SECOND_TAG));
assertFalse(json.containsKey(DIMENSION_TAG));
JsonObject placement = json.get(TUBES_SET).getAsJsonObject().getAsJsonObject("placement");
assertEquals(20, placement.get("spacing").getAsInt());
assertEquals(10, placement.get("separation").getAsInt());
assertEquals(0.5f, placement.get("frequency").getAsFloat(), 0.0f);
assertEquals(1, matching(context, ExportLimit.STRUCTURE_PLACEMENT, "tubes"));
assertEquals(1, matching(context, ExportLimit.OBJECT_BOUNDS, "tubes"));
} finally {
data.close();
}
}
@Test
public void existingPlacementTagIsReused() throws Exception {
IrisData data = IrisData.openRuntime(SubterrainTestPacks.pack(temporaryFolder.newFolder("pack"), SubterrainTestPacks.TUBE));
try {
PackCompileContext context = SubterrainTestPacks.context(data, DataVersion.V26_3);
PlacementTags.collect(context).regionTag("second").orElseThrow();
int before = context.jsonResources().size();
new SubterrainStage().apply(context);
SortedMap<String, JsonElement> json = SubterrainTestPacks.json(context);
assertTrue(json.containsKey(SECOND_TAG));
assertEquals(before + 3, context.jsonResources().size());
} finally {
data.close();
}
}
@Test
public void roomBiomeIsReported() throws Exception {
IrisData data = IrisData.openRuntime(SubterrainTestPacks.pack(temporaryFolder.newFolder("pack"), SubterrainTestPacks.ROOM_CENOTE));
try {
PackCompileContext context = SubterrainTestPacks.context(data, DataVersion.V26_3);
new SubterrainStage().apply(context);
assertEquals(1, matching(context, ExportLimit.SUBTERRAIN_BIOME, "grottos"));
for (ExportDiagnostic diagnostic : SubterrainTestPacks.diagnostics(context.diagnostics(), ExportLimit.SUBTERRAIN_BIOME)) {
assertTrue(diagnostic.message(), diagnostic.message().contains("'room'"));
}
} finally {
data.close();
}
}
@Test
public void disabledAndUnplaceableFeaturesExportNothing() throws Exception {
IrisData data = IrisData.openRuntime(SubterrainTestPacks.pack(temporaryFolder.newFolder("pack"),
SubterrainTestPacks.DISABLED, SubterrainTestPacks.SHALLOW));
try {
PackCompileContext context = SubterrainTestPacks.context(data, DataVersion.V26_3);
new SubterrainStage().apply(context);
assertTrue(SubterrainTestPacks.binaries(context).isEmpty());
for (String path : SubterrainTestPacks.json(context).keySet()) {
assertFalse(path, path.contains("/subterrain/"));
}
assertEquals(1, matching(context, ExportLimit.STRUCTURE_PLACEMENT, "shallow"));
assertEquals(0, matching(context, ExportLimit.SUBTERRAIN_VARIANT, "off"));
} finally {
data.close();
}
}
@Test
public void dimensionWithoutCarvingExportsNoRooms() throws Exception {
IrisData data = IrisData.openRuntime(SubterrainTestPacks.packWith(temporaryFolder.newFolder("pack"), "\"carvingEnabled\": false",
SubterrainTestPacks.CENOTE));
try {
PackCompileContext context = SubterrainTestPacks.context(data, DataVersion.V26_3);
new SubterrainStage().apply(context);
assertTrue(context.jsonResources().isEmpty());
assertTrue(context.binaryResources().isEmpty());
assertTrue(context.diagnostics().isEmpty());
} finally {
data.close();
}
}
@Test
public void prunerKeepsPlacedRoomsAndDropsUnplacedRooms() throws Exception {
IrisData data = IrisData.openRuntime(SubterrainTestPacks.pack(temporaryFolder.newFolder("pack"),
SubterrainTestPacks.CENOTE, SubterrainTestPacks.TUBE));
try {
PackCompileContext context = SubterrainTestPacks.context(data, DataVersion.V26_3);
new SubterrainStage().apply(context);
SortedMap<String, byte[]> files = files(context);
List<String> rooms = rooms(files);
assertEquals(2 * (3 + 2 * SubterrainBaker.VARIANTS) + 2, rooms.size());
UnusedResourcePruner.Pruned placed = UnusedResourcePruner.prune(files);
for (String path : rooms) {
assertTrue(path, placed.files().containsKey(path));
}
files.put(SECOND_TAG, "{\"replace\":false,\"values\":[]}".getBytes(StandardCharsets.UTF_8));
UnusedResourcePruner.Pruned unplaced = UnusedResourcePruner.prune(files);
for (String path : rooms) {
boolean tubes = path.contains("/subterrain/tubes") || path.equals(SECOND_TAG);
assertEquals(path, !tubes, unplaced.files().containsKey(path));
}
} finally {
data.close();
}
}
private static int salt(String id) {
long salt = 0xcbf29ce484222325L;
for (int index = 0; index < id.length(); index++) {
salt = (salt ^ id.charAt(index)) * 0x100000001b3L;
}
return (int) (salt ^ (salt >>> 32)) & Integer.MAX_VALUE;
}
private static JsonElement guard(String air, String water, String lava) {
return JsonParser.parseString("{\"processors\":[{\"processor_type\":\"minecraft:rule\",\"rules\":["
+ rule("{\"predicate_type\":\"minecraft:tag_match\",\"tag\":\"minecraft:air\"}", air) + ","
+ rule("{\"predicate_type\":\"minecraft:block_match\",\"block\":\"minecraft:water\"}", water) + ","
+ rule("{\"predicate_type\":\"minecraft:block_match\",\"block\":\"minecraft:lava\"}", lava) + "]}]}");
}
private static String rule(String location, String output) {
return "{\"input_predicate\":{\"predicate_type\":\"minecraft:always_true\"},\"location_predicate\":" + location
+ ",\"output_state\":" + output + "}";
}
private static CompoundTag template(SortedMap<String, byte[]> binaries, String path) throws IOException {
byte[] bytes = binaries.get(path);
assertNotNull(path + " in " + binaries.keySet(), bytes);
return (CompoundTag) NBTUtil.read(new ByteArrayInputStream(bytes), true).getTag();
}
private static CompoundTag anchor(CompoundTag template) {
ListTag<CompoundTag> palette = template.getListTag("palette").asCompoundTagList();
CompoundTag found = null;
for (CompoundTag block : template.getListTag("blocks").asCompoundTagList()) {
CompoundTag state = palette.get(block.getInt("state"));
String name = state.containsKey("Name") ? state.getString("Name") : state.getString("id");
if (name.equals("minecraft:jigsaw")) {
assertTrue(found == null);
found = block.getCompoundTag("nbt");
}
}
assertNotNull(found);
return found;
}
private static int matching(PackCompileContext context, ExportLimit limit, String feature) {
int count = 0;
for (ExportDiagnostic diagnostic : SubterrainTestPacks.diagnostics(context.diagnostics(), limit)) {
if (diagnostic.resource().endsWith("/subterrainFeatures/" + feature)) {
count++;
}
}
return count;
}
private static SortedMap<String, byte[]> files(PackCompileContext context) {
SortedMap<String, byte[]> files = new TreeMap<>();
files.put("pack.mcmeta", "{\"pack\":{\"description\":\"test\",\"min_format\":121,\"max_format\":121}}".getBytes(StandardCharsets.UTF_8));
for (Map.Entry<String, JsonElement> entry : SubterrainTestPacks.json(context).entrySet()) {
files.put(entry.getKey(), entry.getValue().toString().getBytes(StandardCharsets.UTF_8));
}
files.putAll(SubterrainTestPacks.binaries(context));
return files;
}
private static List<String> rooms(SortedMap<String, byte[]> files) {
return files.keySet().stream().filter(path -> path.contains("/subterrain/") || path.contains("/placement/")).toList();
}
}
@@ -0,0 +1,118 @@
package art.arcane.iris.pack.datapack.export.compile.subterrain;
import art.arcane.iris.pack.datapack.DataVersion;
import art.arcane.iris.pack.datapack.export.ExportTestPacks;
import art.arcane.iris.pack.datapack.export.compile.DimensionStage;
import art.arcane.iris.pack.datapack.export.compile.PackCompileContext;
import art.arcane.iris.pack.datapack.export.compile.biome.BiomeCodes;
import art.arcane.iris.pack.datapack.export.ir.BinaryResource;
import art.arcane.iris.pack.datapack.export.ir.ClimateLayout;
import art.arcane.iris.pack.datapack.export.ir.ExportDiagnostic;
import art.arcane.iris.pack.datapack.export.ir.ExportLimit;
import art.arcane.iris.pack.datapack.export.ir.Field;
import art.arcane.iris.pack.datapack.export.ir.JsonResource;
import art.arcane.iris.pack.loading.IrisData;
import art.arcane.iris.testsupport.CompatTestPlatform;
import com.google.gson.JsonElement;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.SortedMap;
import java.util.TreeMap;
final class SubterrainTestPacks {
static final String NAMESPACE = "iris_export";
static final String FOREST = "iris_export:forest_land";
static final String MAPPED = "iris_export:mapped";
static final String OCEAN = "iris_export:ocean";
static final String DESERT = "iris_export:desert";
static final Map<String, String> EXPORTED = Map.of(FOREST, "Forest Land", MAPPED, "mapped", OCEAN, "ocean", DESERT, "desert");
static final int MIN_Y = -64;
static final int MAX_Y = 320;
static final String CENOTE = """
{"id": "pools", "family": "CENOTE", "worldYRange": {"min": -60, "max": 40}, "spacing": 64, "probability": 1.0,
"radius": 8, "height": 12, "fluid": "WATER", "fluidDepth": 2, "shapeWarp": 0.5, "pillarSpacing": 0,
"formationFraction": 0.0, "solid": "minecraft:stone"}
""";
static final String ROOM_CENOTE = """
{"id": "grottos", "family": "CENOTE", "biome": "room", "worldYRange": {"min": -60, "max": 40}, "spacing": 64,
"probability": 1.0, "radius": 8, "height": 12, "fluidDepth": 0, "shapeWarp": 0.0, "pillarSpacing": 0,
"formationFraction": 0.0, "solid": "minecraft:stone"}
""";
static final String TUBE = """
{"id": "tubes", "family": "LAVA_TUBE", "allowedRegions": ["second"], "worldYRange": {"min": -60, "max": 40},
"spacing": 320, "probability": 0.5, "length": 300, "radius": 6, "height": 8, "fluidDepth": 2, "chimneyHeight": 0,
"shapeWarp": 0.0, "pillarSpacing": 0, "formationFraction": 0.0, "solid": "minecraft:stone"}
""";
static final String SHALLOW = """
{"id": "shallow", "family": "CENOTE", "worldYRange": {"min": -60, "max": -50}, "spacing": 64, "probability": 1.0,
"radius": 8, "height": 12, "fluidDepth": 2, "solid": "minecraft:stone"}
""";
static final String DISABLED = """
{"id": "off", "enabled": false, "family": "CENOTE", "spacing": 64, "probability": 1.0, "radius": 8, "height": 12,
"solid": "minecraft:stone"}
""";
private static final Field ZERO = new Field.Const(0.0);
private SubterrainTestPacks() {
}
static File pack(File folder, String... features) throws IOException {
return packWith(folder, "", features);
}
static File packWith(File folder, String extra, String... features) throws IOException {
String dimension = "{\"regions\":[\"region\",\"second\"],\"subterrainFeatures\":[" + String.join(",", features) + "]"
+ (extra.isEmpty() ? "" : "," + extra) + "}";
File pack = ExportTestPacks.withDimension(folder, dimension);
CompatTestPlatform.write(pack, "regions/second.json", "{\"landBiomes\":[\"desert\"],\"seaBiomes\":[\"ocean\"]}");
CompatTestPlatform.write(pack, "biomes/desert.json", "{\"name\":\"Desert\"}");
CompatTestPlatform.write(pack, "biomes/room.json", """
{"name": "Room",
"layers": [{"palette": [{"block": "minecraft:grass_block"}], "minHeight": 1, "maxHeight": 1}],
"caveCeilingLayers": [{"palette": [{"block": "minecraft:grass_block"}], "minHeight": 1, "maxHeight": 1}],
"wall": {"palette": [{"block": "minecraft:grass_block"}]}}
""");
return pack;
}
static PackCompileContext context(IrisData data, DataVersion target) {
PackCompileContext context = ExportTestPacks.context(data, target);
new DimensionStage().apply(context);
context.setBiomeCodes(new BiomeCodes(ZERO, ZERO, ZERO, new ClimateLayout(List.of()), EXPORTED));
return context;
}
static SortedMap<String, JsonElement> json(PackCompileContext context) {
SortedMap<String, JsonElement> resources = new TreeMap<>();
for (JsonResource resource : context.jsonResources()) {
if (resources.put(resource.path(), resource.json()) != null) {
throw new AssertionError("Duplicate json resource " + resource.path());
}
}
return resources;
}
static SortedMap<String, byte[]> binaries(PackCompileContext context) {
SortedMap<String, byte[]> resources = new TreeMap<>();
for (BinaryResource resource : context.binaryResources()) {
if (resources.put(resource.path(), resource.bytes()) != null) {
throw new AssertionError("Duplicate binary resource " + resource.path());
}
}
return resources;
}
static List<ExportDiagnostic> diagnostics(List<ExportDiagnostic> diagnostics, ExportLimit limit) {
List<ExportDiagnostic> matching = new ArrayList<>();
for (ExportDiagnostic diagnostic : diagnostics) {
if (diagnostic.limit() == limit) {
matching.add(diagnostic);
}
}
return matching;
}
}
@@ -0,0 +1,390 @@
package art.arcane.iris.pack.datapack.export.compile.surface;
import art.arcane.iris.pack.datapack.DataVersion;
import art.arcane.iris.pack.datapack.export.ExportTestPacks;
import art.arcane.iris.pack.datapack.export.compile.BlockStateResolver;
import art.arcane.iris.pack.datapack.export.compile.PackCompileContext;
import art.arcane.iris.pack.datapack.export.compile.StageTestPacks;
import art.arcane.iris.pack.datapack.export.ir.ExportDiagnostic;
import art.arcane.iris.pack.datapack.export.ir.ExportLimit;
import art.arcane.iris.pack.datapack.export.ir.Field;
import art.arcane.iris.pack.datapack.export.ir.JsonResource;
import art.arcane.iris.pack.datapack.export.ir.MaterialProgram;
import art.arcane.iris.pack.datapack.export.ir.NoiseDef;
import art.arcane.iris.pack.loading.IrisData;
import art.arcane.iris.testsupport.PlatformLeakGuard;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import org.junit.ClassRule;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import java.io.File;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Consumer;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
public class MaterialProgramCompilerTest {
@ClassRule
public static final PlatformLeakGuard PLATFORM_GUARD = PlatformLeakGuard.clean();
private static final String DIMENSION = "{\"regions\":[\"region\"]}";
private static final String NO_BEDROCK = "{\"regions\":[\"region\"],\"bedrock\":false}";
private static final Field.Shared DEEP_OPENING = new Field.Shared("cave/deep_opening", new Field.Const(1.0));
private static final Field.Shared CAVE_FIELD = new Field.Shared("cave/field", new Field.Const(1.0));
private static final double WALL_BAND = 0.04;
@Rule
public TemporaryFolder temporaryFolder = new TemporaryFolder();
@Rule
public ExportTestPacks.BoundPlatform platform = new ExportTestPacks.BoundPlatform();
@Test
public void depthGuardPrecedesBiomeDispatch() throws Exception {
Map<String, String> biomes = new LinkedHashMap<>();
biomes.put("plains", layers("{\"palette\":[{\"block\":\"grass_block\"}],\"minHeight\":1,\"maxHeight\":1}",
"{\"palette\":[{\"block\":\"dirt\"}],\"minHeight\":3,\"maxHeight\":3}"));
biomes.put("desert", layers("{\"palette\":[{\"block\":\"sand\"}],\"minHeight\":4,\"maxHeight\":4}"));
MaterialProgram program = compile(DIMENSION, biomes, DataVersion.V26_3);
JsonObject rule = program.rule().getAsJsonObject();
List<JsonObject> guards = new ArrayList<>();
for (JsonElement entry : rule.getAsJsonArray("sequence")) {
JsonObject top = entry.getAsJsonObject();
assertFalse("a biome dispatch sits outside a depth guard", isBiomeCondition(top));
if (isFloorGuard(top)) {
guards.add(top);
}
}
assertEquals(1, guards.size());
JsonObject guard = guards.getFirst();
assertEquals(3, guard.getAsJsonObject("if_true").get("offset").getAsInt());
assertEquals(0, guard.getAsJsonObject("if_true").get("secondary_depth_range").getAsInt());
List<JsonObject> dispatch = StageTestPacks.ofType(guard.get("then_run"), "minecraft:biome");
assertEquals(2, dispatch.size());
assertEquals(StageTestPacks.ofType(rule, "minecraft:biome").size(), dispatch.size());
}
@Test
public void layerDepthBandsExact() throws Exception {
Map<String, String> biomes = new LinkedHashMap<>();
biomes.put("fixed", layers("{\"palette\":[{\"block\":\"grass_block\"}],\"minHeight\":1,\"maxHeight\":1}",
"{\"palette\":[{\"block\":\"dirt\"}],\"minHeight\":3,\"maxHeight\":3}",
"{\"palette\":[{\"block\":\"gravel\"}],\"minHeight\":2,\"maxHeight\":2}"));
biomes.put("varied", layers("{\"palette\":[{\"block\":\"sand\"}],\"minHeight\":1,\"maxHeight\":1}",
"{\"palette\":[{\"block\":\"sandstone\"}],\"minHeight\":1,\"maxHeight\":4}",
"{\"palette\":[{\"block\":\"clay\"}],\"minHeight\":0,\"maxHeight\":2}"));
PackCompileContext[] holder = new PackCompileContext[1];
MaterialProgram program = compile(DIMENSION, biomes, DataVersion.V26_3, holder);
JsonObject rule = program.rule().getAsJsonObject();
assertEquals(List.of(List.of(0, 0), List.of(3, 0), List.of(5, 0)), bands(rule, StageTestPacks.biomeId("fixed")));
assertEquals(List.of(List.of(0, 0), List.of(1, 3), List.of(1, 5)), bands(rule, StageTestPacks.biomeId("varied")));
assertTrue(hasDiagnostic(holder[0], ExportLimit.LAYER_THICKNESS, "biomes/varied"));
assertFalse(hasDiagnostic(holder[0], ExportLimit.LAYER_THICKNESS, "biomes/fixed"));
}
@Test
public void oreVeinRulesCappedAtEight() throws Exception {
List<String> walls = List.of("stone_bricks", "mossy_cobblestone", "tuff", "calcite", "deepslate", "andesite", "diorite",
"granite", "basalt", "blackstone");
Map<String, String> biomes = new LinkedHashMap<>();
for (int index = 0; index < walls.size(); index++) {
biomes.put("cave_" + index, "{\"layers\":[{\"palette\":[{\"block\":\"stone\"}]}],\"wall\":{\"palette\":[{\"block\":\""
+ walls.get(index) + "\"}]}}");
}
biomes.put("shared", "{\"layers\":[{\"palette\":[{\"block\":\"stone\"}]}],\"wall\":{\"palette\":[{\"block\":\"stone_bricks\"}]}}");
PackCompileContext[] holder = new PackCompileContext[1];
MaterialProgram modern = compile(NO_BEDROCK, biomes, DataVersion.V26_3, holder, context -> context.setCaveField(CAVE_FIELD, WALL_BAND));
List<JsonObject> veins = StageTestPacks.ofType(modern.rule(), "minecraft:ore_vein");
assertEquals(MaterialProgramCompiler.ORE_VEIN_BUDGET, veins.size());
for (JsonObject vein : veins) {
assertEquals("iris_export:" + MaterialProgramCompiler.WALL_SHELL, vein.get("density").getAsString());
}
List<JsonResource> shells = wallShells(holder[0]);
assertEquals(1, shells.size());
JsonObject shell = shells.getFirst().json().getAsJsonObject();
assertEquals("minecraft:range_choice", shell.get("type").getAsString());
assertEquals(1.0, shell.get("when_in_range").getAsDouble(), 0.0);
assertEquals(0.0, shell.get("when_out_of_range").getAsDouble(), 0.0);
assertEquals(0.0, shell.get("min_inclusive").getAsDouble(), 0.0);
assertEquals(WALL_BAND, shell.get("max_exclusive").getAsDouble(), 0.0);
assertEquals("iris_export:" + CAVE_FIELD.name(), shell.get("input").getAsString());
assertEquals(walls.size() - MaterialProgramCompiler.ORE_VEIN_BUDGET, count(holder[0], ExportLimit.WALL_PALETTE));
}
@Test
public void overLimitWallPalettesUseTheNearestKeptPalette() throws Exception {
Map<String, String> biomes = new LinkedHashMap<>();
biomes.put("quarry", wall("{\"block\":\"stone\"}"));
biomes.put("cliff", wall("{\"block\":\"stone\"}"));
for (String kept : List.of("gray_terracotta", "packed_ice", "deepslate", "tuff", "calcite", "andesite", "diorite")) {
biomes.put("kept_" + kept, wall("{\"block\":\"" + kept + "\"}"));
}
biomes.put("mesa", wall("{\"block\":\"orange_terracotta\"}"));
biomes.put("frozen", wall("{\"block\":\"blue_ice\"}"));
biomes.put("dark", wall("{\"block\":\"granite\",\"weight\":1},{\"block\":\"deepslate\",\"weight\":3}"));
biomes.put("glassy", wall("{\"block\":\"glass\"}"));
PackCompileContext[] holder = new PackCompileContext[1];
MaterialProgram program = compile(NO_BEDROCK, biomes, DataVersion.V26_3, holder, context -> context.setCaveField(CAVE_FIELD, WALL_BAND));
assertEquals(MaterialProgramCompiler.ORE_VEIN_BUDGET, StageTestPacks.ofType(program.rule(), "minecraft:ore_vein").size());
assertEquals("minecraft:gray_terracotta", wallFiller(program, "mesa"));
assertEquals("minecraft:packed_ice", wallFiller(program, "frozen"));
assertEquals("minecraft:deepslate", wallFiller(program, "dark"));
assertEquals("minecraft:stone", wallFiller(program, "glassy"));
assertEquals(4, count(holder[0], ExportLimit.WALL_PALETTE));
for (ExportDiagnostic diagnostic : holder[0].diagnostics()) {
if (diagnostic.limit() == ExportLimit.WALL_PALETTE) {
String fallback = wallFiller(program, diagnostic.resource().substring("biomes/".length()));
assertTrue(diagnostic.message(), diagnostic.message().contains(fallback));
}
}
}
@Test
public void wallPalettesNeedCaves() throws Exception {
Map<String, String> biomes = new LinkedHashMap<>();
biomes.put("cave", "{\"layers\":[{\"palette\":[{\"block\":\"stone\"}]}],\"wall\":{\"palette\":[{\"block\":\"tuff\"}]}}");
PackCompileContext[] holder = new PackCompileContext[1];
MaterialProgram program = compile(NO_BEDROCK, biomes, DataVersion.V26_3, holder);
assertTrue(StageTestPacks.ofType(program.rule(), "minecraft:ore_vein").isEmpty());
assertTrue(wallShells(holder[0]).isEmpty());
assertEquals(0, count(holder[0], ExportLimit.WALL_PALETTE));
}
@Test
public void blockRuleUsesIdAndProperties() throws Exception {
Map<String, String> biomes = new LinkedHashMap<>();
biomes.put("logs", layers("{\"palette\":[{\"block\":\"oak_log\",\"data\":{\"axis\":\"x\"}}],\"minHeight\":1,\"maxHeight\":1}"));
MaterialProgram program = compile(NO_BEDROCK, biomes, DataVersion.V26_3);
JsonObject modern = StageTestPacks.ofType(program.rule(), "minecraft:block").getFirst();
assertEquals("{\"type\":\"minecraft:block\",\"result_state\":{\"id\":\"minecraft:oak_log\",\"properties\":{\"axis\":\"x\"}}}", modern.toString());
}
@Test
public void staticPaletteUsesGradientPairsAndSmoothPaletteUsesRegisteredNoise() throws Exception {
Map<String, String> biomes = new LinkedHashMap<>();
biomes.put("speckled", layers("{\"palette\":[{\"block\":\"stone\",\"weight\":3},{\"block\":\"andesite\"}],\"minHeight\":1,\"maxHeight\":1}",
"{\"palette\":[{\"block\":\"dirt\"},{\"block\":\"coarse_dirt\"}],\"style\":{\"style\":\"SIMPLEX\"},\"zoom\":8,\"minHeight\":1,\"maxHeight\":1}"));
PackCompileContext[] holder = new PackCompileContext[1];
MaterialProgram program = compile(NO_BEDROCK, biomes, DataVersion.V26_3, holder);
List<JsonObject> gradients = StageTestPacks.ofType(program.rule(), "minecraft:vertical_gradient");
assertEquals(2, gradients.size());
int seaLevel = holder[0].dimensionDef().fluidHeight();
assertEquals(0.25, ramp(gradients.get(0), seaLevel) * (1.0 - ramp(gradients.get(1), seaLevel)), 1.0e-3);
List<JsonObject> thresholds = StageTestPacks.ofType(program.rule(), "minecraft:noise_threshold");
assertEquals(1, thresholds.size());
String noise = thresholds.getFirst().get("noise").getAsString();
assertEquals("iris_export:surface/palette_3_1", noise);
NoiseDef registered = holder[0].noises().definitions().getFirst();
assertEquals("surface/palette_3_1", registered.id());
assertEquals(-3, registered.firstOctave());
assertTrue(thresholds.getFirst().get("is_3d").getAsBoolean());
}
@Test
public void gradientChanceHoldsProbabilityAcrossSurfaceBand() {
for (double probability : List.of(0.5, 0.3, 0.1, 0.01, 0.001)) {
List<JsonObject> conditions = SurfacePalettes.gradientChance(probability, "iris_export:test/", 63);
for (int y = 63 - 192; y <= 63 + 192; y += 32) {
double product = 1.0;
for (int index = 0; index < conditions.size(); index += 2) {
product *= ramp(conditions.get(index), y) * (1.0 - ramp(conditions.get(index + 1).getAsJsonObject("invert"), y));
}
assertEquals("p=" + probability + " y=" + y, probability, product, probability * 0.06);
}
}
}
@Test
public void bedrockAndOreBandsUseExactAnchors() throws Exception {
String dimension = "{\"regions\":[\"region\"],\"ores\":[{\"palette\":{\"palette\":[{\"block\":\"deepslate\"}]},\"threshold\":1,\"range\":{\"min\":1,\"max\":57}}]}";
Map<String, String> biomes = new LinkedHashMap<>();
biomes.put("plains", layers("{\"palette\":[{\"block\":\"grass_block\"}],\"minHeight\":1,\"maxHeight\":1}"));
PackCompileContext[] holder = new PackCompileContext[1];
MaterialProgram program = compile(dimension, biomes, DataVersion.V26_3, holder);
int minY = holder[0].dimensionDef().minY();
JsonObject sequence = program.rule().getAsJsonObject();
JsonObject bedrock = sequence.getAsJsonArray("sequence").get(0).getAsJsonObject();
JsonObject floor = bedrock.getAsJsonObject("if_true");
assertEquals(minY, floor.getAsJsonObject("true_at_and_below").get("absolute").getAsInt());
assertEquals(minY + 1, floor.getAsJsonObject("false_at_and_above").get("absolute").getAsInt());
List<JsonObject> anchors = StageTestPacks.ofType(program.rule(), "minecraft:y_above");
assertEquals(List.of(minY + 1, minY + 58), List.of(anchors.get(0).getAsJsonObject("anchor").get("absolute").getAsInt(),
anchors.get(1).getAsJsonObject("anchor").get("absolute").getAsInt()));
JsonElement last = sequence.getAsJsonArray("sequence").get(sequence.getAsJsonArray("sequence").size() - 1);
assertFalse(StageTestPacks.ofType(last, "minecraft:y_above").isEmpty());
}
@Test
public void compilationIsDeterministic() throws Exception {
Map<String, String> biomes = new LinkedHashMap<>();
biomes.put("plains", layers("{\"palette\":[{\"block\":\"grass_block\"},{\"block\":\"moss_block\"}],\"minHeight\":1,\"maxHeight\":2}",
"{\"palette\":[{\"block\":\"dirt\"},{\"block\":\"gravel\"}],\"style\":{\"style\":\"PERLIN\"},\"minHeight\":2,\"maxHeight\":3}"));
biomes.put("cave", "{\"layers\":[{\"palette\":[{\"block\":\"stone\"}]}],\"caveCeilingLayers\":[{\"palette\":[{\"block\":\"tuff\"}]}],"
+ "\"wall\":{\"palette\":[{\"block\":\"tuff\",\"weight\":2},{\"block\":\"calcite\"},{\"block\":\"diorite\"},{\"block\":\"granite\"}]}}");
MaterialProgram first = compile(DIMENSION, biomes, DataVersion.V26_3, new PackCompileContext[1], context -> context.setCaveField(CAVE_FIELD, WALL_BAND));
MaterialProgram second = compile(DIMENSION, biomes, DataVersion.V26_3, new PackCompileContext[1], context -> context.setCaveField(CAVE_FIELD, WALL_BAND));
assertEquals(first.rule().toString(), second.rule().toString());
assertEquals(1, StageTestPacks.ofType(first.rule(), "minecraft:ore_vein").size());
JsonObject vein = StageTestPacks.ofType(first.rule(), "minecraft:ore_vein").getFirst();
assertEquals("minecraft:tuff", vein.getAsJsonObject("filler_block").get("id").getAsString());
assertEquals(0.5f, vein.get("richness").getAsFloat(), 1.0e-6f);
assertEquals(0.5f, vein.get("raw_ore_chance").getAsFloat(), 1.0e-6f);
}
@Test
public void deepCaveOpeningLeadsTheRule() throws Exception {
Map<String, String> biomes = new LinkedHashMap<>();
biomes.put("plains", layers("{\"palette\":[{\"block\":\"grass_block\"}],\"minHeight\":1,\"maxHeight\":1}"));
MaterialProgram program = compile(DIMENSION, biomes, DataVersion.V26_3, new PackCompileContext[1], context -> context.setDeepCaves(DEEP_OPENING));
JsonObject head = program.rule().getAsJsonObject().getAsJsonArray("sequence").get(0).getAsJsonObject();
assertEquals("minecraft:ore_vein", head.get("type").getAsString());
assertEquals("iris_export:" + DEEP_OPENING.name(), head.get("density").getAsString());
for (String slot : List.of("ore_block", "raw_ore_block", "filler_block")) {
assertEquals("minecraft:air", head.getAsJsonObject(slot).get("id").getAsString());
}
assertEquals(0.0, head.get("richness").getAsDouble(), 0.0);
assertEquals(1, StageTestPacks.ofType(program.rule(), "minecraft:ore_vein").size());
}
@Test
public void deepCaveRuleCountsTowardTheOreVeinBudget() throws Exception {
Map<String, String> biomes = new LinkedHashMap<>();
for (String wall : List.of("stone_bricks", "mossy_cobblestone", "tuff", "calcite", "deepslate", "andesite", "diorite", "granite", "basalt")) {
biomes.put("cave_" + wall, "{\"layers\":[{\"palette\":[{\"block\":\"stone\"}]}],\"wall\":{\"palette\":[{\"block\":\"" + wall + "\"}]}}");
}
PackCompileContext[] holder = new PackCompileContext[1];
MaterialProgram program = compile(NO_BEDROCK, biomes, DataVersion.V26_3, holder, context -> {
context.setCaveField(CAVE_FIELD, WALL_BAND);
context.setDeepCaves(DEEP_OPENING);
});
assertEquals(MaterialProgramCompiler.ORE_VEIN_BUDGET, StageTestPacks.ofType(program.rule(), "minecraft:ore_vein").size());
assertEquals(biomes.size() - MaterialProgramCompiler.ORE_VEIN_BUDGET + 1, count(holder[0], ExportLimit.WALL_PALETTE));
}
private MaterialProgram compile(String dimension, Map<String, String> biomes, DataVersion target) throws Exception {
return compile(dimension, biomes, target, new PackCompileContext[1]);
}
private MaterialProgram compile(String dimension, Map<String, String> biomes, DataVersion target, PackCompileContext[] holder) throws Exception {
return compile(dimension, biomes, target, holder, context -> {
});
}
private MaterialProgram compile(String dimension, Map<String, String> biomes, DataVersion target, PackCompileContext[] holder,
Consumer<PackCompileContext> setup) throws Exception {
File pack = StageTestPacks.pack(temporaryFolder.newFolder(), dimension, biomes);
IrisData data = IrisData.openRuntime(pack);
try {
PackCompileContext context = StageTestPacks.context(data, target, new ArrayList<>(biomes.keySet()));
setup.accept(context);
holder[0] = context;
return new MaterialProgramCompiler(context, BlockStateResolver.forContext(context)).compile();
} finally {
data.close();
}
}
private static List<JsonResource> wallShells(PackCompileContext context) {
String path = "data/iris_export/worldgen/density_function/" + MaterialProgramCompiler.WALL_SHELL + ".json";
return context.jsonResources().stream().filter(resource -> resource.path().equals(path)).toList();
}
private static String layers(String... layers) {
return "{\"layers\":[" + String.join(",", layers) + "]}";
}
private static boolean isBiomeCondition(JsonObject rule) {
return "minecraft:condition".equals(rule.get("type").getAsString())
&& "minecraft:biome".equals(rule.getAsJsonObject("if_true").get("type").getAsString());
}
private static boolean isFloorGuard(JsonObject rule) {
if (!"minecraft:condition".equals(rule.get("type").getAsString())) {
return false;
}
JsonObject condition = rule.getAsJsonObject("if_true");
return "minecraft:stone_depth".equals(condition.get("type").getAsString()) && "floor".equals(condition.get("surface_type").getAsString());
}
private static List<List<Integer>> bands(JsonObject rule, String biomeId) {
JsonObject branch = StageTestPacks.ofType(rule, "minecraft:condition").stream()
.filter(object -> "minecraft:biome".equals(object.getAsJsonObject("if_true").get("type").getAsString())
&& object.getAsJsonObject("if_true").getAsJsonArray("biome_is").size() == 1
&& biomeId.equals(object.getAsJsonObject("if_true").getAsJsonArray("biome_is").get(0).getAsString())).findFirst().orElseThrow();
List<List<Integer>> bands = new ArrayList<>();
for (JsonObject depth : StageTestPacks.ofType(branch.get("then_run"), "minecraft:stone_depth")) {
bands.add(List.of(depth.get("offset").getAsInt(), depth.get("secondary_depth_range").getAsInt()));
}
return bands;
}
private static double ramp(JsonObject gradient, int y) {
int trueAt = gradient.getAsJsonObject("true_at_and_below").get("absolute").getAsInt();
int falseAt = gradient.getAsJsonObject("false_at_and_above").get("absolute").getAsInt();
if (y <= trueAt) {
return 1.0;
}
if (y >= falseAt) {
return 0.0;
}
return (double) (falseAt - y) / (falseAt - trueAt);
}
private static String wall(String palette) {
return "{\"layers\":[{\"palette\":[{\"block\":\"stone\"}]}],\"wall\":{\"palette\":[" + palette + "]}}";
}
private static String wallFiller(MaterialProgram program, String biome) {
String biomeId = StageTestPacks.biomeId(biome);
for (JsonObject condition : StageTestPacks.ofType(program.rule(), "minecraft:condition")) {
JsonObject test = condition.getAsJsonObject("if_true");
JsonObject rule = condition.getAsJsonObject("then_run");
if (!"minecraft:biome".equals(test.get("type").getAsString()) || !"minecraft:ore_vein".equals(rule.get("type").getAsString())) {
continue;
}
for (JsonElement member : test.getAsJsonArray("biome_is")) {
if (member.getAsString().equals(biomeId)) {
return rule.getAsJsonObject("filler_block").get("id").getAsString();
}
}
}
throw new AssertionError("Biome " + biome + " has no wall rule");
}
private static boolean hasDiagnostic(PackCompileContext context, ExportLimit limit, String resource) {
for (ExportDiagnostic diagnostic : context.diagnostics()) {
if (diagnostic.limit() == limit && diagnostic.resource().equals(resource)) {
return true;
}
}
return false;
}
private static int count(PackCompileContext context, ExportLimit limit) {
int count = 0;
for (ExportDiagnostic diagnostic : context.diagnostics()) {
if (diagnostic.limit() == limit) {
count++;
}
}
return count;
}
}
@@ -0,0 +1,156 @@
package art.arcane.iris.pack.datapack.export.compile.terrain;
import art.arcane.iris.generation.noise.IrisInterpolator;
import art.arcane.iris.pack.datapack.DataVersion;
import art.arcane.iris.pack.datapack.export.compile.biome.BiomeCodes;
import art.arcane.iris.pack.datapack.export.compile.noise.NoiseRegistry;
import art.arcane.iris.pack.datapack.export.ir.Axis;
import art.arcane.iris.pack.datapack.export.ir.Field;
import art.arcane.volmlib.util.interpolation.InterpolationMethod;
import org.junit.Test;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeSet;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertThrows;
import static org.junit.Assert.assertTrue;
public class BandTreeCompilerTest {
private static final Map<String, Double> VALUES = Map.of(TerrainTestSupport.NAMESPACE + ":a", 10.0, TerrainTestSupport.NAMESPACE + ":b", 80.0);
@Test
public void hardBandFollowsTheLayoutCodes() {
NoiseRegistry registry = new NoiseRegistry(TerrainTestSupport.NAMESPACE);
BiomeCodes codes = TerrainTestSupport.twoBiomeCodes(registry, 0.0);
BandTreeCompiler bands = new BandTreeCompiler(codes, "test");
Field hard = bands.hard(VALUES);
for (int x = -2000; x <= 2000; x += 97) {
double code = TerrainTestSupport.sample(codes.surfaceCode(), registry, DataVersion.V26_3, x, 0, 31);
double expected = code < 0.2 ? 10.0 : 80.0;
assertEquals(expected, TerrainTestSupport.sample(hard, registry, DataVersion.V26_3, x, 0, 31), 0.0);
}
}
@Test
public void blendMatchesTheLeavesAwayFromTheThreshold() {
NoiseRegistry registry = new NoiseRegistry(TerrainTestSupport.NAMESPACE);
BiomeCodes codes = TerrainTestSupport.twoBiomeCodes(registry, 0.0);
BandTreeCompiler bands = new BandTreeCompiler(codes, "test");
Field blend = bands.band(VALUES, interpolator(InterpolationMethod.BILINEAR_STARCAST_9, 12.0));
Field hard = bands.hard(VALUES);
int blended = 0;
for (int x = -3000; x <= 3000; x += 13) {
double value = TerrainTestSupport.sample(blend, registry, DataVersion.V26_3, x, 0, 7);
double exact = TerrainTestSupport.sample(hard, registry, DataVersion.V26_3, x, 0, 7);
assertTrue(value >= 10.0 - 1.0e-3 && value <= 80.0 + 1.0e-3);
if (Math.abs(value - exact) > 1.0e-3) {
blended++;
}
}
assertTrue("blend should soften some columns, got " + blended, blended > 0);
assertTrue("blend should leave most columns at their leaf value, got " + blended, blended < 300);
assertFalse(blend.axes().contains(Axis.Y));
}
@Test
public void starcastBlendsAverageThreeLadderLattices() {
assertEquals(List.of(23, 32, 45), BandTreeCompiler.lattices(interpolator(InterpolationMethod.BILINEAR_STARCAST_9, 12.0)));
assertEquals(List.of(362, 512, 724), BandTreeCompiler.lattices(interpolator(InterpolationMethod.BILINEAR_STARCAST_12, 200.0)));
assertEquals(List.of(64, 91, 128), BandTreeCompiler.lattices(interpolator(InterpolationMethod.STARCAST_12, 42.0)));
assertEquals(List.of(30), BandTreeCompiler.lattices(interpolator(InterpolationMethod.BILINEAR, 30.0)));
assertEquals(List.of(), BandTreeCompiler.lattices(interpolator(InterpolationMethod.NONE, 30.0)));
}
@Test
public void blendSamplesTheSelectorWithoutOffsetCopies() {
NoiseRegistry registry = new NoiseRegistry(TerrainTestSupport.NAMESPACE);
BiomeCodes codes = TerrainTestSupport.twoBiomeCodes(registry, 0.0);
BandTreeCompiler bands = new BandTreeCompiler(codes, "test");
Map<String, Double> other = Map.of(TerrainTestSupport.NAMESPACE + ":a", 3.0, TerrainTestSupport.NAMESPACE + ":b", 40.0);
Field first = bands.band(VALUES, interpolator(InterpolationMethod.BILINEAR_STARCAST_12, 200.0));
Field second = bands.band(other, interpolator(InterpolationMethod.BILINEAR_STARCAST_9, 26.0));
Set<Field> noises = new HashSet<>(nodes(first, Field.Noise.class));
noises.addAll(nodes(second, Field.Noise.class));
assertEquals(new HashSet<>(nodes(codes.surfaceCode(), Field.Noise.class)), noises);
Set<String> lattices = new TreeSet<>();
for (Field shared : nodes(new Field.Binary(Field.BinaryOp.ADD, first, second), Field.Shared.class)) {
String name = ((Field.Shared) shared).name();
if (name.startsWith("terrain/test/blend/lattice/")) {
lattices.add(name);
}
}
assertEquals(Set.of("terrain/test/blend/lattice/362", "terrain/test/blend/lattice/512", "terrain/test/blend/lattice/724",
"terrain/test/blend/lattice/45", "terrain/test/blend/lattice/64", "terrain/test/blend/lattice/91"), lattices);
}
@Test
public void noneInterpolationIsTheHardBand() {
NoiseRegistry registry = new NoiseRegistry(TerrainTestSupport.NAMESPACE);
BandTreeCompiler bands = new BandTreeCompiler(TerrainTestSupport.twoBiomeCodes(registry, 0.0), "test");
assertEquals(bands.hard(VALUES), bands.band(VALUES, interpolator(InterpolationMethod.NONE, 30.0)));
}
@Test
public void equalValuesCollapseToAConstant() {
NoiseRegistry registry = new NoiseRegistry(TerrainTestSupport.NAMESPACE);
BandTreeCompiler bands = new BandTreeCompiler(TerrainTestSupport.twoBiomeCodes(registry, 0.0), "test");
Map<String, Double> flat = Map.of(TerrainTestSupport.NAMESPACE + ":a", 5.0, TerrainTestSupport.NAMESPACE + ":b", 5.0);
assertEquals(new Field.Const(5.0), bands.band(flat, interpolator(InterpolationMethod.BILINEAR_STARCAST_9, 12.0)));
}
@Test
public void baseCodeSubtreeDrivesTheBands() {
NoiseRegistry registry = new NoiseRegistry(TerrainTestSupport.NAMESPACE);
BiomeCodes plain = TerrainTestSupport.twoBiomeCodes(registry, 0.0);
Field base = new Field.Shared(BiomeCodes.BASE_CODE, plain.surfaceCode());
Field relabelled = new Field.RangeIf(base, 0.25, 0.35, base, new Field.Const(0.1));
BiomeCodes codes = new BiomeCodes(relabelled, plain.caveCode(), plain.class3d(), plain.layout(), plain.loadKeyByBiomeId());
Field selector = BandTreeCompiler.selector(codes);
assertEquals(base, selector);
}
@Test
public void heightDependentCodeWithoutBaseCodeIsRejected() {
NoiseRegistry registry = new NoiseRegistry(TerrainTestSupport.NAMESPACE);
BiomeCodes plain = TerrainTestSupport.twoBiomeCodes(registry, 0.0);
Field height = new Field.Shared(HeightCompiler.HEIGHT, new Field.Const(63.0));
Field relabelled = new Field.RangeIf(height, 60.0, 70.0, new Field.Const(0.3), plain.surfaceCode());
BiomeCodes codes = new BiomeCodes(relabelled, plain.caveCode(), plain.class3d(), plain.layout(), plain.loadKeyByBiomeId());
IllegalStateException failure = assertThrows(IllegalStateException.class, () -> BandTreeCompiler.selector(codes));
assertTrue(failure.getMessage(), failure.getMessage().contains(BiomeCodes.BASE_CODE));
}
private static IrisInterpolator interpolator(InterpolationMethod method, double radius) {
IrisInterpolator interpolator = new IrisInterpolator();
interpolator.setFunction(method);
interpolator.setHorizontalScale(radius);
return interpolator;
}
private static List<Field> nodes(Field root, Class<? extends Field> type) {
List<Field> found = new ArrayList<>();
for (Field field : TerrainTestSupport.nodes(root)) {
if (type.isInstance(field)) {
found.add(field);
}
}
return found;
}
}
@@ -0,0 +1,185 @@
package art.arcane.iris.pack.datapack.export.compile.terrain;
import art.arcane.iris.generation.terrain.IrisDimension;
import art.arcane.iris.pack.datapack.DataVersion;
import art.arcane.iris.pack.datapack.export.ExportTestPacks;
import art.arcane.iris.pack.datapack.export.GenerationCost;
import art.arcane.iris.pack.datapack.export.compile.biome.BiomeCodes;
import art.arcane.iris.pack.datapack.export.compile.noise.NoiseRegistry;
import art.arcane.iris.pack.datapack.export.compile.noise.StyleCompiler;
import art.arcane.iris.pack.datapack.export.ir.AquiferDef;
import art.arcane.iris.pack.datapack.export.ir.Field;
import art.arcane.iris.pack.datapack.export.ir.FieldValidator;
import art.arcane.iris.pack.datapack.export.ir.NoiseDef;
import art.arcane.iris.pack.datapack.export.ir.RouterDef;
import art.arcane.iris.pack.datapack.export.lower.ExportCapabilities;
import art.arcane.iris.pack.datapack.export.lower.GenerationCostCounter;
import art.arcane.iris.pack.datapack.export.lower.VanillaBounds;
import art.arcane.iris.pack.loading.IrisData;
import art.arcane.iris.testsupport.PlatformLeakGuard;
import org.junit.ClassRule;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import java.io.File;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Deque;
import java.util.IdentityHashMap;
import java.util.List;
import java.util.Set;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
public class ClimateHeightCompilerTest {
private static final ExportCapabilities CAPABILITIES = ExportCapabilities.forTarget(DataVersion.V26_3);
private static final int SEA_LEVEL = 63;
@ClassRule
public static final PlatformLeakGuard PLATFORM_GUARD = PlatformLeakGuard.clean();
@Rule
public TemporaryFolder temporaryFolder = new TemporaryFolder();
@Rule
public ExportTestPacks.BoundPlatform platform = new ExportTestPacks.BoundPlatform();
@Test
public void climateHeightIsTheUnblendedTerrainHeight() throws Exception {
IrisData data = IrisData.openRuntime(pack());
try {
NoiseRegistry registry = new NoiseRegistry(TerrainTestSupport.NAMESPACE);
BiomeCodes codes = TerrainTestSupport.twoBiomeCodes(registry, 0.0);
IrisDimension dimension = data.getDimensionLoader().load(TerrainTestPacks.DIMENSION, false);
Field generator = new GeneratorCompiler(TerrainTestSupport.noiseStyles(), registry, CAPABILITIES, new ArrayList<>())
.compile(data.getGeneratorLoader().load("hills", false), "height");
Field selector = new Field.Noise(registry.namespace() + ":" + TerrainTestSupport.SELECTOR_ID, 1.0, 0.0, null, null, null);
Field climate = new ClimateHeightCompiler(TerrainTestSupport.noiseStyles()).compile(codes, dimension, data, registry, CAPABILITIES);
assertEquals(ClimateHeightCompiler.CLIMATE_HEIGHT, ((Field.Shared) climate).name());
FieldValidator.requireTwoDimensional(climate, "climate height");
assertFalse(contains(climate, Field.Grid.class));
for (int x = -2000; x <= 2000; x += 97) {
for (int z = -2000; z <= 2000; z += 89) {
double mean = TerrainTestSupport.sample(generator, registry, DataVersion.V26_3, x, 0, z);
boolean low = TerrainTestSupport.sample(selector, registry, DataVersion.V26_3, x, 0, z) < 0.0;
double expected = SEA_LEVEL + (low ? 20.0 * mean : 60.0 + 40.0 * mean);
double actual = TerrainTestSupport.sample(climate, registry, DataVersion.V26_3, x, 0, z);
assertEquals(x + "," + z, expected, actual, 1.0e-3);
}
}
} finally {
data.close();
}
}
@Test
public void climateHeightCostsAFractionOfTheTerrainHeightUncached() throws Exception {
IrisData data = IrisData.openRuntime(pack());
try {
NoiseRegistry registry = new NoiseRegistry(TerrainTestSupport.NAMESPACE);
BiomeCodes codes = TerrainTestSupport.twoBiomeCodes(registry, 0.0);
IrisDimension dimension = data.getDimensionLoader().load(TerrainTestPacks.DIMENSION, false);
Field terrain = new HeightCompiler(TerrainTestSupport.noiseStyles(), new ArrayList<>()).compile(codes, dimension, data, registry, CAPABILITIES).height();
Field climate = new ClimateHeightCompiler(TerrainTestSupport.noiseStyles()).compile(codes, dimension, data, registry, CAPABILITIES);
double terrainCost = worstCase(terrain, registry);
double climateCost = worstCase(climate, registry);
assertTrue(climateCost + " vs " + terrainCost, climateCost * 10.0 < terrainCost);
assertTrue(String.valueOf(climateCost), climateCost <= 30.0);
} finally {
data.close();
}
}
@Test
public void expensiveGeneratorsEnterAsTheirCalibratedMean() throws Exception {
IrisData data = IrisData.openRuntime(pack());
try {
NoiseRegistry registry = new NoiseRegistry(TerrainTestSupport.NAMESPACE);
BiomeCodes codes = TerrainTestSupport.twoBiomeCodes(registry, 0.0);
IrisDimension dimension = data.getDimensionLoader().load(TerrainTestPacks.DIMENSION, false);
StyleCompiler expensive = (style, seedSalt, styleRegistry, capabilities) -> {
String id = styleRegistry.register(new NoiseDef("test/expensive", -5, List.of(1.0)));
Field value = new Field.Binary(Field.BinaryOp.ADD, new Field.Const(0.5), new Field.Binary(Field.BinaryOp.MUL, new Field.Const(0.5),
new Field.Noise(id, 1.0 / style.getZoom(), 0.0, null, null, null)));
for (int level = 0; level < 12; level++) {
value = new Field.Shared("test/expensive/" + level, new Field.Binary(Field.BinaryOp.MIN, value, value));
}
return value;
};
Field climate = new ClimateHeightCompiler(expensive).compile(codes, dimension, data, registry, CAPABILITIES);
assertTrue(String.valueOf(worstCase(climate, registry)), worstCase(climate, registry) <= 20.0);
Field selector = new Field.Noise(registry.namespace() + ":" + TerrainTestSupport.SELECTOR_ID, 1.0, 0.0, null, null, null);
for (int x = -2000; x <= 2000; x += 211) {
double value = TerrainTestSupport.sample(climate, registry, DataVersion.V26_3, x, 0, 37);
boolean low = TerrainTestSupport.sample(selector, registry, DataVersion.V26_3, x, 0, 37) < 0.0;
assertTrue(x + " " + value, low ? value > SEA_LEVEL && value < SEA_LEVEL + 20.0 : value > SEA_LEVEL + 60.0 && value < SEA_LEVEL + 100.0);
}
} finally {
data.close();
}
}
@Test
public void flatBiomesGiveAConstantLeafSelection() throws Exception {
File pack = TerrainTestPacks.twoBiomes(temporaryFolder.newFolder("pack"),
TerrainTestPacks.link("hills", 10, 10), TerrainTestPacks.link("hills", 50, 50));
TerrainTestPacks.generator(pack, "hills", TerrainTestPacks.twoLayers("BILINEAR_STARCAST_9", 12));
IrisData data = IrisData.openRuntime(pack);
try {
NoiseRegistry registry = new NoiseRegistry(TerrainTestSupport.NAMESPACE);
BiomeCodes codes = TerrainTestSupport.twoBiomeCodes(registry, 0.0);
IrisDimension dimension = data.getDimensionLoader().load(TerrainTestPacks.DIMENSION, false);
Field climate = new ClimateHeightCompiler(TerrainTestSupport.noiseStyles()).compile(codes, dimension, data, registry, CAPABILITIES);
assertFalse(contains(climate, Field.Mux.class));
assertTrue(contains(climate, Field.Partition.class));
assertEquals(1, registry.definitions().size());
} finally {
data.close();
}
}
private File pack() throws Exception {
File pack = TerrainTestPacks.twoBiomes(temporaryFolder.newFolder("pack"),
TerrainTestPacks.link("hills", 0, 20), TerrainTestPacks.link("hills", 60, 100));
TerrainTestPacks.generator(pack, "hills", TerrainTestPacks.singleLayer("BILINEAR_STARCAST_9", 12, "SIMPLEX"));
return pack;
}
private static double worstCase(Field field, NoiseRegistry registry) {
Field zero = new Field.Const(0.0);
RouterDef router = new RouterDef(field, zero, zero, zero, zero, zero, zero, zero, AquiferDef.dry(zero));
return GenerationCostCounter.count(router, VanillaBounds.of(registry.namespace(), registry.definitions()), DataVersion.V26_3)
.root(GenerationCost.Root.TEMPERATURE).orElseThrow().worstCaseNodes();
}
private static boolean contains(Field root, Class<? extends Field> type) {
Set<Field> visited = Collections.newSetFromMap(new IdentityHashMap<>());
Deque<Field> pending = new ArrayDeque<>();
pending.push(root);
while (!pending.isEmpty()) {
Field field = pending.pop();
if (!visited.add(field)) {
continue;
}
if (type.isInstance(field)) {
return true;
}
for (Field child : FieldMacros.children(field)) {
pending.push(child);
}
}
return false;
}
}
@@ -0,0 +1,163 @@
package art.arcane.iris.pack.datapack.export.compile.terrain;
import art.arcane.iris.pack.datapack.DataVersion;
import art.arcane.iris.pack.datapack.export.compile.noise.NoiseRegistry;
import art.arcane.iris.pack.datapack.export.ir.Axis;
import art.arcane.iris.pack.datapack.export.ir.Field;
import art.arcane.iris.pack.datapack.export.ir.NoiseDef;
import org.junit.Test;
import java.util.List;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertThrows;
import static org.junit.Assert.assertTrue;
public class FieldMacrosTest {
private static final double EPSILON = 1.0e-5;
private static final Field X = new Field.Coord(Axis.X, Field.Tiling.CLAMP, -4096, 4096, -40.96, 40.96);
private static final Field Y = new Field.Coord(Axis.Y, Field.Tiling.CLAMP, -64, 320, -64, 320);
@Test
public void offsetEvaluatesTheExpressionAtTheShiftedPosition() {
NoiseRegistry registry = new NoiseRegistry(TerrainTestSupport.NAMESPACE);
String id = registry.register(new NoiseDef("macro/base", -4, List.of(1.0, 0.5)));
String warpId = registry.register(new NoiseDef("macro/warp", -6, List.of(1.0)));
Field warp = new Field.Noise(warpId, 0.5, 0.0, null, null, null);
Field noise = new Field.Noise(id, 0.75, 0.0, new Field.Binary(Field.BinaryOp.MUL, new Field.Const(8.0), warp), null, null);
Field expr = new Field.Binary(Field.BinaryOp.ADD, noise, X);
Field shifted = FieldMacros.offset(expr, 7.0, -3.0);
for (int x = -40; x <= 40; x += 9) {
for (int z = -30; z <= 30; z += 11) {
assertEquals(TerrainTestSupport.sample(expr, registry, DataVersion.V26_3, x + 7, 0, z - 3),
TerrainTestSupport.sample(shifted, registry, DataVersion.V26_3, x, 0, z), EPSILON);
}
}
}
@Test
public void offsetRenamesChangedSharedSubtreesOnly() {
NoiseRegistry registry = new NoiseRegistry(TerrainTestSupport.NAMESPACE);
String id = registry.register(new NoiseDef("macro/base", -4, List.of(1.0)));
Field vertical = new Field.Shared("vertical", Y);
Field horizontal = new Field.Shared("horizontal", new Field.Noise(id, 1.0, 0.0, null, null, null));
Field shifted = FieldMacros.offset(new Field.Binary(Field.BinaryOp.ADD, vertical, horizontal), 4.0, 0.0);
Field.Binary sum = (Field.Binary) shifted;
assertSame(vertical, sum.left());
assertEquals("horizontal/offset_x4_z0", ((Field.Shared) sum.right()).name());
}
@Test
public void offsetOfReferenceFails() {
assertThrows(IllegalArgumentException.class, () -> FieldMacros.offset(new Field.Ref("minecraft:overworld/continents"), 1.0, 0.0));
}
@Test
public void signedDistanceOfALinearRampIsTheBlockDistance() {
NoiseRegistry registry = new NoiseRegistry(TerrainTestSupport.NAMESPACE);
DataVersion target = DataVersion.V26_3;
Field distance = FieldMacros.signedDistance(X, 0.5, 4.0);
assertEquals(-20.0, TerrainTestSupport.sample(distance, registry, target, 30, 0, 0), 0.01);
assertEquals(15.0, TerrainTestSupport.sample(distance, registry, target, 65, 0, 9), 0.01);
}
@Test
public void substituteSwapsTheTargetAndRenamesChangedSharedSubtrees() {
Field target = new Field.Shared("target", X);
Field replacement = new Field.Const(5.0);
Field untouched = new Field.Shared("untouched", new Field.Unary(Field.UnaryOp.ABS, X));
Field root = new Field.Binary(Field.BinaryOp.ADD, new Field.Shared("wrapper", new Field.Binary(Field.BinaryOp.MUL, target, target)), untouched);
Field.Binary result = (Field.Binary) FieldMacros.substitute(root, target, replacement, "swap");
assertEquals(new Field.Shared("wrapper/swap", new Field.Binary(Field.BinaryOp.MUL, replacement, replacement)), result.left());
assertTrue(result.right() == untouched);
assertTrue(FieldMacros.substitute(root, target, target, "swap") == root);
}
@Test
public void productGuardsAnExpensivePayloadBehindTheMask() {
NoiseRegistry registry = new NoiseRegistry(TerrainTestSupport.NAMESPACE);
String first = registry.register(new NoiseDef("macro/first", -4, List.of(1.0)));
String second = registry.register(new NoiseDef("macro/second", -5, List.of(1.0)));
Field mask = new Field.Noise(first, 1.0, 0.0, null, null, null);
Field payload = new Field.Binary(Field.BinaryOp.ADD, mask, new Field.Noise(second, 1.0, 0.0, null, null, null));
Field product = FieldMacros.product(mask, payload);
Field.Binary multiply = (Field.Binary) product;
assertSame(mask, multiply.left());
assertTrue(multiply.right() instanceof Field.Gate);
assertTrue(TerrainTestSupport.unguardedExpensiveBranches(product).isEmpty());
for (int x = -50; x <= 50; x += 17) {
double expected = TerrainTestSupport.sample(mask, registry, DataVersion.V26_3, x, 0, 3)
* TerrainTestSupport.sample(payload, registry, DataVersion.V26_3, x, 0, 3);
assertEquals(expected, TerrainTestSupport.sample(product, registry, DataVersion.V26_3, x, 0, 3), 1.0e-6);
}
}
@Test
public void unguardedExpensiveBranchesAreDetected() {
NoiseRegistry registry = new NoiseRegistry(TerrainTestSupport.NAMESPACE);
Field first = new Field.Noise(registry.register(new NoiseDef("macro/first", -4, List.of(1.0))), 1.0, 0.0, null, null, null);
Field second = new Field.Noise(registry.register(new NoiseDef("macro/second", -5, List.of(1.0))), 1.0, 0.0, null, null, null);
Field expensive = new Field.Binary(Field.BinaryOp.ADD, first, second);
assertEquals(1, TerrainTestSupport.unguardedExpensiveBranches(new Field.Binary(Field.BinaryOp.MUL, first, expensive)).size());
assertEquals(1, TerrainTestSupport.unguardedExpensiveBranches(new Field.Lerp(first, expensive, second)).size());
assertEquals(1, TerrainTestSupport.unguardedExpensiveBranches(new Field.RangeIf(first, 0.0, 1.0, second, expensive)).size());
assertTrue(TerrainTestSupport.unguardedExpensiveBranches(new Field.Binary(Field.BinaryOp.MUL, new Field.Const(2.0), expensive)).isEmpty());
assertTrue(TerrainTestSupport.unguardedExpensiveBranches(new Field.Gate(first, new Field.Binary(Field.BinaryOp.ADD, expensive, X))).isEmpty());
}
@Test
public void liftGivesHorizontalNoiseAVerticalScale() {
NoiseRegistry registry = new NoiseRegistry(TerrainTestSupport.NAMESPACE);
String id = registry.register(new NoiseDef("macro/base", -4, List.of(1.0)));
Field flat = new Field.Noise(id, 0.5, 0.0, null, null, null);
Field lifted = FieldMacros.lift(flat, 3.0);
assertEquals(new Field.Noise(id, 0.5, 1.5, null, null, null), lifted);
assertTrue(lifted.axes().contains(Axis.Y));
}
@Test
public void smoothstepIsTheZeroDerivativeHermite() {
NoiseRegistry registry = new NoiseRegistry(TerrainTestSupport.NAMESPACE);
Field ramp = FieldMacros.smoothstep(X, 0.0, 0.4);
assertEquals(0.0, TerrainTestSupport.sample(ramp, registry, DataVersion.V26_3, -5, 0, 0), 0.0);
assertEquals(0.5, TerrainTestSupport.sample(ramp, registry, DataVersion.V26_3, 20, 0, 0), 1.0e-5);
assertEquals(0.15625, TerrainTestSupport.sample(ramp, registry, DataVersion.V26_3, 10, 0, 0), 1.0e-5);
assertEquals(1.0, TerrainTestSupport.sample(ramp, registry, DataVersion.V26_3, 90, 0, 0), 0.0);
}
@Test
public void lookupFollowsTheFunction() {
NoiseRegistry registry = new NoiseRegistry(TerrainTestSupport.NAMESPACE);
Field input = FieldMacros.scale(X, 10.0);
Field sine = FieldMacros.lookup(input, value -> Math.sin(Math.PI * value), value -> Math.PI * Math.cos(Math.PI * value), 0.0, 1.0, 16);
for (int x = 0; x <= 10; x++) {
assertEquals(Math.sin(Math.PI * x / 10.0), TerrainTestSupport.sample(sine, registry, DataVersion.V26_3, x, 0, 0), 1.0e-4);
}
}
@Test
public void sumFoldsConstantsAndBalancesTerms() {
Field sum = FieldMacros.sum(List.of(new Field.Const(1.0), X, X, new Field.Const(2.0), X, X));
Field.Binary root = (Field.Binary) sum;
assertEquals(new Field.Const(3.0), root.right());
assertEquals(new Field.Binary(Field.BinaryOp.ADD,
new Field.Binary(Field.BinaryOp.ADD, X, X),
new Field.Binary(Field.BinaryOp.ADD, X, X)), root.left());
}
}
@@ -0,0 +1,229 @@
package art.arcane.iris.pack.datapack.export.compile.terrain;
import art.arcane.iris.generation.noise.IrisGenerator;
import art.arcane.iris.generation.noise.IrisGeneratorStyle;
import art.arcane.iris.generation.noise.IrisNoiseGenerator;
import art.arcane.iris.generation.noise.NoiseStyle;
import art.arcane.iris.pack.datapack.DataVersion;
import art.arcane.iris.pack.datapack.export.compile.noise.NoiseRegistry;
import art.arcane.iris.pack.datapack.export.compile.noise.StyleCompiler;
import art.arcane.iris.pack.datapack.export.ir.Axis;
import art.arcane.iris.pack.datapack.export.ir.ExportDiagnostic;
import art.arcane.iris.pack.datapack.export.ir.ExportLimit;
import art.arcane.iris.pack.datapack.export.ir.Field;
import art.arcane.iris.pack.datapack.export.lower.ExportCapabilities;
import art.arcane.volmlib.util.collection.KList;
import art.arcane.volmlib.util.interpolation.IrisInterpolation;
import org.junit.Test;
import java.util.ArrayList;
import java.util.List;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertTrue;
public class GeneratorCompilerTest {
private static final ExportCapabilities CAPABILITIES = ExportCapabilities.forTarget(DataVersion.V26_3);
@Test
public void cliffStepsAreExact() {
IrisGenerator cliffs = generator("cliffs", layer(NoiseStyle.SIMPLEX, 1.0));
cliffs.setCliffHeightMin(40);
cliffs.setCliffHeightMax(40);
IrisGenerator smooth = generator("cliffs", layer(NoiseStyle.SIMPLEX, 1.0));
NoiseRegistry registry = new NoiseRegistry(TerrainTestSupport.NAMESPACE);
GeneratorCompiler compiler = compiler(TerrainTestSupport.noiseStyles(), registry);
Field stepped = compiler.compile(cliffs, "steps");
Field raw = new GeneratorCompiler(TerrainTestSupport.noiseStyles(), registry, CAPABILITIES, new ArrayList<>()).compile(smooth, "steps");
double step = 40.0 / 255.0;
int distinct = 0;
double previous = Double.NaN;
for (int x = -400; x <= 400; x += 7) {
double value = TerrainTestSupport.sample(stepped, registry, DataVersion.V26_3, x, 0, 13);
double steps = value / step;
assertEquals("cliff value " + value + " at x " + x, Math.rint(steps), steps, 1.0e-3);
double expected = Math.round(TerrainTestSupport.sample(raw, registry, DataVersion.V26_3, x, 0, 13) / step) * step;
assertEquals(expected, value, 1.0e-5);
if (value != previous) {
distinct++;
previous = value;
}
}
assertTrue("cliffs should produce several terraces, got " + distinct, distinct > 3);
}
@Test
public void variableCliffHeightQuantisesByTheLocalStep() {
IrisGenerator cliffs = generator("variable", layer(NoiseStyle.SIMPLEX, 1.0));
cliffs.setCliffHeightMin(20);
cliffs.setCliffHeightMax(80);
NoiseRegistry registry = new NoiseRegistry(TerrainTestSupport.NAMESPACE);
Field.Shared compiled = (Field.Shared) compiler(TerrainTestSupport.noiseStyles(), registry).compile(cliffs, "steps");
Field.Round round = (Field.Round) compiled.expr();
assertEquals(Field.RoundMode.ROUND, round.mode());
for (int x = -300; x <= 300; x += 23) {
double multiple = TerrainTestSupport.sample(round.multiple(), registry, DataVersion.V26_3, x, 0, -5);
double value = TerrainTestSupport.sample(compiled, registry, DataVersion.V26_3, x, 0, -5);
assertTrue(multiple >= 20.0 / 255.0 - 1.0e-6 && multiple <= 80.0 / 255.0 + 1.0e-6);
assertEquals(Math.rint(value / multiple), value / multiple, 1.0e-3);
}
}
@Test
public void bezierLayerMatchesTheIrisCurve() {
IrisNoiseGenerator curved = layer(NoiseStyle.SIMPLEX, 1.0);
curved.setBezier(true);
NoiseRegistry registry = new NoiseRegistry(TerrainTestSupport.NAMESPACE);
Field shaped = compiler(TerrainTestSupport.noiseStyles(), registry).compile(generator("curve", curved), "curve");
Field raw = compiler(TerrainTestSupport.noiseStyles(), registry).compile(generator("curve", layer(NoiseStyle.SIMPLEX, 1.0)), "curve");
for (int x = -200; x <= 200; x += 19) {
double source = TerrainTestSupport.sample(raw, registry, DataVersion.V26_3, x, 0, 4);
assertEquals(IrisInterpolation.bezier(source), TerrainTestSupport.sample(shaped, registry, DataVersion.V26_3, x, 0, 4), 1.0e-6);
}
}
@Test
public void layersAverageByOpacity() {
IrisNoiseGenerator heavy = layer(NoiseStyle.SIMPLEX, 1.0);
IrisNoiseGenerator light = layer(NoiseStyle.PERLIN, 0.5);
light.setSeed(9);
IrisGenerator blended = generator("blend", heavy, light);
blended.setOpacity(0.8);
NoiseRegistry registry = new NoiseRegistry(TerrainTestSupport.NAMESPACE);
GeneratorCompiler compiler = compiler(TerrainTestSupport.constantStyles(0.25), registry);
Field value = compiler.compile(blended, "blend");
assertEquals((0.25 + 0.25 * 0.5) / 1.5 * 0.8, TerrainTestSupport.sample(value, registry, DataVersion.V26_3, 3, 0, 3), 1.0e-6);
}
@Test
public void zoomsCombineIntoTheCompiledStyle() {
List<Double> zooms = new ArrayList<>();
StyleCompiler recording = (style, seedSalt, registry, capabilities) -> {
zooms.add(style.getZoom());
return new Field.Const(0.5);
};
IrisNoiseGenerator zoomed = layer(NoiseStyle.SIMPLEX, 1.0);
zoomed.setZoom(3.0);
zoomed.getStyle().setZoom(2.0);
IrisGenerator generator = generator("zoom", zoomed);
generator.setZoom(5.0);
compiler(recording, new NoiseRegistry(TerrainTestSupport.NAMESPACE)).compile(generator, "zoom");
assertEquals(List.of(30.0), zooms);
assertEquals(2.0, zoomed.getStyle().getZoom(), 0.0);
}
@Test
public void surfaceDetailBlendsTheSixBlockGrid() {
IrisGenerator detailed = generator("detail", layer(NoiseStyle.SIMPLEX, 1.0));
detailed.setSurfaceDetail(0.5);
NoiseRegistry registry = new NoiseRegistry(TerrainTestSupport.NAMESPACE);
Field blended = compiler(TerrainTestSupport.noiseStyles(), registry).compile(detailed, "detail");
Field raw = compiler(TerrainTestSupport.noiseStyles(), registry).compile(generator("detail", layer(NoiseStyle.SIMPLEX, 1.0)), "detail");
double low = TerrainTestSupport.sample(raw, registry, DataVersion.V26_3, 12, 0, 18);
double high = TerrainTestSupport.sample(raw, registry, DataVersion.V26_3, 18, 0, 18);
double middle = TerrainTestSupport.sample(raw, registry, DataVersion.V26_3, 15, 0, 18);
assertEquals(low, TerrainTestSupport.sample(blended, registry, DataVersion.V26_3, 12, 0, 18), 1.0e-6);
assertEquals(0.5 * middle + 0.25 * (low + high), TerrainTestSupport.sample(blended, registry, DataVersion.V26_3, 15, 0, 18), 1.0e-6);
}
@Test
public void rawGeneratorSkipsTheSurfaceGridAndSharesTheBlendInput() {
IrisGenerator detailed = generator("detail", layer(NoiseStyle.SIMPLEX, 1.0));
detailed.setSurfaceDetail(0.5);
NoiseRegistry registry = new NoiseRegistry(TerrainTestSupport.NAMESPACE);
Field blended = compiler(TerrainTestSupport.noiseStyles(), registry).compile(detailed, "detail");
GeneratorCompiler compiler = compiler(TerrainTestSupport.noiseStyles(), registry);
Field raw = compiler.compileRaw(detailed, "detail");
assertSame(raw, compiler.compileRaw(detailed, "detail"));
assertTrue(TerrainTestSupport.contains(blended, raw));
assertFalse(containsGrid(raw));
assertTrue(containsGrid(blended));
assertEquals(TerrainTestSupport.sample(blended, registry, DataVersion.V26_3, 12, 0, 18),
TerrainTestSupport.sample(raw, registry, DataVersion.V26_3, 12, 0, 18), 1.0e-12);
}
@Test
public void generatorFieldsAreTwoDimensionalAndShared() {
NoiseRegistry registry = new NoiseRegistry(TerrainTestSupport.NAMESPACE);
Field compiled = compiler(TerrainTestSupport.noiseStyles(), registry).compile(generator("Mixed Case/hills", layer(NoiseStyle.SIMPLEX, 1.0)), "height");
assertEquals("terrain/generator/height/mixed_case/hills", ((Field.Shared) compiled).name());
assertFalse(compiled.axes().contains(Axis.Y));
}
@Test
public void unsupportedLayerFeaturesReportDiagnostics() {
IrisNoiseGenerator octaves = layer(NoiseStyle.SIMPLEX, 1.0);
octaves.setOctaves(3);
IrisGenerator generator = generator("octaves", octaves);
generator.setCellFractureHeight(4.0);
List<ExportDiagnostic> diagnostics = new ArrayList<>();
new GeneratorCompiler(TerrainTestSupport.noiseStyles(), new NoiseRegistry(TerrainTestSupport.NAMESPACE), CAPABILITIES, diagnostics)
.compile(generator, "height");
assertEquals(2, diagnostics.size());
for (ExportDiagnostic diagnostic : diagnostics) {
assertEquals(ExportLimit.NOISE_STYLE, diagnostic.limit());
assertEquals("generators/octaves", diagnostic.resource());
}
}
@Test
public void compileIsDeterministic() {
IrisGenerator first = generator("same", layer(NoiseStyle.SIMPLEX, 1.0), layer(NoiseStyle.PERLIN, 0.5));
IrisGenerator second = generator("same", layer(NoiseStyle.SIMPLEX, 1.0), layer(NoiseStyle.PERLIN, 0.5));
NoiseRegistry firstRegistry = new NoiseRegistry(TerrainTestSupport.NAMESPACE);
NoiseRegistry secondRegistry = new NoiseRegistry(TerrainTestSupport.NAMESPACE);
Field one = compiler(TerrainTestSupport.noiseStyles(), firstRegistry).compile(first, "height");
Field two = compiler(TerrainTestSupport.noiseStyles(), secondRegistry).compile(second, "height");
assertEquals(one, two);
assertEquals(firstRegistry.definitions(), secondRegistry.definitions());
}
private static GeneratorCompiler compiler(StyleCompiler styles, NoiseRegistry registry) {
return new GeneratorCompiler(styles, registry, CAPABILITIES, new ArrayList<>());
}
private static IrisGenerator generator(String key, IrisNoiseGenerator... layers) {
IrisGenerator generator = new IrisGenerator();
generator.setLoadKey(key);
generator.setComposite(new KList<>(List.of(layers)));
return generator;
}
private static IrisNoiseGenerator layer(NoiseStyle style, double opacity) {
IrisNoiseGenerator layer = new IrisNoiseGenerator();
layer.setStyle(new IrisGeneratorStyle(style));
layer.setOpacity(opacity);
return layer;
}
private static boolean containsGrid(Field root) {
if (root instanceof Field.Grid) {
return true;
}
for (Field child : FieldMacros.children(root)) {
if (containsGrid(child)) {
return true;
}
}
return false;
}
}
@@ -0,0 +1,327 @@
package art.arcane.iris.pack.datapack.export.compile.terrain;
import art.arcane.iris.generation.terrain.IrisDimension;
import art.arcane.iris.pack.datapack.DataVersion;
import art.arcane.iris.pack.datapack.export.ExportTestPacks;
import art.arcane.iris.pack.datapack.export.compile.biome.BiomeCodes;
import art.arcane.iris.pack.datapack.export.compile.noise.NoiseRegistry;
import art.arcane.iris.pack.datapack.export.compile.noise.StyleCompiler;
import art.arcane.iris.pack.datapack.export.ir.Axis;
import art.arcane.iris.pack.datapack.export.ir.Field;
import art.arcane.iris.pack.datapack.export.ir.FieldValidator;
import art.arcane.iris.pack.datapack.export.lower.ExportCapabilities;
import art.arcane.iris.pack.loading.IrisData;
import art.arcane.iris.testsupport.PlatformLeakGuard;
import art.arcane.volmlib.util.interpolation.InterpolationMethod;
import art.arcane.volmlib.util.interpolation.IrisInterpolation;
import art.arcane.volmlib.util.interpolation.NoiseBounds;
import art.arcane.volmlib.util.interpolation.NoiseBoundsProvider;
import org.junit.ClassRule;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import java.io.File;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Deque;
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.assertTrue;
public class HeightCompilerTest {
private static final ExportCapabilities CAPABILITIES = ExportCapabilities.forTarget(DataVersion.V26_3);
private static final int SEA_LEVEL = 63;
private static final int BLEND_RADIUS = 12;
private static final int BOUNDS_STEP = 4;
private static final double LOW_MIDPOINT = 10.0;
private static final double HIGH_MIDPOINT = 80.0;
private static final double STEPS = 4.0;
@ClassRule
public static final PlatformLeakGuard PLATFORM_GUARD = PlatformLeakGuard.clean();
@Rule
public TemporaryFolder temporaryFolder = new TemporaryFolder();
@Rule
public ExportTestPacks.BoundPlatform platform = new ExportTestPacks.BoundPlatform();
@Test
public void heightRootIsTwoDimensional() throws Exception {
File pack = TerrainTestPacks.twoBiomes(temporaryFolder.newFolder("pack"),
TerrainTestPacks.link("hills", 0, 20), TerrainTestPacks.link("hills", 40, 90));
TerrainTestPacks.generator(pack, "hills", TerrainTestPacks.twoLayers("BILINEAR_STARCAST_9", 12));
IrisData data = IrisData.openRuntime(pack);
try {
NoiseRegistry registry = new NoiseRegistry(TerrainTestSupport.NAMESPACE);
Field height = compile(data, registry, TerrainTestSupport.noiseStyles(), TerrainTestSupport.twoBiomeCodes(registry, 0.0));
assertEquals(HeightCompiler.HEIGHT, ((Field.Shared) height).name());
FieldValidator.requireTwoDimensional(height, "height");
assertFalse(height.axes().contains(Axis.Y));
for (int x = -500; x <= 500; x += 41) {
double value = TerrainTestSupport.sample(height, registry, DataVersion.V26_3, x, 0, x / 3);
assertTrue("height " + value, value >= SEA_LEVEL && value <= SEA_LEVEL + 90);
}
} finally {
data.close();
}
}
@Test
public void bandBlendRmsWithin0_13() throws Exception {
NoiseRegistry registry = new NoiseRegistry(TerrainTestSupport.NAMESPACE);
double rms = blendRms(registry, TerrainTestSupport.twoBiomeCodes(registry, 0.0));
assertTrue("band blend rms " + rms, rms <= 0.13);
}
@Test
public void steppedSelectorBandBlendRmsWithin0_13() throws Exception {
NoiseRegistry registry = new NoiseRegistry(TerrainTestSupport.NAMESPACE);
double rms = blendRms(registry, steppedCodes(registry));
assertTrue("stepped band blend rms " + rms, rms <= 0.13);
}
@Test
public void slopeIsTheForwardDifferenceOfTheRelief() throws Exception {
File pack = TerrainTestPacks.twoBiomes(temporaryFolder.newFolder("pack"),
TerrainTestPacks.link("hills", 0, 40), TerrainTestPacks.link("hills", 0, 40));
TerrainTestPacks.generator(pack, "hills", TerrainTestPacks.twoLayers("BILINEAR_STARCAST_9", 12));
IrisData data = IrisData.openRuntime(pack);
try {
NoiseRegistry registry = new NoiseRegistry(TerrainTestSupport.NAMESPACE);
IrisDimension dimension = data.getDimensionLoader().load(TerrainTestPacks.DIMENSION, false);
TerrainHeight terrain = new HeightCompiler(TerrainTestSupport.noiseStyles(), new ArrayList<>())
.compile(TerrainTestSupport.singleBiomeCodes("a"), dimension, data, registry, CAPABILITIES);
for (int x = -900; x <= 900; x += 113) {
int z = 2 * x / 3;
double here = TerrainTestSupport.sample(terrain.height(), registry, DataVersion.V26_3, x, 0, z);
double east = (TerrainTestSupport.sample(terrain.height(), registry, DataVersion.V26_3, x + 4, 0, z) - here) / 4.0;
double south = (TerrainTestSupport.sample(terrain.height(), registry, DataVersion.V26_3, x, 0, z + 4) - here) / 4.0;
double slope = TerrainTestSupport.sample(terrain.slope(), registry, DataVersion.V26_3, x, 0, z);
assertEquals("slope at " + x + "," + z, Math.sqrt(east * east + south * south), slope, 1.0e-3);
}
} finally {
data.close();
}
}
@Test
public void slopeNeverCopiesTheBiomeSelector() throws Exception {
File pack = TerrainTestPacks.twoBiomes(temporaryFolder.newFolder("pack"),
TerrainTestPacks.link("hills", 0, 20), TerrainTestPacks.link("hills", 40, 90));
TerrainTestPacks.generator(pack, "hills", TerrainTestPacks.twoLayers("BILINEAR_STARCAST_9", 12));
IrisData data = IrisData.openRuntime(pack);
try {
NoiseRegistry registry = new NoiseRegistry(TerrainTestSupport.NAMESPACE);
IrisDimension dimension = data.getDimensionLoader().load(TerrainTestPacks.DIMENSION, false);
TerrainHeight terrain = new HeightCompiler(TerrainTestSupport.noiseStyles(), new ArrayList<>())
.compile(TerrainTestSupport.twoBiomeCodes(registry, 0.0), dimension, data, registry, CAPABILITIES);
String selector = TerrainTestSupport.NAMESPACE + ":" + TerrainTestSupport.SELECTOR_ID;
for (Field node : TerrainTestSupport.nodes(new Field.Binary(Field.BinaryOp.ADD, terrain.height(), terrain.slope()))) {
if (node instanceof Field.Noise noise && noise.noiseId().equals(selector)) {
assertTrue("selector sampled with a shift: " + noise, noise.shiftX() == null && noise.shiftZ() == null);
}
}
} finally {
data.close();
}
}
@Test
public void heightCliffsStepByTheBandSpan() throws Exception {
File pack = TerrainTestPacks.twoBiomes(temporaryFolder.newFolder("pack"),
TerrainTestPacks.link("terraces", 0, 51), TerrainTestPacks.link("terraces", 0, 51));
TerrainTestPacks.generator(pack, "terraces", """
{"interpolator":{"function":"BILINEAR_STARCAST_9","horizontalScale":12},"cliffHeightMin":50,"cliffHeightMax":50,
"composite":[{"style":{"style":"SIMPLEX"},"seed":3}]}""");
IrisData data = IrisData.openRuntime(pack);
try {
NoiseRegistry registry = new NoiseRegistry(TerrainTestSupport.NAMESPACE);
Field height = compile(data, registry, TerrainTestSupport.noiseStyles(), TerrainTestSupport.twoBiomeCodes(registry, 0.0));
double step = 51.0 * 50.0 / 255.0;
for (int x = -600; x <= 600; x += 5) {
double rise = (TerrainTestSupport.sample(height, registry, DataVersion.V26_3, x, 0, 17) - SEA_LEVEL) / step;
assertEquals("terrace " + rise + " at x " + x, Math.rint(rise), rise, 1.0e-3);
}
} finally {
data.close();
}
}
@Test
public void silentBucketsLeaveSeaLevel() throws Exception {
File pack = TerrainTestPacks.twoBiomes(temporaryFolder.newFolder("pack"),
TerrainTestPacks.link("hills", 0, 0), TerrainTestPacks.link("hills", 0, 0));
TerrainTestPacks.generator(pack, "hills", TerrainTestPacks.twoLayers("BILINEAR_STARCAST_9", 12));
IrisData data = IrisData.openRuntime(pack);
try {
NoiseRegistry registry = new NoiseRegistry(TerrainTestSupport.NAMESPACE);
Field height = compile(data, registry, TerrainTestSupport.noiseStyles(), TerrainTestSupport.twoBiomeCodes(registry, 0.0));
assertEquals(new Field.Shared(HeightCompiler.HEIGHT, new Field.Const(SEA_LEVEL)), height);
} finally {
data.close();
}
}
@Test
public void wideBucketsBlendOnCoarseLattices() throws Exception {
File pack = TerrainTestPacks.twoBiomes(temporaryFolder.newFolder("pack"),
TerrainTestPacks.link("ranges", 0, 20), TerrainTestPacks.link("ranges", 60, 120));
TerrainTestPacks.generator(pack, "ranges", TerrainTestPacks.singleLayer("BILINEAR_STARCAST_12", 200, "SIMPLEX"));
IrisData data = IrisData.openRuntime(pack);
try {
NoiseRegistry registry = new NoiseRegistry(TerrainTestSupport.NAMESPACE);
Field height = compile(data, registry, TerrainTestSupport.noiseStyles(), TerrainTestSupport.twoBiomeCodes(registry, 0.0));
assertTrue(containsGrid(height, 512));
} finally {
data.close();
}
}
@Test
public void compileIsDeterministic() throws Exception {
File pack = TerrainTestPacks.twoBiomes(temporaryFolder.newFolder("pack"),
TerrainTestPacks.link("hills", 0, 20) + "," + TerrainTestPacks.link("dunes", 5, 9),
TerrainTestPacks.link("hills", 40, 90));
TerrainTestPacks.generator(pack, "hills", TerrainTestPacks.twoLayers("BILINEAR_STARCAST_9", 12));
TerrainTestPacks.generator(pack, "dunes", TerrainTestPacks.singleLayer("BILINEAR_STARCAST_9", 23, "PERLIN"));
IrisData data = IrisData.openRuntime(pack);
try {
NoiseRegistry first = new NoiseRegistry(TerrainTestSupport.NAMESPACE);
NoiseRegistry second = new NoiseRegistry(TerrainTestSupport.NAMESPACE);
Field one = compile(data, first, TerrainTestSupport.noiseStyles(), TerrainTestSupport.twoBiomeCodes(first, 0.0));
Field two = compile(data, second, TerrainTestSupport.noiseStyles(), TerrainTestSupport.twoBiomeCodes(second, 0.0));
assertEquals(one, two);
assertEquals(first.definitions(), second.definitions());
} finally {
data.close();
}
}
private double blendRms(NoiseRegistry registry, BiomeCodes codes) throws Exception {
File pack = TerrainTestPacks.twoBiomes(temporaryFolder.newFolder("pack"),
TerrainTestPacks.link("hills", 0, 20), TerrainTestPacks.link("hills", 60, 100));
TerrainTestPacks.generator(pack, "hills", TerrainTestPacks.singleLayer("BILINEAR_STARCAST_9", BLEND_RADIUS, "SIMPLEX"));
IrisData data = IrisData.openRuntime(pack);
try {
Field height = compile(data, registry, TerrainTestSupport.constantStyles(0.5), codes);
IrisBands iris = new IrisBands(codes.surfaceCode(), registry);
double squared = 0.0;
int zone = 0;
for (int x = 0; x < 768; x += 3) {
for (int z = 0; z < 768; z += 3) {
double reference = SEA_LEVEL + iris.height(x, z);
double weight = (reference - SEA_LEVEL - LOW_MIDPOINT) / (HIGH_MIDPOINT - LOW_MIDPOINT);
if (weight < 0.02 || weight > 0.98) {
continue;
}
double exported = TerrainTestSupport.sample(height, registry, DataVersion.V26_3, x, 0, z);
double error = (exported - reference) / (HIGH_MIDPOINT - LOW_MIDPOINT);
squared += error * error;
zone++;
}
}
assertTrue("transition zone too small: " + zone, zone > 500);
return Math.sqrt(squared / zone);
} finally {
data.close();
}
}
private static BiomeCodes steppedCodes(NoiseRegistry registry) {
BiomeCodes smooth = TerrainTestSupport.twoBiomeCodes(registry, 0.0);
Field.Partition partition = (Field.Partition) smooth.surfaceCode();
Field stepped = new Field.Round(Field.RoundMode.ROUND, FieldMacros.scale(partition.input(), STEPS), new Field.Const(1.0));
Field code = new Field.Partition(stepped, List.of(0.5), partition.leaves());
return new BiomeCodes(code, smooth.caveCode(), smooth.class3d(), smooth.layout(), smooth.loadKeyByBiomeId());
}
private static Field compile(IrisData data, NoiseRegistry registry, StyleCompiler styles, BiomeCodes codes) {
IrisDimension dimension = data.getDimensionLoader().load(TerrainTestPacks.DIMENSION, false);
return new HeightCompiler(styles, new ArrayList<>()).compile(codes, dimension, data, registry, CAPABILITIES).height();
}
private static boolean containsGrid(Field root, int cell) {
Deque<Field> pending = new ArrayDeque<>();
pending.push(root);
while (!pending.isEmpty()) {
Field field = pending.pop();
if (field instanceof Field.Grid grid && grid.cellXZ() == cell) {
return true;
}
for (Field child : FieldMacros.children(field)) {
pending.push(child);
}
}
return false;
}
private static final class IrisBands implements NoiseBoundsProvider {
private final Field code;
private final NoiseRegistry registry;
private final Map<Long, NoiseBounds> samples = new HashMap<>();
private final Map<Long, NoiseBounds> corners = new HashMap<>();
private IrisBands(Field code, NoiseRegistry registry) {
this.code = code;
this.registry = registry;
}
@Override
public NoiseBounds noise(double x, double z) {
int blockX = (int) x;
int blockZ = (int) z;
return samples.computeIfAbsent(key(blockX, blockZ), ignored -> {
double value = TerrainTestSupport.sample(code, registry, DataVersion.V26_3, blockX, 0, blockZ);
return value < 0.2 ? new NoiseBounds(0.0, 20.0) : new NoiseBounds(60.0, 100.0);
});
}
private double height(int x, int z) {
int gridX = Math.floorDiv(x, BOUNDS_STEP) * BOUNDS_STEP;
int gridZ = Math.floorDiv(z, BOUNDS_STEP) * BOUNDS_STEP;
double fractionX = (x - gridX) / (double) BOUNDS_STEP;
double fractionZ = (z - gridZ) / (double) BOUNDS_STEP;
NoiseBounds northWest = corner(gridX, gridZ);
NoiseBounds northEast = corner(gridX + BOUNDS_STEP, gridZ);
NoiseBounds southWest = corner(gridX, gridZ + BOUNDS_STEP);
NoiseBounds southEast = corner(gridX + BOUNDS_STEP, gridZ + BOUNDS_STEP);
double low = bilinear(northWest.min(), northEast.min(), southWest.min(), southEast.min(), fractionX, fractionZ);
double high = bilinear(northWest.max(), northEast.max(), southWest.max(), southEast.max(), fractionX, fractionZ);
return low + (high - low) * 0.5;
}
private NoiseBounds corner(int x, int z) {
return corners.computeIfAbsent(key(x, z),
ignored -> IrisInterpolation.getNoiseBounds(InterpolationMethod.BILINEAR_STARCAST_9, x, z, BLEND_RADIUS, this));
}
private static double bilinear(double northWest, double northEast, double southWest, double southEast, double fractionX, double fractionZ) {
double north = northWest + (northEast - northWest) * fractionX;
double south = southWest + (southEast - southWest) * fractionX;
return north + (south - north) * fractionZ;
}
private static long key(int x, int z) {
return ((long) x << 32) ^ (z & 0xffffffffL);
}
}
}
@@ -0,0 +1,199 @@
package art.arcane.iris.pack.datapack.export.compile.terrain;
import art.arcane.iris.generation.biome.IrisBiome;
import art.arcane.iris.generation.terrain.IrisDimension;
import art.arcane.iris.pack.datapack.DataVersion;
import art.arcane.iris.pack.datapack.export.ExportTestPacks;
import art.arcane.iris.pack.datapack.export.compile.biome.BiomeCodes;
import art.arcane.iris.pack.datapack.export.compile.biome.BiomeIdSanitizer;
import art.arcane.iris.pack.datapack.export.compile.noise.NoiseRegistry;
import art.arcane.iris.pack.datapack.export.ir.Axis;
import art.arcane.iris.pack.datapack.export.ir.ClimateLayout;
import art.arcane.iris.pack.datapack.export.ir.ExportDiagnostic;
import art.arcane.iris.pack.datapack.export.ir.Field;
import art.arcane.iris.pack.datapack.export.lower.ExportCapabilities;
import art.arcane.iris.pack.loading.IrisData;
import art.arcane.iris.spi.IrisPlatforms;
import art.arcane.iris.testsupport.PlatformLeakGuard;
import org.junit.Assume;
import org.junit.ClassRule;
import org.junit.Rule;
import org.junit.Test;
import java.io.File;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.IdentityHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.mockito.Mockito.doReturn;
public class OverworldTerrainProbeTest {
private static final String PROPERTY = "iris.exportProbePack";
private static final String DIMENSION = "overworld";
private static final double CODE_SPAN = 0.9;
@ClassRule
public static final PlatformLeakGuard PLATFORM_GUARD = PlatformLeakGuard.clean();
@Rule
public ExportTestPacks.BoundPlatform platform = new ExportTestPacks.BoundPlatform();
@Test
public void overworldTerrainCompiles() {
String pack = System.getProperty(PROPERTY);
Assume.assumeTrue("Set -P" + PROPERTY + " to probe a real pack", pack != null && !pack.isBlank());
doReturn(DataVersion.V26_3.getVersion()).when(IrisPlatforms.get()).minecraftVersion();
doReturn(null).when(IrisPlatforms.get()).registries();
IrisData data = IrisData.openRuntime(new File(pack));
try {
IrisDimension dimension = data.getDimensionLoader().load(DIMENSION, false);
NoiseRegistry registry = new NoiseRegistry(TerrainTestSupport.NAMESPACE);
BiomeCodes codes = codes(dimension, data, registry);
ExportCapabilities capabilities = ExportCapabilities.forTarget(DataVersion.V26_3);
List<ExportDiagnostic> diagnostics = new ArrayList<>();
TerrainHeight terrain = new HeightCompiler(TerrainTestSupport.noiseStyles(), diagnostics).compile(codes, dimension, data, registry, capabilities);
Field height = terrain.height();
Field volumetric = new VolumetricCompiler(TerrainTestSupport.noiseStyles(), diagnostics).compile(terrain, codes, dimension, data, registry, capabilities);
assertFalse(height.axes().contains(Axis.Y));
List<String> violations = new ArrayList<>(TerrainTestSupport.unguardedExpensiveBranches(height));
violations.addAll(TerrainTestSupport.unguardedExpensiveBranches(volumetric));
assertTrue(violations.toString(), violations.isEmpty());
for (int sample = 0; sample < 8; sample++) {
int x = sample * 977 - 3000;
int z = sample * 613 - 2000;
double value = TerrainTestSupport.sample(height, registry, DataVersion.V26_3, x, 0, z);
assertTrue("height " + value, value >= dimension.getMinHeight() && value <= dimension.getMaxHeight());
assertTrue(Double.isFinite(TerrainTestSupport.sample(volumetric, registry, DataVersion.V26_3, x, (int) value, z)));
}
Map<String, Integer> limits = new TreeMap<>();
for (ExportDiagnostic diagnostic : diagnostics) {
limits.merge(diagnostic.limit().name(), 1, Integer::sum);
}
System.out.println("[terrain probe] biomes " + codes.loadKeyByBiomeId().size() + " noises " + registry.definitions().size()
+ " diagnostics " + limits);
System.out.println("[terrain probe] height " + Shape.of(height));
System.out.println("[terrain probe] volumetric " + Shape.of(volumetric));
} finally {
data.close();
}
}
private static BiomeCodes codes(IrisDimension dimension, IrisData data, NoiseRegistry registry) {
Map<String, IrisBiome> biomes = new TreeMap<>();
for (IrisBiome biome : dimension.getReachableBiomes(() -> data)) {
biomes.put(biome.getLoadKey(), biome);
}
int count = biomes.size();
String selector = registry.register(TerrainTestSupport.SELECTOR);
List<Double> thresholds = new ArrayList<>(count - 1);
List<Field> leaves = new ArrayList<>(count);
List<ClimateLayout.ClimateEntry> entries = new ArrayList<>(count);
Map<String, String> loadKeys = new TreeMap<>();
Set<String> taken = new HashSet<>();
int index = 0;
for (String loadKey : biomes.keySet()) {
String id = BiomeIdSanitizer.sanitize(TerrainTestSupport.NAMESPACE, loadKey, taken);
double center = -1.0 + (2.0 * index + 1.0) / count;
double half = CODE_SPAN / count;
entries.add(new ClimateLayout.ClimateEntry(id, ClimateLayout.ClimateAxis.TEMPERATURE, center - half, center + half));
leaves.add(new Field.Const(center));
loadKeys.put(id, loadKey);
if (index > 0) {
thresholds.add(-0.8 + 1.6 * index / count);
}
index++;
}
Field code = new Field.Partition(new Field.Noise(selector, 1.0, 0.0, null, null, null), thresholds, leaves);
return new BiomeCodes(code, new Field.Const(0.0), new Field.Const(0.0), new ClimateLayout(entries), loadKeys);
}
private record Shape(long distinct, long emitted, long sharedFiles, int inlineDepth, int fileDepth, long gates, long muxes, long knots) {
private static Shape of(Field root) {
Map<Field, Long> sizes = new IdentityHashMap<>();
Map<Field, Integer> depths = new IdentityHashMap<>();
Map<Field, Integer> fileDepths = new IdentityHashMap<>();
Set<Field> distinct = Collections.newSetFromMap(new IdentityHashMap<>());
Set<String> shared = new HashSet<>();
long[] counts = new long[3];
collect(root, distinct, shared, counts);
int deepestFile = fileDepth(root, fileDepths);
for (Field field : distinct) {
if (field instanceof Field.Shared sharedField) {
deepestFile = Math.max(deepestFile, fileDepth(sharedField.expr(), fileDepths));
}
}
long emitted = root instanceof Field.Shared ? 0 : emitted(root, sizes);
for (Field field : distinct) {
if (field instanceof Field.Shared sharedField) {
emitted += emitted(sharedField.expr(), sizes);
}
}
return new Shape(distinct.size(), emitted, shared.size(), depth(root, depths), deepestFile, counts[0], counts[1], counts[2]);
}
private static void collect(Field field, Set<Field> distinct, Set<String> shared, long[] counts) {
if (!distinct.add(field)) {
return;
}
switch (field) {
case Field.Shared sharedField -> shared.add(sharedField.name());
case Field.Gate ignored -> counts[0]++;
case Field.Mux ignored -> counts[1]++;
case Field.Curve curve -> counts[2] += curve.knots().size();
default -> {
}
}
for (Field child : FieldMacros.children(field)) {
collect(child, distinct, shared, counts);
}
}
private static long emitted(Field field, Map<Field, Long> sizes) {
Long cached = sizes.get(field);
if (cached != null) {
return cached;
}
long total = 1;
for (Field child : FieldMacros.children(field)) {
total += child instanceof Field.Shared ? 1 : emitted(child, sizes);
}
sizes.put(field, total);
return total;
}
private static int depth(Field field, Map<Field, Integer> depths) {
Integer cached = depths.get(field);
if (cached != null) {
return cached;
}
int deepest = 0;
for (Field child : FieldMacros.children(field)) {
deepest = Math.max(deepest, depth(child, depths));
}
depths.put(field, deepest + 1);
return deepest + 1;
}
private static int fileDepth(Field field, Map<Field, Integer> depths) {
Integer cached = depths.get(field);
if (cached != null) {
return cached;
}
int deepest = 0;
for (Field child : FieldMacros.children(field)) {
deepest = Math.max(deepest, child instanceof Field.Shared ? 1 : fileDepth(child, depths));
}
depths.put(field, deepest + 1);
return deepest + 1;
}
}
}
@@ -0,0 +1,258 @@
package art.arcane.iris.pack.datapack.export.compile.terrain;
import art.arcane.iris.generation.hydrology.config.IrisBankStyle;
import art.arcane.iris.generation.hydrology.config.IrisHydrology;
import art.arcane.iris.generation.hydrology.config.IrisHydrologyDeformation;
import art.arcane.iris.generation.hydrology.config.IrisHydrologyTier;
import art.arcane.iris.generation.terrain.IrisDimension;
import art.arcane.iris.pack.datapack.DataVersion;
import art.arcane.iris.pack.datapack.export.compile.noise.NoiseRegistry;
import art.arcane.iris.pack.datapack.export.ir.Axis;
import art.arcane.iris.pack.datapack.export.ir.CostClass;
import art.arcane.iris.pack.datapack.export.ir.ExportDiagnostic;
import art.arcane.iris.pack.datapack.export.ir.ExportLimit;
import art.arcane.iris.pack.datapack.export.ir.Field;
import art.arcane.iris.pack.datapack.export.ir.FieldEvaluator;
import art.arcane.iris.pack.datapack.export.ir.FieldValidator;
import art.arcane.iris.pack.datapack.export.ir.NoiseDef;
import art.arcane.iris.pack.datapack.export.lower.ExportCapabilities;
import art.arcane.volmlib.util.collection.KList;
import org.junit.Test;
import java.util.ArrayList;
import java.util.EnumSet;
import java.util.List;
import java.util.Map;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertTrue;
public class RiverCompilerTest {
private static final int SEA_LEVEL = 63;
private static final int WIDTH_REGION = 768;
private static final int RUN_LIMIT = 96;
private static final double HALF_WIDTH = 5.0;
private static final double TOLERANCE = 1.0e-3;
@Test
public void riverWidthConstantAlongIsoline() {
NoiseRegistry registry = registry();
IrisHydrology hydrology = hydrology(tier(5000, HALF_WIDTH, HALF_WIDTH, 2, 8, IrisBankStyle.SMOOTH));
Field carved = compile(new Field.Const(SEA_LEVEL + 2.0), hydrology, registry, DataVersion.V26_3, new ArrayList<>());
Map<String, NoiseDef> noises = TerrainTestSupport.noises(registry);
boolean[][] wet = new boolean[WIDTH_REGION][WIDTH_REGION];
for (int x = 0; x < WIDTH_REGION; x++) {
for (int z = 0; z < WIDTH_REGION; z++) {
wet[x][z] = sample(carved, noises, DataVersion.V26_3, x, z) < SEA_LEVEL - 0.5;
}
}
List<Double> widths = new ArrayList<>();
for (int z = RUN_LIMIT; z < WIDTH_REGION - RUN_LIMIT; z += 2) {
int x = 0;
while (x < WIDTH_REGION) {
if (!wet[x][z]) {
x++;
continue;
}
int start = x;
while (x < WIDTH_REGION && wet[x][z]) {
x++;
}
if (start == 0 || x == WIDTH_REGION) {
continue;
}
double across = x - start;
int middle = (start + x - 1) / 2;
int low = z;
int high = z;
while (low > z - RUN_LIMIT && wet[middle][low - 1]) {
low--;
}
while (high < z + RUN_LIMIT && wet[middle][high + 1]) {
high++;
}
double along = low == z - RUN_LIMIT || high == z + RUN_LIMIT ? Double.POSITIVE_INFINITY : high - low + 1.0;
widths.add(1.0 / Math.sqrt(1.0 / (across * across) + 1.0 / (along * along)));
}
}
double mean = widths.stream().mapToDouble(Double::doubleValue).average().orElseThrow();
double variance = widths.stream().mapToDouble(width -> (width - mean) * (width - mean)).average().orElseThrow();
double variation = Math.sqrt(variance) / mean;
assertTrue("only " + widths.size() + " channel crossings", widths.size() >= 100);
assertTrue("mean width " + mean, Math.abs(mean - 2.0 * HALF_WIDTH) <= 2.0);
assertTrue("width CV " + variation + " over " + widths.size() + " crossings", variation <= 0.15);
}
@Test
public void riverBedNeverBelowSeaLevelMinusDepth() {
NoiseRegistry registry = registry();
Field natural = rollingHeight(registry, 30.0);
Field carved = compile(natural, overworldHydrology(), registry, DataVersion.V26_3, new ArrayList<>());
Map<String, NoiseDef> noises = TerrainTestSupport.noises(registry);
double deepest = 0.5 * 18.0;
int flooded = 0;
for (int x = 0; x < 320; x += 2) {
for (int z = 0; z < 320; z += 2) {
double ground = sample(natural, noises, DataVersion.V26_3, x, z);
double bed = sample(carved, noises, DataVersion.V26_3, x, z);
assertTrue("bed " + bed + " under ground " + ground + " at " + x + "," + z, bed >= Math.min(ground, SEA_LEVEL - deepest) - TOLERANCE);
assertTrue("bed " + bed + " raised above ground " + ground + " at " + x + "," + z, bed <= ground + TOLERANCE);
if (ground > SEA_LEVEL && bed < SEA_LEVEL - 0.5) {
flooded++;
}
}
}
assertTrue("no lowland channel reaches the sea", flooded > 0);
}
@Test
public void uplandChannelsAreDryGullies() {
NoiseRegistry registry = registry();
double ground = SEA_LEVEL + 80.0;
Field carved = compile(new Field.Const(ground), overworldHydrology(), registry, DataVersion.V26_3, new ArrayList<>());
Map<String, NoiseDef> noises = TerrainTestSupport.noises(registry);
double gully = 3.0 + 0.5 * 9.0;
int carvedColumns = 0;
int columns = 0;
for (int x = 0; x < 256; x += 2) {
for (int z = 0; z < 256; z += 2) {
double bed = sample(carved, noises, DataVersion.V26_3, x, z);
columns++;
assertTrue("upland bed " + bed + " at " + x + "," + z + " reaches the sea", bed > SEA_LEVEL + 0.5);
assertTrue("gully " + (ground - bed) + " deeper than " + gully, ground - bed <= gully + TOLERANCE);
if (bed < ground - 0.5) {
carvedColumns++;
}
}
}
assertTrue("only " + carvedColumns + " of " + columns + " upland columns carved", carvedColumns >= columns / 100);
}
@Test
public void riverRootIsTwoDimensional() {
DataVersion target = DataVersion.V26_3;
NoiseRegistry registry = registry();
Field carved = compile(rollingHeight(registry, 30.0), overworldHydrology(), registry, target, new ArrayList<>());
assertEquals(RiverCompiler.CARVED_HEIGHT, ((Field.Shared) carved).name());
assertEquals(EnumSet.of(Axis.X, Axis.Z), carved.axes());
FieldValidator.requireTwoDimensional(carved, "height");
}
@Test
public void noRiversWhenHydrologyDisabled() {
Field natural = new Field.Const(SEA_LEVEL + 2.0);
for (IrisHydrology hydrology : new IrisHydrology[]{null, overworldHydrology().setEnabled(false)}) {
NoiseRegistry registry = registry();
List<ExportDiagnostic> diagnostics = new ArrayList<>();
Field result = compile(natural, hydrology, registry, DataVersion.V26_3, diagnostics);
assertSame(natural, result);
assertTrue(registry.definitions().isEmpty());
assertTrue(diagnostics.isEmpty());
}
}
@Test
public void riversReportDrainageAndElevatedWaterLimits() {
List<ExportDiagnostic> diagnostics = new ArrayList<>();
compile(new Field.Const(SEA_LEVEL + 2.0), overworldHydrology(), registry(), DataVersion.V26_3, diagnostics);
assertEquals(List.of(ExportLimit.ELEVATED_WATER, ExportLimit.RIVER_DRAINAGE), diagnostics.stream().map(ExportDiagnostic::limit).toList());
assertEquals("dimensions/rivers/hydrology", diagnostics.getFirst().resource());
}
@Test
public void expensiveChildrenOnlyBehindMuxOrGate() {
IrisHydrology hydrology = hydrology(
tier(900, 0.5, 2.5, 1, 8, IrisBankStyle.SMOOTH),
tier(2000, 1.0, 4.0, 1, 12, IrisBankStyle.LINEAR),
tier(5000, 2.5, 9.0, 2, 32, IrisBankStyle.CONCAVE),
tier(20000, 3.0, 10.0, 2, 24, IrisBankStyle.TERRACED),
tier(60000, 4.0, 12.0, 3, 16, IrisBankStyle.CLIFF),
tier(200000, 9.0, 18.0, 3, 0, IrisBankStyle.SMOOTH));
DataVersion target = DataVersion.V26_3;
NoiseRegistry registry = registry();
Field natural = rollingHeight(registry, 30.0);
assertEquals(CostClass.EXPENSIVE, natural.cost());
Field carved = compile(natural, hydrology, registry, target, new ArrayList<>());
List<String> violations = TerrainTestSupport.unguardedExpensiveBranches(carved);
assertTrue(target + " " + violations, violations.isEmpty());
}
@Test
public void riverCompileIsDeterministic() {
List<Field> fields = new ArrayList<>();
List<List<NoiseDef>> definitions = new ArrayList<>();
List<Double> samples = new ArrayList<>();
for (int run = 0; run < 2; run++) {
NoiseRegistry registry = registry();
Field carved = compile(rollingHeight(registry, 30.0), overworldHydrology(), registry, DataVersion.V26_3, new ArrayList<>());
fields.add(carved);
definitions.add(registry.definitions());
samples.add(sample(carved, TerrainTestSupport.noises(registry), DataVersion.V26_3, 137, -411));
}
assertEquals(fields.getFirst(), fields.getLast());
assertEquals(definitions.getFirst(), definitions.getLast());
assertEquals(samples.getFirst(), samples.getLast());
}
private static Field compile(Field natural, IrisHydrology hydrology, NoiseRegistry registry, DataVersion target, List<ExportDiagnostic> diagnostics) {
IrisDimension dimension = new IrisDimension();
dimension.setLoadKey("rivers");
dimension.setFluidHeight(SEA_LEVEL);
dimension.setHydrology(hydrology);
return new RiverCompiler(diagnostics).compile(natural, dimension, registry, ExportCapabilities.forTarget(target));
}
private static double sample(Field field, Map<String, NoiseDef> noises, DataVersion target, int x, int z) {
return FieldEvaluator.sample(field, noises, TerrainTestSupport.SEED, target, x, 0, z);
}
private static NoiseRegistry registry() {
return new NoiseRegistry(TerrainTestSupport.NAMESPACE);
}
private static Field rollingHeight(NoiseRegistry registry, double amplitude) {
String warp = registry.register(new NoiseDef("test/height_warp", -8, List.of(1.0)));
String hills = registry.register(new NoiseDef("test/height", -7, List.of(1.0, 0.5)));
Field shift = FieldMacros.scale(new Field.Noise(warp, 1.0, 0.0, null, null, null), 0.5);
Field noise = new Field.Noise(hills, 1.0, 0.0, shift, null, shift);
return new Field.Shared(HeightCompiler.HEIGHT, FieldMacros.sum(List.of(new Field.Const(SEA_LEVEL), FieldMacros.scale(noise, amplitude))));
}
private static IrisHydrology overworldHydrology() {
return hydrology(
tier(900, 0.5, 2.5, 1, 8, IrisBankStyle.SMOOTH).setDepthRatio(0.4),
tier(5000, 2.5, 9.0, 2, 32, IrisBankStyle.SMOOTH),
tier(200000, 9.0, 18.0, 3, 48, IrisBankStyle.SMOOTH).setDepthRatio(0.5));
}
private static IrisHydrology hydrology(IrisHydrologyTier... tiers) {
return new IrisHydrology()
.setEnabled(true)
.setDensity(0.5)
.setTiers(new KList<>(tiers))
.setDeformation(new IrisHydrologyDeformation().setBankSlope(0.2).setBankSteepFactor(3.5).setBankNoise(0.2));
}
private static IrisHydrologyTier tier(double catchment, double minHalfWidth, double maxHalfWidth, int inset, int bankBand, IrisBankStyle style) {
return new IrisHydrologyTier()
.setName("tier_" + (long) catchment)
.setMinCatchment(catchment)
.setHalfWidth(new KList<>(minHalfWidth, maxHalfWidth))
.setWidthFactor(1.2)
.setDepthRatio(0.45)
.setInset(inset)
.setBankBand(bankBand)
.setBankStyle(style);
}
}
@@ -0,0 +1,170 @@
package art.arcane.iris.pack.datapack.export.compile.terrain;
import art.arcane.iris.pack.datapack.DataVersion;
import art.arcane.iris.pack.datapack.export.ExportTestPacks;
import art.arcane.iris.pack.datapack.export.WorldgenExportMode;
import art.arcane.iris.pack.datapack.export.WorldgenExportProgress;
import art.arcane.iris.pack.datapack.export.WorldgenExportRequest;
import art.arcane.iris.pack.datapack.export.compile.DimensionStage;
import art.arcane.iris.pack.datapack.export.compile.PackCompileContext;
import art.arcane.iris.pack.datapack.export.compile.PackCompiler;
import art.arcane.iris.pack.datapack.export.ir.Axis;
import art.arcane.iris.pack.datapack.export.ir.ExportDiagnostic;
import art.arcane.iris.pack.datapack.export.ir.ExportLimit;
import art.arcane.iris.pack.datapack.export.ir.Field;
import art.arcane.iris.pack.datapack.export.lower.ExportCapabilities;
import art.arcane.iris.pack.loading.IrisData;
import art.arcane.iris.testsupport.CompatTestPlatform;
import art.arcane.iris.testsupport.PlatformLeakGuard;
import org.junit.ClassRule;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertTrue;
public class RiverStageTest {
@ClassRule
public static final PlatformLeakGuard PLATFORM_GUARD = PlatformLeakGuard.clean();
@Rule
public TemporaryFolder temporaryFolder = new TemporaryFolder();
@Rule
public ExportTestPacks.BoundPlatform platform = new ExportTestPacks.BoundPlatform();
@Test
public void stageCarvesRiversIntoTheTerrainHeight() throws Exception {
IrisData data = IrisData.openRuntime(pack(true));
try {
DataVersion target = DataVersion.V26_3;
PackCompileContext context = terrainContext(data, target);
Field natural = context.height();
new RiverStage().apply(context);
Field.Shared carved = (Field.Shared) context.height();
assertEquals(RiverCompiler.CARVED_HEIGHT, carved.name());
assertSame(natural, ((Field.Binary) carved.expr()).left());
assertSame(natural, context.naturalHeight());
assertFalse(carved.axes().contains(Axis.Y));
List<String> violations = TerrainTestSupport.unguardedExpensiveBranches(carved);
assertTrue(target + " " + violations, violations.isEmpty());
List<ExportLimit> limits = context.diagnostics().stream().map(ExportDiagnostic::limit).toList();
assertTrue(limits.toString(), limits.contains(ExportLimit.RIVER_DRAINAGE));
assertTrue(limits.toString(), limits.contains(ExportLimit.ELEVATED_WATER));
} finally {
data.close();
}
}
@Test
public void aquiferSurfaceCarvesTheClimateHeight() throws Exception {
IrisData data = IrisData.openRuntime(pack(true));
try {
PackCompileContext context = terrainContext(data, DataVersion.V26_3);
Field estimate = context.surfaceEstimate();
assertSame(context.climateHeight(), estimate);
assertEquals(ClimateHeightCompiler.CLIMATE_HEIGHT, ((Field.Shared) estimate).name());
new RiverStage().apply(context);
assertSame(estimate, context.climateHeight());
Field.Shared surface = (Field.Shared) context.surfaceEstimate();
assertEquals(RiverCompiler.CARVED_HEIGHT + "/estimate", surface.name());
assertSame(estimate, ((Field.Binary) surface.expr()).left());
assertTrue(TerrainTestSupport.contains(surface, estimate));
assertFalse(TerrainTestSupport.contains(surface, context.naturalHeight()));
for (Field node : TerrainTestSupport.nodes(surface)) {
assertFalse("aquifer surface interpolates " + node, node instanceof Field.Grid grid && grid.cellXZ() != 4);
}
for (int x = -900; x <= 900; x += 97) {
double carved = TerrainTestSupport.sample(context.height(), context.noises(), DataVersion.V26_3, x, 0, x / 2);
double natural = TerrainTestSupport.sample(context.naturalHeight(), context.noises(), DataVersion.V26_3, x, 0, x / 2);
double cut = TerrainTestSupport.sample(surface, context.noises(), DataVersion.V26_3, x, 0, x / 2)
- TerrainTestSupport.sample(estimate, context.noises(), DataVersion.V26_3, x, 0, x / 2);
assertTrue("estimate cut " + cut, cut <= 1.0e-3);
assertTrue("carved cut " + (carved - natural), carved - natural <= 1.0e-3);
}
} finally {
data.close();
}
}
@Test
public void stageKeepsTheHeightWithoutHydrology() throws Exception {
IrisData data = IrisData.openRuntime(pack(false));
try {
PackCompileContext context = terrainContext(data, DataVersion.V26_3);
Field natural = context.height();
int noises = context.noises().definitions().size();
new RiverStage().apply(context);
assertSame(natural, context.height());
assertEquals(noises, context.noises().definitions().size());
} finally {
data.close();
}
}
@Test
public void defaultCompilerRunsRiversAfterTerrain() throws Exception {
IrisData data = IrisData.openRuntime(pack(true));
try {
List<String> stages = new ArrayList<>();
WorldgenExportProgress progress = new WorldgenExportProgress() {
@Override
public void stage(String stage) {
stages.add(stage);
}
@Override
public void resources(int done, int total) {
}
};
PackCompiler.create().compile(context(data, DataVersion.V26_3), progress);
assertEquals(stages.indexOf("terrain") + 1, stages.indexOf("rivers"));
} finally {
data.close();
}
}
private File pack(boolean hydrology) throws Exception {
File pack = TerrainTestPacks.twoBiomes(temporaryFolder.newFolder("pack"),
TerrainTestPacks.link("hills", 0, 40), TerrainTestPacks.link("hills", 20, 90));
TerrainTestPacks.generator(pack, "hills", TerrainTestPacks.twoLayers("BILINEAR_STARCAST_9", 12));
String water = hydrology ? ",\"hydrology\":{\"enabled\":true,\"density\":0.5}" : "";
CompatTestPlatform.write(pack, "dimensions/" + TerrainTestPacks.DIMENSION + ".json", "{\"regions\":[\"region\"]" + water + "}");
return pack;
}
private static PackCompileContext terrainContext(IrisData data, DataVersion target) {
PackCompileContext context = context(data, target);
new DimensionStage().apply(context);
context.setBiomeCodes(TerrainTestSupport.twoBiomeCodes(context.noises(), 0.0));
new TerrainStage().apply(context);
return context;
}
private static PackCompileContext context(IrisData data, DataVersion target) {
return PackCompileContext.builder()
.data(data)
.dimension(data.getDimensionLoader().load(TerrainTestPacks.DIMENSION, false))
.capabilities(ExportCapabilities.forTarget(target))
.namespace(WorldgenExportRequest.DEFAULT_NAMESPACE)
.mode(WorldgenExportMode.PRESET)
.styles(TerrainTestSupport.noiseStyles())
.build();
}
}
@@ -0,0 +1,185 @@
package art.arcane.iris.pack.datapack.export.compile.terrain;
import art.arcane.iris.pack.datapack.DataVersion;
import art.arcane.iris.pack.datapack.export.ExportTestPacks;
import art.arcane.iris.pack.datapack.export.ExportTestStyles;
import art.arcane.iris.pack.datapack.export.WorldgenExportMode;
import art.arcane.iris.pack.datapack.export.WorldgenExportProgress;
import art.arcane.iris.pack.datapack.export.WorldgenExportRequest;
import art.arcane.iris.pack.datapack.export.compile.CompileStage;
import art.arcane.iris.pack.datapack.export.compile.DimensionStage;
import art.arcane.iris.pack.datapack.export.compile.PackCompileContext;
import art.arcane.iris.pack.datapack.export.compile.PackCompiler;
import art.arcane.iris.pack.datapack.export.compile.biome.BiomeCodes;
import art.arcane.iris.pack.datapack.export.compile.biome.BiomeStage;
import art.arcane.iris.pack.datapack.export.ir.Axis;
import art.arcane.iris.pack.datapack.export.ir.ExportIr;
import art.arcane.iris.pack.datapack.export.ir.Field;
import art.arcane.iris.pack.datapack.export.lower.ExportCapabilities;
import art.arcane.iris.pack.loading.IrisData;
import art.arcane.iris.testsupport.PlatformLeakGuard;
import org.junit.ClassRule;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
public class TerrainStageTest {
@ClassRule
public static final PlatformLeakGuard PLATFORM_GUARD = PlatformLeakGuard.clean();
@Rule
public TemporaryFolder temporaryFolder = new TemporaryFolder();
@Rule
public ExportTestPacks.BoundPlatform platform = new ExportTestPacks.BoundPlatform();
@Test
public void stageFillsTheHeightAndVolumetricSlots() throws Exception {
IrisData data = IrisData.openRuntime(featurePack());
try {
PackCompileContext context = context(data, DataVersion.V26_3);
new DimensionStage().apply(context);
context.setBiomeCodes(TerrainTestSupport.twoBiomeCodes(context.noises(), 0.0));
new TerrainStage().apply(context);
assertEquals(HeightCompiler.HEIGHT, ((Field.Shared) context.height()).name());
assertFalse(context.height().axes().contains(Axis.Y));
assertTrue(context.volumetric().axes().contains(Axis.Y));
assertFalse(context.noises().definitions().isEmpty());
} finally {
data.close();
}
}
@Test
public void expensiveChildrenOnlyBehindMuxOrGate() throws Exception {
IrisData data = IrisData.openRuntime(featurePack());
try {
DataVersion target = DataVersion.V26_3;
PackCompileContext context = context(data, target);
new DimensionStage().apply(context);
BiomeCodes codes = TerrainTestSupport.twoBiomeCodes(context.noises(), 0.0);
context.setBiomeCodes(codes);
new TerrainStage().apply(context);
List<String> violations = new ArrayList<>(TerrainTestSupport.unguardedExpensiveBranches(context.height()));
violations.addAll(TerrainTestSupport.unguardedExpensiveBranches(context.volumetric()));
assertTrue(target + " " + violations, violations.isEmpty());
} finally {
data.close();
}
}
@Test
public void defaultCompilerRunsTerrainBetweenBiomesAndRivers() throws Exception {
File pack = ExportTestPacks.basic(temporaryFolder.newFolder("pack"));
IrisData data = IrisData.openRuntime(pack);
try {
List<String> stages = new ArrayList<>();
WorldgenExportProgress progress = new WorldgenExportProgress() {
@Override
public void stage(String stage) {
stages.add(stage);
}
@Override
public void resources(int done, int total) {
}
};
ExportIr ir = PackCompiler.create().compile(ExportTestPacks.contextBuilder(data, DataVersion.V26_3).styles(new ExportTestStyles()).build(), progress);
assertEquals(stages.toString(), stages.indexOf("biomes") + 1, stages.indexOf("terrain"));
assertEquals(stages.toString(), stages.indexOf("terrain") + 1, stages.indexOf("rivers"));
assertEquals(stages.toString(), stages.indexOf("rivers") + 1, stages.indexOf("caves"));
assertEquals(new Field.Grid(new Field.Shared(HeightCompiler.HEIGHT, new Field.Const(63.0)), 16, 1), ir.router().chunkSurfaceLevel());
} finally {
data.close();
}
}
@Test
public void terrainRunsOnBaseCodesAndBiomeCodesRebindToTheClimateHeight() throws Exception {
File pack = ExportTestPacks.basic(temporaryFolder.newFolder("pack"));
IrisData data = IrisData.openRuntime(pack);
try {
PackCompileContext context = ExportTestPacks.contextBuilder(data, DataVersion.V26_3).styles(new ExportTestStyles()).build();
new DimensionStage().apply(context);
new BiomeStage().apply(context);
BiomeCodes base = context.biomeCodes();
new TerrainStage().apply(context);
BiomeCodes bound = context.biomeCodes();
assertEquals(base, context.baseBiomeCodes());
assertEquals(ClimateHeightCompiler.CLIMATE_HEIGHT, ((Field.Shared) context.climateHeight()).name());
assertTrue(TerrainTestSupport.contains(bound.surfaceCode(), context.climateHeight()));
assertFalse(TerrainTestSupport.contains(bound.surfaceCode(), context.height()));
assertFalse(TerrainTestSupport.contains(BandTreeCompiler.selector(base), context.height()));
} finally {
data.close();
}
}
@Test
public void stageCompileIsDeterministic() throws Exception {
IrisData data = IrisData.openRuntime(featurePack());
try {
List<Field> heights = new ArrayList<>();
List<Field> volumes = new ArrayList<>();
List<Object> noises = new ArrayList<>();
for (int run = 0; run < 2; run++) {
PackCompileContext context = context(data, DataVersion.V26_3);
new DimensionStage().apply(context);
context.setBiomeCodes(TerrainTestSupport.twoBiomeCodes(context.noises(), 0.0));
CompileStage stage = new TerrainStage();
stage.apply(context);
heights.add(context.height());
volumes.add(context.volumetric());
noises.add(context.noises().definitions());
}
assertEquals(heights.getFirst(), heights.getLast());
assertEquals(volumes.getFirst(), volumes.getLast());
assertEquals(noises.getFirst(), noises.getLast());
} finally {
data.close();
}
}
private File featurePack() throws Exception {
File pack = TerrainTestPacks.twoBiomes(temporaryFolder.newFolder("pack"), "", "");
TerrainTestPacks.generator(pack, "hills", TerrainTestPacks.twoLayers("BILINEAR_STARCAST_9", 12));
TerrainTestPacks.generator(pack, "ranges", TerrainTestPacks.twoLayers("BILINEAR_STARCAST_12", 200));
TerrainTestPacks.generator(pack, "terraces", """
{"interpolator":{"function":"BILINEAR_STARCAST_9","horizontalScale":26},"cliffHeightMin":20,"cliffHeightMax":80,
"surfaceDetail":0.5,"composite":[{"style":{"style":"SIMPLEX"},"seed":3,"bezier":true},{"style":{"style":"PERLIN"},"seed":4,"exponent":1.5}]}""");
TerrainTestPacks.biome(pack, "a", "{\"name\":\"A\",\"generators\":[" + TerrainTestPacks.link("hills", 20, 140) + ","
+ TerrainTestPacks.link("ranges", 0, 60) + "],\"terrain3D\":" + TerrainTestPacks.TERRAIN3D + "}");
TerrainTestPacks.biome(pack, "b", "{\"name\":\"B\",\"generators\":[" + TerrainTestPacks.link("terraces", 5, 70) + "],"
+ "\"terrain3D\":{\"amplitude\":12,\"horizontalScale\":32,\"verticalScale\":12},"
+ "\"floatingChildBiomes\":[{\"biome\":\"a\",\"topShapeMode\":\"BIOME\"},{\"topShapeMode\":\"NOISE\",\"rarity\":3}]}");
return pack;
}
private static PackCompileContext context(IrisData data, DataVersion target) {
return PackCompileContext.builder()
.data(data)
.dimension(data.getDimensionLoader().load(TerrainTestPacks.DIMENSION, false))
.capabilities(ExportCapabilities.forTarget(target))
.namespace(WorldgenExportRequest.DEFAULT_NAMESPACE)
.mode(WorldgenExportMode.PRESET)
.styles(TerrainTestSupport.noiseStyles())
.build();
}
}
@@ -0,0 +1,46 @@
package art.arcane.iris.pack.datapack.export.compile.terrain;
import art.arcane.iris.testsupport.CompatTestPlatform;
import java.io.File;
import java.io.IOException;
final class TerrainTestPacks {
static final String DIMENSION = "main";
static final String TERRAIN3D = """
{"amplitude": 24, "horizontalScale": 64, "verticalScale": 16, "crackDepth": 12, "crackWidth": 3,
"crackScale": 48, "minimumSlope": 0.1, "slopeFade": 0.3, "fluidClearance": 4, "fluidFade": 12}""";
private TerrainTestPacks() {
}
static File twoBiomes(File pack, String generatorA, String generatorB) throws IOException {
CompatTestPlatform.write(pack, "dimensions/" + DIMENSION + ".json", "{\"regions\":[\"region\"]}");
CompatTestPlatform.write(pack, "regions/region.json", "{\"landBiomes\":[\"a\",\"b\"]}");
CompatTestPlatform.write(pack, "biomes/a.json", "{\"name\":\"A\",\"generators\":[" + generatorA + "]}");
CompatTestPlatform.write(pack, "biomes/b.json", "{\"name\":\"B\",\"generators\":[" + generatorB + "]}");
return pack;
}
static void biome(File pack, String key, String json) throws IOException {
CompatTestPlatform.write(pack, "biomes/" + key + ".json", json);
}
static void generator(File pack, String key, String json) throws IOException {
CompatTestPlatform.write(pack, "generators/" + key + ".json", json);
}
static String singleLayer(String function, double radius, String style) {
return "{\"interpolator\":{\"function\":\"" + function + "\",\"horizontalScale\":" + radius + "},"
+ "\"composite\":[{\"style\":{\"style\":\"" + style + "\"},\"seed\":3}]}";
}
static String twoLayers(String function, double radius) {
return "{\"interpolator\":{\"function\":\"" + function + "\",\"horizontalScale\":" + radius + "},"
+ "\"composite\":[{\"style\":{\"style\":\"SIMPLEX\"},\"seed\":3},{\"style\":{\"style\":\"PERLIN\"},\"seed\":5,\"opacity\":0.5}]}";
}
static String link(String generator, int min, int max) {
return "{\"generator\":\"" + generator + "\",\"min\":" + min + ",\"max\":" + max + "}";
}
}
@@ -0,0 +1,203 @@
package art.arcane.iris.pack.datapack.export.compile.terrain;
import art.arcane.iris.pack.datapack.DataVersion;
import art.arcane.iris.pack.datapack.export.compile.biome.BiomeCodes;
import art.arcane.iris.pack.datapack.export.compile.noise.NoiseRegistry;
import art.arcane.iris.pack.datapack.export.compile.noise.StyleCompiler;
import art.arcane.iris.pack.datapack.export.ir.ClimateLayout;
import art.arcane.iris.pack.datapack.export.ir.CostClass;
import art.arcane.iris.pack.datapack.export.ir.Field;
import art.arcane.iris.pack.datapack.export.ir.FieldEvaluator;
import art.arcane.iris.pack.datapack.export.ir.NoiseDef;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Deque;
import java.util.IdentityHashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
final class TerrainTestSupport {
static final String NAMESPACE = "iris_export";
static final long SEED = 1337L;
static final String SELECTOR_ID = "test/selector";
static final NoiseDef SELECTOR = new NoiseDef(SELECTOR_ID, -8, List.of(1.0, 1.0));
private TerrainTestSupport() {
}
static StyleCompiler noiseStyles() {
return (style, seedSalt, registry, capabilities) -> {
String id = registry.register(new NoiseDef("test/style_" + Long.toHexString(seedSalt), -5, List.of(1.0)));
Field noise = new Field.Noise(id, 1.0 / style.getZoom(), 0.0, null, null, null);
return new Field.Binary(Field.BinaryOp.ADD, new Field.Const(0.5), new Field.Binary(Field.BinaryOp.MUL, new Field.Const(0.5), noise));
};
}
static StyleCompiler constantStyles(double value) {
return (style, seedSalt, registry, capabilities) -> new Field.Const(value);
}
static BiomeCodes twoBiomeCodes(NoiseRegistry registry, double threshold) {
String selector = registry.register(SELECTOR);
Field code = new Field.Partition(new Field.Noise(selector, 1.0, 0.0, null, null, null), List.of(threshold),
List.of(new Field.Const(0.1), new Field.Const(0.3)));
ClimateLayout layout = new ClimateLayout(List.of(
new ClimateLayout.ClimateEntry(NAMESPACE + ":a", ClimateLayout.ClimateAxis.TEMPERATURE, 0.05, 0.15),
new ClimateLayout.ClimateEntry(NAMESPACE + ":b", ClimateLayout.ClimateAxis.TEMPERATURE, 0.25, 0.35)));
return new BiomeCodes(code, new Field.Const(0.0), new Field.Const(0.0), layout, Map.of(NAMESPACE + ":a", "a", NAMESPACE + ":b", "b"));
}
static BiomeCodes singleBiomeCodes(String loadKey) {
ClimateLayout layout = new ClimateLayout(List.of(
new ClimateLayout.ClimateEntry(NAMESPACE + ":" + loadKey, ClimateLayout.ClimateAxis.TEMPERATURE, -1.0, 1.0)));
return new BiomeCodes(new Field.Const(0.0), new Field.Const(0.0), new Field.Const(0.0), layout, Map.of(NAMESPACE + ":" + loadKey, loadKey));
}
static double sample(Field field, NoiseRegistry registry, DataVersion target, int x, int y, int z) {
return FieldEvaluator.sample(field, noises(registry), SEED, target, x, y, z);
}
static Map<String, NoiseDef> noises(NoiseRegistry registry) {
Map<String, NoiseDef> noises = new LinkedHashMap<>();
for (NoiseDef definition : registry.definitions()) {
noises.put(registry.namespace() + ":" + definition.id(), definition);
}
return noises;
}
static boolean contains(Field root, Field target) {
Set<Field> visited = Collections.newSetFromMap(new IdentityHashMap<>());
Deque<Field> pending = new ArrayDeque<>();
pending.push(root);
while (!pending.isEmpty()) {
Field field = pending.pop();
if (field.equals(target)) {
return true;
}
if (visited.add(field)) {
for (Field child : FieldMacros.children(field)) {
pending.push(child);
}
}
}
return false;
}
static List<Field> nodes(Field root) {
List<Field> nodes = new ArrayList<>();
Set<Field> visited = Collections.newSetFromMap(new IdentityHashMap<>());
Deque<Field> pending = new ArrayDeque<>();
pending.push(root);
while (!pending.isEmpty()) {
Field field = pending.pop();
if (visited.add(field)) {
nodes.add(field);
for (Field child : FieldMacros.children(field)) {
pending.push(child);
}
}
}
return nodes;
}
static List<String> unguardedExpensiveBranches(Field root) {
List<String> violations = new ArrayList<>();
walkGuards(root, "root", violations, Collections.newSetFromMap(new IdentityHashMap<>()));
return violations;
}
private static void walkGuards(Field field, String path, List<String> violations, Set<Field> visited) {
if (!visited.add(field)) {
return;
}
switch (field) {
case Field.Binary binary -> {
if (binary.op() == Field.BinaryOp.MUL) {
checkProduct(binary, path, violations);
}
walkGuards(binary.left(), path + "/left", violations, visited);
walkGuards(binary.right(), path + "/right", violations, visited);
}
case Field.Lerp lerp -> {
checkBranch(lerp.first(), path + "/lerp.first", violations);
checkBranch(lerp.second(), path + "/lerp.second", violations);
walkGuards(lerp.alpha(), path + "/alpha", violations, visited);
walkGuards(lerp.first(), path + "/first", violations, visited);
walkGuards(lerp.second(), path + "/second", violations, visited);
}
case Field.RangeIf rangeIf -> {
checkBranch(rangeIf.inRange(), path + "/range.in", violations);
checkBranch(rangeIf.outOfRange(), path + "/range.out", violations);
walkGuards(rangeIf.input(), path + "/input", violations, visited);
walkGuards(rangeIf.inRange(), path + "/in", violations, visited);
walkGuards(rangeIf.outOfRange(), path + "/out", violations, visited);
}
case Field.Partition partition -> {
for (Field leaf : partition.leaves()) {
checkBranch(leaf, path + "/partition.leaf", violations);
}
walkGuards(partition.input(), path + "/input", violations, visited);
}
case Field.Unary unary -> walkGuards(unary.input(), path + "/" + unary.op(), violations, visited);
case Field.Clamp clamp -> walkGuards(clamp.input(), path + "/clamp", violations, visited);
case Field.Round round -> {
walkGuards(round.input(), path + "/round", violations, visited);
walkGuards(round.multiple(), path + "/multiple", violations, visited);
}
case Field.Curve curve -> {
walkGuards(curve.input(), path + "/curve", violations, visited);
for (Field.Knot knot : curve.knots()) {
walkGuards(knot.value(), path + "/knot", violations, visited);
}
}
case Field.Mux mux -> {
walkGuards(mux.index(), path + "/index", violations, visited);
for (Field selected : mux.cases()) {
walkGuards(selected, path + "/case", violations, visited);
}
}
case Field.Gate gate -> {
walkGuards(gate.condition(), path + "/condition", violations, visited);
walkGuards(gate.expr(), path + "/gated", violations, visited);
}
case Field.Grid grid -> walkGuards(grid.expr(), path + "/grid", violations, visited);
case Field.Shared shared -> walkGuards(shared.expr(), path + "/" + shared.name(), violations, visited);
case Field.Slice slice -> walkGuards(slice.expr(), path + "/slice", violations, visited);
case Field.TopSurface topSurface -> walkGuards(topSurface.density(), path + "/top", violations, visited);
case Field.Noise noise -> {
for (Field shift : new Field[]{noise.shiftX(), noise.shiftY(), noise.shiftZ()}) {
if (shift != null) {
walkGuards(shift, path + "/shift", violations, visited);
}
}
}
case Field.Const ignored -> {
}
case Field.Coord ignored -> {
}
case Field.Ref ignored -> {
}
}
}
private static void checkProduct(Field.Binary product, String path, List<String> violations) {
boolean leftShields = product.left() instanceof Field.Const || FieldMacros.isGuard(product.left());
boolean rightShields = product.right() instanceof Field.Const || FieldMacros.isGuard(product.right());
if (!rightShields) {
checkBranch(product.left(), path + "/mul.left", violations);
}
if (!leftShields) {
checkBranch(product.right(), path + "/mul.right", violations);
}
}
private static void checkBranch(Field branch, String path, List<String> violations) {
if (branch.cost() == CostClass.EXPENSIVE && !FieldMacros.isGuard(branch)) {
violations.add(path + " " + branch.getClass().getSimpleName());
}
}
}
@@ -0,0 +1,252 @@
package art.arcane.iris.pack.datapack.export.compile.terrain;
import art.arcane.iris.generation.noise.IrisGeneratorStyle;
import art.arcane.iris.generation.noise.NoiseStyle;
import art.arcane.iris.generation.terrain.IrisDimension;
import art.arcane.iris.pack.datapack.DataVersion;
import art.arcane.iris.pack.datapack.export.ExportTestPacks;
import art.arcane.iris.pack.datapack.export.compile.biome.BiomeCodes;
import art.arcane.iris.pack.datapack.export.compile.noise.NoiseRegistry;
import art.arcane.iris.pack.datapack.export.compile.noise.NoiseStyleCompiler;
import art.arcane.iris.pack.datapack.export.compile.noise.StyleCompiler;
import art.arcane.iris.pack.datapack.export.compile.noise.ValueDistributionFit;
import art.arcane.iris.pack.datapack.export.ir.Axis;
import art.arcane.iris.pack.datapack.export.ir.ExportDiagnostic;
import art.arcane.iris.pack.datapack.export.ir.ExportLimit;
import art.arcane.iris.pack.datapack.export.ir.Field;
import art.arcane.iris.pack.datapack.export.lower.ExportCapabilities;
import art.arcane.iris.pack.loading.IrisData;
import art.arcane.iris.testsupport.PlatformLeakGuard;
import art.arcane.volmlib.util.math.RNG;
import art.arcane.volmlib.util.noise.CNG;
import org.junit.ClassRule;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.SplittableRandom;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
public class VolumetricCompilerTest {
private static final ExportCapabilities CAPABILITIES = ExportCapabilities.forTarget(DataVersion.V26_3);
private static final int SEA_LEVEL = 63;
private static final double VOLUME_AMPLITUDE = 24.0;
private static final double VOLUME_SCALE = 96.0;
private static final double CRACK_DEPTH = 12.0;
private static final double CRACK_WIDTH = 15.0;
private static final double CRACK_SCALE = 96.0;
private static final long MARGINAL_SEED = 8191L;
private static final int MARGINAL_SAMPLES = 6000;
private static final int MARGINAL_SPAN = 1 << 20;
private static final int SHAPED_FLOOR = SEA_LEVEL + 8;
private static final int SHAPED_CEILING = 320;
private static final String ISLAND = """
{"name":"Sky","floatingChildBiomes":[{"topShapeMode":"FLAT","maxTopHeight":10,"minHeightAboveSurface":160,
"maxHeightAboveSurface":160,"bottomDepthMin":4,"bottomDepthMax":4,"footprintThreshold":0.5}]}""";
@ClassRule
public static final PlatformLeakGuard PLATFORM_GUARD = PlatformLeakGuard.clean();
@Rule
public TemporaryFolder temporaryFolder = new TemporaryFolder();
@Rule
public ExportTestPacks.BoundPlatform platform = new ExportTestPacks.BoundPlatform();
@Test
public void terrain3dVariantsSitBehindGates() throws Exception {
File pack = TerrainTestPacks.twoBiomes(temporaryFolder.newFolder("pack"),
TerrainTestPacks.link("hills", 20, 140), TerrainTestPacks.link("hills", 10, 60));
TerrainTestPacks.generator(pack, "hills", TerrainTestPacks.singleLayer("BILINEAR_STARCAST_9", 12, "SIMPLEX"));
TerrainTestPacks.biome(pack, "a", "{\"name\":\"A\",\"generators\":[" + TerrainTestPacks.link("hills", 20, 140)
+ "],\"terrain3D\":" + TerrainTestPacks.TERRAIN3D + "}");
TerrainTestPacks.biome(pack, "b", "{\"name\":\"B\",\"generators\":[" + TerrainTestPacks.link("hills", 10, 60)
+ "],\"terrain3D\":{\"amplitude\":12,\"horizontalScale\":32,\"verticalScale\":12}}");
IrisData data = IrisData.openRuntime(pack);
try {
NoiseRegistry registry = new NoiseRegistry(TerrainTestSupport.NAMESPACE);
BiomeCodes codes = TerrainTestSupport.twoBiomeCodes(registry, 0.0);
Compiled compiled = compile(data, registry, TerrainTestSupport.noiseStyles(), codes);
int shaped = 0;
assertTrue(compiled.volumetric().axes().contains(Axis.Y));
assertTrue(TerrainTestSupport.unguardedExpensiveBranches(compiled.volumetric()).toString(),
TerrainTestSupport.unguardedExpensiveBranches(compiled.volumetric()).isEmpty());
for (int x = -800; x <= 800; x += 37) {
for (int z = -800; z <= 800; z += 41) {
assertEquals(0.0, TerrainTestSupport.sample(compiled.volumetric(), registry, DataVersion.V26_3, x, SEA_LEVEL + 4, z), 0.0);
double surface = TerrainTestSupport.sample(compiled.height(), registry, DataVersion.V26_3, x, 0, z);
double displacement = TerrainTestSupport.sample(compiled.volumetric(), registry, DataVersion.V26_3, x, (int) surface, z);
assertTrue("displacement " + displacement, Math.abs(displacement) <= 24.0 + 12.0 + 1.0e-3);
if (Math.abs(displacement) > 0.5) {
shaped++;
}
}
}
assertTrue("terrain3D should shape some columns, got " + shaped, shaped > 0);
} finally {
data.close();
}
}
@Test
public void displacementFollowsTheVolumetricNoiseMarginal() throws Exception {
IrisData data = IrisData.openRuntime(uniformTerrain3d(temporaryFolder.newFolder("pack"), VOLUME_AMPLITUDE, 0));
try {
NoiseRegistry registry = new NoiseRegistry(TerrainTestSupport.NAMESPACE);
Compiled compiled = compile(data, registry, NoiseStyleCompiler.create(new ArrayList<>()), TerrainTestSupport.twoBiomeCodes(registry, 0.0));
CNG iris = new IrisGeneratorStyle(NoiseStyle.SIMPLEX).createNoCache(new RNG(MARGINAL_SEED), data);
SplittableRandom random = new SplittableRandom(MARGINAL_SEED);
double[] exported = new double[MARGINAL_SAMPLES];
double[] expected = new double[MARGINAL_SAMPLES];
for (int index = 0; index < MARGINAL_SAMPLES; index++) {
int x = random.nextInt(-MARGINAL_SPAN, MARGINAL_SPAN);
int y = random.nextInt(SHAPED_FLOOR, SHAPED_CEILING);
int z = random.nextInt(-MARGINAL_SPAN, MARGINAL_SPAN);
exported[index] = TerrainTestSupport.sample(compiled.volumetric(), registry, DataVersion.V26_3, x, y, z) / VOLUME_AMPLITUDE;
expected[index] = Math.clamp(iris.noiseFastSigned3D(x * 64.0 / VOLUME_SCALE, y * 64.0 / VOLUME_SCALE, z * 64.0 / VOLUME_SCALE), -1.0, 1.0);
}
Arrays.sort(exported);
Arrays.sort(expected);
for (double level : new double[]{0.02, 0.05, 0.25, 0.75, 0.95, 0.98}) {
assertEquals("quantile " + level, ValueDistributionFit.quantile(expected, level), ValueDistributionFit.quantile(exported, level), 0.05);
}
} finally {
data.close();
}
}
@Test
public void fissuresOpenAsOftenAsTheVolumetricCrackNoiseAllows() throws Exception {
IrisData data = IrisData.openRuntime(uniformTerrain3d(temporaryFolder.newFolder("pack"), 0, CRACK_DEPTH));
try {
NoiseRegistry registry = new NoiseRegistry(TerrainTestSupport.NAMESPACE);
Compiled compiled = compile(data, registry, NoiseStyleCompiler.create(new ArrayList<>()), TerrainTestSupport.twoBiomeCodes(registry, 0.0));
CNG iris = new IrisGeneratorStyle(NoiseStyle.SIMPLEX).createNoCache(new RNG(MARGINAL_SEED), data);
SplittableRandom random = new SplittableRandom(MARGINAL_SEED);
int exported = 0;
int expected = 0;
for (int index = 0; index < MARGINAL_SAMPLES; index++) {
int x = random.nextInt(-MARGINAL_SPAN, MARGINAL_SPAN);
int y = random.nextInt(SHAPED_FLOOR, SHAPED_CEILING);
int z = random.nextInt(-MARGINAL_SPAN, MARGINAL_SPAN);
if (TerrainTestSupport.sample(compiled.volumetric(), registry, DataVersion.V26_3, x, y, z) < 0.0) {
exported++;
}
double frequency = 64.0 / CRACK_SCALE;
double distance = CRACK_SCALE * 0.5 * Math.clamp(iris.noiseFastSigned3D(x * frequency, y * frequency * 0.25, z * frequency), -1.0, 1.0);
if (Math.abs(distance) < CRACK_WIDTH) {
expected++;
}
}
assertEquals(expected / (double) MARGINAL_SAMPLES, exported / (double) MARGINAL_SAMPLES, 0.02);
} finally {
data.close();
}
}
@Test
public void floatingIslandIsSolidBetweenItsBaseAndTop() throws Exception {
File pack = TerrainTestPacks.twoBiomes(temporaryFolder.newFolder("pack"), "", "");
TerrainTestPacks.biome(pack, "b", ISLAND);
IrisData data = IrisData.openRuntime(pack);
try {
NoiseRegistry registry = new NoiseRegistry(TerrainTestSupport.NAMESPACE);
BiomeCodes codes = TerrainTestSupport.twoBiomeCodes(registry, 0.0);
Compiled compiled = compile(data, registry, TerrainTestSupport.constantStyles(0.75), codes);
int island = 0;
int ground = 0;
assertTrue(TerrainTestSupport.unguardedExpensiveBranches(compiled.volumetric()).isEmpty());
for (int x = -1200; x <= 1200; x += 53) {
double code = TerrainTestSupport.sample(codes.surfaceCode(), registry, DataVersion.V26_3, x, 0, 9);
boolean sky = code > 0.2;
for (int y : new int[]{150, 155, 156, 163, 170, 171, 180}) {
double density = SEA_LEVEL - y + TerrainTestSupport.sample(compiled.volumetric(), registry, DataVersion.V26_3, x, y, 9);
boolean solid = density > 0.0;
assertEquals("x " + x + " y " + y + " density " + density, sky && y >= 156 && y <= 170, solid);
}
if (sky) {
island++;
} else {
ground++;
}
}
assertTrue(island > 0 && ground > 0);
} finally {
data.close();
}
}
@Test
public void unexportedIslandFeaturesReportDiagnostics() throws Exception {
File pack = TerrainTestPacks.twoBiomes(temporaryFolder.newFolder("pack"), "", "");
TerrainTestPacks.biome(pack, "b", """
{"name":"Sky","floatingChildBiomes":[{"topShapeMode":"BIOME","wallWarpStyle":{"style":"SIMPLEX"},"localFluidHeight":3}]}""");
IrisData data = IrisData.openRuntime(pack);
try {
NoiseRegistry registry = new NoiseRegistry(TerrainTestSupport.NAMESPACE);
List<ExportDiagnostic> diagnostics = new ArrayList<>();
IrisDimension dimension = data.getDimensionLoader().load(TerrainTestPacks.DIMENSION, false);
BiomeCodes codes = TerrainTestSupport.twoBiomeCodes(registry, 0.0);
TerrainHeight height = new HeightCompiler(TerrainTestSupport.noiseStyles(), diagnostics).compile(codes, dimension, data, registry, CAPABILITIES);
new VolumetricCompiler(TerrainTestSupport.noiseStyles(), diagnostics).compile(height, codes, dimension, data, registry, CAPABILITIES);
assertEquals(1, diagnostics.size());
assertEquals(ExportLimit.FLOATING_ISLAND, diagnostics.getFirst().limit());
assertEquals("biomes/b", diagnostics.getFirst().resource());
} finally {
data.close();
}
}
@Test
public void packWithoutVolumetricFeaturesIsNeutral() throws Exception {
File pack = TerrainTestPacks.twoBiomes(temporaryFolder.newFolder("pack"),
TerrainTestPacks.link("hills", 0, 20), TerrainTestPacks.link("hills", 40, 90));
TerrainTestPacks.generator(pack, "hills", TerrainTestPacks.twoLayers("BILINEAR_STARCAST_9", 12));
IrisData data = IrisData.openRuntime(pack);
try {
NoiseRegistry registry = new NoiseRegistry(TerrainTestSupport.NAMESPACE);
Compiled compiled = compile(data, registry, TerrainTestSupport.noiseStyles(), TerrainTestSupport.twoBiomeCodes(registry, 0.0));
assertEquals(new Field.Const(0.0), compiled.volumetric());
} finally {
data.close();
}
}
private static File uniformTerrain3d(File folder, double amplitude, double crackDepth) throws Exception {
File pack = TerrainTestPacks.twoBiomes(folder, TerrainTestPacks.link("flat", 100, 100), TerrainTestPacks.link("flat", 100, 100));
TerrainTestPacks.generator(pack, "flat", TerrainTestPacks.singleLayer("BILINEAR_STARCAST_9", 12, "FLAT"));
String terrain = "{\"amplitude\":" + amplitude + ",\"horizontalScale\":" + VOLUME_SCALE + ",\"verticalScale\":" + VOLUME_SCALE
+ ",\"densityStyle\":{\"style\":\"SIMPLEX\"},\"crackDepth\":" + crackDepth + ",\"crackWidth\":" + CRACK_WIDTH
+ ",\"crackScale\":" + CRACK_SCALE + ",\"crackStyle\":{\"style\":\"SIMPLEX\"},\"minimumSlope\":0,\"fluidClearance\":0,\"fluidFade\":1}";
for (String key : new String[]{"a", "b"}) {
TerrainTestPacks.biome(pack, key, "{\"name\":\"" + key + "\",\"generators\":[" + TerrainTestPacks.link("flat", 100, 100)
+ "],\"terrain3D\":" + terrain + "}");
}
return pack;
}
private static Compiled compile(IrisData data, NoiseRegistry registry, StyleCompiler styles, BiomeCodes codes) {
IrisDimension dimension = data.getDimensionLoader().load(TerrainTestPacks.DIMENSION, false);
List<ExportDiagnostic> diagnostics = new ArrayList<>();
TerrainHeight terrain = new HeightCompiler(styles, diagnostics).compile(codes, dimension, data, registry, CAPABILITIES);
Field volumetric = new VolumetricCompiler(styles, diagnostics).compile(terrain, codes, dimension, data, registry, CAPABILITIES);
return new Compiled(terrain.height(), volumetric);
}
private record Compiled(Field height, Field volumetric) {
}
}
@@ -0,0 +1,363 @@
package art.arcane.iris.pack.datapack.export.emit;
import art.arcane.iris.pack.datapack.DataVersion;
import art.arcane.iris.pack.datapack.export.ir.Axis;
import art.arcane.iris.pack.datapack.export.ir.Field;
import art.arcane.iris.pack.datapack.export.ir.NoiseDef;
import art.arcane.iris.pack.datapack.export.lower.ExportCapabilities;
import art.arcane.iris.pack.datapack.export.lower.VanillaBounds;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import org.junit.Test;
import java.util.ArrayList;
import java.util.List;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertThrows;
import static org.junit.Assert.assertTrue;
public class DensityFunctionEmitter26_3Test {
private static final String NAMESPACE = "iris_export";
private static final Field NOISE = new Field.Noise("iris_export:base", 0.25, 0.0, null, null, null);
private static final Field NOISE_3D = new Field.Noise("iris_export:base", 0.25, 0.5, null, null, null);
private static final String NOISE_JSON = "{\"type\":\"minecraft:noise\",\"noise\":\"iris_export:base\",\"xz_scale\":0.25,\"y_scale\":0.0}";
private static final String NOISE_3D_JSON = "{\"type\":\"minecraft:noise\",\"noise\":\"iris_export:base\",\"xz_scale\":0.25,\"y_scale\":0.5}";
@Test
public void disjointMinMaxEmitsTheInputThatAlwaysWins() {
Field band = new Field.Clamp(NOISE, 0.25, 0.75);
DensityFunctionEmitter emitter = DensityFunctionEmitter.forTarget(ExportCapabilities.forTarget(DataVersion.V26_3), NAMESPACE,
VanillaBounds.of(NAMESPACE, List.of(new NoiseDef("base", 0, List.of(1.0)))));
JsonElement clamp = emitter.emit(band, new FunctionTable(NAMESPACE));
assertEquals(clamp, emitter.emit(new Field.Binary(Field.BinaryOp.MAX, band, new Field.Const(0.0)), new FunctionTable(NAMESPACE)));
assertEquals(clamp, emitter.emit(new Field.Binary(Field.BinaryOp.MIN, new Field.Const(2.0), band), new FunctionTable(NAMESPACE)));
assertEquals(json("0.125"), emitter.emit(new Field.Binary(Field.BinaryOp.MIN, new Field.Const(0.125), band), new FunctionTable(NAMESPACE)));
assertEquals("minecraft:max", type(emitter.emit(new Field.Binary(Field.BinaryOp.MAX, band, new Field.Const(0.5)), new FunctionTable(NAMESPACE))));
}
@Test
public void sub26_3UsesLeftRight() {
JsonElement emitted = emit(new Field.Binary(Field.BinaryOp.SUB, NOISE, new Field.Const(2.0)));
assertEquals(json("{\"type\":\"minecraft:sub\",\"left\":" + NOISE_JSON + ",\"right\":2.0}"), emitted);
}
@Test
public void unaryUsesInput() {
JsonElement emitted = emit(new Field.Unary(Field.UnaryOp.HALF_NEG, NOISE));
assertEquals(json("{\"type\":\"minecraft:half_negative\",\"input\":" + NOISE_JSON + "}"), emitted);
assertEquals("minecraft:negate", type(emit(new Field.Unary(Field.UnaryOp.NEG, NOISE))));
assertEquals("minecraft:quarter_negative", type(emit(new Field.Unary(Field.UnaryOp.QUARTER_NEG, NOISE))));
}
@Test
public void powUsesBaseAndExponent() {
Field base = new Field.Clamp(NOISE, 0.0, 1.0);
JsonObject emitted = emit(new Field.Binary(Field.BinaryOp.POW, base, new Field.Const(1.5))).getAsJsonObject();
assertEquals("minecraft:pow", emitted.get("type").getAsString());
assertEquals(emit(base), emitted.get("base"));
assertEquals(1.5, emitted.get("exponent").getAsDouble(), 0.0);
}
@Test
public void noiseIsAlwaysARegisteredReference() {
Field shifted = new Field.Noise("iris_export:base", 0.25, 0.0, new Field.Const(3.0), null, NOISE);
JsonObject emitted = emit(shifted).getAsJsonObject();
assertEquals("minecraft:noise", emitted.get("type").getAsString());
assertEquals("iris_export:base", emitted.get("noise").getAsString());
assertEquals(3.0, emitted.get("shift_x").getAsDouble(), 0.0);
assertEquals(json(NOISE_JSON), emitted.get("shift_z"));
assertTrue(!emitted.has("shift_y"));
}
@Test
public void coordinateEmitsGradient() {
Field coord = new Field.Coord(Axis.X, Field.Tiling.REPEAT, 0.0, 512.0, 0.0, 1.0);
assertEquals(json("{\"type\":\"minecraft:gradient\",\"axis\":\"x\",\"tiling\":\"repeat\",\"from_coordinate\":0,\"to_coordinate\":512,\"from_value\":0.0,\"to_value\":1.0}"), emit(coord));
Field fractional = new Field.Coord(Axis.X, Field.Tiling.CLAMP, 0.5, 512.0, 0.0, 1.0);
assertThrows(IllegalArgumentException.class, () -> emit(fractional));
}
@Test
public void gridCustomCell26_3EmitsCellSizes() {
JsonElement emitted = emit(new Field.Grid(NOISE_3D, 8, 4));
assertEquals(json("{\"type\":\"minecraft:interpolated\",\"input\":" + NOISE_3D_JSON + ",\"cell_size_xz\":8,\"cell_size_y\":4}"), emitted);
}
@Test
public void muxOn26_3IsSplineWithIdentityKnots() {
Field second = new Field.Noise("iris_export:other", 0.5, 0.0, null, null, null);
JsonObject emitted = emit(new Field.Mux(NOISE, List.of(NOISE_3D, second))).getAsJsonObject();
assertEquals("minecraft:spline", emitted.get("type").getAsString());
JsonObject spline = emitted.getAsJsonObject("spline");
assertEquals(json(NOISE_JSON), spline.get("coordinate"));
JsonArray points = spline.getAsJsonArray("points");
List<Double> locations = new ArrayList<>();
for (JsonElement point : points) {
locations.add(point.getAsJsonObject().get("location").getAsDouble());
}
assertEquals(List.of(0.0, 0.25, 0.75, 1.0), locations);
assertEquals(identity(NOISE_3D_JSON, "-2.0", "2.0"), points.get(0).getAsJsonObject().get("value"));
assertEquals(0.0, points.get(1).getAsJsonObject().get("value").getAsDouble(), 0.0);
assertEquals(0.0, points.get(2).getAsJsonObject().get("value").getAsDouble(), 0.0);
assertEquals(identity(emit(second).toString(), "-2.0", "2.0"), points.get(3).getAsJsonObject().get("value"));
for (JsonElement point : points) {
assertEquals(0.0, point.getAsJsonObject().get("derivative").getAsDouble(), 0.0);
}
}
@Test
public void gateOn26_3IsSplineGate() {
JsonObject emitted = emit(new Field.Gate(NOISE, NOISE_3D)).getAsJsonObject();
JsonObject spline = emitted.getAsJsonObject("spline");
assertEquals(json(NOISE_JSON), spline.get("coordinate"));
JsonArray points = spline.getAsJsonArray("points");
assertEquals(2, points.size());
assertEquals(Float.MIN_VALUE, points.get(0).getAsJsonObject().get("location").getAsFloat(), 0.0f);
assertEquals(0.0, points.get(0).getAsJsonObject().get("value").getAsDouble(), 0.0);
assertEquals(Math.nextUp(Float.MIN_VALUE), points.get(1).getAsJsonObject().get("location").getAsFloat(), 0.0f);
assertEquals(identity(NOISE_3D_JSON, "-2.0", "2.0"), points.get(1).getAsJsonObject().get("value"));
}
@Test
public void identitySplineSpansAPowerOfTwoAroundTheCaseRange() {
Field scaled = new Field.Binary(Field.BinaryOp.ADD, new Field.Const(1.0), new Field.Binary(Field.BinaryOp.MUL, new Field.Const(4.0), NOISE));
Field reference = new Field.Ref("minecraft:overworld/continents");
JsonArray points = emit(new Field.Mux(NOISE, List.of(scaled, reference))).getAsJsonObject().getAsJsonObject("spline").getAsJsonArray("points");
assertEquals(identity(emit(scaled).toString(), "-8.0", "8.0"), points.get(0).getAsJsonObject().get("value"));
assertEquals(identity("\"minecraft:overworld/continents\"", "-1000000.0", "1000000.0"), points.get(3).getAsJsonObject().get("value"));
}
@Test
public void identitySplineIsExactForCodesInFloat() {
Field code = new Field.Clamp(NOISE, -1.0, 1.0);
JsonObject identity = emit(new Field.Mux(NOISE, List.of(code, code))).getAsJsonObject().getAsJsonObject("spline")
.getAsJsonArray("points").get(0).getAsJsonObject().getAsJsonObject("value");
for (float value : new float[]{-0.99f, -0.5f, -0.0123f, 0.0f, 0.2731f, 0.731f, 0.99f}) {
assertEquals(value, vanillaSpline(identity, value), 1.0e-6f);
}
}
@Test
public void identitySplineIsExactForIndexValuesInFloat() {
List<Field> leaves = new ArrayList<>();
List<Double> thresholds = new ArrayList<>();
for (int index = 0; index <= 312; index++) {
leaves.add(new Field.Const(index));
if (index > 0) {
thresholds.add(-1.0 + 2.0 * index / 313.0);
}
}
Field index = new Field.Partition(NOISE, thresholds, leaves);
JsonObject identity = emit(new Field.Mux(NOISE, List.of(index, index))).getAsJsonObject().getAsJsonObject("spline")
.getAsJsonArray("points").get(0).getAsJsonObject().getAsJsonObject("value");
for (int value = 0; value <= 312; value++) {
assertEquals(value, vanillaSpline(identity, value), 0.0f);
}
}
@Test
public void muxTakesTheCaseAtTheRoundedClampedIndex() {
JsonObject spline = emit(new Field.Mux(NOISE, List.of(new Field.Clamp(NOISE, -1.0, 1.0), new Field.Clamp(NOISE, -1.0, 1.0),
new Field.Clamp(NOISE, -1.0, 1.0)))).getAsJsonObject().getAsJsonObject("spline");
JsonArray points = spline.getAsJsonArray("points");
List<Double> locations = new ArrayList<>();
for (JsonElement point : points) {
locations.add(point.getAsJsonObject().get("location").getAsDouble());
}
assertEquals(List.of(0.0, 0.25, 0.75, 1.0, 1.25, 1.75, 2.0), locations);
assertTrue(points.get(0).getAsJsonObject().get("value").isJsonObject());
assertTrue(points.get(locations.size() - 1).getAsJsonObject().get("value").isJsonObject());
assertEquals(0.0f, derivative(points, 0), 0.0f);
assertEquals(0.0f, derivative(points, locations.size() - 1), 0.0f);
}
@Test
public void constantMuxCasesAreKnotValues() {
JsonArray points = emit(new Field.Mux(NOISE, List.of(new Field.Const(3.0), NOISE_3D))).getAsJsonObject()
.getAsJsonObject("spline").getAsJsonArray("points");
assertEquals(3.0, points.get(0).getAsJsonObject().get("value").getAsDouble(), 0.0);
assertTrue(points.get(3).getAsJsonObject().get("value").isJsonObject());
}
@Test
public void singleCaseMuxEmitsTheCase() {
assertEquals(json(NOISE_3D_JSON), emit(new Field.Mux(NOISE, List.of(NOISE_3D))));
}
@Test
public void gateOpensForEveryPositiveCondition() {
JsonObject spline = emit(new Field.Gate(NOISE, new Field.Clamp(NOISE, -1.0, 1.0))).getAsJsonObject().getAsJsonObject("spline");
JsonArray points = spline.getAsJsonArray("points");
assertEquals(0.0f, vanillaSpline(spline, 0.0f), 0.0f);
assertEquals(0.0f, vanillaSpline(spline, -3.0f), 0.0f);
assertTrue(location(points, 0) > 0.0f);
assertEquals(Math.nextUp(Float.MIN_VALUE), location(points, 1), 0.0f);
assertTrue(points.get(1).getAsJsonObject().get("value").isJsonObject());
}
@Test
public void curveEmitsNestedSplines() {
Field.Curve inner = new Field.Curve(NOISE_3D, List.of(new Field.Knot(-1.0, new Field.Const(0.0), 0.0), new Field.Knot(1.0, new Field.Const(0.4), 0.1)));
Field.Curve outer = new Field.Curve(NOISE, List.of(new Field.Knot(-1.0, new Field.Const(-0.5), 0.0), new Field.Knot(0.0, inner, 0.0)));
JsonElement expected = json("{\"type\":\"minecraft:spline\",\"spline\":{\"coordinate\":" + NOISE_JSON + ",\"points\":["
+ "{\"location\":-1.0,\"value\":-0.5,\"derivative\":0.0},"
+ "{\"location\":0.0,\"value\":{\"coordinate\":" + NOISE_3D_JSON + ",\"points\":[{\"location\":-1.0,\"value\":0.0,\"derivative\":0.0},{\"location\":1.0,\"value\":0.4,\"derivative\":0.1}]},\"derivative\":0.0}]}}");
assertEquals(expected, emit(outer));
}
@Test
public void partitionIsIntervalSelect() {
Field partition = new Field.Partition(NOISE, List.of(-0.2, 0.3), List.of(new Field.Const(-1.0), new Field.Const(0.0), new Field.Const(1.0)));
assertEquals(json("{\"type\":\"minecraft:interval_select\",\"input\":" + NOISE_JSON + ",\"thresholds\":[-0.2,0.3],\"functions\":[-1.0,0.0,1.0]}"), emit(partition));
}
@Test
public void sharedEmitsCacheAndNamedFile() {
FunctionTable table = new FunctionTable(NAMESPACE);
Field.Shared shared = new Field.Shared("terrain/height", new Field.Binary(Field.BinaryOp.MUL, NOISE, new Field.Const(16.0)));
JsonElement emitted = emitter().emit(new Field.Binary(Field.BinaryOp.ADD, shared, new Field.Binary(Field.BinaryOp.MUL, shared, new Field.Const(2.0))), table);
assertEquals(1, table.files().size());
assertEquals(json("{\"type\":\"minecraft:cache\",\"input\":{\"type\":\"minecraft:mul\",\"left\":" + NOISE_JSON + ",\"right\":16.0}}"), table.files().get("terrain/height"));
JsonObject root = emitted.getAsJsonObject();
assertEquals("iris_export:terrain/height", root.get("left").getAsString());
assertEquals("iris_export:terrain/height", root.getAsJsonObject("right").get("left").getAsString());
}
@Test
public void constantsRoundTripAsFloat26_3() {
assertEquals("0.1", JsonNumbers.constant(0.1, DataVersion.V26_3).toString());
assertEquals("0.12345679", JsonNumbers.constant(0.1234567890123, DataVersion.V26_3).toString());
assertEquals("0.0001", JsonNumbers.constant(1.0e-4, DataVersion.V26_3).toString());
assertEquals("2.0", JsonNumbers.constant(2.0, DataVersion.V26_3).toString());
assertEquals("0.0", JsonNumbers.constant(-0.0, DataVersion.V26_3).toString());
assertEquals(0.1, JsonNumbers.constant(0.1, DataVersion.V26_3).getAsDouble(), 0.0);
assertEquals("0.1", emit(new Field.Const(0.1)).toString());
}
@Test
public void constantBeyondLimitThrows() {
assertEquals("1000000.0", JsonNumbers.constant(1.0e6, DataVersion.V26_3).toString());
assertThrows(IllegalArgumentException.class, () -> JsonNumbers.constant(1.0e6 + 1.0, DataVersion.V26_3));
assertThrows(IllegalArgumentException.class, () -> JsonNumbers.constant(-2.0e6, DataVersion.V26_3));
assertThrows(IllegalArgumentException.class, () -> emit(new Field.Clamp(NOISE, -2.0e6, 0.0)));
}
@Test
public void sqrtAndLogInputsAreClampedToTheirDomain() {
JsonObject sqrt = emit(new Field.Unary(Field.UnaryOp.SQRT, NOISE)).getAsJsonObject();
JsonObject sqrtInput = sqrt.getAsJsonObject("input");
assertEquals("minecraft:clamp", sqrtInput.get("type").getAsString());
assertEquals(0.0, sqrtInput.get("min").getAsDouble(), 0.0);
JsonObject log = emit(new Field.Unary(Field.UnaryOp.LOG, NOISE)).getAsJsonObject();
JsonObject logInput = log.getAsJsonObject("input");
assertEquals("minecraft:clamp", logInput.get("type").getAsString());
assertTrue(logInput.get("min").getAsDouble() > 0.0);
Field positive = new Field.Clamp(NOISE, 0.5, 1.0);
assertEquals(emit(positive), emit(new Field.Unary(Field.UnaryOp.SQRT, positive)).getAsJsonObject().get("input"));
}
@Test
public void powBaseIsClampedWhenExponentIsFractional() {
JsonObject fractional = emit(new Field.Binary(Field.BinaryOp.POW, NOISE, new Field.Const(1.5))).getAsJsonObject();
assertEquals("minecraft:clamp", fractional.getAsJsonObject("base").get("type").getAsString());
assertEquals(0.0, fractional.getAsJsonObject("base").get("min").getAsDouble(), 0.0);
JsonObject negative = emit(new Field.Binary(Field.BinaryOp.POW, NOISE, new Field.Const(-0.5))).getAsJsonObject();
assertTrue(negative.getAsJsonObject("base").get("min").getAsDouble() > 0.0);
JsonObject integral = emit(new Field.Binary(Field.BinaryOp.POW, NOISE, new Field.Const(3.0))).getAsJsonObject();
assertEquals(json(NOISE_JSON), integral.get("base"));
}
@Test
public void remainingNodesUseTheirCodecFields() {
assertEquals(json("{\"type\":\"minecraft:clamp\",\"input\":" + NOISE_JSON + ",\"min\":-0.5,\"max\":0.5}"), emit(new Field.Clamp(NOISE, -0.5, 0.5)));
assertEquals(json("{\"type\":\"minecraft:lerp\",\"alpha\":" + NOISE_JSON + ",\"first\":1.0,\"second\":2.0}"), emit(new Field.Lerp(NOISE, new Field.Const(1.0), new Field.Const(2.0))));
assertEquals(json("{\"type\":\"minecraft:floor\",\"input\":" + NOISE_JSON + ",\"multiple\":2.0}"), emit(new Field.Round(Field.RoundMode.FLOOR, NOISE, new Field.Const(2.0))));
assertEquals(json("{\"type\":\"minecraft:range_choice\",\"input\":" + NOISE_JSON + ",\"min_inclusive\":0.0,\"max_exclusive\":1.0,\"when_in_range\":1.0,\"when_out_of_range\":0.0}"),
emit(new Field.RangeIf(NOISE, 0.0, 1.0, new Field.Const(1.0), new Field.Const(0.0))));
assertEquals(json("{\"type\":\"minecraft:slice\",\"axis\":\"y\",\"coordinate\":64,\"input\":" + NOISE_3D_JSON + "}"), emit(new Field.Slice(NOISE_3D, Axis.Y, 64)));
assertEquals(json("{\"type\":\"minecraft:find_top_surface\",\"density\":" + NOISE_3D_JSON + ",\"upper_bound\":320.0,\"lower_bound\":-64,\"cell_height\":8}"), emit(new Field.TopSurface(NOISE_3D, 320, -64, 8)));
assertEquals(json("\"minecraft:overworld/continents\""), emit(new Field.Ref("minecraft:overworld/continents")));
}
@Test
public void tableNamespaceMustMatchEmitter() {
assertThrows(IllegalArgumentException.class, () -> emitter().emit(NOISE, new FunctionTable("other")));
}
@Test
public void emissionIsDeterministic() {
Field.Shared shared = new Field.Shared("terrain/height", new Field.Binary(Field.BinaryOp.MUL, NOISE, new Field.Const(16.0)));
Field root = new Field.Mux(new Field.Clamp(NOISE, 0.0, 1.0), List.of(shared, new Field.Gate(NOISE, new Field.Unary(Field.UnaryOp.SQRT, shared))));
FunctionTable first = new FunctionTable(NAMESPACE);
FunctionTable second = new FunctionTable(NAMESPACE);
String firstRoot = emitter().emit(root, first).toString();
String secondRoot = emitter().emit(root, second).toString();
assertEquals(firstRoot, secondRoot);
assertEquals(first.files().toString(), second.files().toString());
}
private static JsonElement identity(String coordinate, String low, String high) {
return json("{\"coordinate\":" + coordinate + ",\"points\":[{\"location\":" + low + ",\"value\":" + low + ",\"derivative\":1.0},{\"location\":"
+ high + ",\"value\":" + high + ",\"derivative\":1.0}]}");
}
private static float vanillaSpline(JsonObject spline, float coordinate) {
JsonArray points = spline.getAsJsonArray("points");
int last = points.size() - 1;
int start = -1;
for (int index = 0; index <= last && coordinate >= location(points, index); index++) {
start = index;
}
if (start < 0) {
return value(points, 0) + derivative(points, 0) * (coordinate - location(points, 0));
}
if (start == last) {
return value(points, last) + derivative(points, last) * (coordinate - location(points, last));
}
float low = location(points, start);
float high = location(points, start + 1);
float delta = (coordinate - low) / (high - low);
float first = value(points, start);
float second = value(points, start + 1);
float entry = derivative(points, start) * (high - low) - (second - first);
float exit = -derivative(points, start + 1) * (high - low) + (second - first);
return first + delta * (second - first) + delta * (1.0f - delta) * (entry + delta * (exit - entry));
}
private static float location(JsonArray points, int index) {
return points.get(index).getAsJsonObject().get("location").getAsFloat();
}
private static float derivative(JsonArray points, int index) {
return points.get(index).getAsJsonObject().get("derivative").getAsFloat();
}
private static float value(JsonArray points, int index) {
return points.get(index).getAsJsonObject().get("value").getAsFloat();
}
private static String type(JsonElement element) {
return element.getAsJsonObject().get("type").getAsString();
}
private static DensityFunctionEmitter emitter() {
return DensityFunctionEmitter.forTarget(ExportCapabilities.forTarget(DataVersion.V26_3), NAMESPACE, VanillaBounds.of(NAMESPACE, List.of()));
}
private static JsonElement emit(Field field) {
return emitter().emit(field, new FunctionTable(NAMESPACE));
}
private static JsonElement json(String text) {
return JsonParser.parseString(text);
}
}
@@ -0,0 +1,362 @@
package art.arcane.iris.pack.datapack.export.emit;
import art.arcane.iris.pack.datapack.DataVersion;
import art.arcane.iris.pack.datapack.export.ExportIrFixtures;
import art.arcane.iris.pack.datapack.export.WorldgenExportMode;
import art.arcane.iris.pack.datapack.export.ir.AquiferDef;
import art.arcane.iris.pack.datapack.export.ir.BinaryResource;
import art.arcane.iris.pack.datapack.export.ir.BiomeDef;
import art.arcane.iris.pack.datapack.export.ir.ClimateLayout;
import art.arcane.iris.pack.datapack.export.ir.DimensionDef;
import art.arcane.iris.pack.datapack.export.ir.ExportIr;
import art.arcane.iris.pack.datapack.export.ir.Field;
import art.arcane.iris.pack.datapack.export.ir.JsonResource;
import art.arcane.iris.pack.datapack.export.ir.MaterialProgram;
import art.arcane.iris.pack.datapack.export.ir.RouterDef;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import org.junit.Test;
import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.SortedMap;
import java.util.TreeSet;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertThrows;
import static org.junit.Assert.assertTrue;
public class Format26_3WriterTest {
private static final String SETTINGS = "data/iris_export/worldgen/noise_settings/flat.json";
private static final String PRESET = "data/iris_export/worldgen/world_preset/flat.json";
private static final String NORMAL_TAG = "data/minecraft/tags/worldgen/world_preset/normal.json";
private static final String DIMENSION = "data/iris_export/dimension/flat.json";
private static final String OVERWORLD = "data/minecraft/dimension/overworld.json";
private static final String DENSITY_PREFIX = "data/iris_export/worldgen/density_function/";
private static final String FEATURE = "data/iris_export/worldgen/feature/ore.json";
private static final String TEMPLATE = "data/iris_export/structure/ore.nbt";
@Test
public void writesTheIrisPackIcon() {
byte[] icon = write(fixture(WorldgenExportMode.OVERWORLD)).get("pack.png");
assertArrayEquals(new byte[]{(byte) 0x89, 'P', 'N', 'G', '\r', '\n', 0x1A, '\n'}, Arrays.copyOf(icon, 8));
assertEquals(128, ByteBuffer.wrap(icon, 16, 4).getInt());
assertEquals(128, ByteBuffer.wrap(icon, 20, 4).getInt());
}
@Test
public void forTargetSelectsTheFormatWriter() {
assertTrue(WorldgenJsonWriter.forTarget(DataVersion.V26_3) instanceof Format26_3Writer);
assertThrows(IllegalArgumentException.class, () -> WorldgenJsonWriter.forTarget(DataVersion.V26_2));
assertThrows(IllegalArgumentException.class, () -> WorldgenJsonWriter.forTarget(DataVersion.V26_1_2));
}
@Test
public void packMcmetaDeclaresFormatRange() {
JsonObject pack = json(write(fixture(WorldgenExportMode.PRESET)), "pack.mcmeta").getAsJsonObject("pack");
assertEquals(121, pack.get("min_format").getAsInt());
assertEquals(121, pack.get("max_format").getAsInt());
assertFalse(pack.has("pack_format"));
assertTrue(pack.get("description").getAsString().length() > 0);
}
@Test
public void packDescriptionTellsPlayersToKeepTheVanillaPack() {
String description = json(write(fixture(WorldgenExportMode.OVERWORLD)), "pack.mcmeta").getAsJsonObject("pack").get("description").getAsString();
assertTrue(description, description.contains("Keep Default selected"));
}
@Test
public void noiseFileUsesNormalNoiseParameters() {
JsonObject noise = json(write(fixture(WorldgenExportMode.PRESET)), "data/iris_export/worldgen/noise/flat/height.json");
assertEquals(JsonParser.parseString("{\"amplitude_modifiers\":[1.0,1.0,1.0],\"base_amplitude\":1.0,\"base_octave\":-7,\"normalize\":false,\"octave_count\":3}"), noise);
}
@Test
public void noiseSettingsRouterHasEightFields26_3() {
SortedMap<String, byte[]> files = write(fixture(WorldgenExportMode.PRESET));
JsonObject settings = json(files, SETTINGS);
JsonObject router = settings.getAsJsonObject("noise_router");
assertEquals(Set.of("temperature", "vegetation", "continents", "erosion", "depth", "ridges", "chunk_surface_level", "final_density"), router.keySet());
assertEquals(Set.of("barrier", "fluid_level_floodedness", "fluid_level_spread", "lava", "exclusion", "surface_level"), settings.getAsJsonObject("aquifers").keySet());
assertEquals(Set.of("aquifers", "default_block", "default_fluid", "disable_mob_generation", "legacy_random_source", "material_rule", "noise",
"noise_router", "sea_level", "spawn_target"), settings.keySet());
assertEquals(JsonParser.parseString("{\"height\":384,\"min_y\":-64}"), settings.get("noise"));
assertEquals("iris_export:flat", settings.get("material_rule").getAsString());
assertTrue(files.containsKey("data/iris_export/worldgen/material_rule/flat.json"));
assertEquals(ExportIrFixtures.FLUID_HEIGHT + 1, settings.get("sea_level").getAsInt());
assertEquals(0.0, router.get("temperature").getAsDouble(), 0.0);
assertResolves(files, router.get("final_density"));
assertResolves(files, router.get("chunk_surface_level"));
assertResolves(files, settings.getAsJsonObject("aquifers").get("surface_level"));
}
@Test
public void spawnTargetIsKeyedByRegisteredDensityFunctions() {
SortedMap<String, byte[]> files = write(fixture(WorldgenExportMode.PRESET));
JsonArray targets = json(files, SETTINGS).getAsJsonArray("spawn_target");
assertEquals(1, targets.size());
for (Map.Entry<String, JsonElement> entry : targets.get(0).getAsJsonObject().entrySet()) {
assertTrue(entry.getKey(), files.containsKey(DENSITY_PREFIX + entry.getKey().substring("iris_export:".length()) + ".json"));
JsonArray range = entry.getValue().getAsJsonArray();
assertTrue(range.get(0).getAsDouble() >= -2.0 && range.get(1).getAsDouble() <= 2.0);
assertTrue(range.get(0).getAsDouble() < range.get(1).getAsDouble());
}
}
@Test
public void presetModeWritesWorldPresetAndNormalTag() {
SortedMap<String, byte[]> files = write(fixture(WorldgenExportMode.PRESET));
JsonObject dimensions = json(files, PRESET).getAsJsonObject("dimensions");
assertEquals(Set.of("minecraft:overworld", "minecraft:the_nether", "minecraft:the_end"), dimensions.keySet());
JsonObject overworld = dimensions.getAsJsonObject("minecraft:overworld");
assertEquals("iris_export:flat", overworld.get("type").getAsString());
assertEquals("minecraft:noise", overworld.getAsJsonObject("generator").get("type").getAsString());
assertEquals("iris_export:flat", overworld.getAsJsonObject("generator").get("settings").getAsString());
assertEquals(JsonParser.parseString("{\"values\":[\"iris_export:flat\"]}"), json(files, NORMAL_TAG));
assertFalse(files.containsKey(DIMENSION));
assertFalse(files.containsKey(OVERWORLD));
}
@Test
public void dimensionModeWritesNamespacedDimension() {
SortedMap<String, byte[]> files = write(fixture(WorldgenExportMode.DIMENSION));
JsonObject stem = json(files, DIMENSION);
assertEquals("iris_export:flat", stem.get("type").getAsString());
assertFalse(files.containsKey(PRESET));
assertFalse(files.containsKey(NORMAL_TAG));
assertFalse(files.containsKey(OVERWORLD));
}
@Test
public void overworldModeOverridesMinecraftDimension() {
SortedMap<String, byte[]> files = write(fixture(WorldgenExportMode.OVERWORLD));
JsonObject stem = json(files, OVERWORLD);
assertEquals("iris_export:flat", stem.get("type").getAsString());
assertEquals("iris_export:flat", stem.getAsJsonObject("generator").get("settings").getAsString());
assertFalse(files.containsKey(PRESET));
assertFalse(files.containsKey(DIMENSION));
}
@Test
public void climateLayoutPutsCodesOnTemperature() {
ExportIr base = fixture(WorldgenExportMode.DIMENSION);
ClimateLayout climate = new ClimateLayout(List.of(new ClimateLayout.ClimateEntry("iris_export:plains", ClimateLayout.ClimateAxis.TEMPERATURE, 0.1, 0.2)));
ExportIr ir = new ExportIr(base.namespace(), base.target(), base.mode(), base.dimension(), base.noises(), base.router(), climate, base.biomes(), base.material(), base.diagnostics(), base.jsonResources(), base.binaryResources());
JsonObject source = json(write(ir), DIMENSION).getAsJsonObject("generator").getAsJsonObject("biome_source");
assertEquals("minecraft:multi_noise", source.get("type").getAsString());
JsonArray biomes = source.getAsJsonArray("biomes");
assertEquals(1, biomes.size());
JsonObject entry = biomes.get(0).getAsJsonObject();
assertEquals("iris_export:plains", entry.get("biome").getAsString());
JsonObject parameters = entry.getAsJsonObject("parameters");
assertEquals(JsonParser.parseString("[0.1,0.2]"), parameters.get("temperature"));
assertEquals("[0.1,0.2]", parameters.get("temperature").toString());
for (String axis : List.of("humidity", "continentalness", "erosion", "depth", "weirdness", "offset")) {
assertEquals(axis, 0.0, parameters.get(axis).getAsDouble(), 0.0);
}
}
@Test
public void blockStateSyntaxPerFamily() {
SortedMap<String, byte[]> files = write(fixture(WorldgenExportMode.PRESET));
JsonObject settings = json(files, SETTINGS);
assertEquals(JsonParser.parseString("{\"id\":\"minecraft:stone\"}"), settings.get("default_block"));
assertEquals(JsonParser.parseString("{\"id\":\"minecraft:water\"}"), settings.get("default_fluid"));
assertEquals(JsonParser.parseString("{\"type\":\"minecraft:block\",\"result_state\":{\"id\":\"minecraft:stone\"}}"),
json(files, "data/iris_export/worldgen/material_rule/flat.json"));
ExportIr base = fixture(WorldgenExportMode.PRESET);
MaterialProgram legacy = new MaterialProgram(JsonParser.parseString("{\"type\":\"minecraft:block\",\"result_state\":{\"Name\":\"minecraft:stone\"}}"));
ExportIr wrong = new ExportIr(base.namespace(), base.target(), base.mode(), base.dimension(), base.noises(), base.router(), base.climate(), base.biomes(), legacy, base.diagnostics(), base.jsonResources(), base.binaryResources());
assertThrows(IllegalArgumentException.class, () -> write(wrong));
}
@Test
public void dimensionTypeHeightsFollowNoiseSettings() {
ExportIr base = fixture(WorldgenExportMode.PRESET);
JsonObject type = json(write(base), "data/iris_export/dimension_type/flat.json");
assertEquals(-64, type.get("min_y").getAsInt());
assertEquals(384, type.get("height").getAsInt());
assertEquals(384, type.get("logical_height").getAsInt());
assertEquals(true, type.get("has_skylight").getAsBoolean());
}
@Test
public void unknownKeysAreRejected() {
ExportIr base = fixture(WorldgenExportMode.PRESET);
JsonObject biome = ExportIrFixtures.biome();
biome.add("spawners", new JsonObject());
ExportIr legacyBiome = new ExportIr(base.namespace(), base.target(), base.mode(), base.dimension(), base.noises(), base.router(), base.climate(),
List.of(new BiomeDef("plains", biome)), base.material(), base.diagnostics(), base.jsonResources(), base.binaryResources());
IllegalArgumentException biomeFailure = assertThrows(IllegalArgumentException.class, () -> write(legacyBiome));
assertTrue(biomeFailure.getMessage(), biomeFailure.getMessage().contains("spawners"));
JsonObject type = ExportIrFixtures.dimensionType();
type.addProperty("bogus", 1);
ExportIr bogusType = new ExportIr(base.namespace(), base.target(), base.mode(),
new DimensionDef("flat", -64, 384, 384, 63, "minecraft:stone", "minecraft:water", type),
base.noises(), base.router(), base.climate(), base.biomes(), base.material(), base.diagnostics(), base.jsonResources(), base.binaryResources());
assertThrows(IllegalArgumentException.class, () -> write(bogusType));
}
@Test
public void unregisteredNoiseIsRejected() {
ExportIr base = fixture(WorldgenExportMode.PRESET);
RouterDef router = base.router();
Field missing = new Field.Noise("iris_export:missing", 1.0, 0.0, null, null, null);
RouterDef broken = new RouterDef(missing, router.vegetation(), router.continents(), router.erosion(), router.depth(), router.ridges(),
router.chunkSurfaceLevel(), router.finalDensity(), router.aquifer());
ExportIr ir = new ExportIr(base.namespace(), base.target(), base.mode(), base.dimension(), base.noises(), broken, base.climate(), base.biomes(), base.material(), base.diagnostics(), base.jsonResources(), base.binaryResources());
IllegalStateException failure = assertThrows(IllegalStateException.class, () -> write(ir));
assertTrue(failure.getMessage(), failure.getMessage().contains("iris_export:missing"));
}
@Test
public void noFileExceedsNestingLimit() {
ExportIr base = fixture(WorldgenExportMode.PRESET);
Field chain = new Field.Noise("iris_export:flat/height", 1.0, 0.0, null, null, null);
for (int index = 0; index < 700; index++) {
chain = new Field.Binary(Field.BinaryOp.ADD, chain, new Field.Const(index * 0.001));
}
RouterDef router = base.router();
RouterDef deep = new RouterDef(router.temperature(), router.vegetation(), router.continents(), router.erosion(), router.depth(), router.ridges(),
router.chunkSurfaceLevel(), chain, AquiferDef.dry(router.aquifer().surfaceLevel()));
ExportIr ir = new ExportIr(base.namespace(), base.target(), base.mode(), base.dimension(), base.noises(), deep, base.climate(), base.biomes(), base.material(), base.diagnostics(), base.jsonResources(), base.binaryResources());
SortedMap<String, byte[]> files = write(ir);
for (String path : files.keySet()) {
if (!isJson(path)) {
continue;
}
JsonElement parsed = JsonParser.parseString(new String(files.get(path), StandardCharsets.UTF_8));
assertTrue(path, NestingSplitter.depth(parsed) <= 255);
if (path.startsWith(DENSITY_PREFIX)) {
assertReferencesResolve(files, parsed);
}
}
assertResolves(files, json(files, SETTINGS).getAsJsonObject("noise_router").get("final_density"));
}
@Test
public void finalDensityAlwaysHasItsNamedFile() {
ExportIr base = fixture(WorldgenExportMode.PRESET);
RouterDef router = base.router();
Field shared = new Field.Shared("flat/terrain", router.finalDensity());
List<RouterDef> routers = List.of(
new RouterDef(router.temperature(), router.vegetation(), router.continents(), router.erosion(), router.depth(), router.ridges(),
router.chunkSurfaceLevel(), new Field.Const(1.0), router.aquifer()),
new RouterDef(router.finalDensity(), router.vegetation(), router.continents(), router.erosion(), router.depth(), router.ridges(),
router.chunkSurfaceLevel(), router.finalDensity(), router.aquifer()),
new RouterDef(router.temperature(), router.vegetation(), router.continents(), router.erosion(), router.depth(), router.ridges(),
router.chunkSurfaceLevel(), shared, router.aquifer()));
for (RouterDef variant : routers) {
ExportIr ir = new ExportIr(base.namespace(), base.target(), base.mode(), base.dimension(), base.noises(), variant, base.climate(), base.biomes(),
base.material(), base.diagnostics(), base.jsonResources(), base.binaryResources());
SortedMap<String, byte[]> files = write(ir);
assertEquals("iris_export:flat/final_density", json(files, SETTINGS).getAsJsonObject("noise_router").get("final_density").getAsString());
assertTrue(files.keySet().toString(), files.containsKey(DENSITY_PREFIX + "flat/final_density.json"));
}
}
@Test
public void outputIsSortedAndDeterministic() {
SortedMap<String, byte[]> first = write(fixture(WorldgenExportMode.PRESET));
SortedMap<String, byte[]> second = write(fixture(WorldgenExportMode.PRESET));
assertEquals(first.keySet(), second.keySet());
for (String path : first.keySet()) {
assertArrayEquals(path, first.get(path), second.get(path));
if (!isJson(path)) {
continue;
}
String text = new String(first.get(path), StandardCharsets.UTF_8);
assertTrue(path, text.endsWith("\n"));
assertFalse(path, text.contains("\r"));
}
String settings = new String(first.get(SETTINGS), StandardCharsets.UTF_8);
List<Integer> order = new ArrayList<>();
for (String key : new TreeSet<>(json(first, SETTINGS).keySet())) {
order.add(settings.indexOf("\"" + key + "\""));
}
List<Integer> sorted = new ArrayList<>(order);
sorted.sort(Integer::compare);
assertEquals(sorted, order);
}
private static void assertResolves(SortedMap<String, byte[]> files, JsonElement reference) {
assertTrue(reference.toString(), reference.isJsonPrimitive() && reference.getAsJsonPrimitive().isString());
assertTrue(reference.getAsString(), files.containsKey(DENSITY_PREFIX + reference.getAsString().substring("iris_export:".length()) + ".json"));
}
private static void assertReferencesResolve(SortedMap<String, byte[]> files, JsonElement element) {
if (element.isJsonPrimitive()) {
String value = element.getAsJsonPrimitive().isString() ? element.getAsString() : "";
if (value.startsWith("iris_export:") && !value.equals("iris_export:flat/height")) {
assertResolves(files, element);
}
return;
}
if (element.isJsonObject()) {
for (Map.Entry<String, JsonElement> member : element.getAsJsonObject().entrySet()) {
assertReferencesResolve(files, member.getValue());
}
}
if (element.isJsonArray()) {
for (JsonElement item : element.getAsJsonArray()) {
assertReferencesResolve(files, item);
}
}
}
@Test
public void resourcesAreCopiedAtTheirPaths() {
JsonObject feature = JsonParser.parseString("{\"type\":\"minecraft:ore\",\"config\":{\"size\":4,\"discard_chance_on_air_exposure\":0.0}}").getAsJsonObject();
byte[] template = {10, 0, 0, 3, 1, 2};
ExportIr ir = ExportIrFixtures.withResources(fixture(WorldgenExportMode.PRESET),
List.of(new JsonResource(FEATURE, feature)), List.of(new BinaryResource(TEMPLATE, template)));
SortedMap<String, byte[]> files = write(ir);
assertEquals(feature, json(files, FEATURE));
String text = new String(files.get(FEATURE), StandardCharsets.UTF_8);
assertTrue(text.endsWith("\n"));
assertTrue(text.indexOf("\"config\"") < text.indexOf("\"type\""));
assertTrue(text.indexOf("\"discard_chance_on_air_exposure\"") < text.indexOf("\"size\""));
assertArrayEquals(template, files.get(TEMPLATE));
assertArrayEquals(write(ir).get(FEATURE), files.get(FEATURE));
}
@Test
public void resourcesCollidingWithGeneratedFilesAreRejected() {
ExportIr base = fixture(WorldgenExportMode.PRESET);
ExportIr jsonCollision = ExportIrFixtures.withResources(base, List.of(new JsonResource(SETTINGS, new JsonObject())), List.of());
IllegalArgumentException jsonFailure = assertThrows(IllegalArgumentException.class, () -> write(jsonCollision));
assertTrue(jsonFailure.getMessage(), jsonFailure.getMessage().contains(SETTINGS));
ExportIr binaryCollision = ExportIrFixtures.withResources(base, List.of(), List.of(new BinaryResource("pack.mcmeta", new byte[] {1})));
IllegalArgumentException binaryFailure = assertThrows(IllegalArgumentException.class, () -> write(binaryCollision));
assertTrue(binaryFailure.getMessage(), binaryFailure.getMessage().contains("pack.mcmeta"));
}
private static ExportIr fixture(WorldgenExportMode mode) {
return ExportIrFixtures.flatNoise(DataVersion.V26_3, mode);
}
private static SortedMap<String, byte[]> write(ExportIr ir) {
return new Format26_3Writer().write(ir);
}
private static JsonObject json(SortedMap<String, byte[]> files, String path) {
byte[] bytes = files.get(path);
assertTrue(path, bytes != null);
return JsonParser.parseString(new String(bytes, StandardCharsets.UTF_8)).getAsJsonObject();
}
private static boolean isJson(String path) {
return path.endsWith(".json") || path.endsWith(".mcmeta");
}
}
Loaded 100 of 498 files, more files were not shown because too many files have changed in this diff. Show more