diff --git a/builtin-modules.txt b/builtin-modules.txt index 824782905..550a80810 100644 --- a/builtin-modules.txt +++ b/builtin-modules.txt @@ -18,3 +18,24 @@ module art.arcane.iris.engine.modifier.PostModule include art/arcane/iris/engine/modifier/SurfaceSmoothing*.class module art.arcane.iris.engine.modifier.PerfectionModule module art.arcane.iris.engine.modifier.MatterModule +module art.arcane.iris.engine.modifier.CarveModule +include art/arcane/iris/engine/modifier/CaveApplying*.class +include art/arcane/iris/engine/modifier/CaveBiomeBands*.class +include art/arcane/iris/engine/modifier/CaveBiomeCache.class +include art/arcane/iris/engine/modifier/CaveBlockClasses.class +include art/arcane/iris/engine/modifier/CarveColumnMask.class +include art/arcane/iris/engine/modifier/CarveWallBuffer*.class +include art/arcane/iris/engine/modifier/IrisCarveScratch.class +include art/arcane/iris/engine/mantle/components/CarveOrphanSweep*.class +include art/arcane/iris/engine/mantle/components/CarveWorld.class +include art/arcane/iris/engine/mantle/components/CaveCarveScratch*.class +include art/arcane/iris/engine/mantle/components/CaveCarving*.class +include art/arcane/iris/engine/mantle/components/CaveFieldModuleState.class +include art/arcane/iris/engine/mantle/components/CaveFluidSupportPlan*.class +include art/arcane/iris/engine/mantle/components/IrisCaveCarver3D*.class +include art/arcane/iris/engine/mantle/components/SurfaceFluidBoundaryPlan*.class +include art/arcane/iris/engine/object/terrain/carving/CarvingResolver*.class +include art/arcane/iris/engine/object/terrain/carving/CaveProfileSampler*.class +include art/arcane/iris/engine/object/terrain/carving/DeclaredByLevel.class +include art/arcane/iris/engine/object/terrain/carving/DeclaredCaveProfiles.class +include art/arcane/iris/engine/object/terrain/carving/ResolvedCarvingEntry.class diff --git a/src/main/java/art/arcane/iris/builtin/CaveDressing.java b/src/main/java/art/arcane/iris/builtin/CaveDressing.java new file mode 100644 index 000000000..14afe16e0 --- /dev/null +++ b/src/main/java/art/arcane/iris/builtin/CaveDressing.java @@ -0,0 +1,88 @@ +/* + * 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.builtin; + +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 com.volmit.world.PackWorld; + +import java.util.List; + +/** + * What a cave's floor, ceiling and walls get from the rest of Iris's terrain and decoration: the blocks of a biome's layers + * and wall, its decorators and the fluid of the dimension's palette. Those features keep their workers per world and are + * ported on their own; until they are modules this narrow interface is the one thing {@code iris:carve} needs from them, in + * IrisApi's types, and Iris's worlds implement it ({@link Source}). + * + *

Transitional: when {@code iris:terrain} and {@code iris:decorant} are modules of the same jar, {@code iris:carve} asks + * their classes directly and this interface goes. + * + *

The methods that give a block take the {@code chunk} hunk the block is for. A block read from here and written to that + * hunk keeps the identity of a content plugin's custom block, as it did when the layers wrote the platform's states themselves. + */ +public interface CaveDressing { + /** The dressing of {@code world}, which must be a world Iris generates. */ + static CaveDressing of(PackWorld world) { + if (world instanceof Source source) { + return source.caveDressing(); + } + throw new IllegalArgumentException("Built-in modules generate Iris's own worlds, not " + world); + } + + /** Iris's worlds answer for their dressing. */ + interface Source { + CaveDressing caveDressing(); + } + + /** Whether the dimension's fluid palette gives a fluid (water, lava) at the column; false where it gives none. */ + boolean fluidPresentAt(int x, int z); + + /** The block the dimension's fluid palette gives at the column; null where it gives none. */ + BlockState fluidAt(Hunk chunk, int x, int z); + + /** The block the biome's wall gives at the position; null where the biome has no wall or the layer gives none. */ + BlockState wall(Hunk chunk, ResourceId biome, RNG rng, int x, int y, int z); + + /** The blocks the biome's surface layers stack up to at the column, top first, at most {@code depth} of them. */ + List floorLayers(Hunk chunk, ResourceId biome, int x, int z, RNG rng, int depth, int floorY); + + /** The blocks the biome's cave ceiling layers stack up to at the column, nearest the ceiling first, at most {@code depth} of them. */ + List ceilingLayers(Hunk chunk, ResourceId biome, int x, int z, RNG rng, int depth, int ceilingY); + + /** Whether the biome has a decorator for {@code part}. */ + boolean hasDecorators(ResourceId biome, DecorationPart part); + + /** + * Decorates a cave's floor in the column at {@code chunk}'s {@code localX}, {@code localZ} (world {@code x}, {@code z}) above + * the block at {@code floorY}, with the biome's decorators for {@link DecorationPart#NONE}, in a space {@code airThickness} high. + */ + void decorateFloor(Hunk chunk, int localX, int localZ, int x, int z, ResourceId biome, int floorY, int airThickness); + + /** Decorates a cave's ceiling the same way, from the block at {@code ceilingY} down, with the decorators for {@link DecorationPart#CEILING}. */ + void decorateCeiling(Hunk chunk, int localX, int localZ, int x, int z, ResourceId biome, int ceilingY, int airThickness); + + /** + * {@code layer}, the block a layer wants in the place of the ore {@code existing}, as the deepslate or the stone variant + * of the ore that fits the rock {@code existing} is; {@code layer} itself where it has no variant. + */ + BlockState deepSlateOre(Hunk chunk, BlockState existing, BlockState layer); +} diff --git a/src/main/java/art/arcane/iris/builtin/MatterMantle.java b/src/main/java/art/arcane/iris/builtin/MatterMantle.java new file mode 100644 index 000000000..34ae03f93 --- /dev/null +++ b/src/main/java/art/arcane/iris/builtin/MatterMantle.java @@ -0,0 +1,59 @@ +/* + * 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.builtin; + +import art.arcane.volmlib.util.mantle.runtime.MantleChunk; +import art.arcane.volmlib.util.matter.Matter; +import com.volmit.host.ReadOnlyMantle; +import com.volmit.mantle.Mantle; + +/** + * Iris's mantle as the matter slices it stores, for the built-ins whose data the platform and the rest of Iris read as + * slices rather than through a {@link com.volmit.mantle.MantleLayer}: caves ({@code MatterCavern}) and markers. The + * slices are VolmLib's own types, which a pack module may use as well; Iris's worlds implement this next to + * {@link Mantle}, and {@link #of(Mantle)} reaches it from an invocation's mantle. + * + *

Heights are as the mantle stores them: above the dimension's bottom. A chunk the invocation reaches is pinned for + * as long as the invocation runs; callers neither release it nor keep it afterwards. + */ +public interface MatterMantle { + /** + * The matter side of {@code mantle}, which must be a mantle Iris hands to its stages. A chunk stage's mantle is read-only + * to the stage; the matter behind it is not, and a built-in chunk stage that writes markers into it (the caves' floors and + * ceilings) is why this reaches through. + */ + static MatterMantle of(Mantle mantle) { + if (mantle instanceof ReadOnlyMantle readOnly) { + return of(readOnly.host()); + } + if (mantle instanceof MatterMantle matter) { + return matter; + } + throw new IllegalArgumentException("Built-in modules write Iris's own mantle, not " + mantle); + } + + /** The mantle chunk at chunk coordinates {@code chunkX}, {@code chunkZ}, or null outside what the invocation reaches. */ + MantleChunk chunk(int chunkX, int chunkZ); + + /** + * The mantle chunk at those coordinates if the world holds it in memory, wherever it is, or null. It is never loaded + * or created for the call and not pinned, so read it at once and do not keep it. + */ + MantleChunk loadedChunk(int chunkX, int chunkZ); +} diff --git a/src/main/java/art/arcane/iris/builtin/carve/CaveLavaHeightSettings.java b/src/main/java/art/arcane/iris/builtin/carve/CaveLavaHeightSettings.java new file mode 100644 index 000000000..4355cbb47 --- /dev/null +++ b/src/main/java/art/arcane/iris/builtin/carve/CaveLavaHeightSettings.java @@ -0,0 +1,49 @@ +/* + * 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.builtin.carve; + +import com.volmit.FeatureAttachment.Target; +import com.volmit.IrisFeature; +import com.volmit.config.Desc; +import com.volmit.config.Feature; +import com.volmit.config.MaxNumber; +import com.volmit.config.MinNumber; + +/** A dimension's {@code caveLavaHeight}, written as the bare number. */ +@Desc("The subterranean fluid (cave lava) layer height, in engine-local Y where 0 is the bottom of the dimension, not world Y. With the default -64..320 height, 8 means world Y -56.") +@Feature(id = "iris:carve/lava-height", name = "Cave lava height", key = "caveLavaHeight", root = "height", targets = Target.DIMENSION) +public final class CaveLavaHeightSettings implements IrisFeature { + public static final int DEFAULT_HEIGHT = 8; + + @MinNumber(0) + @MaxNumber(318) + @Desc("The subterranean fluid (cave lava) layer height, in engine-local Y where 0 is the bottom of the dimension, not world Y. With the default -64..320 height, 8 means world Y -56.") + private int height = DEFAULT_HEIGHT; + + public CaveLavaHeightSettings() { + } + + public CaveLavaHeightSettings(int height) { + this.height = height; + } + + public int height() { + return height; + } +} diff --git a/src/main/java/art/arcane/iris/builtin/carve/UpperDimensionCarvingSettings.java b/src/main/java/art/arcane/iris/builtin/carve/UpperDimensionCarvingSettings.java new file mode 100644 index 000000000..741aaa382 --- /dev/null +++ b/src/main/java/art/arcane/iris/builtin/carve/UpperDimensionCarvingSettings.java @@ -0,0 +1,43 @@ +/* + * 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.builtin.carve; + +import com.volmit.FeatureAttachment.Target; +import com.volmit.IrisFeature; +import com.volmit.config.Desc; +import com.volmit.config.Feature; + +/** A dimension's {@code upperDimensionCarving}, written as the bare boolean. */ +@Desc("When true, cave carving will cut through the upper dimension terrain. When false, the upper terrain is a solid untouched mass.") +@Feature(id = "iris:carve/upper-dimension", name = "Upper dimension carving", key = "upperDimensionCarving", root = "enabled", targets = Target.DIMENSION) +public final class UpperDimensionCarvingSettings implements IrisFeature { + @Desc("When true, cave carving will cut through the upper dimension terrain. When false, the upper terrain is a solid untouched mass.") + private boolean enabled = false; + + public UpperDimensionCarvingSettings() { + } + + public UpperDimensionCarvingSettings(boolean enabled) { + this.enabled = enabled; + } + + public boolean enabled() { + return enabled; + } +} diff --git a/src/main/java/art/arcane/iris/engine/framework/StructureCaveAnchorResolver.java b/src/main/java/art/arcane/iris/engine/framework/StructureCaveAnchorResolver.java index 599b4bd88..5f8620d76 100644 --- a/src/main/java/art/arcane/iris/engine/framework/StructureCaveAnchorResolver.java +++ b/src/main/java/art/arcane/iris/engine/framework/StructureCaveAnchorResolver.java @@ -1,5 +1,6 @@ package art.arcane.iris.engine.framework; +import art.arcane.iris.builtin.carve.CaveLavaHeightSettings; import art.arcane.iris.engine.object.world.biome.IrisBiome; import art.arcane.iris.engine.object.structure.IrisStructureAnchorMode; import art.arcane.iris.engine.object.structure.IrisStructurePlacement; @@ -291,7 +292,7 @@ public final class StructureCaveAnchorResolver { placement.isUnderwater(), cavern, mantleY, - engine.getDimension().getCaveLavaHeight()); + engine.getDimension().getModuleSettings().find(CaveLavaHeightSettings.class).map(CaveLavaHeightSettings::height).orElse(CaveLavaHeightSettings.DEFAULT_HEIGHT)); } static boolean acceptsAnchorFluid( diff --git a/src/main/java/art/arcane/iris/engine/mantle/components/CarveWorld.java b/src/main/java/art/arcane/iris/engine/mantle/components/CarveWorld.java new file mode 100644 index 000000000..2d04b7cd0 --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/mantle/components/CarveWorld.java @@ -0,0 +1,29 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.engine.mantle.components; + +import com.volmit.noise.NoiseFactory; + +/** + * What the cave carvers need to know about one world that does not change while it runs: the noise the world's pack builds, + * the carve seed, the dimension's height, its fluid and cave-lava heights (above the dimension's bottom) and the platform's Y of + * its bottom, which converts the absolute world Y of a cave biome band. + */ +public record CarveWorld(NoiseFactory noise, long carveSeed, int height, int fluidHeight, int lavaHeight, int minHeight) { +} diff --git a/src/main/java/art/arcane/iris/engine/mantle/components/CaveCarving.java b/src/main/java/art/arcane/iris/engine/mantle/components/CaveCarving.java index 7046d1da8..94745233d 100644 --- a/src/main/java/art/arcane/iris/engine/mantle/components/CaveCarving.java +++ b/src/main/java/art/arcane/iris/engine/mantle/components/CaveCarving.java @@ -18,31 +18,19 @@ package art.arcane.iris.engine.mantle.components; +import art.arcane.iris.builtin.CaveDressing; +import art.arcane.iris.builtin.MatterMantle; import art.arcane.iris.builtin.carve.CaveProfile; -import art.arcane.iris.core.modules.IrisValues; -import art.arcane.iris.engine.IrisComplex; -import art.arcane.iris.engine.UpperDimensionContext; -import art.arcane.iris.engine.framework.Engine; -import art.arcane.iris.engine.mantle.MantleWriter; -import art.arcane.iris.engine.terrain.TerrainPalettes; -import art.arcane.iris.engine.object.terrain.carving.CaveProfiles; -import art.arcane.iris.engine.object.world.biome.IrisBiome; -import art.arcane.iris.engine.object.terrain.carving.ResolvedCarvingEntry; -import art.arcane.iris.engine.modifier.CaveBiomeBands; -import art.arcane.iris.engine.object.terrain.carving.CarvingBands; import art.arcane.iris.engine.object.terrain.carving.CarvingResolver; -import art.arcane.iris.engine.object.world.region.IrisRegion; -import art.arcane.iris.engine.object.value.IrisRange; -import art.arcane.iris.spi.PlatformBlockState; -import art.arcane.iris.util.common.data.B; -import art.arcane.iris.util.project.context.ChunkContext; -import art.arcane.iris.util.project.stream.ProceduralStream; -import art.arcane.iris.util.project.stream.utility.ChunkFillableDoubleStream2D; -import art.arcane.iris.util.simd.SimdKernels; -import art.arcane.iris.util.simd.SimdSupport; -import art.arcane.volmlib.util.documentation.ChunkCoordinates; +import art.arcane.iris.engine.object.terrain.carving.DeclaredCaveProfiles; +import art.arcane.iris.engine.object.terrain.carving.ResolvedCarvingEntry; import art.arcane.volmlib.util.math.PowerOfTwoCoordinates; -import art.arcane.volmlib.util.scheduling.PrecisionStopwatch; +import com.volmit.config.Range; +import com.volmit.resource.ResourceId; +import com.volmit.world.BiomeSample; +import com.volmit.world.PackBiome; +import com.volmit.world.PackWorld; +import com.volmit.world.TerrainSampler; import java.util.ArrayList; import java.util.Arrays; @@ -59,6 +47,8 @@ public class CaveCarving { private static final int CHUNK_SIZE = 16; private static final int CHUNK_AREA = CHUNK_SIZE * CHUNK_SIZE; private static final int BLEND_RADIUS = 3; + /** A column's cave biome is the one the world places this far below its surface (at least at height 1). */ + private static final int CAVE_SAMPLE_DEPTH_BELOW_SURFACE_BLOCKS = 56; private static final int FIELD_SIZE = CHUNK_SIZE + (BLEND_RADIUS * 2); private static final double MIN_WEIGHT = 0.08D; private static final double THRESHOLD_PENALTY = 0.24D; @@ -70,7 +60,11 @@ public class CaveCarving { private static final double[] KERNEL_WEIGHT = new double[KERNEL_SIZE]; private static final ThreadLocal BLEND_SCRATCH = ThreadLocal.withInitial(BlendScratch::new); - private final Engine engine; + private final CarveWorld world; + private final DeclaredCaveProfiles declaredProfiles; + private final CarvingResolver resolver; + private final CaveDressing dressing; + private final boolean upperDimensionCarving; private final Object profileCarverLock = new Object(); private volatile Map profileCarvers = new IdentityHashMap<>(); @@ -87,20 +81,20 @@ public class CaveCarving { } } - public CaveCarving(Engine engine) { - this.engine = engine; + public CaveCarving(PackWorld packWorld, CarveWorld world, boolean upperDimensionCarving) { + this.world = world; + this.declaredProfiles = DeclaredCaveProfiles.of(packWorld); + this.resolver = CarvingResolver.of(packWorld); + this.dressing = CaveDressing.of(packWorld); + this.upperDimensionCarving = upperDimensionCarving; } - /** Carves the caves of the chunk at chunk coordinates {@code x}, {@code z} into {@code writer}. */ - public void carve(MantleWriter writer, int x, int z, ChunkContext context) { - IrisComplex complex = context.getComplex(); - CarvingResolver.State resolverState = new CarvingResolver.State(); + /** Carves the caves of the chunk at chunk coordinates {@code x}, {@code z} into {@code mantle}, reading the terrain around it from {@code terrain}. */ + public void carve(MatterMantle mantle, TerrainSampler terrain, int x, int z) { BlendScratch blendScratch = BLEND_SCRATCH.get(); - int[] chunkSurfaceHeights = prepareChunkSurfaceHeights(x, z, context, blendScratch.chunkSurfaceHeights); - PrecisionStopwatch resolveStopwatch = PrecisionStopwatch.start(); - List weightedProfiles = resolveWeightedProfiles(x, z, complex, resolverState); - engine.getMetrics().getCarveResolve().put(resolveStopwatch.getMilliseconds()); - int fluidHeight = engine.getDimension().getFluidHeight(); + int[] chunkSurfaceHeights = prepareChunkSurfaceHeights(x, z, terrain, blendScratch.chunkSurfaceHeights); + List weightedProfiles = resolveWeightedProfiles(x, z, terrain); + int fluidHeight = world.fluidHeight(); int[] surfaceFluidBoundaryStartY = blendScratch.surfaceFluidBoundaryStartY; SurfaceFluidBoundaryPlan.fill( chunkSurfaceHeights, @@ -113,27 +107,30 @@ public class CaveCarving { ); CaveFluidSupportPlan fluidSupportPlan = new CaveFluidSupportPlan(); for (WeightedProfile weightedProfile : weightedProfiles) { - carveProfile(weightedProfile, writer, x, z, chunkSurfaceHeights, surfaceFluidBoundaryStartY, fluidSupportPlan); + carveProfile(weightedProfile, mantle, x, z, chunkSurfaceHeights, surfaceFluidBoundaryStartY, fluidSupportPlan); } - UpperDimensionContext upperCtx = engine.getUpperContext(); - if (upperCtx != null && engine.getDimension().isUpperDimensionCarving()) { - carveUpperTerrain(upperCtx, weightedProfiles, writer, x, z, chunkSurfaceHeights, fluidSupportPlan); + if (upperDimensionCarving && hasUpperDimension(terrain, x, z)) { + carveUpperTerrain(terrain, weightedProfiles, mantle, x, z, fluidSupportPlan); } - fluidSupportPlan.resolve(writer.acquireChunk(x, z)); + fluidSupportPlan.resolve(mantle.chunk(x, z)); if (!weightedProfiles.isEmpty()) { CarveOrphanSweep.sweepChunk( - writer.acquireChunk(x, z), + mantle.chunk(x, z), chunkSurfaceHeights, maxSurfaceBreakDepth(weightedProfiles), - writer.getMantle().getWorldHeight() - 1, + world.height() - 1, surfaceFluidBoundaryStartY, fluidHeight ); } } + private static boolean hasUpperDimension(TerrainSampler terrain, int chunkX, int chunkZ) { + return terrain.upperDimensionY(PowerOfTwoCoordinates.chunkToBlock(chunkX), PowerOfTwoCoordinates.chunkToBlock(chunkZ)).isPresent(); + } + private static int maxSurfaceBreakDepth(List weightedProfiles) { int maxDepth = 0; for (WeightedProfile weightedProfile : weightedProfiles) { @@ -142,21 +139,19 @@ public class CaveCarving { return maxDepth; } - @ChunkCoordinates - private void carveProfile(WeightedProfile weightedProfile, MantleWriter writer, int cx, int cz, + private void carveProfile(WeightedProfile weightedProfile, MatterMantle mantle, int cx, int cz, int[] chunkSurfaceHeights, int[] surfaceFluidBoundaryStartY, CaveFluidSupportPlan fluidSupportPlan) { IrisCaveCarver3D carver = getCarver(weightedProfile.profile); - carver.carve(writer, cx, cz, weightedProfile.columnWeights, MIN_WEIGHT, THRESHOLD_PENALTY, + carver.carve(mantle, cx, cz, weightedProfile.columnWeights, MIN_WEIGHT, THRESHOLD_PENALTY, weightedProfile.worldYRange, chunkSurfaceHeights, surfaceFluidBoundaryStartY, null, fluidSupportPlan); } - private void carveUpperTerrain(UpperDimensionContext upperCtx, List normalProfiles, - MantleWriter writer, int cx, int cz, int[] lowerSurfaceHeights, + private void carveUpperTerrain(TerrainSampler terrain, List normalProfiles, + MatterMantle mantle, int cx, int cz, CaveFluidSupportPlan fluidSupportPlan) { - int chunkHeight = engine.getHeight(); - int worldMinHeight = engine.getWorld().minHeight(); - int gap = engine.getDimension().getUpperDimensionGap(); + int chunkHeight = world.height(); + int worldMinHeight = world.minHeight(); int baseX = PowerOfTwoCoordinates.chunkToBlock(cx); int baseZ = PowerOfTwoCoordinates.chunkToBlock(cz); @@ -165,9 +160,7 @@ public class CaveCarving { int worldX = baseX + localX; for (int localZ = 0; localZ < CHUNK_SIZE; localZ++) { int worldZ = baseZ + localZ; - int columnIndex = PowerOfTwoCoordinates.packLocal16(localX, localZ); - int rawUpper = upperCtx.getUpperSurfaceY(worldX, worldZ); - int upperY = Math.max(rawUpper, lowerSurfaceHeights[columnIndex] + gap); + int upperY = terrain.upperDimensionY(worldX, worldZ).getAsInt(); if (upperY < minUpperSurfaceY) { minUpperSurfaceY = upperY; } @@ -178,34 +171,34 @@ public class CaveCarving { return; } - IrisRange upperYRange = new IrisRange( + Range upperYRange = Range.of( minUpperSurfaceY + worldMinHeight, chunkHeight - 1 + worldMinHeight ); - IrisRange fullVerticalRange = new IrisRange(0, chunkHeight); + Range fullVerticalRange = Range.of(0, chunkHeight); int[] ceilingSurfaceHeights = new int[CHUNK_AREA]; Arrays.fill(ceilingSurfaceHeights, chunkHeight - 1); for (WeightedProfile weightedProfile : normalProfiles) { - IrisRange constrainedRange; + Range constrainedRange; if (weightedProfile.worldYRange != null) { - double min = Math.max(weightedProfile.worldYRange.getMin(), upperYRange.getMin()); - double max = Math.min(weightedProfile.worldYRange.getMax(), upperYRange.getMax()); + double min = Math.max(weightedProfile.worldYRange.min(), upperYRange.min()); + double max = Math.min(weightedProfile.worldYRange.max(), upperYRange.max()); if (min >= max) { continue; } - constrainedRange = new IrisRange(min, max); + constrainedRange = Range.of(min, max); } else { constrainedRange = upperYRange; } IrisCaveCarver3D carver = getCarver(weightedProfile.profile); - carver.carve(writer, cx, cz, weightedProfile.columnWeights, MIN_WEIGHT, THRESHOLD_PENALTY, + carver.carve(mantle, cx, cz, weightedProfile.columnWeights, MIN_WEIGHT, THRESHOLD_PENALTY, constrainedRange, ceilingSurfaceHeights, null, fullVerticalRange, fluidSupportPlan); } } - private List resolveWeightedProfiles(int chunkX, int chunkZ, IrisComplex complex, CarvingResolver.State resolverState) { + private List resolveWeightedProfiles(int chunkX, int chunkZ, TerrainSampler terrain) { BlendScratch blendScratch = BLEND_SCRATCH.get(); CaveProfile[] profileField = blendScratch.profileField; Map columnProfileWeights = blendScratch.columnProfileWeights; @@ -215,7 +208,7 @@ public class CaveCarving { double[] kernelProfileWeights = blendScratch.kernelProfileWeights; activeProfiles.clear(); profileOrder.clear(); - fillProfileField(profileField, chunkX, chunkZ, complex, resolverState, blendScratch); + fillProfileField(profileField, chunkX, chunkZ, terrain, blendScratch); for (int localX = 0; localX < CHUNK_SIZE; localX++) { for (int localZ = 0; localZ < CHUNK_SIZE; localZ++) { @@ -285,7 +278,7 @@ public class CaveCarving { // averageWeight ranks and orders carve passes, so it must be bit-identical across // installations: kernels.sum reassociates FP addition under the vector kernel, // making profile order depend on a JVM flag. max() is order-independent and safe. - double maxWeight = SimdSupport.kernels().max(weights, weights.length); + double maxWeight = maxOf(weights); if (maxWeight < MIN_WEIGHT) { continue; @@ -296,14 +289,14 @@ public class CaveCarving { } List blendedProfiles = limitAndMergeBlendedProfiles(columnWeightedProfiles, MAX_BLENDED_PROFILE_PASSES, CHUNK_AREA); - List resolvedProfiles = resolveDimensionCarvingProfiles(chunkX, chunkZ, resolverState, blendScratch); + List resolvedProfiles = resolveDimensionCarvingProfiles(chunkX, chunkZ, blendScratch); resolvedProfiles.addAll(blendedProfiles); return resolvedProfiles; } - private List resolveDimensionCarvingProfiles(int chunkX, int chunkZ, CarvingResolver.State resolverState, BlendScratch blendScratch) { + private List resolveDimensionCarvingProfiles(int chunkX, int chunkZ, BlendScratch blendScratch) { List weightedProfiles = new ArrayList<>(); - List entries = CarvingBands.of(engine).entries(); + List entries = resolver.entries(); if (entries.isEmpty()) { return weightedProfiles; } @@ -316,25 +309,25 @@ public class CaveCarving { continue; } - IrisBiome rootBiome = CarvingResolver.resolveEntryBiome(engine, entry, resolverState); + PackBiome rootBiome = resolver.entryBiome(entry); if (rootBiome == null) { continue; } ResolvedCarvingEntry[] columnPlan = dimensionColumnPlans.computeIfAbsent(entry, key -> new ResolvedCarvingEntry[CHUNK_AREA]); - buildDimensionColumnPlan(columnPlan, chunkX, chunkZ, entry, resolverState); + buildDimensionColumnPlan(columnPlan, chunkX, chunkZ, entry); Map rootProfileColumnWeights = new IdentityHashMap<>(); List rootProfileOrder = new ArrayList<>(); - IrisRange worldYRange = entry.worldYRange() == null ? null : IrisValues.range(entry.worldYRange()); + Range worldYRange = entry.worldYRange(); for (int columnIndex = 0; columnIndex < CHUNK_AREA; columnIndex++) { ResolvedCarvingEntry resolvedEntry = columnPlan[columnIndex]; - IrisBiome resolvedBiome = CarvingResolver.resolveEntryBiome(engine, resolvedEntry, resolverState); + PackBiome resolvedBiome = resolver.entryBiome(resolvedEntry); if (resolvedBiome == null) { continue; } - CaveProfile profile = CaveProfiles.declaredBy(resolvedBiome); + CaveProfile profile = declaredProfiles.ofBiome(resolvedBiome.id()); if (!isProfileEnabled(profile)) { continue; } @@ -356,7 +349,7 @@ public class CaveCarving { return weightedProfiles; } - private void buildDimensionColumnPlan(ResolvedCarvingEntry[] columnPlan, int chunkX, int chunkZ, ResolvedCarvingEntry entry, CarvingResolver.State resolverState) { + private void buildDimensionColumnPlan(ResolvedCarvingEntry[] columnPlan, int chunkX, int chunkZ, ResolvedCarvingEntry entry) { int baseX = PowerOfTwoCoordinates.chunkToBlock(chunkX); int baseZ = PowerOfTwoCoordinates.chunkToBlock(chunkZ); for (int localX = 0; localX < CHUNK_SIZE; localX++) { @@ -364,30 +357,22 @@ public class CaveCarving { for (int localZ = 0; localZ < CHUNK_SIZE; localZ++) { int worldZ = baseZ + localZ; int columnIndex = PowerOfTwoCoordinates.packLocal16(localX, localZ); - columnPlan[columnIndex] = CarvingResolver.resolveFromRoot(engine, entry, worldX, worldZ, resolverState); + columnPlan[columnIndex] = resolver.resolveFromRoot(entry, worldX, worldZ); } } } - private void fillProfileField(CaveProfile[] profileField, int chunkX, int chunkZ, IrisComplex complex, CarvingResolver.State resolverState, BlendScratch blendScratch) { + private void fillProfileField(CaveProfile[] profileField, int chunkX, int chunkZ, TerrainSampler terrain, BlendScratch blendScratch) { int startX = PowerOfTwoCoordinates.chunkToBlock(chunkX) - BLEND_RADIUS; int startZ = PowerOfTwoCoordinates.chunkToBlock(chunkZ) - BLEND_RADIUS; - prefillProfileFieldSamples(startX, startZ, complex, blendScratch); + prefillFieldHeightsAndFluid(terrain, startX, startZ, blendScratch); for (int fieldX = 0; fieldX < FIELD_SIZE; fieldX++) { int worldX = startX + fieldX; for (int fieldZ = 0; fieldZ < FIELD_SIZE; fieldZ++) { int worldZ = startZ + fieldZ; int fieldIndex = (fieldX * FIELD_SIZE) + fieldZ; - profileField[fieldIndex] = resolveColumnProfile( - worldX, - worldZ, - blendScratch.fieldSurfaceHeights[fieldIndex], - blendScratch.fieldRegions[fieldIndex], - blendScratch.fieldSurfaceBiomes[fieldIndex], - blendScratch.fieldCaveBiomes[fieldIndex], - resolverState - ); + profileField[fieldIndex] = resolveColumnProfile(terrain, worldX, worldZ, blendScratch.fieldSurfaceHeights[fieldIndex]); } } } @@ -402,65 +387,34 @@ public class CaveCarving { return -1; } - private CaveProfile resolveColumnProfile( - int worldX, - int worldZ, - double surfaceHeight, - IrisRegion region, - IrisBiome surfaceBiome, - IrisBiome caveBiome, - CarvingResolver.State resolverState - ) { + /** + * The profile that carves a column: the dimension's, replaced by the region's, the surface biome's and the cave biome's + * wherever they declare an enabled one. The cave biome is the one the world places at the depth below the surface this + * column's caves start at ({@link #CAVE_SAMPLE_DEPTH_BELOW_SURFACE_BLOCKS}), after the dimension's carving bands. + */ + private CaveProfile resolveColumnProfile(TerrainSampler terrain, int worldX, int worldZ, double surfaceHeight) { CaveProfile resolved = null; - CaveProfile dimensionProfile = CaveProfiles.declaredBy(engine.getDimension()); + CaveProfile dimensionProfile = declaredProfiles.ofDimension(); if (isProfileEnabled(dimensionProfile)) { resolved = dimensionProfile; } - if (region != null) { - CaveProfile regionProfile = CaveProfiles.declaredBy(region); - if (isProfileEnabled(regionProfile)) { - resolved = regionProfile; - } - } - - if (surfaceBiome != null) { - CaveProfile surfaceProfile = CaveProfiles.declaredBy(surfaceBiome); - if (isProfileEnabled(surfaceProfile)) { - resolved = surfaceProfile; - } - } - int roundedSurfaceY = (int) Math.round(surfaceHeight); - int sampleY = Math.max(1, roundedSurfaceY - 56); - int worldY = sampleY + engine.getWorld().minHeight(); - ResolvedCarvingEntry rootCarvingEntry = CarvingResolver.resolveRootEntry(engine, worldY, resolverState); - IrisBiome resolvedCarvingBiome = null; - if (rootCarvingEntry != null) { - ResolvedCarvingEntry resolvedCarvingEntry = CarvingResolver.resolveFromRoot(engine, rootCarvingEntry, worldX, worldZ, resolverState); - resolvedCarvingBiome = CarvingResolver.resolveEntryBiome(engine, resolvedCarvingEntry, resolverState); - if (resolvedCarvingBiome != null) { - caveBiome = resolvedCarvingBiome; - } - } - if (caveBiome != null) { - IrisBiome effectiveCaveBiome = caveBiome; - if (resolvedCarvingBiome == null && surfaceBiome != null) { - if (surfaceBiome != null) { - int truncatedSurfaceY = (int) surfaceHeight; - int depthBelowSurface = truncatedSurfaceY - sampleY; - if (depthBelowSurface <= 0) { - effectiveCaveBiome = surfaceBiome; - } else { - int minDepth = Math.max(0, CaveBiomeBands.minDepthBelowSurface(caveBiome)); - if (depthBelowSurface < minDepth) { - effectiveCaveBiome = surfaceBiome; - } - } - } - } + int sampleY = Math.max(1, roundedSurfaceY - CAVE_SAMPLE_DEPTH_BELOW_SURFACE_BLOCKS); + BiomeSample sample = terrain.biome(worldX, sampleY, worldZ); - CaveProfile caveProfile = CaveProfiles.declaredBy(effectiveCaveBiome); + CaveProfile regionProfile = declaredProfiles.ofRegion(sample.region()); + if (isProfileEnabled(regionProfile)) { + resolved = regionProfile; + } + + CaveProfile surfaceProfile = declaredProfiles.ofBiome(sample.surfaceBiome()); + if (isProfileEnabled(surfaceProfile)) { + resolved = surfaceProfile; + } + + if (sample.caveBiome().isPresent()) { + CaveProfile caveProfile = declaredProfiles.ofBiome(sample.caveBiome().get()); if (isProfileEnabled(caveProfile)) { resolved = caveProfile; } @@ -469,37 +423,14 @@ public class CaveCarving { return resolved; } - private void prefillProfileFieldSamples(int startX, int startZ, IrisComplex complex, BlendScratch blendScratch) { - fillFieldHeights(complex.getHeightStream(), startX, startZ, blendScratch.fieldSurfaceHeights); - fillFieldFluidPresence(TerrainPalettes.of(engine), startX, startZ, blendScratch.fieldHasFluid); - fillFieldObjects(complex.getRegionStream(), startX, startZ, blendScratch.fieldRegions); - fillFieldObjects(complex.getTrueBiomeStream(), startX, startZ, blendScratch.fieldSurfaceBiomes); - fillFieldObjects(complex.getCaveBiomeStream(), startX, startZ, blendScratch.fieldCaveBiomes); - } - - private void fillFieldObjects(ProceduralStream stream, int startX, int startZ, T[] target) { + private void prefillFieldHeightsAndFluid(TerrainSampler terrain, int startX, int startZ, BlendScratch blendScratch) { for (int fieldX = 0; fieldX < FIELD_SIZE; fieldX++) { int worldX = startX + fieldX; for (int fieldZ = 0; fieldZ < FIELD_SIZE; fieldZ++) { - target[(fieldX * FIELD_SIZE) + fieldZ] = stream.get(worldX, startZ + fieldZ); - } - } - } - - private void fillFieldHeights(ProceduralStream stream, int startX, int startZ, double[] target) { - for (int fieldX = 0; fieldX < FIELD_SIZE; fieldX++) { - int worldX = startX + fieldX; - for (int fieldZ = 0; fieldZ < FIELD_SIZE; fieldZ++) { - target[(fieldX * FIELD_SIZE) + fieldZ] = stream.getDouble(worldX, startZ + fieldZ); - } - } - } - - private void fillFieldFluidPresence(TerrainPalettes palettes, int startX, int startZ, boolean[] target) { - for (int fieldX = 0; fieldX < FIELD_SIZE; fieldX++) { - int worldX = startX + fieldX; - for (int fieldZ = 0; fieldZ < FIELD_SIZE; fieldZ++) { - target[(fieldX * FIELD_SIZE) + fieldZ] = B.isFluid(palettes.fluidAt(worldX, startZ + fieldZ)); + int worldZ = startZ + fieldZ; + int fieldIndex = (fieldX * FIELD_SIZE) + fieldZ; + blendScratch.fieldSurfaceHeights[fieldIndex] = terrain.surfaceY(worldX, worldZ); + blendScratch.fieldHasFluid[fieldIndex] = dressing.fluidPresentAt(worldX, worldZ); } } } @@ -510,7 +441,7 @@ public class CaveCarving { return carver; } - IrisCaveCarver3D createdCarver = new IrisCaveCarver3D(engine, profile); + IrisCaveCarver3D createdCarver = new IrisCaveCarver3D(world, profile); synchronized (profileCarverLock) { IrisCaveCarver3D published = profileCarvers.get(profile); if (published != null) { @@ -528,39 +459,25 @@ public class CaveCarving { return profile != null && profile.enabled(); } - private int[] prepareChunkSurfaceHeights(int chunkX, int chunkZ, ChunkContext context, int[] scratch) { - int[] surfaceHeights = scratch; + private int[] prepareChunkSurfaceHeights(int chunkX, int chunkZ, TerrainSampler terrain, int[] scratch) { int baseX = PowerOfTwoCoordinates.chunkToBlock(chunkX); int baseZ = PowerOfTwoCoordinates.chunkToBlock(chunkZ); - boolean useContextHeight = context != null - && context.getHeight() != null - && context.getX() == baseX - && context.getZ() == baseZ; - double[] cachedChunkHeights = null; - if (!useContextHeight && context != null) { - ProceduralStream heightStream = context.getComplex().getHeightStream(); - if (heightStream instanceof ChunkFillableDoubleStream2D cachedHeightStream) { - cachedChunkHeights = BLEND_SCRATCH.get().chunkSurfaceHeightSamples; - cachedHeightStream.fillChunkDoubles(baseX, baseZ, cachedChunkHeights); - } - } for (int localX = 0; localX < CHUNK_SIZE; localX++) { int worldX = baseX + localX; for (int localZ = 0; localZ < CHUNK_SIZE; localZ++) { - int worldZ = baseZ + localZ; int columnIndex = PowerOfTwoCoordinates.packLocal16(localX, localZ); - if (useContextHeight) { - surfaceHeights[columnIndex] = context.getRoundedHeight(localX, localZ); - continue; - } - if (cachedChunkHeights != null) { - surfaceHeights[columnIndex] = (int) Math.round(cachedChunkHeights[(localZ << 4) + localX]); - continue; - } - surfaceHeights[columnIndex] = engine.getHeight(worldX, worldZ); + scratch[columnIndex] = (int) Math.round(terrain.surfaceY(worldX, baseZ + localZ)); } } - return surfaceHeights; + return scratch; + } + + private static double maxOf(double[] values) { + double max = Double.NEGATIVE_INFINITY; + for (double value : values) { + max = Math.max(max, value); + } + return max; } private static List limitAndMergeBlendedProfiles(List blendedProfiles, int maxProfiles) { @@ -664,10 +581,10 @@ public class CaveCarving { private final CaveProfile profile; private final double[] columnWeights; private final double averageWeight; - private final IrisRange worldYRange; + private final Range worldYRange; private final int sequence; - private WeightedProfile(CaveProfile profile, double[] columnWeights, double averageWeight, IrisRange worldYRange, int sequence) { + private WeightedProfile(CaveProfile profile, double[] columnWeights, double averageWeight, Range worldYRange, int sequence) { this.profile = profile; this.columnWeights = columnWeights; this.averageWeight = averageWeight; @@ -690,11 +607,7 @@ public class CaveCarving { private final List profileOrder = new ArrayList<>(); private final double[] fieldSurfaceHeights = new double[FIELD_SIZE * FIELD_SIZE]; private final boolean[] fieldHasFluid = new boolean[FIELD_SIZE * FIELD_SIZE]; - private final IrisRegion[] fieldRegions = new IrisRegion[FIELD_SIZE * FIELD_SIZE]; - private final IrisBiome[] fieldSurfaceBiomes = new IrisBiome[FIELD_SIZE * FIELD_SIZE]; - private final IrisBiome[] fieldCaveBiomes = new IrisBiome[FIELD_SIZE * FIELD_SIZE]; private final int[] chunkSurfaceHeights = new int[CHUNK_AREA]; private final int[] surfaceFluidBoundaryStartY = new int[CHUNK_AREA]; - private final double[] chunkSurfaceHeightSamples = new double[CHUNK_AREA]; } } diff --git a/src/main/java/art/arcane/iris/engine/mantle/components/CaveFieldModuleState.java b/src/main/java/art/arcane/iris/engine/mantle/components/CaveFieldModuleState.java index f07e069ce..392ac27ce 100644 --- a/src/main/java/art/arcane/iris/engine/mantle/components/CaveFieldModuleState.java +++ b/src/main/java/art/arcane/iris/engine/mantle/components/CaveFieldModuleState.java @@ -18,12 +18,12 @@ package art.arcane.iris.engine.mantle.components; -import art.arcane.iris.engine.object.terrain.carving.ResolvedCaveProfile; -import art.arcane.iris.engine.object.value.IrisRange; -import art.arcane.iris.util.project.noise.CNG; +import art.arcane.iris.builtin.carve.CaveFieldModule; +import com.volmit.config.Range; +import com.volmit.noise.NoiseSampler; final class CaveFieldModuleState { - final CNG density; + final NoiseSampler density; final int minY; final int maxY; final double weight; @@ -32,11 +32,11 @@ final class CaveFieldModuleState { final double minContribution; final double maxContribution; - CaveFieldModuleState(ResolvedCaveProfile.Module module, CNG density) { - IrisRange range = module.verticalRange(); + CaveFieldModuleState(CaveFieldModule module, NoiseSampler density) { + Range range = module.verticalRange(); this.density = density; - this.minY = (int) Math.floor(range.getMin()); - this.maxY = (int) Math.ceil(range.getMax()); + this.minY = (int) Math.floor(range.min()); + this.maxY = (int) Math.ceil(range.max()); this.weight = module.weight(); this.threshold = module.threshold(); this.invert = module.invert(); @@ -47,12 +47,12 @@ final class CaveFieldModuleState { } double sample(double x, int y, double z) { - double sampled = density.noiseFastSigned3D(x, y, z); + double sampled = density.signed(x, y, z); return invert ? (threshold - sampled) * weight : (sampled - threshold) * weight; } double sample(double x, double y, double z) { - double sampled = density.noiseFastSigned3D(x, y, z); + double sampled = density.signed(x, y, z); return invert ? (threshold - sampled) * weight : (sampled - threshold) * weight; } } diff --git a/src/main/java/art/arcane/iris/engine/mantle/components/IrisCaveCarver3D.java b/src/main/java/art/arcane/iris/engine/mantle/components/IrisCaveCarver3D.java index 3f219f4be..91b0e9cfd 100644 --- a/src/main/java/art/arcane/iris/engine/mantle/components/IrisCaveCarver3D.java +++ b/src/main/java/art/arcane/iris/engine/mantle/components/IrisCaveCarver3D.java @@ -18,22 +18,19 @@ 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.terrain.carving.ResolvedCaveProfile; -import art.arcane.iris.core.loader.IrisData; -import art.arcane.iris.engine.framework.Engine; -import art.arcane.iris.engine.mantle.MantleWriter; -import art.arcane.iris.engine.object.value.IrisRange; -import art.arcane.iris.engine.object.noise.IrisStyledRange; -import art.arcane.iris.util.project.noise.CNG; import art.arcane.volmlib.util.mantle.runtime.MantleChunk; import art.arcane.volmlib.util.math.M; import art.arcane.volmlib.util.math.PowerOfTwoCoordinates; -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 art.arcane.volmlib.util.scheduling.PrecisionStopwatch; +import com.volmit.config.Range; +import com.volmit.noise.NoiseSampler; +import com.volmit.noise.NoiseStyle; +import com.volmit.noise.StyledRange; import java.util.ArrayList; import java.util.Arrays; @@ -51,15 +48,13 @@ public class IrisCaveCarver3D { private static final int SURFACE_CEILING_FADE_DEPTH = 12; private static final double SURFACE_CEILING_SOLID_EPSILON = 0.000001D; - private final Engine engine; - private final IrisData data; private final CaveProfile profile; - private final ResolvedCaveProfile resolved; - private final CNG baseDensity; - private final CNG detailDensity; - private final CNG warpDensity; - private final CNG surfaceBreakDensity; - private final RNG thresholdRng; + private final NoiseSampler baseDensity; + private final NoiseSampler detailDensity; + private final NoiseSampler warpDensity; + private final NoiseSampler surfaceBreakDensity; + private final NoiseSampler thresholdNoise; + private final int lavaHeight; private final CaveFieldModuleState[] modules; private final double inverseNormalization; private final MatterCavern carveAir; @@ -80,25 +75,24 @@ public class IrisCaveCarver3D { private final int fluidMinDepthBelowSurface; private final int fluidHeight; private final int aquiferCeilingY; + private final int minHeight; + private final int worldHeight; private final ThreadLocal scratchCache = ThreadLocal.withInitial(CaveCarveScratch::new); - public IrisCaveCarver3D(Engine engine, CaveProfile profile) { - this.engine = engine; - this.data = engine.getData(); + public IrisCaveCarver3D(CarveWorld world, CaveProfile profile) { this.profile = profile; - this.resolved = ResolvedCaveProfile.of(profile); this.carveAir = new MatterCavern(true, "", LIQUID_AIR); this.carveFluid = new MatterCavern(true, "", LIQUID_FLUID); this.carveLava = new MatterCavern(true, "", LIQUID_LAVA); this.carveForcedAir = new MatterCavern(true, "", LIQUID_FORCED_AIR); List moduleStates = new ArrayList<>(); - RNG baseRng = new RNG(engine.getSeedManager().getCarve()); - this.baseDensity = resolved.baseDensityStyle().create(baseRng.nextParallelRNG(934_447), data); - this.detailDensity = resolved.detailDensityStyle().create(baseRng.nextParallelRNG(612_991), data); - this.warpDensity = resolved.warpStyle().create(baseRng.nextParallelRNG(770_713), data); - this.surfaceBreakDensity = resolved.surfaceBreakStyle().create(baseRng.nextParallelRNG(341_219), data); - this.thresholdRng = baseRng.nextParallelRNG(489_112); + long carveSeed = world.carveSeed(); + this.baseDensity = world.noise().sampler(profile.baseDensityStyle(), carveSeed + 934_447); + this.detailDensity = world.noise().sampler(profile.detailDensityStyle(), carveSeed + 612_991); + this.warpDensity = world.noise().sampler(profile.warpStyle(), carveSeed + 770_713); + this.surfaceBreakDensity = world.noise().sampler(profile.surfaceBreakStyle(), carveSeed + 341_219); + this.thresholdNoise = world.noise().sampler(profile.densityThreshold().style(), carveSeed + 489_112); this.baseWeight = profile.baseWeight(); this.detailWeight = profile.detailWeight(); this.warpStrength = profile.warpStrength(); @@ -107,13 +101,16 @@ public class IrisCaveCarver3D { this.allowFluid = profile.allowFluid(); this.fluidRequiresFloor = profile.fluidRequiresFloor(); this.fluidMinDepthBelowSurface = Math.max(0, profile.fluidMinDepthBelowSurface()); - this.fluidHeight = engine.getDimension().getFluidHeight(); - this.aquiferCeilingY = engine.getHeight() - 1; + this.fluidHeight = world.fluidHeight(); + this.worldHeight = world.height(); + this.aquiferCeilingY = world.height() - 1; + this.lavaHeight = world.lavaHeight(); + this.minHeight = world.minHeight(); double weight = Math.abs(baseWeight) + Math.abs(detailWeight); int index = 0; - for (ResolvedCaveProfile.Module module : resolved.modules()) { - CNG moduleDensity = module.style().create(baseRng.nextParallelRNG(1_000_003L + (index * 65_537L)), data); + for (CaveFieldModule module : profile.modules()) { + NoiseSampler moduleDensity = world.noise().sampler(module.style(), carveSeed + 1_000_003L + (index * 65_537L)); CaveFieldModuleState state = new CaveFieldModuleState(module, moduleDensity); moduleStates.add(state); weight += Math.abs(state.weight); @@ -129,249 +126,183 @@ public class IrisCaveCarver3D { detailMaxContribution = detailWeight; } - public int carve(MantleWriter writer, int chunkX, int chunkZ) { - CaveCarveScratch scratch = scratchCache.get(); - if (!scratch.fullWeightsInitialized) { - Arrays.fill(scratch.fullWeights, 1D); - scratch.fullWeightsInitialized = true; - } - return carve(writer, chunkX, chunkZ, scratch.fullWeights, 0D, 0D, null, null); - } - public int carve( - MantleWriter writer, - int chunkX, - int chunkZ, - double[] columnWeights, - double minWeight, - double thresholdPenalty - ) { - return carve(writer, chunkX, chunkZ, columnWeights, minWeight, thresholdPenalty, null, null); - } - - public int carve( - MantleWriter writer, + MatterMantle mantle, int chunkX, int chunkZ, double[] columnWeights, double minWeight, double thresholdPenalty, - IrisRange worldYRange + Range worldYRange, + int[] surfaceHeights ) { - return carve(writer, chunkX, chunkZ, columnWeights, minWeight, thresholdPenalty, worldYRange, null); + return carve(mantle, chunkX, chunkZ, columnWeights, minWeight, thresholdPenalty, worldYRange, surfaceHeights, null); } public int carve( - MantleWriter writer, + MatterMantle mantle, int chunkX, int chunkZ, double[] columnWeights, double minWeight, double thresholdPenalty, - IrisRange worldYRange, - int[] precomputedSurfaceHeights - ) { - return carve(writer, chunkX, chunkZ, columnWeights, minWeight, thresholdPenalty, worldYRange, precomputedSurfaceHeights, null); - } - - public int carve( - MantleWriter writer, - int chunkX, - int chunkZ, - double[] columnWeights, - double minWeight, - double thresholdPenalty, - IrisRange worldYRange, - int[] precomputedSurfaceHeights, - IrisRange overrideVerticalRange + Range worldYRange, + int[] surfaceHeights, + Range overrideVerticalRange ) { CaveFluidSupportPlan fluidSupportPlan = new CaveFluidSupportPlan(); - int carved = carve(writer, chunkX, chunkZ, columnWeights, minWeight, thresholdPenalty, - worldYRange, precomputedSurfaceHeights, null, overrideVerticalRange, fluidSupportPlan); - fluidSupportPlan.resolve(writer.acquireChunk(chunkX, chunkZ)); + int carved = carve(mantle, chunkX, chunkZ, columnWeights, minWeight, thresholdPenalty, + worldYRange, surfaceHeights, null, overrideVerticalRange, fluidSupportPlan); + fluidSupportPlan.resolve(mantle.chunk(chunkX, chunkZ)); return carved; } + /** {@code surfaceHeights} are the rounded heights of the chunk's columns, packed as {@link PowerOfTwoCoordinates#packLocal16}. */ int carve( - MantleWriter writer, + MatterMantle mantle, int chunkX, int chunkZ, double[] columnWeights, double minWeight, double thresholdPenalty, - IrisRange worldYRange, - int[] precomputedSurfaceHeights, + Range worldYRange, + int[] surfaceHeights, int[] surfaceFluidBoundaryStartY, - IrisRange overrideVerticalRange, + Range overrideVerticalRange, CaveFluidSupportPlan fluidSupportPlan ) { - PrecisionStopwatch applyStopwatch = PrecisionStopwatch.start(); - try { - CaveCarveScratch scratch = scratchCache.get(); - if (columnWeights == null || columnWeights.length < 256) { - if (!scratch.fullWeightsInitialized) { - Arrays.fill(scratch.fullWeights, 1D); - scratch.fullWeightsInitialized = true; - } - columnWeights = scratch.fullWeights; + CaveCarveScratch scratch = scratchCache.get(); + if (columnWeights == null || columnWeights.length < 256) { + if (!scratch.fullWeightsInitialized) { + Arrays.fill(scratch.fullWeights, 1D); + scratch.fullWeightsInitialized = true; } + columnWeights = scratch.fullWeights; + } - double resolvedMinWeight = Math.max(0D, Math.min(1D, minWeight)); - double resolvedThresholdPenalty = Math.max(0D, thresholdPenalty); - int worldHeight = writer.getMantle().getWorldHeight(); - IrisRange effectiveVerticalRange = overrideVerticalRange != null ? overrideVerticalRange : resolved.verticalRange(); - int minY = Math.max(0, (int) Math.floor(effectiveVerticalRange.getMin())); - int maxY = Math.min(worldHeight - 1, (int) Math.ceil(effectiveVerticalRange.getMax())); - if (worldYRange != null) { - int worldMinHeight = engine.getWorld().minHeight(); - int rangeMinY = (int) Math.floor(worldYRange.getMin() - worldMinHeight); - int rangeMaxY = (int) Math.ceil(worldYRange.getMax() - worldMinHeight); - minY = Math.max(minY, rangeMinY); - maxY = Math.min(maxY, rangeMaxY); - } - int sampleStep = Math.max(1, profile.sampleStep()); - boolean exactSampling = sampleStep <= 2; - boolean adaptiveSampling = exactSampling && profile.adaptiveSampling(); - int adaptiveSampleStep = Math.max(2, profile.adaptiveSampleStep()); - double adaptiveThresholdMargin = Math.max(0D, profile.adaptiveThresholdMargin()); - int surfaceClearance = Math.max(0, profile.surfaceClearance()); - int surfaceBreakDepth = Math.max(0, profile.surfaceBreakDepth()); - double surfaceBreakNoiseThreshold = profile.surfaceBreakNoiseThreshold(); - double surfaceBreakThresholdBoost = Math.max(0, profile.surfaceBreakThresholdBoost()); - boolean allowSurfaceBreak = profile.allowSurfaceBreak(); - if (maxY < minY) { - return 0; + double resolvedMinWeight = Math.max(0D, Math.min(1D, minWeight)); + double resolvedThresholdPenalty = Math.max(0D, thresholdPenalty); + Range effectiveVerticalRange = overrideVerticalRange != null ? overrideVerticalRange : profile.verticalRange(); + int minY = Math.max(0, (int) Math.floor(effectiveVerticalRange.min())); + int maxY = Math.min(worldHeight - 1, (int) Math.ceil(effectiveVerticalRange.max())); + if (worldYRange != null) { + int rangeMinY = (int) Math.floor(worldYRange.min() - minHeight); + int rangeMaxY = (int) Math.ceil(worldYRange.max() - minHeight); + minY = Math.max(minY, rangeMinY); + maxY = Math.min(maxY, rangeMaxY); + } + int sampleStep = Math.max(1, profile.sampleStep()); + boolean exactSampling = sampleStep <= 2; + boolean adaptiveSampling = exactSampling && profile.adaptiveSampling(); + int adaptiveSampleStep = Math.max(2, profile.adaptiveSampleStep()); + double adaptiveThresholdMargin = Math.max(0D, profile.adaptiveThresholdMargin()); + int surfaceClearance = Math.max(0, profile.surfaceClearance()); + int surfaceBreakDepth = Math.max(0, profile.surfaceBreakDepth()); + double surfaceBreakNoiseThreshold = profile.surfaceBreakNoiseThreshold(); + double surfaceBreakThresholdBoost = Math.max(0, profile.surfaceBreakThresholdBoost()); + boolean allowSurfaceBreak = profile.allowSurfaceBreak(); + if (maxY < minY) { + return 0; + } + + MantleChunk chunk = mantle.chunk(chunkX, chunkZ); + if (chunk == null) { + return 0; + } + + int x0 = PowerOfTwoCoordinates.chunkToBlock(chunkX); + int z0 = PowerOfTwoCoordinates.chunkToBlock(chunkZ); + int[] columnMaxY = scratch.columnMaxY; + int[] fluidMaxY = scratch.fluidMaxY; + int[] surfaceBreakFloorY = scratch.surfaceBreakFloorY; + boolean[] surfaceBreakColumn = scratch.surfaceBreakColumn; + boolean[] surfaceCeilingColumn = scratch.surfaceCeilingColumn; + double[] columnThreshold = scratch.columnThreshold; + double[] clampedWeights = scratch.clampedColumnWeights; + double[] verticalEdgeFade = prepareVerticalEdgeFadeTable(scratch, minY, maxY); + prepareSurfaceClosureThresholdTable(scratch, minY, maxY); + MatterCavern[] matterByY = prepareMatterByYTable(scratch, minY, maxY); + prepareSectionCaches(scratch, minY, maxY); + + // The threshold noise is constant for the carver, so it is built once (in the constructor) and the + // min==max / flat-style short circuits are decided here, as Iris's styled range has always decided them. + StyledRange densityThreshold = profile.densityThreshold(); + double thresholdMin = densityThreshold.min(); + double thresholdMax = densityThreshold.max(); + double thresholdBias = profile.thresholdBias(); + NoiseSampler thresholdDensity = null; + double constantThreshold = 0D; + if (thresholdMin == thresholdMax) { + constantThreshold = thresholdMin; + } else if (NoiseStyle.FLAT.equals(densityThreshold.style().style())) { + constantThreshold = M.lerp(thresholdMin, thresholdMax, 0.5); + } else { + thresholdDensity = thresholdNoise; + } + + for (int lx = 0; lx < 16; lx++) { + int x = x0 + lx; + for (int lz = 0; lz < 16; lz++) { + int z = z0 + lz; + int index = PowerOfTwoCoordinates.packLocal16(lx, lz); + int columnSurfaceY; + columnSurfaceY = surfaceHeights[index]; + int unclampedClearanceTopY = columnSurfaceY - surfaceClearance; + int clearanceTopY = Math.min(maxY, Math.max(minY, unclampedClearanceTopY)); + boolean breakColumn = allowSurfaceBreak + && surfaceBreakDensity.signed(x, z) >= surfaceBreakNoiseThreshold; + int columnTopY = breakColumn + ? Math.min(maxY, Math.max(minY, columnSurfaceY)) + : clearanceTopY; + + columnMaxY[index] = columnTopY; + fluidMaxY[index] = allowFluid + ? Math.min(fluidHeight, columnSurfaceY - fluidMinDepthBelowSurface) + : Integer.MIN_VALUE; + surfaceBreakFloorY[index] = Math.max(minY, columnSurfaceY - surfaceBreakDepth); + surfaceBreakColumn[index] = breakColumn; + surfaceCeilingColumn[index] = !breakColumn && unclampedClearanceTopY <= maxY; + columnThreshold[index] = (thresholdDensity == null + ? constantThreshold + : thresholdMin + (thresholdDensity.sample(x, z) * (thresholdMax - thresholdMin))) - thresholdBias; + clampedWeights[index] = clampColumnWeight(columnWeights[index]); } + } - MantleChunk chunk = writer.acquireChunk(chunkX, chunkZ); - if (chunk == null) { - return 0; - } - - int x0 = PowerOfTwoCoordinates.chunkToBlock(chunkX); - int z0 = PowerOfTwoCoordinates.chunkToBlock(chunkZ); - int[] columnMaxY = scratch.columnMaxY; - int[] fluidMaxY = scratch.fluidMaxY; - int[] surfaceBreakFloorY = scratch.surfaceBreakFloorY; - boolean[] surfaceBreakColumn = scratch.surfaceBreakColumn; - boolean[] surfaceCeilingColumn = scratch.surfaceCeilingColumn; - double[] columnThreshold = scratch.columnThreshold; - double[] clampedWeights = scratch.clampedColumnWeights; - double[] verticalEdgeFade = prepareVerticalEdgeFadeTable(scratch, minY, maxY); - prepareSurfaceClosureThresholdTable(scratch, minY, maxY); - MatterCavern[] matterByY = prepareMatterByYTable(scratch, minY, maxY); - prepareSectionCaches(scratch, minY, maxY); - - // IrisStyledRange.get() resolves its CNG per call, which costs a cache-key allocation, - // a capturing lambda and a shared LRU touch. The CNG is constant for (thresholdRng, data), - // so resolve it once here and replicate the min==max / isFlat short circuits verbatim. - IrisStyledRange densityThreshold = resolved.densityThreshold(); - double thresholdMin = densityThreshold.getMin(); - double thresholdMax = densityThreshold.getMax(); - double thresholdBias = profile.thresholdBias(); - CNG thresholdDensity = null; - double constantThreshold = 0D; - if (thresholdMin == thresholdMax) { - constantThreshold = thresholdMin; - } else if (densityThreshold.getStyle().isFlat()) { - constantThreshold = M.lerp(thresholdMin, thresholdMax, 0.5); + int carved; + if (exactSampling) { + if (adaptiveSampling) { + carved = carvePassAdaptive( + chunk, + x0, + z0, + minY, + maxY, + adaptiveSampleStep, + adaptiveThresholdMargin, + surfaceBreakThresholdBoost, + columnMaxY, + fluidMaxY, + surfaceFluidBoundaryStartY, + surfaceBreakFloorY, + surfaceBreakColumn, + columnThreshold, + clampedWeights, + verticalEdgeFade, + matterByY, + fluidRequiresFloor ? fluidSupportPlan : null, + resolvedMinWeight, + resolvedThresholdPenalty, + 0D, + false + ); } else { - thresholdDensity = densityThreshold.getStyle().create(thresholdRng, data); - } - - for (int lx = 0; lx < 16; lx++) { - int x = x0 + lx; - for (int lz = 0; lz < 16; lz++) { - int z = z0 + lz; - int index = PowerOfTwoCoordinates.packLocal16(lx, lz); - int columnSurfaceY; - if (precomputedSurfaceHeights != null && precomputedSurfaceHeights.length > index) { - columnSurfaceY = precomputedSurfaceHeights[index]; - } else { - columnSurfaceY = engine.getHeight(x, z); - } - int unclampedClearanceTopY = columnSurfaceY - surfaceClearance; - int clearanceTopY = Math.min(maxY, Math.max(minY, unclampedClearanceTopY)); - boolean breakColumn = allowSurfaceBreak - && surfaceBreakDensity.noiseFastSigned2D(x, z) >= surfaceBreakNoiseThreshold; - int columnTopY = breakColumn - ? Math.min(maxY, Math.max(minY, columnSurfaceY)) - : clearanceTopY; - - columnMaxY[index] = columnTopY; - fluidMaxY[index] = allowFluid - ? Math.min(fluidHeight, columnSurfaceY - fluidMinDepthBelowSurface) - : Integer.MIN_VALUE; - surfaceBreakFloorY[index] = Math.max(minY, columnSurfaceY - surfaceBreakDepth); - surfaceBreakColumn[index] = breakColumn; - surfaceCeilingColumn[index] = !breakColumn && unclampedClearanceTopY <= maxY; - columnThreshold[index] = (thresholdDensity == null - ? constantThreshold - : thresholdDensity.fitDouble(thresholdMin, thresholdMax, x, z)) - thresholdBias; - clampedWeights[index] = clampColumnWeight(columnWeights[index]); - } - } - - int carved; - if (exactSampling) { - if (adaptiveSampling) { - carved = carvePassAdaptive( - chunk, - x0, - z0, - minY, - maxY, - adaptiveSampleStep, - adaptiveThresholdMargin, - surfaceBreakThresholdBoost, - columnMaxY, - fluidMaxY, - surfaceFluidBoundaryStartY, - surfaceBreakFloorY, - surfaceBreakColumn, - columnThreshold, - clampedWeights, - verticalEdgeFade, - matterByY, - fluidRequiresFloor ? fluidSupportPlan : null, - resolvedMinWeight, - resolvedThresholdPenalty, - 0D, - false - ); - } else { - carved = carvePassExact( - chunk, - x0, - z0, - minY, - maxY, - surfaceBreakThresholdBoost, - columnMaxY, - fluidMaxY, - surfaceFluidBoundaryStartY, - surfaceBreakFloorY, - surfaceBreakColumn, - columnThreshold, - clampedWeights, - verticalEdgeFade, - matterByY, - fluidRequiresFloor ? fluidSupportPlan : null, - resolvedMinWeight, - resolvedThresholdPenalty, - 0D, - false - ); - } - } else { - int latticeStep = sampleStep; - carved = carvePassLattice( + carved = carvePassExact( chunk, x0, z0, minY, maxY, - latticeStep, surfaceBreakThresholdBoost, columnMaxY, fluidMaxY, @@ -388,37 +319,60 @@ public class IrisCaveCarver3D { 0D, false ); - if (carved == 0 && hasFallbackCandidates(columnMaxY, clampedWeights, minY, resolvedMinWeight)) { - carved += carvePassFallback( - chunk, - x0, - z0, - minY, - maxY, - sampleStep, - surfaceBreakThresholdBoost, - columnMaxY, - fluidMaxY, - surfaceFluidBoundaryStartY, - surfaceBreakFloorY, - surfaceBreakColumn, - columnThreshold, - clampedWeights, - verticalEdgeFade, - matterByY, - fluidRequiresFloor ? fluidSupportPlan : null, - resolvedMinWeight, - resolvedThresholdPenalty, - 0D, - false - ); - } } - - return carved; - } finally { - engine.getMetrics().getCarveApply().put(applyStopwatch.getMilliseconds()); + } else { + int latticeStep = sampleStep; + carved = carvePassLattice( + chunk, + x0, + z0, + minY, + maxY, + latticeStep, + surfaceBreakThresholdBoost, + columnMaxY, + fluidMaxY, + surfaceFluidBoundaryStartY, + surfaceBreakFloorY, + surfaceBreakColumn, + columnThreshold, + clampedWeights, + verticalEdgeFade, + matterByY, + fluidRequiresFloor ? fluidSupportPlan : null, + resolvedMinWeight, + resolvedThresholdPenalty, + 0D, + false + ); + if (carved == 0 && hasFallbackCandidates(columnMaxY, clampedWeights, minY, resolvedMinWeight)) { + carved += carvePassFallback( + chunk, + x0, + z0, + minY, + maxY, + sampleStep, + surfaceBreakThresholdBoost, + columnMaxY, + fluidMaxY, + surfaceFluidBoundaryStartY, + surfaceBreakFloorY, + surfaceBreakColumn, + columnThreshold, + clampedWeights, + verticalEdgeFade, + matterByY, + fluidRequiresFloor ? fluidSupportPlan : null, + resolvedMinWeight, + resolvedThresholdPenalty, + 0D, + false + ); + } } + + return carved; } private int carvePassExact( @@ -1670,7 +1624,7 @@ public class IrisCaveCarver3D { } private boolean classifyDensityPointNoWarpNoModules(int x, int y, int z, double thresholdLimit) { - double density = baseDensity.noiseFastSigned3D(x, y, z) * baseWeight; + double density = baseDensity.signed(x, y, z) * baseWeight; if ((density + detailMinContribution) > thresholdLimit) { return false; } @@ -1678,7 +1632,7 @@ public class IrisCaveCarver3D { return true; } - density += detailDensity.noiseFastSigned3D(x, y, z) * detailWeight; + density += detailDensity.signed(x, y, z) * detailWeight; return density <= thresholdLimit; } @@ -1696,7 +1650,7 @@ public class IrisCaveCarver3D { return classifyDensityPointNoWarpNoModules(x, y, z, thresholdLimit); } - double density = baseDensity.noiseFastSigned3D(x, y, z) * baseWeight; + double density = baseDensity.signed(x, y, z) * baseWeight; if ((density + detailMinContribution + remainingMin[0]) > thresholdLimit) { return false; } @@ -1704,7 +1658,7 @@ public class IrisCaveCarver3D { return true; } - density += detailDensity.noiseFastSigned3D(x, y, z) * detailWeight; + density += detailDensity.signed(x, y, z) * detailWeight; if ((density + remainingMin[0]) > thresholdLimit) { return false; } @@ -1746,7 +1700,7 @@ public class IrisCaveCarver3D { double warpedX = x + (warpA * warpStrength); double warpedY = y + (warpB * warpStrength); double warpedZ = z + ((warpA - warpB) * 0.5D * warpStrength); - double density = baseDensity.noiseFastSigned3D(warpedX, warpedY, warpedZ) * baseWeight; + double density = baseDensity.signed(warpedX, warpedY, warpedZ) * baseWeight; if ((density + detailMinContribution) > thresholdLimit) { return false; } @@ -1754,7 +1708,7 @@ public class IrisCaveCarver3D { return true; } - density += detailDensity.noiseFastSigned3D(warpedX, warpedY, warpedZ) * detailWeight; + density += detailDensity.signed(warpedX, warpedY, warpedZ) * detailWeight; return density <= thresholdLimit; } @@ -1782,7 +1736,7 @@ public class IrisCaveCarver3D { double warpedX = x + (warpA * warpStrength); double warpedY = y + (warpB * warpStrength); double warpedZ = z + ((warpA - warpB) * 0.5D * warpStrength); - double density = baseDensity.noiseFastSigned3D(warpedX, warpedY, warpedZ) * baseWeight; + double density = baseDensity.signed(warpedX, warpedY, warpedZ) * baseWeight; if ((density + detailMinContribution + remainingMin[0]) > thresholdLimit) { return false; } @@ -1790,7 +1744,7 @@ public class IrisCaveCarver3D { return true; } - density += detailDensity.noiseFastSigned3D(warpedX, warpedY, warpedZ) * detailWeight; + density += detailDensity.signed(warpedX, warpedY, warpedZ) * detailWeight; if ((density + remainingMin[0]) > thresholdLimit) { return false; } @@ -2008,8 +1962,8 @@ public class IrisCaveCarver3D { } private double sampleDensityNoWarpNoModules(int x, int y, int z) { - double density = baseDensity.noiseFastSigned3D(x, y, z) * baseWeight; - density += detailDensity.noiseFastSigned3D(x, y, z) * detailWeight; + double density = baseDensity.signed(x, y, z) * baseWeight; + density += detailDensity.signed(x, y, z) * detailWeight; return density * inverseNormalization; } @@ -2020,11 +1974,11 @@ public class IrisCaveCarver3D { } CaveFieldModuleState[] localModules = scratch.activeModules; - double density = baseDensity.noiseFastSigned3D(x, y, z) * baseWeight; - density += detailDensity.noiseFastSigned3D(x, y, z) * detailWeight; + double density = baseDensity.signed(x, y, z) * baseWeight; + density += detailDensity.signed(x, y, z) * detailWeight; for (int moduleIndex = 0; moduleIndex < activeModuleCount; moduleIndex++) { CaveFieldModuleState module = localModules[moduleIndex]; - double moduleDensity = module.density.noiseFastSigned3D(x, y, z) - module.threshold; + double moduleDensity = module.density.signed(x, y, z) - module.threshold; if (module.invert) { moduleDensity = -moduleDensity; } @@ -2045,8 +1999,8 @@ public class IrisCaveCarver3D { double warpedX = x + (warpA * warpStrength); double warpedY = y + (warpB * warpStrength); double warpedZ = z + ((warpA - warpB) * 0.5D * warpStrength); - double density = baseDensity.noiseFastSigned3D(warpedX, warpedY, warpedZ) * baseWeight; - density += detailDensity.noiseFastSigned3D(warpedX, warpedY, warpedZ) * detailWeight; + double density = baseDensity.signed(warpedX, warpedY, warpedZ) * baseWeight; + density += detailDensity.signed(warpedX, warpedY, warpedZ) * detailWeight; return density * inverseNormalization; } @@ -2070,11 +2024,11 @@ public class IrisCaveCarver3D { double warpedX = x + (warpA * warpStrength); double warpedY = y + (warpB * warpStrength); double warpedZ = z + ((warpA - warpB) * 0.5D * warpStrength); - double density = baseDensity.noiseFastSigned3D(warpedX, warpedY, warpedZ) * baseWeight; - density += detailDensity.noiseFastSigned3D(warpedX, warpedY, warpedZ) * detailWeight; + double density = baseDensity.signed(warpedX, warpedY, warpedZ) * baseWeight; + density += detailDensity.signed(warpedX, warpedY, warpedZ) * detailWeight; for (int moduleIndex = 0; moduleIndex < activeModuleCount; moduleIndex++) { CaveFieldModuleState module = localModules[moduleIndex]; - double moduleDensity = module.density.noiseFastSigned3D(warpedX, warpedY, warpedZ) - module.threshold; + double moduleDensity = module.density.signed(warpedX, warpedY, warpedZ) - module.threshold; if (module.invert) { moduleDensity = -moduleDensity; } @@ -2098,8 +2052,8 @@ public class IrisCaveCarver3D { scratch.warpCacheX[slot] = sx; scratch.warpCacheY[slot] = sy; scratch.warpCacheZ[slot] = sz; - scratch.warpCacheA[slot] = warpDensity.noiseFastSigned3D(sx, sy, sz); - scratch.warpCacheB[slot] = warpDensity.noiseFastSigned3D(sx + 31.37D, sy - 17.21D, sz + 23.91D); + scratch.warpCacheA[slot] = warpDensity.signed(sx, sy, sz); + scratch.warpCacheB[slot] = warpDensity.signed(sx + 31.37D, sy - 17.21D, sz + 23.91D); return slot; } @@ -2183,7 +2137,6 @@ public class IrisCaveCarver3D { MatterCavern[] matterByY = scratch.matterByY; boolean allowLava = profile.allowLava(); - int lavaHeight = engine.getDimension().getCaveLavaHeight(); for (int y = minY; y <= maxY; y++) { int offset = y - minY; @@ -2215,7 +2168,7 @@ public class IrisCaveCarver3D { private boolean isAquiferCandidate(CaveCarveScratch scratch, int x, int y, int z, double localThreshold) { double depthFactor = Math.max(0D, Math.min(1.5D, (fluidHeight - y) / 48D)); double cutoff = 0.35D + (depthFactor * 0.2D); - if (detailDensity.noiseFastSigned3D(x, y * 0.5D, z) <= cutoff) { + if (detailDensity.signed(x, y * 0.5D, z) <= cutoff) { return false; } return !fluidRequiresFloor || hasAquiferCupSupport(scratch, x, y, z, localThreshold); diff --git a/src/main/java/art/arcane/iris/engine/mantle/components/ObjectPlacing.java b/src/main/java/art/arcane/iris/engine/mantle/components/ObjectPlacing.java index 87f2a3f23..a1696d4fb 100644 --- a/src/main/java/art/arcane/iris/engine/mantle/components/ObjectPlacing.java +++ b/src/main/java/art/arcane/iris/engine/mantle/components/ObjectPlacing.java @@ -19,6 +19,7 @@ package art.arcane.iris.engine.mantle.components; +import art.arcane.iris.builtin.carve.CaveLavaHeightSettings; import art.arcane.iris.builtin.anchor.PlaceTrait; import art.arcane.iris.builtin.carve.CarvingMode; import art.arcane.iris.builtin.carve.CaveAnchorMode; @@ -585,7 +586,7 @@ public class ObjectPlacing { underwater, writer.getDataIfPresent(candidateX, candidateY, candidateZ, MatterCavern.class), candidateY, - engine.getDimension().getCaveLavaHeight())) { + engine.getDimension().getModuleSettings().find(CaveLavaHeightSettings.class).map(CaveLavaHeightSettings::height).orElse(CaveLavaHeightSettings.DEFAULT_HEIGHT))) { continue; } return new CavePlacementAnchor(candidateX, candidateY, candidateZ); diff --git a/src/main/java/art/arcane/iris/engine/modifier/CarveColumnMask.java b/src/main/java/art/arcane/iris/engine/modifier/CarveColumnMask.java new file mode 100644 index 000000000..58a3af38a --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/modifier/CarveColumnMask.java @@ -0,0 +1,95 @@ +/* + * 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 java.util.Arrays; + +final class CarveColumnMask { + private long[] words = new long[8]; + private int maxWord = -1; + + void add(int y) { + if (y < 0) { + return; + } + + int wordIndex = y >> 6; + if (wordIndex >= words.length) { + words = Arrays.copyOf(words, Math.max(words.length << 1, wordIndex + 1)); + } + + words[wordIndex] |= 1L << (y & 63); + if (wordIndex > maxWord) { + maxWord = wordIndex; + } + } + + int nextSetBit(int fromBit) { + if (maxWord < 0) { + return -1; + } + + int startBit = Math.max(0, fromBit); + int wordIndex = startBit >> 6; + if (wordIndex > maxWord) { + return -1; + } + + long word = words[wordIndex] & (-1L << (startBit & 63)); + while (true) { + if (word != 0L) { + return (wordIndex << 6) + Long.numberOfTrailingZeros(word); + } + + wordIndex++; + if (wordIndex > maxWord) { + return -1; + } + word = words[wordIndex]; + } + } + + boolean isEmpty() { + return maxWord < 0; + } + + boolean contains(int y) { + if (y < 0) { + return false; + } + + int wordIndex = y >> 6; + if (wordIndex > maxWord) { + return false; + } + + return (words[wordIndex] & (1L << (y & 63))) != 0L; + } + + void clear() { + if (maxWord < 0) { + return; + } + + for (int index = 0; index <= maxWord; index++) { + words[index] = 0L; + } + maxWord = -1; + } +} diff --git a/src/main/java/art/arcane/iris/engine/modifier/CarveModule.java b/src/main/java/art/arcane/iris/engine/modifier/CarveModule.java index 41dd78bc4..0c484456d 100644 --- a/src/main/java/art/arcane/iris/engine/modifier/CarveModule.java +++ b/src/main/java/art/arcane/iris/engine/modifier/CarveModule.java @@ -18,36 +18,50 @@ package art.arcane.iris.engine.modifier; +import art.arcane.iris.builtin.IrisSeed; +import art.arcane.iris.builtin.IrisStages; +import art.arcane.iris.builtin.MatterMantle; import art.arcane.iris.builtin.carve.CarvingBiomeSettings; import art.arcane.iris.builtin.carve.CarvingEnabledSettings; 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 com.volmit.FeatureRegistry; -import art.arcane.iris.builtin.IrisStages; -import art.arcane.iris.core.modules.IrisChunk; -import art.arcane.iris.core.modules.IrisMantleChunk; +import art.arcane.iris.builtin.carve.UpperDimensionCarvingSettings; +import art.arcane.iris.engine.mantle.components.CarveWorld; import art.arcane.iris.engine.mantle.components.CaveCarving; -import art.arcane.iris.engine.object.world.dimension.IrisDimension; +import com.volmit.FeatureRegistry; +import com.volmit.IrisFeature; import com.volmit.IrisModule; import com.volmit.ModuleInfo; -import com.volmit.ModuleLog; +import com.volmit.config.FeatureSettings; +import com.volmit.config.FeatureSettings.Entry; +import com.volmit.FeatureAttachment.Target; +import com.volmit.hunk.Hunk; +import com.volmit.block.BlockState; import com.volmit.service.CaveBiomes; import com.volmit.stage.ChunkStageContext; import com.volmit.stage.MantleStageContext; import com.volmit.stage.StageGraph; +import com.volmit.world.PackWorld; +import com.volmit.world.TerrainSampler; + +import java.util.Optional; +import java.util.function.Function; /** * Module {@code iris:carve}: caves. A mantle stage plans them into the mantle, reaching one block into each * neighboring chunk where blended cave walls cross the border; a chunk stage later cuts them out of the chunk's * terrain. The mantle stage is a port of what was Iris's carving mantle component, its work done by - * {@link CaveCarving}, one per engine runtime. The chunk stage's work is done by {@link CaveApplying}. + * {@link CaveCarving}, one per world. The chunk stage's work is done by {@link CaveApplying}. */ public final class CarveModule implements IrisModule { private static final String VERSION = "built-in"; /** Blended cave walls reach one block past the chunk. */ private static final int CAVE_REACH_BLOCKS = 1; private static final int CHUNK_SHIFT = 4; + /** The centre column of a chunk, where per-chunk settings are read. */ + private static final int CHUNK_CENTRE_BLOCKS = 7; @Override public ModuleInfo info() { @@ -61,6 +75,8 @@ public final class CarveModule implements IrisModule { registry.registerSettings(CarvingEnabledSettings.class); registry.registerSettings(CarvingBiomeSettings.class); registry.registerSettings(CaveDepthSettings.class); + registry.registerSettings(CaveLavaHeightSettings.class); + registry.registerSettings(UpperDimensionCarvingSettings.class); registry.registerService(CaveBiomes.class, new CaveBiomeBands()); } @@ -71,28 +87,58 @@ public final class CarveModule implements IrisModule { } private static void planCaves(MantleStageContext context) { - IrisMantleChunk chunk = IrisMantleChunk.current(); - if (!carves(chunk.engine().getDimension())) { + if (!carves(context.settings(), context.originX(), context.originZ())) { return; } - chunk.state(CaveCarving.class, CaveCarving::new).carve(chunk.writer(), chunk.chunkX(), chunk.chunkZ(), chunk.context()); + MatterMantle mantle = MatterMantle.of(context.mantle()); + caveCarving(context.world(), context.terrain(), context.settings(), context.originX(), context.originZ()) + .carve(mantle, context.terrain(), context.originX() >> CHUNK_SHIFT, context.originZ() >> CHUNK_SHIFT); } private static void applyCaves(ChunkStageContext context) { - IrisChunk chunk = IrisChunk.current(); - if (chunk.bypassesMantleStages()) { - return; - } - ModuleLog log = context.log(); - chunk.state(CaveApplying.class, generating -> new CaveApplying(generating, log)).apply(chunk.originX() >> CHUNK_SHIFT, chunk.originZ() >> CHUNK_SHIFT, - chunk.blocks(), chunk.multicore(), chunk.context()); + MatterMantle mantle = MatterMantle.of(context.mantle()); + Hunk blocks = context.hunk(BlockState.class); + caveApplying(context.world(), context.terrain(), context.settings(), context.originX(), context.originZ()) + .apply(mantle, context.terrain(), context.originX() >> CHUNK_SHIFT, context.originZ() >> CHUNK_SHIFT, blocks); + } + + private static CaveCarving caveCarving(PackWorld world, TerrainSampler terrain, FeatureSettings settings, int originX, int originZ) { + return world.state(CaveCarving.class, generating -> new CaveCarving(generating, carveWorld(generating, terrain), + upperDimensionCarving(settings, originX, originZ))); + } + + private static CaveApplying caveApplying(PackWorld world, TerrainSampler terrain, FeatureSettings settings, int originX, int originZ) { + return world.state(CaveApplying.class, generating -> new CaveApplying(generating, carveWorld(generating, terrain), + upperDimensionCarving(settings, originX, originZ))); + } + + /** What the carvers need of the world, from the dimension's settings and the first terrain they see (constant for the world). */ + private static CarveWorld carveWorld(PackWorld world, TerrainSampler terrain) { + int lavaHeight = dimensionSetting(world, CaveLavaHeightSettings.class, CaveLavaHeightSettings::height, CaveLavaHeightSettings.DEFAULT_HEIGHT); + return new CarveWorld(world.resources().noise(), IrisSeed.CARVE.of(world), terrain.bounds().maxY(), terrain.fluidHeight(), lavaHeight, + world.minHeight()); + } + + private static boolean upperDimensionCarving(FeatureSettings settings, int originX, int originZ) { + return dimensionEntry(settings, UpperDimensionCarvingSettings.class, originX + CHUNK_CENTRE_BLOCKS, originZ + CHUNK_CENTRE_BLOCKS) + .map(UpperDimensionCarvingSettings::enabled).orElse(false); } /** * A dimension turns carving off with {@code carvingEnabled}. Listing {@code CARVED} in {@code disabledComponents} * also does: Iris then skips this stage's mantle pass like any disabled component. */ - private static boolean carves(IrisDimension dimension) { - return dimension.getModuleSettings().find(CarvingEnabledSettings.class).map(CarvingEnabledSettings::enabled).orElse(true); + private static boolean carves(FeatureSettings settings, int originX, int originZ) { + return dimensionEntry(settings, CarvingEnabledSettings.class, originX + CHUNK_CENTRE_BLOCKS, originZ + CHUNK_CENTRE_BLOCKS) + .map(CarvingEnabledSettings::enabled).orElse(true); + } + + private static Optional dimensionEntry(FeatureSettings settings, Class type, int x, int z) { + return settings.at(type, x, z).stream().filter(entry -> entry.level() == Target.DIMENSION).map(Entry::value).findFirst(); + } + + private static V dimensionSetting(PackWorld world, Class type, Function read, V fallback) { + return world.settings().declared(type).stream().filter(entry -> entry.level() == Target.DIMENSION).map(Entry::value).map(read) + .findFirst().orElse(fallback); } } diff --git a/src/main/java/art/arcane/iris/engine/modifier/CarveWallBuffer.java b/src/main/java/art/arcane/iris/engine/modifier/CarveWallBuffer.java new file mode 100644 index 000000000..8b036ebc7 --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/modifier/CarveWallBuffer.java @@ -0,0 +1,166 @@ +/* + * 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.volmlib.util.math.PowerOfTwoCoordinates; +import art.arcane.volmlib.util.matter.MatterCavern; + +import java.util.Arrays; + +final class CarveWallBuffer { + private static final int EMPTY_KEY = -1; + private static final double LOAD_FACTOR = 0.75D; + + private int[] keys; + private MatterCavern[] values; + private int mask; + private int resizeAt; + private int size; + + CarveWallBuffer(int expectedSize) { + int capacity = 1; + int minimumCapacity = Math.max(8, expectedSize); + while (capacity < minimumCapacity) { + capacity <<= 1; + } + + keys = new int[capacity]; + Arrays.fill(keys, EMPTY_KEY); + values = new MatterCavern[capacity]; + mask = capacity - 1; + resizeAt = Math.max(1, (int) (capacity * LOAD_FACTOR)); + } + + void put(int x, int y, int z, MatterCavern value) { + int key = pack(x, y, z); + int index = mix(key) & mask; + + while (true) { + int existingKey = keys[index]; + if (existingKey == EMPTY_KEY) { + keys[index] = key; + values[index] = value; + size++; + if (size >= resizeAt) { + resize(); + } + return; + } + + if (existingKey == key) { + values[index] = value; + return; + } + + index = (index + 1) & mask; + } + } + + MatterCavern get(int x, int y, int z) { + int key = pack(x, y, z); + int index = mix(key) & mask; + while (true) { + int existingKey = keys[index]; + if (existingKey == EMPTY_KEY) { + return null; + } + if (existingKey == key) { + return values[index]; + } + index = (index + 1) & mask; + } + } + + void forEach(Consumer consumer) { + for (int index = 0; index < keys.length; index++) { + int key = keys[index]; + if (key == EMPTY_KEY) { + continue; + } + + MatterCavern cavern = values[index]; + if (cavern != null) { + consumer.accept(unpackX(key), unpackY(key), unpackZ(key), cavern); + } + } + } + + void clear() { + Arrays.fill(keys, EMPTY_KEY); + Arrays.fill(values, null); + size = 0; + } + + private void resize() { + int[] oldKeys = keys; + MatterCavern[] oldValues = values; + int nextCapacity = oldKeys.length << 1; + keys = new int[nextCapacity]; + Arrays.fill(keys, EMPTY_KEY); + values = new MatterCavern[nextCapacity]; + mask = nextCapacity - 1; + resizeAt = Math.max(1, (int) (nextCapacity * LOAD_FACTOR)); + size = 0; + + for (int index = 0; index < oldKeys.length; index++) { + int key = oldKeys[index]; + MatterCavern value = oldValues[index]; + if (key != EMPTY_KEY && value != null) { + reinsert(key, value); + } + } + } + + private void reinsert(int key, MatterCavern value) { + int index = mix(key) & mask; + while (keys[index] != EMPTY_KEY) { + index = (index + 1) & mask; + } + + keys[index] = key; + values[index] = value; + size++; + } + + private int pack(int x, int y, int z) { + return (y << 8) | PowerOfTwoCoordinates.packLocal16(x & 15, z & 15); + } + + private int unpackX(int key) { + return PowerOfTwoCoordinates.unpackLocal16X(key & 255); + } + + private int unpackY(int key) { + return key >> 8; + } + + private int unpackZ(int key) { + return PowerOfTwoCoordinates.unpackLocal16Z(key); + } + + private int mix(int value) { + int mixed = value * 0x9E3779B9; + return mixed ^ (mixed >>> 16); + } + + @FunctionalInterface + interface Consumer { + void accept(int x, int y, int z, MatterCavern cavern); + } +} diff --git a/src/main/java/art/arcane/iris/engine/modifier/CaveApplying.java b/src/main/java/art/arcane/iris/engine/modifier/CaveApplying.java index 306822d7d..a939da5e5 100644 --- a/src/main/java/art/arcane/iris/engine/modifier/CaveApplying.java +++ b/src/main/java/art/arcane/iris/engine/modifier/CaveApplying.java @@ -1,6 +1,6 @@ /* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) + * 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 @@ -18,107 +18,178 @@ package art.arcane.iris.engine.modifier; -import art.arcane.iris.engine.UpperDimensionContext; +import art.arcane.iris.builtin.CaveDressing; +import art.arcane.iris.builtin.MatterMantle; import art.arcane.iris.builtin.decorant.DecorationPart; -import art.arcane.iris.engine.decorator.BiomeDecorators; -import art.arcane.iris.engine.terrain.BiomeLayers; -import art.arcane.iris.engine.terrain.TerrainPalettes; -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.util.project.context.ChunkContext; -import art.arcane.iris.util.common.data.B; -import art.arcane.volmlib.util.documentation.ChunkCoordinates; -import art.arcane.iris.util.project.hunk.Hunk; -import art.arcane.volmlib.util.collection.KList; -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.math.BlockPosition; -import art.arcane.volmlib.util.math.M; import art.arcane.volmlib.util.math.PowerOfTwoCoordinates; 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.MatterMarker; import art.arcane.volmlib.util.matter.slices.MarkerMatter; -import art.arcane.volmlib.util.scheduling.PrecisionStopwatch; -import com.volmit.ModuleLog; -import it.unimi.dsi.fastutil.longs.Long2ObjectOpenHashMap; +import art.arcane.iris.engine.mantle.components.CarveWorld; +import com.volmit.block.BlockRegistry; +import com.volmit.block.BlockState; +import com.volmit.hunk.Hunk; +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.world.TerrainSampler; import lombok.Data; -import art.arcane.iris.spi.PlatformBlockState; +import java.util.List; import java.util.Map; /** * Applies the caves the mantle planned to a chunk's blocks for {@link CarveModule}: carves each cave zone, paints * its floor and ceiling with the cave biomes' layers, fills fluids and lava and decorates the cave surfaces. - * One per engine runtime, holding the carve stream's random. + * One per world, holding the carve stream's random. */ public class CaveApplying { private static final byte LIQUID_FLUID = 1; + private static final byte LIQUID_FORCED_AIR = 3; private static final ThreadLocal SCRATCH = ThreadLocal.withInitial(IrisCarveScratch::new); private static final int CAVE_BIOME_BLEND_RADIUS = 3; private static final int CAVE_BIOME_BLEND_CENTER_WEIGHT = 4; private static final int CAVE_BIOME_BLEND_TOTAL_WEIGHT = 8; + private static final int CAVE_BIOME_CACHE_SIZE = 2048; + private static final int CHUNK_AREA = 256; + private static final int LAYER_DEPTH = 3; + private static final long CEILING_MARKER_SALT = 0x9E3779B97F4A7C15L; + private static final long FLOOR_MARKER_SALT = 0xC2B2AE3D27D4EB4FL; private static final MatterCavern BASIC_CAVERN = new MatterCavern(true, "", (byte) 0); - private final Engine engine; - private final RNG rng; - private final PlatformBlockState AIR = B.getState("CAVE_AIR"); - private final PlatformBlockState LAVA = B.getState("LAVA"); - private final BiomeDecorators decorators; - private final BiomeLayers layers; - private final TerrainPalettes palettes; - private final IrisSurfaceDecorator surfaceDecorator; - private final IrisCeilingDecorator ceilingDecorator; - public CaveApplying(Engine engine, ModuleLog log) { - this.engine = engine; - rng = new RNG(engine.getSeedManager().getCarve()); - decorators = BiomeDecorators.of(engine); - layers = BiomeLayers.of(engine, log); - palettes = TerrainPalettes.of(engine); - surfaceDecorator = new IrisSurfaceDecorator(engine); - ceilingDecorator = new IrisCeilingDecorator(engine); + private final CarveWorld world; + private final PackResources resources; + private final BlockRegistry blocks; + private final CaveDressing dressing; + private final boolean upperDimensionCarving; + private final RNG rng; + private final BlockState caveAir; + private final BlockState plainAir; + private final BlockState lava; + + public CaveApplying(PackWorld packWorld, CarveWorld world, boolean upperDimensionCarving) { + this.world = world; + this.resources = packWorld.resources(); + this.blocks = resources.blocks(); + this.dressing = CaveDressing.of(packWorld); + this.upperDimensionCarving = upperDimensionCarving; + this.rng = new RNG(world.carveSeed()); + this.caveAir = blocks.resolve("minecraft:cave_air"); + this.plainAir = blocks.resolve("minecraft:air"); + this.lava = blocks.resolve("minecraft:lava"); } - /** Applies the caves to the chunk at chunk coordinates {@code x}, {@code z}. */ - @ChunkCoordinates - public void apply(int x, int z, Hunk output, boolean multicore, ChunkContext context) { - PrecisionStopwatch caveStopwatch = PrecisionStopwatch.start(); - Mantle mantle = engine.getMantle().getMantle(); - Long2ObjectOpenHashMap caveBiomeCache = new Long2ObjectOpenHashMap<>(2048); - IrisCarveScratch scratch = SCRATCH.get(); - scratch.reset(); - CarveWallBuffer walls = scratch.walls; - CarveColumnMask[] columnMasks = scratch.columnMasks; - CarveColumnMask[] boundaryMasks = scratch.boundaryMasks; - int[] surfaceHeights = scratch.surfaceHeights; - Map customBiomeCache = scratch.customBiomeCache; - UpperDimensionContext upperCtx = engine.getUpperContext(); - boolean protectUpper = upperCtx != null && !engine.getDimension().isUpperDimensionCarving(); - int[] upperSurfaceHeights = protectUpper ? scratch.getOrCreateUpperSurfaceHeights() : null; - int chunkBlockX = PowerOfTwoCoordinates.chunkToBlock(x); - int chunkBlockZ = PowerOfTwoCoordinates.chunkToBlock(z); - for (int columnIndex = 0; columnIndex < 256; columnIndex++) { - int localX = PowerOfTwoCoordinates.unpackLocal16X(columnIndex); - int localZ = columnIndex & 15; - surfaceHeights[columnIndex] = context.getRoundedHeight(localX, localZ); - if (protectUpper) { - int worldX = localX + chunkBlockX; - int worldZ = localZ + chunkBlockZ; - int rawUpper = upperCtx.getUpperSurfaceY(worldX, worldZ); - int gap = engine.getDimension().getUpperDimensionGap(); - upperSurfaceHeights[columnIndex] = Math.max(rawUpper, surfaceHeights[columnIndex] + gap); - } + /** + * Applies the caves to the chunk at chunk coordinates {@code x}, {@code z}, whose blocks are {@code output}; the caves are in + * {@code mantle}, and {@code terrain} gives the heights and cave biomes around the chunk. + */ + public void apply(MatterMantle mantle, TerrainSampler terrain, int x, int z, Hunk output) { + MantleChunk mantleChunk = mantle.chunk(x, z); + if (mantleChunk == null) { + return; + } + new Application(mantle, mantleChunk, terrain, x, z, output).run(); + } + + static boolean hasExplicitCarveIntent(MatterCavern cavern) { + return cavern != null && (isFluidIntent(cavern) || cavern.isLava() || cavern.getLiquid() == LIQUID_FORCED_AIR); + } + + static boolean isFluidIntent(MatterCavern cavern) { + return cavern != null && cavern.getLiquid() == LIQUID_FLUID; + } + + static boolean shouldPreserveExistingFluid(MatterCavern cavern, boolean existingIsFluid) { + return existingIsFluid && !hasExplicitCarveIntent(cavern); + } + + static boolean usesDefaultLava(int caveLavaHeight, int y) { + return y <= caveLavaHeight; + } + + static boolean isUnsupportedSurfaceOre(boolean surfaceIsOre, boolean belowIsSolid) { + return surfaceIsOre && !belowIsSolid; + } + + static BlockState resolveExplicitCarveState(MatterCavern cavern, BlockState fluid, BlockState lava, BlockState air) { + if (cavern == null) { + return null; + } + if (isFluidIntent(cavern)) { + return fluid; + } + if (cavern.isLava()) { + return lava; + } + return cavern.getLiquid() == LIQUID_FORCED_AIR ? air : null; + } + + static boolean canReplaceCaveFloorLayer(Hunk output, int x, int y, int z, BlockState layer, CaveBlockClasses classes) { + return !classes.hasGravity(layer) || y > 0 && classes.isSolid(output.get(x, y - 1, z)); + } + + static boolean hasStableCaveFloorSupport(Hunk output, int x, int floorY, int z, CaveBlockClasses classes) { + if (floorY <= 0) { + return false; + } + BlockState support = output.get(x, floorY - 1, z); + if (!classes.isSolid(support)) { + return false; + } + return !classes.hasGravity(support) || floorY > 1 && classes.isSolid(output.get(x, floorY - 2, z)); + } + + /** One chunk's application: the chunk's blocks, mantle and the caches its passes share. */ + final class Application { + private final MatterMantle mantle; + private final MantleChunk mantleChunk; + private final TerrainSampler terrain; + private final int chunkX; + private final int chunkZ; + private final Hunk output; + private final CaveBlockClasses classes = new CaveBlockClasses(blocks); + private final CaveBiomeCache caveBiomeCache = new CaveBiomeCache(CAVE_BIOME_CACHE_SIZE); + private final IrisCarveScratch scratch = SCRATCH.get(); + + Application(MatterMantle mantle, MantleChunk mantleChunk, TerrainSampler terrain, int chunkX, int chunkZ, Hunk output) { + this.mantle = mantle; + this.mantleChunk = mantleChunk; + this.terrain = terrain; + this.chunkX = chunkX; + this.chunkZ = chunkZ; + this.output = output; } - MantleChunk mantleChunk = mantle.getChunk(x, z).use(); - try { - PrecisionStopwatch resolveStopwatch = PrecisionStopwatch.start(); - int worldHeightSpan = engine.getWorld().maxHeight() - engine.getWorld().minHeight(); - int caveLavaHeight = engine.getDimension().getCaveLavaHeight(); + void run() { + scratch.reset(); + CarveWallBuffer walls = scratch.walls; + CarveColumnMask[] columnMasks = scratch.columnMasks; + CarveColumnMask[] boundaryMasks = scratch.boundaryMasks; + int[] surfaceHeights = scratch.surfaceHeights; + Map customBiomeCache = scratch.customBiomeCache; + int chunkBlockX = PowerOfTwoCoordinates.chunkToBlock(chunkX); + int chunkBlockZ = PowerOfTwoCoordinates.chunkToBlock(chunkZ); + boolean protectUpper = !upperDimensionCarving && terrain.upperDimensionY(chunkBlockX, chunkBlockZ).isPresent(); + int[] upperSurfaceHeights = protectUpper ? scratch.getOrCreateUpperSurfaceHeights() : null; + for (int columnIndex = 0; columnIndex < CHUNK_AREA; columnIndex++) { + int localX = PowerOfTwoCoordinates.unpackLocal16X(columnIndex); + int localZ = columnIndex & 15; + int worldX = localX + chunkBlockX; + int worldZ = localZ + chunkBlockZ; + surfaceHeights[columnIndex] = (int) Math.round(terrain.surfaceY(worldX, worldZ)); + if (protectUpper) { + upperSurfaceHeights[columnIndex] = terrain.upperDimensionY(worldX, worldZ).getAsInt(); + } + } + + int worldHeightSpan = world.height(); + int caveLavaHeight = world.lavaHeight(); mantleChunk.iterate(MatterCavern.class, (xx, yy, zz, cavern) -> { if (cavern == null) { return; @@ -136,10 +207,10 @@ public class CaveApplying { return; } - PlatformBlockState current = output.getRaw(rx, yy, rz); + BlockState current = output.get(rx, yy, rz); boolean explicitCarveIntent = hasExplicitCarveIntent(cavern); - if (shouldPreserveExistingFluid(cavern, current)) { + if (shouldPreserveExistingFluid(cavern, classes.isFluid(current))) { return; } @@ -149,608 +220,466 @@ public class CaveApplying { scratch.customCaveBiomePresent = true; } - if (current.isAir() && !explicitCarveIntent) { + if (classes.isAir(current) && !explicitCarveIntent) { return; } if (explicitCarveIntent) { - // Only a fluid cavern consumes the fluid sample, and on the maintenance path that - // sample is a full procedural stream evaluation, so never take it per voxel. - PlatformBlockState fluid = isFluidIntent(cavern) ? palettes.fluidAt(chunkBlockX + rx, chunkBlockZ + rz) : null; - output.setRaw(rx, yy, rz, resolveExplicitCarveState(cavern, fluid, LAVA, AIR)); + // Only a fluid cavern consumes the fluid sample, so never take it per voxel. + BlockState fluid = isFluidIntent(cavern) ? dressing.fluidAt(output, chunkBlockX + rx, chunkBlockZ + rz) : null; + BlockState carved = resolveExplicitCarveState(cavern, fluid, lava, caveAir); + output.set(rx, yy, rz, carved == null ? plainAir : carved); } else if (usesDefaultLava(caveLavaHeight, yy)) { - output.setRaw(rx, yy, rz, LAVA); + output.set(rx, yy, rz, lava); } else { - output.setRaw(rx, yy, rz, AIR); + output.set(rx, yy, rz, caveAir); } }); if (scratch.customCaveBiomePresent) { - addInternalWallsFromMantle(mantleChunk, walls, columnMasks); + addInternalWallsFromMantle(walls, columnMasks); } else { addInternalWallsFromMasks(walls, columnMasks); } - addCrossChunkBoundaryWalls(mantle, mantleChunk, walls, boundaryMasks, x, z, surfaceHeights); - engine.getMetrics().getCarveResolve().put(resolveStopwatch.getMilliseconds()); + addCrossChunkBoundaryWalls(walls, boundaryMasks, surfaceHeights); - PrecisionStopwatch applyStopwatch = PrecisionStopwatch.start(); - try { - walls.forEach((rx, yy, rz, cavern) -> { - int worldX = rx + chunkBlockX; - int worldZ = rz + chunkBlockZ; - String customBiome = cavern.getCustomBiome(); - IrisBiome biome = customBiome.isEmpty() - ? resolveCaveBiome(caveBiomeCache, worldX, yy, worldZ) - : resolveCustomBiome(customBiomeCache, customBiome); + walls.forEach((rx, yy, rz, cavern) -> { + int worldX = rx + chunkBlockX; + int worldZ = rz + chunkBlockZ; + String customBiome = cavern.getCustomBiome(); + ResourceId biome = customBiome.isEmpty() + ? resolveCaveBiome(worldX, yy, worldZ) + : resolveCustomBiome(customBiomeCache, customBiome); - if (biome != null) { - PlatformBlockState data = layers.wall(biome).get(rng, worldX, yy, worldZ); - int columnIndex = PowerOfTwoCoordinates.packLocal16(rx, rz); + if (biome != null) { + BlockState data = dressing.wall(output, biome, rng, worldX, yy, worldZ); + int columnIndex = PowerOfTwoCoordinates.packLocal16(rx, rz); - if (data != null && B.isSolid(output.getRaw(rx, yy, rz)) && yy < surfaceHeights[columnIndex]) { - output.setRaw(rx, yy, rz, data); + if (data != null && classes.isSolid(output.get(rx, yy, rz)) && yy < surfaceHeights[columnIndex]) { + output.set(rx, yy, rz, data); + } + } + }); + + for (int columnIndex = 0; columnIndex < CHUNK_AREA; columnIndex++) { + processColumnFromMask(columnMasks[columnIndex], columnIndex, customBiomeCache); + } + + for (int columnIndex = 0; columnIndex < CHUNK_AREA; columnIndex++) { + if (boundaryMasks[columnIndex].isEmpty() || !columnMasks[columnIndex].isEmpty()) { + continue; + } + processBoundaryColumnFromMask(boundaryMasks[columnIndex], walls, columnIndex, customBiomeCache); + } + + // Surface-break carving must not leave an ore cap suspended across the opening. + for (int columnIndex = 0; columnIndex < surfaceHeights.length; columnIndex++) { + int surfaceY = surfaceHeights[columnIndex]; + if (surfaceY <= 0 || surfaceY >= output.getHeight()) { + continue; + } + + int belowY = surfaceY - 1; + if (!columnMasks[columnIndex].contains(belowY) && !boundaryMasks[columnIndex].contains(belowY)) { + continue; + } + + int localX = PowerOfTwoCoordinates.unpackLocal16X(columnIndex); + int localZ = columnIndex & 15; + BlockState surface = output.get(localX, surfaceY, localZ); + BlockState below = output.get(localX, belowY, localZ); + if (isUnsupportedSurfaceOre(classes.isOre(surface), classes.isSolid(below))) { + output.set(localX, surfaceY, localZ, caveAir); + } + } + } + + private void addInternalWallsFromMasks(CarveWallBuffer walls, CarveColumnMask[] columnMasks) { + for (int columnIndex = 0; columnIndex < CHUNK_AREA; columnIndex++) { + CarveColumnMask columnMask = columnMasks[columnIndex]; + if (columnMask.isEmpty()) { + continue; + } + + int rx = columnIndex >> 4; + int rz = columnIndex & 15; + int yy = columnMask.nextSetBit(0); + while (yy >= 0) { + if (rz < 15 && !columnMasks[columnIndex + 1].contains(yy)) { + walls.put(rx, yy, rz + 1, BASIC_CAVERN); + } + if (rx < 15 && !columnMasks[columnIndex + 16].contains(yy)) { + walls.put(rx + 1, yy, rz, BASIC_CAVERN); + } + if (rz > 0 && !columnMasks[columnIndex - 1].contains(yy)) { + walls.put(rx, yy, rz - 1, BASIC_CAVERN); + } + if (rx > 0 && !columnMasks[columnIndex - 16].contains(yy)) { + walls.put(rx - 1, yy, rz, BASIC_CAVERN); + } + yy = columnMask.nextSetBit(yy + 1); + } + } + } + + private void addInternalWallsFromMantle(CarveWallBuffer walls, CarveColumnMask[] columnMasks) { + for (int columnIndex = 0; columnIndex < CHUNK_AREA; columnIndex++) { + CarveColumnMask columnMask = columnMasks[columnIndex]; + if (columnMask.isEmpty()) { + continue; + } + + int rx = columnIndex >> 4; + int rz = columnIndex & 15; + int yy = columnMask.nextSetBit(0); + while (yy >= 0) { + MatterCavern cavern = mantleChunk.get(rx, yy, rz, MatterCavern.class); + if (cavern != null) { + if (rz < 15 && mantleChunk.get(rx, yy, rz + 1, MatterCavern.class) == null) { + walls.put(rx, yy, rz + 1, cavern); + } + if (rx < 15 && mantleChunk.get(rx + 1, yy, rz, MatterCavern.class) == null) { + walls.put(rx + 1, yy, rz, cavern); + } + if (rz > 0 && mantleChunk.get(rx, yy, rz - 1, MatterCavern.class) == null) { + walls.put(rx, yy, rz - 1, cavern); + } + if (rx > 0 && mantleChunk.get(rx - 1, yy, rz, MatterCavern.class) == null) { + walls.put(rx - 1, yy, rz, cavern); } } - }); - - for (int columnIndex = 0; columnIndex < 256; columnIndex++) { - processColumnFromMask(output, mantleChunk, mantle, columnMasks[columnIndex], columnIndex, x, z, caveBiomeCache, customBiomeCache); + yy = columnMask.nextSetBit(yy + 1); } - - for (int columnIndex = 0; columnIndex < 256; columnIndex++) { - if (boundaryMasks[columnIndex].isEmpty() || !columnMasks[columnIndex].isEmpty()) { - continue; - } - processBoundaryColumnFromMask(output, boundaryMasks[columnIndex], walls, columnIndex, x, z, caveBiomeCache, customBiomeCache); - } - - // Surface-break carving must not leave an ore cap suspended across the opening. - for (int columnIndex = 0; columnIndex < surfaceHeights.length; columnIndex++) { - int surfaceY = surfaceHeights[columnIndex]; - if (surfaceY <= 0 || surfaceY >= output.getHeight()) { - continue; - } - - int belowY = surfaceY - 1; - if (!columnMasks[columnIndex].contains(belowY) && !boundaryMasks[columnIndex].contains(belowY)) { - continue; - } - - int localX = PowerOfTwoCoordinates.unpackLocal16X(columnIndex); - int localZ = columnIndex & 15; - PlatformBlockState surface = output.getRaw(localX, surfaceY, localZ); - PlatformBlockState below = output.getRaw(localX, belowY, localZ); - if (isUnsupportedSurfaceOre(surface, below)) { - output.setRaw(localX, surfaceY, localZ, AIR); - } - } - } finally { - engine.getMetrics().getCarveApply().put(applyStopwatch.getMilliseconds()); } - } finally { - engine.getMetrics().getCave().put(caveStopwatch.getMilliseconds()); - mantleChunk.release(); } - } - static boolean hasExplicitCarveIntent(MatterCavern cavern) { - return cavern != null && (isFluidIntent(cavern) || cavern.isLava() || cavern.getLiquid() == 3); - } - - static boolean isFluidIntent(MatterCavern cavern) { - return cavern != null && cavern.getLiquid() == LIQUID_FLUID; - } - - static boolean shouldPreserveExistingFluid(MatterCavern cavern, PlatformBlockState current) { - return B.isFluid(current) && !hasExplicitCarveIntent(cavern); - } - - static boolean usesDefaultLava(int caveLavaHeight, int y) { - return y <= caveLavaHeight; - } - - static boolean isUnsupportedSurfaceOre(PlatformBlockState surface, PlatformBlockState below) { - return B.isOre(surface) && !B.isSolid(below); - } - - static PlatformBlockState resolveExplicitCarveState(MatterCavern cavern, PlatformBlockState fluid, - PlatformBlockState lava, PlatformBlockState air) { - if (cavern == null) { - return null; - } - if (isFluidIntent(cavern)) { - return fluid; - } - if (cavern.isLava()) { - return lava; - } - return cavern.getLiquid() == 3 ? air : null; - } - - private void addInternalWallsFromMasks(CarveWallBuffer walls, CarveColumnMask[] columnMasks) { - for (int columnIndex = 0; columnIndex < 256; columnIndex++) { - CarveColumnMask columnMask = columnMasks[columnIndex]; - if (columnMask.isEmpty()) { - continue; + private void addCrossChunkBoundaryWalls(CarveWallBuffer walls, CarveColumnMask[] boundaryMasks, int[] surfaceHeights) { + int maxSurfaceY = 0; + for (int index = 0; index < surfaceHeights.length; index++) { + if (surfaceHeights[index] > maxSurfaceY) { + maxSurfaceY = surfaceHeights[index]; + } + } + int maxY = Math.min(world.height() - 1, maxSurfaceY + 1); + if (maxY < 1) { + return; } - int rx = columnIndex >> 4; + MantleChunk west = mantle.loadedChunk(chunkX - 1, chunkZ); + MantleChunk east = mantle.loadedChunk(chunkX + 1, chunkZ); + MantleChunk north = mantle.loadedChunk(chunkX, chunkZ - 1); + MantleChunk south = mantle.loadedChunk(chunkX, chunkZ + 1); + if (west == null && east == null && north == null && south == null) { + return; + } + + for (int yy = 1; yy <= maxY; yy++) { + for (int offset = 0; offset < 16; offset++) { + if (west != null) { + tryAddBoundaryWall(west, walls, boundaryMasks, 0, yy, offset, 15, offset); + } + if (east != null) { + tryAddBoundaryWall(east, walls, boundaryMasks, 15, yy, offset, 0, offset); + } + if (north != null) { + tryAddBoundaryWall(north, walls, boundaryMasks, offset, yy, 0, offset, 15); + } + if (south != null) { + tryAddBoundaryWall(south, walls, boundaryMasks, offset, yy, 15, offset, 0); + } + } + } + } + + private void tryAddBoundaryWall(MantleChunk neighborChunk, CarveWallBuffer walls, CarveColumnMask[] boundaryMasks, + int localX, int yy, int localZ, int neighborX, int neighborZ) { + if (mantleChunk.get(localX, yy, localZ, MatterCavern.class) != null) { + return; + } + + MatterCavern neighbor = neighborChunk.get(neighborX, yy, neighborZ, MatterCavern.class); + if (neighbor == null) { + return; + } + + walls.put(localX, yy, localZ, neighbor); + int columnIndex = PowerOfTwoCoordinates.packLocal16(localX, localZ); + boundaryMasks[columnIndex].add(yy); + } + + private void processColumnFromMask(CarveColumnMask columnMask, int columnIndex, Map customBiomeCache) { + if (columnMask == null || columnMask.isEmpty()) { + return; + } + + int firstHeight = columnMask.nextSetBit(0); + if (firstHeight < 0) { + return; + } + + int rx = PowerOfTwoCoordinates.unpackLocal16X(columnIndex); int rz = columnIndex & 15; - int yy = columnMask.nextSetBit(0); - while (yy >= 0) { - if (rz < 15 && !columnMasks[columnIndex + 1].contains(yy)) { - walls.put(rx, yy, rz + 1, BASIC_CAVERN); + int worldX = rx + PowerOfTwoCoordinates.chunkToBlock(chunkX); + int worldZ = rz + PowerOfTwoCoordinates.chunkToBlock(chunkZ); + CaveZone zone = new CaveZone(); + zone.setFloor(firstHeight); + int buf = firstHeight - 1; + int y = firstHeight; + + while (y >= 0) { + if (y <= world.height()) { + if (y == buf + 1) { + buf = y; + zone.ceiling = buf; + } else { + if (zone.isValid(world.height())) { + processZone(zone, rx, rz, worldX, worldZ, customBiomeCache); + } + zone = new CaveZone(); + zone.setFloor(y); + buf = y; + } } - if (rx < 15 && !columnMasks[columnIndex + 16].contains(yy)) { - walls.put(rx + 1, yy, rz, BASIC_CAVERN); - } - if (rz > 0 && !columnMasks[columnIndex - 1].contains(yy)) { - walls.put(rx, yy, rz - 1, BASIC_CAVERN); - } - if (rx > 0 && !columnMasks[columnIndex - 16].contains(yy)) { - walls.put(rx - 1, yy, rz, BASIC_CAVERN); - } - yy = columnMask.nextSetBit(yy + 1); + + y = columnMask.nextSetBit(y + 1); + } + + if (zone.isValid(world.height())) { + processZone(zone, rx, rz, worldX, worldZ, customBiomeCache); } } - } - private void addInternalWallsFromMantle(MantleChunk mc, CarveWallBuffer walls, CarveColumnMask[] columnMasks) { - for (int columnIndex = 0; columnIndex < 256; columnIndex++) { - CarveColumnMask columnMask = columnMasks[columnIndex]; - if (columnMask.isEmpty()) { - continue; + private void processBoundaryColumnFromMask(CarveColumnMask boundaryMask, CarveWallBuffer walls, int columnIndex, + Map customBiomeCache) { + int firstHeight = boundaryMask.nextSetBit(0); + if (firstHeight < 0) { + return; } - int rx = columnIndex >> 4; + int rx = PowerOfTwoCoordinates.unpackLocal16X(columnIndex); int rz = columnIndex & 15; - int yy = columnMask.nextSetBit(0); - while (yy >= 0) { - MatterCavern cavern = mc.get(rx, yy, rz, MatterCavern.class); - if (cavern != null) { - if (rz < 15 && mc.get(rx, yy, rz + 1, MatterCavern.class) == null) { - walls.put(rx, yy, rz + 1, cavern); - } - if (rx < 15 && mc.get(rx + 1, yy, rz, MatterCavern.class) == null) { - walls.put(rx + 1, yy, rz, cavern); - } - if (rz > 0 && mc.get(rx, yy, rz - 1, MatterCavern.class) == null) { - walls.put(rx, yy, rz - 1, cavern); - } - if (rx > 0 && mc.get(rx - 1, yy, rz, MatterCavern.class) == null) { - walls.put(rx - 1, yy, rz, cavern); - } - } - yy = columnMask.nextSetBit(yy + 1); - } - } - } + int worldX = rx + PowerOfTwoCoordinates.chunkToBlock(chunkX); + int worldZ = rz + PowerOfTwoCoordinates.chunkToBlock(chunkZ); + int zoneFloor = firstHeight; + int zoneCeiling = firstHeight; + int y = boundaryMask.nextSetBit(firstHeight + 1); - private void addCrossChunkBoundaryWalls( - Mantle mantle, - MantleChunk mc, - CarveWallBuffer walls, - CarveColumnMask[] boundaryMasks, - int chunkX, - int chunkZ, - int[] surfaceHeights - ) { - int baseX = PowerOfTwoCoordinates.chunkToBlock(chunkX); - int baseZ = PowerOfTwoCoordinates.chunkToBlock(chunkZ); - int maxSurfaceY = 0; - for (int index = 0; index < surfaceHeights.length; index++) { - if (surfaceHeights[index] > maxSurfaceY) { - maxSurfaceY = surfaceHeights[index]; - } - } - int maxY = Math.min(engine.getWorld().maxHeight() - engine.getWorld().minHeight() - 1, maxSurfaceY + 1); - if (maxY < 1) { - return; - } - - MantleChunk west = existingMantleChunk(mantle, chunkX - 1, chunkZ); - MantleChunk east = existingMantleChunk(mantle, chunkX + 1, chunkZ); - MantleChunk north = existingMantleChunk(mantle, chunkX, chunkZ - 1); - MantleChunk south = existingMantleChunk(mantle, chunkX, chunkZ + 1); - if (west == null && east == null && north == null && south == null) { - return; - } - - for (int yy = 1; yy <= maxY; yy++) { - for (int offset = 0; offset < 16; offset++) { - if (west != null) { - tryAddBoundaryWall(mc, west, walls, boundaryMasks, 0, yy, offset, 15, offset); - } - if (east != null) { - tryAddBoundaryWall(mc, east, walls, boundaryMasks, 15, yy, offset, 0, offset); - } - if (north != null) { - tryAddBoundaryWall(mc, north, walls, boundaryMasks, offset, yy, 0, offset, 15); - } - if (south != null) { - tryAddBoundaryWall(mc, south, walls, boundaryMasks, offset, yy, 15, offset, 0); - } - } - } - } - - private void tryAddBoundaryWall( - MantleChunk mc, - MantleChunk neighborChunk, - CarveWallBuffer walls, - CarveColumnMask[] boundaryMasks, - int localX, - int yy, - int localZ, - int neighborX, - int neighborZ - ) { - if (mc.get(localX, yy, localZ, MatterCavern.class) != null) { - return; - } - - MatterCavern neighbor = neighborChunk.get(neighborX, yy, neighborZ, MatterCavern.class); - if (neighbor == null) { - return; - } - - walls.put(localX, yy, localZ, neighbor); - int columnIndex = PowerOfTwoCoordinates.packLocal16(localX, localZ); - boundaryMasks[columnIndex].add(yy); - } - - private MantleChunk existingMantleChunk(Mantle mantle, int chunkX, int chunkZ) { - TectonicPlate plate = mantle.getLoadedRegions().get(Mantle.key(chunkX >> 5, chunkZ >> 5)); - if (plate == null || plate.isClosed()) { - return null; - } - return plate.get(chunkX & 31, chunkZ & 31); - } - - private void processColumnFromMask( - Hunk output, - MantleChunk mc, - Mantle mantle, - CarveColumnMask columnMask, - int columnIndex, - int chunkX, - int chunkZ, - Long2ObjectOpenHashMap caveBiomeCache, - Map customBiomeCache - ) { - if (columnMask == null || columnMask.isEmpty()) { - return; - } - - int firstHeight = columnMask.nextSetBit(0); - if (firstHeight < 0) { - return; - } - - int rx = PowerOfTwoCoordinates.unpackLocal16X(columnIndex); - int rz = columnIndex & 15; - int worldX = rx + PowerOfTwoCoordinates.chunkToBlock(chunkX); - int worldZ = rz + PowerOfTwoCoordinates.chunkToBlock(chunkZ); - CaveZone zone = new CaveZone(); - zone.setFloor(firstHeight); - int buf = firstHeight - 1; - int y = firstHeight; - - while (y >= 0) { - if (y <= engine.getHeight()) { - if (y == buf + 1) { - buf = y; - zone.ceiling = buf; + while (y >= 0) { + if (y == zoneCeiling + 1) { + zoneCeiling = y; } else { - if (zone.isValid(engine)) { - processZone(output, mc, mantle, zone, rx, rz, worldX, worldZ, caveBiomeCache, customBiomeCache); - } - zone = new CaveZone(); - zone.setFloor(y); - buf = y; + paintBoundaryZone(walls, rx, rz, worldX, worldZ, zoneFloor, zoneCeiling, customBiomeCache); + zoneFloor = y; + zoneCeiling = y; } + y = boundaryMask.nextSetBit(y + 1); } - y = columnMask.nextSetBit(y + 1); + paintBoundaryZone(walls, rx, rz, worldX, worldZ, zoneFloor, zoneCeiling, customBiomeCache); } - if (zone.isValid(engine)) { - processZone(output, mc, mantle, zone, rx, rz, worldX, worldZ, caveBiomeCache, customBiomeCache); - } - } + private void paintBoundaryZone(CarveWallBuffer walls, int rx, int rz, int worldX, int worldZ, int zoneFloor, int zoneCeiling, + Map customBiomeCache) { + ResourceId floorBiome = resolveCaveBoundaryBiome(walls.get(rx, zoneFloor, rz), worldX, zoneFloor, worldZ, customBiomeCache); + ResourceId ceilingBiome = resolveCaveBoundaryBiome(walls.get(rx, zoneCeiling, rz), worldX, zoneCeiling, worldZ, customBiomeCache); + if (floorBiome == null && ceilingBiome == null) { + return; + } - private void processBoundaryColumnFromMask( - Hunk output, - CarveColumnMask boundaryMask, - CarveWallBuffer walls, - int columnIndex, - int chunkX, - int chunkZ, - Long2ObjectOpenHashMap caveBiomeCache, - Map customBiomeCache - ) { - int firstHeight = boundaryMask.nextSetBit(0); - if (firstHeight < 0) { - return; - } + if (floorBiome != null) { + paintFloorLayers(floorBiome, rx, rz, worldX, worldZ, zoneFloor); + } - int rx = PowerOfTwoCoordinates.unpackLocal16X(columnIndex); - int rz = columnIndex & 15; - int worldX = rx + PowerOfTwoCoordinates.chunkToBlock(chunkX); - int worldZ = rz + PowerOfTwoCoordinates.chunkToBlock(chunkZ); - int zoneFloor = firstHeight; - int zoneCeiling = firstHeight; - int y = boundaryMask.nextSetBit(firstHeight + 1); - - while (y >= 0) { - if (y == zoneCeiling + 1) { - zoneCeiling = y; - } else { - paintBoundaryZone(output, walls, rx, rz, worldX, worldZ, zoneFloor, zoneCeiling, caveBiomeCache, customBiomeCache); - zoneFloor = y; - zoneCeiling = y; + if (ceilingBiome != null) { + paintCeilingLayers(ceilingBiome, rx, rz, worldX, worldZ, zoneCeiling, world.height()); } - y = boundaryMask.nextSetBit(y + 1); } - paintBoundaryZone(output, walls, rx, rz, worldX, worldZ, zoneFloor, zoneCeiling, caveBiomeCache, customBiomeCache); - } - - private void paintBoundaryZone( - Hunk output, - CarveWallBuffer walls, - int rx, - int rz, - int worldX, - int worldZ, - int zoneFloor, - int zoneCeiling, - Long2ObjectOpenHashMap caveBiomeCache, - Map customBiomeCache - ) { - IrisBiome floorBiome = resolveCaveBoundaryBiome( - walls.get(rx, zoneFloor, rz), worldX, zoneFloor, worldZ, - caveBiomeCache, customBiomeCache); - IrisBiome ceilingBiome = resolveCaveBoundaryBiome( - walls.get(rx, zoneCeiling, rz), worldX, zoneCeiling, worldZ, - caveBiomeCache, customBiomeCache); - if (floorBiome == null && ceilingBiome == null) { - return; - } - - if (floorBiome != null) { - KList floorLayers = layers.generateLayers(floorBiome, - engine.getDimension(), worldX, worldZ, rng, 3, zoneFloor, engine.getData(), engine.getComplex()); - for (int i = 0; i < zoneFloor - 1; i++) { - if (!floorLayers.hasIndex(i)) { + /** Replaces the solid blocks under {@code floorY} with the layers of {@code floorBiome}. */ + private void paintFloorLayers(ResourceId floorBiome, int rx, int rz, int worldX, int worldZ, int floorY) { + List floorLayers = dressing.floorLayers(output, floorBiome, worldX, worldZ, rng, LAYER_DEPTH, floorY); + for (int i = 0; i < floorY - 1; i++) { + if (i >= floorLayers.size()) { break; } - int floorY = zoneFloor - i - 1; - if (floorY < 0) { - break; - } - PlatformBlockState existing = output.getRaw(rx, floorY, rz); - PlatformBlockState layer = floorLayers.get(i); - if (!B.isSolid(existing) || !canReplaceCaveFloorLayer(output, rx, floorY, rz, layer)) { + int y = floorY - i - 1; + BlockState layer = floorLayers.get(i); + BlockState existing = output.get(rx, y, rz); + if (layer == null || !classes.isSolid(existing) || !canReplaceCaveFloorLayer(output, rx, y, rz, layer, classes)) { continue; } - if (B.isOre(existing)) { - output.setRaw(rx, floorY, rz, B.toDeepSlateOre(existing, layer)); - continue; - } - output.setRaw(rx, floorY, rz, layer); + output.set(rx, y, rz, classes.isOre(existing) ? dressing.deepSlateOre(output, existing, layer) : layer); } } - if (ceilingBiome != null) { - int worldMaxY = engine.getWorld().maxHeight() - engine.getWorld().minHeight(); - KList ceilingLayers = layers.generateCeilingLayers(ceilingBiome, - engine.getDimension(), worldX, worldZ, rng, 3, zoneCeiling, engine.getData(), engine.getComplex()); + /** Replaces the solid blocks over {@code ceilingY} with the cave ceiling layers of {@code ceilingBiome}, below {@code maxY}. */ + private void paintCeilingLayers(ResourceId ceilingBiome, int rx, int rz, int worldX, int worldZ, int ceilingY, int maxY) { + List ceilingLayers = dressing.ceilingLayers(output, ceilingBiome, worldX, worldZ, rng, LAYER_DEPTH, ceilingY); for (int i = 0; i < ceilingLayers.size(); i++) { - int ceilingY = zoneCeiling + i + 1; - if (ceilingY >= worldMaxY) { + int y = ceilingY + i + 1; + if (y >= maxY) { break; } - PlatformBlockState existing = output.getRaw(rx, ceilingY, rz); - if (!B.isSolid(existing)) { + BlockState layer = ceilingLayers.get(i); + BlockState existing = output.get(rx, y, rz); + if (layer == null || !classes.isSolid(existing)) { continue; } - PlatformBlockState layer = ceilingLayers.get(i); - if (B.isOre(existing)) { - output.setRaw(rx, ceilingY, rz, B.toDeepSlateOre(existing, layer)); - continue; - } - output.setRaw(rx, ceilingY, rz, layer); - } - } - } - - /** - * 1-in-16 marker roll from a SplitMix64 finalizer over (carve seed, block position, salt). - * Deterministic per seed and position, thread-order independent, allocation free. - */ - private boolean markerRoll(int x, int y, int z, long salt) { - long h = (engine.getSeedManager().getCarve() + salt) ^ BlockPosition.toLong(x, y, z); - h = (h ^ (h >>> 30)) * 0xBF58476D1CE4E5B9L; - h = (h ^ (h >>> 27)) * 0x94D049BB133111EBL; - h ^= h >>> 31; - return (h & 15L) == 0L; - } - - private void processZone(Hunk output, MantleChunk mc, Mantle mantle, CaveZone zone, int rx, int rz, int xx, int zz, Long2ObjectOpenHashMap caveBiomeCache, Map customBiomeCache) { - int maxY = output.getHeight(); - - if (zone.ceiling + 1 < maxY && B.isDecorant(output.getRaw(rx, zone.ceiling + 1, rz))) { - output.setRaw(rx, zone.ceiling + 1, rz, AIR); - } - - if (B.isDecorant(output.getRaw(rx, zone.ceiling, rz))) { - output.setRaw(rx, zone.ceiling, rz, AIR); - } - - // Seed-derived and position-keyed, never Math.random(): these markers persist into the - // mantle and drive cave spawning, so the same seed must stamp the same markers on - // every run and every platform. Inline mix, no allocation on this hot path. - if (markerRoll(xx, zone.ceiling, zz, 0x9E3779B97F4A7C15L)) { - mantle.set(xx, zone.ceiling, zz, MarkerMatter.CAVE_CEILING); - } - - if (markerRoll(xx, zone.floor, zz, 0xC2B2AE3D27D4EB4FL)) { - mantle.set(xx, zone.floor, zz, MarkerMatter.CAVE_FLOOR); - } - - IrisBiome floorBiome = resolveCaveBoundaryBiome(mc, rx, zone.floor, rz, xx, zz, caveBiomeCache, customBiomeCache); - IrisBiome ceilingBiome = resolveCaveBoundaryBiome(mc, rx, zone.ceiling, rz, xx, zz, caveBiomeCache, customBiomeCache); - if (floorBiome == null && ceilingBiome == null) { - return; - } - - if (floorBiome != null) { - KList floorBlocks = layers.generateLayers(floorBiome, engine.getDimension(), xx, zz, rng, 3, zone.floor, engine.getData(), engine.getComplex()); - for (int i = 0; i < zone.floor - 1; i++) { - if (!floorBlocks.hasIndex(i)) { - break; - } - int y = zone.floor - i - 1; - PlatformBlockState block = floorBlocks.get(i); - PlatformBlockState existing = output.getRaw(rx, y, rz); - if (!B.isSolid(existing) || !canReplaceCaveFloorLayer(output, rx, y, rz, block)) { - continue; - } - if (B.isOre(existing)) { - output.setRaw(rx, y, rz, B.toDeepSlateOre(existing, block)); - continue; - } - output.setRaw(rx, y, rz, block); + output.set(rx, y, rz, classes.isOre(existing) ? dressing.deepSlateOre(output, existing, layer) : layer); } } - if (ceilingBiome != null) { - KList ceilingBlocks = layers.generateCeilingLayers(ceilingBiome, engine.getDimension(), xx, zz, rng, 3, zone.ceiling, engine.getData(), engine.getComplex()); - for (int i = 0; i < ceilingBlocks.size(); i++) { - int cy = zone.ceiling + i + 1; - if (cy >= maxY) { - break; - } - PlatformBlockState block = ceilingBlocks.get(i); - PlatformBlockState existing = output.getRaw(rx, cy, rz); - if (!B.isSolid(existing)) { - continue; - } - if (B.isOre(existing)) { - output.setRaw(rx, cy, rz, B.toDeepSlateOre(existing, block)); - continue; - } - output.setRaw(rx, cy, rz, block); + /** + * 1-in-16 marker roll from a SplitMix64 finalizer over (carve seed, block position, salt). + * Deterministic per seed and position, thread-order independent, allocation free. + */ + private boolean markerRoll(int x, int y, int z, long salt) { + long h = (world.carveSeed() + salt) ^ BlockPosition.toLong(x, y, z); + h = (h ^ (h >>> 30)) * 0xBF58476D1CE4E5B9L; + h = (h ^ (h >>> 27)) * 0x94D049BB133111EBL; + h ^= h >>> 31; + return (h & 15L) == 0L; + } + + private void processZone(CaveZone zone, int rx, int rz, int xx, int zz, Map customBiomeCache) { + int maxY = output.getHeight(); + + if (zone.ceiling + 1 < maxY && classes.isDecorant(output.get(rx, zone.ceiling + 1, rz))) { + output.set(rx, zone.ceiling + 1, rz, caveAir); + } + + if (classes.isDecorant(output.get(rx, zone.ceiling, rz))) { + output.set(rx, zone.ceiling, rz, caveAir); + } + + // Seed-derived and position-keyed, never Math.random(): these markers persist into the + // mantle and drive cave spawning, so the same seed must stamp the same markers on + // every run and every platform. Inline mix, no allocation on this hot path. + if (markerRoll(xx, zone.ceiling, zz, CEILING_MARKER_SALT)) { + setMarker(rx, zone.ceiling, rz, MarkerMatter.CAVE_CEILING); + } + + if (markerRoll(xx, zone.floor, zz, FLOOR_MARKER_SALT)) { + setMarker(rx, zone.floor, rz, MarkerMatter.CAVE_FLOOR); + } + + ResourceId floorBiome = resolveCaveBoundaryBiome(rx, zone.floor, rz, xx, zz, customBiomeCache); + ResourceId ceilingBiome = resolveCaveBoundaryBiome(rx, zone.ceiling, rz, xx, zz, customBiomeCache); + if (floorBiome == null && ceilingBiome == null) { + return; + } + + if (floorBiome != null) { + paintFloorLayers(floorBiome, rx, rz, xx, zz, zone.floor); + } + + if (ceilingBiome != null) { + paintCeilingLayers(ceilingBiome, rx, rz, xx, zz, zone.ceiling, maxY); + } + + if (floorBiome != null && dressing.hasDecorators(floorBiome, DecorationPart.NONE) + && hasStableCaveFloorSupport(output, rx, zone.getFloor(), rz, classes)) { + dressing.decorateFloor(output, rx, rz, xx, zz, floorBiome, zone.getFloor() - 1, zone.airThickness()); + } + + if (ceilingBiome != null && dressing.hasDecorators(ceilingBiome, DecorationPart.CEILING) && zone.getCeiling() + 1 < maxY + && classes.isSolid(output.get(rx, zone.getCeiling() + 1, rz))) { + dressing.decorateCeiling(output, rx, rz, xx, zz, ceilingBiome, zone.getCeiling(), zone.airThickness()); } } - if (floorBiome != null && decorators.hasDecorators(floorBiome, DecorationPart.NONE) && hasStableCaveFloorSupport(output, rx, zone.getFloor(), rz)) { - surfaceDecorator.decorate(rx, rz, xx, xx, xx, zz, zz, zz, output, floorBiome, InferredType.CAVE, zone.getFloor() - 1, zone.airThickness()); + private void setMarker(int localX, int y, int localZ, MatterMarker marker) { + Matter section = mantleChunk.getOrCreate(y >> 4); + section.slice(MatterMarker.class).set(localX, y & 15, localZ, marker); } - if (ceilingBiome != null && decorators.hasDecorators(ceilingBiome, DecorationPart.CEILING) && zone.getCeiling() + 1 < maxY && B.isSolid(output.getRaw(rx, zone.getCeiling() + 1, rz))) { - ceilingDecorator.decorate(rx, rz, xx, xx, xx, zz, zz, zz, output, ceilingBiome, InferredType.CAVE, zone.getCeiling(), zone.airThickness()); - } - } - - IrisBiome resolveCaveBoundaryBiome(MantleChunk mantleChunk, int x, int y, int z, int worldX, int worldZ, Long2ObjectOpenHashMap caveBiomeCache, Map customBiomeCache) { - MatterCavern cavern = dataIfPresent(mantleChunk, x, y, z, MatterCavern.class); - return resolveCaveBoundaryBiome( - cavern, worldX, y, worldZ, caveBiomeCache, customBiomeCache); - } - - private static T dataIfPresent(MantleChunk mantleChunk, int x, int y, int z, Class type) { - int section = y >> 4; - if (y < 0 || !mantleChunk.exists(section)) { - return null; - } - Matter matter = mantleChunk.get(section); - if (matter == null || !matter.hasSlice(type)) { - return null; - } - return matter.getSlice(type).get(x & 15, y & 15, z & 15); - } - - IrisBiome resolveCaveBoundaryBiome(MatterCavern cavern, int worldX, int y, int worldZ, Long2ObjectOpenHashMap caveBiomeCache, Map customBiomeCache) { - if (cavern != null && !cavern.getCustomBiome().isEmpty()) { - return resolveCustomBiome(customBiomeCache, cavern.getCustomBiome()); - } - return resolveCaveBiome(caveBiomeCache, worldX, y, worldZ); - } - - static boolean canReplaceCaveFloorLayer(Hunk output, int x, int y, int z, PlatformBlockState layer) { - return !isGravityAffected(layer) || y > 0 && B.isSolid(output.getRaw(x, y - 1, z)); - } - - static boolean hasStableCaveFloorSupport(Hunk output, int x, int floorY, int z) { - if (floorY <= 0) { - return false; - } - PlatformBlockState support = output.getRaw(x, floorY - 1, z); - if (!B.isSolid(support)) { - return false; - } - return !isGravityAffected(support) || floorY > 1 && B.isSolid(output.getRaw(x, floorY - 2, z)); - } - - static boolean isGravityAffected(PlatformBlockState state) { - return state != null && state.hasGravity(); - } - - private IrisBiome resolveCaveBiome(Long2ObjectOpenHashMap caveBiomeCache, int x, int y, int z) { - IrisBiome center = sampleCaveBiome(caveBiomeCache, x, y, z); - if (center == null) { - return null; + ResourceId resolveCaveBoundaryBiome(int x, int y, int z, int worldX, int worldZ, Map customBiomeCache) { + return resolveCaveBoundaryBiome(cavernIfPresent(x, y, z), worldX, y, worldZ, customBiomeCache); } - IrisBiome xPos = sampleCaveBiome(caveBiomeCache, x + CAVE_BIOME_BLEND_RADIUS, y, z); - IrisBiome xNeg = sampleCaveBiome(caveBiomeCache, x - CAVE_BIOME_BLEND_RADIUS, y, z); - IrisBiome zPos = sampleCaveBiome(caveBiomeCache, x, y, z + CAVE_BIOME_BLEND_RADIUS); - IrisBiome zNeg = sampleCaveBiome(caveBiomeCache, x, y, z - CAVE_BIOME_BLEND_RADIUS); - - if (xPos == center && xNeg == center && zPos == center && zNeg == center) { - return center; + private MatterCavern cavernIfPresent(int x, int y, int z) { + int section = y >> 4; + if (y < 0 || !mantleChunk.exists(section)) { + return null; + } + Matter matter = mantleChunk.get(section); + if (matter == null || !matter.hasSlice(MatterCavern.class)) { + return null; + } + return matter.getSlice(MatterCavern.class).get(x & 15, y & 15, z & 15); } - int roll = Math.floorMod(rng.nextParallelRNG(BlockPosition.toLong(x, y, z)).nextInt(), CAVE_BIOME_BLEND_TOTAL_WEIGHT); - if (roll < CAVE_BIOME_BLEND_CENTER_WEIGHT) { - return center; - } - roll -= CAVE_BIOME_BLEND_CENTER_WEIGHT; - if (roll == 0) { - return xPos != null ? xPos : center; - } - if (roll == 1) { - return xNeg != null ? xNeg : center; - } - if (roll == 2) { - return zPos != null ? zPos : center; - } - return zNeg != null ? zNeg : center; - } - - private IrisBiome sampleCaveBiome(Long2ObjectOpenHashMap caveBiomeCache, int x, int y, int z) { - long key = BlockPosition.toLong(x, y, z); - IrisBiome cachedBiome = caveBiomeCache.get(key); - if (cachedBiome != null) { - return cachedBiome; + ResourceId resolveCaveBoundaryBiome(MatterCavern cavern, int worldX, int y, int worldZ, Map customBiomeCache) { + if (cavern != null && !cavern.getCustomBiome().isEmpty()) { + return resolveCustomBiome(customBiomeCache, cavern.getCustomBiome()); + } + return resolveCaveBiome(worldX, y, worldZ); } - IrisBiome resolvedBiome = engine.getCaveBiome(x, y, z); - if (resolvedBiome != null) { - caveBiomeCache.put(key, resolvedBiome); - } - return resolvedBiome; - } + private ResourceId resolveCaveBiome(int x, int y, int z) { + ResourceId center = sampleCaveBiome(x, y, z); + if (center == null) { + return null; + } - private IrisBiome resolveCustomBiome(Map customBiomeCache, String customBiome) { - if (customBiomeCache.containsKey(customBiome)) { - return customBiomeCache.get(customBiome); + ResourceId xPos = sampleCaveBiome(x + CAVE_BIOME_BLEND_RADIUS, y, z); + ResourceId xNeg = sampleCaveBiome(x - CAVE_BIOME_BLEND_RADIUS, y, z); + ResourceId zPos = sampleCaveBiome(x, y, z + CAVE_BIOME_BLEND_RADIUS); + ResourceId zNeg = sampleCaveBiome(x, y, z - CAVE_BIOME_BLEND_RADIUS); + + if (xPos == center && xNeg == center && zPos == center && zNeg == center) { + return center; + } + + int roll = Math.floorMod(rng.nextParallelRNG(BlockPosition.toLong(x, y, z)).nextInt(), CAVE_BIOME_BLEND_TOTAL_WEIGHT); + if (roll < CAVE_BIOME_BLEND_CENTER_WEIGHT) { + return center; + } + roll -= CAVE_BIOME_BLEND_CENTER_WEIGHT; + if (roll == 0) { + return xPos != null ? xPos : center; + } + if (roll == 1) { + return xNeg != null ? xNeg : center; + } + if (roll == 2) { + return zPos != null ? zPos : center; + } + return zNeg != null ? zNeg : center; } - IrisBiome loaded = engine.getData().getBiomeLoader().load(customBiome); - customBiomeCache.put(customBiome, loaded); - return loaded; + private ResourceId sampleCaveBiome(int x, int y, int z) { + long key = BlockPosition.toLong(x, y, z); + ResourceId cachedBiome = caveBiomeCache.get(key); + if (cachedBiome != null) { + return cachedBiome; + } + + ResourceId resolvedBiome = terrain.caveBiome(x, y, z).orElse(null); + if (resolvedBiome != null) { + caveBiomeCache.put(key, resolvedBiome); + } + return resolvedBiome; + } + + /** The id of the pack's biome with this key; null when the pack has none or it cannot be loaded. */ + private ResourceId existingBiomeId(String key) { + ResourceId id = resources.idOf(key); + try { + return resources.find(new ResourceKey<>(id, PackBiome.class)).isPresent() ? id : null; + } catch (IllegalStateException unreadable) { + return null; + } + } + + private ResourceId resolveCustomBiome(Map customBiomeCache, String customBiome) { + if (customBiomeCache.containsKey(customBiome)) { + return customBiomeCache.get(customBiome); + } + + ResourceId id = existingBiomeId(customBiome); + customBiomeCache.put(customBiome, id); + return id; + } } @Data @@ -762,8 +691,8 @@ public class CaveApplying { return (ceiling - floor) - 1; } - public boolean isValid(Engine engine) { - return floor < ceiling && ceiling - floor >= 1 && floor >= 0 && ceiling <= engine.getHeight() && airThickness() > 0; + public boolean isValid(int height) { + return floor < ceiling && ceiling - floor >= 1 && floor >= 0 && ceiling <= height && airThickness() > 0; } public String toString() { diff --git a/src/main/java/art/arcane/iris/engine/modifier/CaveBiomeBands.java b/src/main/java/art/arcane/iris/engine/modifier/CaveBiomeBands.java index 4a67e77c3..bae9f392d 100644 --- a/src/main/java/art/arcane/iris/engine/modifier/CaveBiomeBands.java +++ b/src/main/java/art/arcane/iris/engine/modifier/CaveBiomeBands.java @@ -19,11 +19,10 @@ package art.arcane.iris.engine.modifier; import art.arcane.iris.builtin.carve.CaveDepthSettings; -import art.arcane.iris.core.modules.IrisPackWorld; -import art.arcane.iris.engine.framework.Engine; import art.arcane.iris.engine.object.terrain.carving.CarvingResolver; +import art.arcane.iris.engine.object.terrain.carving.DeclaredByLevel; import art.arcane.iris.engine.object.terrain.carving.ResolvedCarvingEntry; -import art.arcane.iris.engine.object.world.biome.IrisBiome; +import com.volmit.resource.ResourceId; import com.volmit.service.CaveBiomes; import com.volmit.world.PackWorld; @@ -36,13 +35,13 @@ import java.util.Optional; public final class CaveBiomeBands implements CaveBiomes { @Override public Optional overriddenBiome(PackWorld world, int x, int y, int z) { - Engine engine = IrisPackWorld.of(world).engine(); - ResolvedCarvingEntry rootEntry = CarvingResolver.resolveRootEntry(engine, y + engine.getWorld().minHeight(), null); + CarvingResolver resolver = CarvingResolver.of(world); + ResolvedCarvingEntry rootEntry = resolver.rootEntryAt(y); if (rootEntry == null) { return Optional.empty(); } - ResolvedCarvingEntry entry = CarvingResolver.resolveFromRoot(engine, rootEntry, x, z, null); - if (CarvingResolver.resolveEntryBiome(engine, entry, null) == null) { + ResolvedCarvingEntry entry = resolver.resolveFromRoot(rootEntry, x, z); + if (resolver.entryBiome(entry) == null) { return Optional.empty(); } return Optional.of(entry.biomeKey().trim()); @@ -50,12 +49,25 @@ public final class CaveBiomeBands implements CaveBiomes { @Override public int minDepthBelowSurface(PackWorld world, String biomeKey) { - IrisBiome biome = IrisPackWorld.of(world).engine().getData().getBiomeLoader().load(biomeKey); - return biome == null ? 0 : minDepthBelowSurface(biome); + return Depths.of(world).minDepthBelowSurface(world.resources().idOf(biomeKey)); } - /** How many blocks below the surface {@code biome}'s caves begin, as its {@code caveMinDepthBelowSurface} says; 0 where it says none. */ - public static int minDepthBelowSurface(IrisBiome biome) { - return biome.getModuleSettings().find(CaveDepthSettings.class).map(CaveDepthSettings::depth).orElse(0); + /** The minimum depths the world's biomes declare ({@code caveMinDepthBelowSurface}), found by biome id. */ + private static final class Depths { + private final DeclaredByLevel declared; + + private Depths(PackWorld world) { + this.declared = DeclaredByLevel.of(world, CaveDepthSettings.class); + } + + static Depths of(PackWorld world) { + return world.state(Depths.class, Depths::new); + } + + /** How many blocks below the surface the biome's caves begin, as its {@code caveMinDepthBelowSurface} says; 0 where it says none. */ + int minDepthBelowSurface(ResourceId biome) { + CaveDepthSettings depth = declared.ofBiome(biome); + return depth == null ? 0 : depth.depth(); + } } } diff --git a/src/main/java/art/arcane/iris/engine/modifier/CaveBiomeCache.java b/src/main/java/art/arcane/iris/engine/modifier/CaveBiomeCache.java new file mode 100644 index 000000000..5f32cab21 --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/modifier/CaveBiomeCache.java @@ -0,0 +1,99 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.engine.modifier; + +import com.volmit.resource.ResourceId; + +import java.util.Arrays; + +/** + * The cave biomes one chunk's caves have sampled so far, by block position (see {@link art.arcane.volmlib.util.math.BlockPosition#toLong}): + * a cave wall asks for the biome around it five times, and the next wall block asks again for most of them. Open addressing on + * longs, which spares the boxing a map of {@link Long} would do on this hot path; only biomes that exist are kept. + */ +final class CaveBiomeCache { + private static final double LOAD_FACTOR = 0.5D; + private static final long EMPTY_KEY = Long.MIN_VALUE; + + private long[] keys; + private ResourceId[] values; + private int mask; + private int size; + + CaveBiomeCache(int expectedSize) { + int capacity = 8; + while (capacity * LOAD_FACTOR < expectedSize) { + capacity <<= 1; + } + allocate(capacity); + } + + /** The biome kept for {@code key}; null where none is. */ + ResourceId get(long key) { + int index = slot(key); + while (keys[index] != EMPTY_KEY) { + if (keys[index] == key) { + return values[index]; + } + index = (index + 1) & mask; + } + return null; + } + + void put(long key, ResourceId biome) { + if ((size + 1) > keys.length * LOAD_FACTOR) { + grow(); + } + int index = slot(key); + while (keys[index] != EMPTY_KEY) { + if (keys[index] == key) { + values[index] = biome; + return; + } + index = (index + 1) & mask; + } + keys[index] = key; + values[index] = biome; + size++; + } + + private int slot(long key) { + long mixed = key * 0x9E3779B97F4A7C15L; + return (int) (mixed ^ (mixed >>> 32)) & mask; + } + + private void allocate(int capacity) { + keys = new long[capacity]; + Arrays.fill(keys, EMPTY_KEY); + values = new ResourceId[capacity]; + mask = capacity - 1; + size = 0; + } + + private void grow() { + long[] oldKeys = keys; + ResourceId[] oldValues = values; + allocate(oldKeys.length << 1); + for (int index = 0; index < oldKeys.length; index++) { + if (oldKeys[index] != EMPTY_KEY) { + put(oldKeys[index], oldValues[index]); + } + } + } +} diff --git a/src/main/java/art/arcane/iris/engine/modifier/CaveBlockClasses.java b/src/main/java/art/arcane/iris/engine/modifier/CaveBlockClasses.java new file mode 100644 index 000000000..78d88e7c8 --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/modifier/CaveBlockClasses.java @@ -0,0 +1,89 @@ +/* + * 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 com.volmit.block.BlockRegistry; +import com.volmit.block.BlockState; +import com.volmit.block.BlockTrait; + +import java.util.IdentityHashMap; +import java.util.Map; + +/** + * What the cave passes of one chunk ask about blocks, answered from memory. A chunk holds few distinct states and a cave pass asks + * about them per block, so each state instance (the hunk hands out one per distinct state) is classified once. + */ +final class CaveBlockClasses { + private static final int SOLID = 1; + private static final int FLUID = 2; + private static final int AIR = 4; + private static final int ORE = 8; + private static final int DECORATION = 16; + private static final int GRAVITY = 32; + + private final BlockRegistry blocks; + private final Map classes = new IdentityHashMap<>(); + + CaveBlockClasses(BlockRegistry blocks) { + this.blocks = blocks; + } + + boolean isSolid(BlockState state) { + return (classesOf(state) & SOLID) != 0; + } + + boolean isFluid(BlockState state) { + return (classesOf(state) & FLUID) != 0; + } + + boolean isAir(BlockState state) { + return (classesOf(state) & AIR) != 0; + } + + boolean isOre(BlockState state) { + return (classesOf(state) & ORE) != 0; + } + + boolean isDecorant(BlockState state) { + return (classesOf(state) & DECORATION) != 0; + } + + boolean hasGravity(BlockState state) { + return state != null && (classesOf(state) & GRAVITY) != 0; + } + + private int classesOf(BlockState state) { + Integer known = classes.get(state); + if (known != null) { + return known; + } + int computed = classify(state); + classes.put(state, computed); + return computed; + } + + private int classify(BlockState state) { + return flag(state, BlockTrait.SOLID, SOLID) | flag(state, BlockTrait.FLUID, FLUID) | flag(state, BlockTrait.AIR, AIR) + | flag(state, BlockTrait.ORE, ORE) | flag(state, BlockTrait.DECORATION, DECORATION) | flag(state, BlockTrait.GRAVITY, GRAVITY); + } + + private int flag(BlockState state, BlockTrait trait, int bit) { + return blocks.hasTrait(state, trait) ? bit : 0; + } +} diff --git a/src/main/java/art/arcane/iris/engine/modifier/IrisCarveScratch.java b/src/main/java/art/arcane/iris/engine/modifier/IrisCarveScratch.java index a2e51e88d..21859bc8a 100644 --- a/src/main/java/art/arcane/iris/engine/modifier/IrisCarveScratch.java +++ b/src/main/java/art/arcane/iris/engine/modifier/IrisCarveScratch.java @@ -18,11 +18,8 @@ package art.arcane.iris.engine.modifier; -import art.arcane.iris.engine.object.world.biome.IrisBiome; -import art.arcane.volmlib.util.matter.MatterCavern; -import art.arcane.volmlib.util.math.PowerOfTwoCoordinates; +import com.volmit.resource.ResourceId; -import java.util.Arrays; import java.util.HashMap; import java.util.Map; @@ -31,7 +28,7 @@ final class IrisCarveScratch { final CarveColumnMask[] boundaryMasks = new CarveColumnMask[256]; final int[] surfaceHeights = new int[256]; final CarveWallBuffer walls = new CarveWallBuffer(512); - final Map customBiomeCache = new HashMap<>(); + final Map customBiomeCache = new HashMap<>(); int[] upperSurfaceHeights; boolean customCaveBiomePresent; @@ -59,219 +56,3 @@ final class IrisCarveScratch { customCaveBiomePresent = false; } } - -final class CarveColumnMask { - private long[] words = new long[8]; - private int maxWord = -1; - - void add(int y) { - if (y < 0) { - return; - } - - int wordIndex = y >> 6; - if (wordIndex >= words.length) { - words = Arrays.copyOf(words, Math.max(words.length << 1, wordIndex + 1)); - } - - words[wordIndex] |= 1L << (y & 63); - if (wordIndex > maxWord) { - maxWord = wordIndex; - } - } - - int nextSetBit(int fromBit) { - if (maxWord < 0) { - return -1; - } - - int startBit = Math.max(0, fromBit); - int wordIndex = startBit >> 6; - if (wordIndex > maxWord) { - return -1; - } - - long word = words[wordIndex] & (-1L << (startBit & 63)); - while (true) { - if (word != 0L) { - return (wordIndex << 6) + Long.numberOfTrailingZeros(word); - } - - wordIndex++; - if (wordIndex > maxWord) { - return -1; - } - word = words[wordIndex]; - } - } - - boolean isEmpty() { - return maxWord < 0; - } - - boolean contains(int y) { - if (y < 0) { - return false; - } - - int wordIndex = y >> 6; - if (wordIndex > maxWord) { - return false; - } - - return (words[wordIndex] & (1L << (y & 63))) != 0L; - } - - void clear() { - if (maxWord < 0) { - return; - } - - for (int index = 0; index <= maxWord; index++) { - words[index] = 0L; - } - maxWord = -1; - } -} - -final class CarveWallBuffer { - private static final int EMPTY_KEY = -1; - private static final double LOAD_FACTOR = 0.75D; - - private int[] keys; - private MatterCavern[] values; - private int mask; - private int resizeAt; - private int size; - - CarveWallBuffer(int expectedSize) { - int capacity = 1; - int minimumCapacity = Math.max(8, expectedSize); - while (capacity < minimumCapacity) { - capacity <<= 1; - } - - keys = new int[capacity]; - Arrays.fill(keys, EMPTY_KEY); - values = new MatterCavern[capacity]; - mask = capacity - 1; - resizeAt = Math.max(1, (int) (capacity * LOAD_FACTOR)); - } - - void put(int x, int y, int z, MatterCavern value) { - int key = pack(x, y, z); - int index = mix(key) & mask; - - while (true) { - int existingKey = keys[index]; - if (existingKey == EMPTY_KEY) { - keys[index] = key; - values[index] = value; - size++; - if (size >= resizeAt) { - resize(); - } - return; - } - - if (existingKey == key) { - values[index] = value; - return; - } - - index = (index + 1) & mask; - } - } - - MatterCavern get(int x, int y, int z) { - int key = pack(x, y, z); - int index = mix(key) & mask; - while (true) { - int existingKey = keys[index]; - if (existingKey == EMPTY_KEY) { - return null; - } - if (existingKey == key) { - return values[index]; - } - index = (index + 1) & mask; - } - } - - void forEach(Consumer consumer) { - for (int index = 0; index < keys.length; index++) { - int key = keys[index]; - if (key == EMPTY_KEY) { - continue; - } - - MatterCavern cavern = values[index]; - if (cavern != null) { - consumer.accept(unpackX(key), unpackY(key), unpackZ(key), cavern); - } - } - } - - void clear() { - Arrays.fill(keys, EMPTY_KEY); - Arrays.fill(values, null); - size = 0; - } - - private void resize() { - int[] oldKeys = keys; - MatterCavern[] oldValues = values; - int nextCapacity = oldKeys.length << 1; - keys = new int[nextCapacity]; - Arrays.fill(keys, EMPTY_KEY); - values = new MatterCavern[nextCapacity]; - mask = nextCapacity - 1; - resizeAt = Math.max(1, (int) (nextCapacity * LOAD_FACTOR)); - size = 0; - - for (int index = 0; index < oldKeys.length; index++) { - int key = oldKeys[index]; - MatterCavern value = oldValues[index]; - if (key != EMPTY_KEY && value != null) { - reinsert(key, value); - } - } - } - - private void reinsert(int key, MatterCavern value) { - int index = mix(key) & mask; - while (keys[index] != EMPTY_KEY) { - index = (index + 1) & mask; - } - - keys[index] = key; - values[index] = value; - size++; - } - - private int pack(int x, int y, int z) { - return (y << 8) | PowerOfTwoCoordinates.packLocal16(x & 15, z & 15); - } - - private int unpackX(int key) { - return PowerOfTwoCoordinates.unpackLocal16X(key & 255); - } - - private int unpackY(int key) { - return key >> 8; - } - - private int unpackZ(int key) { - return PowerOfTwoCoordinates.unpackLocal16Z(key); - } - - private int mix(int value) { - int mixed = value * 0x9E3779B9; - return mixed ^ (mixed >>> 16); - } - - @FunctionalInterface - interface Consumer { - void accept(int x, int y, int z, MatterCavern cavern); - } -} diff --git a/src/main/java/art/arcane/iris/engine/object/terrain/carving/CarvingBands.java b/src/main/java/art/arcane/iris/engine/object/terrain/carving/CarvingBands.java deleted file mode 100644 index 916e35316..000000000 --- a/src/main/java/art/arcane/iris/engine/object/terrain/carving/CarvingBands.java +++ /dev/null @@ -1,71 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Servers - * Copyright (c) 2026 Arcane Arts (Volmit Software) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package art.arcane.iris.engine.object.terrain.carving; - -import art.arcane.iris.builtin.carve.CarvingEntry; -import art.arcane.iris.builtin.carve.CarvingSettings; -import art.arcane.iris.engine.framework.Engine; - -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Objects; - -/** - * What the carve module keeps for one world: the cave biome bands its dimension declares ({@link CarvingSettings}) made ready - * ({@link ResolvedCarvingEntry}), in the order the dimension lists them, and by id. - */ -public final class CarvingBands { - private final List entries; - private final Map index; - - CarvingBands(List declared) { - this.entries = declared.stream().filter(Objects::nonNull).map(ResolvedCarvingEntry::new).toList(); - this.index = indexById(entries); - } - - CarvingBands(Engine engine) { - this(engine.getDimension().getModuleSettings().find(CarvingSettings.class).map(CarvingSettings::entries).orElse(List.of())); - } - - /** The bands of the world {@code engine} generates now. */ - public static CarvingBands of(Engine engine) { - return engine.getGeneration().state(CarvingBands.class, CarvingBands::new); - } - - /** Every declared entry, enabled or not. */ - public List entries() { - return entries; - } - - /** The entries by their trimmed ids; entries without an id are not in it, and the last of several with one id is. */ - public Map index() { - return index; - } - - private static Map indexById(List entries) { - Map index = new HashMap<>(); - for (ResolvedCarvingEntry entry : entries) { - if (!entry.id().isBlank()) { - index.put(entry.id().trim(), entry); - } - } - return Map.copyOf(index); - } -} diff --git a/src/main/java/art/arcane/iris/engine/object/terrain/carving/CarvingResolver.java b/src/main/java/art/arcane/iris/engine/object/terrain/carving/CarvingResolver.java index a4eb736ed..ad137c0fa 100644 --- a/src/main/java/art/arcane/iris/engine/object/terrain/carving/CarvingResolver.java +++ b/src/main/java/art/arcane/iris/engine/object/terrain/carving/CarvingResolver.java @@ -1,78 +1,122 @@ +/* + * 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.object.terrain.carving; -import art.arcane.iris.engine.object.value.IRare; -import art.arcane.iris.engine.object.world.biome.IrisBiome; -import art.arcane.iris.core.loader.IrisData; -import art.arcane.iris.engine.framework.Engine; -import art.arcane.iris.engine.object.world.dimension.IrisDimension; -import art.arcane.iris.util.project.interpolation.IrisInterpolation; -import art.arcane.iris.util.project.noise.CNG; +import art.arcane.iris.builtin.IrisSeed; +import art.arcane.iris.builtin.carve.CarvingEntry; +import art.arcane.iris.builtin.carve.CarvingSettings; +import com.volmit.ModuleLog; +import com.volmit.config.FeatureSettings.Entry; import com.volmit.config.Range; +import com.volmit.FeatureAttachment.Target; +import com.volmit.noise.NoiseSampler; +import com.volmit.resource.PackResources; +import com.volmit.world.PackBiome; +import com.volmit.world.PackWorld; -import java.lang.ref.WeakReference; import java.util.ArrayList; import java.util.HashMap; -import java.util.IdentityHashMap; import java.util.List; import java.util.Map; +import java.util.Objects; +import java.util.Optional; +import java.util.concurrent.ConcurrentHashMap; /** - * Picks the dimension's carving entry for a position: the last enabled root entry whose world Y band holds the height, - * then, through the entries' children, the one a noise pattern selects at the column. The state a caller passes (or, when - * it passes none, the thread's) keeps the picks and the entries' biomes, so a caller resolving many positions reuses them. + * What the carve module keeps for one world about the cave biome bands its dimension declares ({@link CarvingSettings}): the + * entries made ready ({@link ResolvedCarvingEntry}), in the order the dimension lists them and by id, and the picks among them. + * A pick is the dimension's last enabled root entry whose world Y band holds a height, then, through the entries' children, the + * one a noise pattern selects at a column. */ public final class CarvingResolver { private static final int MAX_CHILD_DEPTH = 32; private static final long CHILD_SEED_SALT = 0x9E3779B97F4A7C15L; - private static final ThreadLocal> THREAD_STATE = - ThreadLocal.withInitial(() -> new WeakReference<>(null)); - private CarvingResolver() { + private final PackResources resources; + private final ModuleLog log; + private final int minHeight; + private final long childSeed; + private final List entries; + private final Map index; + private final Map> rootEntriesByWorldY = new ConcurrentHashMap<>(); + private final Map selectionPlans = new ConcurrentHashMap<>(); + CarvingResolver(PackWorld world, List declared) { + this.resources = world.resources(); + this.log = world.log(); + this.minHeight = world.minHeight(); + this.childSeed = IrisSeed.CARVE.of(world) ^ CHILD_SEED_SALT; + this.entries = declared.stream().filter(Objects::nonNull).map(ResolvedCarvingEntry::new).toList(); + this.index = indexById(entries); } - public static ResolvedCarvingEntry resolveRootEntry(Engine engine, int worldY) { - return resolveRootEntry(engine, worldY, threadState()); + /** The bands of the world {@code world} generates now. */ + public static CarvingResolver of(PackWorld world) { + return world.state(CarvingResolver.class, generating -> new CarvingResolver(generating, dimensionEntries(generating))); } - public static ResolvedCarvingEntry resolveRootEntry(Engine engine, int worldY, State state) { - State resolvedState = state == null ? threadState() : state; - resolvedState.bind(engine); - if (resolvedState.rootEntriesByWorldY.containsKey(worldY)) { - return resolvedState.rootEntriesByWorldY.get(worldY); + private static List dimensionEntries(PackWorld world) { + List dimensionEntries = new ArrayList<>(); + for (Entry entry : world.settings().declared(CarvingSettings.class)) { + if (entry.level() == Target.DIMENSION) { + dimensionEntries.addAll(entry.value().entries()); + } } + return dimensionEntries; + } - List entries = resolvedState.bands.entries(); - if (entries.isEmpty()) { - resolvedState.rootEntriesByWorldY.put(worldY, null); - return null; - } + /** Every declared entry, enabled or not. */ + public List entries() { + return entries; + } + /** The entries by their trimmed ids; entries without an id are not in it, and the last of several with one id is. */ + public Map index() { + return index; + } + + /** The root entry for a height above the dimension's bottom; null where no enabled entry with a biome holds it. */ + public ResolvedCarvingEntry rootEntryAt(int y) { + return rootEntryAtWorldY(y + minHeight); + } + + /** The root entry for a world Y as packs write them; null where no enabled entry with a biome holds it. */ + public ResolvedCarvingEntry rootEntryAtWorldY(int worldY) { + return rootEntriesByWorldY.computeIfAbsent(worldY, this::pickRootEntry).orElse(null); + } + + private Optional pickRootEntry(int worldY) { ResolvedCarvingEntry resolved = null; for (ResolvedCarvingEntry entry : entries) { - if (!isRootCandidate(engine, entry, worldY, resolvedState)) { - continue; + if (isRootCandidate(entry, worldY)) { + resolved = entry; } - - resolved = entry; } - - resolvedState.rootEntriesByWorldY.put(worldY, resolved); - return resolved; + return Optional.ofNullable(resolved); } - public static ResolvedCarvingEntry resolveFromRoot(Engine engine, ResolvedCarvingEntry rootEntry, int worldX, int worldZ) { - return resolveFromRoot(engine, rootEntry, worldX, worldZ, threadState()); - } - - public static ResolvedCarvingEntry resolveFromRoot(Engine engine, ResolvedCarvingEntry rootEntry, int worldX, int worldZ, State state) { - State resolvedState = state == null ? threadState() : state; - resolvedState.bind(engine); + public ResolvedCarvingEntry resolveFromRoot(ResolvedCarvingEntry rootEntry, int worldX, int worldZ) { if (rootEntry == null) { return null; } - IrisBiome rootBiome = resolveEntryBiome(engine, rootEntry, resolvedState); + PackBiome rootBiome = entryBiome(rootEntry); if (rootBiome == null) { return null; } @@ -82,11 +126,10 @@ public final class CarvingResolver { return rootEntry; } - Map entryIndex = resolvedState.bands.index(); ResolvedCarvingEntry current = rootEntry; int depth = remainingDepth; while (depth > 0) { - ResolvedCarvingEntry selected = selectChild(engine, current, worldX, worldZ, entryIndex, resolvedState); + ResolvedCarvingEntry selected = selectChild(current, worldX, worldZ); if (selected == null || selected == current) { break; } @@ -102,30 +145,12 @@ public final class CarvingResolver { return current; } - public static IrisBiome resolveEntryBiome(Engine engine, ResolvedCarvingEntry entry) { - return resolveEntryBiome(engine, entry, null); + /** The pack biome the entry names; null when it names none or the pack has no such biome. */ + public PackBiome entryBiome(ResolvedCarvingEntry entry) { + return entry == null ? null : entry.realBiome(resources, log); } - public static IrisBiome resolveEntryBiome(Engine engine, ResolvedCarvingEntry entry, State state) { - if (entry == null) { - return null; - } - - if (state == null) { - return entry.realBiome(engine.getData()); - } - - state.bind(engine); - if (state.biomeCache.containsKey(entry)) { - return state.biomeCache.get(entry); - } - - IrisBiome biome = entry.realBiome(engine.getData()); - state.biomeCache.put(entry, biome); - return biome; - } - - private static boolean isRootCandidate(Engine engine, ResolvedCarvingEntry entry, int worldY, State state) { + private boolean isRootCandidate(ResolvedCarvingEntry entry, int worldY) { if (entry == null || !entry.enabled()) { return false; } @@ -135,41 +160,28 @@ public final class CarvingResolver { return false; } - return resolveEntryBiome(engine, entry, state) != null; + return entryBiome(entry) != null; } - private static ResolvedCarvingEntry selectChild( - Engine engine, - ResolvedCarvingEntry parent, - int worldX, - int worldZ, - Map entryIndex, - State state - ) { + private ResolvedCarvingEntry selectChild(ResolvedCarvingEntry parent, int worldX, int worldZ) { List children = parent.children(); if (children.isEmpty()) { return parent; } - IrisBiome parentBiome = resolveEntryBiome(engine, parent, state); + PackBiome parentBiome = entryBiome(parent); if (parentBiome == null) { return parent; } - ParentSelectionPlan selectionPlan = state.selectionPlans.get(parent); - if (selectionPlan == null) { - selectionPlan = buildSelectionPlan(engine, parent, parentBiome, entryIndex, state); - state.selectionPlans.put(parent, selectionPlan); - } - + ParentSelectionPlan selectionPlan = selectionPlans.computeIfAbsent(parent, key -> buildSelectionPlan(key, parentBiome)); if (selectionPlan.parentOnly) { return parent; } - long seed = resolveChildSeed(engine, state); - CNG childGenerator = parent.childrenGenerator(seed, engine.getData()); - double sample = childGenerator.noiseFast2D(worldX, worldZ); - int selectedIndex = (int) Math.round(IrisInterpolation.lerp(0, selectionPlan.maxIndex, sample)); + NoiseSampler childGenerator = parent.childrenGenerator(childSeed, resources); + double sample = childGenerator.sample(worldX, worldZ); + int selectedIndex = (int) Math.round(sample * selectionPlan.maxIndex); CarvingChoice selected = selectionPlan.get(selectedIndex); if (selected == null || selected.entry == null) { return parent; @@ -178,25 +190,19 @@ public final class CarvingResolver { return selected.entry; } - private static ParentSelectionPlan buildSelectionPlan( - Engine engine, - ResolvedCarvingEntry parent, - IrisBiome parentBiome, - Map entryIndex, - State state - ) { + private ParentSelectionPlan buildSelectionPlan(ResolvedCarvingEntry parent, PackBiome parentBiome) { List options = new ArrayList<>(); for (String childId : parent.children()) { if (childId == null || childId.isBlank()) { continue; } - ResolvedCarvingEntry child = entryIndex.get(childId.trim()); + ResolvedCarvingEntry child = index.get(childId.trim()); if (child == null || !child.enabled()) { continue; } - IrisBiome childBiome = resolveEntryBiome(engine, child, state); + PackBiome childBiome = entryBiome(child); if (childBiome == null) { continue; } @@ -243,13 +249,12 @@ public final class CarvingResolver { return mapped.toArray(new CarvingChoice[0]); } - private static int rarity(IrisBiome biome) { + private static int rarity(PackBiome biome) { if (biome == null) { return 1; } - int rarity = biome.getRarity(); - return Math.max(rarity, 1); + return Math.max(biome.rarity(), 1); } private static int clampDepth(int depth) { @@ -260,56 +265,14 @@ public final class CarvingResolver { return Math.min(depth, MAX_CHILD_DEPTH); } - private static long resolveChildSeed(Engine engine, State state) { - if (state.childSeed == null) { - state.childSeed = engine.getSeedManager().getCarve() ^ CHILD_SEED_SALT; - } - - return state.childSeed; - } - - private static State threadState() { - WeakReference reference = THREAD_STATE.get(); - State state = reference.get(); - if (state != null) { - return state; - } - State replacement = new State(); - THREAD_STATE.set(new WeakReference<>(replacement)); - return replacement; - } - - public static final class State { - private final Map rootEntriesByWorldY = new HashMap<>(); - private final Map selectionPlans = new IdentityHashMap<>(); - private final Map biomeCache = new IdentityHashMap<>(); - private WeakReference engineIdentity; - private WeakReference dimensionIdentity; - private WeakReference dataIdentity; - private CarvingBands bands; - private Long childSeed; - - private void bind(Engine engine) { - IrisDimension dimension = engine.getDimension(); - IrisData data = engine.getData(); - if (references(engineIdentity, engine) - && references(dimensionIdentity, dimension) - && references(dataIdentity, data)) { - return; + private static Map indexById(List entries) { + Map index = new HashMap<>(); + for (ResolvedCarvingEntry entry : entries) { + if (!entry.id().isBlank()) { + index.put(entry.id().trim(), entry); } - engineIdentity = new WeakReference<>(engine); - dimensionIdentity = new WeakReference<>(dimension); - dataIdentity = new WeakReference<>(data); - bands = CarvingBands.of(engine); - rootEntriesByWorldY.clear(); - selectionPlans.clear(); - biomeCache.clear(); - childSeed = null; - } - - private static boolean references(WeakReference identity, Object value) { - return identity != null && identity.get() == value; } + return Map.copyOf(index); } private static final class ParentSelectionPlan { @@ -350,18 +313,6 @@ public final class CarvingResolver { } } - private static final class CarvingChoice implements IRare { - private final ResolvedCarvingEntry entry; - private final int rarity; - - private CarvingChoice(ResolvedCarvingEntry entry, int rarity) { - this.entry = entry; - this.rarity = rarity; - } - - @Override - public int getRarity() { - return rarity; - } + private record CarvingChoice(ResolvedCarvingEntry entry, int rarity) { } } diff --git a/src/main/java/art/arcane/iris/engine/object/terrain/carving/IrisCaveProfileSampler.java b/src/main/java/art/arcane/iris/engine/object/terrain/carving/CaveProfileSampler.java similarity index 63% rename from src/main/java/art/arcane/iris/engine/object/terrain/carving/IrisCaveProfileSampler.java rename to src/main/java/art/arcane/iris/engine/object/terrain/carving/CaveProfileSampler.java index 4eaef2997..6432cc232 100644 --- a/src/main/java/art/arcane/iris/engine/object/terrain/carving/IrisCaveProfileSampler.java +++ b/src/main/java/art/arcane/iris/engine/object/terrain/carving/CaveProfileSampler.java @@ -18,26 +18,26 @@ package art.arcane.iris.engine.object.terrain.carving; +import art.arcane.iris.builtin.carve.CaveFieldModule; import art.arcane.iris.builtin.carve.CaveProfile; -import art.arcane.iris.engine.object.value.IrisRange; -import art.arcane.iris.core.loader.IrisData; -import art.arcane.iris.engine.framework.Engine; -import art.arcane.iris.util.project.noise.CNG; -import art.arcane.volmlib.util.math.RNG; +import art.arcane.volmlib.util.math.M; +import com.volmit.config.Range; +import com.volmit.noise.NoiseFactory; +import com.volmit.noise.NoiseSampler; +import com.volmit.noise.NoiseStyle; +import com.volmit.noise.StyledRange; import java.util.ArrayList; import java.util.List; -public final class IrisCaveProfileSampler { +public final class CaveProfileSampler { private static final double FLOATING_THRESHOLD_BIAS_SCALE = 0.2D; - private final IrisData data; private final CaveProfile profile; - private final ResolvedCaveProfile resolved; - private final CNG baseDensity; - private final CNG detailDensity; - private final CNG warpDensity; - private final RNG thresholdRng; + private final NoiseSampler baseDensity; + private final NoiseSampler detailDensity; + private final NoiseSampler warpDensity; + private final NoiseSampler thresholdNoise; private final ModuleState[] modules; private final double inverseNormalization; private final double baseWeight; @@ -47,16 +47,13 @@ public final class IrisCaveProfileSampler { private final boolean hasWarp; private final boolean hasModules; - public IrisCaveProfileSampler(Engine engine, CaveProfile profile) { - this.data = engine.getData(); + public CaveProfileSampler(NoiseFactory noise, long carveSeed, CaveProfile profile) { this.profile = profile; - this.resolved = ResolvedCaveProfile.of(profile); List moduleStates = new ArrayList<>(); - RNG baseRng = new RNG(engine.getSeedManager().getCarve()); - this.baseDensity = resolved.baseDensityStyle().create(baseRng.nextParallelRNG(934_447), data); - this.detailDensity = resolved.detailDensityStyle().create(baseRng.nextParallelRNG(612_991), data); - this.warpDensity = resolved.warpStyle().create(baseRng.nextParallelRNG(770_713), data); - this.thresholdRng = baseRng.nextParallelRNG(489_112); + this.baseDensity = noise.sampler(profile.baseDensityStyle(), carveSeed + 934_447); + this.detailDensity = noise.sampler(profile.detailDensityStyle(), carveSeed + 612_991); + this.warpDensity = noise.sampler(profile.warpStyle(), carveSeed + 770_713); + this.thresholdNoise = noise.sampler(profile.densityThreshold().style(), carveSeed + 489_112); this.baseWeight = profile.baseWeight(); this.detailWeight = profile.detailWeight(); this.warpStrength = profile.warpStrength(); @@ -64,8 +61,8 @@ public final class IrisCaveProfileSampler { double weight = Math.abs(baseWeight) + Math.abs(detailWeight); int index = 0; - for (ResolvedCaveProfile.Module module : resolved.modules()) { - CNG moduleDensity = module.style().create(baseRng.nextParallelRNG(1_000_003L + (index * 65_537L)), data); + for (CaveFieldModule module : profile.modules()) { + NoiseSampler moduleDensity = noise.sampler(module.style(), carveSeed + 1_000_003L + (index * 65_537L)); ModuleState state = new ModuleState(module, moduleDensity); moduleStates.add(state); weight += Math.abs(state.weight); @@ -76,7 +73,7 @@ public final class IrisCaveProfileSampler { double normalization = weight <= 0 ? 1D : weight; this.inverseNormalization = 1D / normalization; this.hasModules = modules.length > 0; - this.enabled = profile.enabled() && baseDensity != null && detailDensity != null && (!hasWarp || warpDensity != null); + this.enabled = profile.enabled(); } public boolean shouldCarve(int x, int y, int z, double floatingCarveThreshold) { @@ -84,11 +81,23 @@ public final class IrisCaveProfileSampler { return false; } - double threshold = resolved.densityThreshold().get(thresholdRng, x, z, data) - profile.thresholdBias(); + double threshold = thresholdAt(x, z) - profile.thresholdBias(); threshold += floatingThresholdBias(floatingCarveThreshold); return sampleDensity(x, y, z) <= threshold; } + /** The profile's density threshold at the column, as a styled range picks its value. */ + private double thresholdAt(int x, int z) { + StyledRange range = profile.densityThreshold(); + if (range.min() == range.max()) { + return range.min(); + } + if (NoiseStyle.FLAT.equals(range.style().style())) { + return M.lerp(range.min(), range.max(), 0.5); + } + return range.min() + (thresholdNoise.sample(x, z) * (range.max() - range.min())); + } + double sampleDensity(int x, int y, int z) { if (hasWarp) { return sampleDensityWarped(x, y, z); @@ -98,8 +107,8 @@ public final class IrisCaveProfileSampler { } private double sampleDensityUnwarped(int x, int y, int z) { - double density = baseDensity.noiseFastSigned3D(x, y, z) * baseWeight; - density += detailDensity.noiseFastSigned3D(x, y, z) * detailWeight; + double density = baseDensity.signed(x, y, z) * baseWeight; + density += detailDensity.signed(x, y, z) * detailWeight; if (hasModules) { for (ModuleState module : modules) { if (!module.isActive(y)) { @@ -114,13 +123,13 @@ public final class IrisCaveProfileSampler { } private double sampleDensityWarped(int x, int y, int z) { - double warpA = warpDensity.noiseFastSigned3D(x, y, z); - double warpB = warpDensity.noiseFastSigned3D(x + 31.37D, y - 17.21D, z + 23.91D); + double warpA = warpDensity.signed(x, y, z); + double warpB = warpDensity.signed(x + 31.37D, y - 17.21D, z + 23.91D); double warpedX = x + (warpA * warpStrength); double warpedY = y + (warpB * warpStrength); double warpedZ = z + ((warpA - warpB) * 0.5D * warpStrength); - double density = baseDensity.noiseFastSigned3D(warpedX, warpedY, warpedZ) * baseWeight; - density += detailDensity.noiseFastSigned3D(warpedX, warpedY, warpedZ) * detailWeight; + double density = baseDensity.signed(warpedX, warpedY, warpedZ) * baseWeight; + density += detailDensity.signed(warpedX, warpedY, warpedZ) * detailWeight; if (hasModules) { for (ModuleState module : modules) { if (!module.isActive(y)) { @@ -140,18 +149,18 @@ public final class IrisCaveProfileSampler { } private static final class ModuleState { - private final CNG density; + private final NoiseSampler density; private final int minY; private final int maxY; private final double weight; private final double threshold; private final boolean invert; - private ModuleState(ResolvedCaveProfile.Module module, CNG density) { - IrisRange range = module.verticalRange(); + private ModuleState(CaveFieldModule module, NoiseSampler density) { + Range range = module.verticalRange(); this.density = density; - this.minY = (int) Math.floor(range.getMin()); - this.maxY = (int) Math.ceil(range.getMax()); + this.minY = (int) Math.floor(range.min()); + this.maxY = (int) Math.ceil(range.max()); this.weight = module.weight(); this.threshold = module.threshold(); this.invert = module.invert(); @@ -162,7 +171,7 @@ public final class IrisCaveProfileSampler { } private double sample(double x, double y, double z) { - double sampled = density.noiseFastSigned3D(x, y, z); + double sampled = density.signed(x, y, z); return invert ? (threshold - sampled) * weight : (sampled - threshold) * weight; } } diff --git a/src/main/java/art/arcane/iris/engine/object/terrain/carving/DeclaredByLevel.java b/src/main/java/art/arcane/iris/engine/object/terrain/carving/DeclaredByLevel.java new file mode 100644 index 000000000..bc0aac7af --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/object/terrain/carving/DeclaredByLevel.java @@ -0,0 +1,83 @@ +/* + * 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.object.terrain.carving; + +import com.volmit.FeatureAttachment.Target; +import com.volmit.IrisFeature; +import com.volmit.config.FeatureSettings.Entry; +import com.volmit.resource.ResourceId; +import com.volmit.world.PackWorld; + +import java.util.HashMap; +import java.util.Map; + +/** + * The settings of one type that a world's dimension, regions and biomes declare, found again by the id region and biome + * samples carry ({@code overworld:desert/dunes}), which is how the layout names the region or biome of a column. A settings + * entry names its source by kind ({@code overworld:biome/desert/dunes}), so the kind is taken off the id. + * + *

Only the regions and biomes the dimension reaches declare anything here ({@link com.volmit.config.PackSettings#declared}). + */ +public final class DeclaredByLevel { + private final F dimension; + private final Map regions; + private final Map biomes; + + private DeclaredByLevel(F dimension, Map regions, Map biomes) { + this.dimension = dimension; + this.regions = Map.copyOf(regions); + this.biomes = Map.copyOf(biomes); + } + + public static DeclaredByLevel of(PackWorld world, Class type) { + F dimension = null; + Map regions = new HashMap<>(); + Map biomes = new HashMap<>(); + for (Entry entry : world.settings().declared(type)) { + if (entry.level() == Target.DIMENSION) { + dimension = entry.value(); + } else if (entry.level() == Target.REGION) { + regions.putIfAbsent(sampleId(entry.source()), entry.value()); + } else if (entry.level() == Target.BIOME) { + biomes.putIfAbsent(sampleId(entry.source()), entry.value()); + } + } + return new DeclaredByLevel<>(dimension, regions, biomes); + } + + /** The dimension's declaration; null when it declares none. */ + public F ofDimension() { + return dimension; + } + + /** The declaration of the region with this id; null when it declares none. */ + public F ofRegion(ResourceId region) { + return regions.get(region); + } + + /** The declaration of the biome with this id; null when it declares none. */ + public F ofBiome(ResourceId biome) { + return biomes.get(biome); + } + + private static ResourceId sampleId(ResourceId source) { + String path = source.path(); + return new ResourceId(source.namespace(), path.substring(path.indexOf('/') + 1)); + } +} diff --git a/src/main/java/art/arcane/iris/engine/object/terrain/carving/DeclaredCaveProfiles.java b/src/main/java/art/arcane/iris/engine/object/terrain/carving/DeclaredCaveProfiles.java new file mode 100644 index 000000000..36431ece9 --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/object/terrain/carving/DeclaredCaveProfiles.java @@ -0,0 +1,52 @@ +/* + * 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.object.terrain.carving; + +import art.arcane.iris.builtin.carve.CaveProfile; +import com.volmit.resource.ResourceId; +import com.volmit.world.PackWorld; + +/** + * What the carve module keeps for one world: the cave profiles its dimension, regions and biomes declare ({@code caveProfile}). + * A profile that is not declared is as good as one that is not enabled, so the lookups answer null for it. + */ +public final class DeclaredCaveProfiles { + private final DeclaredByLevel declared; + + private DeclaredCaveProfiles(PackWorld world) { + this.declared = DeclaredByLevel.of(world, CaveProfile.class); + } + + /** The profiles of the world {@code world}. */ + public static DeclaredCaveProfiles of(PackWorld world) { + return world.state(DeclaredCaveProfiles.class, DeclaredCaveProfiles::new); + } + + public CaveProfile ofDimension() { + return declared.ofDimension(); + } + + public CaveProfile ofRegion(ResourceId region) { + return declared.ofRegion(region); + } + + public CaveProfile ofBiome(ResourceId biome) { + return declared.ofBiome(biome); + } +} diff --git a/src/main/java/art/arcane/iris/engine/object/terrain/carving/ResolvedCarvingEntry.java b/src/main/java/art/arcane/iris/engine/object/terrain/carving/ResolvedCarvingEntry.java index 53b3752aa..9248d49bb 100644 --- a/src/main/java/art/arcane/iris/engine/object/terrain/carving/ResolvedCarvingEntry.java +++ b/src/main/java/art/arcane/iris/engine/object/terrain/carving/ResolvedCarvingEntry.java @@ -19,21 +19,20 @@ package art.arcane.iris.engine.object.terrain.carving; import art.arcane.iris.builtin.carve.CarvingEntry; -import art.arcane.iris.core.loader.IrisData; -import art.arcane.iris.core.modules.IrisValues; import art.arcane.volmlib.util.cache.AtomicCache; -import art.arcane.iris.engine.object.noise.IrisGeneratorStyle; -import art.arcane.iris.engine.object.world.biome.IrisBiome; -import art.arcane.iris.util.project.noise.CNG; -import art.arcane.volmlib.util.math.RNG; +import com.volmit.ModuleLog; import com.volmit.config.Range; +import com.volmit.noise.NoiseSampler; +import com.volmit.resource.PackResources; +import com.volmit.resource.ResourceKey; +import com.volmit.world.PackBiome; import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; /** - * One {@link CarvingEntry} made ready for one world: the biome it names, loaded from the pack when first asked for, and the + * One {@link CarvingEntry} made ready for one world: the biome it names, found in the pack when first asked for, and the * noise that splits it into child entries, built once per seed. What the entry describes stays in the settings. */ public final class ResolvedCarvingEntry { @@ -42,13 +41,11 @@ public final class ResolvedCarvingEntry { private static final double MIN_CHILD_SCALE = 0.0001D; private final CarvingEntry settings; - private final IrisGeneratorStyle childStyle; - private final AtomicCache realBiome = new AtomicCache<>(true); - private final Map childGenerators = new ConcurrentHashMap<>(); + private final AtomicCache realBiome = new AtomicCache<>(true); + private final Map childGenerators = new ConcurrentHashMap<>(); ResolvedCarvingEntry(CarvingEntry settings) { this.settings = settings; - this.childStyle = IrisValues.generatorStyle(settings.childStyle()); } public String id() { @@ -77,25 +74,29 @@ public final class ResolvedCarvingEntry { } /** The pack biome the entry names; null when it names none or the pack has no such biome. */ - public IrisBiome realBiome(IrisData data) { + public PackBiome realBiome(PackResources resources, ModuleLog log) { return realBiome.aquire(() -> { String biomeKey = settings.biome(); if (biomeKey.isBlank()) { return null; } - return data.getBiomeLoader().load(biomeKey.trim()); + try { + return resources.find(new ResourceKey<>(resources.idOf(biomeKey.trim()), PackBiome.class)).orElse(null); + } catch (IllegalStateException unreadable) { + log.warnOnce("carving-biome:" + biomeKey, "The biome " + biomeKey + " of a carving entry cannot be loaded: " + unreadable.getMessage()); + return null; + } }); } /** The noise that picks between the entry and its children, seeded by {@code seed} and the entry's id. */ - public CNG childrenGenerator(long seed, IrisData data) { + public NoiseSampler childrenGenerator(long seed, PackResources resources) { long idHash = settings.id().trim().hashCode(); long generatorSeed = seed ^ (idHash << 32) ^ CHILD_GENERATOR_SALT; return childGenerators.computeIfAbsent(generatorSeed, key -> { double scale = Math.max(MIN_CHILD_SCALE, settings.childShrinkFactor()); - RNG random = new RNG(key); - return childStyle.create(random.nextParallelRNG(CHILD_GENERATOR_SIGNATURE), data).bake().scale(scale).bake(); + return resources.noise().sampler(settings.childStyle(), key + CHILD_GENERATOR_SIGNATURE).scaled(scale); }); } } diff --git a/src/main/java/art/arcane/iris/engine/object/terrain/carving/ResolvedCaveProfile.java b/src/main/java/art/arcane/iris/engine/object/terrain/carving/ResolvedCaveProfile.java deleted file mode 100644 index c4cdb4918..000000000 --- a/src/main/java/art/arcane/iris/engine/object/terrain/carving/ResolvedCaveProfile.java +++ /dev/null @@ -1,123 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Servers - * Copyright (c) 2026 Arcane Arts (Volmit Software) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package art.arcane.iris.engine.object.terrain.carving; - -import art.arcane.iris.builtin.carve.CaveFieldModule; -import art.arcane.iris.builtin.carve.CaveProfile; -import art.arcane.iris.core.modules.IrisValues; -import art.arcane.iris.engine.object.noise.IrisGeneratorStyle; -import art.arcane.iris.engine.object.noise.IrisStyledRange; -import art.arcane.iris.engine.object.value.IrisRange; - -import java.util.List; - -/** - * The parts of a {@link CaveProfile} that the carvers read as Iris's own noise and range types, made once per carver: - * the generator styles that build the cave fields, the ranges and the extra field modules. The carvers read these - * through Iris's generators because those keep Iris's coordinate caches and fast signed reads, which the cave - * hot paths rely on. - */ -public final class ResolvedCaveProfile { - private final IrisRange verticalRange; - private final IrisGeneratorStyle baseDensityStyle; - private final IrisGeneratorStyle detailDensityStyle; - private final IrisGeneratorStyle warpStyle; - private final IrisGeneratorStyle surfaceBreakStyle; - private final IrisStyledRange densityThreshold; - private final List modules; - - private ResolvedCaveProfile(CaveProfile settings) { - this.verticalRange = IrisValues.range(settings.verticalRange()); - this.baseDensityStyle = IrisValues.generatorStyle(settings.baseDensityStyle()); - this.detailDensityStyle = IrisValues.generatorStyle(settings.detailDensityStyle()); - this.warpStyle = IrisValues.generatorStyle(settings.warpStyle()); - this.surfaceBreakStyle = IrisValues.generatorStyle(settings.surfaceBreakStyle()); - this.densityThreshold = IrisValues.styledRange(settings.densityThreshold()); - this.modules = settings.modules().stream().map(Module::new).toList(); - } - - public static ResolvedCaveProfile of(CaveProfile settings) { - return new ResolvedCaveProfile(settings); - } - - public IrisRange verticalRange() { - return verticalRange; - } - - public IrisGeneratorStyle baseDensityStyle() { - return baseDensityStyle; - } - - public IrisGeneratorStyle detailDensityStyle() { - return detailDensityStyle; - } - - public IrisGeneratorStyle warpStyle() { - return warpStyle; - } - - public IrisGeneratorStyle surfaceBreakStyle() { - return surfaceBreakStyle; - } - - public IrisStyledRange densityThreshold() { - return densityThreshold; - } - - public List modules() { - return modules; - } - - /** One {@link CaveFieldModule} with its style and range as Iris's types. */ - public static final class Module { - private final IrisGeneratorStyle style; - private final double weight; - private final double threshold; - private final IrisRange verticalRange; - private final boolean invert; - - private Module(CaveFieldModule settings) { - this.style = IrisValues.generatorStyle(settings.style()); - this.weight = settings.weight(); - this.threshold = settings.threshold(); - this.verticalRange = IrisValues.range(settings.verticalRange()); - this.invert = settings.invert(); - } - - public IrisGeneratorStyle style() { - return style; - } - - public double weight() { - return weight; - } - - public double threshold() { - return threshold; - } - - public IrisRange verticalRange() { - return verticalRange; - } - - public boolean invert() { - return invert; - } - } -} diff --git a/src/main/java/art/arcane/iris/engine/object/terrain/floating/FloatingIslandSample.java b/src/main/java/art/arcane/iris/engine/object/terrain/floating/FloatingIslandSample.java index 668cebc73..82e2d9d63 100644 --- a/src/main/java/art/arcane/iris/engine/object/terrain/floating/FloatingIslandSample.java +++ b/src/main/java/art/arcane/iris/engine/object/terrain/floating/FloatingIslandSample.java @@ -19,7 +19,7 @@ package art.arcane.iris.engine.object.terrain.floating; import art.arcane.iris.builtin.floating.FloatingChildBiome; -import art.arcane.iris.engine.object.terrain.carving.IrisCaveProfileSampler; +import art.arcane.iris.engine.object.terrain.carving.CaveProfileSampler; import art.arcane.iris.engine.object.world.biome.IrisBiome; import art.arcane.iris.core.loader.IrisData; import art.arcane.iris.engine.framework.Engine; @@ -415,7 +415,7 @@ public final class FloatingIslandSample { CNG wallWarp = entry.getWallWarpCng(baseSeed, data); double warpAmp = Math.max(0, entry.settings().wallWarpAmplitude()); double effectiveWarpAmp = effectiveWallWarpAmplitude(warpAmp, edgeFade); - IrisCaveProfileSampler carvingProfileSampler = entry.getCarvingProfileSampler(engine, data); + CaveProfileSampler carvingProfileSampler = entry.getCarvingProfileSampler(engine, data); CNG carve = carvingProfileSampler == null && !entry.hasCarvingReference() ? entry.getCarveCng(baseSeed, data) : null; double carveThreshold = entry.settings().carveThreshold(); boolean useWarp = wallWarp != null && effectiveWarpAmp > 0; @@ -484,7 +484,7 @@ public final class FloatingIslandSample { return amplitude * fade; } - static boolean directCarveEnabled(ResolvedFloatingChild entry, IrisCaveProfileSampler carvingProfileSampler, CNG carve, double carveThreshold) { + static boolean directCarveEnabled(ResolvedFloatingChild entry, CaveProfileSampler carvingProfileSampler, CNG carve, double carveThreshold) { return carvingProfileSampler == null && (entry == null || !entry.hasCarvingReference()) && carve != null && carveThreshold < 1.0; } @@ -500,7 +500,7 @@ public final class FloatingIslandSample { }); } - static int carveSolidInterior(boolean[] solidMask, boolean[] lateralCarveMask, int botY, int wx, int wz, IrisCaveProfileSampler carve, double carveThreshold) { + static int carveSolidInterior(boolean[] solidMask, boolean[] lateralCarveMask, int botY, int wx, int wz, CaveProfileSampler carve, double carveThreshold) { return carveSolidInterior(solidMask, lateralCarveMask, botY, wx, wz, (x, y, z) -> carve.shouldCarve(x, y, z, carveThreshold)); } diff --git a/src/main/java/art/arcane/iris/engine/object/terrain/floating/ResolvedFloatingChild.java b/src/main/java/art/arcane/iris/engine/object/terrain/floating/ResolvedFloatingChild.java index f92556cd0..6949b9003 100644 --- a/src/main/java/art/arcane/iris/engine/object/terrain/floating/ResolvedFloatingChild.java +++ b/src/main/java/art/arcane/iris/engine/object/terrain/floating/ResolvedFloatingChild.java @@ -29,9 +29,8 @@ import art.arcane.iris.engine.object.noise.IrisGeneratorStyle; import art.arcane.iris.engine.object.placement.IrisObjectPlacement; import art.arcane.iris.engine.object.prefab.IrisObjectScale; import art.arcane.iris.engine.object.terrain.carving.ResolvedCarvingEntry; -import art.arcane.iris.engine.object.terrain.carving.CarvingBands; import art.arcane.iris.engine.object.terrain.carving.CarvingResolver; -import art.arcane.iris.engine.object.terrain.carving.IrisCaveProfileSampler; +import art.arcane.iris.engine.object.terrain.carving.CaveProfileSampler; import art.arcane.iris.engine.object.value.IRare; import art.arcane.iris.engine.object.world.biome.IrisBiome; import art.arcane.iris.util.project.noise.CNG; @@ -62,7 +61,7 @@ public final class ResolvedFloatingChild implements IRare { private final AtomicCache bottomCache = new AtomicCache<>(); private final AtomicCache wallWarpCache = new AtomicCache<>(); private final AtomicCache carveCache = new AtomicCache<>(); - private final AtomicCache carvingProfileSamplerCache = new AtomicCache<>(true); + private final AtomicCache carvingProfileSamplerCache = new AtomicCache<>(true); private final AtomicCache shrinkScaleCache = new AtomicCache<>(); public ResolvedFloatingChild(FloatingChildBiome settings) { @@ -132,7 +131,7 @@ public final class ResolvedFloatingChild implements IRare { return carveCache.aquire(() -> carveStyle.create(new RNG(baseSeed ^ 0xCA5EC1EE5EL), data)); } - public IrisCaveProfileSampler getCarvingProfileSampler(Engine engine, IrisData data) { + public CaveProfileSampler getCarvingProfileSampler(Engine engine, IrisData data) { if (!hasCarvingReference()) { return null; } @@ -144,7 +143,7 @@ public final class ResolvedFloatingChild implements IRare { return null; } - return new IrisCaveProfileSampler(engine, profile); + return new CaveProfileSampler(data.getPackResources().noise(), engine.getSeedManager().getCarve(), profile); }); } @@ -158,9 +157,10 @@ public final class ResolvedFloatingChild implements IRare { return null; } - ResolvedCarvingEntry entry = CarvingBands.of(engine).index().get(carving); + CarvingResolver resolver = CarvingResolver.of(engine.getGeneration().world()); + ResolvedCarvingEntry entry = resolver.index().get(carving); if (entry != null) { - return CarvingResolver.resolveEntryBiome(engine, entry); + return resolver.entryBiome(entry) == null || data.getBiomeLoader() == null ? null : data.getBiomeLoader().load(entry.biomeKey().trim()); } if (data.getBiomeLoader() == null) { diff --git a/src/main/java/art/arcane/iris/engine/object/world/dimension/IrisDimension.java b/src/main/java/art/arcane/iris/engine/object/world/dimension/IrisDimension.java index 327edb132..ace7709c7 100644 --- a/src/main/java/art/arcane/iris/engine/object/world/dimension/IrisDimension.java +++ b/src/main/java/art/arcane/iris/engine/object/world/dimension/IrisDimension.java @@ -186,8 +186,6 @@ public class IrisDimension extends IrisRegistrant { @MaxNumber(256) @Desc("Minimum air gap in blocks between the lower terrain surface and the upper terrain surface.") private int upperDimensionGap = 32; - @Desc("When true, cave carving will cut through the upper dimension terrain. When false, the upper terrain is a solid untouched mass.") - private boolean upperDimensionCarving = false; @Desc("When true, objects from the mantle (structures, trees, etc.) can be placed in the upper dimension terrain zone. When false, the upper terrain is protected from object placement.") private boolean upperDimensionObjects = false; @Desc("When true, upper-dimension objects force-place regardless of placement restrictions (slope, underwater, clamp, collisions, carving). Normal dimension objects always place first; upper objects place second and may clip or occlude lower-dimension placements when this is enabled.") @@ -245,10 +243,6 @@ public class IrisDimension extends IrisRegistrant { @ArrayType(type = String.class, min = 1) @Desc("External datapack sources owned by this dimension. Bukkit registers their resources server-wide, but Iris excludes their structure sets and definitions from generation and locate state in vanilla worlds and Iris dimensions that do not declare the same source. Editable auto-import is limited to resources supplied by the URLs declared by each Iris pack. Any registered datapack structure can be placed directly through nativeStructures without conversion. Replacing native generation requires a dimension-level structure placement with nativeSuppression set to REPLACE_SOURCE; provenance alone never disables native structures.") private KList datapackImports = new KList<>(); - @MinNumber(0) - @MaxNumber(318) - @Desc("The subterranean fluid (cave lava) layer height, in engine-local Y where 0 is the bottom of the dimension, not world Y. With the default -64..320 height, 8 means world Y -56.") - private int caveLavaHeight = 8; @RegistryListFunction(ComponentFlagFunction.class) @ArrayType(type = String.class) @Desc("Mantle passes to skip in this dimension: CARVED (caves), OBJECT (objects), FLOATING_OBJECT (objects on floating islands) or JIGSAW (structures), or the id of a pack module's mantle stage, such as example:moss/veins. A name that matches nothing is warned about and ignored.")