From d15c3480abfed5d543233e156aeb944fe6f8a94b Mon Sep 17 00:00:00 2001 From: piexel Date: Mon, 12 Oct 2026 02:07:13 +0200 Subject: [PATCH 1/3] Host side of the carve port: NoiseSampler signed and scaled, minHeight, cave biome of a block, MatterMantle over the invocation's mantle, CaveDressing over layers, decorators and palettes, carve leaves the compiled-in list --- .../iris/core/modules/BlockStateHunk.java | 10 ++ .../iris/core/modules/IrisCaveDressing.java | 160 ++++++++++++++++++ .../modules/IrisMantleGenerationContext.java | 4 +- .../iris/core/modules/IrisModuleHost.java | 5 +- .../iris/core/modules/IrisModuleMantle.java | 18 +- .../iris/core/modules/IrisNoiseFactory.java | 30 +++- .../iris/core/modules/IrisPackResources.java | 12 ++ .../iris/core/modules/IrisPackWorld.java | 13 +- .../iris/core/modules/IrisTerrainSampler.java | 7 + .../iris/core/modules/PackResourceIds.java | 10 +- .../iris/core/modules/PinnedMantleChunk.java | 16 ++ .../iris/core/modules/StageMetrics.java | 3 +- .../arcane/iris/core/modules/BuiltInPack.java | 3 +- .../iris/core/modules/IrisValuesTest.java | 30 ++++ 14 files changed, 309 insertions(+), 12 deletions(-) create mode 100644 core/src/main/java/art/arcane/iris/core/modules/IrisCaveDressing.java diff --git a/core/src/main/java/art/arcane/iris/core/modules/BlockStateHunk.java b/core/src/main/java/art/arcane/iris/core/modules/BlockStateHunk.java index 0bb54444f..0298f1609 100644 --- a/core/src/main/java/art/arcane/iris/core/modules/BlockStateHunk.java +++ b/core/src/main/java/art/arcane/iris/core/modules/BlockStateHunk.java @@ -38,6 +38,16 @@ final class BlockStateHunk implements Hunk { this.states = states; } + /** Iris's own hunk behind this view, which the built-ins that decorate with Iris's decorators write to. */ + art.arcane.iris.util.project.hunk.Hunk platform() { + return blocks; + } + + /** The conversions this chunk's views share. */ + PlatformBlockStates states() { + return states; + } + @Override public int getWidth() { return blocks.getWidth(); diff --git a/core/src/main/java/art/arcane/iris/core/modules/IrisCaveDressing.java b/core/src/main/java/art/arcane/iris/core/modules/IrisCaveDressing.java new file mode 100644 index 000000000..756d643a2 --- /dev/null +++ b/core/src/main/java/art/arcane/iris/core/modules/IrisCaveDressing.java @@ -0,0 +1,160 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.core.modules; + +import art.arcane.iris.builtin.CaveDressing; +import art.arcane.iris.builtin.decorant.DecorationPart; +import art.arcane.iris.engine.decorator.BiomeDecorators; +import art.arcane.iris.engine.decorator.IrisCeilingDecorator; +import art.arcane.iris.engine.decorator.IrisSurfaceDecorator; +import art.arcane.iris.engine.framework.Engine; +import art.arcane.iris.engine.object.world.biome.InferredType; +import art.arcane.iris.engine.object.world.biome.IrisBiome; +import art.arcane.iris.engine.terrain.BiomeLayers; +import art.arcane.iris.engine.terrain.TerrainPalettes; +import art.arcane.iris.spi.PlatformBlockState; +import art.arcane.iris.util.common.data.B; +import art.arcane.volmlib.util.math.RNG; +import com.volmit.ModuleLog; +import com.volmit.block.BlockState; +import com.volmit.hunk.Hunk; +import com.volmit.resource.ResourceId; + +import java.util.ArrayList; +import java.util.List; + +/** + * {@link CaveDressing} over Iris's biome layers, decorators and terrain palettes: what the carve module asks of the features that + * are not modules yet, in IrisApi's types. Transitional, like the interface. + */ +final class IrisCaveDressing implements CaveDressing { + private final Engine engine; + private final IrisPackResources resources; + private final BiomeLayers layers; + private final BiomeDecorators decorators; + private final TerrainPalettes palettes; + private final IrisSurfaceDecorator surfaceDecorator; + private final IrisCeilingDecorator ceilingDecorator; + + IrisCaveDressing(Engine engine, IrisPackResources resources, ModuleLog log) { + this.engine = engine; + this.resources = resources; + this.layers = BiomeLayers.of(engine, log); + this.decorators = BiomeDecorators.of(engine); + this.palettes = TerrainPalettes.of(engine); + this.surfaceDecorator = new IrisSurfaceDecorator(engine); + this.ceilingDecorator = new IrisCeilingDecorator(engine); + } + + @Override + public boolean fluidPresentAt(int x, int z) { + return B.isFluid(palettes.fluidAt(x, z)); + } + + @Override + public BlockState fluidAt(Hunk chunk, int x, int z) { + return nullable(states(chunk), palettes.fluidAt(x, z)); + } + + @Override + public BlockState wall(Hunk chunk, ResourceId biome, RNG rng, int x, int y, int z) { + IrisBiome irisBiome = resources.irisBiome(biome); + if (irisBiome == null) { + return null; + } + return nullable(states(chunk), layers.wall(irisBiome).get(rng, x, y, z)); + } + + @Override + public List floorLayers(Hunk chunk, ResourceId biome, int x, int z, RNG rng, int depth, int floorY) { + IrisBiome irisBiome = resources.irisBiome(biome); + if (irisBiome == null) { + return List.of(); + } + return toApi(chunk, layers.generateLayers(irisBiome, engine.getDimension(), x, z, rng, depth, floorY, engine.getData(), engine.getComplex())); + } + + @Override + public List ceilingLayers(Hunk chunk, ResourceId biome, int x, int z, RNG rng, int depth, int ceilingY) { + IrisBiome irisBiome = resources.irisBiome(biome); + if (irisBiome == null) { + return List.of(); + } + return toApi(chunk, layers.generateCeilingLayers(irisBiome, engine.getDimension(), x, z, rng, depth, ceilingY, engine.getData(), engine.getComplex())); + } + + @Override + public boolean hasDecorators(ResourceId biome, DecorationPart part) { + IrisBiome irisBiome = resources.irisBiome(biome); + return irisBiome != null && decorators.hasDecorators(irisBiome, part); + } + + @Override + public void decorateFloor(Hunk chunk, int localX, int localZ, int x, int z, ResourceId biome, int floorY, int airThickness) { + IrisBiome irisBiome = resources.irisBiome(biome); + if (irisBiome == null) { + return; + } + surfaceDecorator.decorate(localX, localZ, x, x, x, z, z, z, platform(chunk), irisBiome, InferredType.CAVE, floorY, airThickness); + } + + @Override + public void decorateCeiling(Hunk chunk, int localX, int localZ, int x, int z, ResourceId biome, int ceilingY, int airThickness) { + IrisBiome irisBiome = resources.irisBiome(biome); + if (irisBiome == null) { + return; + } + ceilingDecorator.decorate(localX, localZ, x, x, x, z, z, z, platform(chunk), irisBiome, InferredType.CAVE, ceilingY, airThickness); + } + + @Override + public BlockState deepSlateOre(Hunk chunk, BlockState existing, BlockState layer) { + PlatformBlockStates states = states(chunk); + return states.toApi(B.toDeepSlateOre(states.toPlatform(existing), states.toPlatform(layer))); + } + + private List toApi(Hunk chunk, List blocks) { + PlatformBlockStates states = states(chunk); + List converted = new ArrayList<>(blocks.size()); + for (PlatformBlockState block : blocks) { + converted.add(nullable(states, block)); + } + return converted; + } + + /** A state or null where the layer gave none; IrisApi's conversion reads null as air. */ + private static BlockState nullable(PlatformBlockStates states, PlatformBlockState block) { + return block == null ? null : states.toApi(block); + } + + private static PlatformBlockStates states(Hunk chunk) { + return hunk(chunk).states(); + } + + private static art.arcane.iris.util.project.hunk.Hunk platform(Hunk chunk) { + return hunk(chunk).platform(); + } + + private static BlockStateHunk hunk(Hunk chunk) { + if (chunk instanceof BlockStateHunk hunk) { + return hunk; + } + throw new IllegalArgumentException("Built-in modules dress the chunks Iris hands to them, not " + chunk); + } +} diff --git a/core/src/main/java/art/arcane/iris/core/modules/IrisMantleGenerationContext.java b/core/src/main/java/art/arcane/iris/core/modules/IrisMantleGenerationContext.java index 4cd06f77a..d21dc60d8 100644 --- a/core/src/main/java/art/arcane/iris/core/modules/IrisMantleGenerationContext.java +++ b/core/src/main/java/art/arcane/iris/core/modules/IrisMantleGenerationContext.java @@ -39,6 +39,8 @@ import java.util.Collection; final class IrisMantleGenerationContext implements MantleGenerationContext { private static final int CHUNK_SHIFT = 4; private static final int CHUNK_WIDTH = 16; + /** Mantle stages see the terrain at least this far around their chunk, as chunk stages do (IrisApi's promise). */ + private static final int TERRAIN_MARGIN_BLOCKS = 16; private final Engine engine; private final int originX; @@ -54,7 +56,7 @@ final class IrisMantleGenerationContext implements MantleGenerationContext { this.engine = engine; this.originX = chunkX << CHUNK_SHIFT; this.originZ = chunkZ << CHUNK_SHIFT; - this.terrain = new IrisTerrainSampler(engine, ids, originX, originZ, reachBlocks); + this.terrain = new IrisTerrainSampler(engine, ids, originX, originZ, Math.max(reachBlocks, TERRAIN_MARGIN_BLOCKS)); this.settings = new ChunkModuleSettings(engine, ids); BlockBox reach = ApiHeights.columns(engine, originX - reachBlocks, originZ - reachBlocks, originX + CHUNK_WIDTH + reachBlocks, originZ + CHUNK_WIDTH + reachBlocks); diff --git a/core/src/main/java/art/arcane/iris/core/modules/IrisModuleHost.java b/core/src/main/java/art/arcane/iris/core/modules/IrisModuleHost.java index 565107f46..f348c92c2 100644 --- a/core/src/main/java/art/arcane/iris/core/modules/IrisModuleHost.java +++ b/core/src/main/java/art/arcane/iris/core/modules/IrisModuleHost.java @@ -25,7 +25,6 @@ import art.arcane.iris.engine.loot.LootModule; import art.arcane.iris.engine.mantle.components.ObjectModule; import art.arcane.iris.engine.spawn.SpawnModule; import art.arcane.iris.engine.mantle.components.StructureModule; -import art.arcane.iris.engine.modifier.CarveModule; import art.arcane.iris.engine.modifier.DepositModule; import art.arcane.iris.engine.modifier.FloatingModule; import art.arcane.iris.engine.object.placement.PlacementModules; @@ -63,7 +62,7 @@ public final class IrisModuleHost { * {@code IrisModule/builtin-modules.txt}) instead of being compiled into Iris. A pack loads them from its {@code modules} * folder, and {@link MissingBuiltInModules} warns when it loads none; a test keeps this equal to the jar's list. */ - public static final List JAR_MODULE_IDS = List.of("iris:post", "iris:perfection", "iris:matter"); + public static final List JAR_MODULE_IDS = List.of("iris:post", "iris:perfection", "iris:matter", "iris:carve"); /** Iris's pack object model: built-in settings may hold these classes, which Iris reads and describes itself. */ public static final String HOST_TYPE_PACKAGE = "art.arcane.iris.engine.object"; private static final String[] JAR_COPY_FOLDER = {"cache", "module-jars"}; @@ -87,7 +86,7 @@ public final class IrisModuleHost { } private static List generationModules() { - return List.of(new TerrainModule(), new CarveModule(), new ObjectModule(), new StructureModule(), + return List.of(new TerrainModule(), new ObjectModule(), new StructureModule(), new FloatingModule(), new DepositModule(), new DecorantModule(), new LootModule(), new SpawnModule()); } diff --git a/core/src/main/java/art/arcane/iris/core/modules/IrisModuleMantle.java b/core/src/main/java/art/arcane/iris/core/modules/IrisModuleMantle.java index 438efe5df..19b267096 100644 --- a/core/src/main/java/art/arcane/iris/core/modules/IrisModuleMantle.java +++ b/core/src/main/java/art/arcane/iris/core/modules/IrisModuleMantle.java @@ -23,6 +23,7 @@ import art.arcane.volmlib.util.matter.Matter; import art.arcane.volmlib.util.matter.MatterSlice; import com.volmit.block.BlockState; import com.volmit.host.MantleRegistration; +import art.arcane.iris.builtin.MatterMantle; import com.volmit.mantle.BlockBox; import com.volmit.mantle.Mantle; import com.volmit.mantle.MantleCodec; @@ -53,7 +54,7 @@ import java.util.stream.Collectors; * lose each other's layers. {@link #edit()} buffers changes across layers until they are committed; while an * edit is open, the view itself only reads. */ -final class IrisModuleMantle implements Mantle { +final class IrisModuleMantle implements Mantle, MatterMantle { private static final int CHUNK_SHIFT = 4; private static final int SECTION_SHIFT = 4; private static final int LOCAL_MASK = 15; @@ -65,6 +66,11 @@ final class IrisModuleMantle implements Mantle { /** The mantle chunk at chunk coordinates, or null when it is outside what the invocation prepared. */ interface Chunks { MantleChunk chunk(int chunkX, int chunkZ); + + /** The chunk if the world holds it in memory, whether or not the invocation reaches it; never loads one. */ + default MantleChunk loadedChunk(int chunkX, int chunkZ) { + return null; + } } private final BlockBox bounds; @@ -85,6 +91,16 @@ final class IrisModuleMantle implements Mantle { return bounds; } + @Override + public MantleChunk chunk(int chunkX, int chunkZ) { + return chunks.chunk(chunkX, chunkZ); + } + + @Override + public MantleChunk loadedChunk(int chunkX, int chunkZ) { + return chunks.loadedChunk(chunkX, chunkZ); + } + @Override public MantleLayer layer(MantleKey key) { return new Layer<>(key, codecOf(key)); diff --git a/core/src/main/java/art/arcane/iris/core/modules/IrisNoiseFactory.java b/core/src/main/java/art/arcane/iris/core/modules/IrisNoiseFactory.java index aaa653802..eaebdc16c 100644 --- a/core/src/main/java/art/arcane/iris/core/modules/IrisNoiseFactory.java +++ b/core/src/main/java/art/arcane/iris/core/modules/IrisNoiseFactory.java @@ -28,6 +28,7 @@ import com.volmit.noise.NoiseStyle; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; +import java.util.function.Supplier; /** * Builds the noise of IrisApi noise styles with Iris's own generators: each style becomes the @@ -36,6 +37,8 @@ import java.util.concurrent.ConcurrentHashMap; * built generators. */ final class IrisNoiseFactory implements NoiseFactory { + private static final double NO_EXTRA_SCALE = 1D; + private final IrisData data; private final Map styles = new ConcurrentHashMap<>(); @@ -47,14 +50,17 @@ final class IrisNoiseFactory implements NoiseFactory { public NoiseSampler sampler(NoiseStyle style, long seed) { IrisGeneratorStyle iris = styles.computeIfAbsent(style, IrisValues::generatorStyle); try { - return new CngSampler(iris.create(new RNG(seed), data)); + return new CngSampler(iris.create(new RNG(seed), data), () -> iris.createNoCache(new RNG(seed), data), NO_EXTRA_SCALE); } catch (RuntimeException failure) { throw new IllegalArgumentException("Cannot build the noise of " + style + ": " + failure.getMessage(), failure); } } - /** Iris's noise as an IrisApi sampler; CNG is safe for the concurrent reads generation makes. */ - private record CngSampler(CNG noise) implements NoiseSampler { + /** + * Iris's noise as an IrisApi sampler; CNG is safe for the concurrent reads generation makes. {@code fresh} builds the same + * generator again, unshared, for {@link #scaled}: scaling a generator changes it, and this one is shared. + */ + private record CngSampler(CNG noise, Supplier fresh, double extraScale) implements NoiseSampler { @Override public double sample(double worldX, double worldZ) { return noise.noise(worldX, worldZ); @@ -64,5 +70,23 @@ final class IrisNoiseFactory implements NoiseFactory { public double sample(double worldX, double y, double worldZ) { return noise.noise(worldX, y, worldZ); } + + /** CNG's own signed read, which answers a repeated read of the same coordinates from a per-thread memo. */ + @Override + public double signed(double worldX, double worldZ) { + return noise.noiseFastSigned2D(worldX, worldZ); + } + + @Override + public double signed(double worldX, double y, double worldZ) { + return noise.noiseFastSigned3D(worldX, y, worldZ); + } + + /** The generator with {@code factor} baked into its scale, as {@code create(...).bake().scale(factor).bake()} always gave. */ + @Override + public NoiseSampler scaled(double factor) { + double total = extraScale * factor; + return new CngSampler(fresh.get().bake().scale(total).bake(), fresh, total); + } } } diff --git a/core/src/main/java/art/arcane/iris/core/modules/IrisPackResources.java b/core/src/main/java/art/arcane/iris/core/modules/IrisPackResources.java index 2259f5040..11d97c8c3 100644 --- a/core/src/main/java/art/arcane/iris/core/modules/IrisPackResources.java +++ b/core/src/main/java/art/arcane/iris/core/modules/IrisPackResources.java @@ -145,7 +145,14 @@ public final class IrisPackResources implements PackResources { return kindOf(type).ids(); } + /** The biome of the pack with this id as Iris's own class, for the built-ins that decorate with it; null when the pack has none. */ + public IrisBiome irisBiome(ResourceId id) { + String key = kindOf(PackBiome.class).keyOf(id); + return key == null ? null : data.getBiomeLoader().load(key); + } + /** The id of the resource the pack names by {@code packKey}, such as {@code overworld:castle/keep} for {@code castle/keep}. */ + @Override public ResourceId idOf(String packKey) { return ids.of(packKey); } @@ -246,6 +253,11 @@ public final class IrisPackResources implements PackResources { return Optional.of(raced != null ? raced : made); } + /** The key of the resource with this id; null when the pack has none. */ + String keyOf(ResourceId id) { + return keysById().get(id); + } + List ids() { return keysById().keySet().stream().sorted().toList(); } diff --git a/core/src/main/java/art/arcane/iris/core/modules/IrisPackWorld.java b/core/src/main/java/art/arcane/iris/core/modules/IrisPackWorld.java index eee4832ee..736404719 100644 --- a/core/src/main/java/art/arcane/iris/core/modules/IrisPackWorld.java +++ b/core/src/main/java/art/arcane/iris/core/modules/IrisPackWorld.java @@ -18,6 +18,7 @@ package art.arcane.iris.core.modules; +import art.arcane.iris.builtin.CaveDressing; import art.arcane.iris.builtin.IrisSeed; import art.arcane.iris.engine.framework.Engine; import art.arcane.iris.engine.framework.SeedManager; @@ -35,7 +36,7 @@ import java.util.function.Function; * pack's resources reload under it. Iris's built-in modules reach the engine through {@link #of(PackWorld)}, as built-in * reaches do through {@link IrisPackSettings#of}. */ -public final class IrisPackWorld implements PackWorld, IrisSeed.Source { +public final class IrisPackWorld implements PackWorld, IrisSeed.Source, CaveDressing.Source { private final Engine engine; private final IrisPackResources resources; private final WorldStates states; @@ -78,6 +79,11 @@ public final class IrisPackWorld implements PackWorld, IrisSeed.Source { return resources; } + @Override + public int minHeight() { + return engine.getWorld().minHeight(); + } + @Override public PackSettings settings() { return new IrisPackSettings(engine); @@ -99,6 +105,11 @@ public final class IrisPackWorld implements PackWorld, IrisSeed.Source { return viewsByLog.computeIfAbsent(log, moduleLog -> new IrisPackWorld(engine, resources, states, moduleLog, viewsByLog)); } + @Override + public CaveDressing caveDressing() { + return state(IrisCaveDressing.class, world -> new IrisCaveDressing(engine, resources, log)); + } + @Override public long seed(IrisSeed seed) { SeedManager seeds = engine.getSeedManager(); diff --git a/core/src/main/java/art/arcane/iris/core/modules/IrisTerrainSampler.java b/core/src/main/java/art/arcane/iris/core/modules/IrisTerrainSampler.java index a48dcfd85..d0e6a6148 100644 --- a/core/src/main/java/art/arcane/iris/core/modules/IrisTerrainSampler.java +++ b/core/src/main/java/art/arcane/iris/core/modules/IrisTerrainSampler.java @@ -22,6 +22,7 @@ import art.arcane.iris.engine.UpperDimensionContext; import art.arcane.iris.engine.framework.Engine; import art.arcane.iris.engine.object.world.biome.IrisBiome; import com.volmit.mantle.BlockBox; +import com.volmit.resource.ResourceId; import com.volmit.world.BiomeSample; import com.volmit.world.TerrainSample; import com.volmit.world.TerrainSampler; @@ -87,6 +88,12 @@ final class IrisTerrainSampler implements TerrainSampler { cave.map(biome -> ids.of(biome.getLoadKey()))); } + @Override + public Optional caveBiome(int worldX, int y, int worldZ) { + requireInside(worldX, y, worldZ); + return Optional.ofNullable(engine.getCaveBiome(worldX, y, worldZ)).map(biome -> ids.of(biome.getLoadKey())); + } + @Override public int fluidHeight() { return engine.getDimension().getFluidHeight(); diff --git a/core/src/main/java/art/arcane/iris/core/modules/PackResourceIds.java b/core/src/main/java/art/arcane/iris/core/modules/PackResourceIds.java index 2b1263fd9..c7637a89a 100644 --- a/core/src/main/java/art/arcane/iris/core/modules/PackResourceIds.java +++ b/core/src/main/java/art/arcane/iris/core/modules/PackResourceIds.java @@ -22,6 +22,8 @@ import com.volmit.resource.ResourceId; import java.io.File; import java.util.Locale; +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; import java.util.regex.Pattern; /** @@ -37,11 +39,16 @@ final class PackResourceIds { private static final String UNNAMED_PACK = "pack"; private static final String PACK_PATH = "pack"; + /** Stages ask per column, so each key is turned into its id once, however many invocations ask. A pack has a few thousand keys at most. */ + private static final Map> BY_NAMESPACE_AND_KEY = new ConcurrentHashMap<>(); + private final String namespace; + private final Map byKey; PackResourceIds(File packFolder) { String name = NOT_NAMESPACE.matcher(packFolder.getName().toLowerCase(Locale.ROOT)).replaceAll(REPLACEMENT); this.namespace = name.isEmpty() ? UNNAMED_PACK : name; + this.byKey = BY_NAMESPACE_AND_KEY.computeIfAbsent(namespace, ignored -> new ConcurrentHashMap<>()); } /** The namespace of every id this pack's resources have. */ @@ -56,7 +63,8 @@ final class PackResourceIds { /** {@code key} of a resource whose type its use makes clear, such as a biome in a biome sample. */ ResourceId of(String key) { - return new ResourceId(namespace, NOT_PATH.matcher(key.toLowerCase(Locale.ROOT)).replaceAll(REPLACEMENT)); + return byKey.computeIfAbsent(key, + known -> new ResourceId(namespace, NOT_PATH.matcher(known.toLowerCase(Locale.ROOT)).replaceAll(REPLACEMENT))); } /** {@code key} of a resource of {@code type}, such as {@code overworld:biome/desert/dunes}. */ diff --git a/core/src/main/java/art/arcane/iris/core/modules/PinnedMantleChunk.java b/core/src/main/java/art/arcane/iris/core/modules/PinnedMantleChunk.java index bee6ae674..a80ff2a4f 100644 --- a/core/src/main/java/art/arcane/iris/core/modules/PinnedMantleChunk.java +++ b/core/src/main/java/art/arcane/iris/core/modules/PinnedMantleChunk.java @@ -19,7 +19,9 @@ package art.arcane.iris.core.modules; import art.arcane.iris.engine.framework.Engine; +import art.arcane.volmlib.util.mantle.runtime.Mantle; import art.arcane.volmlib.util.mantle.runtime.MantleChunk; +import art.arcane.volmlib.util.mantle.runtime.TectonicPlate; import art.arcane.volmlib.util.matter.Matter; /** @@ -27,6 +29,10 @@ import art.arcane.volmlib.util.matter.Matter; * released once the chunk's stages are done. */ final class PinnedMantleChunk implements IrisModuleMantle.Chunks, AutoCloseable { + /** A tectonic plate holds 32 by 32 chunks. */ + private static final int PLATE_SHIFT = 5; + private static final int PLATE_MASK = (1 << PLATE_SHIFT) - 1; + private final Engine engine; private final int chunkX; private final int chunkZ; @@ -49,6 +55,16 @@ final class PinnedMantleChunk implements IrisModuleMantle.Chunks, AutoCloseable return pinned; } + @Override + public MantleChunk loadedChunk(int x, int z) { + Mantle mantle = engine.getMantle().getMantle(); + TectonicPlate plate = mantle.getLoadedRegions().get(Mantle.key(x >> PLATE_SHIFT, z >> PLATE_SHIFT)); + if (plate == null || plate.isClosed()) { + return null; + } + return plate.get(x & PLATE_MASK, z & PLATE_MASK); + } + @Override public synchronized void close() { if (pinned != null) { diff --git a/core/src/main/java/art/arcane/iris/core/modules/StageMetrics.java b/core/src/main/java/art/arcane/iris/core/modules/StageMetrics.java index e910d35dc..0dc7b1a75 100644 --- a/core/src/main/java/art/arcane/iris/core/modules/StageMetrics.java +++ b/core/src/main/java/art/arcane/iris/core/modules/StageMetrics.java @@ -35,7 +35,8 @@ final class StageMetrics implements StageTimings { private static final double NANOS_PER_MILLISECOND = 1_000_000D; private static final Map> NAMED = Map.of( "iris:post/smooth", EngineMetrics::getPost, - "iris:perfection/surface", EngineMetrics::getPerfection); + "iris:perfection/surface", EngineMetrics::getPerfection, + "iris:carve/apply", EngineMetrics::getCave); private final EngineMetrics metrics; diff --git a/core/src/test/java/art/arcane/iris/core/modules/BuiltInPack.java b/core/src/test/java/art/arcane/iris/core/modules/BuiltInPack.java index 196de02ef..67a5ade27 100644 --- a/core/src/test/java/art/arcane/iris/core/modules/BuiltInPack.java +++ b/core/src/test/java/art/arcane/iris/core/modules/BuiltInPack.java @@ -21,6 +21,7 @@ package art.arcane.iris.core.modules; import art.arcane.iris.core.loader.IrisData; import art.arcane.iris.engine.framework.Engine; import art.arcane.iris.engine.framework.SeedManager; +import art.arcane.iris.engine.modifier.CarveModule; import art.arcane.iris.engine.modifier.MatterModule; import art.arcane.iris.engine.modifier.PerfectionModule; import art.arcane.iris.engine.modifier.PostModule; @@ -51,7 +52,7 @@ public final class BuiltInPack { * with Iris; {@code BuiltInModulesJarTest} loads the same modules from the jar instead. */ public static List jarModules() { - return List.of(new PostModule(), new PerfectionModule(), new MatterModule()); + return List.of(new PostModule(), new PerfectionModule(), new MatterModule(), new CarveModule()); } /** Every built-in module: Iris's own and the compiled-in copies of the jar's ({@link #jarModules()}). */ diff --git a/core/src/test/java/art/arcane/iris/core/modules/IrisValuesTest.java b/core/src/test/java/art/arcane/iris/core/modules/IrisValuesTest.java index 37ece4b6d..38a88d665 100644 --- a/core/src/test/java/art/arcane/iris/core/modules/IrisValuesTest.java +++ b/core/src/test/java/art/arcane/iris/core/modules/IrisValuesTest.java @@ -128,6 +128,36 @@ public class IrisValuesTest { } } + @Test + public void signedNoiseIsTheSignedFastReadOfTheIrisGeneratorsNoise() { + String json = "{\"style\": \"SIMPLEX\", \"zoom\": 4, \"exponent\": 1.5, \"fracture\": {\"style\": \"PERLIN\", \"zoom\": 2, \"multiplier\": 3}}"; + IrisData data = packWithoutCustomBlocks(); + CNG iris = new Gson().fromJson(json, IrisGeneratorStyle.class).create(new RNG(1337), data); + NoiseSampler sampler = new IrisNoiseFactory(data).sampler(new Gson().fromJson(json, NoiseStyle.class), 1337); + + for (double[] column : COLUMNS) { + assertEquals(iris.noiseFastSigned2D(column[0], column[1]), sampler.signed(column[0], column[1]), 0); + assertEquals(iris.noiseFastSigned3D(column[0], 64, column[1]), sampler.signed(column[0], 64, column[1]), 0); + assertEquals(iris.noiseFastSigned3D(column[0], 64, column[1]), sampler.signed(column[0], 64, column[1]), 0); + } + } + + @Test + public void scaledNoiseIsTheGeneratorWithTheScaleBakedIn() { + String json = "{\"style\": \"CELLULAR_IRIS_DOUBLE\", \"zoom\": 1}"; + IrisData data = packWithoutCustomBlocks(); + double scale = 1.5D; + CNG baked = new Gson().fromJson(json, IrisGeneratorStyle.class).createNoCache(new RNG(4242), data).bake().scale(scale).bake(); + NoiseSampler plain = new IrisNoiseFactory(data).sampler(new Gson().fromJson(json, NoiseStyle.class), 4242); + NoiseSampler scaled = plain.scaled(scale); + + for (int x = -30; x <= 30; x += 3) { + assertEquals(baked.noiseFast2D(x, 7), scaled.sample(x, 7), 0); + } + assertEquals("the sampler it was made from is left as it was", new Gson().fromJson(json, IrisGeneratorStyle.class) + .createNoCache(new RNG(4242), data).noise(9, 4), plain.sample(9, 4), 0); + } + @Test public void aStyleNameIrisDoesNotKnowIsFlat() { IrisData data = packWithoutCustomBlocks(); From 4f69881e1fcbe1b477d8bdb923f20fb3bf32527b Mon Sep 17 00:00:00 2001 From: piexel Date: Mon, 12 Oct 2026 02:19:37 +0200 Subject: [PATCH 2/3] Carve port tests: CarveTestWorld/Terrain fixtures, carving resolver parity against Iris's generators, cave carving, applying and mantle facade tests; the jar test lists carve; mantle stages see 16 blocks of terrain --- .../modules/CarveSettingsDecodingTest.java | 16 +- .../iris/core/modules/CarveTestTerrain.java | 111 +++ .../iris/core/modules/CarveTestWorld.java | 281 +++++++ .../core/modules/DimensionBottomTest.java | 4 +- .../core/modules/IrisModuleMantleTest.java | 35 + .../PackModuleJarNextToBuiltInsTest.java | 6 +- .../engine/framework/EngineCaveBiomeTest.java | 12 - .../StructureCaveAnchorResolverTest.java | 4 +- .../mantle/components/CaveCarvingTest.java | 131 ++++ .../components/CaveCarvingTop2BlendTest.java | 3 +- .../IrisCaveCarver3DNearParityTest.java | 212 +++--- .../arcane/iris/engine/modifier/ApiChunk.java | 58 +- .../CaveApplyingBoundarySupportTest.java | 171 +++-- .../modifier/CaveApplyingFluidIntentTest.java | 36 +- .../CaveApplyingInferenceIsolationTest.java | 129 ---- .../engine/modifier/CaveApplyingTest.java | 168 +++++ .../engine/modifier/CaveBiomeBandsTest.java | 43 +- .../modifier/RecordingCaveDressing.java | 85 +++ .../carving/CarvingResolverParityTest.java | 687 +++++------------- .../carving/CaveProfileDecodingTest.java | 28 +- 20 files changed, 1290 insertions(+), 930 deletions(-) create mode 100644 core/src/test/java/art/arcane/iris/core/modules/CarveTestTerrain.java create mode 100644 core/src/test/java/art/arcane/iris/core/modules/CarveTestWorld.java create mode 100644 core/src/test/java/art/arcane/iris/engine/mantle/components/CaveCarvingTest.java delete mode 100644 core/src/test/java/art/arcane/iris/engine/modifier/CaveApplyingInferenceIsolationTest.java create mode 100644 core/src/test/java/art/arcane/iris/engine/modifier/CaveApplyingTest.java create mode 100644 core/src/test/java/art/arcane/iris/engine/modifier/RecordingCaveDressing.java diff --git a/core/src/test/java/art/arcane/iris/core/modules/CarveSettingsDecodingTest.java b/core/src/test/java/art/arcane/iris/core/modules/CarveSettingsDecodingTest.java index 5be522a5f..8507d6c23 100644 --- a/core/src/test/java/art/arcane/iris/core/modules/CarveSettingsDecodingTest.java +++ b/core/src/test/java/art/arcane/iris/core/modules/CarveSettingsDecodingTest.java @@ -24,7 +24,9 @@ import art.arcane.iris.builtin.carve.CarvingEnabledSettings; import art.arcane.iris.builtin.carve.CarvingEntry; import art.arcane.iris.builtin.carve.CarvingSettings; import art.arcane.iris.builtin.carve.CaveDepthSettings; +import art.arcane.iris.builtin.carve.CaveLavaHeightSettings; import art.arcane.iris.builtin.carve.CaveProfile; +import art.arcane.iris.builtin.carve.UpperDimensionCarvingSettings; import art.arcane.volmlib.util.json.JSONObject; import com.google.gson.Gson; import com.volmit.FeatureAttachment.Target; @@ -188,9 +190,21 @@ public class CarveSettingsDecodingTest { assertEquals(Set.of(), settings.usedBiomes(ModuleSettings.NONE)); } + @Test + public void theOverworldReadsItsUpperDimensionCarvingAndANumberIsTheCaveLavaHeight() throws IOException { + ModuleSettings overworld = decoder.decode(Target.DIMENSION, file("dimensions/overworld.json"), "dimension overworld"); + assertFalse(overworld.find(UpperDimensionCarvingSettings.class).orElseThrow().enabled()); + assertTrue("the overworld writes no cave lava height", overworld.find(CaveLavaHeightSettings.class).isEmpty()); + + ModuleSettings written = decoder.decode(Target.DIMENSION, new JSONObject("{\"caveLavaHeight\": 18, \"upperDimensionCarving\": true}"), "dimension test"); + assertEquals(18, written.find(CaveLavaHeightSettings.class).orElseThrow().height()); + assertTrue(written.find(UpperDimensionCarvingSettings.class).orElseThrow().enabled()); + assertEquals(8, CaveLavaHeightSettings.DEFAULT_HEIGHT); + } + @Test public void everyKeyIsOnlyReadAtTheLevelsTheOldFieldExistedAt() { - assertTrue(decoder.keys(Target.DIMENSION).containsAll(List.of("caveProfile", "carving", "carvingEnabled"))); + assertTrue(decoder.keys(Target.DIMENSION).containsAll(List.of("caveProfile", "carving", "carvingEnabled", "caveLavaHeight", "upperDimensionCarving"))); assertTrue(decoder.keys(Target.REGION).contains("caveProfile")); assertTrue(decoder.keys(Target.BIOME).containsAll(List.of("caveProfile", "carvingBiome", "caveMinDepthBelowSurface"))); assertFalse(decoder.keys(Target.REGION).contains("carving")); diff --git a/core/src/test/java/art/arcane/iris/core/modules/CarveTestTerrain.java b/core/src/test/java/art/arcane/iris/core/modules/CarveTestTerrain.java new file mode 100644 index 000000000..10d156ef2 --- /dev/null +++ b/core/src/test/java/art/arcane/iris/core/modules/CarveTestTerrain.java @@ -0,0 +1,111 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.core.modules; + +import com.volmit.mantle.BlockBox; +import com.volmit.resource.ResourceId; +import com.volmit.world.BiomeSample; +import com.volmit.world.TerrainSample; +import com.volmit.world.TerrainSampler; + +import java.util.Optional; +import java.util.OptionalInt; +import java.util.function.IntBinaryOperator; + +/** Terrain for the tests of the carve module: a surface height per column, a biome sample per block and an optional dimension above. */ +public final class CarveTestTerrain implements TerrainSampler { + private static final int MARGIN = 16; + + /** The biome sample of a block. */ + @FunctionalInterface + public interface Biomes { + BiomeSample at(int x, int y, int z); + } + + private final int originX; + private final int originZ; + private final int height; + private final int fluidHeight; + private final IntBinaryOperator surface; + private Biomes biomes = (x, y, z) -> new BiomeSample(CarveTestWorld.id("region"), CarveTestWorld.id("plains"), Optional.empty()); + private IntBinaryOperator upper; + + public CarveTestTerrain(int originX, int originZ, int height, int fluidHeight, IntBinaryOperator surface) { + this.originX = originX; + this.originZ = originZ; + this.height = height; + this.fluidHeight = fluidHeight; + this.surface = surface; + } + + public CarveTestTerrain biomes(Biomes biomes) { + this.biomes = biomes; + return this; + } + + public CarveTestTerrain upperDimension(IntBinaryOperator upper) { + this.upper = upper; + return this; + } + + @Override + public BlockBox bounds() { + return new BlockBox(originX - MARGIN, 0, originZ - MARGIN, originX + 16 + MARGIN, height, originZ + 16 + MARGIN); + } + + @Override + public TerrainSample column(int worldX, int worldZ) { + int surfaceY = surface.applyAsInt(worldX, worldZ); + return new TerrainSample(surfaceY, surfaceY < fluidHeight ? OptionalInt.of(fluidHeight) : OptionalInt.empty(), 0D); + } + + @Override + public double surfaceY(int worldX, int worldZ) { + require(worldX, 0, worldZ); + return surface.applyAsInt(worldX, worldZ); + } + + @Override + public BiomeSample biome(int worldX, int y, int worldZ) { + require(worldX, y, worldZ); + return biomes.at(worldX, y, worldZ); + } + + @Override + public Optional caveBiome(int worldX, int y, int worldZ) { + return biome(worldX, y, worldZ).caveBiome(); + } + + @Override + public int fluidHeight() { + return fluidHeight; + } + + @Override + public OptionalInt upperDimensionY(int worldX, int worldZ) { + require(worldX, 0, worldZ); + return upper == null ? OptionalInt.empty() : OptionalInt.of(upper.applyAsInt(worldX, worldZ)); + } + + private void require(int worldX, int y, int worldZ) { + if (!bounds().contains(worldX, y, worldZ)) { + throw new IndexOutOfBoundsException(worldX + ", " + y + ", " + worldZ + " is outside " + bounds()); + } + } +} diff --git a/core/src/test/java/art/arcane/iris/core/modules/CarveTestWorld.java b/core/src/test/java/art/arcane/iris/core/modules/CarveTestWorld.java new file mode 100644 index 000000000..7bbc1b4c5 --- /dev/null +++ b/core/src/test/java/art/arcane/iris/core/modules/CarveTestWorld.java @@ -0,0 +1,281 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.core.modules; + +import art.arcane.iris.builtin.CaveDressing; +import art.arcane.iris.builtin.IrisSeed; +import art.arcane.iris.core.loader.IrisData; +import art.arcane.iris.core.loader.ResourceLoader; +import art.arcane.iris.engine.object.material.IrisBlockData; +import com.volmit.FeatureAttachment.Target; +import com.volmit.IrisFeature; +import com.volmit.ModuleLog; +import com.volmit.block.BlockFace; +import com.volmit.block.BlockSpec; +import com.volmit.block.BlockState; +import com.volmit.block.BlockTrait; +import com.volmit.block.BlockRegistry; +import com.volmit.block.PaletteSampler; +import com.volmit.block.PaletteSpec; +import com.volmit.config.FeatureSettings.Entry; +import com.volmit.config.PackSettings; +import com.volmit.host.ModuleLogs; +import com.volmit.item.ItemRegistry; +import com.volmit.noise.NoiseFactory; +import com.volmit.resource.PackResources; +import com.volmit.resource.ResourceId; +import com.volmit.resource.ResourceKey; +import com.volmit.world.PackBiome; +import com.volmit.world.PackWorld; +import com.volmit.object.BlockEntityData; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.Set; +import java.util.UUID; +import java.util.function.Function; + +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +/** + * A world for the tests of the carve module: the settings its dimension, regions and biomes declare, the biomes its pack has, Iris's + * own noise over an empty pack, a few blocks by name and the world's seeds, all in memory, so the module is tested through IrisApi alone. + * Biomes and regions have the ids {@code test:}; a declaration made for {@code } has the source {@code test:/}. + */ +public final class CarveTestWorld implements PackWorld, IrisSeed.Source, CaveDressing.Source { + public static final String NAMESPACE = "test"; + public static final int MIN_HEIGHT = -64; + private static final Set AIRS = Set.of("minecraft:air", "minecraft:cave_air", "minecraft:void_air"); + private static final Set FLUIDS = Set.of("minecraft:water", "minecraft:lava"); + private static final Set DECORATIONS = Set.of("minecraft:short_grass", "minecraft:poppy", "minecraft:glow_lichen"); + private static final Set FALLING = Set.of("minecraft:sand", "minecraft:gravel"); + + private final Map, Object> states = new HashMap<>(); + private final List> declared = new ArrayList<>(); + private final Map biomes = new HashMap<>(); + private final IrisData data = packData(); + private final Resources resources = new Resources(); + private long carveSeed = 1337L; + private CaveDressing dressing; + + public CarveTestWorld declare(Target level, String key, IrisFeature value) { + String kind = level.name().toLowerCase(); + declared.add(new Entry<>(level, new ResourceId(NAMESPACE, kind + "/" + key), value)); + return this; + } + + public CarveTestWorld dimension(IrisFeature value) { + return declare(Target.DIMENSION, "overworld", value); + } + + public CarveTestWorld biome(String key, int rarity) { + ResourceId id = new ResourceId(NAMESPACE, key); + biomes.put(id, new PackBiome(id, key, ResourceId.parse("minecraft:plains"), rarity, List.of())); + return this; + } + + public CarveTestWorld carveSeed(long seed) { + this.carveSeed = seed; + return this; + } + + public CarveTestWorld dressing(CaveDressing dressing) { + this.dressing = dressing; + return this; + } + + /** The pack data under the noise: nothing in it, as the tests of Iris's value types have it. */ + public IrisData data() { + return data; + } + + public static ResourceId id(String key) { + return new ResourceId(NAMESPACE, key); + } + + @Override + public long seed() { + return carveSeed; + } + + @Override + public PackResources resources() { + return resources; + } + + @Override + public PackSettings settings() { + return new PackSettings() { + @Override + @SuppressWarnings("unchecked") + public List> declared(Class featureType) { + return declared.stream().filter(entry -> featureType.isInstance(entry.value())).map(entry -> (Entry) entry).toList(); + } + }; + } + + @Override + public int minHeight() { + return MIN_HEIGHT; + } + + @Override + public synchronized T state(Class type, Function create) { + Object known = states.get(type); + if (known == null) { + known = create.apply(this); + states.put(type, known); + } + return type.cast(known); + } + + @Override + public ModuleLog log() { + return ModuleLogs.discarding(); + } + + @Override + public PackWorld withLog(ModuleLog log) { + return this; + } + + @Override + public long seed(IrisSeed seed) { + return seed == IrisSeed.CARVE ? carveSeed : carveSeed + seed.ordinal(); + } + + @Override + public CaveDressing caveDressing() { + if (dressing == null) { + throw new UnsupportedOperationException("This world has no cave dressing"); + } + return dressing; + } + + @SuppressWarnings("unchecked") + private static IrisData packData() { + IrisData pack = mock(IrisData.class); + ResourceLoader blocks = mock(ResourceLoader.class); + when(pack.getBlockLoader()).thenReturn(blocks); + return pack; + } + + private final class Resources implements PackResources { + private final UUID snapshot = UUID.randomUUID(); + private final NoiseFactory noise = new IrisNoiseFactory(data); + + @Override + public ResourceId packId() { + return new ResourceId(NAMESPACE, "pack"); + } + + @Override + public UUID snapshotId() { + return snapshot; + } + + @Override + public BlockRegistry blocks() { + return new Blocks(); + } + + @Override + public ItemRegistry items() { + throw new UnsupportedOperationException("No items here"); + } + + @Override + public NoiseFactory noise() { + return noise; + } + + @Override + @SuppressWarnings("unchecked") + public Optional find(ResourceKey key) { + if (key.type() != PackBiome.class) { + return Optional.empty(); + } + return Optional.ofNullable((T) biomes.get(key.id())); + } + + @Override + public List ids(Class type) { + return type == PackBiome.class ? biomes.keySet().stream().sorted().toList() : List.of(); + } + } + + /** Blocks by name: air, water and lava, a few decorations, falling blocks and ores (named {@code *_ore}); everything else is a solid cube. */ + public static final class Blocks implements BlockRegistry { + @Override + public BlockState resolve(String key) { + return BlockState.parse(key.contains(":") ? key : "minecraft:" + key); + } + + @Override + public BlockState resolve(BlockSpec spec) { + return resolve(spec.block()); + } + + @Override + public Optional blockEntity(BlockSpec spec) { + return Optional.empty(); + } + + @Override + public PaletteSampler palette(PaletteSpec spec, long seed) { + throw new UnsupportedOperationException("No palettes here"); + } + + @Override + public boolean hasTrait(BlockState state, BlockTrait trait) { + String material = state.material().toString(); + boolean air = AIRS.contains(material); + boolean fluid = FLUIDS.contains(material); + boolean decoration = DECORATIONS.contains(material); + return switch (trait) { + case AIR -> air; + case FLUID -> fluid; + case SOLID -> !air && !fluid && !decoration; + case ORE -> material.endsWith("_ore"); + case DECORATION -> decoration; + case GRAVITY -> FALLING.contains(material); + default -> false; + }; + } + + @Override + public boolean inTag(BlockState state, ResourceId tag) { + return false; + } + + @Override + public boolean canAttach(BlockState state, BlockState support, BlockFace face) { + return hasTrait(support, BlockTrait.SOLID); + } + + @Override + public boolean canPlaceOn(BlockState state, BlockState below) { + return hasTrait(below, BlockTrait.SOLID); + } + } +} diff --git a/core/src/test/java/art/arcane/iris/core/modules/DimensionBottomTest.java b/core/src/test/java/art/arcane/iris/core/modules/DimensionBottomTest.java index e7c8d931e..2c3588472 100644 --- a/core/src/test/java/art/arcane/iris/core/modules/DimensionBottomTest.java +++ b/core/src/test/java/art/arcane/iris/core/modules/DimensionBottomTest.java @@ -213,8 +213,8 @@ public class DimensionBottomTest { } private void assertSamplesAndBoundsAgree() { - assertEquals(List.of(WHOLE_HEIGHT_OF_ONE_CHUNK), terrainBounds); - assertEquals("the mantle view covers the same heights as the terrain", terrainBounds, viewBounds); + assertEquals("a mantle stage sees the terrain around its chunk, as a chunk stage does", List.of(WHOLE_HEIGHT_AROUND_ONE_CHUNK), terrainBounds); + assertEquals(List.of(WHOLE_HEIGHT_OF_ONE_CHUNK), viewBounds); assertEquals("the terrain samples count from the same bottom", List.of(Double.valueOf(SURFACE_HEIGHT)), surfaces); assertTrue(terrainBounds.getFirst().contains(0, SURFACE_HEIGHT, 0)); } diff --git a/core/src/test/java/art/arcane/iris/core/modules/IrisModuleMantleTest.java b/core/src/test/java/art/arcane/iris/core/modules/IrisModuleMantleTest.java index a0807a793..95cfb9293 100644 --- a/core/src/test/java/art/arcane/iris/core/modules/IrisModuleMantleTest.java +++ b/core/src/test/java/art/arcane/iris/core/modules/IrisModuleMantleTest.java @@ -18,6 +18,7 @@ package art.arcane.iris.core.modules; +import art.arcane.iris.builtin.MatterMantle; import art.arcane.iris.core.loader.IrisData; import art.arcane.iris.engine.framework.Engine; import art.arcane.iris.engine.framework.SeedManager; @@ -34,6 +35,7 @@ import art.arcane.volmlib.util.matter.IrisMatter; import art.arcane.volmlib.util.matter.Matter; import art.arcane.volmlib.util.matter.MatterSlice; import com.volmit.FeatureRegistry; +import com.volmit.block.BlockState; import com.volmit.IrisModule; import com.volmit.ModuleInfo; import com.volmit.host.LoadedPack; @@ -114,6 +116,16 @@ public class IrisModuleMantleTest { return new IrisModuleMantle(bounds, this::chunk, LAYERS, PlannedBlocks.none(bounds)); } + @Test + public void theMatterSideGivesTheMantleChunksTheInvocationReachesAndNoOthers() { + IrisModuleMantle mantle = mantle(new BlockBox(0, 0, 0, 16, HEIGHT, 16)); + MatterMantle matter = MatterMantle.of(mantle); + + org.junit.Assert.assertSame(chunk(3, 4), matter.chunk(3, 4)); + org.junit.Assert.assertNull("nothing is loaded that the host did not say is", matter.loadedChunk(3, 4)); + org.junit.Assert.assertThrows(IllegalArgumentException.class, () -> MatterMantle.of(new InMemoryOnly())); + } + @Test public void layersShareABlockAndReadInWorldCoordinatesAcrossChunks() { IrisModuleMantle mantle = mantle(new BlockBox(-16, 0, -16, 32, HEIGHT, 32)); @@ -335,4 +347,27 @@ public class IrisModuleMantleTest { private static DataInputStream input(byte[] bytes) { return new DataInputStream(new ByteArrayInputStream(bytes)); } + + /** A mantle that is none of Iris's. */ + private static final class InMemoryOnly implements com.volmit.mantle.Mantle { + @Override + public BlockBox bounds() { + return new BlockBox(0, 0, 0, 0, 0, 0); + } + + @Override + public MantleLayer layer(MantleKey key) { + throw new UnsupportedOperationException(); + } + + @Override + public MantleLayer blocks() { + throw new UnsupportedOperationException(); + } + + @Override + public MantleEdit edit() { + throw new UnsupportedOperationException(); + } + } } diff --git a/core/src/test/java/art/arcane/iris/core/modules/PackModuleJarNextToBuiltInsTest.java b/core/src/test/java/art/arcane/iris/core/modules/PackModuleJarNextToBuiltInsTest.java index 358d0fbc3..d37a786c5 100644 --- a/core/src/test/java/art/arcane/iris/core/modules/PackModuleJarNextToBuiltInsTest.java +++ b/core/src/test/java/art/arcane/iris/core/modules/PackModuleJarNextToBuiltInsTest.java @@ -19,7 +19,7 @@ package art.arcane.iris.core.modules; import art.arcane.iris.core.loader.IrisData; -import art.arcane.iris.engine.modifier.CarveModule; +import art.arcane.iris.engine.actuator.TerrainModule; import com.volmit.host.LoadedPack; import org.junit.Rule; import org.junit.Test; @@ -79,7 +79,7 @@ public class PackModuleJarNextToBuiltInsTest { @Test public void aJarModuleWithTheIdOfACompiledInBuiltInFailsAsADuplicate() throws IOException { - String builtInId = new CarveModule().info().id().toString(); + String builtInId = new TerrainModule().info().id().toString(); Path packFolder = BuiltInPack.newPackFolder(folder); PackModuleJar.write(packFolder, "carve.jar", "pack.ported.Ported", Map.of("pack.ported.Ported", module("ported", "Ported", builtInId))); @@ -88,7 +88,7 @@ public class PackModuleJarNextToBuiltInsTest { () -> BuiltInPack.serve(mock(IrisData.class), folder, packFolder, List.of())); assertEquals("Duplicate module " + builtInId + " from " + Path.of("modules", "carve.jar") + " (pack.ported.Ported); already loaded from host classpath (" - + CarveModule.class.getName() + ")", failure.getMessage()); + + TerrainModule.class.getName() + ")", failure.getMessage()); } private static String module(String packageName, String className, String moduleId) { diff --git a/core/src/test/java/art/arcane/iris/engine/framework/EngineCaveBiomeTest.java b/core/src/test/java/art/arcane/iris/engine/framework/EngineCaveBiomeTest.java index e0f89c988..70ad7454c 100644 --- a/core/src/test/java/art/arcane/iris/engine/framework/EngineCaveBiomeTest.java +++ b/core/src/test/java/art/arcane/iris/engine/framework/EngineCaveBiomeTest.java @@ -27,7 +27,6 @@ import art.arcane.iris.engine.IrisComplex; import art.arcane.iris.engine.decorator.DecoratorTestEngines; import art.arcane.iris.engine.object.world.IrisWorld; import art.arcane.iris.engine.object.world.biome.IrisBiome; -import art.arcane.iris.engine.modifier.CaveBiomeBands; import art.arcane.iris.util.project.stream.ProceduralStream; import com.volmit.FeatureRegistry; import com.volmit.IrisModule; @@ -196,15 +195,4 @@ public class EngineCaveBiomeTest { assertEquals(1, depthQuestions.get()); verify(data.getBiomeLoader(), times(1)).load("band/deep"); } - - @Test - public void theCarveModulesProviderReadsTheDepthFromTheBiomesSettings() { - IrisBiome deep = mock(IrisBiome.class); - when(deep.getModuleSettings()).thenReturn(BuiltInPack.settings(new CaveDepthSettings(25))); - IrisBiome plain = mock(IrisBiome.class); - when(plain.getModuleSettings()).thenReturn(BuiltInPack.settings()); - - org.junit.Assert.assertEquals(25, CaveBiomeBands.minDepthBelowSurface(deep)); - org.junit.Assert.assertEquals(0, CaveBiomeBands.minDepthBelowSurface(plain)); - } } diff --git a/core/src/test/java/art/arcane/iris/engine/framework/StructureCaveAnchorResolverTest.java b/core/src/test/java/art/arcane/iris/engine/framework/StructureCaveAnchorResolverTest.java index 40eb961ba..04e955118 100644 --- a/core/src/test/java/art/arcane/iris/engine/framework/StructureCaveAnchorResolverTest.java +++ b/core/src/test/java/art/arcane/iris/engine/framework/StructureCaveAnchorResolverTest.java @@ -1,5 +1,7 @@ package art.arcane.iris.engine.framework; +import art.arcane.iris.builtin.carve.CaveLavaHeightSettings; +import art.arcane.iris.core.modules.BuiltInPack; import art.arcane.iris.engine.object.world.dimension.IrisDimension; import art.arcane.iris.engine.object.structure.IrisStructureAnchorMode; import art.arcane.iris.engine.object.structure.IrisStructurePlacement; @@ -164,7 +166,7 @@ public class StructureCaveAnchorResolverTest { when(engine.getHeight(anyInt(), anyInt(), eq(true))).thenReturn(surfaceHeight); when(engine.getDimension()).thenReturn(dimension); when(dimension.getFluidHeight()).thenReturn(127); - when(dimension.getCaveLavaHeight()).thenReturn(8); + when(dimension.getModuleSettings()).thenReturn(BuiltInPack.settings(new CaveLavaHeightSettings(8))); when(engine.getMantle().getMantle().get( anyInt(), anyInt(), anyInt(), eq(MatterCavern.class))) .thenAnswer(invocation -> { diff --git a/core/src/test/java/art/arcane/iris/engine/mantle/components/CaveCarvingTest.java b/core/src/test/java/art/arcane/iris/engine/mantle/components/CaveCarvingTest.java new file mode 100644 index 000000000..960dc853a --- /dev/null +++ b/core/src/test/java/art/arcane/iris/engine/mantle/components/CaveCarvingTest.java @@ -0,0 +1,131 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.engine.mantle.components; + +import art.arcane.iris.builtin.MatterMantle; +import art.arcane.iris.builtin.carve.CaveProfile; +import art.arcane.iris.core.modules.CarveTestTerrain; +import art.arcane.iris.core.modules.CarveTestWorld; +import art.arcane.iris.core.modules.InMemoryMantle; +import art.arcane.iris.engine.modifier.RecordingCaveDressing; +import art.arcane.iris.engine.object.TestSettings; +import art.arcane.volmlib.util.mantle.runtime.MantleChunk; +import art.arcane.volmlib.util.matter.Matter; +import art.arcane.volmlib.util.matter.MatterCavern; +import com.volmit.FeatureAttachment.Target; +import com.volmit.config.Range; +import com.volmit.noise.NoiseStyle; +import com.volmit.noise.StyledRange; +import com.volmit.world.BiomeSample; +import org.junit.Before; +import org.junit.Test; + +import java.util.Optional; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + +/** The caves a chunk gets: the profile its dimension, region, surface biome and cave biome declare, the last enabled one winning, carved into the mantle. */ +public class CaveCarvingTest { + private static final int HEIGHT = 128; + private static final int SURFACE = 100; + private static final int FLUID_HEIGHT = 30; + private static final int LAVA_HEIGHT = 8; + private static final double EVERYTHING_BELOW = 2D; + + private InMemoryMantle mantle; + private CarveTestWorld world; + + @Before + public void setUp() { + world = newWorld(); + } + + private static CarveTestWorld newWorld() { + return new CarveTestWorld().biome("cave/lush", 1).biome("plains", 1).dressing(new RecordingCaveDressing()); + } + + @Test + public void theDimensionsProfileCarvesWhereNothingNarrowerDeclaresOne() { + world.dimension(profile(true)); + + assertTrue(carvedBlocks(BiomeSample::surfaceBiome) > 0); + } + + @Test + public void aDisabledProfileDeclaresNothingAndTheDimensionsStillCarves() { + world.dimension(profile(true)); + int dimensionOnly = carvedBlocks(BiomeSample::surfaceBiome); + world = newWorld().dimension(profile(true)).declare(Target.REGION, "region", profile(false)); + + assertTrue(dimensionOnly > 0); + assertEquals(dimensionOnly, carvedBlocks(BiomeSample::surfaceBiome)); + } + + @Test + public void anEnabledProfileOfARegionReplacesTheDimensionsWithinItsOwnBounds() { + world.dimension(profile(true)).declare(Target.REGION, "region", TestSettings.with(profile(true), "verticalRange", Range.of(50D, 60D))); + + int carved = carvedBlocks(BiomeSample::surfaceBiome); + + assertTrue(carved > 0); + mantle.chunk(0, 0).iterate(MatterCavern.class, (x, y, z, cavern) -> assertTrue("y=" + y, y >= 50 && y <= 60)); + } + + @Test + public void theCaveBiomeOfAColumnCarvesWithItsOwnProfileWhereTheDimensionDeclaresNone() { + world.declare(Target.BIOME, "cave/lush", profile(true)); + + assertEquals("the surface biome declares none", 0, carvedBlocks(BiomeSample::surfaceBiome)); + assertTrue(carvedBlocks(sample -> sample.caveBiome().orElseThrow()) > 0); + } + + /** Carves chunk 0, 0 with the cave biome of every block {@code caveBiomeOf} says, and counts the blocks of the chunk's mantle that became cave. */ + private int carvedBlocks(java.util.function.Function caveBiomeOf) { + mantle = new InMemoryMantle(HEIGHT / 16); + CarveTestTerrain terrain = new CarveTestTerrain(0, 0, HEIGHT, FLUID_HEIGHT, (x, z) -> SURFACE).biomes((x, y, z) -> { + BiomeSample sample = new BiomeSample(CarveTestWorld.id("region"), CarveTestWorld.id("plains"), Optional.of(CarveTestWorld.id("cave/lush"))); + return new BiomeSample(sample.region(), sample.surfaceBiome(), Optional.of(caveBiomeOf.apply(sample))); + }); + MatterMantle matter = new MatterMantle() { + @Override + public MantleChunk chunk(int chunkX, int chunkZ) { + return mantle.chunk(chunkX, chunkZ); + } + + @Override + public MantleChunk loadedChunk(int chunkX, int chunkZ) { + return null; + } + }; + CarveWorld carveWorld = new CarveWorld(world.resources().noise(), 1337L, HEIGHT, FLUID_HEIGHT, LAVA_HEIGHT, CarveTestWorld.MIN_HEIGHT); + + new CaveCarving(world, carveWorld, false).carve(matter, terrain, 0, 0); + + int[] count = new int[1]; + mantle.chunk(0, 0).iterate(MatterCavern.class, (x, y, z, cavern) -> count[0]++); + return count[0]; + } + + private static CaveProfile profile(boolean enabled) { + return TestSettings.with(new CaveProfile(), "enabled", enabled, "verticalRange", Range.of(20D, 90D), + "densityThreshold", StyledRange.of(EVERYTHING_BELOW, EVERYTHING_BELOW, NoiseStyle.of(NoiseStyle.FLAT)), + "allowSurfaceBreak", false, "allowFluid", false, "adaptiveSampling", false, "sampleStep", 1); + } +} diff --git a/core/src/test/java/art/arcane/iris/engine/mantle/components/CaveCarvingTop2BlendTest.java b/core/src/test/java/art/arcane/iris/engine/mantle/components/CaveCarvingTop2BlendTest.java index 59ea1a06d..ac3b518d9 100644 --- a/core/src/test/java/art/arcane/iris/engine/mantle/components/CaveCarvingTop2BlendTest.java +++ b/core/src/test/java/art/arcane/iris/engine/mantle/components/CaveCarvingTop2BlendTest.java @@ -2,7 +2,6 @@ package art.arcane.iris.engine.mantle.components; import art.arcane.iris.builtin.carve.CaveProfile; import art.arcane.iris.engine.object.TestSettings; -import art.arcane.iris.engine.object.value.IrisRange; import org.junit.BeforeClass; import org.junit.Test; @@ -25,7 +24,7 @@ public class CaveCarvingTop2BlendTest { @BeforeClass public static void setup() throws Exception { Class weightedProfileClass = Class.forName("art.arcane.iris.engine.mantle.components.CaveCarving$WeightedProfile"); - weightedProfileConstructor = weightedProfileClass.getDeclaredConstructor(CaveProfile.class, double[].class, double.class, Class.forName("art.arcane.iris.engine.object.value.IrisRange"), int.class); + weightedProfileConstructor = weightedProfileClass.getDeclaredConstructor(CaveProfile.class, double[].class, double.class, com.volmit.config.Range.class, int.class); weightedProfileConstructor.setAccessible(true); limitMethod = CaveCarving.class.getDeclaredMethod("limitAndMergeBlendedProfiles", List.class, int.class, int.class); limitMethod.setAccessible(true); diff --git a/core/src/test/java/art/arcane/iris/engine/mantle/components/IrisCaveCarver3DNearParityTest.java b/core/src/test/java/art/arcane/iris/engine/mantle/components/IrisCaveCarver3DNearParityTest.java index 7b548e9e4..1a35e4cf6 100644 --- a/core/src/test/java/art/arcane/iris/engine/mantle/components/IrisCaveCarver3DNearParityTest.java +++ b/core/src/test/java/art/arcane/iris/engine/mantle/components/IrisCaveCarver3DNearParityTest.java @@ -1,29 +1,18 @@ package art.arcane.iris.engine.mantle.components; +import art.arcane.iris.builtin.MatterMantle; import art.arcane.iris.builtin.carve.CaveFieldModule; import art.arcane.iris.builtin.carve.CaveProfile; -import art.arcane.iris.engine.object.TestSettings; -import art.arcane.iris.engine.object.noise.IrisGeneratorStyle; -import art.arcane.iris.core.loader.IrisData; +import art.arcane.iris.core.modules.CarveTestWorld; import art.arcane.iris.builtin.terrain.FluidPaletteSettings; -import art.arcane.iris.engine.framework.Engine; -import art.arcane.iris.engine.framework.EngineMetrics; import art.arcane.iris.engine.framework.SeedManager; -import art.arcane.iris.engine.mantle.MantleWriter; -import art.arcane.iris.engine.object.terrain.carving.ResolvedCaveProfile; -import art.arcane.iris.engine.object.world.dimension.IrisDimension; -import art.arcane.iris.engine.object.value.IrisRange; -import art.arcane.iris.engine.object.noise.IrisStyledRange; -import art.arcane.iris.engine.object.world.IrisWorld; -import art.arcane.iris.engine.object.noise.NoiseStyle; -import art.arcane.iris.util.project.noise.CNG; -import art.arcane.volmlib.util.collection.KList; -import art.arcane.volmlib.util.mantle.runtime.Mantle; +import art.arcane.iris.engine.object.TestSettings; import art.arcane.volmlib.util.mantle.runtime.MantleChunk; -import art.arcane.volmlib.util.math.RNG; import art.arcane.volmlib.util.matter.Matter; import art.arcane.volmlib.util.matter.MatterCavern; import art.arcane.volmlib.util.matter.MatterSlice; +import com.volmit.config.Range; +import com.volmit.noise.NoiseSampler; import org.junit.BeforeClass; import org.junit.Test; @@ -53,11 +42,14 @@ public class IrisCaveCarver3DNearParityTest { private static Method sampleDensityMethod; private static Method aquiferCandidateMethod; - private static Field engineField; - private static Field dataField; + private static final int MIN_HEIGHT = 0; + private static final int FLUID_HEIGHT = 64; + private static final int LAVA_HEIGHT = 18; + private static final long CARVE_SEED = new SeedManager(942_337_445L).getCarve(); + private static Field profileField; private static Field surfaceBreakDensityField; - private static Field thresholdRngField; + private static Field thresholdNoiseField; private static Field carveAirField; private static Field carveFluidField; private static Field carveLavaField; @@ -69,16 +61,12 @@ public class IrisCaveCarver3DNearParityTest { sampleDensityMethod.setAccessible(true); aquiferCandidateMethod = IrisCaveCarver3D.class.getDeclaredMethod("isAquiferCandidate", int.class, int.class, int.class, double.class); aquiferCandidateMethod.setAccessible(true); - engineField = IrisCaveCarver3D.class.getDeclaredField("engine"); - engineField.setAccessible(true); - dataField = IrisCaveCarver3D.class.getDeclaredField("data"); - dataField.setAccessible(true); profileField = IrisCaveCarver3D.class.getDeclaredField("profile"); profileField.setAccessible(true); surfaceBreakDensityField = IrisCaveCarver3D.class.getDeclaredField("surfaceBreakDensity"); surfaceBreakDensityField.setAccessible(true); - thresholdRngField = IrisCaveCarver3D.class.getDeclaredField("thresholdRng"); - thresholdRngField.setAccessible(true); + thresholdNoiseField = IrisCaveCarver3D.class.getDeclaredField("thresholdNoise"); + thresholdNoiseField.setAccessible(true); carveAirField = IrisCaveCarver3D.class.getDeclaredField("carveAir"); carveAirField.setAccessible(true); carveFluidField = IrisCaveCarver3D.class.getDeclaredField("carveFluid"); @@ -100,15 +88,15 @@ public class IrisCaveCarver3DNearParityTest { @Test public void carvedCellDistributionStableAcrossEquivalentCarvers() { - Engine engine = createEngine(128, 92); + CarveWorld engine = createEngine(128, 92); IrisCaveCarver3D firstCarver = new IrisCaveCarver3D(engine, createProfile(true, true)); WriterCapture firstCapture = createWriterCapture(128); - int firstCarved = firstCarver.carve(firstCapture.writer, 7, -3); + int firstCarved = firstCarver.carve(firstCapture.writer, 7, -3, fullWeights(), 0D, 0D, null, filledHeights(92)); IrisCaveCarver3D secondCarver = new IrisCaveCarver3D(engine, createProfile(true, true)); WriterCapture secondCapture = createWriterCapture(128); - int secondCarved = secondCarver.carve(secondCapture.writer, 7, -3); + int secondCarved = secondCarver.carve(secondCapture.writer, 7, -3, fullWeights(), 0D, 0D, null, filledHeights(92)); assertTrue(firstCarved > 0); assertEquals(firstCarved, secondCarved); @@ -118,7 +106,7 @@ public class IrisCaveCarver3DNearParityTest { @Test public void warpCacheDoesNotCrossContaminateCarverInstancesOnSameThread() throws Exception { - Engine engine = createEngine(128, 92); + CarveWorld engine = createEngine(128, 92); CaveProfile firstProfile = createProfile(true, false); TestSettings.with(firstProfile, "warpStyle", com.volmit.noise.NoiseStyle.of("SIMPLEX").withZoom(0.12D)); CaveProfile secondProfile = createProfile(true, false); @@ -155,13 +143,13 @@ public class IrisCaveCarver3DNearParityTest { @Test public void exactPathCarvesChunkEdgesAndRespectsWorldHeightClipping() { - Engine engine = createEngine(48, 46); + CarveWorld engine = createEngine(48, 46); IrisCaveCarver3D carver = new IrisCaveCarver3D(engine, createProfile(true, true)); WriterCapture capture = createWriterCapture(48); double[] columnWeights = fullWeights(); int[] precomputedSurfaceHeights = filledHeights(46); - int carved = carver.carve(capture.writer, 0, 0, columnWeights, 0D, 0D, new IrisRange(0D, 80D), precomputedSurfaceHeights); + int carved = carver.carve(capture.writer, 0, 0, columnWeights, 0D, 0D, Range.of(0D, 80D), precomputedSurfaceHeights); assertTrue(carved > 0); assertTrue(hasX(capture.carvedCells, 14)); @@ -190,10 +178,10 @@ public class IrisCaveCarver3DNearParityTest { @Test public void legacySampleStepTwoMatchesExactReference() throws Exception { - Engine engine = createEngine(96, 90); + CarveWorld engine = createEngine(96, 90); double[] columnWeights = fullWeights(); int[] precomputedSurfaceHeights = filledHeights(90); - IrisRange worldYRange = new IrisRange(0D, 88D); + Range worldYRange = Range.of(0D, 88D); CaveProfile exactProfile = TestSettings.with(createProfile(true, true), "sampleStep", 1, "adaptiveSampling", false); IrisCaveCarver3D exactCarver = new IrisCaveCarver3D(engine, exactProfile); @@ -212,19 +200,19 @@ public class IrisCaveCarver3DNearParityTest { @Test public void exactPathUsesExpectedLavaAndForcedAirBands() { - Engine engine = createEngine(48, 46); + CarveWorld engine = createEngine(48, 46); double[] columnWeights = fullWeights(); int[] precomputedSurfaceHeights = filledHeights(46); CaveProfile lavaProfile = TestSettings.with(createProfile(false, false), "allowLava", true, "allowFluid", false); IrisCaveCarver3D lavaCarver = new IrisCaveCarver3D(engine, lavaProfile); WriterCapture lavaCapture = createWriterCapture(48); - lavaCarver.carve(lavaCapture.writer, 0, 0, columnWeights, 0D, 0D, new IrisRange(0D, 80D), precomputedSurfaceHeights); + lavaCarver.carve(lavaCapture.writer, 0, 0, columnWeights, 0D, 0D, Range.of(0D, 80D), precomputedSurfaceHeights); CaveProfile forcedAirProfile = TestSettings.with(createProfile(false, false), "allowLava", false, "allowFluid", false); IrisCaveCarver3D forcedAirCarver = new IrisCaveCarver3D(engine, forcedAirProfile); WriterCapture forcedAirCapture = createWriterCapture(48); - forcedAirCarver.carve(forcedAirCapture.writer, 0, 0, columnWeights, 0D, 0D, new IrisRange(0D, 80D), precomputedSurfaceHeights); + forcedAirCarver.carve(forcedAirCapture.writer, 0, 0, columnWeights, 0D, 0D, Range.of(0D, 80D), precomputedSurfaceHeights); assertTrue(containsLiquidInRange(lavaCapture.carvedLiquids, 0, 18, (byte) 2)); assertTrue(containsLiquidInRange(forcedAirCapture.carvedLiquids, 0, 18, (byte) 3)); @@ -234,7 +222,7 @@ public class IrisCaveCarver3DNearParityTest { @Test public void fluidPrecedesForcedAirWhenLavaIsDisabled() { - Engine engine = createEngine(48, 46); + CarveWorld engine = createEngine(48, 46); int[] surfaceHeights = filledHeights(46); CaveProfile wetProfile = TestSettings.with(createFluidProfile(), "verticalRange", com.volmit.config.Range.of(2D, 18D), "allowLava", false, "fluidRequiresFloor", false); WriterCapture wetCapture = createWriterCapture(48); @@ -255,7 +243,7 @@ public class IrisCaveCarver3DNearParityTest { @Test public void fluidToggleAndMinimumDepthUseEachColumnsTerrainSurface() { - Engine engine = createEngine(80, 70); + CarveWorld engine = createEngine(80, 70); int[] surfaceHeights = splitSurfaceHeights(40, 70); CaveProfile enabledProfile = TestSettings.with(createFluidProfile(), "allowFluid", true, "fluidMinDepthBelowSurface", 10); @@ -278,7 +266,7 @@ public class IrisCaveCarver3DNearParityTest { @Test public void dimensionFluidHeightCapsFluidIntent() { - Engine engine = createEngine(80, 70); + CarveWorld engine = createEngine(80, 70); CaveProfile profile = TestSettings.with(createFluidProfile(), "fluidMinDepthBelowSurface", 0); WriterCapture capture = createWriterCapture(80); @@ -299,7 +287,7 @@ public class IrisCaveCarver3DNearParityTest { @Test public void floorRequiredFluidResolvesAfterTheCompleteCarveMask() { - Engine engine = createEngine(80, 70); + CarveWorld engine = createEngine(80, 70); int[] surfaceHeights = filledHeights(70); int chunkX = -8; int chunkZ = -1; @@ -311,7 +299,7 @@ public class IrisCaveCarver3DNearParityTest { new IrisCaveCarver3D(engine, supportedProfile).carve( firstCapture.writer, chunkX, chunkZ, fullWeights(), 0D, 0D, null, surfaceHeights, null, null, supportPlan); int candidateCount = countLiquid(firstCapture, (byte) 1); - supportPlan.resolve(firstCapture.writer.acquireChunk(chunkX, chunkZ)); + supportPlan.resolve(firstCapture.writer.chunk(chunkX, chunkZ)); CaveProfile repeatedProfile = TestSettings.with(createFluidProfile(), "densityThreshold", cupThreshold, "fluidMinDepthBelowSurface", 0, "fluidRequiresFloor", true); WriterCapture secondCapture = createWriterCapture(80); @@ -333,7 +321,7 @@ public class IrisCaveCarver3DNearParityTest { @Test public void finalFluidSupportRejectsUnknownNeighborChunkEdges() { WriterCapture capture = createWriterCapture(80); - MantleChunk chunk = capture.writer.acquireChunk(0, 0); + MantleChunk chunk = capture.writer.chunk(0, 0); MatterSlice slice = chunk.getOrCreate(3).slice(MatterCavern.class); MatterCavern fluid = new MatterCavern(true, "", (byte) 1); MatterCavern air = new MatterCavern(true, "", (byte) 0); @@ -353,36 +341,38 @@ public class IrisCaveCarver3DNearParityTest { @Test public void floorRequiredFluidSeesLaterProfileCarvePasses() { - Engine engine = createEngine(80, 70); + CarveWorld engine = createEngine(80, 70); int[] surfaceHeights = filledHeights(70); + int chunkX = -8; + int chunkZ = -1; WriterCapture capture = createWriterCapture(80); CaveFluidSupportPlan fluidSupportPlan = new CaveFluidSupportPlan(); - CaveProfile fluidProfile = TestSettings.with(createFluidProfile(), "densityThreshold", com.volmit.noise.StyledRange.of(0.15D, 0.15D, com.volmit.noise.NoiseStyle.of("FLAT")), "fluidRequiresFloor", true); + CaveProfile fluidProfile = TestSettings.with(createFluidProfile(), "densityThreshold", com.volmit.noise.StyledRange.of(0.15D, 0.15D, com.volmit.noise.NoiseStyle.of("FLAT")), "fluidMinDepthBelowSurface", 0, "fluidRequiresFloor", true); CaveProfile airProfile = TestSettings.with(createFluidProfile(), "allowFluid", false); new IrisCaveCarver3D(engine, fluidProfile).carve( - capture.writer, 0, 0, fullWeights(), 0D, 0D, null, surfaceHeights, - null, new IrisRange(20D, 64D), fluidSupportPlan); + capture.writer, chunkX, chunkZ, fullWeights(), 0D, 0D, null, surfaceHeights, + null, Range.of(20D, 64D), fluidSupportPlan); String fluidCell = firstCellWithLiquid(capture, (byte) 1); assertTrue(fluidCell != null); int fluidY = coordinate(fluidCell, 1); new IrisCaveCarver3D(engine, airProfile).carve( - capture.writer, 0, 0, fullWeights(), 0D, 0D, null, surfaceHeights, - null, new IrisRange(fluidY - 1D, fluidY - 1D), fluidSupportPlan); + capture.writer, chunkX, chunkZ, fullWeights(), 0D, 0D, null, surfaceHeights, + null, Range.of(fluidY - 1D, fluidY - 1D), fluidSupportPlan); assertEquals(Byte.valueOf((byte) 1), capture.carvedLiquids.get(fluidCell)); - fluidSupportPlan.resolve(capture.writer.acquireChunk(0, 0)); + fluidSupportPlan.resolve(capture.writer.chunk(chunkX, chunkZ)); assertEquals(Byte.valueOf((byte) 0), capture.carvedLiquids.get(fluidCell)); } @Test public void optimizedExactPathOutperformsNaiveReference() throws Exception { - Engine engine = createEngine(128, 92); + CarveWorld engine = createEngine(128, 92); IrisCaveCarver3D optimizedCarver = new IrisCaveCarver3D(engine, TestSettings.with(createProfile(true, true), "adaptiveSampling", false)); IrisCaveCarver3D naiveCarver = new IrisCaveCarver3D(engine, TestSettings.with(createProfile(true, true), "adaptiveSampling", false)); double[] columnWeights = fullWeights(); int[] precomputedSurfaceHeights = filledHeights(92); - IrisRange worldYRange = new IrisRange(0D, 96D); + Range worldYRange = Range.of(0D, 96D); for (int warmup = 0; warmup < 4; warmup++) { runOptimizedOnce(optimizedCarver, 3, -2, columnWeights, worldYRange, precomputedSurfaceHeights, 128); @@ -411,10 +401,10 @@ public class IrisCaveCarver3DNearParityTest { @Test public void adaptivePathStaysNearExactReferenceWithWarpAndModules() throws Exception { - Engine engine = createEngine(96, 90); + CarveWorld engine = createEngine(96, 90); double[] columnWeights = fullWeights(); int[] precomputedSurfaceHeights = filledHeights(90); - IrisRange worldYRange = new IrisRange(0D, 88D); + Range worldYRange = Range.of(0D, 88D); IrisCaveCarver3D adaptiveCarver = new IrisCaveCarver3D(engine, TestSettings.with(createProfile(true, true), "adaptiveSampling", true)); WriterCapture adaptiveCapture = createWriterCapture(96); @@ -438,7 +428,7 @@ public class IrisCaveCarver3DNearParityTest { } private void assertFlatSurfaceCeiling(CaveProfile profile) { - Engine engine = createEngine(96, 72); + CarveWorld engine = createEngine(96, 72); WriterCapture capture = createWriterCapture(96); new IrisCaveCarver3D(engine, profile).carve( @@ -470,10 +460,10 @@ public class IrisCaveCarver3DNearParityTest { } private void assertExactParity(boolean warp, boolean modules, boolean adaptiveSampling) throws Exception { - Engine engine = createEngine(96, 90); + CarveWorld engine = createEngine(96, 90); double[] columnWeights = fullWeights(); int[] precomputedSurfaceHeights = filledHeights(90); - IrisRange worldYRange = new IrisRange(0D, 88D); + Range worldYRange = Range.of(0D, 88D); IrisCaveCarver3D optimizedCarver = new IrisCaveCarver3D(engine, TestSettings.with(createProfile(warp, modules), "adaptiveSampling", adaptiveSampling)); WriterCapture optimizedCapture = createWriterCapture(96); @@ -481,14 +471,14 @@ public class IrisCaveCarver3DNearParityTest { IrisCaveCarver3D naiveCarver = new IrisCaveCarver3D(engine, TestSettings.with(createProfile(warp, modules), "adaptiveSampling", false)); WriterCapture naiveCapture = createWriterCapture(96); - int naiveCarved = carveNaiveExact(naiveCarver, naiveCapture.writer, 5, -1, columnWeights, worldYRange, precomputedSurfaceHeights); + int naiveCarved = carveNaiveExact(naiveCarver, naiveCapture.writer, 96, 5, -1, columnWeights, worldYRange, precomputedSurfaceHeights); assertEquals(optimizedCarved, naiveCarved); assertEquals(optimizedCapture.carvedCells, naiveCapture.carvedCells); assertEquals(optimizedCapture.carvedLiquids, naiveCapture.carvedLiquids); } - private long runOptimizedOnce(IrisCaveCarver3D carver, int chunkX, int chunkZ, double[] columnWeights, IrisRange worldYRange, int[] precomputedSurfaceHeights, int worldHeight) { + private long runOptimizedOnce(IrisCaveCarver3D carver, int chunkX, int chunkZ, double[] columnWeights, Range worldYRange, int[] precomputedSurfaceHeights, int worldHeight) { WriterCapture capture = createWriterCapture(worldHeight); long start = System.nanoTime(); carver.carve(capture.writer, chunkX, chunkZ, columnWeights, 0D, 0D, worldYRange, precomputedSurfaceHeights); @@ -501,21 +491,19 @@ public class IrisCaveCarver3DNearParityTest { return (double) sampleDensityMethod.invoke(carver, x, y, z); } - private long runNaiveOnce(IrisCaveCarver3D carver, int chunkX, int chunkZ, double[] columnWeights, IrisRange worldYRange, int[] precomputedSurfaceHeights, int worldHeight) throws Exception { + private long runNaiveOnce(IrisCaveCarver3D carver, int chunkX, int chunkZ, double[] columnWeights, Range worldYRange, int[] precomputedSurfaceHeights, int worldHeight) throws Exception { WriterCapture capture = createWriterCapture(worldHeight); long start = System.nanoTime(); - int carved = carveNaiveExact(carver, capture.writer, chunkX, chunkZ, columnWeights, worldYRange, precomputedSurfaceHeights); + int carved = carveNaiveExact(carver, capture.writer, worldHeight, chunkX, chunkZ, columnWeights, worldYRange, precomputedSurfaceHeights); long elapsed = System.nanoTime() - start; assertTrue(carved > 0); return elapsed; } - private int carveNaiveExact(IrisCaveCarver3D carver, MantleWriter writer, int chunkX, int chunkZ, double[] columnWeights, IrisRange worldYRange, int[] precomputedSurfaceHeights) throws Exception { - Engine engine = (Engine) engineField.get(carver); - IrisData data = (IrisData) dataField.get(carver); + private int carveNaiveExact(IrisCaveCarver3D carver, MatterMantle writer, int worldHeight, int chunkX, int chunkZ, double[] columnWeights, Range worldYRange, int[] precomputedSurfaceHeights) throws Exception { CaveProfile profile = (CaveProfile) profileField.get(carver); - CNG surfaceBreakDensity = (CNG) surfaceBreakDensityField.get(carver); - RNG thresholdRng = (RNG) thresholdRngField.get(carver); + NoiseSampler surfaceBreakDensity = (NoiseSampler) surfaceBreakDensityField.get(carver); + NoiseSampler thresholdNoise = (NoiseSampler) thresholdNoiseField.get(carver); MatterCavern carveAir = (MatterCavern) carveAirField.get(carver); MatterCavern carveFluid = (MatterCavern) carveFluidField.get(carver); MatterCavern carveLava = (MatterCavern) carveLavaField.get(carver); @@ -526,13 +514,11 @@ public class IrisCaveCarver3DNearParityTest { resolvedWeights = fullWeights(); } - int worldHeight = writer.getMantle().getWorldHeight(); int minY = Math.max(0, (int) Math.floor(profile.verticalRange().min())); int maxY = Math.min(worldHeight - 1, (int) Math.ceil(profile.verticalRange().max())); if (worldYRange != null) { - int worldMinHeight = engine.getWorld().minHeight(); - int rangeMinY = (int) Math.floor(worldYRange.getMin() - worldMinHeight); - int rangeMaxY = (int) Math.ceil(worldYRange.getMax() - worldMinHeight); + int rangeMinY = (int) Math.floor(worldYRange.min() - MIN_HEIGHT); + int rangeMaxY = (int) Math.ceil(worldYRange.max() - MIN_HEIGHT); minY = Math.max(minY, rangeMinY); maxY = Math.min(maxY, rangeMaxY); } @@ -553,7 +539,7 @@ public class IrisCaveCarver3DNearParityTest { double[] passThreshold = new double[256]; double[] verticalEdgeFade = computeVerticalEdgeFade(profile, minY, maxY); double[] surfaceClosureThreshold = computeSurfaceClosureThresholds(profile, minY, maxY); - MatterCavern[] matterByY = computeMatterByY(engine, profile, carveAir, carveLava, carveForcedAir, minY, maxY); + MatterCavern[] matterByY = computeMatterByY(profile, carveAir, carveLava, carveForcedAir, minY, maxY); int x0 = chunkX << 4; int z0 = chunkZ << 4; @@ -562,20 +548,15 @@ public class IrisCaveCarver3DNearParityTest { for (int localZ = 0; localZ < 16; localZ++) { int z = z0 + localZ; int columnIndex = (localX << 4) | localZ; - int columnSurfaceY; - if (precomputedSurfaceHeights != null && precomputedSurfaceHeights.length > columnIndex) { - columnSurfaceY = precomputedSurfaceHeights[columnIndex]; - } else { - columnSurfaceY = engine.getHeight(x, z); - } + int columnSurfaceY = precomputedSurfaceHeights[columnIndex]; int unclampedClearanceTopY = columnSurfaceY - surfaceClearance; int clearanceTopY = Math.min(maxY, Math.max(minY, unclampedClearanceTopY)); - boolean breakColumn = allowSurfaceBreak && signed(surfaceBreakDensity.noiseFast2D(x, z)) >= surfaceBreakNoiseThreshold; + boolean breakColumn = allowSurfaceBreak && surfaceBreakDensity.signed(x, z) >= surfaceBreakNoiseThreshold; int resolvedTopY = breakColumn ? Math.min(maxY, Math.max(minY, columnSurfaceY)) : clearanceTopY; columnTopY[columnIndex] = resolvedTopY; fluidMaxY[columnIndex] = profile.allowFluid() - ? Math.min(engine.getDimension().getFluidHeight(), columnSurfaceY - Math.max(0, profile.fluidMinDepthBelowSurface())) + ? Math.min(FLUID_HEIGHT, columnSurfaceY - Math.max(0, profile.fluidMinDepthBelowSurface())) : Integer.MIN_VALUE; surfaceBreakFloorY[columnIndex] = Math.max(minY, columnSurfaceY - surfaceBreakDepth); surfaceBreakColumn[columnIndex] = breakColumn; @@ -586,12 +567,12 @@ public class IrisCaveCarver3DNearParityTest { continue; } - passThreshold[columnIndex] = ResolvedCaveProfile.of(profile).densityThreshold().get(thresholdRng, x, z, data) - profile.thresholdBias(); + passThreshold[columnIndex] = thresholdAt(profile, thresholdNoise, x, z) - profile.thresholdBias(); } } @SuppressWarnings("unchecked") - MantleChunk chunk = writer.acquireChunk(chunkX, chunkZ); + MantleChunk chunk = writer.chunk(chunkX, chunkZ); if (chunk == null) { return 0; } @@ -643,6 +624,18 @@ public class IrisCaveCarver3DNearParityTest { return carved; } + /** The density threshold at the column the way a styled range picks it. */ + private double thresholdAt(CaveProfile profile, NoiseSampler thresholdNoise, int x, int z) { + com.volmit.noise.StyledRange range = profile.densityThreshold(); + if (range.min() == range.max()) { + return range.min(); + } + if (com.volmit.noise.NoiseStyle.FLAT.equals(range.style().style())) { + return art.arcane.volmlib.util.math.M.lerp(range.min(), range.max(), 0.5); + } + return range.min() + (thresholdNoise.sample(x, z) * (range.max() - range.min())); + } + private double applySurfaceCeilingFade( double threshold, boolean surfaceCeilingColumn, @@ -672,7 +665,7 @@ public class IrisCaveCarver3DNearParityTest { private double[] computeSurfaceClosureThresholds(CaveProfile profile, int minY, int maxY) { double normalization = Math.abs(profile.baseWeight()) + Math.abs(profile.detailWeight()); - for (ResolvedCaveProfile.Module module : ResolvedCaveProfile.of(profile).modules()) { + for (CaveFieldModule module : profile.modules()) { normalization += Math.abs(module.weight()); } if (normalization <= 0D) { @@ -683,9 +676,9 @@ public class IrisCaveCarver3DNearParityTest { double baseMinimum = -Math.abs(profile.baseWeight()) - Math.abs(profile.detailWeight()); for (int y = minY; y <= maxY; y++) { double minimumDensity = baseMinimum; - for (ResolvedCaveProfile.Module module : ResolvedCaveProfile.of(profile).modules()) { - IrisRange range = module.verticalRange(); - if (y < Math.floor(range.getMin()) || y > Math.ceil(range.getMax())) { + for (CaveFieldModule module : profile.modules()) { + Range range = module.verticalRange(); + if (y < Math.floor(range.min()) || y > Math.ceil(range.max())) { continue; } double rawMinimum = module.invert() @@ -727,10 +720,10 @@ public class IrisCaveCarver3DNearParityTest { return verticalEdgeFade; } - private MatterCavern[] computeMatterByY(Engine engine, CaveProfile profile, MatterCavern carveAir, MatterCavern carveLava, MatterCavern carveForcedAir, int minY, int maxY) { + private MatterCavern[] computeMatterByY(CaveProfile profile, MatterCavern carveAir, MatterCavern carveLava, MatterCavern carveForcedAir, int minY, int maxY) { MatterCavern[] matterByY = new MatterCavern[Math.max(0, maxY - minY + 1)]; boolean allowLava = profile.allowLava(); - int lavaHeight = engine.getDimension().getCaveLavaHeight(); + int lavaHeight = LAVA_HEIGHT; for (int y = minY; y <= maxY; y++) { int offset = y - minY; @@ -749,25 +742,9 @@ public class IrisCaveCarver3DNearParityTest { return matterByY; } - private Engine createEngine(int worldHeight, int sampledHeight) { - Engine engine = mock(Engine.class); - IrisData data = mock(IrisData.class); - IrisDimension dimension = mock(IrisDimension.class); - SeedManager seedManager = new SeedManager(942_337_445L); - EngineMetrics metrics = new EngineMetrics(16); - IrisWorld world = IrisWorld.builder().minHeight(0).maxHeight(worldHeight).build(); - - doReturn(data).when(engine).getData(); - doReturn(dimension).when(engine).getDimension(); - doReturn(seedManager).when(engine).getSeedManager(); - doReturn(metrics).when(engine).getMetrics(); - doReturn(world).when(engine).getWorld(); - doReturn(sampledHeight).when(engine).getHeight(anyInt(), anyInt()); - - doReturn(18).when(dimension).getCaveLavaHeight(); - doReturn(64).when(dimension).getFluidHeight(); - - return engine; + private CarveWorld createEngine(int worldHeight, int sampledHeight) { + CarveTestWorld world = new CarveTestWorld(); + return new CarveWorld(world.resources().noise(), CARVE_SEED, worldHeight, FLUID_HEIGHT, LAVA_HEIGHT, MIN_HEIGHT); } private CaveProfile createProfile(boolean warp, boolean modules) { @@ -812,7 +789,7 @@ public class IrisCaveCarver3DNearParityTest { } private void assertSurfaceFluidBoundaryForProfile(CaveProfile profile) { - Engine engine = createEngine(80, 70); + CarveWorld engine = createEngine(80, 70); int[] surfaceHeights = filledHeights(70); surfaceHeights[0] = 60; int[] boundaryStartY = new int[256]; @@ -849,9 +826,6 @@ public class IrisCaveCarver3DNearParityTest { } private WriterCapture createWriterCapture(int worldHeight) { - MantleWriter writer = mock(MantleWriter.class); - @SuppressWarnings("unchecked") - Mantle mantle = mock(Mantle.class); @SuppressWarnings("unchecked") MantleChunk chunk = mock(MantleChunk.class); Map sections = new HashMap<>(); @@ -859,9 +833,6 @@ public class IrisCaveCarver3DNearParityTest { Set carvedCells = new HashSet<>(); Map carvedLiquids = new HashMap<>(); - doReturn(mantle).when(writer).getMantle(); - doReturn(worldHeight).when(mantle).getWorldHeight(); - doReturn(chunk).when(writer).acquireChunk(anyInt(), anyInt()); doAnswer(invocation -> sections.get(invocation.getArgument(0, Integer.class))).when(chunk).get(anyInt()); doAnswer(invocation -> { int sectionIndex = invocation.getArgument(0); @@ -875,7 +846,18 @@ public class IrisCaveCarver3DNearParityTest { return created; }).when(chunk).getOrCreate(anyInt()); - return new WriterCapture(writer, carvedCells, carvedLiquids); + MatterMantle mantle = new MatterMantle() { + @Override + public MantleChunk chunk(int chunkX, int chunkZ) { + return chunk; + } + + @Override + public MantleChunk loadedChunk(int chunkX, int chunkZ) { + return null; + } + }; + return new WriterCapture(mantle, carvedCells, carvedLiquids); } private Matter createSection(int sectionIndex, Map> sectionCells, Set carvedCells, Map carvedLiquids) { @@ -1101,11 +1083,11 @@ public class IrisCaveCarver3DNearParityTest { } private static final class WriterCapture { - private final MantleWriter writer; + private final MatterMantle writer; private final Set carvedCells; private final Map carvedLiquids; - private WriterCapture(MantleWriter writer, Set carvedCells, Map carvedLiquids) { + private WriterCapture(MatterMantle writer, Set carvedCells, Map carvedLiquids) { this.writer = writer; this.carvedCells = carvedCells; this.carvedLiquids = carvedLiquids; diff --git a/core/src/test/java/art/arcane/iris/engine/modifier/ApiChunk.java b/core/src/test/java/art/arcane/iris/engine/modifier/ApiChunk.java index 62ce3a031..ef8da1125 100644 --- a/core/src/test/java/art/arcane/iris/engine/modifier/ApiChunk.java +++ b/core/src/test/java/art/arcane/iris/engine/modifier/ApiChunk.java @@ -18,6 +18,11 @@ package art.arcane.iris.engine.modifier; +import art.arcane.iris.builtin.CaveDressing; +import art.arcane.iris.builtin.MatterMantle; +import art.arcane.volmlib.util.mantle.runtime.MantleChunk; +import art.arcane.volmlib.util.matter.Matter; +import com.volmit.noise.NoiseSampler; import art.arcane.iris.builtin.IrisStages; import art.arcane.iris.builtin.IrisSeed; import art.arcane.iris.builtin.post.PostProcessingSlabsSettings; @@ -82,6 +87,7 @@ import java.util.Set; import java.util.UUID; import java.util.function.Function; import java.util.function.IntBinaryOperator; +import static org.mockito.Mockito.mock; /** * One chunk as IrisApi shows it to a chunk stage, held in memory, so the ported built-ins are tested through the surface @@ -96,6 +102,7 @@ public final class ApiChunk implements GenerationContext { private static final ResourceId DIMENSION = ResourceId.parse("test:dimension/overworld"); private static final ResourceId BIOME = ResourceId.parse("test:biome/plains"); private static final int TERRAIN_MARGIN = 16; + private static final double FLAT_NOISE = 0.5D; private static final Set AIRS = Set.of("minecraft:air", "minecraft:cave_air", "minecraft:void_air"); private static final Set FLUIDS = Set.of("minecraft:water", "minecraft:lava"); private static final Set DECORATIONS = Set.of("minecraft:short_grass", "minecraft:poppy", "minecraft:tall_grass", @@ -197,9 +204,9 @@ public final class ApiChunk implements GenerationContext { return TestSettings.with(new PaletteLayer(), "palette", List.of(BlockSpec.of(block.key())), "slopeCondition", slope); } - /** Empty stand-ins for the built-in stages the ported modules order after: carving and floating islands. */ + /** Empty stand-ins for the built-in stages the ported modules order after or require: terrain and floating islands. */ public static List standIns() { - return List.of(new CarveStandIn(), new FloatingStandIn()); + return List.of(new TerrainStandIn(), new FloatingStandIn()); } /** Runs {@code modules} as a pack's chunk graph, with the {@link #standIns()}. */ @@ -323,7 +330,20 @@ public final class ApiChunk implements GenerationContext { } } - private final class ChunkMantle implements Mantle { + private final class ChunkMantle implements Mantle, MatterMantle { + private final MantleChunk noCaves = mock(MantleChunk.class); + + /** The matter of the chunk: none; a test of caves brings its own mantle. */ + @Override + public MantleChunk chunk(int chunkX, int chunkZ) { + return noCaves; + } + + @Override + public MantleChunk loadedChunk(int chunkX, int chunkZ) { + return null; + } + @Override public BlockBox bounds() { return chunkColumns(); @@ -382,7 +402,7 @@ public final class ApiChunk implements GenerationContext { } /** A world of the chunk: its pack's blocks, a state store and Iris's seeds, each the world seed plus its place. */ - private static final class World implements PackWorld, IrisSeed.Source { + private static final class World implements PackWorld, IrisSeed.Source, CaveDressing.Source { private final Resources resources = new Resources(); private final Map, Object> states = new HashMap<>(); @@ -398,7 +418,17 @@ public final class ApiChunk implements GenerationContext { @Override public PackSettings settings() { - throw new UnsupportedOperationException("No pack settings here"); + return new PackSettings() { + @Override + public List> declared(Class featureType) { + return List.of(); + } + }; + } + + @Override + public CaveDressing caveDressing() { + return new RecordingCaveDressing(); } @Override @@ -452,7 +482,17 @@ public final class ApiChunk implements GenerationContext { @Override public NoiseFactory noise() { - throw new UnsupportedOperationException("No noise here"); + return (style, seed) -> new NoiseSampler() { + @Override + public double sample(double worldX, double worldZ) { + return FLAT_NOISE; + } + + @Override + public double sample(double worldX, double y, double worldZ) { + return FLAT_NOISE; + } + }; } @Override @@ -535,15 +575,15 @@ public final class ApiChunk implements GenerationContext { } } - private static final class CarveStandIn implements IrisModule { + private static final class TerrainStandIn implements IrisModule { @Override public ModuleInfo info() { - return ModuleInfo.of("iris:carve", "Carving stand-in", "test"); + return ModuleInfo.of("iris:terrain", "Terrain stand-in", "test"); } @Override public void install(StageGraph graph) { - graph.define(IrisStages.Carve.APPLY).run(context -> { + graph.define(IrisStages.Terrain.SHAPE).run(context -> { }); } } diff --git a/core/src/test/java/art/arcane/iris/engine/modifier/CaveApplyingBoundarySupportTest.java b/core/src/test/java/art/arcane/iris/engine/modifier/CaveApplyingBoundarySupportTest.java index 1bbb9b6b2..9cfd47efc 100644 --- a/core/src/test/java/art/arcane/iris/engine/modifier/CaveApplyingBoundarySupportTest.java +++ b/core/src/test/java/art/arcane/iris/engine/modifier/CaveApplyingBoundarySupportTest.java @@ -1,64 +1,47 @@ package art.arcane.iris.engine.modifier; -import art.arcane.iris.core.loader.IrisData; -import art.arcane.iris.core.loader.ResourceLoader; -import art.arcane.iris.engine.UsableBlockPlatform; -import art.arcane.iris.engine.decorator.DecoratorTestEngines; -import art.arcane.iris.engine.framework.Engine; -import art.arcane.iris.engine.framework.SeedManager; -import art.arcane.iris.engine.object.world.biome.IrisBiome; -import art.arcane.iris.spi.PlatformBlockState; -import art.arcane.iris.util.project.hunk.Hunk; +import art.arcane.iris.builtin.MatterMantle; +import art.arcane.iris.core.modules.CarveTestWorld; +import art.arcane.iris.engine.mantle.components.CarveWorld; import art.arcane.volmlib.util.mantle.runtime.MantleChunk; import art.arcane.volmlib.util.matter.Matter; import art.arcane.volmlib.util.matter.MatterCavern; import art.arcane.volmlib.util.matter.MatterSlice; -import com.volmit.host.ModuleLogs; -import it.unimi.dsi.fastutil.longs.Long2ObjectOpenHashMap; -import org.junit.After; -import org.junit.Before; +import com.volmit.block.BlockState; +import com.volmit.host.ArrayHunk; +import com.volmit.hunk.Hunk; +import com.volmit.mantle.BlockBox; +import com.volmit.resource.ResourceId; +import com.volmit.world.BiomeSample; +import com.volmit.world.TerrainSample; +import com.volmit.world.TerrainSampler; import org.junit.Test; import java.util.HashMap; import java.util.Map; +import java.util.Optional; +import java.util.OptionalInt; +import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertSame; import static org.junit.Assert.assertTrue; -import static org.mockito.ArgumentMatchers.anyInt; -import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.mock; public class CaveApplyingBoundarySupportTest { - @Before - public void bindPlatform() { - UsableBlockPlatform.bind(); - } + private static final int CEILING_Y = 42; + private static final BlockState AIR = new BlockState("minecraft:cave_air"); + private static final BlockState STONE = new BlockState("minecraft:stone"); + private static final BlockState SAND = new BlockState("minecraft:sand"); - @After - public void unbindPlatform() { - UsableBlockPlatform.unbind(); - } + private final CarveTestWorld world = new CarveTestWorld().biome("custom/floor", 1).dressing(new RecordingCaveDressing()); + private final CaveBlockClasses classes = new CaveBlockClasses(new CarveTestWorld.Blocks()); @Test @SuppressWarnings("unchecked") public void boundaryBiomeUsesCustomMatterAtItsOwnY() { - IrisBiome customFloor = mock(IrisBiome.class); - IrisBiome resolvedCeiling = mock(IrisBiome.class); - IrisData data = mock(IrisData.class); - ResourceLoader biomeLoader = mock(ResourceLoader.class); - doReturn(biomeLoader).when(data).getBiomeLoader(); - doReturn(customFloor).when(biomeLoader).load("custom/floor"); - - Engine engine = mock(Engine.class); - doReturn(data).when(engine).getData(); - doReturn(resolvedCeiling).when(engine).getCaveBiome(anyInt(), eq(42), anyInt()); - - doReturn(mock(SeedManager.class)).when(engine).getSeedManager(); - DecoratorTestEngines.withGeneration(engine); - CaveApplying modifier = new CaveApplying(engine, ModuleLogs.discarding()); - + ResourceId resolvedCeiling = CarveTestWorld.id("cave/ceiling"); + CaveApplying modifier = new CaveApplying(world, new CarveWorld(world.resources().noise(), 1L, 384, 127, 8, CarveTestWorld.MIN_HEIGHT), false); MantleChunk mantleChunk = mock(MantleChunk.class); Matter floorMatter = mock(Matter.class); Matter ceilingMatter = mock(Matter.class); @@ -73,58 +56,86 @@ public class CaveApplyingBoundarySupportTest { doReturn(floorSlice).when(floorMatter).getSlice(MatterCavern.class); doReturn(ceilingSlice).when(ceilingMatter).getSlice(MatterCavern.class); doReturn(new MatterCavern(true, "custom/floor", (byte) 0)).when(floorSlice).get(1, 6, 2); - doReturn(null).when(ceilingSlice).get(1, 10, 2); + doReturn(null).when(ceilingSlice).get(1, CEILING_Y & 15, 2); + TerrainSampler terrain = new CaveBiomeTerrain((x, y, z) -> y == CEILING_Y ? Optional.of(resolvedCeiling) : Optional.empty()); + CaveApplying.Application application = modifier.new Application(chunkOnly(mantleChunk), mantleChunk, terrain, 2, 2, new ArrayHunk<>(BlockState.class, 16, 64, 16, AIR)); + Map customBiomeCache = new HashMap<>(); - Long2ObjectOpenHashMap caveBiomeCache = new Long2ObjectOpenHashMap<>(); - Map customBiomeCache = new HashMap<>(); + ResourceId floor = application.resolveCaveBoundaryBiome(1, 6, 2, 40, 44, customBiomeCache); + ResourceId ceiling = application.resolveCaveBoundaryBiome(1, CEILING_Y, 2, 40, 44, customBiomeCache); - IrisBiome floor = modifier.resolveCaveBoundaryBiome( - mantleChunk, 1, 6, 2, 40, 44, caveBiomeCache, customBiomeCache); - IrisBiome ceiling = modifier.resolveCaveBoundaryBiome( - mantleChunk, 1, 42, 2, 40, 44, caveBiomeCache, customBiomeCache); - - assertSame(customFloor, floor); - assertSame(resolvedCeiling, ceiling); + assertEquals(CarveTestWorld.id("custom/floor"), floor); + assertEquals(resolvedCeiling, ceiling); } @Test - @SuppressWarnings("unchecked") public void gravityFloorLayerRequiresSolidSupportBelowItsTarget() { - Hunk output = mock(Hunk.class); - PlatformBlockState air = state("minecraft:cave_air", false); - PlatformBlockState solid = state("minecraft:stone", true); - PlatformBlockState sand = state("minecraft:sand", true); - PlatformBlockState stone = state("minecraft:stone", true); - - doReturn(air).when(output).getRaw(0, 4, 0); - assertFalse(CaveApplying.canReplaceCaveFloorLayer(output, 0, 5, 0, sand)); - assertTrue(CaveApplying.canReplaceCaveFloorLayer(output, 0, 5, 0, stone)); - - doReturn(solid).when(output).getRaw(0, 4, 0); - assertTrue(CaveApplying.canReplaceCaveFloorLayer(output, 0, 5, 0, sand)); + Hunk output = new ArrayHunk<>(BlockState.class, 1, 8, 1, AIR); + output.set(0, 4, 0, AIR); + assertFalse(CaveApplying.canReplaceCaveFloorLayer(output, 0, 5, 0, SAND, classes)); + assertTrue(CaveApplying.canReplaceCaveFloorLayer(output, 0, 5, 0, STONE, classes)); + output.set(0, 4, 0, STONE); + assertTrue(CaveApplying.canReplaceCaveFloorLayer(output, 0, 5, 0, SAND, classes)); } @Test - @SuppressWarnings("unchecked") public void gravityFloorDoesNotReceiveDecoratorsOverLowerCaveAir() { - Hunk output = mock(Hunk.class); - PlatformBlockState air = state("minecraft:cave_air", false); - PlatformBlockState sand = state("minecraft:sand", true); - PlatformBlockState stone = state("minecraft:stone", true); - - doReturn(sand).when(output).getRaw(0, 5, 0); - doReturn(air).when(output).getRaw(0, 4, 0); - assertFalse(CaveApplying.hasStableCaveFloorSupport(output, 0, 6, 0)); - - doReturn(stone).when(output).getRaw(0, 4, 0); - assertTrue(CaveApplying.hasStableCaveFloorSupport(output, 0, 6, 0)); + Hunk output = new ArrayHunk<>(BlockState.class, 1, 8, 1, AIR); + output.set(0, 5, 0, SAND); + output.set(0, 4, 0, AIR); + assertFalse(CaveApplying.hasStableCaveFloorSupport(output, 0, 6, 0, classes)); + output.set(0, 4, 0, STONE); + assertTrue(CaveApplying.hasStableCaveFloorSupport(output, 0, 6, 0, classes)); } - private PlatformBlockState state(String key, boolean solid) { - PlatformBlockState state = mock(PlatformBlockState.class); - doReturn(key).when(state).key(); - doReturn(solid).when(state).isSolid(); - doReturn(key.equals("minecraft:sand")).when(state).hasGravity(); - return state; + private static MatterMantle chunkOnly(MantleChunk chunk) { + return new MatterMantle() { + @Override + public MantleChunk chunk(int chunkX, int chunkZ) { + return chunk; + } + + @Override + public MantleChunk loadedChunk(int chunkX, int chunkZ) { + return null; + } + }; + } + + /** Terrain that knows cave biomes only. */ + private record CaveBiomeTerrain(CaveBiomeAt biomes) implements TerrainSampler { + interface CaveBiomeAt { + Optional at(int x, int y, int z); + } + + @Override + public Optional caveBiome(int worldX, int y, int worldZ) { + return biomes.at(worldX, y, worldZ); + } + + @Override + public BlockBox bounds() { + throw new UnsupportedOperationException(); + } + + @Override + public TerrainSample column(int worldX, int worldZ) { + throw new UnsupportedOperationException(); + } + + @Override + public BiomeSample biome(int worldX, int y, int worldZ) { + throw new UnsupportedOperationException(); + } + + @Override + public int fluidHeight() { + throw new UnsupportedOperationException(); + } + + @Override + public OptionalInt upperDimensionY(int worldX, int worldZ) { + throw new UnsupportedOperationException(); + } } } diff --git a/core/src/test/java/art/arcane/iris/engine/modifier/CaveApplyingFluidIntentTest.java b/core/src/test/java/art/arcane/iris/engine/modifier/CaveApplyingFluidIntentTest.java index 18b787baf..42bf027f6 100644 --- a/core/src/test/java/art/arcane/iris/engine/modifier/CaveApplyingFluidIntentTest.java +++ b/core/src/test/java/art/arcane/iris/engine/modifier/CaveApplyingFluidIntentTest.java @@ -1,15 +1,13 @@ package art.arcane.iris.engine.modifier; -import art.arcane.iris.spi.PlatformBlockState; import art.arcane.volmlib.util.matter.MatterCavern; +import com.volmit.block.BlockState; import org.junit.Test; 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.Mockito.mock; -import static org.mockito.Mockito.when; public class CaveApplyingFluidIntentTest { @Test @@ -18,18 +16,17 @@ public class CaveApplyingFluidIntentTest { MatterCavern fluidIntent = new MatterCavern(true, "", (byte) 1); MatterCavern lavaIntent = new MatterCavern(true, "", (byte) 2); MatterCavern forcedAirIntent = new MatterCavern(true, "", (byte) 3); - PlatformBlockState existingFluid = mock(PlatformBlockState.class); - PlatformBlockState fluid = mock(PlatformBlockState.class); - PlatformBlockState lava = mock(PlatformBlockState.class); - PlatformBlockState air = mock(PlatformBlockState.class); - when(existingFluid.isFluid()).thenReturn(true); + BlockState fluid = new BlockState("minecraft:water"); + BlockState lava = new BlockState("minecraft:lava"); + BlockState air = new BlockState("minecraft:cave_air"); assertFalse(CaveApplying.hasExplicitCarveIntent(null)); - assertTrue(CaveApplying.shouldPreserveExistingFluid(airIntent, existingFluid)); + assertTrue(CaveApplying.shouldPreserveExistingFluid(airIntent, true)); assertTrue(CaveApplying.isFluidIntent(fluidIntent)); - assertFalse(CaveApplying.shouldPreserveExistingFluid(fluidIntent, existingFluid)); - assertFalse(CaveApplying.shouldPreserveExistingFluid(lavaIntent, existingFluid)); - assertFalse(CaveApplying.shouldPreserveExistingFluid(forcedAirIntent, existingFluid)); + assertFalse(CaveApplying.shouldPreserveExistingFluid(fluidIntent, true)); + assertFalse(CaveApplying.shouldPreserveExistingFluid(lavaIntent, true)); + assertFalse(CaveApplying.shouldPreserveExistingFluid(forcedAirIntent, true)); + assertFalse("nothing to preserve where there is no fluid", CaveApplying.shouldPreserveExistingFluid(airIntent, false)); assertNull(CaveApplying.resolveExplicitCarveState(null, fluid, lava, air)); assertSame(fluid, CaveApplying.resolveExplicitCarveState(fluidIntent, fluid, lava, air)); assertSame(lava, CaveApplying.resolveExplicitCarveState(lavaIntent, fluid, lava, air)); @@ -46,17 +43,8 @@ public class CaveApplyingFluidIntentTest { @Test public void unsupportedSurfaceOreIsRemovedOnlyOverCarvedAir() { - PlatformBlockState ore = mock(PlatformBlockState.class); - PlatformBlockState ordinarySurface = mock(PlatformBlockState.class); - PlatformBlockState air = mock(PlatformBlockState.class); - PlatformBlockState solid = mock(PlatformBlockState.class); - when(ore.isOre()).thenReturn(true); - when(ordinarySurface.isOre()).thenReturn(false); - when(air.isSolid()).thenReturn(false); - when(solid.isSolid()).thenReturn(true); - - assertTrue(CaveApplying.isUnsupportedSurfaceOre(ore, air)); - assertFalse(CaveApplying.isUnsupportedSurfaceOre(ore, solid)); - assertFalse(CaveApplying.isUnsupportedSurfaceOre(ordinarySurface, air)); + assertTrue(CaveApplying.isUnsupportedSurfaceOre(true, false)); + assertFalse(CaveApplying.isUnsupportedSurfaceOre(true, true)); + assertFalse(CaveApplying.isUnsupportedSurfaceOre(false, false)); } } diff --git a/core/src/test/java/art/arcane/iris/engine/modifier/CaveApplyingInferenceIsolationTest.java b/core/src/test/java/art/arcane/iris/engine/modifier/CaveApplyingInferenceIsolationTest.java deleted file mode 100644 index 4e63286b6..000000000 --- a/core/src/test/java/art/arcane/iris/engine/modifier/CaveApplyingInferenceIsolationTest.java +++ /dev/null @@ -1,129 +0,0 @@ -package art.arcane.iris.engine.modifier; - -import art.arcane.iris.builtin.terrain.LayersSettings; -import art.arcane.iris.core.loader.IrisData; -import art.arcane.iris.core.modules.BuiltInPack; -import art.arcane.iris.engine.IrisComplex; -import art.arcane.iris.engine.decorator.DecoratorTestEngines; -import art.arcane.iris.engine.framework.Engine; -import art.arcane.iris.engine.framework.SeedManager; -import art.arcane.iris.engine.object.world.biome.InferredType; -import art.arcane.iris.engine.object.world.biome.IrisBiome; -import art.arcane.iris.engine.object.world.dimension.IrisDimension; -import art.arcane.iris.engine.object.world.region.IrisRegion; -import art.arcane.iris.engine.object.world.IrisWorld; -import art.arcane.iris.spi.IrisPlatform; -import art.arcane.iris.spi.IrisPlatforms; -import art.arcane.iris.spi.PlatformBlockState; -import art.arcane.iris.spi.PlatformRegistries; -import art.arcane.iris.util.project.hunk.Hunk; -import art.arcane.iris.util.project.stream.ProceduralStream; -import art.arcane.volmlib.util.matter.MatterCavern; -import com.google.gson.Gson; -import com.volmit.host.ModuleLogs; -import it.unimi.dsi.fastutil.longs.Long2ObjectOpenHashMap; -import org.junit.AfterClass; -import org.junit.BeforeClass; -import org.junit.Test; - -import java.lang.reflect.Field; -import java.lang.reflect.Method; -import java.util.HashMap; -import java.util.Map; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertSame; -import static org.mockito.ArgumentMatchers.anyDouble; -import static org.mockito.ArgumentMatchers.anyString; -import static org.mockito.Mockito.CALLS_REAL_METHODS; -import static org.mockito.Mockito.doReturn; -import static org.mockito.Mockito.mock; - -public class CaveApplyingInferenceIsolationTest { - @BeforeClass - public static void bindPlatform() { - IrisPlatforms.unbind(); - PlatformBlockState block = mock(PlatformBlockState.class); - PlatformRegistries registries = mock(PlatformRegistries.class); - doReturn(block).when(registries).block(anyString()); - IrisPlatform platform = mock(IrisPlatform.class); - doReturn(registries).when(platform).registries(); - IrisPlatforms.bind(platform); - } - - @AfterClass - public static void unbindPlatform() { - IrisPlatforms.unbind(); - } - - @Test - @SuppressWarnings("unchecked") - public void cavePaintingDoesNotMutateSharedBiomeInference() throws Exception { - IrisBiome biome = new IrisBiome().setInferredType(InferredType.LAND); - biome.setModuleSettings(BuiltInPack.settings(new Gson().fromJson("{\"layers\": []}", LayersSettings.class))); - - Engine engine = mock(Engine.class); - doReturn(mock(IrisData.class)).when(engine).getData(); - doReturn(mock(IrisDimension.class)).when(engine).getDimension(); - doReturn(mock(IrisComplex.class)).when(engine).getComplex(); - doReturn(IrisWorld.builder().minHeight(-256).maxHeight(512).build()).when(engine).getWorld(); - doReturn(mock(SeedManager.class)).when(engine).getSeedManager(); - DecoratorTestEngines.withGeneration(engine); - CaveApplying modifier = new CaveApplying(engine, ModuleLogs.discarding()); - - Map customBiomes = new HashMap<>(); - customBiomes.put("shared", biome); - CarveWallBuffer walls = new CarveWallBuffer(1); - walls.put(0, 1, 0, new MatterCavern(true, "shared", (byte) 0)); - Method paintBoundaryZone = CaveApplying.class.getDeclaredMethod( - "paintBoundaryZone", - Hunk.class, - CarveWallBuffer.class, - int.class, - int.class, - int.class, - int.class, - int.class, - int.class, - Long2ObjectOpenHashMap.class, - Map.class - ); - paintBoundaryZone.setAccessible(true); - paintBoundaryZone.invoke( - modifier, - mock(Hunk.class), - walls, - 0, - 0, - 0, - 0, - 1, - 1, - new Long2ObjectOpenHashMap(), - customBiomes - ); - - IrisBiome fallback = new IrisBiome(); - ProceduralStream landStream = mock(ProceduralStream.class); - doReturn(fallback).when(landStream).get(anyDouble(), anyDouble()); - IrisComplex complex = mock(IrisComplex.class, CALLS_REAL_METHODS); - Field landBiomeStream = IrisComplex.class.getDeclaredField("landBiomeStream"); - landBiomeStream.setAccessible(true); - landBiomeStream.set(complex, landStream); - IrisRegion region = mock(IrisRegion.class); - doReturn(0D).when(region).getShoreHeight(anyDouble(), anyDouble()); - Method fixBiomeType = IrisComplex.class.getDeclaredMethod( - "fixBiomeType", - Double.class, - IrisBiome.class, - IrisRegion.class, - Double.class, - Double.class, - double.class - ); - fixBiomeType.setAccessible(true); - IrisBiome resolved = (IrisBiome) fixBiomeType.invoke(complex, 10D, biome, region, 0D, 0D, 0D); - assertSame(biome, resolved); - assertEquals(InferredType.LAND, biome.getInferredType()); - } -} diff --git a/core/src/test/java/art/arcane/iris/engine/modifier/CaveApplyingTest.java b/core/src/test/java/art/arcane/iris/engine/modifier/CaveApplyingTest.java new file mode 100644 index 000000000..67aa3383e --- /dev/null +++ b/core/src/test/java/art/arcane/iris/engine/modifier/CaveApplyingTest.java @@ -0,0 +1,168 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.engine.modifier; + +import art.arcane.iris.builtin.MatterMantle; +import art.arcane.iris.core.modules.CarveTestTerrain; +import art.arcane.iris.core.modules.CarveTestWorld; +import art.arcane.iris.core.modules.InMemoryMantle; +import art.arcane.iris.engine.mantle.components.CarveWorld; +import art.arcane.volmlib.util.mantle.runtime.MantleChunk; +import art.arcane.volmlib.util.matter.Matter; +import art.arcane.volmlib.util.matter.MatterCavern; +import art.arcane.volmlib.util.matter.MatterMarker; +import com.volmit.block.BlockState; +import com.volmit.host.ArrayHunk; +import com.volmit.hunk.Hunk; +import com.volmit.resource.ResourceId; +import com.volmit.world.BiomeSample; +import org.junit.Before; +import org.junit.Test; + +import java.util.List; +import java.util.Optional; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + +/** The caves the mantle planned become the chunk's blocks: air, lava low down, the biome's wall, floor and ceiling, and the markers cave spawning reads. */ +public class CaveApplyingTest { + private static final int HEIGHT = 64; + private static final int FLUID_HEIGHT = 20; + private static final int LAVA_HEIGHT = 4; + private static final int SURFACE = 40; + private static final BlockState STONE = new BlockState("minecraft:stone"); + private static final BlockState CAVE_AIR = new BlockState("minecraft:cave_air"); + private static final BlockState LAVA = new BlockState("minecraft:lava"); + private static final BlockState WALL = new BlockState("minecraft:mossy_cobblestone"); + private static final BlockState FLOOR = new BlockState("minecraft:moss_block"); + private static final BlockState CEILING = new BlockState("minecraft:dripstone_block"); + private static final ResourceId LUSH = CarveTestWorld.id("cave/lush"); + private static final MatterCavern AIR_CAVERN = new MatterCavern(true, "", (byte) 0); + private static final MatterCavern FLUID_CAVERN = new MatterCavern(true, "", (byte) 1); + private static final int CAVE_X = 5; + private static final int CAVE_Z = 5; + private static final int CAVE_FLOOR_Y = 10; + private static final int CAVE_CEILING_Y = 13; + + private final InMemoryMantle mantle = new InMemoryMantle(HEIGHT / 16); + private final RecordingCaveDressing dressing = new RecordingCaveDressing(); + private CarveTestWorld world; + private Hunk blocks; + private CarveTestTerrain terrain; + + @Before + public void setUp() { + world = new CarveTestWorld().biome("cave/lush", 1).dressing(dressing); + dressing.walls.put(LUSH, WALL); + dressing.floors.put(LUSH, List.of(FLOOR)); + dressing.ceilings.put(LUSH, List.of(CEILING)); + blocks = new ArrayHunk<>(BlockState.class, 16, HEIGHT, 16, STONE); + terrain = new CarveTestTerrain(0, 0, HEIGHT, FLUID_HEIGHT, (x, z) -> SURFACE) + .biomes((x, y, z) -> new BiomeSample(CarveTestWorld.id("region"), CarveTestWorld.id("plains"), Optional.of(LUSH))); + } + + @Test + public void aPlannedCaveBecomesCaveAirWithTheBiomesWallFloorAndCeiling() { + carve(CAVE_X, CAVE_Z, CAVE_FLOOR_Y, CAVE_CEILING_Y, AIR_CAVERN); + + apply(false); + + for (int y = CAVE_FLOOR_Y; y <= CAVE_CEILING_Y; y++) { + assertEquals("y=" + y, CAVE_AIR, blocks.get(CAVE_X, y, CAVE_Z)); + } + assertEquals("the wall beside the cave", WALL, blocks.get(CAVE_X + 1, CAVE_FLOOR_Y + 1, CAVE_Z)); + assertEquals("the floor layer under it", FLOOR, blocks.get(CAVE_X, CAVE_FLOOR_Y - 1, CAVE_Z)); + assertEquals("the ceiling layer over it", CEILING, blocks.get(CAVE_X, CAVE_CEILING_Y + 1, CAVE_Z)); + assertEquals("rock the cave did not touch", STONE, blocks.get(CAVE_X + 3, CAVE_FLOOR_Y + 1, CAVE_Z)); + } + + @Test + public void lowCavesFillWithLavaAndFluidCavernsWithTheDimensionsFluid() { + dressing.fluid = new BlockState("minecraft:water"); + carve(CAVE_X, CAVE_Z, LAVA_HEIGHT - 2, LAVA_HEIGHT, AIR_CAVERN); + carve(CAVE_X + 4, CAVE_Z, CAVE_FLOOR_Y, CAVE_CEILING_Y, FLUID_CAVERN); + + apply(false); + + assertEquals(LAVA, blocks.get(CAVE_X, LAVA_HEIGHT, CAVE_Z)); + assertEquals(LAVA, blocks.get(CAVE_X, LAVA_HEIGHT - 1, CAVE_Z)); + assertEquals(new BlockState("minecraft:water"), blocks.get(CAVE_X + 4, CAVE_FLOOR_Y + 1, CAVE_Z)); + } + + @Test + public void aDimensionAboveIsLeftAloneUnlessCarvingIsAllowedThroughIt() { + carve(CAVE_X, CAVE_Z, CAVE_FLOOR_Y, CAVE_CEILING_Y, AIR_CAVERN); + terrain.upperDimension((x, z) -> CAVE_FLOOR_Y + 1); + + apply(false); + assertEquals("the first block of the upper dimension stays", STONE, blocks.get(CAVE_X, CAVE_FLOOR_Y + 1, CAVE_Z)); + assertEquals("what lies below it is carved", CAVE_AIR, blocks.get(CAVE_X, CAVE_FLOOR_Y, CAVE_Z)); + + blocks = new ArrayHunk<>(BlockState.class, 16, HEIGHT, 16, STONE); + apply(true); + assertEquals("carving through it", CAVE_AIR, blocks.get(CAVE_X, CAVE_FLOOR_Y + 1, CAVE_Z)); + } + + @Test + public void markersAreStampedFromTheSeedAndPositionAlone() { + for (int x = 0; x < 16; x++) { + for (int z = 0; z < 16; z++) { + carve(x, z, CAVE_FLOOR_Y, CAVE_CEILING_Y, AIR_CAVERN); + } + } + + apply(false); + int first = markers(); + blocks = new ArrayHunk<>(BlockState.class, 16, HEIGHT, 16, STONE); + apply(false); + + assertTrue("about one in sixteen of the 512 floors and ceilings", first > 0 && first < 128); + assertEquals(first, markers()); + } + + private void carve(int x, int z, int floorY, int ceilingY, MatterCavern cavern) { + MantleChunk chunk = mantle.chunk(0, 0); + for (int y = floorY; y <= ceilingY; y++) { + chunk.getOrCreate(y >> 4).slice(MatterCavern.class).set(x, y & 15, z, cavern); + } + } + + private void apply(boolean upperDimensionCarving) { + MatterMantle matter = new MatterMantle() { + @Override + public MantleChunk chunk(int chunkX, int chunkZ) { + return mantle.chunk(chunkX, chunkZ); + } + + @Override + public MantleChunk loadedChunk(int chunkX, int chunkZ) { + return null; + } + }; + CarveWorld carveWorld = new CarveWorld(world.resources().noise(), 1337L, HEIGHT, FLUID_HEIGHT, LAVA_HEIGHT, CarveTestWorld.MIN_HEIGHT); + new CaveApplying(world, carveWorld, upperDimensionCarving).apply(matter, terrain, 0, 0, blocks); + } + + private int markers() { + int[] count = new int[1]; + mantle.chunk(0, 0).iterate(MatterMarker.class, (x, y, z, marker) -> count[0]++); + return count[0]; + } +} diff --git a/core/src/test/java/art/arcane/iris/engine/modifier/CaveBiomeBandsTest.java b/core/src/test/java/art/arcane/iris/engine/modifier/CaveBiomeBandsTest.java index a6075b02c..990d194a3 100644 --- a/core/src/test/java/art/arcane/iris/engine/modifier/CaveBiomeBandsTest.java +++ b/core/src/test/java/art/arcane/iris/engine/modifier/CaveBiomeBandsTest.java @@ -21,16 +21,9 @@ package art.arcane.iris.engine.modifier; import art.arcane.iris.builtin.carve.CarvingEntry; import art.arcane.iris.builtin.carve.CarvingSettings; import art.arcane.iris.builtin.carve.CaveDepthSettings; -import art.arcane.iris.core.loader.IrisData; -import art.arcane.iris.core.loader.ResourceLoader; -import art.arcane.iris.core.modules.BuiltInPack; -import art.arcane.iris.core.modules.IrisPackWorld; -import art.arcane.iris.engine.decorator.DecoratorTestEngines; -import art.arcane.iris.engine.framework.Engine; -import art.arcane.iris.engine.object.world.IrisWorld; -import art.arcane.iris.engine.object.world.biome.IrisBiome; -import art.arcane.iris.engine.object.world.dimension.IrisDimension; +import art.arcane.iris.core.modules.CarveTestWorld; import com.google.gson.Gson; +import com.volmit.FeatureAttachment.Target; import org.junit.Before; import org.junit.Test; @@ -38,12 +31,10 @@ import java.util.List; import java.util.Optional; import static org.junit.Assert.assertEquals; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; /** What the carve module answers the host about cave biomes: the biome of the dimension's band at a height above the dimension's bottom, and the minimum depths. */ public class CaveBiomeBandsTest { - private static final int MIN_HEIGHT = -64; + private static final int MIN_HEIGHT = CarveTestWorld.MIN_HEIGHT; private static final String BANDS = """ [{"id": "shallow", "biome": "band/shallow", "worldYRange": {"min": -64, "max": 0}}, {"id": "disabled", "enabled": false, "biome": "band/disabled", "worldYRange": {"min": 100, "max": 200}}, @@ -51,46 +42,32 @@ public class CaveBiomeBandsTest { {"id": "padded", "biome": " band/padded ", "worldYRange": {"min": 500, "max": 600}}] """; - private Engine engine; - private final IrisBiome shallow = mock(IrisBiome.class); + private CarveTestWorld world; @Before - @SuppressWarnings("unchecked") - public void mockEngine() { - IrisData data = mock(IrisData.class); - ResourceLoader biomes = mock(ResourceLoader.class); - when(data.getBiomeLoader()).thenReturn(biomes); - when(biomes.load("band/shallow")).thenReturn(shallow); - when(biomes.load("band/padded")).thenReturn(mock(IrisBiome.class)); - when(biomes.load("band/disabled")).thenReturn(mock(IrisBiome.class)); - when(shallow.getModuleSettings()).thenReturn(BuiltInPack.settings(new CaveDepthSettings(30))); + public void declareBands() { List entries = new Gson().fromJson(BANDS, new com.google.gson.reflect.TypeToken>() { }.getType()); - IrisDimension dimension = mock(IrisDimension.class); - when(dimension.getModuleSettings()).thenReturn(BuiltInPack.settings(new CarvingSettings(entries))); - engine = mock(Engine.class); - when(engine.getData()).thenReturn(data); - when(engine.getDimension()).thenReturn(dimension); - when(engine.getWorld()).thenReturn(IrisWorld.builder().minHeight(MIN_HEIGHT).maxHeight(320).build()); - DecoratorTestEngines.withGeneration(engine); + world = new CarveTestWorld() + .biome("band/shallow", 1).biome("band/padded", 1).biome("band/disabled", 1) + .dimension(new CarvingSettings(entries)) + .declare(Target.BIOME, "band/shallow", new CaveDepthSettings(30)); } @Test public void aPositionInsideAnEnabledBandGetsTheBandsBiomeKey() { CaveBiomeBands bands = new CaveBiomeBands(); - IrisPackWorld world = engine.getGeneration().world(); assertEquals("world Y -54 is in the band from -64 to 0", Optional.of("band/shallow"), bands.overriddenBiome(world, 5, 10, 5)); assertEquals("the band's end is in it", Optional.of("band/shallow"), bands.overriddenBiome(world, 5, 64, 5)); assertEquals("above it", Optional.empty(), bands.overriddenBiome(world, 5, 65, 5)); assertEquals("a disabled band overrides nothing", Optional.empty(), bands.overriddenBiome(world, 5, 200 - MIN_HEIGHT - 50, 5)); assertEquals("a band whose biome the pack lacks overrides nothing", Optional.empty(), bands.overriddenBiome(world, 5, 305 - MIN_HEIGHT, 5)); - assertEquals("the key is trimmed as the loader is asked for it", Optional.of("band/padded"), bands.overriddenBiome(world, 5, 550 - MIN_HEIGHT, 5)); + assertEquals("the key is trimmed as the pack is asked for it", Optional.of("band/padded"), bands.overriddenBiome(world, 5, 550 - MIN_HEIGHT, 5)); } @Test public void aBiomeKeyHasTheMinimumDepthItsSettingsDeclareAndZeroWhenTheKeyIsUnknown() { CaveBiomeBands bands = new CaveBiomeBands(); - IrisPackWorld world = engine.getGeneration().world(); assertEquals(30, bands.minDepthBelowSurface(world, "band/shallow")); assertEquals(0, bands.minDepthBelowSurface(world, "band/unknown")); diff --git a/core/src/test/java/art/arcane/iris/engine/modifier/RecordingCaveDressing.java b/core/src/test/java/art/arcane/iris/engine/modifier/RecordingCaveDressing.java new file mode 100644 index 000000000..326b85be9 --- /dev/null +++ b/core/src/test/java/art/arcane/iris/engine/modifier/RecordingCaveDressing.java @@ -0,0 +1,85 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.engine.modifier; + +import art.arcane.iris.builtin.CaveDressing; +import art.arcane.iris.builtin.decorant.DecorationPart; +import art.arcane.volmlib.util.math.RNG; +import com.volmit.block.BlockState; +import com.volmit.hunk.Hunk; +import com.volmit.resource.ResourceId; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +/** A cave dressing the tests of the carve module set up by biome: the wall block, the floor and ceiling layers and the fluid, with a record of what was decorated. */ +public final class RecordingCaveDressing implements CaveDressing { + public final Map walls = new HashMap<>(); + public final Map> floors = new HashMap<>(); + public final Map> ceilings = new HashMap<>(); + public final List decorated = new ArrayList<>(); + public BlockState fluid; + + @Override + public boolean fluidPresentAt(int x, int z) { + return fluid != null; + } + + @Override + public BlockState fluidAt(Hunk chunk, int x, int z) { + return fluid; + } + + @Override + public BlockState wall(Hunk chunk, ResourceId biome, RNG rng, int x, int y, int z) { + return walls.get(biome); + } + + @Override + public List floorLayers(Hunk chunk, ResourceId biome, int x, int z, RNG rng, int depth, int floorY) { + return floors.getOrDefault(biome, List.of()); + } + + @Override + public List ceilingLayers(Hunk chunk, ResourceId biome, int x, int z, RNG rng, int depth, int ceilingY) { + return ceilings.getOrDefault(biome, List.of()); + } + + @Override + public boolean hasDecorators(ResourceId biome, DecorationPart part) { + return false; + } + + @Override + public void decorateFloor(Hunk chunk, int localX, int localZ, int x, int z, ResourceId biome, int floorY, int airThickness) { + decorated.add("floor " + localX + "," + floorY + "," + localZ); + } + + @Override + public void decorateCeiling(Hunk chunk, int localX, int localZ, int x, int z, ResourceId biome, int ceilingY, int airThickness) { + decorated.add("ceiling " + localX + "," + ceilingY + "," + localZ); + } + + @Override + public BlockState deepSlateOre(Hunk chunk, BlockState existing, BlockState layer) { + return new BlockState("minecraft:deepslate_" + layer.material().path()); + } +} diff --git a/core/src/test/java/art/arcane/iris/engine/object/terrain/carving/CarvingResolverParityTest.java b/core/src/test/java/art/arcane/iris/engine/object/terrain/carving/CarvingResolverParityTest.java index 9b1dd39c7..275413e22 100644 --- a/core/src/test/java/art/arcane/iris/engine/object/terrain/carving/CarvingResolverParityTest.java +++ b/core/src/test/java/art/arcane/iris/engine/object/terrain/carving/CarvingResolverParityTest.java @@ -1,120 +1,70 @@ package art.arcane.iris.engine.object.terrain.carving; -import art.arcane.iris.engine.object.value.IRare; -import com.volmit.config.Range; import art.arcane.iris.builtin.carve.CarvingEntry; -import art.arcane.iris.engine.decorator.DecoratorTestEngines; -import art.arcane.iris.engine.object.world.IrisWorld; -import art.arcane.iris.engine.object.world.biome.IrisBiome; -import art.arcane.iris.engine.object.world.dimension.IrisDimension; -import art.arcane.iris.core.loader.IrisData; -import art.arcane.iris.core.loader.ResourceLoader; -import art.arcane.iris.engine.framework.Engine; -import art.arcane.iris.engine.framework.EngineGeneration; -import art.arcane.iris.engine.framework.SeedManager; +import art.arcane.iris.builtin.carve.CarvingSettings; +import art.arcane.iris.core.modules.CarveTestWorld; +import art.arcane.iris.core.modules.IrisValues; +import art.arcane.iris.engine.object.value.IRare; import art.arcane.iris.util.project.noise.CNG; import art.arcane.volmlib.util.collection.KList; +import art.arcane.volmlib.util.math.RNG; import com.google.gson.Gson; import com.google.gson.JsonObject; -import org.bukkit.Bukkit; -import org.bukkit.Material; -import org.bukkit.Server; -import org.bukkit.block.data.BlockData; -import org.junit.BeforeClass; +import com.volmit.config.Range; import org.junit.Test; -import org.mockito.invocation.InvocationOnMock; -import java.lang.ref.WeakReference; -import java.lang.reflect.Field; -import java.lang.reflect.Proxy; +import java.util.HashMap; import java.util.List; -import java.util.Locale; import java.util.Map; -import java.util.concurrent.CountDownLatch; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; -import java.util.concurrent.Future; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.atomic.AtomicReference; -import java.util.logging.Logger; -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; -import static org.mockito.Answers.CALLS_REAL_METHODS; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.ArgumentMatchers.anyInt; -import static org.mockito.ArgumentMatchers.anyString; -import static org.mockito.Mockito.doAnswer; -import static org.mockito.Mockito.doReturn; -import static org.mockito.Mockito.mock; +import static org.junit.Assert.assertNotSame; +/** + * The module's pick of a cave biome band is the pick the band code made with Iris's own generators: the root by world Y, then the + * child a rarity-weighted draw of the generator's noise selects. The reference below is that code, written out again. + */ public class CarvingResolverParityTest { private static final int MAX_CHILD_DEPTH = 32; private static final long CHILD_SEED_SALT = 0x9E3779B97F4A7C15L; - - @BeforeClass - public static void setupBukkit() { - if (Bukkit.getServer() != null) { - return; - } - - Server server = mock(Server.class); - doReturn(Logger.getLogger("IrisTest")).when(server).getLogger(); - doReturn("IrisTestServer").when(server).getName(); - doReturn("1.0").when(server).getVersion(); - doReturn("1.0").when(server).getBukkitVersion(); - doAnswer((InvocationOnMock invocation) -> namedBlockData(invocation.getArgument(0, Material.class).name().toLowerCase(Locale.ROOT))).when(server).createBlockData(any(Material.class)); - doAnswer((InvocationOnMock invocation) -> namedBlockData(invocation.getArgument(0, String.class))).when(server).createBlockData(anyString()); - try { - Bukkit.setServer(server); - } catch (Throwable ignored) { - } - } - - private static BlockData namedBlockData(String key) { - String canonical = key.indexOf(':') >= 0 ? key : "minecraft:" + key; - BlockData data = mock(BlockData.class); - doReturn(canonical).when(data).getAsString(); - return data; - } + private static final long CHILD_GENERATOR_SALT = 2137L; + private static final int CHILD_GENERATOR_SIGNATURE = 2137; + private static final double MIN_CHILD_SCALE = 0.0001D; @Test - public void resolverStatefulOverloadsMatchLegacyResolverAcrossSampleGrid() { + public void resolverMatchesLegacyResolverAcrossSampleGrid() { Fixture fixture = createFixture(); - CarvingResolver.State state = new CarvingResolver.State(); for (int worldY = -64; worldY <= 320; worldY += 11) { - ResolvedCarvingEntry legacyRoot = legacyResolveRootEntry(fixture.engine, worldY); - ResolvedCarvingEntry statefulRoot = CarvingResolver.resolveRootEntry(fixture.engine, worldY, state); - assertSame("root mismatch at worldY=" + worldY, legacyRoot, statefulRoot); + ResolvedCarvingEntry legacyRoot = fixture.legacyRootEntry(worldY); + ResolvedCarvingEntry root = fixture.resolver.rootEntryAtWorldY(worldY); + assertSame("root mismatch at worldY=" + worldY, legacyRoot, root); for (int worldX = -384; worldX <= 384; worldX += 29) { for (int worldZ = -384; worldZ <= 384; worldZ += 31) { - ResolvedCarvingEntry legacyResolved = legacyResolveFromRoot(fixture.engine, legacyRoot, worldX, worldZ); - ResolvedCarvingEntry statefulResolved = CarvingResolver.resolveFromRoot(fixture.engine, statefulRoot, worldX, worldZ, state); - assertSame("entry mismatch at worldY=" + worldY + " worldX=" + worldX + " worldZ=" + worldZ, legacyResolved, statefulResolved); + ResolvedCarvingEntry legacyResolved = fixture.legacyResolveFromRoot(legacyRoot, worldX, worldZ); + ResolvedCarvingEntry resolved = fixture.resolver.resolveFromRoot(root, worldX, worldZ); + assertSame("entry mismatch at worldY=" + worldY + " worldX=" + worldX + " worldZ=" + worldZ, legacyResolved, resolved); } } } } @Test - public void resolverStatefulOverloadsMatchLegacyResolverAcrossMixedDepthGraph() { + public void resolverMatchesLegacyResolverAcrossMixedDepthGraph() { Fixture fixture = createMixedDepthFixture(); - CarvingResolver.State state = new CarvingResolver.State(); for (int worldY = -64; worldY <= 320; worldY += 17) { - ResolvedCarvingEntry legacyRoot = legacyResolveRootEntry(fixture.engine, worldY); - ResolvedCarvingEntry statefulRoot = CarvingResolver.resolveRootEntry(fixture.engine, worldY, state); - assertSame("mixed root mismatch at worldY=" + worldY, legacyRoot, statefulRoot); + ResolvedCarvingEntry legacyRoot = fixture.legacyRootEntry(worldY); + ResolvedCarvingEntry root = fixture.resolver.rootEntryAtWorldY(worldY); + assertSame("mixed root mismatch at worldY=" + worldY, legacyRoot, root); for (int worldX = -640; worldX <= 640; worldX += 79) { for (int worldZ = -640; worldZ <= 640; worldZ += 83) { - ResolvedCarvingEntry legacyResolved = legacyResolveFromRoot(fixture.engine, legacyRoot, worldX, worldZ); - ResolvedCarvingEntry statefulResolved = CarvingResolver.resolveFromRoot(fixture.engine, statefulRoot, worldX, worldZ, state); - assertSame("mixed entry mismatch at worldY=" + worldY + " worldX=" + worldX + " worldZ=" + worldZ, legacyResolved, statefulResolved); + ResolvedCarvingEntry legacyResolved = fixture.legacyResolveFromRoot(legacyRoot, worldX, worldZ); + ResolvedCarvingEntry resolved = fixture.resolver.resolveFromRoot(root, worldX, worldZ); + assertSame("mixed entry mismatch at worldY=" + worldY + " worldX=" + worldX + " worldZ=" + worldZ, legacyResolved, resolved); } } } @@ -123,324 +73,86 @@ public class CarvingResolverParityTest { @Test public void columnAnchoredChunkPlanResolutionIsStableAcrossRepeatedBuilds() { Fixture fixture = createMixedDepthFixture(); - CarvingResolver.State state = new CarvingResolver.State(); - ResolvedCarvingEntry root = legacyResolveRootEntry(fixture.engine, 80); + ResolvedCarvingEntry root = fixture.legacyRootEntry(80); for (int chunkX = -24; chunkX <= 24; chunkX += 6) { for (int chunkZ = -24; chunkZ <= 24; chunkZ += 6) { - ResolvedCarvingEntry[] firstPlan = buildColumnPlan(fixture.engine, root, chunkX, chunkZ, state); - ResolvedCarvingEntry[] secondPlan = buildColumnPlan(fixture.engine, root, chunkX, chunkZ, state); + ResolvedCarvingEntry[] firstPlan = buildColumnPlan(fixture.resolver, root, chunkX, chunkZ); + ResolvedCarvingEntry[] secondPlan = buildColumnPlan(fixture.resolver, root, chunkX, chunkZ); for (int columnIndex = 0; columnIndex < firstPlan.length; columnIndex++) { - assertSame( - "column plan mismatch at chunkX=" + chunkX + " chunkZ=" + chunkZ + " columnIndex=" + columnIndex, - firstPlan[columnIndex], - secondPlan[columnIndex] - ); + assertSame("column plan mismatch at chunkX=" + chunkX + " chunkZ=" + chunkZ + " columnIndex=" + columnIndex, + firstPlan[columnIndex], secondPlan[columnIndex]); } } } } @Test - public void sharedResolverStateNeverCarriesDimensionEntriesAcrossEngines() { + public void eachWorldKeepsItsOwnBands() { Fixture first = createFixture(); Fixture second = createMixedDepthFixture(); - CarvingResolver.State state = new CarvingResolver.State(); - ResolvedCarvingEntry firstExpected = legacyResolveRootEntry(first.engine, 80); - ResolvedCarvingEntry secondExpected = legacyResolveRootEntry(second.engine, 80); + ResolvedCarvingEntry firstExpected = first.legacyRootEntry(80); + ResolvedCarvingEntry secondExpected = second.legacyRootEntry(80); - assertSame(firstExpected, CarvingResolver.resolveRootEntry(first.engine, 80, state)); - assertSame(secondExpected, CarvingResolver.resolveRootEntry(second.engine, 80, state)); - assertSame(firstExpected, CarvingResolver.resolveRootEntry(first.engine, 80, state)); + assertSame(firstExpected, first.resolver.rootEntryAtWorldY(80)); + assertSame(secondExpected, second.resolver.rootEntryAtWorldY(80)); + assertSame(firstExpected, first.resolver.rootEntryAtWorldY(80)); + assertNotSame(firstExpected, secondExpected); } @Test - public void threadLocalResolverNeverCarriesDimensionEntriesAcrossEngines() { - Fixture first = createFixture(); - Fixture second = createMixedDepthFixture(); - int worldY = 83; + public void aWorldReadsItsBandsFromTheDimensionsSettings() { + CarveTestWorld world = new CarveTestWorld().biome("root-low", 6) + .dimension(new CarvingSettings(List.of(buildEntry("root-low", "root-low", Range.of(-64, 120), 4, List.of())))); - ResolvedCarvingEntry firstExpected = legacyResolveRootEntry(first.engine, worldY); - ResolvedCarvingEntry secondExpected = legacyResolveRootEntry(second.engine, worldY); + CarvingResolver resolver = CarvingResolver.of(world); - assertSame(firstExpected, CarvingResolver.resolveRootEntry(first.engine, worldY)); - assertSame(secondExpected, CarvingResolver.resolveRootEntry(second.engine, worldY)); - } - - @Test - public void threadLocalResolverInvalidatesWhenTheSameEnginePublishesReplacementData() { - Fixture first = createFixture(); - Fixture replacement = createMixedDepthFixture(); - AtomicReference dimension = new AtomicReference<>(first.engine.getDimension()); - AtomicReference data = new AtomicReference<>(first.engine.getData()); - AtomicReference generation = new AtomicReference<>(first.engine.getGeneration()); - Engine engine = mock(Engine.class, CALLS_REAL_METHODS); - doAnswer((InvocationOnMock invocation) -> dimension.get()).when(engine).getDimension(); - doAnswer((InvocationOnMock invocation) -> data.get()).when(engine).getData(); - doAnswer((InvocationOnMock invocation) -> generation.get()).when(engine).getGeneration(); - - int worldY = 83; - ResolvedCarvingEntry firstExpected = legacyResolveRootEntry(first.engine, worldY); - ResolvedCarvingEntry replacementExpected = legacyResolveRootEntry(replacement.engine, worldY); - assertSame(firstExpected, CarvingResolver.resolveRootEntry(engine, worldY)); - - dimension.set(replacement.engine.getDimension()); - data.set(replacement.engine.getData()); - generation.set(replacement.engine.getGeneration()); - assertSame(replacementExpected, CarvingResolver.resolveRootEntry(engine, worldY)); - } - - @Test - public void resolverStateUsesWeakRuntimeIdentityBindings() throws NoSuchFieldException { - Field engineIdentity = CarvingResolver.State.class.getDeclaredField("engineIdentity"); - Field dimensionIdentity = CarvingResolver.State.class.getDeclaredField("dimensionIdentity"); - Field dataIdentity = CarvingResolver.State.class.getDeclaredField("dataIdentity"); - - assertSame(WeakReference.class, engineIdentity.getType()); - assertSame(WeakReference.class, dimensionIdentity.getType()); - assertSame(WeakReference.class, dataIdentity.getType()); - } - - @Test(timeout = 20_000L) - public void longLivedWorkerDoesNotRetainPopulatedThreadLocalStateOrEngine() throws Exception { - ExecutorService executor = Executors.newSingleThreadExecutor(); - CountDownLatch blockerStarted = new CountDownLatch(1); - CountDownLatch releaseBlocker = new CountDownLatch(1); - try { - LifetimeReferences references = executor.submit(this::populateThreadLocalLifetimeReferences).get(); - Future blocker = executor.submit(() -> { - blockerStarted.countDown(); - releaseBlocker.await(); - return null; - }); - assertTrue(blockerStarted.await(5L, TimeUnit.SECONDS)); - - awaitCollection(references); - - releaseBlocker.countDown(); - blocker.get(5L, TimeUnit.SECONDS); - } finally { - releaseBlocker.countDown(); - executor.shutdownNow(); - assertTrue(executor.awaitTermination(5L, TimeUnit.SECONDS)); - } - } - - private LifetimeReferences populateThreadLocalLifetimeReferences() throws Exception { - RetainedFixture fixture = createRetainedFixture(); - assertNotNull(CarvingResolver.resolveRootEntry(fixture.engine(), 80)); - - Field threadStateField = CarvingResolver.class.getDeclaredField("THREAD_STATE"); - threadStateField.setAccessible(true); - ThreadLocal threadState = (ThreadLocal) threadStateField.get(null); - Object value = threadState.get(); - assertTrue(value instanceof WeakReference); - @SuppressWarnings("unchecked") - WeakReference state = - (WeakReference) value; - CarvingResolver.State populatedState = state.get(); - assertNotNull(populatedState); - Field biomeCacheField = CarvingResolver.State.class.getDeclaredField("biomeCache"); - biomeCacheField.setAccessible(true); - assertFalse(((Map) biomeCacheField.get(populatedState)).isEmpty()); - return new LifetimeReferences( - state, - new WeakReference<>(fixture.engine())); - } - - private static void awaitCollection(LifetimeReferences references) throws InterruptedException { - for (int attempt = 0; attempt < 100; attempt++) { - System.gc(); - if (references.state().get() == null - && references.engine().get() == null) { - return; - } - byte[] pressure = new byte[1_048_576]; - pressure[0] = (byte) attempt; - Thread.sleep(10L); - } - assertTrue("Thread-local State was retained", references.state().get() == null); - assertTrue("Engine was retained", references.engine().get() == null); - } - - @Test - public void explicitStateRemainsStronglyCallerOwned() throws Exception { - RetainedFixture fixture = createRetainedFixture(); - CarvingResolver.State state = new CarvingResolver.State(); - assertSame(fixture.entry(), CarvingResolver.resolveRootEntry( - fixture.engine(), 80, state)); - - Field rootEntriesField = CarvingResolver.State.class - .getDeclaredField("rootEntriesByWorldY"); - rootEntriesField.setAccessible(true); - System.gc(); - - assertSame(fixture.entry(), ((Map) rootEntriesField.get(state)).get(80)); - } - - private RetainedFixture createRetainedFixture() { - IrisData data = mock(IrisData.class); - IrisBiome biome = new IrisBiome(); - biome.setLoader(data); - - @SuppressWarnings("unchecked") - ResourceLoader biomeLoader = mock(ResourceLoader.class); - doReturn(biome).when(biomeLoader).load("retained"); - doReturn(biomeLoader).when(data).getBiomeLoader(); - - CarvingBands bands = new CarvingBands(List.of(buildEntry("retained", "retained", Range.of(-64, 320), 0, List.of()))); - IrisDimension dimension = new IrisDimension(); - - Engine[] engine = new Engine[1]; - AtomicReference generation = new AtomicReference<>(); - engine[0] = (Engine) Proxy.newProxyInstance( - Engine.class.getClassLoader(), - new Class[]{Engine.class}, - (proxy, method, arguments) -> switch (method.getName()) { - case "getDimension" -> dimension; - case "getData" -> data; - case "getGeneration" -> generation.updateAndGet(existing -> existing != null ? existing : generationWith(engine[0], bands)); - case "hashCode" -> System.identityHashCode(proxy); - case "equals" -> proxy == arguments[0]; - case "toString" -> "carving-retention-test-engine"; - default -> throw new UnsupportedOperationException(method.toString()); - }); - return new RetainedFixture(engine[0], bands.entries().getFirst()); + assertSame(resolver, CarvingResolver.of(world)); + assertSame(resolver.index().get("root-low"), resolver.rootEntryAt(80 - CarveTestWorld.MIN_HEIGHT)); + assertNull(resolver.rootEntryAtWorldY(121)); } private Fixture createFixture() { - IrisBiome rootLowBiome = mock(IrisBiome.class); - IrisBiome rootHighBiome = mock(IrisBiome.class); - IrisBiome childABiome = mock(IrisBiome.class); - IrisBiome childBBiome = mock(IrisBiome.class); - IrisBiome childCBiome = mock(IrisBiome.class); - IrisBiome fallbackBiome = mock(IrisBiome.class); - IrisBiome surfaceBiome = mock(IrisBiome.class); - - doReturn(6).when(rootLowBiome).getRarity(); - doReturn(4).when(rootHighBiome).getRarity(); - doReturn(2).when(childABiome).getRarity(); - doReturn(5).when(childBBiome).getRarity(); - doReturn(1).when(childCBiome).getRarity(); - - @SuppressWarnings("unchecked") - ResourceLoader biomeLoader = mock(ResourceLoader.class); - doReturn(rootLowBiome).when(biomeLoader).load("root-low"); - doReturn(rootHighBiome).when(biomeLoader).load("root-high"); - doReturn(childABiome).when(biomeLoader).load("child-a"); - doReturn(childBBiome).when(biomeLoader).load("child-b"); - doReturn(childCBiome).when(biomeLoader).load("child-c"); - - IrisData data = mock(IrisData.class); - doReturn(biomeLoader).when(data).getBiomeLoader(); - - CarvingEntry rootLow = buildEntry("root-low", "root-low", Range.of(-64, 120), 4, List.of("child-a", "child-b")); - CarvingEntry rootHigh = buildEntry("root-high", "root-high", Range.of(121, 320), 3, List.of("child-b", "child-c")); - CarvingEntry childA = buildEntry("child-a", "child-a", Range.of(-2048, -1024), 3, List.of("child-b")); - CarvingEntry childB = buildEntry("child-b", "child-b", Range.of(-2048, -1024), 2, List.of("child-c", "child-a")); - CarvingEntry childC = buildEntry("child-c", "child-c", Range.of(-2048, -1024), 1, List.of()); - - CarvingBands bands = new CarvingBands(List.of(rootLow, rootHigh, childA, childB, childC)); - - IrisDimension dimension = mock(IrisDimension.class); - - Engine engine = mock(Engine.class, CALLS_REAL_METHODS); - doReturn(dimension).when(engine).getDimension(); - doReturn(data).when(engine).getData(); - doReturn(new SeedManager(913_531_771L)).when(engine).getSeedManager(); - doReturn(IrisWorld.builder().minHeight(-64).maxHeight(320).build()).when(engine).getWorld(); - doReturn(surfaceBiome).when(engine).getSurfaceBiome(anyInt(), anyInt()); - doReturn(fallbackBiome).when(engine).getCaveBiome(anyInt(), anyInt()); - DecoratorTestEngines.withGeneration(engine).state(CarvingBands.class, ignored -> bands); - - return new Fixture(engine); + CarveTestWorld world = new CarveTestWorld().carveSeed(913_531_771L) + .biome("root-low", 6).biome("root-high", 4).biome("child-a", 2).biome("child-b", 5).biome("child-c", 1); + return new Fixture(world, List.of( + buildEntry("root-low", "root-low", Range.of(-64, 120), 4, List.of("child-a", "child-b")), + buildEntry("root-high", "root-high", Range.of(121, 320), 3, List.of("child-b", "child-c")), + buildEntry("child-a", "child-a", Range.of(-2048, -1024), 3, List.of("child-b")), + buildEntry("child-b", "child-b", Range.of(-2048, -1024), 2, List.of("child-c", "child-a")), + buildEntry("child-c", "child-c", Range.of(-2048, -1024), 1, List.of()))); } private Fixture createMixedDepthFixture() { - IrisBiome rootLowBiome = mock(IrisBiome.class); - IrisBiome rootHighBiome = mock(IrisBiome.class); - IrisBiome childABiome = mock(IrisBiome.class); - IrisBiome childBBiome = mock(IrisBiome.class); - IrisBiome childCBiome = mock(IrisBiome.class); - IrisBiome childDBiome = mock(IrisBiome.class); - IrisBiome childEBiome = mock(IrisBiome.class); - IrisBiome childFBiome = mock(IrisBiome.class); - IrisBiome childGBiome = mock(IrisBiome.class); - IrisBiome fallbackBiome = mock(IrisBiome.class); - IrisBiome surfaceBiome = mock(IrisBiome.class); - - doReturn(7).when(rootLowBiome).getRarity(); - doReturn(5).when(rootHighBiome).getRarity(); - doReturn(2).when(childABiome).getRarity(); - doReturn(3).when(childBBiome).getRarity(); - doReturn(6).when(childCBiome).getRarity(); - doReturn(1).when(childDBiome).getRarity(); - doReturn(4).when(childEBiome).getRarity(); - doReturn(8).when(childFBiome).getRarity(); - doReturn(2).when(childGBiome).getRarity(); - - @SuppressWarnings("unchecked") - ResourceLoader biomeLoader = mock(ResourceLoader.class); - doReturn(rootLowBiome).when(biomeLoader).load("root-low"); - doReturn(rootHighBiome).when(biomeLoader).load("root-high"); - doReturn(childABiome).when(biomeLoader).load("child-a"); - doReturn(childBBiome).when(biomeLoader).load("child-b"); - doReturn(childCBiome).when(biomeLoader).load("child-c"); - doReturn(childDBiome).when(biomeLoader).load("child-d"); - doReturn(childEBiome).when(biomeLoader).load("child-e"); - doReturn(childFBiome).when(biomeLoader).load("child-f"); - doReturn(childGBiome).when(biomeLoader).load("child-g"); - - IrisData data = mock(IrisData.class); - doReturn(biomeLoader).when(data).getBiomeLoader(); - - CarvingEntry rootLow = buildEntry("root-low", "root-low", Range.of(-64, 120), 7, List.of("child-a", "child-d", "child-e")); - CarvingEntry rootHigh = buildEntry("root-high", "root-high", Range.of(121, 320), 6, List.of("child-b", "child-c", "child-f")); - CarvingEntry childA = buildEntry("child-a", "child-a", Range.of(-4096, 4096), 5, List.of("child-b", "child-g")); - CarvingEntry childB = buildEntry("child-b", "child-b", Range.of(-4096, 4096), 1, List.of("child-c")); - CarvingEntry childC = buildEntry("child-c", "child-c", Range.of(-4096, 4096), 0, List.of()); - CarvingEntry childD = buildEntry("child-d", "child-d", Range.of(-4096, 4096), 6, List.of("child-e", "child-f")); - CarvingEntry childE = buildEntry("child-e", "child-e", Range.of(-4096, 4096), 2, List.of("child-a")); - CarvingEntry childF = buildEntry("child-f", "child-f", Range.of(-4096, 4096), 8, List.of("child-g", "child-c")); - CarvingEntry childG = buildEntry("child-g", "child-g", Range.of(-4096, 4096), 3, List.of("child-d")); - - CarvingBands bands = new CarvingBands(List.of(rootLow, rootHigh, childA, childB, childC, childD, childE, childF, childG)); - - IrisDimension dimension = mock(IrisDimension.class); - - Engine engine = mock(Engine.class, CALLS_REAL_METHODS); - doReturn(dimension).when(engine).getDimension(); - doReturn(data).when(engine).getData(); - doReturn(new SeedManager(4_627_991_643L)).when(engine).getSeedManager(); - doReturn(IrisWorld.builder().minHeight(-64).maxHeight(320).build()).when(engine).getWorld(); - doReturn(surfaceBiome).when(engine).getSurfaceBiome(anyInt(), anyInt()); - doReturn(fallbackBiome).when(engine).getCaveBiome(anyInt(), anyInt()); - DecoratorTestEngines.withGeneration(engine).state(CarvingBands.class, ignored -> bands); - - return new Fixture(engine); + CarveTestWorld world = new CarveTestWorld().carveSeed(4_627_991_643L) + .biome("root-low", 7).biome("root-high", 5).biome("child-a", 2).biome("child-b", 3).biome("child-c", 6) + .biome("child-d", 1).biome("child-e", 4).biome("child-f", 8).biome("child-g", 2); + return new Fixture(world, List.of( + buildEntry("root-low", "root-low", Range.of(-64, 120), 7, List.of("child-a", "child-d", "child-e")), + buildEntry("root-high", "root-high", Range.of(121, 320), 6, List.of("child-b", "child-c", "child-f")), + buildEntry("child-a", "child-a", Range.of(-4096, 4096), 5, List.of("child-b", "child-g")), + buildEntry("child-b", "child-b", Range.of(-4096, 4096), 1, List.of("child-c")), + buildEntry("child-c", "child-c", Range.of(-4096, 4096), 0, List.of()), + buildEntry("child-d", "child-d", Range.of(-4096, 4096), 6, List.of("child-e", "child-f")), + buildEntry("child-e", "child-e", Range.of(-4096, 4096), 2, List.of("child-a")), + buildEntry("child-f", "child-f", Range.of(-4096, 4096), 8, List.of("child-g", "child-c")), + buildEntry("child-g", "child-g", Range.of(-4096, 4096), 3, List.of("child-d")))); } - private ResolvedCarvingEntry[] buildColumnPlan(Engine engine, ResolvedCarvingEntry rootEntry, int chunkX, int chunkZ, CarvingResolver.State state) { + private ResolvedCarvingEntry[] buildColumnPlan(CarvingResolver resolver, ResolvedCarvingEntry rootEntry, int chunkX, int chunkZ) { ResolvedCarvingEntry[] plan = new ResolvedCarvingEntry[256]; for (int localX = 0; localX < 16; localX++) { int worldX = (chunkX << 4) + localX; for (int localZ = 0; localZ < 16; localZ++) { int worldZ = (chunkZ << 4) + localZ; - int columnIndex = (localX << 4) | localZ; - plan[columnIndex] = CarvingResolver.resolveFromRoot(engine, rootEntry, worldX, worldZ, state); + plan[(localX << 4) | localZ] = resolver.resolveFromRoot(rootEntry, worldX, worldZ); } } return plan; } - private static EngineGeneration generationWith(Engine engine, CarvingBands bands) { - EngineGeneration generation = new EngineGeneration(engine); - generation.state(CarvingBands.class, ignored -> bands); - return generation; - } - - private CarvingEntry buildEntry(String id, String biome, Range worldRange, int depth, List children) { + private static CarvingEntry buildEntry(String id, String biome, Range worldRange, int depth, List children) { JsonObject json = new JsonObject(); json.addProperty("id", id); json.addProperty("biome", biome); @@ -453,158 +165,123 @@ public class CarvingResolverParityTest { return new Gson().fromJson(json, CarvingEntry.class); } - private ResolvedCarvingEntry legacyResolveRootEntry(Engine engine, int worldY) { - List entries = CarvingBands.of(engine).entries(); - if (entries.isEmpty()) { - return null; - } - - ResolvedCarvingEntry resolved = null; - for (ResolvedCarvingEntry entry : entries) { - if (!legacyIsRootCandidate(engine, entry, worldY)) { - continue; - } - - resolved = entry; - } - - return resolved; - } - - private ResolvedCarvingEntry legacyResolveFromRoot(Engine engine, ResolvedCarvingEntry rootEntry, int worldX, int worldZ) { - if (rootEntry == null) { - return null; - } - - IrisBiome rootBiome = legacyResolveEntryBiome(engine, rootEntry); - if (rootBiome == null) { - return null; - } - - int remainingDepth = clampDepth(rootEntry.childRecursionDepth()); - if (remainingDepth <= 0) { - return rootEntry; - } - - Map entryIndex = CarvingBands.of(engine).index(); - ResolvedCarvingEntry current = rootEntry; - int depth = remainingDepth; - while (depth > 0) { - ResolvedCarvingEntry selected = legacySelectChild(engine, current, worldX, worldZ, entryIndex); - if (selected == null || selected == current) { - break; - } - - depth--; - int childDepthLimit = clampDepth(selected.childRecursionDepth()); - if (childDepthLimit < depth) { - depth = childDepthLimit; - } - current = selected; - } - - return current; - } - - private IrisBiome legacyResolveEntryBiome(Engine engine, ResolvedCarvingEntry entry) { - if (entry == null) { - return null; - } - - return entry.realBiome(engine.getData()); - } - - private boolean legacyIsRootCandidate(Engine engine, ResolvedCarvingEntry entry, int worldY) { - if (entry == null || !entry.enabled()) { - return false; - } - - Range worldYRange = entry.worldYRange(); - if (worldYRange != null && !worldYRange.contains(worldY)) { - return false; - } - - return legacyResolveEntryBiome(engine, entry) != null; - } - - private ResolvedCarvingEntry legacySelectChild( - Engine engine, - ResolvedCarvingEntry parent, - int worldX, - int worldZ, - Map entryIndex - ) { - List children = parent.children(); - if (children.isEmpty()) { - return parent; - } - - IrisBiome parentBiome = legacyResolveEntryBiome(engine, parent); - if (parentBiome == null) { - return parent; - } - - KList options = new KList<>(); - for (String childId : children) { - if (childId == null || childId.isBlank()) { - continue; - } - - ResolvedCarvingEntry child = entryIndex.get(childId.trim()); - if (child == null || !child.enabled()) { - continue; - } - - IrisBiome childBiome = legacyResolveEntryBiome(engine, child); - if (childBiome == null) { - continue; - } - - options.add(new LegacyCarvingChoice(child, rarity(childBiome))); - } - - options.add(new LegacyCarvingChoice(parent, rarity(parentBiome))); - if (options.size() <= 1) { - return parent; - } - - long seed = engine.getSeedManager().getCarve() ^ CHILD_SEED_SALT; - CNG childGenerator = parent.childrenGenerator(seed, engine.getData()); - LegacyCarvingChoice selected = childGenerator.fitRarity(options, worldX, worldZ); - if (selected == null || selected.entry == null) { - return parent; - } - - return selected.entry; - } - - private int rarity(IrisBiome biome) { - if (biome == null) { - return 1; - } - - int rarity = biome.getRarity(); - return Math.max(rarity, 1); - } - - private int clampDepth(int depth) { + private static int clampDepth(int depth) { if (depth <= 0) { return 0; } - return Math.min(depth, MAX_CHILD_DEPTH); } - private record Fixture(Engine engine) { - } + /** The module's resolver, and the band code as it was, over the same entries and world. */ + private static final class Fixture { + private final CarveTestWorld world; + private final CarvingResolver resolver; + private final Map settingsById = new HashMap<>(); - private record RetainedFixture(Engine engine, ResolvedCarvingEntry entry) { - } + private Fixture(CarveTestWorld world, List entries) { + this.world = world; + this.resolver = new CarvingResolver(world, entries); + entries.forEach(entry -> settingsById.put(entry.id(), entry)); + } - private record LifetimeReferences( - WeakReference state, - WeakReference engine - ) { + private ResolvedCarvingEntry legacyRootEntry(int worldY) { + ResolvedCarvingEntry resolved = null; + for (ResolvedCarvingEntry entry : resolver.entries()) { + if (!entry.enabled()) { + continue; + } + Range worldYRange = entry.worldYRange(); + if (worldYRange != null && !worldYRange.contains(worldY)) { + continue; + } + if (resolver.entryBiome(entry) == null) { + continue; + } + resolved = entry; + } + return resolved; + } + + private ResolvedCarvingEntry legacyResolveFromRoot(ResolvedCarvingEntry rootEntry, int worldX, int worldZ) { + if (rootEntry == null || resolver.entryBiome(rootEntry) == null) { + return null; + } + + int remainingDepth = clampDepth(rootEntry.childRecursionDepth()); + if (remainingDepth <= 0) { + return rootEntry; + } + + ResolvedCarvingEntry current = rootEntry; + int depth = remainingDepth; + while (depth > 0) { + ResolvedCarvingEntry selected = legacySelectChild(current, worldX, worldZ); + if (selected == null || selected == current) { + break; + } + + depth--; + int childDepthLimit = clampDepth(selected.childRecursionDepth()); + if (childDepthLimit < depth) { + depth = childDepthLimit; + } + current = selected; + } + + return current; + } + + private ResolvedCarvingEntry legacySelectChild(ResolvedCarvingEntry parent, int worldX, int worldZ) { + List children = parent.children(); + if (children.isEmpty()) { + return parent; + } + if (resolver.entryBiome(parent) == null) { + return parent; + } + + KList options = new KList<>(); + for (String childId : children) { + if (childId == null || childId.isBlank()) { + continue; + } + + ResolvedCarvingEntry child = resolver.index().get(childId.trim()); + if (child == null || !child.enabled() || resolver.entryBiome(child) == null) { + continue; + } + + options.add(new LegacyCarvingChoice(child, rarity(child))); + } + + options.add(new LegacyCarvingChoice(parent, rarity(parent))); + if (options.size() <= 1) { + return parent; + } + + long seed = world.seed(art.arcane.iris.builtin.IrisSeed.CARVE) ^ CHILD_SEED_SALT; + LegacyCarvingChoice selected = legacyChildrenGenerator(parent, seed).fitRarity(options, worldX, worldZ); + if (selected == null || selected.entry == null) { + return parent; + } + + return selected.entry; + } + + private int rarity(ResolvedCarvingEntry entry) { + return Math.max(resolver.entryBiome(entry).rarity(), 1); + } + + /** The generator of an entry's children as Iris built it: its style created from the entry's seed, then scaled by the shrink factor. */ + private CNG legacyChildrenGenerator(ResolvedCarvingEntry parent, long seed) { + CarvingEntry settings = settingsById.get(parent.id()); + long idHash = settings.id().trim().hashCode(); + long generatorSeed = seed ^ (idHash << 32) ^ CHILD_GENERATOR_SALT; + double scale = Math.max(MIN_CHILD_SCALE, settings.childShrinkFactor()); + RNG random = new RNG(generatorSeed); + return IrisValues.generatorStyle(settings.childStyle()).createNoCache(random.nextParallelRNG(CHILD_GENERATOR_SIGNATURE), world.data()) + .bake().scale(scale).bake(); + } } private static final class LegacyCarvingChoice implements IRare { diff --git a/core/src/test/java/art/arcane/iris/engine/object/terrain/carving/CaveProfileDecodingTest.java b/core/src/test/java/art/arcane/iris/engine/object/terrain/carving/CaveProfileDecodingTest.java index 93f3cf5ee..38acb398a 100644 --- a/core/src/test/java/art/arcane/iris/engine/object/terrain/carving/CaveProfileDecodingTest.java +++ b/core/src/test/java/art/arcane/iris/engine/object/terrain/carving/CaveProfileDecodingTest.java @@ -152,20 +152,20 @@ public class CaveProfileDecodingTest { } @Test - public void carversReadTheProfileAsIrisStylesAndRanges() { - ResolvedCaveProfile resolved = ResolvedCaveProfile.of(gson.fromJson(OVERWORLD_CAVE_PROFILE, CaveProfile.class)); + public void carversReadTheProfileThroughItsApiValues() { + CaveProfile profile = gson.fromJson(OVERWORLD_CAVE_PROFILE, CaveProfile.class); - assertEquals(6, resolved.verticalRange().getMin(), 0); - assertEquals(700, resolved.verticalRange().getMax(), 0); - assertEquals("PERLIN_IRIS", resolved.baseDensityStyle().getStyle().name()); - assertEquals(0.72, resolved.baseDensityStyle().getZoom(), 0); - assertEquals("FRACTAL_WATER", resolved.warpStyle().getStyle().name()); - assertEquals(0.88, resolved.surfaceBreakStyle().getZoom(), 0); - assertEquals(-0.06, resolved.densityThreshold().getMax(), 0); - assertEquals("SIMPLEX", resolved.densityThreshold().getStyle().getStyle().name()); - assertEquals(2, resolved.modules().size()); - assertEquals(0.08, resolved.modules().get(0).weight(), 0); - assertEquals(24, resolved.modules().get(0).verticalRange().getMin(), 0); - assertTrue(resolved.modules().get(1).invert()); + assertEquals(6, profile.verticalRange().min(), 0); + assertEquals(700, profile.verticalRange().max(), 0); + assertEquals("PERLIN_IRIS", profile.baseDensityStyle().style()); + assertEquals(0.72, profile.baseDensityStyle().zoom(), 0); + assertEquals("FRACTAL_WATER", profile.warpStyle().style()); + assertEquals(0.88, profile.surfaceBreakStyle().zoom(), 0); + assertEquals(-0.06, profile.densityThreshold().max(), 0); + assertEquals("SIMPLEX", profile.densityThreshold().style().style()); + assertEquals(2, profile.modules().size()); + assertEquals(0.08, profile.modules().get(0).weight(), 0); + assertEquals(24, profile.modules().get(0).verticalRange().min(), 0); + assertTrue(profile.modules().get(1).invert()); } } From 556ad2faf23044604a08e50649ca92c484a620d8 Mon Sep 17 00:00:00 2001 From: piexel Date: Mon, 12 Oct 2026 02:41:59 +0200 Subject: [PATCH 3/3] The missing built-ins warning names the caves --- .../art/arcane/iris/core/modules/MissingBuiltInModules.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/core/src/main/java/art/arcane/iris/core/modules/MissingBuiltInModules.java b/core/src/main/java/art/arcane/iris/core/modules/MissingBuiltInModules.java index cdc634b30..5c4675895 100644 --- a/core/src/main/java/art/arcane/iris/core/modules/MissingBuiltInModules.java +++ b/core/src/main/java/art/arcane/iris/core/modules/MissingBuiltInModules.java @@ -43,7 +43,7 @@ final class MissingBuiltInModules { return Optional.empty(); } return Optional.of("Pack " + packFolder.getName() + " loads without the built-in modules (" + JAR_NAME + "): its chunks get" - + " no objects or structures, no surface smoothing and no clean-up of floating decorations. Copy " + JAR_NAME + + " no caves, no objects or structures, no surface smoothing and no clean-up of floating decorations. Copy " + JAR_NAME + " into " + new File(packFolder, PackModuleSet.MODULES_FOLDER).getPath() + " to fix it."); } }