Merge IrisModule into module/ with its history

git-subtree-dir: module
git-subtree-mainline: 925c942764
git-subtree-split: 27b0036450
This commit is contained in:
piexel committed 2026-11-06 16:52:56 +01:00
commit 68ae3c8d3a
391 files changed
+43895

No files matched your search

@@ -0,0 +1,130 @@
/*
* Iris is a World Generator for Minecraft Servers
* Copyright (c) 2026 Arcane Arts (Volmit Software)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package art.arcane.iris.engine.actuator;
import art.arcane.iris.builtin.IrisStages;
import art.arcane.iris.builtin.decorant.DecorantSettings;
import art.arcane.iris.modules.decorant.DecorateSettings;
import art.arcane.iris.engine.decorator.BiomeDecorators;
import art.arcane.iris.engine.decorator.DecoratedBiome;
import art.arcane.iris.engine.decorator.DecorationScene;
import art.arcane.iris.engine.decorator.IrisSeaFloorDecorator;
import art.arcane.iris.engine.decorator.IrisSeaSurfaceDecorator;
import art.arcane.iris.engine.decorator.IrisShoreLineDecorator;
import art.arcane.iris.engine.decorator.IrisSurfaceDecorator;
import com.volmit.IrisModule;
import com.volmit.ModuleInfo;
import com.volmit.ModuleLifecycle;
import com.volmit.ModuleSetup;
import com.volmit.block.BlockState;
import com.volmit.config.FeatureSettings;
import com.volmit.hunk.Hunk;
import com.volmit.stage.ChunkStageContext;
import com.volmit.world.BiomeKind;
import com.volmit.world.PackWorld;
import com.volmit.world.TerrainSampler;
/**
* Module {@code iris:decorant}: the biomes' decorators ({@link DecorantSettings}), placed on the surface the mantle's
* blocks left: the surface itself, the sea surface and floor, and the shore line. A dimension turns decorating off with
* {@link DecorateSettings}. The decorators' noise is built ahead of generation, in {@link #warmUp}.
*/
public final class DecorantModule implements IrisModule, ModuleLifecycle {
private static final String VERSION = "built-in";
@Override
public ModuleInfo info() {
return ModuleInfo.of("iris:decorant", "Decorators", VERSION);
}
@Override
public void setup(ModuleSetup setup) {
// Ordering only: iris:matter ships in the built-ins jar, which a pack may not have.
setup.stages().define(IrisStages.Decorant.DECORATE).softAfter(IrisStages.Matter.INSERT).run(DecorantModule::decorate);
var registry = setup.registry();
registry.registerSettings(DecorantSettings.class);
registry.registerSettings(DecorateSettings.class);
registry.registerLifecycle(this);
}
@Override
public void warmUp(PackWorld world) {
BiomeDecorators.of(world).warm();
}
private static void decorate(ChunkStageContext context) {
if (!decorates(context)) {
return;
}
decorate(DecorationScene.of(context), context.settings(), context.originX(), context.originZ());
}
/** A dimension decorates unless it says {@code decorate: false}. */
private static boolean decorates(ChunkStageContext context) {
return context.settings().at(DecorateSettings.class, context.centreX(), context.centreZ()).dimension()
.map(DecorateSettings::decorate).orElse(true);
}
/** Decorates the 16 x 16 columns of the chunk whose first block is {@code x}, {@code z}, a biome's decorators on the surface its blocks left. */
static void decorate(DecorationScene scene, FeatureSettings settings, int x, int z) {
Hunk<BlockState> output = scene.blocks();
TerrainSampler terrain = scene.terrain();
BiomeDecorators decorators = scene.decorators();
IrisSurfaceDecorator surfaceDecorator = new IrisSurfaceDecorator(scene);
IrisSeaSurfaceDecorator seaSurfaceDecorator = new IrisSeaSurfaceDecorator(scene);
IrisSeaFloorDecorator seaFloorDecorator = new IrisSeaFloorDecorator(scene);
IrisShoreLineDecorator shoreLineDecorator = new IrisShoreLineDecorator(scene);
int fluidHeight = scene.fluidHeight();
int worldHeight = scene.worldHeight();
for (int i = 0; i < output.width(); i++) {
int realX = Math.round(x + i);
for (int j = 0; j < output.depth(); j++) {
int realZ = Math.round(z + j);
DecoratedBiome biome = BiomeDecorators.biomeOf(settings, realX, realZ, terrain.surfaceKind(realX, realZ));
if (!decorators.hasDecorators(biome)) {
continue;
}
int height = terrain.surfaceHeight(realX, realZ);
if (height >= 0 && height < fluidHeight && scene.isSolid(output.get(i, height, j))
&& height + 1 < output.height() && scene.isWater(output.get(i, height + 1, j))) {
seaSurfaceDecorator.decorate(i, j,
realX, Math.round(i + 1), Math.round(x + i - 1),
realZ, Math.round(z + j + 1), Math.round(z + j - 1),
biome, fluidHeight, worldHeight);
seaFloorDecorator.decorate(i, j,
realX, realZ, biome, height + 1,
fluidHeight + 1);
}
if (height == fluidHeight) {
shoreLineDecorator.decorate(i, j,
realX, Math.round(x + i + 1), Math.round(x + i - 1),
realZ, Math.round(z + j + 1), Math.round(z + j - 1),
biome, height, worldHeight);
}
if (height >= 0 && height < output.height()) {
surfaceDecorator.decorate(i, j, realX, realZ, biome, height, worldHeight - height);
}
}
}
}
}
@@ -0,0 +1,76 @@
/*
* Iris is a World Generator for Minecraft Servers
* Copyright (c) 2026 Arcane Arts (Volmit Software)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package art.arcane.iris.engine.actuator;
import art.arcane.iris.builtin.IrisSeedPurposes;
import art.arcane.iris.modules.terrain.OreSettings;
import art.arcane.volmlib.util.math.RNG;
import com.volmit.config.FeatureSettings.Entry;
import com.volmit.config.Level;
import com.volmit.config.SettingsStack;
import com.volmit.resource.ResourceId;
import com.volmit.world.PackWorld;
import java.util.Comparator;
import java.util.function.LongSupplier;
/**
* Builds the noise of every ore generator the world's biomes, regions and dimension declare before generation needs it.
* A generator keeps the noise of the first seed it is given, so each one is warmed with the seed of its place in
* this order: the biomes by key, the regions by key, then the dimension. The order is part of what a world generates.
*/
final class OreWarmUp {
private static final long ROOT_SEED_SALT = 7777L;
private final PackWorld world;
private final TerrainOres ores;
private final RNG root;
private int warmed;
OreWarmUp(PackWorld world) {
this(world, TerrainOres.of(world));
}
OreWarmUp(PackWorld world, TerrainOres ores) {
this.world = world;
this.ores = ores;
this.root = new RNG(world.seed(IrisSeedPurposes.COMPONENT) + ROOT_SEED_SALT);
}
void warm() {
LongSupplier seeds = () -> root.nextParallelRNG(warmed++).getSeed();
SettingsStack<OreSettings> declared = world.settings().declared(OreSettings.class);
warmLevel(declared, Level.BIOME, seeds);
warmLevel(declared, Level.REGION, seeds);
warmLevel(declared, Level.DIMENSION, seeds);
}
/** The ores of every owner at {@code level}, ordered by the key of the biome, region or dimension that declares them. */
private void warmLevel(SettingsStack<OreSettings> declared, Level level, LongSupplier seeds) {
declared.entries().stream()
.filter(entry -> entry.level() == level)
.sorted(Comparator.comparing((Entry<OreSettings> entry) -> key(entry.source())))
.forEach(entry -> ores.of(entry.value()).warm(seeds));
}
private static String key(ResourceId source) {
String path = source.path();
return path.substring(path.indexOf('/') + 1);
}
}
@@ -0,0 +1,127 @@
/*
* Iris is a World Generator for Minecraft Servers
* Copyright (c) 2026 Arcane Arts (Volmit Software)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package art.arcane.iris.engine.actuator;
import art.arcane.iris.modules.terrain.OreGenerator;
import art.arcane.volmlib.util.cache.AtomicCache;
import com.volmit.block.BlockRegistry;
import com.volmit.block.BlockSpec;
import com.volmit.block.BlockState;
import com.volmit.block.PaletteSampler;
import com.volmit.noise.NoiseFactory;
import com.volmit.noise.NoiseSampler;
import com.volmit.resource.PackResources;
import java.util.ArrayList;
import java.util.List;
/**
* One {@link OreGenerator} made ready for one world: its palette resolved to blocks and the noise that
* decides where it places ore, built from the seed it is warmed with or, when nothing warmed it, from the terrain seed
* of its first use. The palette picks with the terrain seed. What the generator describes stays in the settings;
* everything that needs the platform, the pack or the world seed is here.
*/
final class ResolvedOre {
private final OreGenerator settings;
private final NoiseFactory noise;
private final BlockRegistry blockRegistry;
private final long terrainSeed;
private final List<BlockState> blocks;
private final AtomicCache<NoiseSampler> chance = new AtomicCache<>();
private final AtomicCache<PaletteSampler> palette = new AtomicCache<>();
/**
* @param terrainSeed the seed the palette picks with, and the noise is built from when nothing warmed it first
* @param blocks the palette as the platform's blocks, each repeated by its weight
*/
ResolvedOre(OreGenerator settings, NoiseFactory noise, BlockRegistry blockRegistry, long terrainSeed, List<BlockState> blocks) {
this.settings = settings;
this.noise = noise;
this.blockRegistry = blockRegistry;
this.terrainSeed = terrainSeed;
this.blocks = List.copyOf(blocks);
}
/** {@code settings} ready for a world with {@code resources}: its blocks resolved through the pack, its picks seeded with the terrain seed. */
static ResolvedOre of(OreGenerator settings, PackResources resources, long terrainSeed) {
BlockRegistry registry = resources.blocks();
return new ResolvedOre(settings, resources.noise(), registry, terrainSeed, weighted(registry, settings.palette().palette()));
}
private static List<BlockState> weighted(BlockRegistry registry, List<BlockSpec> specs) {
List<BlockState> weighted = new ArrayList<>();
for (BlockSpec spec : specs) {
BlockState state = registry.resolve(spec);
for (int n = 0; n < spec.weight(); n++) {
weighted.add(state);
}
}
return weighted;
}
boolean generatesSurface() {
return settings.generateSurface();
}
double minY() {
return settings.range().min();
}
double maxY() {
return settings.range().max();
}
/** Builds the chance noise from {@code seed}, unless it is built already: the first seed it is given is the one it keeps. */
void warm(long seed) {
chance.aquire(() -> noise.sampler(settings.chanceStyle(), seed));
}
/** The ore block at the position, or null when the position is out of the band, the chance noise is above the threshold or the palette has no block. */
BlockState generate(int x, int y, int z) {
if (!settings.range().contains(y)) {
return null;
}
if (settings.palette().palette().isEmpty()) {
return null;
}
if (chanceNoise().sample(x, y, z) > settings.threshold()) {
return null;
}
return pick(x, y, z);
}
/** The chance noise, which this runs per block of the terrain, so a built one is read without creating a supplier. */
private NoiseSampler chanceNoise() {
NoiseSampler built = chance.getIfPresent();
if (built != null) {
return built;
}
return chance.aquire(() -> noise.sampler(settings.chanceStyle(), terrainSeed));
}
private BlockState pick(int x, int y, int z) {
if (blocks.isEmpty()) {
return null;
}
if (blocks.size() == 1) {
return blocks.getFirst();
}
PaletteSampler sampler = palette.aquire(() -> blockRegistry.palette(settings.palette(), terrainSeed));
return sampler.at(x, y, z);
}
}
@@ -0,0 +1,118 @@
/*
* Iris is a World Generator for Minecraft Servers
* Copyright (c) 2026 Arcane Arts (Volmit Software)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package art.arcane.iris.engine.actuator;
import art.arcane.iris.modules.terrain.OreGenerator;
import art.arcane.iris.modules.terrain.OreSettings;
import com.volmit.block.BlockState;
import com.volmit.resource.PackResources;
import java.util.ArrayList;
import java.util.List;
import java.util.function.LongSupplier;
/**
* The ore generators of one dimension, region or biome made ready ({@link ResolvedOre}), in the order its settings list them
* and split into the ones that also replace surface blocks and the ones that only replace rock. A level without ores is
* {@link #NONE}.
*/
final class ResolvedOres {
static final ResolvedOres NONE = new ResolvedOres(List.of());
private final List<ResolvedOre> all;
private final List<ResolvedOre> surface;
private final List<ResolvedOre> underground;
private final YBand surfaceBand;
private final YBand undergroundBand;
ResolvedOres(List<ResolvedOre> all) {
this.all = List.copyOf(all);
this.surface = this.all.stream().filter(ResolvedOre::generatesSurface).toList();
this.underground = this.all.stream().filter(ore -> !ore.generatesSurface()).toList();
this.surfaceBand = YBand.of(surface);
this.undergroundBand = YBand.of(underground);
}
/** {@code settings} ready for a world with {@code resources}; generators the pack wrote as {@code null} are left out. */
static ResolvedOres of(OreSettings settings, PackResources resources, long terrainSeed) {
List<ResolvedOre> ores = new ArrayList<>();
for (OreGenerator generator : settings.generators()) {
if (generator != null) {
ores.add(ResolvedOre.of(generator, resources, terrainSeed));
}
}
return ores.isEmpty() ? NONE : new ResolvedOres(ores);
}
/** The heights where any surface ore can generate. */
YBand surfaceBand() {
return surfaceBand;
}
/** The heights where any rock-only ore can generate. */
YBand undergroundBand() {
return undergroundBand;
}
/** Warms every ore in the order the settings list them, each with the next seed. */
void warm(LongSupplier seeds) {
for (ResolvedOre ore : all) {
ore.warm(seeds.getAsLong());
}
}
BlockState generateSurface(int x, int y, int z) {
return firstOre(surface, x, y, z);
}
BlockState generateUnderground(int x, int y, int z) {
return firstOre(underground, x, y, z);
}
private static BlockState firstOre(List<ResolvedOre> ores, int x, int y, int z) {
for (int index = 0; index < ores.size(); index++) {
BlockState ore = ores.get(index).generate(x, y, z);
if (ore != null) {
return ore;
}
}
return null;
}
/** The lowest and highest height any of a set of ores reaches; empty when there are none. */
record YBand(boolean hasOres, double min, double max) {
static final YBand EMPTY = new YBand(false, 0, 0);
static YBand of(List<ResolvedOre> ores) {
if (ores.isEmpty()) {
return EMPTY;
}
double min = Double.POSITIVE_INFINITY;
double max = Double.NEGATIVE_INFINITY;
for (ResolvedOre ore : ores) {
min = Math.min(min, ore.minY());
max = Math.max(max, ore.maxY());
}
return new YBand(true, min, max);
}
boolean contains(int y) {
return hasOres && y >= min && y <= max;
}
}
}
@@ -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 <https://www.gnu.org/licenses/>.
*/
package art.arcane.iris.engine.actuator;
import art.arcane.iris.builtin.IrisStages;
import art.arcane.iris.builtin.terrain.BedrockSettings;
import art.arcane.iris.modules.terrain.BiomePalettes;
import art.arcane.iris.modules.terrain.CaveCeilingLayersSettings;
import art.arcane.iris.modules.terrain.ExplodeBiomePaletteSizeSettings;
import art.arcane.iris.modules.terrain.ExplodeBiomePalettesSettings;
import art.arcane.iris.modules.terrain.FluidPaletteSettings;
import art.arcane.iris.modules.terrain.HideOresSettings;
import art.arcane.iris.builtin.terrain.LayersSettings;
import art.arcane.iris.modules.terrain.LockLayersMaxSettings;
import art.arcane.iris.modules.terrain.LockLayersSettings;
import art.arcane.iris.modules.terrain.OreSettings;
import art.arcane.iris.modules.terrain.RockPaletteSettings;
import art.arcane.iris.modules.terrain.SeaLayersSettings;
import art.arcane.iris.modules.terrain.SlabSettings;
import art.arcane.iris.modules.terrain.WallSettings;
import com.volmit.IrisModule;
import com.volmit.ModuleInfo;
import com.volmit.ModuleLifecycle;
import com.volmit.ModuleSetup;
import com.volmit.service.ProtectedFloor;
import com.volmit.stage.ChunkStageContext;
import com.volmit.world.PackWorld;
import art.arcane.iris.modules.terrain.TerrainPalettes;
import java.util.List;
/**
* Module {@code iris:terrain}: the chunk's ground, fluids and biome layers. Each column is filled from bedrock up
* to its height and the fluid height with its biome's layers, with ore generators of the dimension, region and
* biome replacing blocks on the way and the upper dimension's ground filled in from the top. The ore generators' noise
* and the rock and fluid palettes' noise are built ahead of generation, in {@link #warmUp}.
*/
public final class TerrainModule implements IrisModule, ModuleLifecycle {
private static final String VERSION = "built-in";
@Override
public ModuleInfo info() {
return ModuleInfo.of("iris:terrain", "Terrain", VERSION);
}
@Override
public void setup(ModuleSetup setup) {
setup.stages().define(IrisStages.Terrain.SHAPE).run(TerrainModule::shape);
var registry = setup.registry();
List.of(LayersSettings.class, SeaLayersSettings.class, CaveCeilingLayersSettings.class, SlabSettings.class,
WallSettings.class, LockLayersSettings.class, LockLayersMaxSettings.class, RockPaletteSettings.class, FluidPaletteSettings.class,
OreSettings.class, HideOresSettings.class, BedrockSettings.class, ExplodeBiomePalettesSettings.class,
ExplodeBiomePaletteSizeSettings.class).forEach(registry::registerSettings);
registry.registerService(ProtectedFloor.class, TerrainModule::protectsFloor);
registry.registerLifecycle(this);
setup.tooling().registerView(new BiomePalettes());
}
/** The bedrock row belongs to the terrain while the dimension has bedrock, as it does unless the pack says otherwise. */
private static boolean protectsFloor(PackWorld world) {
return world.settings().declared(BedrockSettings.class).dimension().map(BedrockSettings::bedrock).orElse(true);
}
@Override
public void warmUp(PackWorld world) {
TerrainPalettes.of(world).warm();
new OreWarmUp(world).warm();
}
private static void shape(ChunkStageContext context) {
TerrainShaper.of(context.world()).shape(context);
}
}
@@ -0,0 +1,61 @@
/*
* Iris is a World Generator for Minecraft Servers
* Copyright (c) 2026 Arcane Arts (Volmit Software)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package art.arcane.iris.engine.actuator;
import art.arcane.iris.builtin.IrisSeedPurposes;
import art.arcane.iris.modules.terrain.OreSettings;
import com.volmit.resource.PackResources;
import com.volmit.world.PackWorld;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
/**
* What the terrain module keeps for one world: the ore generators of its dimension, regions and biomes made ready
* ({@link ResolvedOres}), built from their {@link OreSettings} when first asked for or ahead of generation by {@link OreWarmUp}.
*/
final class TerrainOres {
private final PackResources resources;
private final long terrainSeed;
private final Map<OreSettings, ResolvedOres> resolved = new ConcurrentHashMap<>();
TerrainOres(PackWorld world) {
this.resources = world.resources();
this.terrainSeed = world.seed(IrisSeedPurposes.TERRAIN);
}
/** The ores of {@code world}. */
static TerrainOres of(PackWorld world) {
return world.state(TerrainOres.class, TerrainOres::new);
}
/**
* The ore generators {@code settings}, those a dimension, region or biome declares, make ready; {@link ResolvedOres#NONE} when it
* declares none. The terrain asks this for two owners per column, so a resolved set is read without taking the map's lock.
*/
ResolvedOres of(OreSettings settings) {
if (settings == null) {
return ResolvedOres.NONE;
}
ResolvedOres existing = resolved.get(settings);
if (existing != null) {
return existing;
}
return resolved.computeIfAbsent(settings, declared -> ResolvedOres.of(declared, resources, terrainSeed));
}
}
@@ -0,0 +1,304 @@
/*
* Iris is a World Generator for Minecraft Servers
* Copyright (c) 2026 Arcane Arts (Volmit Software)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package art.arcane.iris.engine.actuator;
import art.arcane.iris.builtin.IrisSeedPurposes;
import art.arcane.iris.builtin.terrain.BedrockSettings;
import art.arcane.iris.modules.terrain.HideOresSettings;
import art.arcane.iris.modules.terrain.OreSettings;
import art.arcane.iris.engine.actuator.ResolvedOres.YBand;
import art.arcane.iris.modules.terrain.BiomeLayers;
import art.arcane.iris.modules.terrain.ColumnSlope;
import art.arcane.iris.modules.terrain.LayeredBiome;
import art.arcane.iris.modules.terrain.PaletteExplosion;
import art.arcane.iris.modules.terrain.TerrainPalettes;
import art.arcane.volmlib.util.collection.KList;
import art.arcane.volmlib.util.math.RNG;
import com.volmit.IrisFeature;
import com.volmit.block.BlockState;
import com.volmit.config.FeatureSettings;
import com.volmit.config.Level;
import com.volmit.config.SettingsStack;
import com.volmit.hunk.Hunk;
import com.volmit.resource.ResourceId;
import com.volmit.stage.ChunkStageContext;
import com.volmit.world.PackWorld;
import com.volmit.world.TerrainSampler;
import com.volmit.world.UpperDimension;
import java.util.Optional;
import java.util.OptionalInt;
/** What shaping terrain keeps for one world: the terrain stream's random and the palettes, layers and ores the columns are filled from. */
final class TerrainShaper {
private static final BlockState BEDROCK = new BlockState("minecraft:bedrock");
private final TerrainPalettes palettes;
private final BiomeLayers layers;
private final TerrainOres ores;
private final RNG rng;
private final boolean levelsBelowTheDimensionDeclareOres;
static TerrainShaper of(PackWorld world) {
return world.state(TerrainShaper.class, TerrainShaper::new);
}
TerrainShaper(PackWorld world) {
this(world, TerrainPalettes.of(world), BiomeLayers.of(world), TerrainOres.of(world));
}
TerrainShaper(PackWorld world, TerrainPalettes palettes, BiomeLayers layers, TerrainOres ores) {
this.palettes = palettes;
this.layers = layers;
this.ores = ores;
this.rng = new RNG(world.seed(IrisSeedPurposes.TERRAIN));
this.levelsBelowTheDimensionDeclareOres = world.settings().declared(OreSettings.class).entries().stream()
.anyMatch(entry -> entry.level() != Level.DIMENSION);
}
/** Fills the 16 x 16 columns of the chunk, one slice along x at a time. */
void shape(ChunkStageContext context) {
Chunk chunk = new Chunk(context);
for (int sliceX = 0; sliceX < chunk.blocks.width(); sliceX++) {
shapeSliver(chunk, sliceX);
}
}
/** One plane from the sky to bedrock, one block thick along x. */
private void shapeSliver(Chunk chunk, int xf) {
Hunk<BlockState> h = chunk.blocks;
int chunkHeight = h.height();
int chunkDepth = h.depth();
int realX = xf + chunk.originX;
for (int zf = 0; zf < chunkDepth; zf++) {
int realZ = zf + chunk.originZ;
int he = Math.min(chunkHeight, chunk.terrain.surfaceHeight(realX, realZ));
int hf = Math.max(chunk.clampedFluidHeight, he);
if (hf < 0) {
continue;
}
int topY = Math.min(hf, chunkHeight - 1);
BlockState fluid = palettes.fluidAt(realX, realZ);
BlockState rock = palettes.rockAt(realX, realZ);
BlockState mappedSurfaceBlock = chunk.terrain.surfaceBlock(realX, realZ).orElse(null);
LayeredBiome biome = layers.biome(chunk.terrain.surfaceBiome(realX, realZ), chunk.settings);
ColumnOres columnOres = chunk.oresAt(realX, realZ);
ResolvedOres biomeOres = columnOres.biome;
ResolvedOres regionOres = columnOres.region;
YBand biomeSurfaceBand = biomeOres.surfaceBand();
YBand regionSurfaceBand = regionOres.surfaceBand();
YBand biomeUndergroundBand = biomeOres.undergroundBand();
YBand regionUndergroundBand = regionOres.undergroundBand();
ResolvedOres dimensionOres = chunk.dimensionOres;
YBand dimensionSurfaceBand = dimensionOres.surfaceBand();
YBand dimensionUndergroundBand = dimensionOres.undergroundBand();
boolean hasSurfaceOres = biomeSurfaceBand.hasOres() || regionSurfaceBand.hasOres() || dimensionSurfaceBand.hasOres();
boolean hasUndergroundOres = biomeUndergroundBand.hasOres() || regionUndergroundBand.hasOres() || dimensionUndergroundBand.hasOres();
KList<BlockState> blocks = null;
KList<BlockState> fblocks = null;
for (int i = topY; i >= 0; i--) {
if (i == 0 && chunk.bedrockEnabled) {
place(h, xf, i, zf, BEDROCK);
continue;
}
BlockState ore = null;
if (hasSurfaceOres) {
if (biomeSurfaceBand.contains(i)) {
ore = biomeOres.generateSurface(realX, i, realZ);
}
if (ore == null && regionSurfaceBand.contains(i)) {
ore = regionOres.generateSurface(realX, i, realZ);
}
if (ore == null && dimensionSurfaceBand.contains(i)) {
ore = dimensionOres.generateSurface(realX, i, realZ);
}
}
if (ore != null) {
place(h, xf, i, zf, ore);
continue;
}
if (i > he && i <= hf) {
int fdepth = hf - i;
if (fblocks == null) {
fblocks = layers.generateSeaLayers(biome, realX, realZ, rng, hf - he);
}
if (fblocks.hasIndex(fdepth)) {
place(h, xf, i, zf, fblocks.get(fdepth));
} else {
place(h, xf, i, zf, fluid);
}
continue;
}
if (i <= he) {
int depth = he - i;
if (depth == 0 && mappedSurfaceBlock != null) {
place(h, xf, i, zf, mappedSurfaceBlock);
continue;
}
if (blocks == null) {
blocks = layers.generateLayers(biome, chunk.explosion, realX, realZ, rng, he, he, chunk.slope);
}
if (blocks.hasIndex(depth)) {
place(h, xf, i, zf, blocks.get(depth));
continue;
}
if (hasUndergroundOres) {
if (biomeUndergroundBand.contains(i)) {
ore = biomeOres.generateUnderground(realX, i, realZ);
}
if (ore == null && regionUndergroundBand.contains(i)) {
ore = regionOres.generateUnderground(realX, i, realZ);
}
if (ore == null && dimensionUndergroundBand.contains(i)) {
ore = dimensionOres.generateUnderground(realX, i, realZ);
}
}
place(h, xf, i, zf, ore != null ? ore : rock);
}
}
if (chunk.upper.isPresent()) {
fillUpperDimension(chunk, chunk.upper.get(), xf, zf, realX, realZ);
}
}
}
/** The upper dimension's ground, filled in from the top of the column down to where it ends. */
private void fillUpperDimension(Chunk chunk, UpperDimension upper, int xf, int zf, int realX, int realZ) {
Hunk<BlockState> h = chunk.blocks;
int chunkHeight = h.height();
OptionalInt upperY = chunk.terrain.upperDimensionY(realX, realZ);
if (upperY.isEmpty()) {
return;
}
int upperSurfaceY = upperY.getAsInt();
if (upperSurfaceY >= chunkHeight - 1) {
return;
}
FeatureSettings upperSettings = upper.settings();
BlockState upperRock = palettes.upperRockAt(upper, realX, realZ);
BlockState upperMappedSurface = upper.surfaceBlock(realX, realZ).orElse(null);
int upperThickness = chunkHeight - 1 - upperSurfaceY;
LayeredBiome upperBiome = upperBiome(upperSettings, realX, realZ);
KList<BlockState> upperBlocks = layers.generateLayers(upperBiome, chunk.upperExplosion(upperSettings, realX, realZ),
realX, realZ, rng, upperThickness, upperThickness, chunk.slope);
for (int y = chunkHeight - 1; y >= upperSurfaceY; y--) {
if (y == chunkHeight - 1 && chunk.bedrockEnabled) {
place(h, xf, y, zf, BEDROCK);
continue;
}
if (y == upperSurfaceY && upperMappedSurface != null) {
place(h, xf, y, zf, upperMappedSurface);
continue;
}
int depthFromFace = y - upperSurfaceY;
if (upperBlocks.hasIndex(depthFromFace)) {
place(h, xf, y, zf, upperBlocks.get(depthFromFace));
} else {
place(h, xf, y, zf, upperRock);
}
}
}
/** What the biome of the upper dimension at the column declares about its layers. */
private LayeredBiome upperBiome(FeatureSettings upperSettings, int worldX, int worldZ) {
return new LayeredBiome(biomeLevel(upperSettings, art.arcane.iris.builtin.terrain.LayersSettings.class, worldX, worldZ), null, null,
biomeLevel(upperSettings, art.arcane.iris.modules.terrain.LockLayersSettings.class, worldX, worldZ),
biomeLevel(upperSettings, art.arcane.iris.modules.terrain.LockLayersMaxSettings.class, worldX, worldZ), null);
}
private static <S extends IrisFeature> S biomeLevel(FeatureSettings settings, Class<S> type, int worldX, int worldZ) {
return settings.at(type, worldX, worldZ).level(Level.BIOME).orElse(null);
}
/** A block the palette has none of leaves the column as it is. */
private static void place(Hunk<BlockState> blocks, int x, int y, int z, BlockState block) {
if (block != null) {
blocks.set(x, y, z, block);
}
}
/** The ores of a column's region and biome. */
private record ColumnOres(ResolvedOres region, ResolvedOres biome) {
static final ColumnOres NONE = new ColumnOres(ResolvedOres.NONE, ResolvedOres.NONE);
}
/** What one chunk's columns share: its views, its dimension's switches and ores. */
private final class Chunk {
final Hunk<BlockState> blocks;
final TerrainSampler terrain;
final FeatureSettings settings;
final int originX;
final int originZ;
final int clampedFluidHeight;
final boolean bedrockEnabled;
final PaletteExplosion explosion;
final ColumnSlope slope;
final Optional<UpperDimension> upper;
final ResolvedOres dimensionOres;
private final boolean hideOres;
private PaletteExplosion upperExplosion;
Chunk(ChunkStageContext context) {
this.blocks = context.blocks();
this.terrain = context.terrain();
this.settings = context.settings();
this.originX = context.originX();
this.originZ = context.originZ();
this.clampedFluidHeight = Math.min(blocks.height(), terrain.fluidHeight());
int centreX = context.centreX();
int centreZ = context.centreZ();
this.bedrockEnabled = settings.at(BedrockSettings.class, centreX, centreZ).dimension().map(BedrockSettings::bedrock).orElse(true);
this.hideOres = settings.at(HideOresSettings.class, centreX, centreZ).dimension().map(HideOresSettings::hide).orElse(false);
this.explosion = PaletteExplosion.of(settings, centreX, centreZ);
this.slope = (x, z) -> terrain.column((int) x, (int) z).slope();
this.upper = terrain.upperDimension();
// Dimension-level ore lookups are chunk-invariant; resolving them per column paid the settings lookup times 256 per chunk for a constant.
this.dimensionOres = hideOres ? ResolvedOres.NONE : ores.of(settings.at(OreSettings.class, centreX, centreZ).dimension().orElse(null));
}
/** What the upper dimension declares about exploded palettes: a setting of the dimension, so the same for every column of the chunk. */
PaletteExplosion upperExplosion(FeatureSettings upperSettings, int worldX, int worldZ) {
if (upperExplosion == null) {
upperExplosion = PaletteExplosion.of(upperSettings, worldX, worldZ);
}
return upperExplosion;
}
/** The ores of the column's region and biome; none where the levels below the dimension declare none, or the dimension hides ores. */
ColumnOres oresAt(int worldX, int worldZ) {
if (hideOres || !levelsBelowTheDimensionDeclareOres) {
return ColumnOres.NONE;
}
SettingsStack<OreSettings> declared = settings.at(OreSettings.class, worldX, worldZ);
return new ColumnOres(ores.of(declared.level(Level.REGION).orElse(null)), ores.of(declared.level(Level.BIOME).orElse(null)));
}
}
}
@@ -0,0 +1,143 @@
/*
* Iris is a World Generator for Minecraft Servers
* Copyright (c) 2026 Arcane Arts (Volmit Software)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package art.arcane.iris.engine.decorator;
import art.arcane.iris.builtin.IrisSeedPurposes;
import art.arcane.iris.builtin.decorant.DecorantSettings;
import art.arcane.iris.builtin.decorant.DecorationPart;
import art.arcane.iris.builtin.decorant.Decorator;
import com.volmit.config.FeatureSettings;
import com.volmit.ModuleLog;
import com.volmit.config.FeatureSettings.Entry;
import com.volmit.resource.PackResources;
import com.volmit.resource.ResourceId;
import com.volmit.world.PackWorld;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.EnumMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
/**
* What the decorant module keeps for one world: the decorators of its biomes made ready ({@link ResolvedDecorator}), sorted into
* the places they decorate. Built from the biomes' {@link DecorantSettings} when first asked for, or ahead of generation by
* {@link #warm()}.
*
* <p>A decorator's noise seed is a function of the world's decorator seed, its biome's key and its place in the biome's
* list, so it does not depend on which column or which warm-up reached it first.
*/
public final class BiomeDecorators {
private static final ResolvedDecorator[] NO_DECORATORS = new ResolvedDecorator[0];
private static final String BIOME_PATH_PREFIX = "biome/";
private static final long KEY_SEED_FACTOR = 0x9E3779B97F4A7C15L;
private static final long INDEX_SEED_FACTOR = 0xC2B2AE3D27D4EB4FL;
private final PackWorld world;
private final PackResources resources;
private final ModuleLog log;
private final long decoratorSeed;
private final Map<DecorantSettings, Map<DecorationPart, ResolvedDecorator[]>> decorators = new ConcurrentHashMap<>();
BiomeDecorators(PackWorld world) {
this.world = world;
this.resources = world.resources();
this.log = world.log();
this.decoratorSeed = world.seed(IrisSeedPurposes.DECORATOR);
}
/** The world's decorators, kept in its state store. */
public static BiomeDecorators of(PackWorld world) {
return world.state(BiomeDecorators.class, BiomeDecorators::new);
}
/** The key of the biome a settings entry was declared by, such as {@code desert/dunes} for {@code overworld:biome/desert/dunes}. */
public static String biomeKey(ResourceId source) {
String path = source.path();
return path.startsWith(BIOME_PATH_PREFIX) ? path.substring(BIOME_PATH_PREFIX.length()) : path;
}
/** The biome of the entry a column's settings gave, which is the column's surface biome; null when the biome declares nothing. */
public static DecoratedBiome biomeOf(FeatureSettings settings, int worldX, int worldZ, com.volmit.world.BiomeKind kind) {
List<Entry<DecorantSettings>> entries = settings.at(DecorantSettings.class, worldX, worldZ).entries();
if (entries.isEmpty()) {
return null;
}
Entry<DecorantSettings> entry = entries.getLast();
return new DecoratedBiome(biomeKey(entry.source()), entry.value(), kind);
}
/** The log of the module that decorates, which the decorators write to. */
ModuleLog log() {
return log;
}
/** Whether the biome declares any decorator. */
public boolean hasDecorators(DecoratedBiome biome) {
return biome != null && biome.settings() != null && !biome.settings().decorators().isEmpty();
}
/** The biome's decorators for {@code part}, in the order the biome lists them. */
ResolvedDecorator[] decorators(DecoratedBiome biome, DecorationPart part) {
if (biome == null || biome.settings() == null) {
return NO_DECORATORS;
}
return decorators.computeIfAbsent(biome.settings(), declared -> resolve(biome.key(), declared)).getOrDefault(part, NO_DECORATORS);
}
/** Whether the biome has a decorator for {@code part}. */
public boolean hasDecorators(DecoratedBiome biome, DecorationPart part) {
return decorators(biome, part).length > 0;
}
/** Resolves every decorator of every biome the dimension reaches and builds its noise, so that generation finds them ready. */
public void warm() {
List<Entry<DecorantSettings>> declared = new ArrayList<>(world.settings().declared(DecorantSettings.class).entries());
declared.sort(Comparator.comparing(entry -> biomeKey(entry.source())));
for (Entry<DecorantSettings> entry : declared) {
DecoratedBiome biome = new DecoratedBiome(biomeKey(entry.source()), entry.value(), null);
for (DecorationPart part : DecorationPart.values()) {
for (ResolvedDecorator decorator : decorators(biome, part)) {
decorator.warm();
}
}
}
}
private Map<DecorationPart, ResolvedDecorator[]> resolve(String biomeKey, DecorantSettings settings) {
Map<DecorationPart, List<ResolvedDecorator>> staging = new EnumMap<>(DecorationPart.class);
List<Decorator> declared = settings.decorators();
for (int index = 0; index < declared.size(); index++) {
Decorator decorator = declared.get(index);
if (decorator == null) {
continue;
}
ResolvedDecorator resolved = ResolvedDecorator.of(decorator, resources, seedOf(biomeKey, index), log, biomeKey);
staging.computeIfAbsent(decorator.partOf(), part -> new ArrayList<>()).add(resolved);
}
Map<DecorationPart, ResolvedDecorator[]> buckets = new EnumMap<>(DecorationPart.class);
staging.forEach((part, list) -> buckets.put(part, list.toArray(NO_DECORATORS)));
return buckets;
}
private long seedOf(String biomeKey, int index) {
return decoratorSeed + (biomeKey.hashCode() * KEY_SEED_FACTOR) + (index * INDEX_SEED_FACTOR);
}
}
@@ -0,0 +1,28 @@
/*
* Iris is a World Generator for Minecraft Servers
* Copyright (c) 2026 Arcane Arts (Volmit Software)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package art.arcane.iris.engine.decorator;
import art.arcane.iris.builtin.decorant.DecorantSettings;
import com.volmit.world.BiomeKind;
/**
* A biome as the decorators see it: the key the pack names it by, which seeds its decorators' noise, the decorators it declares
* (none when it declares no {@link DecorantSettings}) and what it was generated as.
*/
public record DecoratedBiome(String key, DecorantSettings settings, BiomeKind kind) {
}
@@ -0,0 +1,149 @@
/*
* Iris is a World Generator for Minecraft Servers
* Copyright (c) 2026 Arcane Arts (Volmit Software)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package art.arcane.iris.engine.decorator;
import art.arcane.iris.builtin.IrisSeedPurposes;
import com.volmit.ModuleLog;
import com.volmit.block.BlockRegistry;
import com.volmit.block.BlockState;
import com.volmit.block.BlockTrait;
import com.volmit.hunk.Hunk;
import com.volmit.mantle.Mantle;
import com.volmit.mantle.MantleLayer;
import com.volmit.stage.ChunkStageContext;
import com.volmit.world.TerrainSampler;
import java.util.EnumMap;
import java.util.IdentityHashMap;
import java.util.Map;
/**
* Everything the decorators of one chunk look at: its blocks, the blocks the mantle planned around it, the terrain, the pack's
* block rules and the biomes' decorators. A decorator places into {@link #blocks()} only. What it asks of a block is asked
* once for each distinct block instance, since a chunk holds few.
*/
public final class DecorationScene {
private final Hunk<BlockState> blocks;
private final BlockRegistry registry;
private final TerrainSampler terrain;
private final MantleLayer<BlockState> planned;
private final BiomeDecorators decorators;
private final long seed;
private final ModuleLog log;
private final Map<BlockTrait, Map<BlockState, Boolean>> traits = new EnumMap<>(BlockTrait.class);
private final Map<BlockState, Map<BlockState, Boolean>> supports = new IdentityHashMap<>();
/** The chunk of {@code context}, decorated with the world's decorators. */
public static DecorationScene of(ChunkStageContext context) {
Mantle mantle = context.mantle();
return new DecorationScene(context.blocks(),context.world().resources().blocks(), context.terrain(),
mantle == null ? null : mantle.blocks(), BiomeDecorators.of(context.world()), context.world().seed(IrisSeedPurposes.COMPONENT),
context.log());
}
public DecorationScene(Hunk<BlockState> blocks, BlockRegistry registry, TerrainSampler terrain, MantleLayer<BlockState> planned,
BiomeDecorators decorators, long seed, ModuleLog log) {
this.blocks = blocks;
this.registry = registry;
this.terrain = terrain;
this.planned = planned;
this.decorators = decorators;
this.seed = seed;
this.log = log;
}
public Hunk<BlockState> blocks() {
return blocks;
}
public BlockRegistry registry() {
return registry;
}
public TerrainSampler terrain() {
return terrain;
}
public BiomeDecorators decorators() {
return decorators;
}
/** The seed the decorators of every place draw from, each shifted by its own part. */
long seed() {
return seed;
}
ModuleLog log() {
return log;
}
/** The height of the chunk's volume. */
public int worldHeight() {
return blocks.height();
}
public int fluidHeight() {
return terrain.fluidHeight();
}
/** The slope of the terrain at the column. */
double slopeAt(int worldX, int worldZ) {
return terrain.column(worldX, worldZ).slope();
}
/** The height of the terrain at the column, rounded. */
long roundedHeightAt(int worldX, int worldZ) {
return terrain.surfaceHeight(worldX, worldZ);
}
/** The block a placement planned at the position, or air; positions the mantle does not cover read as air. */
BlockState plannedAt(int worldX, int y, int worldZ) {
if (planned == null || y < 0 || y >= worldHeight()) {
return null;
}
return planned.get(worldX, y, worldZ);
}
boolean has(BlockTrait trait, BlockState block) {
return traits.computeIfAbsent(trait, ignored -> new IdentityHashMap<>())
.computeIfAbsent(block, known -> registry.hasTrait(known, trait));
}
public boolean isAir(BlockState block) {
return has(BlockTrait.AIR, block);
}
public boolean isFluid(BlockState block) {
return has(BlockTrait.FLUID, block);
}
public boolean isSolid(BlockState block) {
return has(BlockTrait.SOLID, block);
}
public boolean isWater(BlockState block) {
return has(BlockTrait.WATER, block);
}
/** Whether {@code decoration} may stand on {@code surface}: its kind of block on that kind of block, and the surface carries a block on its top face. */
boolean canGoOn(BlockState decoration, BlockState surface) {
return supports.computeIfAbsent(decoration, ignored -> new IdentityHashMap<>())
.computeIfAbsent(surface, known -> registry.canPlaceOn(decoration, known)
&& registry.canAttach(decoration, known, com.volmit.geometry.BlockFace.UP));
}
}
@@ -0,0 +1,490 @@
/*
* Iris is a World Generator for Minecraft Servers
* Copyright (c) 2026 Arcane Arts (Volmit Software)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package art.arcane.iris.engine.decorator;
import art.arcane.iris.builtin.decorant.DecorationPart;
import art.arcane.volmlib.util.math.RNG;
import com.volmit.ModuleLog;
import com.volmit.geometry.BlockFace;
import com.volmit.block.BlockState;
import com.volmit.block.BlockTrait;
import com.volmit.hunk.Hunk;
import com.volmit.resource.ResourceId;
import java.util.List;
import java.util.Map;
final class DecoratorCore {
private static final long SEED_OFFSET = 29356788L;
private static final long PART_FACTOR = 10439677L;
private static final String HALF = "half";
private static final ResourceId WEEPING_VINES = ResourceId.parse("minecraft:weeping_vines");
private static final ResourceId WEEPING_VINES_PLANT = ResourceId.parse("minecraft:weeping_vines_plant");
private static final ResourceId TWISTING_VINES = ResourceId.parse("minecraft:twisting_vines");
private static final ResourceId TWISTING_VINES_PLANT = ResourceId.parse("minecraft:twisting_vines_plant");
private static final ResourceId POINTED_DRIPSTONE = ResourceId.parse("minecraft:pointed_dripstone");
private static final String[] DRIPSTONE_THICKNESS = {"tip", "frustum", "base"};
private static final BlockState[] DRIPSTONE_UP = dripstones("up");
private static final BlockState[] DRIPSTONE_DOWN = dripstones("down");
private static final BlockState AIR = new BlockState("minecraft:air");
/** The faces a vine can grow on, in the order Iris looks at them, with the neighbour each faces. */
private static final List<Face> FACES = List.of(new Face(BlockFace.NORTH, "north", 0, 0, -1), new Face(BlockFace.EAST, "east", 1, 0, 0),
new Face(BlockFace.SOUTH, "south", 0, 0, 1), new Face(BlockFace.WEST, "west", -1, 0, 0), new Face(BlockFace.UP, "up", 0, 1, 0),
new Face(BlockFace.DOWN, "down", 0, -1, 0));
private static final Map<BlockFace, BlockFace> OPPOSITES = Map.of(BlockFace.NORTH, BlockFace.SOUTH, BlockFace.SOUTH, BlockFace.NORTH,
BlockFace.EAST, BlockFace.WEST, BlockFace.WEST, BlockFace.EAST, BlockFace.UP, BlockFace.DOWN, BlockFace.DOWN, BlockFace.UP);
private static final int CHUNK_LAST = 15;
static final ThreadLocal<PlaceOpts> SCRATCH_OPTS = ThreadLocal.withInitial(PlaceOpts::new);
static final class PlaceOpts {
boolean caveSkipFluid;
boolean underwater;
int fluidHeight;
void reset() {
caveSkipFluid = false;
underwater = false;
fluidHeight = 0;
}
}
private record Face(BlockFace face, String property, int dx, int dy, int dz) {
}
static long partSeed(long baseSeed, int partOrdinal) {
return baseSeed + SEED_OFFSET - (partOrdinal * PART_FACTOR);
}
static long partSeed(long baseSeed, DecorationPart part) {
return partSeed(baseSeed, part.ordinal());
}
/** The decorator of {@code bucket} that decorates the column, drawing from {@code colRng} to choose between those whose chance noise passes. */
static ResolvedDecorator pickDecorator(ResolvedDecorator[] bucket, RNG colRng, double realX, double realZ, ModuleLog log) {
ResolvedDecorator picked = null;
int count = 0;
for (ResolvedDecorator d : bucket) {
try {
if (d.passesChanceGate(realX, realZ)) {
count++;
if (count == 1 || colRng.nextInt(count) == 0) {
picked = d;
}
}
} catch (Throwable e) {
log.error("A decorator failed to pick for the column", e);
}
}
return picked;
}
private static String topHalfValue(String half) {
return half.equals("upper") || half.equals("lower") ? "upper" : "top";
}
private static String bottomHalfValue(String half) {
return half.equals("upper") || half.equals("lower") ? "lower" : "bottom";
}
static void placeSurfaceSingle(ResolvedDecorator decorator, DecorationScene scene,
int x, int z, int realX, int height, int realZ,
boolean underwater, boolean caveSkipFluid) {
Hunk<BlockState> data = scene.blocks();
if (height < 0 || height >= data.height()) {
return;
}
BlockState bdx = data.get(x, height, z);
BlockState bd = decorator.pickBlock(realX, realZ);
if (!underwater && !canGoOn(scene, bd, bdx)
&& !decorator.isForcePlace() && decorator.forceBlock() == null) {
return;
}
if (decorator.forceBlock() != null) {
if (caveSkipFluid && scene.isFluid(bdx)) {
return;
}
data.set(x, height, z, fixFacesForHunk(scene, decorator.forceBlock(), x, z, realX, height, realZ));
}
if (!decorator.isForcePlace() && decorator.rejectsSurface(bdx)) {
return;
}
String half = bd == null ? null : bd.properties().get(HALF);
if (half != null) {
int lowerY = height + 1;
int upperY = height + 2;
if (!canPlaceTwoBlockPlant(scene, x, z, lowerY, upperY, caveSkipFluid)) {
return;
}
try {
BlockState upper = bd.withProperty(HALF, topHalfValue(half));
BlockState lower = fixFacesForHunk(scene,
bd.withProperty(HALF, bottomHalfValue(half)),
x, z, realX, lowerY, realZ);
data.set(x, lowerY, z, lower);
data.set(x, upperY, z, upper);
} catch (Throwable e) {
scene.log().error("Failed to place a two-block plant", e);
}
return;
}
int targetY = height + 1;
if (bd != null && targetY < data.height() && scene.isAir(data.get(x, targetY, z))) {
data.set(x, targetY, z, fixFacesForHunk(scene, bd, x, z, realX, targetY, realZ));
}
}
static void placeSingleAt(ResolvedDecorator decorator, DecorationScene scene, int x, int z,
int realX, int height, int realZ, boolean applyFixFaces) {
BlockState bd = decorator.pickBlock(realX, realZ);
if (bd == null) {
return;
}
if (applyFixFaces) {
bd = fixFacesForHunk(scene, bd, x, z, realX, height, realZ);
}
scene.blocks().set(x, height, z, bd);
}
static void placeStackUp(ResolvedDecorator decorator, DecorationScene scene, int x, int z, int realX, int realZ,
int height, int max, PlaceOpts opts) {
Hunk<BlockState> data = scene.blocks();
if (height < 0 || height >= data.height()) {
return;
}
int effectiveMax = max;
if (opts.underwater && height < opts.fluidHeight) {
effectiveMax = opts.fluidHeight;
}
int stack = computeStack(decorator, realX, realZ, effectiveMax);
if (stack == 1) {
int targetY = height + 1;
if (targetY >= data.height()) {
return;
}
BlockState existing = data.get(x, targetY, z);
if (!canReplaceStackTarget(scene, existing, opts.underwater)
|| (opts.caveSkipFluid && scene.isFluid(existing))) {
return;
}
BlockState block = decorator.pickTopBlock(realX, realZ);
if (block == null || (!opts.underwater && !canGoOn(scene, block, data.get(x, height, z)))) {
return;
}
block = stackedVineBlock(block, stack, 0);
data.set(x, targetY, z, block);
return;
}
BlockState bdx = data.get(x, height, z);
for (int i = 0; i < stack; i++) {
double threshold = ((double) i) / (stack - 1);
BlockState bd = threshold >= decorator.topThreshold()
? decorator.pickTopBlock(realX, realZ)
: decorator.pickBlock(realX, realZ);
if (bd == null) {
break;
}
if (i == 0 && !opts.underwater && !canGoOn(scene, bd, bdx)) {
break;
}
if (opts.underwater && height + 1 + i > opts.fluidHeight) {
break;
}
if (height + 1 + i >= data.height()) {
break;
}
BlockState existing = data.get(x, height + 1 + i, z);
if (!canReplaceStackTarget(scene, existing, opts.underwater)
|| (opts.caveSkipFluid && scene.isFluid(existing))) {
break;
}
if (bd.material().equals(POINTED_DRIPSTONE)) {
bd = dripstoneBlock(stack, i, DRIPSTONE_UP);
}
bd = stackedVineBlock(bd, stack, i);
data.set(x, height + 1 + i, z, bd);
}
}
static void placeStackDown(ResolvedDecorator decorator, DecorationScene scene, int x, int z, int realX, int realZ,
int height, int minHeight, int max, PlaceOpts opts) {
Hunk<BlockState> data = scene.blocks();
if (height < 0 || height >= data.height()) {
return;
}
int stack = computeStack(decorator, realX, realZ, max);
if (stack == 1) {
if (opts.caveSkipFluid && scene.isFluid(data.get(x, height, z))) {
return;
}
BlockState block = decorator.pickTopBlock(realX, realZ);
if (block == null) {
return;
}
block = stackedVineBlock(block, stack, 0);
data.set(x, height, z, fixFacesForHunk(scene, block, x, z, realX, height, realZ));
return;
}
for (int i = 0; i < stack; i++) {
int h = height - i;
if (h < 0 || h < minHeight) {
break;
}
double threshold = ((double) i) / (double) (stack - 1);
BlockState bd = threshold >= decorator.topThreshold()
? decorator.pickTopBlock(realX, realZ)
: decorator.pickBlock(realX, realZ);
if (bd == null) {
break;
}
if (bd.material().equals(POINTED_DRIPSTONE)) {
bd = dripstoneBlock(stack, i, DRIPSTONE_DOWN);
}
bd = stackedVineBlock(bd, stack, i);
if (opts.caveSkipFluid && scene.isFluid(data.get(x, h, z))) {
break;
}
data.set(x, h, z, fixFacesForHunk(scene, bd, x, z, realX, h, realZ));
}
}
static void placeFloatingSimple(ResolvedDecorator decorator, DecorationScene scene,
int xf, int zf, int realX, int realZ,
int height, int max) {
Hunk<BlockState> data = scene.blocks();
BlockState bd = decorator.pickBlock(realX, realZ);
if (bd == null) {
return;
}
String half = bd.properties().get(HALF);
if (half != null) {
int lowerY = height + 1;
int upperY = height + 2;
if (max <= 2 || !canPlaceTwoBlockPlant(scene, xf, zf, lowerY, upperY, false)) {
return;
}
try {
BlockState upper = bd.withProperty(HALF, topHalfValue(half));
BlockState lower = bd.withProperty(HALF, bottomHalfValue(half));
data.set(xf, lowerY, zf, lower);
data.set(xf, upperY, zf, upper);
} catch (Throwable e) {
scene.log().error("Failed to place a two-block plant", e);
}
return;
}
if (max > 1 && height + 1 < data.height()) {
data.set(xf, height + 1, zf, bd);
}
}
static int placeFloatingStacked(ResolvedDecorator decorator, DecorationScene scene,
int xf, int zf, int realX, int realZ,
int height, int max) {
Hunk<BlockState> data = scene.blocks();
int stack = decorator.stackHeight(realX, realZ);
if (decorator.isScaleStack()) {
stack = Math.min((int) Math.ceil((double) max * ((double) stack / 100)), decorator.absoluteMaxStack());
} else {
stack = Math.min(max, stack);
}
int placed = 0;
for (int i = 0; i < stack; i++) {
int h = height + 1 + i;
if (h >= height + max || h >= data.height()) {
break;
}
double threshold = stack == 1 ? 0.0 : ((double) i) / (stack - 1);
BlockState bd = threshold >= decorator.topThreshold()
? decorator.pickTopBlock(realX, realZ)
: decorator.pickBlock(realX, realZ);
if (bd == null) {
break;
}
bd = stackedVineBlock(bd, stack, i);
data.set(xf, h, zf, bd);
placed++;
}
return placed;
}
/**
* A vine placed at {@code x}, {@code y}, {@code z} (the chunk's local column {@code rX}, {@code rZ}) faces the neighbours that
* can hold it: the blocks the mantle planned there, else the chunk's own blocks. A vine with no such neighbour faces down,
* or up when it cannot face down. Any other block is returned as it is.
*/
static BlockState fixFacesForHunk(DecorationScene scene, BlockState b, int rX, int rZ, int x, int y, int z) {
if (b == null || !scene.has(BlockTrait.VINE, b)) {
return b;
}
Hunk<BlockState> hunk = scene.blocks();
BlockState fixed = b;
for (Face face : FACES) {
if (b.properties().containsKey(face.property())) {
fixed = fixed.withProperty(face.property(), "false");
}
}
boolean found = false;
for (Face face : FACES) {
int yy = y + face.dy();
BlockFace opposite = OPPOSITES.get(face.face());
BlockState planned = scene.plannedAt(x + face.dx(), yy, z + face.dz());
BlockState support = planned == null ? AIR : planned;
if (scene.registry().canAttach(b, support, opposite)) {
if (b.properties().containsKey(face.property())) {
found = true;
fixed = fixed.withProperty(face.property(), "true");
}
continue;
}
int xx = rX + face.dx();
int zz = rZ + face.dz();
if (xx < 0 || xx > CHUNK_LAST || zz < 0 || zz > CHUNK_LAST || yy < 0 || yy >= hunk.height()) {
continue;
}
if (scene.registry().canAttach(b, hunk.get(xx, yy, zz), opposite)) {
if (b.properties().containsKey(face.property())) {
found = true;
fixed = fixed.withProperty(face.property(), "true");
}
}
}
if (!found) {
String fallback = b.properties().containsKey("down") ? "down" : "up";
if (b.properties().containsKey(fallback)) {
fixed = fixed.withProperty(fallback, "true");
}
}
return fixed;
}
static boolean canGoOn(DecorationScene scene, BlockState decorator, BlockState surface) {
return decorator != null && surface != null && scene.canGoOn(decorator, surface);
}
static boolean isValidShorelineSupport(DecorationScene scene, ResolvedDecorator decorator, BlockState decorant, BlockState surface) {
return surface != null
&& scene.isSolid(surface)
&& (decorator.isForcePlace() || canGoOn(scene, decorant, surface));
}
static boolean canReplaceStackTarget(DecorationScene scene, BlockState state, boolean allowFluid) {
return scene.isAir(state) || allowFluid && scene.isFluid(state);
}
private static boolean canPlaceTwoBlockPlant(DecorationScene scene, int x, int z,
int lowerY, int upperY, boolean caveSkipFluid) {
Hunk<BlockState> data = scene.blocks();
if (lowerY < 0 || upperY >= data.height()) {
return false;
}
BlockState lower = data.get(x, lowerY, z);
BlockState upper = data.get(x, upperY, z);
return scene.isAir(lower) && scene.isAir(upper)
&& (!caveSkipFluid || !scene.isFluid(lower) && !scene.isFluid(upper));
}
private static int computeStack(ResolvedDecorator decorator, double realX, double realZ, int max) {
int stack = decorator.stackHeight(realX, realZ);
if (decorator.isScaleStack()) {
stack = Math.min((int) Math.ceil((double) max * ((double) stack / 100)), decorator.absoluteMaxStack());
} else {
stack = Math.min(max, stack);
}
return stack;
}
private static BlockState[] dripstones(String direction) {
BlockState[] arr = new BlockState[DRIPSTONE_THICKNESS.length];
for (int k = 0; k < arr.length; k++) {
arr[k] = BlockState.parse("minecraft:pointed_dripstone[thickness=" + DRIPSTONE_THICKNESS[k] + ",vertical_direction=" + direction + "]");
}
return arr;
}
private static BlockState dripstoneBlock(int stack, int i, BlockState[] byThickness) {
int thIdx;
if (i == stack - 1) {
thIdx = 0;
} else if (i == stack - 2) {
thIdx = 1;
} else {
thIdx = 2;
}
return byThickness[thIdx];
}
/** The key of the vine block that fills a stack of vines at {@code index}: the tip at the end, the plant before it; null for other blocks. */
static ResourceId stackedVineMaterial(BlockState state, int stack, int index) {
ResourceId material = state.material();
boolean tip = index == stack - 1;
if (material.equals(WEEPING_VINES) || material.equals(WEEPING_VINES_PLANT)) {
return tip ? WEEPING_VINES : WEEPING_VINES_PLANT;
}
if (material.equals(TWISTING_VINES) || material.equals(TWISTING_VINES_PLANT)) {
return tip ? TWISTING_VINES : TWISTING_VINES_PLANT;
}
return null;
}
private static BlockState stackedVineBlock(BlockState state, int stack, int index) {
ResourceId material = stackedVineMaterial(state, stack, index);
return material == null ? state : new BlockState(material.toString());
}
}
@@ -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 <https://www.gnu.org/licenses/>.
*/
package art.arcane.iris.engine.decorator;
import art.arcane.iris.builtin.decorant.DecorationPart;
import art.arcane.volmlib.util.math.RNG;
/*
* Floating island decoration path. Bypasses all canGoOn, slope, whitelist, and blacklist
* gating from IrisSurfaceDecorator: the island top IS the biome's designated surface by
* construction, so those material-compatibility checks are never meaningful here.
*/
public class FloatingDecorator {
public static int decorateColumn(DecorationScene scene, DecoratedBiome target, DecorationPart part,
int xf, int zf, int realX, int realZ,
int height, int max, RNG rng,
Runnable candidatesNullCallback) {
BiomeDecorators decorators = scene.decorators();
ResolvedDecorator decorator = DecoratorCore.pickDecorator(decorators.decorators(target, part), rng, realX, realZ, decorators.log());
if (decorator == null) {
candidatesNullCallback.run();
return 0;
}
if (!decorator.isStacking()) {
DecoratorCore.placeFloatingSimple(decorator, scene, xf, zf, realX, realZ, height, max);
return max > 1 ? 1 : 0;
}
return DecoratorCore.placeFloatingStacked(decorator, scene, xf, zf, realX, realZ, height, max);
}
}
@@ -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 <https://www.gnu.org/licenses/>.
*/
package art.arcane.iris.engine.decorator;
import art.arcane.iris.builtin.decorant.DecorationPart;
import art.arcane.volmlib.util.math.RNG;
public class IrisCeilingDecorator extends IrisEngineDecorator {
public IrisCeilingDecorator(DecorationScene scene) {
super(scene, DecorationPart.CEILING);
}
@Override
public void decorate(int x, int z, int realX, int realX1, int realX_1, int realZ, int realZ1, int realZ_1,
DecoratedBiome biome, int height, int max) {
boolean caveSkipFluid = IrisSurfaceDecorator.skipsFluid(biome.kind());
RNG rng = getRNG(realX, realZ);
ResolvedDecorator decorator = DecoratorCore.pickDecorator(decorators.decorators(biome, getPart()), rng, realX, realZ, decorators.log());
if (decorator == null) {
return;
}
if (!decorator.isStacking()) {
if (caveSkipFluid && scene.isFluid(scene.blocks().get(x, height, z))) {
return;
}
DecoratorCore.placeSingleAt(decorator, scene, x, z, realX, height, realZ, true);
return;
}
DecoratorCore.PlaceOpts opts = DecoratorCore.SCRATCH_OPTS.get();
opts.reset();
opts.caveSkipFluid = caveSkipFluid;
DecoratorCore.placeStackDown(decorator, scene, x, z, realX, realZ, height, 0, max, opts);
}
}
@@ -0,0 +1,63 @@
/*
* Iris is a World Generator for Minecraft Servers
* Copyright (c) 2026 Arcane Arts (Volmit Software)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package art.arcane.iris.engine.decorator;
import art.arcane.iris.builtin.decorant.DecorationPart;
import art.arcane.volmlib.util.math.RNG;
/** A decorator of one kind of place, placing into the blocks of a {@link DecorationScene}. */
public abstract class IrisEngineDecorator {
private static final long COLUMN_X_FACTOR = 29356788L;
private static final long COLUMN_Z_FACTOR = 10439677L;
private static final int X_PART_OFFSET = 6;
private static final int Z_PART_OFFSET = 1;
private final DecorationPart part;
protected final DecorationScene scene;
protected final BiomeDecorators decorators;
protected IrisEngineDecorator(DecorationScene scene, DecorationPart part) {
this.scene = scene;
this.part = part;
this.decorators = scene.decorators();
}
public DecorationPart getPart() {
return part;
}
/**
* Decorates one column. {@code x} and {@code z} are the column in the chunk, {@code realX} and {@code realZ} in the world,
* with the world columns next to it on either side; {@code height} is the Y to decorate from and {@code max} how much room
* there is.
*/
public abstract void decorate(int x, int z, int realX, int realX1, int realX_1, int realZ, int realZ1, int realZ_1,
DecoratedBiome biome, int height, int max);
/** {@link #decorate} for a decorator that looks at no neighbouring column. */
public void decorate(int x, int z, int realX, int realZ, DecoratedBiome biome, int height, int max) {
decorate(x, z, realX, realX, realX, realZ, realZ, realZ, biome, height, max);
}
protected RNG getRNG(int x, int z) {
long seed = DecoratorCore.partSeed(scene.seed(), part);
long modX = COLUMN_X_FACTOR ^ (part.ordinal() + X_PART_OFFSET);
long modZ = COLUMN_Z_FACTOR ^ (part.ordinal() + Z_PART_OFFSET);
return new RNG(x * modX + z * modZ + seed);
}
}
@@ -0,0 +1,81 @@
/*
* Iris is a World Generator for Minecraft Servers
* Copyright (c) 2026 Arcane Arts (Volmit Software)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package art.arcane.iris.engine.decorator;
import art.arcane.iris.builtin.decorant.DecorationPart;
import art.arcane.volmlib.util.math.RNG;
import com.volmit.block.BlockState;
public class IrisSeaFloorDecorator extends IrisEngineDecorator {
public IrisSeaFloorDecorator(DecorationScene scene) {
super(scene, DecorationPart.SEA_FLOOR);
}
@Override
public void decorate(int x, int z, int realX, int realX1, int realX_1, int realZ, int realZ1, int realZ_1,
DecoratedBiome biome, int height, int max) {
RNG rng = getRNG(realX, realZ);
ResolvedDecorator decorator = DecoratorCore.pickDecorator(decorators.decorators(biome, getPart()), rng, realX, realZ, decorators.log());
if (decorator == null) {
return;
}
var data = scene.blocks();
if (!decorator.isStacking()) {
if (decorator.slopeBlocks(() -> scene.slopeAt(realX, realZ))) {
return;
}
if (height >= 0 && height < scene.worldHeight()) {
place(x, height, z, decorator.blockAt(realX, height, realZ));
}
return;
}
int stack = decorator.stackHeight(realX, realZ);
if (decorator.isScaleStack()) {
stack = (int) Math.ceil((double) (max - height) * ((double) stack / 100));
} else {
stack = Math.min(stack, max - height);
}
if (stack == 1) {
place(x, height, z, decorator.topBlockAt(realX, height, realZ));
return;
}
int engineHeight = scene.worldHeight();
for (int i = 0; i < stack; i++) {
int h = height + i;
if (h > max || h > engineHeight) {
continue;
}
double threshold = ((double) i) / (stack - 1);
place(x, h, z, threshold >= decorator.topThreshold()
? decorator.topBlockAt(realX, h, realZ)
: decorator.blockAt(realX, h, realZ));
}
}
/** A block the decorator has none of leaves the water as it is. */
private void place(int x, int y, int z, BlockState block) {
if (block != null && y < scene.worldHeight()) {
scene.blocks().set(x, y, z, block);
}
}
}
@@ -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 <https://www.gnu.org/licenses/>.
*/
package art.arcane.iris.engine.decorator;
import art.arcane.iris.builtin.decorant.DecorationPart;
import art.arcane.volmlib.util.math.RNG;
import com.volmit.block.BlockState;
public class IrisSeaSurfaceDecorator extends IrisEngineDecorator {
public IrisSeaSurfaceDecorator(DecorationScene scene) {
super(scene, DecorationPart.SEA_SURFACE);
}
@Override
public void decorate(int x, int z, int realX, int realX1, int realX_1, int realZ, int realZ1, int realZ_1,
DecoratedBiome biome, int height, int max) {
RNG rng = getRNG(realX, realZ);
ResolvedDecorator decorator = DecoratorCore.pickDecorator(decorators.decorators(biome, getPart()), rng, realX, realZ, decorators.log());
if (decorator == null) {
return;
}
var data = scene.blocks();
if (!decorator.isStacking()) {
int targetY = height + 1;
if (height >= 0 && targetY < scene.worldHeight()
&& DecoratorCore.canReplaceStackTarget(scene, data.get(x, targetY, z), false)) {
BlockState block = decorator.blockAt(realX, height, realZ);
if (block != null) {
data.set(x, targetY, z, block);
}
}
return;
}
int stack = decorator.stackHeight(realX, realZ);
if (decorator.isScaleStack()) {
stack = (int) Math.ceil((double) (max - height) * ((double) stack / 100));
}
if (stack == 1) {
int targetY = height + 1;
if (targetY >= data.height() || !DecoratorCore.canReplaceStackTarget(scene, data.get(x, targetY, z), false)) {
return;
}
BlockState block = decorator.topBlockAt(realX, height, realZ);
if (block != null) {
data.set(x, targetY, z, block);
}
return;
}
int engineHeight = scene.worldHeight();
for (int i = 0; i < stack; i++) {
int h = height + i;
int targetY = h + 1;
if (h >= max || targetY >= engineHeight
|| !DecoratorCore.canReplaceStackTarget(scene, data.get(x, targetY, z), false)) {
break;
}
double threshold = ((double) i) / (stack - 1);
BlockState block = threshold >= decorator.topThreshold()
? decorator.topBlockAt(realX, h, realZ)
: decorator.blockAt(realX, h, realZ);
if (block == null) {
break;
}
data.set(x, targetY, z, block);
}
}
}
@@ -0,0 +1,114 @@
/*
* Iris is a World Generator for Minecraft Servers
* Copyright (c) 2026 Arcane Arts (Volmit Software)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package art.arcane.iris.engine.decorator;
import art.arcane.iris.builtin.decorant.DecorationPart;
import art.arcane.volmlib.util.math.RNG;
import com.volmit.block.BlockState;
public class IrisShoreLineDecorator extends IrisEngineDecorator {
public IrisShoreLineDecorator(DecorationScene scene) {
super(scene, DecorationPart.SHORE_LINE);
}
@Override
public void decorate(int x, int z, int realX, int realX1, int realX_1, int realZ, int realZ1, int realZ_1,
DecoratedBiome biome, int height, int max) {
if (height != scene.fluidHeight()) {
return;
}
double complexFluidHeight = scene.fluidHeight();
if (scene.roundedHeightAt(realX1, realZ) >= complexFluidHeight
&& scene.roundedHeightAt(realX_1, realZ) >= complexFluidHeight
&& scene.roundedHeightAt(realX, realZ1) >= complexFluidHeight
&& scene.roundedHeightAt(realX, realZ_1) >= complexFluidHeight) {
return;
}
RNG rng = getRNG(realX, realZ);
ResolvedDecorator decorator = DecoratorCore.pickDecorator(decorators.decorators(biome, getPart()), rng, realX, realZ, decorators.log());
if (decorator == null) {
return;
}
if (decorator.slopeBlocks(() -> scene.slopeAt(realX, realZ))) {
return;
}
var data = scene.blocks();
BlockState support = data.get(x, height, z);
if (support == null || !scene.isSolid(support)) {
return;
}
if (!decorator.isStacking()) {
int targetY = height + 1;
if (targetY >= data.height()
|| !DecoratorCore.canReplaceStackTarget(scene, data.get(x, targetY, z), false)) {
return;
}
BlockState block = decorator.blockAt(realX, height, realZ);
if (block != null && DecoratorCore.isValidShorelineSupport(scene, decorator, block, support)) {
data.set(x, targetY, z, block);
}
return;
}
int stack = decorator.stackHeight(realX, realZ);
if (decorator.isScaleStack()) {
stack = (int) Math.ceil((double) (max - height) * ((double) stack / 100));
} else {
stack = Math.min(max - height, stack);
}
if (stack == 1) {
int targetY = height + 1;
if (targetY >= data.height() || !DecoratorCore.canReplaceStackTarget(scene, data.get(x, targetY, z), false)) {
return;
}
BlockState block = decorator.topBlockAt(realX, height, realZ);
if (block != null && DecoratorCore.isValidShorelineSupport(scene, decorator, block, support)) {
data.set(x, targetY, z, block);
}
return;
}
for (int i = 0; i < stack; i++) {
int h = height + i;
int targetY = h + 1;
if (targetY >= data.height()
|| !DecoratorCore.canReplaceStackTarget(scene, data.get(x, targetY, z), false)) {
break;
}
double threshold = ((double) i) / (stack - 1);
BlockState block = threshold >= decorator.topThreshold()
? decorator.topBlockAt(realX, h, realZ)
: decorator.blockAt(realX, h, realZ);
if (block == null) {
break;
}
if (i == 0 && !DecoratorCore.isValidShorelineSupport(scene, decorator, block, support)) {
break;
}
data.set(x, targetY, z, block);
}
}
}
@@ -0,0 +1,71 @@
/*
* Iris is a World Generator for Minecraft Servers
* Copyright (c) 2026 Arcane Arts (Volmit Software)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package art.arcane.iris.engine.decorator;
import art.arcane.iris.builtin.decorant.DecorationPart;
import art.arcane.volmlib.util.math.RNG;
import com.volmit.world.BiomeKind;
public class IrisSurfaceDecorator extends IrisEngineDecorator {
public IrisSurfaceDecorator(DecorationScene scene) {
super(scene, DecorationPart.NONE);
}
protected boolean isSlopeValid(ResolvedDecorator decorator, int realX, int realZ) {
return !decorator.slopeBlocks(() -> scene.slopeAt(realX, realZ));
}
@Override
public void decorate(int x, int z, int realX, int realX1, int realX_1, int realZ, int realZ1, int realZ_1,
DecoratedBiome biome, int height, int max) {
BiomeKind kind = biome.kind();
int fluidHeight = scene.fluidHeight();
if (kind == BiomeKind.SHORE && height < fluidHeight) {
return;
}
boolean underwater = isUnderwater(kind, height, fluidHeight);
boolean caveSkipFluid = skipsFluid(kind);
RNG rng = getRNG(realX, realZ);
ResolvedDecorator decorator = DecoratorCore.pickDecorator(decorators.decorators(biome, getPart()), rng, realX, realZ, decorators.log());
if (decorator == null || !isSlopeValid(decorator, realX, realZ)) {
return;
}
if (decorator.isStacking()) {
DecoratorCore.PlaceOpts opts = DecoratorCore.SCRATCH_OPTS.get();
opts.reset();
opts.underwater = underwater;
opts.fluidHeight = fluidHeight;
opts.caveSkipFluid = caveSkipFluid;
DecoratorCore.placeStackUp(decorator, scene, x, z, realX, realZ, height, max, opts);
return;
}
DecoratorCore.placeSurfaceSingle(decorator, scene, x, z, realX, height, realZ, underwater, caveSkipFluid);
}
static boolean isUnderwater(BiomeKind kind, int height, int fluidHeight) {
return height < fluidHeight && kind != BiomeKind.CAVE;
}
static boolean skipsFluid(BiomeKind kind) {
return kind == BiomeKind.CAVE;
}
}
@@ -0,0 +1,279 @@
/*
* Iris is a World Generator for Minecraft Servers
* Copyright (c) 2026 Arcane Arts (Volmit Software)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package art.arcane.iris.engine.decorator;
import art.arcane.iris.builtin.decorant.DecorationPart;
import art.arcane.iris.builtin.decorant.Decorator;
import art.arcane.volmlib.util.cache.AtomicCache;
import com.volmit.ModuleLog;
import com.volmit.block.BlockRegistry;
import com.volmit.block.BlockSpec;
import com.volmit.block.BlockState;
import com.volmit.noise.NoiseFactory;
import com.volmit.noise.NoiseSampler;
import com.volmit.resource.PackResources;
import java.util.ArrayList;
import java.util.List;
import java.util.function.DoubleSupplier;
/**
* One {@link Decorator} made ready for one world: its palettes resolved to blocks, and the noise that
* decides where it places, which block of the palette it picks and how tall it stacks, built when first asked for. What
* the decorator describes stays in the settings; everything that needs the platform, the pack or the world seed is here.
*
* <p>The noise seeds are the decorator's own seed plus the same offsets Iris's decorator always used, so a decorator
* noise is a pure function of its seed.
*/
final class ResolvedDecorator {
private final Decorator settings;
private final long seed;
private final NoiseFactory noise;
private final List<BlockState> blocks;
private final List<BlockState> topBlocks;
private final BlockState[] blockArray;
private final BlockState[] topBlockArray;
private final BlockState forceBlock;
private final BlockState[] whitelist;
private final BlockState[] blacklist;
private final AtomicCache<NoiseSampler> chanceNoise = new AtomicCache<>();
private final AtomicCache<NoiseSampler> varianceNoise = new AtomicCache<>();
private final AtomicCache<NoiseSampler> heightNoise = new AtomicCache<>();
private final ModuleLog log;
private final String biomeKey;
/**
* @param blocks the palette as the platform's blocks, each repeated by its weight
* @param topBlocks the top palette the same way
* @param forceBlock the block it forces onto the surface, or null
* @param whitelist the blocks it may only be placed onto; ignored unless the decorator has a whitelist
* @param blacklist the blocks it is never placed onto; ignored unless the decorator has a blacklist
* @param log the log of the module that decorates
* @param biomeKey the key of the biome that declares the decorator, which names it in the log
*/
ResolvedDecorator(Decorator settings, long seed, NoiseFactory noise, List<BlockState> blocks, List<BlockState> topBlocks,
BlockState forceBlock, List<BlockState> whitelist, List<BlockState> blacklist,
ModuleLog log, String biomeKey) {
this.settings = settings;
this.seed = seed;
this.noise = noise;
this.blocks = List.copyOf(blocks);
this.topBlocks = List.copyOf(topBlocks);
this.blockArray = blocks.toArray(new BlockState[0]);
this.topBlockArray = topBlocks.toArray(new BlockState[0]);
this.forceBlock = forceBlock;
this.whitelist = whitelist.toArray(new BlockState[0]);
this.blacklist = blacklist.toArray(new BlockState[0]);
this.log = log;
this.biomeKey = biomeKey;
}
/** {@code settings} ready for a world with {@code resources}: its blocks resolved through the pack, its noise seeded from {@code seed}. */
static ResolvedDecorator of(Decorator settings, PackResources resources, long seed, ModuleLog log, String biomeKey) {
BlockRegistry registry = resources.blocks();
BlockState forced = settings.forceBlock().map(registry::resolve).orElse(null);
return new ResolvedDecorator(settings, seed, resources.noise(), weighted(registry, settings.palette()),
weighted(registry, settings.topPalette()), forced, each(registry, settings.whitelist()), each(registry, settings.blacklist()), log,
biomeKey);
}
private static List<BlockState> weighted(BlockRegistry registry, List<BlockSpec> palette) {
List<BlockState> weighted = new ArrayList<>();
for (BlockSpec spec : palette) {
BlockState state = registry.resolve(spec);
for (int n = 0; n < spec.weight(); n++) {
weighted.add(state);
}
}
return weighted;
}
private static List<BlockState> each(BlockRegistry registry, List<BlockSpec> palette) {
return palette.stream().map(registry::resolve).toList();
}
Decorator settings() {
return settings;
}
/** The seed the decorator's noise is built from. */
long seed() {
return seed;
}
DecorationPart part() {
return settings.partOf();
}
boolean isStacking() {
return settings.isStacking();
}
boolean isForcePlace() {
return settings.forcePlace();
}
boolean isScaleStack() {
return settings.scaleStack();
}
int absoluteMaxStack() {
return settings.absoluteMaxStack();
}
double topThreshold() {
return settings.topThreshold();
}
/** The block it forces onto the surface instead of the one found there, or null. */
BlockState forceBlock() {
return forceBlock;
}
/** Whether the terrain's slope keeps the decorator off; the slope is only worked out when the decorator limits it. */
boolean slopeBlocks(DoubleSupplier slope) {
if (settings.forcePlace() || settings.slopeCondition().isDefault()) {
return false;
}
return !settings.slopeCondition().isValid(slope.getAsDouble());
}
/** Whether the white and black lists keep the decorator off {@code surface}. */
boolean rejectsSurface(BlockState surface) {
if (settings.hasWhitelist() && !matches(whitelist, surface)) {
return true;
}
return settings.hasBlacklist() && matches(blacklist, surface);
}
private static boolean matches(BlockState[] palette, BlockState surface) {
for (BlockState state : palette) {
if (state.equals(surface)) {
return true;
}
}
return false;
}
/** How many blocks the decorator stacks at the column: the minimum, or a height between the limits drawn from its height noise. */
int stackHeight(double x, double z) {
if (settings.stackMin() == settings.stackMax()) {
return settings.stackMin();
}
double zoom = settings.heightVariance().zoom();
return fit(settings.stackMin(), settings.stackMax(), heightNoise().sample(x / zoom, z / zoom));
}
/** Whether the chance noise lets the decorator place at the column. */
boolean passesChanceGate(double x, double z) {
if (blocks.isEmpty()) {
return false;
}
return chanceNoisePlacesAt(x, z);
}
/**
* Whether the style noise stays under the chance at the column. A style without a seed divides by its zoom here on top
* of its own scale; a seeded one is read in plain blocks.
*/
private boolean chanceNoisePlacesAt(double x, double z) {
double blocksPerSample = settings.style().isSeeded() ? 1 : settings.style().zoom();
return chanceNoise().sample(x / blocksPerSample, z / blocksPerSample) <= settings.chance();
}
/** The block of the palette at the position, for decorations that fill a column block by block; null when the palette has no block. */
BlockState blockAt(double x, double y, double z) {
if (blocks.isEmpty()) {
log.warnOnce("decorator-empty:" + biomeKey, "Empty Block Data for " + biomeKey);
return null;
}
if (blocks.size() == 1) {
return blocks.get(0);
}
return blocks.get(fit(0, blocks.size() - 1, varianceNoise().sample(z, y, x))); // X and Z are switched
}
/** The top palette's block at the position, or the palette's when there is no top palette; null where the chance noise declines. */
BlockState topBlockAt(double x, double y, double z) {
if (topBlocks.isEmpty()) {
return blockAt(x, y, z);
}
if (!chanceNoisePlacesAt(x, z)) {
return null;
}
if (blocks.size() == 1) {
return topBlocks.get(0);
}
return topBlocks.get(fit(0, topBlocks.size() - 1, varianceNoise().sample(z, y, x)));
}
/** The palette's block for the column, or null when the palette has no block. */
BlockState pickBlock(double x, double z) {
return pick(blockArray, x, z);
}
/** The top palette's block for the column; the palette's when there is no top palette. */
BlockState pickTopBlock(double x, double z) {
if (topBlockArray.length == 0) {
return pickBlock(x, z);
}
return pick(topBlockArray, x, z);
}
private BlockState pick(BlockState[] palette, double x, double z) {
if (palette.length == 0) {
return null;
}
if (palette.length == 1) {
return palette[0];
}
return palette[Math.abs(fit(0, palette.length - 1, varianceNoise().sample(z, x)))];
}
/** Builds the noise now instead of when first asked for. */
void warm() {
heightNoise();
chanceNoise();
varianceNoise();
}
private NoiseSampler heightNoise() {
return heightNoise.aquireOrThrow(() -> noise.sampler(settings.heightVariance(),
seed + blocks.size() + settings.stackMax() + settings.stackMin()));
}
private NoiseSampler chanceNoise() {
return chanceNoise.aquireOrThrow(() -> noise.sampler(settings.style(), seed + blocks.size()));
}
private NoiseSampler varianceNoise() {
return varianceNoise.aquireOrThrow(() -> noise.sampler(settings.variance(), seed + blocks.size()));
}
/** The whole number between {@code min} and {@code max} that {@code fraction}, from 0 to 1, is the way along. */
private static int fit(int min, int max, double fraction) {
return (int) Math.round(min + (fraction * (max - min)));
}
}
@@ -0,0 +1,281 @@
/*
* Iris is a World Generator for Minecraft Bukkit Servers
* Copyright (c) 2022 Arcane Arts (Volmit Software)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package art.arcane.iris.engine.framework;
import art.arcane.iris.builtin.structure.NativeStructureSource;
import art.arcane.iris.builtin.structure.StructureAnchorMode;
import art.arcane.iris.builtin.structure.StructurePlacement;
import art.arcane.volmlib.util.math.RNG;
import java.util.Locale;
import java.util.Set;
import java.util.TreeSet;
public final class StructurePlacementGrid {
private static final long DENSITY_SIGNATURE = 0x6A09E667F3BCC909L;
private StructurePlacementGrid() {
}
public static boolean startsInChunk(StructurePlacement placement, int cx, int cz, long seed) {
return switch (placement.distribution()) {
case RANDOM_SPREAD -> randomSpreadStart(cx, cz, placement.spacing(), placement.separation(),
placementSalt(placement), seed);
case DENSITY -> densityStart(placement, cx, cz, seed);
case CONCENTRIC_RINGS -> concentricRingsStart(cx, cz, placement, seed);
};
}
public static RNG placementRng(StructurePlacement placement, int cx, int cz, long seed) {
return new RNG(placementSeed(placement, cx, cz, seed));
}
public static boolean randomSpreadStart(int cx, int cz, int spacing, int separation, int salt, long seed) {
int sp = Math.max(1, spacing);
int cellX = Math.floorDiv(cx, sp);
int cellZ = Math.floorDiv(cz, sp);
int[] start = randomSpreadCellChunk(cellX, cellZ, spacing, separation, salt, seed);
return start[0] == cx && start[1] == cz;
}
/**
* Returns the single {chunkX, chunkZ} that a RANDOM_SPREAD placement occupies within the given
* grid cell. This is the inverse of {@link #randomSpreadStart} and uses the identical formula, so
* a locator can jump straight to the one candidate per cell instead of testing every chunk.
*/
public static int[] randomSpreadCellChunk(int cellX, int cellZ, int spacing, int separation, int salt, long seed) {
int sp = Math.max(1, spacing);
int sep = Math.max(0, Math.min(separation, sp - 1));
RNG r = new RNG(mix(seed, cellX, cellZ, salt));
int range = Math.max(1, sp - sep);
int startCx = cellX * sp + r.nextInt(range);
int startCz = cellZ * sp + r.nextInt(range);
return new int[]{startCx, startCz};
}
public static int[] concentricRingChunk(StructurePlacement placement, int placementIndex, long seed) {
int count = Math.max(1, placement.ringCount());
if (placementIndex < 0 || placementIndex >= count) {
return null;
}
int distance = Math.max(1, placement.ringDistance());
int spread = Math.max(1, placement.ringSpread());
int ring = Math.floorDiv(placementIndex, spread) + 1;
int firstIndex = (ring - 1) * spread;
int slots = Math.min(spread, count - firstIndex);
int slot = placementIndex - firstIndex;
double slotAngle = (2.0 * Math.PI) / slots;
double offset = unitDouble(mix(seed, ring, count, placementSalt(placement))) * slotAngle;
double angle = offset + (slot * slotAngle);
long configuredRadius = (long) ring * distance;
if (configuredRadius > Integer.MAX_VALUE) {
return null;
}
int radius = (int) configuredRadius;
return new int[]{
(int) Math.round(Math.cos(angle) * radius),
(int) Math.round(Math.sin(angle) * radius)
};
}
private static boolean concentricRingsStart(int cx, int cz, StructurePlacement placement, long seed) {
if (cx == 0 && cz == 0) {
return false;
}
int distance = Math.max(1, placement.ringDistance());
int count = Math.max(1, placement.ringCount());
int spread = Math.max(1, placement.ringSpread());
double dist = Math.sqrt((double) cx * cx + (double) cz * cz);
int estimatedRing = (int) Math.round(dist / distance);
int ringCount = Math.ceilDiv(count, spread);
int firstRing = Math.max(1, estimatedRing - 1);
int lastRing = Math.min(ringCount, estimatedRing + 1);
for (int ring = firstRing; ring <= lastRing; ring++) {
int firstIndex = (ring - 1) * spread;
int slots = Math.min(spread, count - firstIndex);
if (slots <= 0) {
continue;
}
double slotAngle = (2.0 * Math.PI) / slots;
double offset = unitDouble(mix(seed, ring, count, placementSalt(placement))) * slotAngle;
double slotPosition = (Math.atan2(cz, cx) - offset) / slotAngle;
int nearestSlot = Math.floorMod((int) Math.round(slotPosition), slots);
for (int delta = -1; delta <= 1; delta++) {
int slot = Math.floorMod(nearestSlot + delta, slots);
int[] candidate = concentricRingChunk(placement, firstIndex + slot, seed);
if (candidate != null && candidate[0] == cx && candidate[1] == cz) {
return true;
}
}
}
return false;
}
private static boolean densityStart(StructurePlacement placement, int cx, int cz, long seed) {
double density = placement.density();
if (density <= 0.0) {
return false;
}
if (density >= 1.0) {
return true;
}
RNG rng = new RNG(placementSeed(placement, cx, cz, seed) ^ DENSITY_SIGNATURE);
return rng.chance(density);
}
public static long placementIdentity(StructurePlacement placement) {
long signature = 1469598103934665603L;
signature = appendLong(signature, placement.distribution().ordinal());
signature = appendLong(signature, placement.salt());
String placementId = placement.placementId();
if (placementId != null && !placementId.isBlank()) {
signature = appendLong(signature, 1L);
signature = appendSignature(signature, placementId.trim());
} else {
signature = appendLong(signature, 0L);
signature = appendLong(signature, placement.spacing());
signature = appendLong(signature, placement.separation());
signature = appendLong(signature, Double.doubleToLongBits(placement.density()));
signature = appendLong(signature, placement.ringCount());
signature = appendLong(signature, placement.ringDistance());
signature = appendLong(signature, placement.ringSpread());
signature = appendLong(signature, placement.minHeight());
signature = appendLong(signature, placement.maxHeight());
signature = appendLong(signature, placement.underground() ? 1L : 0L);
signature = appendLong(signature, placement.underwater() ? 1L : 0L);
signature = appendSources(signature, placement);
signature = appendAnchor(signature, placement);
}
return signature;
}
private static long placementSeed(StructurePlacement placement, int cx, int cz, long seed) {
long signature = placementIdentity(placement);
int identitySalt = (int) (signature ^ (signature >>> 32));
return mix(seed ^ signature, cx, cz, placementSalt(placement) ^ identitySalt);
}
private static long appendSignature(long signature, String value) {
long result = appendLong(signature, value.length());
for (int index = 0; index < value.length(); index++) {
result = (result ^ value.charAt(index)) * 1099511628211L;
}
return result;
}
private static long appendLong(long signature, long value) {
long result = signature;
long remaining = value;
for (int index = 0; index < Long.BYTES; index++) {
result = (result ^ (remaining & 0xffL)) * 1099511628211L;
remaining >>>= Byte.SIZE;
}
return result;
}
private static long appendSources(long signature, StructurePlacement placement) {
long result = signature;
if (placement.hasIrisStructures()) {
result = appendLong(result, 1L);
result = appendLong(result, placement.structures().size());
for (String key : placement.structures()) {
result = appendSignature(result, key == null ? "" : key);
}
return result;
}
result = appendLong(result, 2L);
result = appendLong(result, placement.nativeStructures().size());
for (NativeStructureSource source : placement.nativeStructures()) {
if (source == null) {
result = appendSignature(result, "");
result = appendLong(result, 0L);
continue;
}
result = appendSignature(result,
source.structure() == null ? "" : source.structure());
result = appendLong(result, source.weight());
}
return result;
}
private static long appendAnchor(long signature, StructurePlacement placement) {
StructureAnchorMode anchor = placement.anchor();
if (anchor == StructureAnchorMode.LEGACY) {
return signature;
}
long result = appendLong(signature, 0x4A49475341574C41L);
result = appendLong(result, anchor.ordinal());
if (!anchor.isCave()) {
return result;
}
result = appendLong(result, placement.caveAnchorAttempts());
result = appendLong(result, placement.caveAnchorScanStep());
result = appendLong(result, placement.caveMinimumClearance());
Set<String> biomes = new TreeSet<>();
for (String biome : placement.caveBiomes()) {
if (biome != null && !biome.isBlank()) {
biomes.add(biome.trim().toLowerCase(Locale.ROOT));
}
}
result = appendLong(result, biomes.size());
for (String biome : biomes) {
result = appendSignature(result, biome);
}
return result;
}
static int placementSalt(StructurePlacement placement) {
String placementId = placement.placementId();
long identity;
if (placementId != null && !placementId.isBlank()) {
identity = appendSignature(1469598103934665603L, placementId.trim());
} else {
identity = 1469598103934665603L;
identity = appendLong(identity, placement.distribution().ordinal());
identity = appendLong(identity, placement.spacing());
identity = appendLong(identity, placement.separation());
identity = appendLong(identity, Double.doubleToLongBits(placement.density()));
identity = appendLong(identity, placement.ringCount());
identity = appendLong(identity, placement.ringDistance());
identity = appendLong(identity, placement.ringSpread());
identity = appendLong(identity, placement.minHeight());
identity = appendLong(identity, placement.maxHeight());
identity = appendLong(identity, placement.underground() ? 1L : 0L);
identity = appendLong(identity, placement.underwater() ? 1L : 0L);
identity = appendSources(identity, placement);
identity = appendAnchor(identity, placement);
}
return placement.salt() ^ (int) (identity ^ (identity >>> 32));
}
private static double unitDouble(long value) {
return (value >>> 11) * 0x1.0p-53;
}
public static long mix(long seed, int a, int b, int salt) {
long h = seed;
h = h * 6364136223846793005L + (a * 341873128712L);
h = h * 6364136223846793005L + (b * 132897987541L);
h = h * 6364136223846793005L + salt;
h ^= (h >>> 33);
h *= 0xff51afd7ed558ccdL;
h ^= (h >>> 33);
return h;
}
}
@@ -0,0 +1,51 @@
/*
* Iris is a World Generator for Minecraft Servers
* Copyright (c) 2026 Arcane Arts (Volmit Software)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package art.arcane.iris.engine.framework;
public final class StructureVerticalBounds {
private StructureVerticalBounds() {
}
public static int clampOffset(
int structureMinY,
int structureMaxY,
int requestedOffset,
int worldMinY,
int worldMaxYExclusive
) {
if (structureMaxY < structureMinY) {
throw new IllegalArgumentException("Structure maximum Y cannot be below its minimum Y");
}
if (worldMaxYExclusive <= worldMinY) {
throw new IllegalArgumentException("World maximum Y must be above its minimum Y");
}
long structureHeight = (long) structureMaxY - structureMinY + 1L;
long worldHeight = (long) worldMaxYExclusive - worldMinY;
if (structureHeight > worldHeight) {
throw new IllegalArgumentException("Structure height " + structureHeight
+ " exceeds writable world height " + worldHeight);
}
long minimumOffset = (long) worldMinY - structureMinY;
long maximumOffset = (long) worldMaxYExclusive - 1L - structureMaxY;
long clamped = Math.max(minimumOffset, Math.min(maximumOffset, (long) requestedOffset));
return Math.toIntExact(clamped);
}
}
@@ -0,0 +1,113 @@
/*
* Iris is a World Generator for Minecraft Servers
* Copyright (c) 2026 Arcane Arts (Volmit Software)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package art.arcane.iris.engine.framework.structure;
import art.arcane.iris.builtin.RegistryKeyFamily;
import art.arcane.iris.builtin.structure.StructureAdjustment;
import art.arcane.iris.builtin.structure.StructureSetFrequency;
import art.arcane.iris.builtin.structure.StructureSettings;
import com.volmit.config.PackSettings;
import com.volmit.resource.ResourceId;
import com.volmit.vanilla.VanillaStructureSetup;
import java.util.List;
import java.util.Locale;
import java.util.Optional;
/**
* What a dimension's {@link StructureSettings} say about the platform's own structures: which ones it disables, how
* the starts of the others are adjusted, and how the platform sets them up. Keys match ignoring case and surrounding
* space; a family pattern also matches the keys it starts at a namespace, slash or underscore boundary
* ({@link RegistryKeyFamily}).
*/
public final class ImportedStructures {
private final StructureSettings settings;
public ImportedStructures(StructureSettings settings) {
this.settings = settings;
}
/** The settings the dimension of {@code settings} declares, or the defaults when it declares none. */
public static ImportedStructures of(PackSettings settings) {
return new ImportedStructures(settings.declared(StructureSettings.class).dimension().orElseGet(StructureSettings::new));
}
/** Whether the dimension disables the platform structure {@code key}, by family or by its exact key. */
public boolean disables(String key) {
String normalizedKey = normalize(key);
if (normalizedKey.isEmpty()) {
return false;
}
return settings.disabled().stream().anyMatch(pattern -> RegistryKeyFamily.matches(pattern, key))
|| settings.disabledExact().stream().map(ImportedStructures::normalize)
.anyMatch(exact -> !exact.isEmpty() && exact.equals(normalizedKey));
}
/**
* How the platform's own starts of {@code key} are adjusted: the underground shift for underground steps, then every
* matching adjustment in the order the pack lists them.
*/
public NativeStructureFit adjustment(String key, boolean underground) {
NativeStructureFit adjustment = NativeStructureFit.NONE.shifted(underground ? settings.undergroundYShift() : 0);
for (StructureAdjustment entry : settings.adjustments()) {
if (entry != null && matchesAny(entry.match(), key)) {
adjustment = adjustment.then(asAdjustment(entry));
}
}
return adjustment;
}
/**
* The structure set frequencies the dimension changes and whether it keeps data packs off the platform's definitions.
* An override naming no namespaced key can match no registered set and is left out.
*/
public VanillaStructureSetup setup() {
VanillaStructureSetup setup = settings.datapackOverrides()
? VanillaStructureSetup.UNCHANGED
: VanillaStructureSetup.UNCHANGED.protectingVanillaDefinitions();
for (StructureSetFrequency override : settings.frequencyOverrides()) {
Optional<ResourceId> structureSet = override == null ? Optional.empty() : structureSetId(override.structureSet());
if (structureSet.isPresent()) {
setup = setup.withFrequency(structureSet.get(), override.multiplier());
}
}
return setup;
}
private static Optional<ResourceId> structureSetId(String key) {
try {
return Optional.of(ResourceId.parse(normalize(key)));
} catch (IllegalArgumentException notAnId) {
return Optional.empty();
}
}
private static boolean matchesAny(List<String> patterns, String key) {
return patterns.stream().anyMatch(pattern -> RegistryKeyFamily.matches(pattern, key));
}
private static NativeStructureFit asAdjustment(StructureAdjustment entry) {
return new NativeStructureFit(entry.yShift(), entry.yBand().orElse(null), entry.preserveSourceY(),
entry.stilt().orElse(null), entry.terrain().orElse(null));
}
private static String normalize(String key) {
return key == null ? "" : key.trim().toLowerCase(Locale.ROOT);
}
}
@@ -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 <https://www.gnu.org/licenses/>.
*/
package art.arcane.iris.engine.framework.structure;
import art.arcane.iris.builtin.structure.StructureStilts;
import art.arcane.iris.builtin.structure.StructureTerrain;
import art.arcane.iris.builtin.structure.StructureYBand;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.volmit.vanilla.StartMemo;
/**
* How {@code iris:structure} places and fits one platform structure, or one start: how far it moves the platform's own
* starts and into which band of world heights, whether they keep the platform's height, the foundation columns built
* under their pieces and how they meet the terrain. A start the module places itself carries its fit as a memo, one
* JSON object of its terrain and stilts, which the host keeps with the start, so its later chunks use the fit it began with.
*
* @param yBand null for no band
* @param stilts null for no foundation columns
* @param terrain null for the structure's own terrain adaptation (SOURCE)
*/
public record NativeStructureFit(int yShift, StructureYBand yBand, boolean keepsSourceY, StructureStilts stilts,
StructureTerrain terrain) {
/** The platform's starts as the platform makes them. */
public static final NativeStructureFit NONE = new NativeStructureFit(0, null, false, null, null);
private static final Gson MEMO_JSON = new Gson();
private static final String MEMO_TERRAIN = "terrain";
private static final String MEMO_STILTS = "stilts";
/** The fit a start's memo records: its terrain and stilts, with no vertical adjustment. */
public static NativeStructureFit of(StartMemo memo) {
JsonObject text = MEMO_JSON.fromJson(memo.text(), JsonObject.class);
if (text == null || !text.has(MEMO_TERRAIN)) {
throw new IllegalStateException("A start's memo has no terrain fit: " + memo);
}
StructureTerrain terrain = MEMO_JSON.fromJson(text.get(MEMO_TERRAIN), StructureTerrain.class);
StructureStilts stilts = text.has(MEMO_STILTS) ? MEMO_JSON.fromJson(text.get(MEMO_STILTS), StructureStilts.class) : null;
return new NativeStructureFit(0, null, false, stilts, terrain);
}
/** The memo of a start placed with this fit's terrain and stilts: one JSON object holding both. */
public StartMemo memo() {
JsonObject text = new JsonObject();
text.add(MEMO_TERRAIN, MEMO_JSON.toJsonTree(resolvedTerrain()));
if (stilts != null) {
text.add(MEMO_STILTS, MEMO_JSON.toJsonTree(stilts));
}
return new StartMemo(MEMO_JSON.toJson(text));
}
/** The terrain fitting; the structure's own adaptation (SOURCE) when none is set. */
public StructureTerrain resolvedTerrain() {
return terrain == null ? new StructureTerrain() : terrain;
}
public NativeStructureFit shifted(int blocks) {
return new NativeStructureFit(Math.addExact(yShift, blocks), yBand, keepsSourceY, stilts, terrain);
}
/**
* Both fits, {@code later} after this one: shifts add up, keeping the platform's height sticks, and a band, stilts
* or terrain {@code later} states replaces this one's.
*/
public NativeStructureFit then(NativeStructureFit later) {
return new NativeStructureFit(Math.addExact(yShift, later.yShift),
later.yBand == null ? yBand : later.yBand,
keepsSourceY || later.keepsSourceY,
later.stilts == null ? stilts : later.stilts,
later.terrain == null ? terrain : later.terrain);
}
}
@@ -0,0 +1,17 @@
package art.arcane.iris.engine.framework.structure;
public enum StructureAssemblyStatus {
COMPLETE,
INTENTIONAL_EMPTY,
FAILED_UNCAPPED,
FAILED_RULES,
HARD_CAP;
public boolean isComplete() {
return this == COMPLETE || this == INTENTIONAL_EMPTY;
}
public boolean isFailure() {
return !isComplete();
}
}
@@ -0,0 +1,30 @@
package art.arcane.iris.engine.framework.structure;
import java.util.List;
import java.util.Objects;
public record StructureGraphAssemblySample(long seed, Outcome outcome) {
public record Outcome(
List<String> pieceKeys,
StructureAssemblyStatus status,
String detail
) {
public Outcome {
pieceKeys = List.copyOf(Objects.requireNonNull(pieceKeys));
status = Objects.requireNonNull(status);
detail = Objects.requireNonNull(detail);
}
public boolean pieceCapReached() {
return status == StructureAssemblyStatus.HARD_CAP;
}
public boolean intentionalEmpty() {
return status == StructureAssemblyStatus.INTENTIONAL_EMPTY;
}
public boolean isComplete() {
return status.isComplete();
}
}
}
@@ -0,0 +1,67 @@
package art.arcane.iris.engine.framework.structure;
import java.util.Objects;
public record StructureGraphDiagnostic(Code code, String message) {
public StructureGraphDiagnostic {
Objects.requireNonNull(code);
Objects.requireNonNull(message);
}
public Severity severity() {
return code.severity();
}
public enum Severity {
ERROR,
WARNING
}
public enum Code {
MISSING_START_POOL(Severity.ERROR),
EMPTY_START_POOL(Severity.ERROR),
MISSING_POOL(Severity.ERROR),
INVALID_MAX_DEPTH(Severity.ERROR),
INVALID_MAX_SIZE(Severity.ERROR),
INVALID_POOL_ENTRY(Severity.ERROR),
INVALID_WEIGHT(Severity.ERROR),
INVALID_CHANCE(Severity.ERROR),
INVALID_THEME(Severity.ERROR),
INVALID_PIECE_RULE(Severity.ERROR),
UNSATISFIABLE_PIECE_RULE(Severity.ERROR),
MISSING_REQUIRED_FALLBACK(Severity.ERROR),
NO_REQUIRED_TERMINAL(Severity.ERROR),
NON_PORTABLE_METADATA(Severity.ERROR),
MISSING_PIECE(Severity.ERROR),
MISSING_OBJECT(Severity.ERROR),
INVALID_OBJECT_BOUNDS(Severity.ERROR),
INVALID_CONNECTOR(Severity.ERROR),
INVALID_CONNECTOR_METADATA(Severity.ERROR),
INVALID_CONNECTOR_POSITION(Severity.ERROR),
INVALID_CONNECTOR_DIRECTION(Severity.ERROR),
INVALID_PLANAR_CELL_SIZE(Severity.ERROR),
INVALID_PLANAR_WORKCELL(Severity.ERROR),
INVALID_PLANAR_OBJECT_SIZE(Severity.ERROR),
INVALID_PLANAR_CONNECTOR(Severity.ERROR),
NON_PORTABLE_CONNECTOR(Severity.ERROR),
MISSING_CONNECTOR_POOL(Severity.ERROR),
FALLBACK_CYCLE(Severity.ERROR),
NO_ENABLED_START_PIECE(Severity.ERROR),
NO_VIABLE_START_PIECE(Severity.WARNING),
NO_COMPATIBLE_CONNECTOR(Severity.WARNING),
UNREACHABLE_POOL(Severity.WARNING),
UNREACHABLE_PIECE(Severity.WARNING),
ASSEMBLY_RUNTIME_FAILURE(Severity.ERROR),
ASSEMBLY_PIECE_CAP_REACHED(Severity.WARNING);
private final Severity severity;
Code(Severity severity) {
this.severity = severity;
}
public Severity severity() {
return severity;
}
}
}
@@ -0,0 +1,11 @@
package art.arcane.iris.engine.framework.structure;
public final class StructureGraphValidationException extends IllegalArgumentException {
public StructureGraphValidationException(String message) {
super(message);
}
public StructureGraphValidationException(String message, Throwable cause) {
super(message, cause);
}
}
@@ -0,0 +1,92 @@
/*
* Iris is a World Generator for Minecraft Servers
* Copyright (c) 2026 Arcane Arts (Volmit Software)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package art.arcane.iris.engine.framework.structure;
import art.arcane.iris.engine.object.structure.IrisStructure;
import art.arcane.iris.engine.object.structure.jigsaw.IrisJigsawPiece;
import art.arcane.iris.engine.object.structure.jigsaw.IrisJigsawPool;
import com.volmit.resource.PackResources;
import com.volmit.resource.ResourceId;
import com.volmit.resource.ResourceKind;
import java.util.List;
/**
* The resource kinds of {@code iris:structure}, which keep the folders and files Iris packs have always used, and
* lookups by pack key for code that names structures, pools and pieces by key. Every lookup goes through the pack's
* {@link PackResources}, so it sees the pack's current snapshot: a hotload, or a tool that rewrote the files and asked
* for a new snapshot, reads them again.
* <p>
* Lookups answer null for a blank key, a key the pack has no file for, and a file that fails to load, which was
* reported when it was read.
*/
public final class StructureResources {
/** Jigsaw structures, in {@code structures/}. */
public static final ResourceKind<IrisStructure> STRUCTURES = ResourceKind.of("iris:structure/structure", "structures", IrisStructure.class);
/** Jigsaw pools a structure starts from and connectors lead to, in {@code jigsaw-pools/}. */
public static final ResourceKind<IrisJigsawPool> POOLS = ResourceKind.of("iris:structure/pool", "jigsaw-pools", IrisJigsawPool.class);
/** Jigsaw pieces pools hold, each an object with connectors, in {@code jigsaw-pieces/}. */
public static final ResourceKind<IrisJigsawPiece> PIECES = ResourceKind.of("iris:structure/piece", "jigsaw-pieces", IrisJigsawPiece.class);
private StructureResources() {
}
/** Every resource kind of the structure model. */
public static List<ResourceKind<?>> kinds() {
return List.of(STRUCTURES, POOLS, PIECES);
}
public static IrisStructure structure(PackResources pack, String key) {
return find(pack, STRUCTURES, key);
}
public static IrisJigsawPool pool(PackResources pack, String key) {
return find(pack, POOLS, key);
}
public static IrisJigsawPiece piece(PackResources pack, String key) {
return find(pack, PIECES, key);
}
/** The key of every structure of the pack snapshot {@code pack}, in key order. */
public static List<String> structureKeys(PackResources pack) {
return keys(pack, STRUCTURES);
}
/** The key of every jigsaw piece of the pack snapshot {@code pack}, in key order. */
public static List<String> pieceKeys(PackResources pack) {
return keys(pack, PIECES);
}
private static <T> T find(PackResources pack, ResourceKind<T> kind, String key) {
if (key == null || key.isBlank()) {
return null;
}
try {
return pack.find(kind, pack.idOf(key)).orElse(null);
} catch (IllegalStateException failedToLoad) {
return null;
}
}
/** A key's id has the key as its path, so the path names the resource again wherever a key is expected. */
private static List<String> keys(PackResources pack, ResourceKind<?> kind) {
return pack.ids(kind).stream().map(ResourceId::path).toList();
}
}
@@ -0,0 +1,75 @@
/*
* Iris is a World Generator for Minecraft Servers
* Copyright (c) 2026 Arcane Arts (Volmit Software)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package art.arcane.iris.engine.framework.structure.fit;
import com.volmit.geometry.BlockBox;
/** A box of world blocks, every bound inclusive and Y in world heights, the way the platform's structures measure. */
record Box(int minX, int minY, int minZ, int maxX, int maxY, int maxZ) {
/** {@code box}, an API box above the dimension's bottom with exclusive maxima, in world heights. */
static Box of(BlockBox box, int bottomY) {
return new Box(box.minX(), box.minY() + bottomY, box.minZ(),
box.maxX() - 1, box.maxY() - 1 + bottomY, box.maxZ() - 1);
}
/** This box as an API box above the dimension's bottom. */
BlockBox toApi(int bottomY) {
return new BlockBox(minX, minY - bottomY, minZ, maxX + 1, maxY + 1 - bottomY, maxZ + 1);
}
int xSpan() {
return maxX - minX + 1;
}
int ySpan() {
return maxY - minY + 1;
}
int zSpan() {
return maxZ - minZ + 1;
}
boolean contains(int x, int y, int z) {
return x >= minX && x <= maxX && y >= minY && y <= maxY && z >= minZ && z <= maxZ;
}
boolean intersects(Box other) {
return maxX >= other.minX && minX <= other.maxX && maxY >= other.minY && minY <= other.maxY
&& maxZ >= other.minZ && minZ <= other.maxZ;
}
boolean intersectsHorizontally(Box other) {
return maxX >= other.minX && minX <= other.maxX && maxZ >= other.minZ && minZ <= other.maxZ;
}
/** This box grown by {@code blocks} sideways, keeping its heights. */
Box widened(int blocks) {
return new Box(minX - blocks, minY, minZ - blocks, maxX + blocks, maxY, maxZ + blocks);
}
Box encapsulating(Box other) {
return new Box(Math.min(minX, other.minX), Math.min(minY, other.minY), Math.min(minZ, other.minZ),
Math.max(maxX, other.maxX), Math.max(maxY, other.maxY), Math.max(maxZ, other.maxZ));
}
/** The column index of a block of this box's columns, rows along X. */
int columnIndex(int x, int z) {
return (z - minZ) * xSpan() + x - minX;
}
}
@@ -0,0 +1,112 @@
/*
* Iris is a World Generator for Minecraft Servers
* Copyright (c) 2026 Arcane Arts (Volmit Software)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package art.arcane.iris.engine.framework.structure.fit;
import com.volmit.geometry.BlockFace;
import com.volmit.block.BlockState;
import com.volmit.block.BlockTrait;
import com.volmit.resource.ResourceId;
import com.volmit.world.BlockAccess;
/**
* The chunk's live blocks in world heights, and the block questions the structure fit asks. The fit's rules were
* written in world heights (deepslate below 0, bands of world Y, noise sampled at world heights), so it keeps them and
* converts here.
*/
final class FitBlocks {
static final BlockState AIR = new BlockState("minecraft:air");
static final BlockState STONE = new BlockState("minecraft:stone");
static final BlockState COBBLESTONE = new BlockState("minecraft:cobblestone");
private static final ResourceId STRUCTURE_VOID = ResourceId.parse("minecraft:structure_void");
private static final ResourceId JIGSAW = ResourceId.parse("minecraft:jigsaw");
private static final ResourceId LOGS_TAG = ResourceId.parse("minecraft:logs");
private static final ResourceId LEAVES_TAG = ResourceId.parse("minecraft:leaves");
private final BlockAccess access;
private final int bottomY;
FitBlocks(BlockAccess access, int bottomY) {
this.access = access;
this.bottomY = bottomY;
}
int bottomY() {
return bottomY;
}
BlockState get(int x, int y, int z) {
return access.get(x, y - bottomY, z);
}
void set(int x, int y, int z, BlockState state) {
access.set(x, y - bottomY, z, state);
}
boolean isAir(BlockState state) {
return access.is(state, BlockTrait.AIR);
}
boolean isSolid(BlockState state) {
return access.is(state, BlockTrait.SOLID);
}
boolean holdsFluid(BlockState state) {
return access.is(state, BlockTrait.FLUID);
}
/** Logs, wood, stems, hyphae and leaves: the blocks of trees the fit never treats as terrain. */
boolean isTree(BlockState state) {
return access.is(state, BlockTrait.LOG) || access.is(state, BlockTrait.LEAVES);
}
/** Logs or leaves by the platform's tags alone, as stilts tell vegetation from ground. */
boolean isTaggedVegetation(BlockState state) {
return access.inTag(state, LOGS_TAG) || access.inTag(state, LEAVES_TAG);
}
boolean inTag(BlockState state, ResourceId tag) {
return access.inTag(state, tag);
}
/** Solid ground that is not part of a tree. */
boolean isTerrain(BlockState state) {
return isSolid(state) && !isTree(state);
}
/** Air or anything holding a fluid: the cells a fill may claim. */
boolean isEncaseable(BlockState state) {
return isAir(state) || holdsFluid(state);
}
/** A block a structure can stand on: solid, dry, and neither structure void nor a jigsaw. */
boolean isSolidBase(BlockState state) {
return state != null && isSolid(state)
&& !state.material().equals(STRUCTURE_VOID)
&& !state.material().equals(JIGSAW)
&& !holdsFluid(state);
}
boolean sturdyTop(int x, int y, int z) {
return access.sturdy(x, y - bottomY, z, BlockFace.UP);
}
BlockState fluidOf(BlockState state) {
return access.fluid(state);
}
}
@@ -0,0 +1,29 @@
/*
* Iris is a World Generator for Minecraft Servers
* Copyright (c) 2026 Arcane Arts (Volmit Software)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package art.arcane.iris.engine.framework.structure.fit;
import com.volmit.block.BlockState;
import com.volmit.block.PaletteSpec;
/** Picks a block of a pack palette for the structure fit, seeded the way the fit's own randomness is. */
@FunctionalInterface
interface FitPalettes {
/** The block {@code palette}, seeded with {@code seed}, gives at the world position. */
BlockState at(PaletteSpec palette, long seed, int x, int y, int z);
}
@@ -0,0 +1,102 @@
/*
* Iris is a World Generator for Minecraft Servers
* Copyright (c) 2026 Arcane Arts (Volmit Software)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package art.arcane.iris.engine.framework.structure.fit;
import com.volmit.vanilla.PieceKind;
import com.volmit.vanilla.StructureFit;
import com.volmit.vanilla.TemplateCells;
import com.volmit.geometry.BlockPosition;
import java.util.ArrayList;
import java.util.List;
/** A piece of a start in world heights with inclusive bounds. */
final class FitPiece {
private final StructureFit.Piece piece;
private final Box box;
private final int bottomY;
FitPiece(StructureFit.Piece piece, int bottomY) {
this.piece = piece;
this.box = Box.of(piece.box(), bottomY);
this.bottomY = bottomY;
}
Box box() {
return box;
}
PieceKind kind() {
return piece.kind();
}
boolean isJigsaw() {
return piece.kind() != PieceKind.FIXED;
}
boolean isRigid() {
return piece.kind() == PieceKind.RIGID;
}
/** Whether the piece keeps its shape over the terrain: every piece built in code, and rigid jigsaw pieces. */
boolean isRigidOrFixed() {
return piece.kind() != PieceKind.TERRAIN_MATCHING;
}
int groundLevelDelta() {
return piece.groundLevelDelta();
}
/** The world height of the piece's ground level. */
int groundY() {
return box.minY() + piece.groundLevelDelta();
}
/** The junctions, their Y the world height of the ground at their source. */
List<BlockPosition> junctions() {
List<BlockPosition> junctions = new ArrayList<>(piece.junctions().size());
for (BlockPosition junction : piece.junctions()) {
junctions.add(new BlockPosition(junction.x(), junction.y() + bottomY, junction.z()));
}
return junctions;
}
TemplateCells cells(Box region) {
return piece.cells(region.toApi(bottomY));
}
/** The cell's world height. */
int cellY(TemplateCells cells, int cell) {
return cells.y(cell) + bottomY;
}
void columns(StructureFit.ColumnVisitor visitor) {
piece.columns((x, z, minY, maxY) -> visitor.column(x, z, minY + bottomY, maxY + bottomY));
}
/** Legacy template air inside {@code clip}, in world heights. */
List<BlockPosition> legacyAir(Box clip) {
List<BlockPosition> air = piece.legacyAir(clip.toApi(bottomY));
List<BlockPosition> world = new ArrayList<>(air.size());
for (BlockPosition position : air) {
world.add(new BlockPosition(position.x(), position.y() + bottomY, position.z()));
}
return world;
}
}
@@ -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 <https://www.gnu.org/licenses/>.
*/
package art.arcane.iris.engine.framework.structure.fit;
import art.arcane.iris.builtin.structure.StructureTerrain;
import art.arcane.iris.engine.framework.structure.NativeStructureFit;
import com.volmit.vanilla.DecorationStep;
import com.volmit.vanilla.StartKey;
import com.volmit.vanilla.StructureFit;
import com.volmit.vanilla.TerrainAdaptation;
import java.util.ArrayList;
import java.util.List;
/** A start the platform places in the chunk, with the fit {@code iris:structure} gives it, its pieces in world heights. */
final class FitStart {
private final StructureFit.Start start;
private final NativeStructureFit fit;
private final List<FitPiece> pieces;
FitStart(StructureFit.Start start, NativeStructureFit fit, int bottomY) {
this.start = start;
this.fit = fit;
List<FitPiece> converted = new ArrayList<>(start.pieces().size());
for (StructureFit.Piece piece : start.pieces()) {
converted.add(new FitPiece(piece, bottomY));
}
this.pieces = List.copyOf(converted);
}
StructureFit.Start start() {
return start;
}
String structureId() {
return start.structure().toString();
}
NativeStructureFit fit() {
return fit;
}
StructureTerrain terrain() {
return fit.resolvedTerrain();
}
TerrainAdaptation adaptation() {
return start.adaptation();
}
DecorationStep step() {
return start.step();
}
int chunkX() {
return start.chunkX();
}
int chunkZ() {
return start.chunkZ();
}
List<FitPiece> pieces() {
return pieces;
}
/** The box around every piece of the start. */
Box contentBounds() {
Box bounds = pieces.getFirst().box();
for (FitPiece piece : pieces) {
bounds = bounds.encapsulating(piece.box());
}
return bounds;
}
StartKey key() {
return start.key();
}
}
@@ -0,0 +1,156 @@
/*
* Iris is a World Generator for Minecraft Servers
* Copyright (c) 2026 Arcane Arts (Volmit Software)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package art.arcane.iris.engine.framework.structure.fit;
import art.arcane.iris.builtin.structure.StructureStilts;
import com.volmit.block.BlockState;
import com.volmit.block.PaletteSpec;
import java.util.ArrayList;
import java.util.BitSet;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.function.IntBinaryOperator;
/**
* Foundation columns under a placed start: in every column of the start's foundation envelope (the pieces' lowest
* layers up to one above their ground), from the lowest solid block placed there down to the first block that can
* carry it, the terrain's surface for a surface structure, at most {@code maxDepth} blocks deep. Sparse stilts keep
* only the columns on their spacing grid.
*
* <p>These are the vanilla structures' stilts. Objects grow theirs from their own bottom layer instead
* ({@code iris:stilt}): repeated object blocks, eroded or organic tips and a ceiling hang have no counterpart here, and
* these columns have no counterpart there, so the two stay separate.
*/
final class FoundationStilts {
private static final int FOUNDATION_VERTICAL_TOLERANCE = 1;
private FoundationStilts() {
}
static void placeStilts(FitBlocks blocks, Box area, FitStart start, StructureStilts settings, long seed,
FitPalettes palettes, IntBinaryOperator surfaceHeight, boolean surfaceStructure) {
Objects.requireNonNull(surfaceHeight, "Structure stilts require an Iris terrain height resolver");
Optional<PaletteSpec> palette = settings.palette();
long paletteSeed = seed ^ start.structureId().hashCode();
for (FoundationColumn column : foundationEnvelope(area, start)) {
if (!isStiltColumn(column.x(), column.z(), settings.spacing())) {
continue;
}
int foundationY = findFoundationY(blocks, column);
if (foundationY == Integer.MIN_VALUE) {
continue;
}
int terrainY = surfaceStructure
? Math.max(area.minY(), Math.min(area.maxY(), surfaceHeight.applyAsInt(column.x(), column.z())))
: area.minY() - 1;
int anchorY = findStiltAnchorY(blocks, column.x(), column.z(), foundationY,
Math.max(1, settings.maxDepth()), terrainY, area.minY());
if (anchorY == Integer.MIN_VALUE) {
continue;
}
for (int y = foundationY - 1; y > anchorY; y--) {
BlockState stilt = palette.isEmpty()
? FitBlocks.COBBLESTONE
: Objects.requireNonNull(palettes.at(palette.get(), paletteSeed, column.x(), y, column.z()),
"Stilt palette returned no block for " + start.structureId() + " at "
+ column.x() + "," + y + "," + column.z());
blocks.set(column.x(), y, column.z(), stilt);
}
}
}
static boolean isStiltColumn(int x, int z, int spacing) {
int resolvedSpacing = Math.max(1, spacing);
return resolvedSpacing == 1 || Math.floorMod(x, resolvedSpacing) == 0 && Math.floorMod(z, resolvedSpacing) == 0;
}
static int findStiltAnchorY(FitBlocks blocks, int x, int z, int foundationY, int maxDepth, int terrainY,
int areaMinY) {
int minimumAnchorY = Math.max(areaMinY, Math.max(terrainY, foundationY - maxDepth - 1));
for (int y = foundationY - 1; y >= minimumAnchorY; y--) {
BlockState state = blocks.get(x, y, z);
if (!blocks.isTaggedVegetation(state) && blocks.sturdyTop(x, y, z)) {
return y;
}
}
return Integer.MIN_VALUE;
}
private static List<FoundationColumn> foundationEnvelope(Box area, FitStart start) {
Box structure = start.contentBounds();
int minX = Math.max(area.minX(), structure.minX());
int minZ = Math.max(area.minZ(), structure.minZ());
int maxX = Math.min(area.maxX(), structure.maxX());
int maxZ = Math.min(area.maxZ(), structure.maxZ());
if (minX > maxX || minZ > maxZ) {
return List.of();
}
List<FoundationColumn> columns = new ArrayList<>((maxX - minX + 1) * (maxZ - minZ + 1));
BitSet envelope = new BitSet(area.ySpan());
for (int z = minZ; z <= maxZ; z++) {
for (int x = minX; x <= maxX; x++) {
envelope.clear();
markFoundationEnvelope(envelope, start, area, x, z);
int cellCount = envelope.cardinality();
if (cellCount == 0) {
continue;
}
int[] ys = new int[cellCount];
int cell = 0;
for (int bit = envelope.nextSetBit(0); bit >= 0; bit = envelope.nextSetBit(bit + 1)) {
ys[cell++] = area.minY() + bit;
}
columns.add(new FoundationColumn(x, z, ys));
}
}
return List.copyOf(columns);
}
private static void markFoundationEnvelope(BitSet envelope, FitStart start, Box area, int x, int z) {
for (FitPiece piece : start.pieces()) {
Box bounds = piece.box();
if (x < bounds.minX() || x > bounds.maxX() || z < bounds.minZ() || z > bounds.maxZ()) {
continue;
}
int groundY = piece.groundY();
if (piece.isJigsaw() && groundY < bounds.minY()) {
continue;
}
int minY = Math.max(area.minY(), bounds.minY());
int maxY = Math.min(area.maxY(), Math.min(bounds.maxY(), groundY + FOUNDATION_VERTICAL_TOLERANCE));
if (minY <= maxY) {
envelope.set(minY - area.minY(), maxY - area.minY() + 1);
}
}
}
private static int findFoundationY(FitBlocks blocks, FoundationColumn column) {
for (int y : column.ys()) {
if (blocks.isSolid(blocks.get(column.x(), y, column.z()))) {
return y;
}
}
return Integer.MIN_VALUE;
}
private record FoundationColumn(int x, int z, int[] ys) {
}
}
@@ -0,0 +1,270 @@
/*
* Iris is a World Generator for Minecraft Servers
* Copyright (c) 2026 Arcane Arts (Volmit Software)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package art.arcane.iris.engine.framework.structure.fit;
import com.volmit.block.BlockState;
import com.volmit.vanilla.StartKey;
import com.volmit.vanilla.TemplateCells;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
/**
* Closes the short gaps between two rigid pieces of one surface start whose ground planes are one or two blocks apart:
* where the upper piece's lowest solid base sits two blocks over the lower piece's ground, the gap is filled with the
* terrain under the lower piece, so steps and terraces stand on ground instead of air. Only the chunk's own blocks are
* filled, never across starts, and nothing at all when the work would exceed its budget.
*/
final class RigidSupport {
private static final int MAX_BATCH_CELLS = 524_288;
private static final int MAX_BRIDGE_SPAN = 2;
private RigidSupport() {
}
static Set<Long> bridgeRigidPieceSupport(FitBlocks blocks, Box area, List<FitStart> starts) {
if (starts.isEmpty()) {
return Set.of();
}
Map<Long, BlockState> planned;
try {
BatchCellBudget budget = new BatchCellBudget();
List<SupportRequest> requests = new ArrayList<>();
Set<StartKey> seenStarts = new HashSet<>();
for (FitStart start : starts) {
if (!SurfaceFitting.requiresSurfaceTerrain(start) || !seenStarts.add(start.key())) {
continue;
}
collectStartRequests(blocks, area, start, budget, requests);
}
planned = planWrites(blocks, area, requests, budget);
} catch (BatchBudgetExceeded ignored) {
return Set.of();
}
if (planned.isEmpty()) {
return Set.of();
}
List<Map.Entry<Long, BlockState>> ordered = new ArrayList<>(planned.entrySet());
ordered.sort(Map.Entry.comparingByKey());
Set<Long> written = new HashSet<>();
for (Map.Entry<Long, BlockState> entry : ordered) {
int x = TemplateFootprint.packedX(entry.getKey());
int y = TemplateFootprint.packedY(entry.getKey());
int z = TemplateFootprint.packedZ(entry.getKey());
BlockState existing = blocks.get(x, y, z);
if (!blocks.isSolid(existing) && !blocks.isTree(existing) && !blocks.holdsFluid(existing)) {
blocks.set(x, y, z, entry.getValue());
written.add(entry.getKey());
}
}
return Set.copyOf(written);
}
private static void collectStartRequests(FitBlocks blocks, Box area, FitStart start, BatchCellBudget budget,
List<SupportRequest> requests) {
List<RigidAnchor> anchors = rigidAnchors(start);
if (anchors.size() < 2) {
return;
}
for (RigidAnchor upper : anchors) {
Map<Long, Integer> lowerMeets = candidateLowerMeets(area, upper, anchors, budget);
if (lowerMeets.isEmpty()) {
continue;
}
TemplateCells cells = upper.piece().cells(area);
budget.consume(cells.readBlocks());
if (!cells.resolved()) {
continue;
}
for (Map.Entry<Long, TemplateFootprint.Cell> entry
: lowestBridgeableCells(cells, upper.piece(), area, lowerMeets).entrySet()) {
TemplateFootprint.Cell cell = entry.getValue();
Integer lowerMeet = lowerMeets.get(entry.getKey());
if (lowerMeet == null || cell.blocker() || !blocks.isSolidBase(cell.state())
|| cell.y() - lowerMeet < 2 || cell.y() - lowerMeet > MAX_BRIDGE_SPAN) {
continue;
}
budget.consume(1);
requests.add(new SupportRequest(cell.x(), cell.z(), lowerMeet, cell.y()));
}
}
}
/**
* The lowest cell of each column over a lower piece's ground, among the cells no higher than the widest bridge
* above that ground: the cells the support could stand under.
*/
private static Map<Long, TemplateFootprint.Cell> lowestBridgeableCells(TemplateCells cells, FitPiece piece, Box area,
Map<Long, Integer> lowerMeets) {
Map<Long, TemplateFootprint.Cell> lowest = new HashMap<>();
for (int cell = 0; cell < cells.size(); cell++) {
int x = cells.x(cell);
int y = piece.cellY(cells, cell);
int z = cells.z(cell);
long column = TemplateFootprint.columnKey(x, z);
Integer lowerMeet = lowerMeets.get(column);
if (!area.contains(x, y, z) || lowerMeet == null || y > lowerMeet + MAX_BRIDGE_SPAN) {
continue;
}
TemplateFootprint.Cell current = lowest.get(column);
if (current == null || y < current.y()) {
lowest.put(column, new TemplateFootprint.Cell(x, y, z, cells.state(cell)));
}
}
return lowest;
}
private static List<RigidAnchor> rigidAnchors(FitStart start) {
List<RigidAnchor> anchors = new ArrayList<>();
for (FitPiece piece : start.pieces()) {
if (!piece.isRigid()) {
continue;
}
anchors.add(new RigidAnchor(piece, piece.box(), piece.groundY() - 1));
}
return List.copyOf(anchors);
}
private static Map<Long, Integer> candidateLowerMeets(Box area, RigidAnchor upper, List<RigidAnchor> anchors,
BatchCellBudget budget) {
Map<Long, Integer> lowerMeets = new HashMap<>();
for (RigidAnchor lower : anchors) {
budget.consume(1);
int span = upper.meetY() - lower.meetY();
if (lower.piece() == upper.piece() || span < 1 || span > MAX_BRIDGE_SPAN
|| lower.meetY() < area.minY() || lower.meetY() > area.maxY()) {
continue;
}
int minimumX = Math.max(area.minX(), Math.max(upper.bounds().minX(), lower.bounds().minX()));
int maximumX = Math.min(area.maxX(), Math.min(upper.bounds().maxX(), lower.bounds().maxX()));
int minimumZ = Math.max(area.minZ(), Math.max(upper.bounds().minZ(), lower.bounds().minZ()));
int maximumZ = Math.min(area.maxZ(), Math.min(upper.bounds().maxZ(), lower.bounds().maxZ()));
if (minimumX > maximumX || minimumZ > maximumZ) {
continue;
}
for (int x = minimumX; x <= maximumX; x++) {
for (int z = minimumZ; z <= maximumZ; z++) {
budget.consume(1);
lowerMeets.merge(TemplateFootprint.columnKey(x, z), lower.meetY(), Math::max);
}
}
}
return lowerMeets;
}
private static Map<Long, BlockState> planWrites(FitBlocks blocks, Box area, List<SupportRequest> requests,
BatchCellBudget budget) {
List<SupportRequest> eligible = new ArrayList<>();
Set<MaterialKey> materialKeys = new HashSet<>();
for (SupportRequest request : requests) {
BlockState lowerTerrain = blocks.get(request.x(), request.lowerMeetY(), request.z());
if (!isTerrainSupport(blocks, lowerTerrain) || !gapIsClear(blocks, area, request, budget)) {
continue;
}
eligible.add(request);
materialKeys.add(new MaterialKey(request.x(), request.z(), request.lowerMeetY()));
}
Map<MaterialKey, BlockState> materials = new HashMap<>();
for (MaterialKey key : materialKeys) {
materials.put(key, resolveSupportState(blocks, key.x(), key.z(), key.lowerMeetY(), budget));
}
Map<Long, BlockState> planned = new HashMap<>();
Set<Long> conflicts = new HashSet<>();
eligible.sort(Comparator.comparingInt(SupportRequest::x)
.thenComparingInt(SupportRequest::z)
.thenComparingInt(SupportRequest::lowerMeetY)
.thenComparingInt(SupportRequest::baseY));
for (SupportRequest request : eligible) {
BlockState material = materials.get(new MaterialKey(request.x(), request.z(), request.lowerMeetY()));
for (int y = request.lowerMeetY() + 1; y < request.baseY(); y++) {
budget.consume(1);
long positionKey = TemplateFootprint.packedPosition(request.x(), y, request.z());
if (conflicts.contains(positionKey)) {
continue;
}
BlockState existing = planned.putIfAbsent(positionKey, material);
if (existing != null && !existing.equals(material)) {
planned.remove(positionKey);
conflicts.add(positionKey);
}
}
}
return planned;
}
private static boolean gapIsClear(FitBlocks blocks, Box area, SupportRequest request, BatchCellBudget budget) {
for (int y = request.lowerMeetY() + 1; y < request.baseY(); y++) {
budget.consume(1);
if (!area.contains(request.x(), y, request.z())) {
return false;
}
BlockState state = blocks.get(request.x(), y, request.z());
if (blocks.isSolid(state) || blocks.isTree(state) || blocks.holdsFluid(state)) {
return false;
}
}
return true;
}
private static BlockState resolveSupportState(FitBlocks blocks, int x, int z, int lowerMeetY, BatchCellBudget budget) {
budget.consume(1);
BlockState below = blocks.get(x, lowerMeetY - 1, z);
if (isTerrainSupport(blocks, below)) {
return below;
}
return blocks.get(x, lowerMeetY, z);
}
private static boolean isTerrainSupport(FitBlocks blocks, BlockState state) {
return blocks.isSolid(state) && !blocks.isTree(state) && !blocks.holdsFluid(state);
}
private record RigidAnchor(FitPiece piece, Box bounds, int meetY) {
}
private record SupportRequest(int x, int z, int lowerMeetY, int baseY) {
}
private record MaterialKey(int x, int z, int lowerMeetY) {
}
private static final class BatchCellBudget {
private int consumed;
private void consume(int amount) {
if (amount < 0 || consumed > MAX_BATCH_CELLS - amount) {
throw BatchBudgetExceeded.INSTANCE;
}
consumed += amount;
}
}
private static final class BatchBudgetExceeded extends RuntimeException {
private static final BatchBudgetExceeded INSTANCE = new BatchBudgetExceeded();
private BatchBudgetExceeded() {
super(null, null, false, false);
}
}
}
@@ -0,0 +1,112 @@
/*
* Iris is a World Generator for Minecraft Servers
* Copyright (c) 2026 Arcane Arts (Volmit Software)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package art.arcane.iris.engine.framework.structure.fit;
import art.arcane.iris.builtin.structure.StructureTerrain;
import art.arcane.iris.builtin.structure.StructureYBand;
import art.arcane.iris.engine.framework.structure.NativeStructureFit;
import art.arcane.volmlib.util.math.RNG;
import com.volmit.geometry.BlockBox;
import com.volmit.vanilla.PlatformStart;
import com.volmit.vanilla.StartReach;
/**
* Where the platform's own starts sit and how far {@code iris:structure} changes the terrain around a start. A start
* that keeps the platform's height only takes its shift; a band moves the start's middle into it, chosen per start
* chunk; an underground start is buried under the lowest terrain column above it; anything else takes its shift. A
* structure the host aligns itself only takes its shift on top of that alignment.
*/
public final class StartLayouts {
private static final int MAX_BURIAL_COLUMNS = 2_000_000;
private static final int UNDERGROUND_SURFACE_CLEARANCE = 1;
private static final long BAND_IDENTITY_X = 341873128712L;
private static final long BAND_IDENTITY_Z = 132897987541L;
private StartLayouts() {
}
/** How far {@code start} moves up (negative: down) under {@code fit}, before the host keeps it inside the world. */
public static int shift(PlatformStart start, NativeStructureFit fit) {
if (start.aligned() || fit.keepsSourceY()) {
return fit.yShift();
}
if (fit.yBand() != null) {
return bandShift(start, fit.yBand());
}
if (start.underground()) {
return burialShift(start, fit.yShift());
}
return fit.yShift();
}
/** How far around its pieces a start with {@code terrain} changes the terrain. */
public static StartReach reach(StructureTerrain terrain) {
return switch (terrain.resolvedMode()) {
case SOURCE -> StartReach.PLATFORM;
case PRESERVE -> StartReach.blocks(0);
case VACUUM -> StartReach.blocks(SurfaceFitting.surfaceTerrainRadius());
case BORE, FORCE_CARVE, ENCASE -> StartReach.blocks(Math.max(0, terrain.horizontalPadding()));
};
}
private static int bandShift(PlatformStart start, StructureYBand band) {
BlockBox bounds = start.bounds();
int minY = bounds.minY() + start.minWorldY();
int maxY = bounds.maxY() - 1 + start.minWorldY();
int target = bandTargetMidpointY(minY, maxY, band.resolvedMin(), band.resolvedMax(), start.chunkX(), start.chunkZ());
return Math.subtractExact(target, minY + (maxY - minY) / 2);
}
/** The world height the middle of a start from {@code maxY - minY} high moves to, inside the band, per start chunk. */
static int bandTargetMidpointY(int minY, int maxY, int bandMin, int bandMax, int chunkX, int chunkZ) {
int height = Math.subtractExact(maxY, minY);
int lowest = Math.addExact(bandMin, height / 2);
int highest = Math.subtractExact(bandMax, height - height / 2);
if (lowest > highest) {
// The band is shorter than the structure, so only its midpoint can be honoured.
return Math.floorDiv(Math.addExact(bandMin, bandMax), 2);
}
int span = highest - lowest + 1;
if (span == 1) {
return lowest;
}
long identity = (long) chunkX * BAND_IDENTITY_X ^ (long) chunkZ * BAND_IDENTITY_Z;
return lowest + new RNG(identity).nextInt(span);
}
/** At most {@code requestedShift}, and low enough that the start's top stays a block under every terrain column. */
private static int burialShift(PlatformStart start, int requestedShift) {
BlockBox bounds = start.bounds();
long width = (long) bounds.maxX() - bounds.minX();
long depth = (long) bounds.maxZ() - bounds.minZ();
if (width <= 0L || depth <= 0L || width > MAX_BURIAL_COLUMNS / depth) {
throw new IllegalStateException("Underground native structure burial footprint is invalid or exceeds "
+ MAX_BURIAL_COLUMNS + " columns");
}
int topY = bounds.maxY() - 1;
int maximumShift = requestedShift;
for (int x = bounds.minX(); x < bounds.maxX(); x++) {
for (int z = bounds.minZ(); z < bounds.maxZ(); z++) {
int allowedTopY = start.surfaceY(x, z) - UNDERGROUND_SURFACE_CLEARANCE;
maximumShift = Math.min(maximumShift, allowedTopY - topY);
}
}
return maximumShift;
}
}
@@ -0,0 +1,723 @@
/*
* Iris is a World Generator for Minecraft Servers
* Copyright (c) 2026 Arcane Arts (Volmit Software)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package art.arcane.iris.engine.framework.structure.fit;
import art.arcane.iris.builtin.structure.StructureTerrainMode;
import com.volmit.ModuleLog;
import com.volmit.block.BlockState;
import com.volmit.vanilla.DecorationStep;
import com.volmit.vanilla.StartKey;
import com.volmit.vanilla.TemplateCells;
import com.volmit.vanilla.TerrainAdaptation;
import com.volmit.geometry.BlockPosition;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.IntBinaryOperator;
/**
* Fits the surface around the platform's surface structures before their pieces are placed. SOURCE replays the
* platform's beard adaptation: the terrain within 12 blocks of the structure's ground planes bends toward them, never
* more than 6 blocks. VACUUM raises the terrain to meet the processed solid foundations of rigid pieces, again over 12
* blocks, without ever lowering it, and after the pieces are placed fills the gaps left under their bases
* ({@link #repairVacuumFoundations}).
*/
final class SurfaceFitting {
private static final double SURFACE_TERRAIN_FALLOFF = 2.0;
private static final long SURFACE_TERRAIN_INFLUENCE_SCALE = 1_000_000L;
private static final int SURFACE_TERRAIN_RADIUS = 12;
private static final int MAX_SOURCE_SURFACE_DELTA = 6;
static final int MAX_SURFACE_TEMPLATE_CELLS = 4_194_304;
private static final int FOUNDATION_ANCHOR_STRENGTH = 2;
private static final int JUNCTION_ANCHOR_STRENGTH = 1;
private static final Set<String> WARNED_SOURCE_BUDGET = ConcurrentHashMap.newKeySet();
private static final Set<String> WARNED_VACUUM_BUDGET = ConcurrentHashMap.newKeySet();
private SurfaceFitting() {
}
/** The radius of the surface falloff, which a VACUUM start reaches beyond its pieces. */
static int surfaceTerrainRadius() {
return SURFACE_TERRAIN_RADIUS;
}
static VacuumFoundationPlan prepareSurfaceStructures(FitBlocks blocks, Box area, List<FitStart> starts,
IntBinaryOperator surfaceHeight, int maximumTemplateCells,
ModuleLog log) {
if (starts.isEmpty()) {
return VacuumFoundationPlan.EMPTY;
}
Objects.requireNonNull(surfaceHeight, "Surface structure terrain fitting requires an Iris height resolver");
List<SurfaceAnchor> anchors = collectSourceSurfaceAnchors(blocks, area, starts, maximumTemplateCells, log);
if (!anchors.isEmpty()) {
fitSurfaceTerrain(blocks, area, anchors, surfaceHeight);
}
VacuumFootprint vacuum = collectVacuumFootprint(blocks, area, starts, maximumTemplateCells, log);
if (!vacuum.anchors().isEmpty()) {
fitVacuumTerrain(blocks, area, vacuum, surfaceHeight);
}
return VacuumFoundationPlan.create(vacuum.foundationBases(), vacuum.occupiedCells(), area);
}
static void repairVacuumFoundations(FitBlocks blocks, Box area, VacuumFoundationPlan plan) {
if (plan == null || plan.foundationBases.isEmpty()) {
return;
}
for (long packedBase : plan.foundationBases) {
int baseX = TemplateFootprint.packedX(packedBase);
int baseY = TemplateFootprint.packedY(packedBase);
int baseZ = TemplateFootprint.packedZ(packedBase);
if (!area.contains(baseX, baseY, baseZ)) {
continue;
}
if (!blocks.isSolidBase(blocks.get(baseX, baseY, baseZ))) {
continue;
}
int supportY = findVacuumFoundationSupport(blocks, area, baseX, baseY - 1, baseZ);
if (supportY == Integer.MIN_VALUE || supportY == baseY - 1) {
continue;
}
if (intersectsVacuumOccupancy(plan.occupiedCells, baseX, baseZ, supportY + 1, baseY - 1)) {
continue;
}
BlockState fill = resolveSurfaceMaterials(blocks, baseX, baseZ, supportY, area.minY()).subsurface();
for (int y = supportY + 1; y < baseY; y++) {
BlockState existing = blocks.get(baseX, y, baseZ);
if (blocks.isAir(existing) || blocks.holdsFluid(existing)) {
blocks.set(baseX, y, baseZ, fill);
}
}
}
}
static boolean shouldPrepareSurfaceTerrain(TerrainAdaptation adaptation, DecorationStep step) {
return step == DecorationStep.SURFACE_STRUCTURES
&& (adaptation == TerrainAdaptation.BEARD_THIN || adaptation == TerrainAdaptation.BEARD_BOX);
}
static int resolveSurfaceTarget(List<SurfaceAnchor> anchors, int worldX, int worldZ, int originalY) {
return resolveSurface(anchors, worldX, worldZ, originalY).targetY();
}
/** How far {@code value} lies outside {@code [low, high]}; 0 inside. Iris's vacuum measures footprints the same way. */
private static int outset(int value, int low, int high) {
if (value < low) {
return low - value;
}
if (value > high) {
return value - high;
}
return 0;
}
private static SurfaceResolution resolveSurface(List<SurfaceAnchor> anchors, int worldX, int worldZ, int originalY) {
int localTargetY = originalY;
SurfaceAnchor selectedLocal = null;
long totalInfluence = 0L;
long weightedTargetY = 0L;
long maximumInfluence = 0L;
for (SurfaceAnchor anchor : anchors) {
int outX = outset(worldX, anchor.minX(), anchor.maxX());
int outZ = outset(worldZ, anchor.minZ(), anchor.maxZ());
boolean containsColumn = outX == 0 && outZ == 0;
long distanceSquared = (long) outX * outX + (long) outZ * outZ;
long radiusSquared = (long) SURFACE_TERRAIN_RADIUS * SURFACE_TERRAIN_RADIUS;
if (distanceSquared > radiusSquared) {
continue;
}
double distance = Math.sqrt(distanceSquared);
double factor = Math.pow(1D - distance / SURFACE_TERRAIN_RADIUS, SURFACE_TERRAIN_FALLOFF);
if (factor <= 0D) {
continue;
}
int boundedTargetY = boundedSurfaceTarget(originalY, anchor.meetY());
if (containsColumn) {
if (precedes(anchor, selectedLocal)) {
localTargetY = boundedTargetY;
selectedLocal = anchor;
}
continue;
}
long influence = Math.round(factor * SURFACE_TERRAIN_INFLUENCE_SCALE);
if (influence <= 0L) {
continue;
}
long weightedInfluence = influence * Math.max(1, anchor.strength());
totalInfluence += weightedInfluence;
weightedTargetY += weightedInfluence * boundedTargetY;
maximumInfluence = Math.max(maximumInfluence, influence);
}
if (selectedLocal != null) {
return new SurfaceResolution(localTargetY,
selectedLocal.strength() > 1 && localTargetY == selectedLocal.meetY());
}
if (totalInfluence == 0L) {
return new SurfaceResolution(originalY, false);
}
double blendedTargetY = weightedTargetY / (double) totalInfluence;
double factor = maximumInfluence / (double) SURFACE_TERRAIN_INFLUENCE_SCALE;
return new SurfaceResolution(blendSurfaceTarget(originalY, blendedTargetY, factor), false);
}
private static int boundedSurfaceTarget(int originalY, int meetY) {
int delta = Math.max(-MAX_SOURCE_SURFACE_DELTA, Math.min(MAX_SOURCE_SURFACE_DELTA, meetY - originalY));
return originalY + delta;
}
private static int blendSurfaceTarget(int originalY, double targetY, double factor) {
double delta = (targetY - originalY) * factor;
int magnitude = (int) Math.round(Math.abs(delta));
return originalY + (delta < 0D ? -magnitude : magnitude);
}
private static boolean precedes(SurfaceAnchor candidate, SurfaceAnchor selected) {
if (selected == null) {
return true;
}
if (candidate.strength() != selected.strength()) {
return candidate.strength() > selected.strength();
}
if (candidate.meetY() != selected.meetY()) {
return candidate.meetY() < selected.meetY();
}
if (candidate.minX() != selected.minX()) {
return candidate.minX() < selected.minX();
}
if (candidate.minZ() != selected.minZ()) {
return candidate.minZ() < selected.minZ();
}
if (candidate.maxX() != selected.maxX()) {
return candidate.maxX() < selected.maxX();
}
if (candidate.maxZ() != selected.maxZ()) {
return candidate.maxZ() < selected.maxZ();
}
return false;
}
private static List<SurfaceAnchor> collectSourceSurfaceAnchors(FitBlocks blocks, Box area, List<FitStart> starts,
int maximumTemplateCells, ModuleLog log) {
Box influenceArea = area.widened(SURFACE_TERRAIN_RADIUS);
List<SurfaceAnchor> anchors = new ArrayList<>();
Set<StartKey> seenStarts = new HashSet<>();
for (FitStart start : starts) {
if (!requiresSourceSurfaceTerrain(start) || !seenStarts.add(start.key())) {
continue;
}
TemplateCellBudget budget = new TemplateCellBudget(maximumTemplateCells);
boolean budgetExceeded = false;
for (FitPiece piece : start.pieces()) {
if (piece.isJigsaw()) {
if (!budgetExceeded && piece.box().intersectsHorizontally(influenceArea)) {
try {
List<SurfaceAnchor> pieceAnchors = new ArrayList<>();
addProcessedSurfaceAnchors(blocks, influenceArea, piece, budget, pieceAnchors);
anchors.addAll(pieceAnchors);
} catch (TemplateBudgetExceeded ignored) {
budgetExceeded = true;
warnBudget(WARNED_SOURCE_BUDGET, start, "SOURCE",
"skipping remaining processed footprints for this start", log);
}
}
for (BlockPosition junction : piece.junctions()) {
anchors.add(new SurfaceAnchor(junction.x(), junction.x(), junction.z(), junction.z(),
junction.y() - 1, JUNCTION_ANCHOR_STRENGTH));
}
continue;
}
Box bounds = piece.box();
anchors.add(surfaceAnchor(bounds, bounds.minY(), FOUNDATION_ANCHOR_STRENGTH));
}
}
return List.copyOf(anchors);
}
private static void addProcessedSurfaceAnchors(FitBlocks blocks, Box influenceArea, FitPiece piece,
TemplateCellBudget budget, List<SurfaceAnchor> anchors) {
TemplateCells cells = piece.cells(influenceArea);
budget.consume(cells.readBlocks());
if (!cells.resolved()) {
return;
}
int maximumFoundationY = piece.groundY();
for (TemplateFootprint.Cell cell : TemplateFootprint.lowestSolidCells(cells, piece, blocks).values()) {
budget.consume(1);
if (piece.isRigid() && cell.y() > maximumFoundationY) {
continue;
}
int groundY = piece.isRigid() ? maximumFoundationY : cell.y();
Box column = new Box(cell.x(), groundY, cell.z(), cell.x(), groundY, cell.z());
anchors.add(surfaceAnchor(column, groundY, FOUNDATION_ANCHOR_STRENGTH));
}
}
private static void warnBudget(Set<String> warned, FitStart start, String mode, String consequence, ModuleLog log) {
if (warned.add(start.structureId())) {
log.warn("Native structure " + mode + " fitting for '" + start.structureId()
+ "' exceeded its bounded template budget; " + consequence);
}
}
private static VacuumFootprint collectVacuumFootprint(FitBlocks blocks, Box area, List<FitStart> starts,
int maximumTemplateCells, ModuleLog log) {
Box influenceArea = area.widened(SURFACE_TERRAIN_RADIUS);
Map<Long, VacuumAnchor> anchors = new HashMap<>();
Map<Long, Integer> columnCaps = new HashMap<>();
Set<Long> foundationBases = new HashSet<>();
Set<Long> occupiedCells = new HashSet<>();
Set<StartKey> seenStarts = new HashSet<>();
for (FitStart start : starts) {
if (start.terrain().resolvedMode() != StructureTerrainMode.VACUUM || !seenStarts.add(start.key())) {
continue;
}
Map<Long, VacuumAnchor> targetAnchors = new HashMap<>();
Map<Long, Integer> targetCaps = new HashMap<>();
Set<Long> targetFoundationBases = new HashSet<>();
Set<Long> targetOccupiedCells = new HashSet<>();
TemplateCellBudget budget = new TemplateCellBudget(maximumTemplateCells);
try {
for (FitPiece piece : start.pieces()) {
if (!piece.box().intersectsHorizontally(influenceArea) || !piece.isRigid()) {
continue;
}
addVacuumJunctionAnchors(anchors, influenceArea, piece);
TemplateCells cells = piece.cells(influenceArea);
budget.consume(cells.readBlocks());
if (!cells.resolved()) {
continue;
}
for (int cell = 0; cell < cells.size(); cell++) {
targetOccupiedCells.add(TemplateFootprint.packedPosition(
cells.x(cell), piece.cellY(cells, cell), cells.z(cell)));
}
int groundY = piece.groundY() - 1;
for (TemplateFootprint.Cell cell : TemplateFootprint.lowestCells(cells, piece).values()) {
budget.consume(1);
long column = TemplateFootprint.columnKey(cell.x(), cell.z());
targetCaps.merge(column, Math.min(cell.y(), groundY), Math::min);
if (cell.blocker() || cell.y() > groundY + 1 || !blocks.isSolidBase(cell.state())) {
continue;
}
addVacuumAnchor(targetAnchors, cell.x(), cell.z(),
new VacuumAnchor(cell.y() - 1, FOUNDATION_ANCHOR_STRENGTH));
targetFoundationBases.add(TemplateFootprint.packedPosition(cell.x(), cell.y(), cell.z()));
}
}
} catch (TemplateBudgetExceeded ignored) {
warnBudget(WARNED_VACUUM_BUDGET, start, "VACUUM", "using jigsaw junction smoothing for oversized starts", log);
continue;
}
targetAnchors.forEach((column, anchor) -> anchors.merge(column, anchor, SurfaceFitting::preferredVacuumAnchor));
targetCaps.forEach((column, cap) -> columnCaps.merge(column, cap, Math::min));
foundationBases.addAll(targetFoundationBases);
occupiedCells.addAll(targetOccupiedCells);
}
return new VacuumFootprint(Map.copyOf(anchors), Map.copyOf(columnCaps),
Set.copyOf(foundationBases), Set.copyOf(occupiedCells));
}
private static void addVacuumJunctionAnchors(Map<Long, VacuumAnchor> anchors, Box influenceArea, FitPiece piece) {
for (BlockPosition junction : piece.junctions()) {
if (junction.x() < influenceArea.minX() || junction.x() > influenceArea.maxX()
|| junction.z() < influenceArea.minZ() || junction.z() > influenceArea.maxZ()) {
continue;
}
addVacuumAnchor(anchors, junction.x(), junction.z(),
new VacuumAnchor(junction.y() - 1, JUNCTION_ANCHOR_STRENGTH));
}
}
private static void addVacuumAnchor(Map<Long, VacuumAnchor> anchors, int x, int z, VacuumAnchor candidate) {
anchors.merge(TemplateFootprint.columnKey(x, z), candidate, SurfaceFitting::preferredVacuumAnchor);
}
private static VacuumAnchor preferredVacuumAnchor(VacuumAnchor first, VacuumAnchor second) {
if (first.strength() != second.strength()) {
return first.strength() > second.strength() ? first : second;
}
return first.surfaceY() <= second.surfaceY() ? first : second;
}
static SurfaceAnchor surfaceAnchor(Box bounds, int groundY, int strength) {
return new SurfaceAnchor(bounds.minX(), bounds.maxX(), bounds.minZ(), bounds.maxZ(), groundY - 1, strength);
}
/** Whether the start's pieces need the surface fitted around them: VACUUM, or SOURCE with a beard adaptation. */
static boolean requiresSurfaceTerrain(FitStart start) {
return start.terrain().resolvedMode() == StructureTerrainMode.VACUUM || requiresSourceSurfaceTerrain(start);
}
private static boolean requiresSourceSurfaceTerrain(FitStart start) {
return start.terrain().resolvedMode() == StructureTerrainMode.SOURCE
&& shouldPrepareSurfaceTerrain(start.adaptation(), start.step());
}
private static void fitSurfaceTerrain(FitBlocks blocks, Box area, List<SurfaceAnchor> anchors,
IntBinaryOperator surfaceHeight) {
int width = area.xSpan();
int depth = area.zSpan();
int[] originalHeights = new int[width * depth];
int[] targetHeights = new int[width * depth];
boolean[] rigidBaseSupport = new boolean[width * depth];
for (int z = area.minZ(); z <= area.maxZ(); z++) {
for (int x = area.minX(); x <= area.maxX(); x++) {
int column = area.columnIndex(x, z);
int originalY = Math.max(area.minY(), Math.min(area.maxY(), surfaceHeight.applyAsInt(x, z)));
SurfaceResolution resolution = resolveSurface(anchors, x, z, originalY);
originalHeights[column] = originalY;
targetHeights[column] = Math.max(area.minY(), Math.min(area.maxY(), resolution.targetY()));
rigidBaseSupport[column] = resolution.rigidBaseSupport();
}
}
for (int z = area.minZ(); z <= area.maxZ(); z++) {
for (int x = area.minX(); x <= area.maxX(); x++) {
int column = area.columnIndex(x, z);
applySurfaceColumn(blocks, x, z, originalHeights[column], targetHeights[column], area.minY(), area.maxY(),
rigidBaseSupport[column]);
}
}
}
private static void fitVacuumTerrain(FitBlocks blocks, Box area, VacuumFootprint footprint,
IntBinaryOperator surfaceHeight) {
int width = area.xSpan();
int depth = area.zSpan();
int[] originalHeights = new int[width * depth];
int[] targetHeights = new int[width * depth];
boolean[] rigidBaseSupport = new boolean[width * depth];
for (int z = area.minZ(); z <= area.maxZ(); z++) {
for (int x = area.minX(); x <= area.maxX(); x++) {
int column = area.columnIndex(x, z);
int nominalY = Math.max(area.minY(), Math.min(area.maxY(), surfaceHeight.applyAsInt(x, z)));
long columnKey = TemplateFootprint.columnKey(x, z);
VacuumAnchor local = footprint.anchors().get(columnKey);
Integer cap = footprint.columnCaps().get(columnKey);
boolean suppressed = local != null && local.strength() > 1 && cap != null && cap < local.surfaceY();
int scanStartY = local != null && local.strength() > 1 && !suppressed
? Math.max(area.minY(), Math.min(area.maxY(), local.surfaceY()))
: nominalY;
int originalY = resolveVacuumSurfaceHeight(blocks, x, z, scanStartY, area.minY());
SurfaceResolution resolution = resolveVacuumSurface(footprint, x, z, originalY);
originalHeights[column] = originalY;
targetHeights[column] = Math.max(originalY, Math.min(area.maxY(), resolution.targetY()));
rigidBaseSupport[column] = resolution.rigidBaseSupport() && targetHeights[column] > originalY;
}
}
for (int z = area.minZ(); z <= area.maxZ(); z++) {
for (int x = area.minX(); x <= area.maxX(); x++) {
int column = area.columnIndex(x, z);
applySurfaceColumn(blocks, x, z, originalHeights[column], targetHeights[column], area.minY(), area.maxY(),
rigidBaseSupport[column]);
}
}
}
private static int resolveVacuumSurfaceHeight(FitBlocks blocks, int x, int z, int nominalY, int worldMinY) {
for (int y = nominalY; y >= worldMinY; y--) {
if (blocks.isTerrain(blocks.get(x, y, z))) {
return y;
}
}
return nominalY;
}
private static int findVacuumFoundationSupport(FitBlocks blocks, Box area, int x, int startY, int z) {
if (startY < area.minY()) {
return Integer.MIN_VALUE;
}
int maximumY = Math.min(area.maxY(), startY);
for (int y = maximumY; y >= area.minY(); y--) {
BlockState state = blocks.get(x, y, z);
if (blocks.isTerrain(state)) {
return y;
}
if (!blocks.isAir(state) && !blocks.holdsFluid(state)) {
return Integer.MIN_VALUE;
}
}
return Integer.MIN_VALUE;
}
private static boolean intersectsVacuumOccupancy(Set<Long> occupiedCells, int x, int z, int minimumY, int maximumY) {
for (int y = minimumY; y <= maximumY; y++) {
if (occupiedCells.contains(TemplateFootprint.packedPosition(x, y, z))) {
return true;
}
}
return false;
}
private static SurfaceResolution resolveVacuumSurface(VacuumFootprint footprint, int worldX, int worldZ, int originalY) {
long column = TemplateFootprint.columnKey(worldX, worldZ);
Integer cap = footprint.columnCaps().get(column);
VacuumAnchor local = footprint.anchors().get(column);
if (local != null && local.strength() > 1) {
int localTargetY = cap == null ? local.surfaceY() : Math.min(local.surfaceY(), cap);
if (localTargetY <= originalY) {
return new SurfaceResolution(originalY, false);
}
return new SurfaceResolution(localTargetY, localTargetY == local.surfaceY());
}
long totalInfluence = 0L;
long weightedSurfaceY = 0L;
long maximumInfluence = 0L;
int radiusSquared = SURFACE_TERRAIN_RADIUS * SURFACE_TERRAIN_RADIUS;
for (int offsetX = -SURFACE_TERRAIN_RADIUS; offsetX <= SURFACE_TERRAIN_RADIUS; offsetX++) {
for (int offsetZ = -SURFACE_TERRAIN_RADIUS; offsetZ <= SURFACE_TERRAIN_RADIUS; offsetZ++) {
int horizontalDistanceSquared = offsetX * offsetX + offsetZ * offsetZ;
if (horizontalDistanceSquared > radiusSquared) {
continue;
}
VacuumAnchor anchor = footprint.anchors().get(
TemplateFootprint.columnKey(worldX + offsetX, worldZ + offsetZ));
if (anchor == null || anchor.surfaceY() <= originalY) {
continue;
}
int verticalDistance = Math.abs(anchor.surfaceY() + 1 - originalY);
long distanceSquared = horizontalDistanceSquared + (long) verticalDistance * verticalDistance;
double factor = 0D;
if (distanceSquared <= radiusSquared) {
factor = surfaceFactor(Math.sqrt(distanceSquared));
}
if (anchor.strength() > 1 && verticalDistance > SURFACE_TERRAIN_RADIUS) {
double rescueProgress = Math.min(1D,
(verticalDistance - SURFACE_TERRAIN_RADIUS) / (double) SURFACE_TERRAIN_RADIUS);
double rescueWeight = rescueProgress * rescueProgress * (3D - 2D * rescueProgress);
factor = Math.max(factor, surfaceFactor(Math.sqrt(horizontalDistanceSquared)) * rescueWeight);
}
long influence = Math.round(factor * SURFACE_TERRAIN_INFLUENCE_SCALE);
if (influence <= 0L) {
continue;
}
long weightedInfluence = influence * Math.max(1, anchor.strength());
totalInfluence += weightedInfluence;
weightedSurfaceY += weightedInfluence * anchor.surfaceY();
maximumInfluence = Math.max(maximumInfluence, influence);
}
}
if (totalInfluence == 0L) {
return new SurfaceResolution(originalY, false);
}
double blendedSurfaceY = weightedSurfaceY / (double) totalInfluence;
double factor = maximumInfluence / (double) SURFACE_TERRAIN_INFLUENCE_SCALE;
int targetY = (int) Math.round(originalY + ((blendedSurfaceY - originalY) * factor));
if (cap != null) {
targetY = Math.min(targetY, cap);
}
return new SurfaceResolution(Math.max(originalY, targetY), false);
}
private static double surfaceFactor(double distance) {
return Math.pow(1D - distance / SURFACE_TERRAIN_RADIUS, SURFACE_TERRAIN_FALLOFF);
}
static void applySurfaceColumn(FitBlocks blocks, int x, int z, int originalY, int targetY, int worldMinY,
int worldMaxY, boolean requireRigidBaseSupport) {
if (targetY == originalY) {
if (requireRigidBaseSupport) {
ensureRigidBaseTerrain(blocks, x, z, targetY, worldMinY);
}
return;
}
SurfaceMaterials materials = resolveSurfaceMaterials(blocks, x, z, originalY, worldMinY);
if (targetY < originalY) {
BlockState clearedState = clearSurfaceDecorationAndResolveFill(blocks, x, z, originalY, worldMaxY);
for (int y = originalY; y > targetY; y--) {
blocks.set(x, y, z, clearedState);
}
blocks.set(x, targetY, z, materials.surface());
if (requireRigidBaseSupport) {
ensureRigidBaseTerrain(blocks, x, z, targetY, worldMinY, materials);
}
return;
}
for (int y = originalY + 1; y < targetY; y++) {
if (!blocks.isTree(blocks.get(x, y, z))) {
blocks.set(x, y, z, materials.subsurface());
}
}
if (!blocks.isTree(blocks.get(x, targetY, z))) {
blocks.set(x, targetY, z, materials.surface());
}
if (requireRigidBaseSupport) {
ensureRigidBaseTerrain(blocks, x, z, targetY, worldMinY, materials);
}
}
private static void ensureRigidBaseTerrain(FitBlocks blocks, int x, int z, int targetY, int worldMinY) {
int supportY = targetY - 1;
boolean targetIsTerrain = blocks.isTerrain(blocks.get(x, targetY, z));
boolean supportIsTerrain = supportY < worldMinY || blocks.isTerrain(blocks.get(x, supportY, z));
if (targetIsTerrain && supportIsTerrain) {
return;
}
SurfaceMaterials materials = resolveSurfaceMaterials(blocks, x, z, targetY, worldMinY);
ensureRigidBaseTerrain(blocks, x, z, targetY, worldMinY, materials);
}
private static void ensureRigidBaseTerrain(FitBlocks blocks, int x, int z, int targetY, int worldMinY,
SurfaceMaterials materials) {
int supportY = targetY - 1;
if (!blocks.isTerrain(blocks.get(x, targetY, z))) {
blocks.set(x, targetY, z, materials.surface());
}
if (supportY < worldMinY) {
return;
}
if (!blocks.isTerrain(blocks.get(x, supportY, z))) {
blocks.set(x, supportY, z, materials.subsurface());
}
}
private static BlockState clearSurfaceDecorationAndResolveFill(FitBlocks blocks, int x, int z, int originalY,
int worldMaxY) {
for (int y = originalY + 1; y <= worldMaxY; y++) {
BlockState state = blocks.get(x, y, z);
if (blocks.isAir(state)) {
return FitBlocks.AIR;
}
if (blocks.holdsFluid(state)) {
BlockState fluid = blocks.fluidOf(state);
if (!state.equals(fluid)) {
blocks.set(x, y, z, fluid);
}
return fluid;
}
if (blocks.isSolid(state) || blocks.isTree(state)) {
return FitBlocks.AIR;
}
blocks.set(x, y, z, FitBlocks.AIR);
}
return FitBlocks.AIR;
}
private static SurfaceMaterials resolveSurfaceMaterials(FitBlocks blocks, int x, int z, int originalY, int worldMinY) {
BlockState surface = blocks.get(x, originalY, z);
BlockState subsurface = null;
for (int y = originalY - 1; y >= worldMinY; y--) {
BlockState candidate = blocks.get(x, y, z);
if (blocks.isTerrain(candidate)) {
subsurface = candidate;
break;
}
}
if (subsurface == null) {
subsurface = blocks.isTerrain(surface) ? surface : FitBlocks.STONE;
}
if (!blocks.isTerrain(surface)) {
surface = subsurface;
}
return new SurfaceMaterials(surface, subsurface);
}
record SurfaceAnchor(int minX, int maxX, int minZ, int maxZ, int meetY, int strength) {
}
private record SurfaceMaterials(BlockState surface, BlockState subsurface) {
}
private record SurfaceResolution(int targetY, boolean rigidBaseSupport) {
}
private record VacuumFootprint(Map<Long, VacuumAnchor> anchors, Map<Long, Integer> columnCaps,
Set<Long> foundationBases, Set<Long> occupiedCells) {
}
private record VacuumAnchor(int surfaceY, int strength) {
}
/** The foundation bases VACUUM raised the terrain to, kept until the pieces are placed for the repair. */
static final class VacuumFoundationPlan {
static final VacuumFoundationPlan EMPTY = new VacuumFoundationPlan(List.of(), Set.of());
private final List<Long> foundationBases;
private final Set<Long> occupiedCells;
private VacuumFoundationPlan(List<Long> foundationBases, Set<Long> occupiedCells) {
this.foundationBases = foundationBases;
this.occupiedCells = occupiedCells;
}
private static VacuumFoundationPlan create(Set<Long> packedBases, Set<Long> packedOccupancy, Box area) {
if (packedBases.isEmpty()) {
return EMPTY;
}
List<Long> bases = new ArrayList<>(packedBases.size());
Set<Long> columns = new HashSet<>();
for (long packedBase : packedBases) {
int x = TemplateFootprint.packedX(packedBase);
int z = TemplateFootprint.packedZ(packedBase);
if (!area.contains(x, TemplateFootprint.packedY(packedBase), z)) {
continue;
}
bases.add(packedBase);
columns.add(TemplateFootprint.columnKey(x, z));
}
if (bases.isEmpty()) {
return EMPTY;
}
bases.sort((first, second) -> {
int yOrder = Integer.compare(TemplateFootprint.packedY(first), TemplateFootprint.packedY(second));
return yOrder == 0 ? Long.compare(first, second) : yOrder;
});
Set<Long> occupancy = new HashSet<>();
for (long packedCell : packedOccupancy) {
if (columns.contains(TemplateFootprint.columnKey(
TemplateFootprint.packedX(packedCell), TemplateFootprint.packedZ(packedCell)))) {
occupancy.add(packedCell);
}
}
return new VacuumFoundationPlan(List.copyOf(bases), Set.copyOf(occupancy));
}
}
/** Bounds the template blocks one start may read for one fitting. */
static final class TemplateCellBudget {
private final int maximum;
private int consumed;
TemplateCellBudget(int maximum) {
if (maximum < 0) {
throw new IllegalArgumentException("Native structure surface template budget cannot be negative");
}
this.maximum = maximum;
}
void consume(int amount) {
if (amount < 0 || consumed > maximum - amount) {
throw TemplateBudgetExceeded.INSTANCE;
}
consumed += amount;
}
}
static final class TemplateBudgetExceeded extends RuntimeException {
static final TemplateBudgetExceeded INSTANCE = new TemplateBudgetExceeded();
private TemplateBudgetExceeded() {
super(null, null, false, false);
}
}
}
@@ -0,0 +1,98 @@
/*
* Iris is a World Generator for Minecraft Servers
* Copyright (c) 2026 Arcane Arts (Volmit Software)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package art.arcane.iris.engine.framework.structure.fit;
import com.volmit.block.BlockState;
import com.volmit.vanilla.TemplateCells;
import java.util.HashMap;
import java.util.Map;
/** The lowest template cell of each column of a piece, the cells a structure stands on. */
final class TemplateFootprint {
private static final int PACKED_HORIZONTAL_BITS = 26;
private static final int PACKED_VERTICAL_BITS = 12;
private static final long PACKED_HORIZONTAL_MASK = (1L << PACKED_HORIZONTAL_BITS) - 1L;
private static final long PACKED_VERTICAL_MASK = (1L << PACKED_VERTICAL_BITS) - 1L;
private static final int PACKED_X_OFFSET = PACKED_VERTICAL_BITS + PACKED_HORIZONTAL_BITS;
private static final int PACKED_Z_OFFSET = PACKED_VERTICAL_BITS;
private TemplateFootprint() {
}
/** The lowest cell of every column, removed blocks included. */
static Map<Long, Cell> lowestCells(TemplateCells cells, FitPiece piece) {
Map<Long, Cell> lowest = new HashMap<>();
for (int cell = 0; cell < cells.size(); cell++) {
keepLowest(lowest, cells, piece, cell);
}
return lowest;
}
/** The lowest cell of every column that a structure can stand on. */
static Map<Long, Cell> lowestSolidCells(TemplateCells cells, FitPiece piece, FitBlocks blocks) {
Map<Long, Cell> lowest = new HashMap<>();
for (int cell = 0; cell < cells.size(); cell++) {
if (cells.removed(cell) || !blocks.isSolidBase(cells.state(cell))) {
continue;
}
keepLowest(lowest, cells, piece, cell);
}
return lowest;
}
private static void keepLowest(Map<Long, Cell> lowest, TemplateCells cells, FitPiece piece, int cell) {
int y = piece.cellY(cells, cell);
long column = columnKey(cells.x(cell), cells.z(cell));
Cell current = lowest.get(column);
if (current == null || y < current.y()) {
lowest.put(column, new Cell(cells.x(cell), y, cells.z(cell), cells.state(cell)));
}
}
static long columnKey(int x, int z) {
return (long) x << 32 ^ z & 0xffffffffL;
}
/** A block position packed the way the platform packs positions, so sets of them sort the platform's way. */
static long packedPosition(int x, int y, int z) {
return ((long) x & PACKED_HORIZONTAL_MASK) << PACKED_X_OFFSET
| ((long) y & PACKED_VERTICAL_MASK)
| ((long) z & PACKED_HORIZONTAL_MASK) << PACKED_Z_OFFSET;
}
static int packedX(long packed) {
return (int) (packed << (64 - PACKED_X_OFFSET - PACKED_HORIZONTAL_BITS) >> (64 - PACKED_HORIZONTAL_BITS));
}
static int packedY(long packed) {
return (int) (packed << (64 - PACKED_VERTICAL_BITS) >> (64 - PACKED_VERTICAL_BITS));
}
static int packedZ(long packed) {
return (int) (packed << (64 - PACKED_Z_OFFSET - PACKED_HORIZONTAL_BITS) >> (64 - PACKED_HORIZONTAL_BITS));
}
/** A template cell at its world position; no state for a block the processors removed. */
record Cell(int x, int y, int z, BlockState state) {
boolean blocker() {
return state == null;
}
}
}
@@ -0,0 +1,64 @@
/*
* Iris is a World Generator for Minecraft Servers
* Copyright (c) 2026 Arcane Arts (Volmit Software)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package art.arcane.iris.engine.framework.vanillafeatures;
import art.arcane.iris.builtin.RegistryKeyFamily;
import art.arcane.iris.modules.vanillafeatures.ImportedFeaturesSettings;
import com.volmit.resource.ResourceId;
import com.volmit.service.VanillaFeatures;
import com.volmit.vanilla.DecorationStep;
import com.volmit.world.PackWorld;
import java.util.Optional;
/**
* What a dimension's {@link ImportedFeaturesSettings} say about the platform's own placed features: whether they run,
* and which decoration steps and features they leave out. A dimension without the settings runs none.
*/
public final class ImportedFeatures implements VanillaFeatures {
private static final ImportedFeaturesSettings NONE = new ImportedFeaturesSettings();
@Override
public boolean generates(PackWorld world) {
return settings(world).enabled();
}
/** A step the API does not name is allowed unless the dimension narrowed generation to listed steps. */
@Override
public boolean generatesStep(PackWorld world, Optional<DecorationStep> step) {
ImportedFeaturesSettings settings = settings(world);
if (step.isEmpty()) {
return settings.steps().isEmpty();
}
if (!settings.steps().isEmpty() && !settings.steps().contains(step.get())) {
return false;
}
return !settings.disabledSteps().contains(step.get());
}
@Override
public boolean generatesFeature(PackWorld world, ResourceId feature) {
String key = feature.toString();
return settings(world).disabled().stream().noneMatch(pattern -> RegistryKeyFamily.matches(pattern, key));
}
private static ImportedFeaturesSettings settings(PackWorld world) {
return world.settings().declared(ImportedFeaturesSettings.class).dimension().orElse(NONE);
}
}
@@ -0,0 +1,47 @@
/*
* Iris is a World Generator for Minecraft Servers
* Copyright (c) 2026 Arcane Arts (Volmit Software)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package art.arcane.iris.engine.framework.vanillafeatures;
import art.arcane.iris.modules.vanillafeatures.ImportedFeaturesSettings;
import com.volmit.IrisModule;
import com.volmit.ModuleInfo;
import com.volmit.ModuleSetup;
import com.volmit.service.VanillaFeatures;
/**
* Module {@code iris:vanilla-features}: whether the platform's own placed features (ores, trees, plants, springs) run
* over a dimension's terrain, and which steps and features they leave out, decided from the dimension's
* {@code importedFeatures} settings and answered through {@link VanillaFeatures} ({@link ImportedFeatures}). The
* platform runs the feature pass itself; the module has no stages.
*/
public final class VanillaFeaturesModule implements IrisModule {
private static final String VERSION = "built-in";
@Override
public ModuleInfo info() {
return ModuleInfo.of("iris:vanilla-features", "Vanilla features", VERSION);
}
@Override
public void setup(ModuleSetup setup) {
var registry = setup.registry();
registry.registerSettings(ImportedFeaturesSettings.class);
registry.registerService(VanillaFeatures.class, new ImportedFeatures());
}
}
@@ -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 <https://www.gnu.org/licenses/>.
*/
package art.arcane.iris.engine.loot;
import com.volmit.IrisFeature;
import com.volmit.geometry.BlockPosition;
import com.volmit.resource.ResourceId;
import com.volmit.world.RunningWorld;
import com.volmit.world.TerrainSampler;
import java.util.Optional;
/**
* The biome of a block in a running world, as block drops and ambient effects read it: the cave biome where the block
* lies at least two blocks under the column's highest solid block, the surface biome everywhere else.
*/
public final class BlockBiomes {
private static final int CAVE_DEPTH_BELOW_HIGHEST_BLOCK = 2;
private BlockBiomes() {
}
public static ResourceId biomeAt(RunningWorld running, int x, int y, int z) {
TerrainSampler layout = running.layout();
ResourceId surface = layout.surfaceBiome(x, z);
if (!layout.bounds().contains(x, y, z) || y > running.highest(x, z, true) - CAVE_DEPTH_BELOW_HIGHEST_BLOCK) {
return surface;
}
return layout.caveBiome(x, y, z).orElse(surface);
}
/** The settings the biome of the block declares; empty when it declares none. */
public static <F extends IrisFeature> Optional<F> declaredAt(RunningWorld running, Class<F> type, BlockPosition at) {
return running.settings().declaredBy(biomeAt(running, at.x(), at.y(), at.z()), type);
}
}
@@ -0,0 +1,96 @@
/*
* Iris is a World Generator for Minecraft Servers
* Copyright (c) 2026 Arcane Arts (Volmit Software)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package art.arcane.iris.engine.loot;
import art.arcane.iris.modules.loot.BlockDrop;
import art.arcane.iris.modules.loot.BlockDropSettings;
import art.arcane.iris.builtin.loot.LootEntry;
import art.arcane.iris.builtin.loot.LootResolver;
import art.arcane.volmlib.util.math.RNG;
import com.volmit.config.Level;
import com.volmit.config.SettingsStack;
import com.volmit.item.ItemDrop;
import com.volmit.service.BlockDrops;
import com.volmit.world.PackWorld;
import com.volmit.world.RunningWorld;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
/**
* How {@code iris:loot} drops items for broken blocks: the block drops of the biome, the region and the dimension, the
* biome's first and the biome able to keep the others from dropping.
*/
public final class BlockDropping implements BlockDrops {
@Override
public Result drops(PackWorld world, Broken broken) {
RunningWorld running = world.running().orElseThrow();
String brokenKey = world.resources().blocks().find(broken.block().key()).orElse(broken.block()).key();
ResolvedDrops resolved = world.state(ResolvedDrops.class, ignored -> new ResolvedDrops());
SettingsStack<BlockDropSettings> column = running.settings().at(BlockDropSettings.class, broken.position().x(), broken.position().z());
List<ResolvedBlockDrop> providers = dropsFor(BlockBiomes.declaredAt(running, BlockDropSettings.class, broken.position()), brokenKey, resolved, world);
if (providers.stream().noneMatch(provider -> provider.drop().skipParents())) {
providers.addAll(dropsFor(column.level(Level.REGION), brokenKey, resolved, world));
providers.addAll(dropsFor(column.dimension(), brokenKey, resolved, world));
}
LootItems items = new LootItems(world.resources().items(), false, world.log());
List<ItemDrop> drops = new ArrayList<>();
providers.forEach(provider -> fillDrops(provider.drop(), items, drops));
return new Result(drops, providers.stream().anyMatch(provider -> provider.drop().replaceVanillaDrops()));
}
/** Adds the items of the drops that pass their rarity to {@code into}. */
private static void fillDrops(BlockDrop drop, LootItems items, List<ItemDrop> into) {
for (LootEntry entry : drop.drops()) {
if (!LootResolver.oneIn(RNG.r, entry.rarity())) {
continue;
}
ItemDrop given = items.give(entry, RNG.r);
if (given != null) {
into.add(given);
}
}
}
private static List<ResolvedBlockDrop> dropsFor(Optional<BlockDropSettings> declared, String brokenKey, ResolvedDrops resolved,
PackWorld world) {
List<ResolvedBlockDrop> matching = new ArrayList<>();
for (BlockDrop drop : declared.map(BlockDropSettings::drops).orElse(List.of())) {
ResolvedBlockDrop candidate = resolved.of(drop, world);
if (candidate.dropsFor(brokenKey)) {
matching.add(candidate);
}
}
return matching;
}
/** The drops of the world with their blocks resolved, once per drop. */
private static final class ResolvedDrops {
private final ConcurrentMap<BlockDrop, ResolvedBlockDrop> byDrop = new ConcurrentHashMap<>();
private ResolvedBlockDrop of(BlockDrop drop, PackWorld world) {
return byDrop.computeIfAbsent(drop, key -> ResolvedBlockDrop.of(key, world.resources().blocks()));
}
}
}
@@ -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 <https://www.gnu.org/licenses/>.
*/
package art.arcane.iris.engine.loot;
import art.arcane.iris.builtin.IrisSeedPurposes;
import art.arcane.iris.builtin.loot.LootResolver;
import art.arcane.iris.builtin.loot.LootTable;
import art.arcane.iris.engine.loot.PlacedObjectLoot.ObjectLoots;
import art.arcane.volmlib.util.math.RNG;
import com.volmit.item.ItemDrop;
import com.volmit.resource.ResourceId;
import com.volmit.service.Loot;
import com.volmit.world.PackWorld;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.OptionalLong;
/**
* How {@code iris:loot} fills containers: the tables of the object placed around a container, then those of the
* dimension, region and biomes at its column, and the items each table gives. Draws are deterministic per container, so
* a container always holds the same loot.
*/
public final class LootGiving implements Loot {
@Override
public List<Source> tables(PackWorld world, Site site) {
int x = site.position().x();
int z = site.position().z();
int relativeY = site.position().y();
int worldY = relativeY + world.minWorldY();
RNG rng = LootResolver.containerRng(lootSeed(world), x, worldY, z);
List<Source> sources = new ArrayList<>();
boolean objectLootDefined = site.nativeLootDefined();
Optional<ObjectLoots> objectLoots = site.container().isEmpty() ? Optional.empty()
: PlacedObjectLoot.at(world, x, relativeY, z);
if (objectLoots.isPresent()) {
objectLootDefined = objectLootDefined || objectLoots.get().defined();
Source picked = placementLoot(world).pick(objectLoots.get().platformTables(), objectLoots.get().packTables(),
site.container().get(), rng, x, worldY, z);
if (picked != null) {
sources.add(picked);
if (objectLoots.get().overridesGlobalLoot()) {
return sources;
}
}
}
LootTables.resolveEnvironmentSources(sources, world, rng, x, relativeY, z, objectLootDefined,
key -> new Table(world.resources().idOf(key)));
return sources;
}
@Override
public List<ItemDrop> items(PackWorld world, Site site, ResourceId tableId) {
LootTable table = LootResources.table(world.resources(), tableId);
if (table == null) {
return List.of();
}
int worldY = site.position().y() + world.minWorldY();
return new LootItems(world.resources().items(), site.debug(), world.log())
.draw(tableId, table, lootSeed(world), site.position().x(), worldY, site.position().z());
}
@Override
public OptionalLong shuffleSeed(PackWorld world, Site site) {
int worldY = site.position().y() + world.minWorldY();
return OptionalLong.of(LootResolver.containerSeed(lootSeed(world), site.position().x(), worldY, site.position().z()));
}
private static PlacementLoot placementLoot(PackWorld world) {
return new PlacementLoot(world.resources(), () -> world.running().orElseThrow().platformLootTables(), lootSeed(world), world.log());
}
private static long lootSeed(PackWorld world) {
return world.seed(IrisSeedPurposes.LOOT);
}
}
@@ -0,0 +1,185 @@
/*
* Iris is a World Generator for Minecraft Servers
* Copyright (c) 2026 Arcane Arts (Volmit Software)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package art.arcane.iris.engine.loot;
import art.arcane.iris.builtin.loot.ItemAttributeModifier;
import art.arcane.iris.builtin.loot.LootEnchantment;
import art.arcane.iris.builtin.loot.LootEntry;
import art.arcane.iris.builtin.loot.LootSlot;
import art.arcane.iris.builtin.loot.LootTable;
import art.arcane.iris.builtin.loot.LootResolver;
import art.arcane.volmlib.util.math.RNG;
import com.volmit.ModuleLog;
import com.volmit.item.ItemAttribute;
import com.volmit.item.ItemDrop;
import com.volmit.item.ItemEnchantment;
import com.volmit.item.ItemRegistry;
import com.volmit.resource.ContentKey;
import com.volmit.resource.ResourceId;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.OptionalDouble;
import java.util.OptionalInt;
/**
* Turns loot entries into the items they give: every random choice is made here, in the order Iris always made them
* (amount, enchantments, attribute modifiers, damage), so that a container's loot stays what it was. What the platform
* must do with the result is the host's.
*/
public final class LootItems {
private static final ContentKey AIR = new ContentKey.Registered(ResourceId.parse("minecraft:air"));
private static final int MIN_AMOUNT = 1;
private final ItemRegistry items;
private final boolean debug;
private final ModuleLog log;
/**
* @param debug whether the items say where they came from
* @param log hears of keys that name nothing the platform could have
*/
public LootItems(ItemRegistry items, boolean debug, ModuleLog log) {
this.items = items;
this.debug = debug;
this.log = log;
}
/**
* The items {@code table}, which the pack names {@code tableKey}, gives at the spot {@code x}, {@code y}, {@code z}
* (world coordinates): picks entries from the table's own random stream until it has the number of items the table
* asks for or runs out of tries.
*/
public List<ItemDrop> draw(String tableKey, LootTable table, long lootSeed, int x, int y, int z) {
return draw(tableKey, Optional.empty(), table, lootSeed, x, y, z);
}
/** As {@link #draw(String, LootTable, long, int, int, int)} for the pack table {@code tableId}, which the items name as their source. */
public List<ItemDrop> draw(ResourceId tableId, LootTable table, long lootSeed, int x, int y, int z) {
return draw(tableId.path(), Optional.of(tableId), table, lootSeed, x, y, z);
}
private List<ItemDrop> draw(String tableKey, Optional<ResourceId> tableId, LootTable table, long lootSeed, int x, int y, int z) {
List<ItemDrop> drops = new ArrayList<>();
List<LootEntry> entries = table.loot();
if (entries.isEmpty() || table.maxTries() <= 0) {
return drops;
}
String identity = LootTables.identity(tableKey);
RNG rng = LootTables.rng(lootSeed, identity, x, y, z);
int wanted = Math.max(0, LootResolver.inclusive(rng, table.minPicked(), table.maxPicked()));
int tries = 0;
while (drops.size() < wanted && tries++ < table.maxTries()) {
int index = rng.nextInt(entries.size());
LootEntry entry = entries.get(index);
if (entry == null || entry.slotTypes() != LootSlot.STORAGE) {
continue;
}
ItemDrop drop = drawEntry(entry, table, tableId, identity, rng, lootSeed, index, x, y, z);
if (drop != null) {
drops.add(drop);
}
}
return drops;
}
/** The item {@code entry} gives when nothing else decides whether it does, such as a block's drop or a mob's equipment; null for no item. */
public ItemDrop give(LootEntry entry, RNG rng) {
return resolve(entry, rng, null, Optional.empty());
}
/** The attribute modifiers that pass their chances, with their amounts drawn, as for an item or an entity. */
public List<ItemAttribute> attributes(List<ItemAttributeModifier> modifiers, RNG rng) {
List<ItemAttribute> attributes = new ArrayList<>();
for (ItemAttributeModifier modifier : modifiers) {
if (rng.nextDouble() >= modifier.chance()) {
continue;
}
String attribute = modifier.attribute();
if (attribute == null || attribute.isBlank()) {
continue;
}
double amount = rng.d(modifier.minAmount(), modifier.maxAmount());
PlatformKeys.id(attribute, log).ifPresent(id -> attributes.add(
new ItemAttribute(id, modifier.name(), PlatformKeys.operation(modifier.operation()), amount)));
}
return attributes;
}
private ItemDrop drawEntry(LootEntry entry, LootTable table, Optional<ResourceId> tableId, String identity, RNG rng, long lootSeed,
int index, int x, int y, int z) {
long combinedRarity = LootResolver.combinedRarity(entry.rarity(), table.rarity());
if (!LootTables.spatialOneIn(lootSeed, identity, index, x, y, z, combinedRarity)) {
return null;
}
return resolve(entry, rng, table, tableId);
}
private ItemDrop resolve(LootEntry entry, RNG rng, LootTable table, Optional<ResourceId> tableId) {
Optional<ContentKey> item = PlatformKeys.item(entry.type(), log);
if (item.isEmpty() || item.get().equals(AIR)) {
return null;
}
OptionalInt maxDurability = items.maxDurability(item.get());
if (maxDurability.isEmpty()) {
return null;
}
int amount = Math.max(MIN_AMOUNT, LootResolver.inclusive(rng, entry.minAmount(), entry.maxAmount()));
List<ItemEnchantment> enchantments = drawEnchantments(entry, rng);
List<ItemAttribute> attributes = attributes(entry.attributes(), rng);
OptionalDouble damage = maxDurability.getAsInt() > 0
? OptionalDouble.of(1D - rng.d(entry.minDurability(), entry.maxDurability()))
: OptionalDouble.empty();
return new ItemDrop(item.get(), amount, lookOf(entry), enchantments, attributes, new ItemDrop.Wear(entry.unbreakable(), damage),
new ItemDrop.PlatformExtras(entry.itemFlags(), Objects.requireNonNullElse(entry.customNbt(), Map.of())),
debug ? Optional.of(sourceOf(entry, table, tableId)) : Optional.empty());
}
private ItemDrop.Look lookOf(LootEntry entry) {
Integer customModel = entry.customModel();
return new ItemDrop.Look(Optional.ofNullable(entry.displayName()), entry.lore(),
customModel == null ? OptionalInt.empty() : OptionalInt.of(customModel),
PlatformKeys.rgb(entry.leatherColor(), log), PlatformKeys.dye(entry.dyeColor(), log));
}
private List<ItemEnchantment> drawEnchantments(LootEntry entry, RNG rng) {
List<ItemEnchantment> enchantments = new ArrayList<>();
for (LootEnchantment enchantment : entry.enchantments()) {
String key = enchantment.enchantment();
if (key == null || key.isBlank() || rng.nextDouble() >= enchantment.chance()) {
continue;
}
int level = Math.max(1, LootResolver.inclusive(rng, enchantment.minLevel(), enchantment.maxLevel()));
PlatformKeys.id(key, log).ifPresent(id -> enchantments.add(new ItemEnchantment(id, level)));
}
return enchantments;
}
private static ItemDrop.Source sourceOf(LootEntry entry, LootTable table, Optional<ResourceId> tableId) {
if (table == null) {
return new ItemDrop.Source(Optional.empty(), 0, entry.rarity());
}
return new ItemDrop.Source(tableId, table.rarity(), entry.rarity());
}
}
@@ -0,0 +1,53 @@
/*
* Iris is a World Generator for Minecraft Servers
* Copyright (c) 2026 Arcane Arts (Volmit Software)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package art.arcane.iris.engine.loot;
import art.arcane.iris.modules.loot.BlockDropSettings;
import art.arcane.iris.builtin.loot.LootSettings;
import com.volmit.IrisModule;
import com.volmit.ModuleInfo;
import com.volmit.ModuleSetup;
import com.volmit.service.BlockDrops;
import com.volmit.service.Loot;
/**
* Module {@code iris:loot}: the loot tables of the pack ({@link LootResources}), the {@link LootSettings} and
* {@link BlockDropSettings} that dimensions, regions and biomes declare, and the items they give. It checks the tables
* and the references to them ({@link LootValidator}). It has no generation stage; Iris asks it through {@link Loot} when
* a container is filled and through {@link BlockDrops} when a player breaks a block.
*/
public final class LootModule implements IrisModule {
private static final String VERSION = "built-in";
@Override
public ModuleInfo info() {
return ModuleInfo.of("iris:loot", "Loot", VERSION);
}
@Override
public void setup(ModuleSetup setup) {
var registry = setup.registry();
registry.registerSettings(LootSettings.class);
registry.registerSettings(BlockDropSettings.class);
LootResources.kinds().forEach(registry::registerResourceKind);
registry.registerValidator(new LootValidator());
registry.registerService(Loot.class, new LootGiving());
registry.registerService(BlockDrops.class, new BlockDropping());
}
}
@@ -0,0 +1,67 @@
/*
* Iris is a World Generator for Minecraft Servers
* Copyright (c) 2026 Arcane Arts (Volmit Software)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package art.arcane.iris.engine.loot;
import art.arcane.iris.builtin.loot.LootTable;
import com.volmit.resource.PackResources;
import com.volmit.resource.ResourceId;
import com.volmit.resource.ResourceKind;
import java.util.List;
/**
* The resource kind of module {@code iris:loot}, which keeps the folder and files Iris packs have always used, and
* lookups by pack key for code that still names loot tables by key. Every lookup goes through the pack's
* {@link com.volmit.resource.PackResources}, so it sees the pack's current snapshot.
* <p>
* Lookups answer null where Iris's loader did: for a blank key, a key the pack has no file for, and a file that fails
* to load, which was reported when it was read.
*/
public final class LootResources {
/** Loot tables, in {@code loot/}. */
public static final ResourceKind<LootTable> TABLES = ResourceKind.of("iris:loot/table", "loot", LootTable.class);
private LootResources() {
}
/** Every resource kind of the loot module. */
public static List<ResourceKind<?>> kinds() {
return List.of(TABLES);
}
public static LootTable table(PackResources resources, String key) {
if (key == null || key.isBlank()) {
return null;
}
return table(resources, resources.idOf(key));
}
public static LootTable table(PackResources resources, ResourceId id) {
try {
return resources.find(TABLES, id).orElse(null);
} catch (IllegalStateException failedToLoad) {
return null;
}
}
/** The key of every loot table of the pack, in key order. */
public static List<String> tableKeys(PackResources resources) {
return resources.ids(TABLES).stream().map(ResourceId::path).toList();
}
}
@@ -0,0 +1,158 @@
/*
* Iris is a World Generator for Minecraft Servers
* Copyright (c) 2026 Arcane Arts (Volmit Software)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package art.arcane.iris.engine.loot;
import art.arcane.iris.builtin.loot.LootMode;
import art.arcane.iris.builtin.loot.LootResolver;
import art.arcane.iris.builtin.loot.LootSettings;
import art.arcane.volmlib.util.math.RNG;
import com.volmit.config.Level;
import com.volmit.config.SettingsStack;
import com.volmit.resource.ResourceId;
import com.volmit.world.PackWorld;
import com.volmit.world.RunningWorld;
import com.volmit.world.TerrainSampler;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.function.Function;
/**
* Which loot tables a place in the world draws from, and the random streams that draw from them: the part of loot
* that reads the pack's tables, loot settings and layout. The streams themselves are {@link LootResolver}'s; here a
* table is named by its {@linkplain #identity identity}, the key the pack names it by.
*/
public final class LootTables {
private static final String VANILLA_IDENTITY_PREFIX = "Vanilla ";
private LootTables() {
}
/** What names a table in the random streams: the key a pack table is named by. */
public static String identity(String tableKey) {
return tableKey;
}
/** What names a table of the platform in the random streams. */
public static String platformIdentity(String platformKey) {
return VANILLA_IDENTITY_PREFIX + platformKey;
}
public static RNG rng(long lootSeed, String identity, int x, int y, int z) {
return LootResolver.tableRng(lootSeed, identity, x, y, z);
}
public static long seed(long lootSeed, String identity, int x, int y, int z) {
return LootResolver.tableSeed(lootSeed, identity, x, y, z);
}
public static boolean spatialOneIn(long lootSeed, String identity, int entryIndex, int x, int y, int z, long rarity) {
return LootResolver.spatialOneIn(lootSeed, identity, entryIndex, x, y, z, rarity);
}
/** The declared loot settings; the defaults, which add nothing, when none are declared. */
private static LootSettings orDefaults(Optional<LootSettings> declared) {
return declared.orElseGet(LootSettings::new);
}
/** The cave biome of a block under the terrain's surface, when it is not the column's surface biome. */
private static Optional<ResourceId> distinctCaveBiome(TerrainSampler layout, int x, int relativeY, int z) {
if (relativeY >= layout.surfaceY(x, z) || !layout.bounds().contains(x, relativeY, z)) {
return Optional.empty();
}
ResourceId surface = layout.surfaceBiome(x, z);
return layout.caveBiome(x, relativeY, z).filter(cave -> !cave.equals(surface));
}
/**
* Adds the tables of the dimension, the region, the surface biome and (below the surface) the cave biome at a
* column to {@code sources}, as their loot settings say, then scales their number by the areas' multipliers.
* {@code mapper} turns the key of a table into the caller's own source; a null result skips it.
*/
public static <T> void resolveEnvironmentSources(
List<T> sources,
PackWorld world,
RNG rng,
int x,
int relativeY,
int z,
boolean objectLootDefined,
Function<String, T> mapper
) {
RunningWorld running = world.running().orElseThrow();
Optional<ResourceId> distinctCaveBiome = distinctCaveBiome(running.layout(), x, relativeY, z);
SettingsStack<LootSettings> column = running.settings().at(LootSettings.class, x, z);
LootSettings dimensionLoot = orDefaults(column.dimension());
LootSettings regionLoot = orDefaults(column.level(Level.REGION));
LootSettings surfaceLoot = orDefaults(column.level(Level.BIOME));
double multiplier = dimensionLoot.multiplier() * regionLoot.multiplier() * surfaceLoot.multiplier();
LootSettings contextualLoot = distinctCaveBiome
.map(cave -> orDefaults(running.settings().declaredBy(cave, LootSettings.class)))
.orElse(null);
if (contextualLoot != null) {
multiplier *= contextualLoot.multiplier();
}
boolean fallback = !objectLootDefined;
injectReference(sources, dimensionLoot, world, mapper, fallback);
injectReference(sources, regionLoot, world, mapper, fallback);
injectReference(sources, surfaceLoot, world, mapper, fallback);
if (contextualLoot != null) {
injectReference(sources, contextualLoot, world, mapper, fallback);
}
LootResolver.scaleSources(sources, multiplier, rng);
}
/** Adds {@code additions} to {@code sources} the way {@code mode} says; {@code fallback} is whether nothing else defined a table. */
public static <T> void injectSources(
List<T> sources,
List<? extends T> additions,
LootMode mode,
boolean fallback
) {
if (mode == LootMode.FALLBACK && !fallback) {
return;
}
if (mode == LootMode.CLEAR) {
sources.clear();
return;
}
if (mode == LootMode.REPLACE) {
sources.clear();
}
sources.addAll(additions);
}
private static <T> void injectReference(
List<T> sources,
LootSettings loot,
PackWorld world,
Function<String, T> mapper,
boolean fallback
) {
List<T> additions = loot.tables().stream()
.filter(key -> LootResources.table(world.resources(), key) != null)
.map(mapper)
.filter(Objects::nonNull)
.toList();
injectSources(sources, additions, loot.mode(), fallback);
}
}
@@ -0,0 +1,227 @@
/*
* Iris is a World Generator for Minecraft Servers
* Copyright (c) 2026 Arcane Arts (Volmit Software)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package art.arcane.iris.engine.loot;
import art.arcane.iris.builtin.loot.LootEnchantment;
import art.arcane.iris.builtin.loot.LootEntry;
import art.arcane.iris.builtin.loot.LootMode;
import art.arcane.iris.builtin.loot.LootSettings;
import art.arcane.iris.builtin.loot.LootTable;
import com.volmit.config.FeatureSettings.Entry;
import com.volmit.config.Level;
import com.volmit.resource.PackResources;
import com.volmit.resource.ResourceId;
import com.volmit.validation.Problem;
import com.volmit.validation.Subject;
import com.volmit.validation.ValidationContext;
import com.volmit.validation.Validator;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Set;
import java.util.function.BiFunction;
/**
* Module {@code iris:loot}'s check of a pack: every loot table has sane picks, tries and entries, and every loot
* reference of a dimension, region or biome names a table the pack has. It checks the tables and settings as they
* decoded; a file that is not valid JSON, or holds a value of the wrong type, fails to load, and the check reports why.
*/
public final class LootValidator implements Validator {
private static final String JSON_EXTENSION = ".json";
private static final String LEVEL_FOLDER_SEPARATOR = "/";
@Override
public void validate(ValidationContext pack) {
checkTables(pack.resources()).forEach(pack::report);
checkReferences(pack).forEach(pack::report);
}
private static List<Problem> checkTables(PackResources resources) {
List<Problem> problems = new ArrayList<>();
for (ResourceId id : resources.ids(LootResources.TABLES)) {
String lootKey = id.path();
List<String> errors = new ArrayList<>();
LootTable table = readTable(resources, id, lootKey, errors);
if (table != null) {
validateLootTable(lootKey, table, errors);
}
report(problems, Problem::error, Subject.file(LootResources.TABLES.folder() + "/" + lootKey + JSON_EXTENSION), errors);
}
return problems;
}
private static List<Problem> checkReferences(ValidationContext pack) {
Set<ResourceId> lootIds = Set.copyOf(pack.resources().ids(LootResources.TABLES));
List<Problem> problems = new ArrayList<>();
List<Entry<LootSettings>> declared = new ArrayList<>(pack.settings().declared(LootSettings.class).entries());
declared.sort(Comparator.comparing(Entry<LootSettings>::level).thenComparing(Entry::source));
for (Entry<LootSettings> entry : declared) {
String resourceKey = keyOf(entry);
List<String> errors = new ArrayList<>();
List<String> warnings = new ArrayList<>();
validateLootReference(pack.resources(), hostType(entry.level()), resourceKey, entry.value(), lootIds, errors, warnings);
Subject subject = Subject.file(folderOf(entry.level()) + "/" + resourceKey + JSON_EXTENSION);
report(problems, Problem::error, subject, errors);
report(problems, Problem::warning, subject, warnings);
}
return problems;
}
private static void report(List<Problem> problems, BiFunction<Subject, String, Problem> severity,
Subject subject, List<String> messages) {
for (String message : messages) {
problems.add(severity.apply(subject, message));
}
}
private static LootTable readTable(PackResources resources, ResourceId id, String key, List<String> errors) {
try {
return resources.find(LootResources.TABLES, id).orElse(null);
} catch (IllegalStateException failedToLoad) {
errors.add("Loot table '" + key + "' cannot be read: " + failedToLoad.getMessage());
return null;
}
}
/** The key of the dimension, region or biome that declared {@code entry}: its source id is {@code <pack>:<level>/<key>}. */
private static String keyOf(Entry<LootSettings> entry) {
String path = entry.source().path();
return path.substring(path.indexOf(LEVEL_FOLDER_SEPARATOR) + 1);
}
private static String hostType(Level level) {
return switch (level) {
case DIMENSION -> "Dimension";
case REGION -> "Region";
case BIOME -> "Biome";
case PLACEMENT -> "Resource";
};
}
private static String folderOf(Level level) {
return switch (level) {
case DIMENSION -> "dimensions";
case REGION -> "regions";
case BIOME -> "biomes";
case PLACEMENT -> "placements";
};
}
private static void validateLootTable(String lootKey, LootTable table, List<String> blockingErrors) {
String path = "Loot table '" + lootKey + "'";
requireMinimum(path + ".rarity", table.rarity(), 1, blockingErrors);
requireMinimum(path + ".minPicked", table.minPicked(), 0, blockingErrors);
requireMinimum(path + ".maxPicked", table.maxPicked(), 1, blockingErrors);
requireMinimum(path + ".maxTries", table.maxTries(), 1, blockingErrors);
requireMaximum(path + ".minPicked", table.minPicked(), LootTable.MAX_PICKED, blockingErrors);
requireMaximum(path + ".maxPicked", table.maxPicked(), LootTable.MAX_PICKED, blockingErrors);
requireMaximum(path + ".maxTries", table.maxTries(), LootTable.MAX_TRIES, blockingErrors);
requireOrdered(path + ".minPicked", table.minPicked(), path + ".maxPicked", table.maxPicked(), blockingErrors);
List<LootEntry> entries = table.loot();
if (entries.isEmpty()) {
blockingErrors.add(path + ".loot must be a non-empty array.");
return;
}
for (int entryIndex = 0; entryIndex < entries.size(); entryIndex++) {
validateLootEntry(path + ".loot[" + entryIndex + "]", entries.get(entryIndex), blockingErrors);
}
}
private static void validateLootEntry(String entryPath, LootEntry entry, List<String> blockingErrors) {
if (entry == null) {
blockingErrors.add(entryPath + " must be an object.");
return;
}
if (entry.type().trim().isEmpty()) {
blockingErrors.add(entryPath + ".type must not be blank.");
}
requireMinimum(entryPath + ".rarity", entry.rarity(), 1, blockingErrors);
requireMinimum(entryPath + ".minAmount", entry.minAmount(), 1, blockingErrors);
requireMinimum(entryPath + ".maxAmount", entry.maxAmount(), 1, blockingErrors);
requireMaximum(entryPath + ".minAmount", entry.minAmount(), LootEntry.MAX_AMOUNT, blockingErrors);
requireMaximum(entryPath + ".maxAmount", entry.maxAmount(), LootEntry.MAX_AMOUNT, blockingErrors);
requireOrdered(entryPath + ".minAmount", entry.minAmount(), entryPath + ".maxAmount", entry.maxAmount(), blockingErrors);
List<LootEnchantment> enchantments = entry.enchantments();
for (int enchantmentIndex = 0; enchantmentIndex < enchantments.size(); enchantmentIndex++) {
validateEnchantment(entryPath + ".enchantments[" + enchantmentIndex + "]", enchantments.get(enchantmentIndex), blockingErrors);
}
}
private static void validateEnchantment(String enchantmentPath, LootEnchantment enchantment, List<String> blockingErrors) {
if (enchantment == null) {
blockingErrors.add(enchantmentPath + " must be an object.");
return;
}
String name = enchantment.enchantment();
if (name == null || name.isBlank()) {
blockingErrors.add(enchantmentPath + ".enchantment must not be blank.");
}
requireMinimum(enchantmentPath + ".minLevel", enchantment.minLevel(), 1, blockingErrors);
requireMinimum(enchantmentPath + ".maxLevel", enchantment.maxLevel(), 1, blockingErrors);
requireOrdered(enchantmentPath + ".minLevel", enchantment.minLevel(),
enchantmentPath + ".maxLevel", enchantment.maxLevel(), blockingErrors);
double chance = enchantment.chance();
if (!Double.isFinite(chance) || chance < 0D || chance > 1D) {
blockingErrors.add(enchantmentPath + ".chance must be a finite number from 0 to 1.");
}
}
private static void validateLootReference(PackResources resources, String resourceType, String resourceKey, LootSettings reference,
Set<ResourceId> lootIds, List<String> blockingErrors, List<String> warnings) {
String path = resourceType + " '" + resourceKey + "'.loot";
double multiplier = reference.multiplier();
if (!Double.isFinite(multiplier) || multiplier < 0D || multiplier > LootSettings.MAX_MULTIPLIER) {
blockingErrors.add(path + ".multiplier must be a finite number from 0 to " + (int) LootSettings.MAX_MULTIPLIER + ".");
}
List<String> tables = reference.tables();
if (reference.mode() == LootMode.CLEAR && !tables.isEmpty()) {
warnings.add(path + " uses mode CLEAR and lists " + tables.size()
+ " table(s); CLEAR clears parent tables and contributes no tables of its own, so these entries are dead. Use REPLACE to substitute them.");
}
for (int tableIndex = 0; tableIndex < tables.size(); tableIndex++) {
String tableKey = tables.get(tableIndex);
if (tableKey == null || tableKey.isBlank()) {
blockingErrors.add(path + ".tables[" + tableIndex + "] must name a loot table.");
} else if (!lootIds.contains(resources.idOf(tableKey))) {
blockingErrors.add(path + ".tables[" + tableIndex + "] references missing loot table '" + tableKey + "'.");
}
}
}
private static void requireMinimum(String fieldPath, int value, int minimum, List<String> blockingErrors) {
if (value < minimum) {
blockingErrors.add(fieldPath + " must be at least " + minimum + ".");
}
}
private static void requireMaximum(String fieldPath, int value, int maximum, List<String> blockingErrors) {
if (value > maximum) {
blockingErrors.add(fieldPath + " must be at most " + maximum + ".");
}
}
private static void requireOrdered(String minimumPath, int minimum, String maximumPath, int maximum, List<String> blockingErrors) {
if (minimum > maximum) {
blockingErrors.add(minimumPath + " must not exceed " + maximumPath + ".");
}
}
}
@@ -0,0 +1,107 @@
/*
* Iris is a World Generator for Minecraft Servers
* Copyright (c) 2026 Arcane Arts (Volmit Software)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package art.arcane.iris.engine.loot;
import art.arcane.iris.builtin.loot.ObjectLoot;
import art.arcane.iris.builtin.loot.ObjectVanillaLoot;
import art.arcane.iris.builtin.objects.ObjectPlacement;
import art.arcane.iris.builtin.objects.ObjectSettings;
import art.arcane.iris.builtin.structure.StructureHost;
import com.volmit.config.Level;
import com.volmit.config.SettingsStack;
import com.volmit.placement.PlacementRecord;
import com.volmit.resource.PackResources;
import com.volmit.resource.ResourceId;
import com.volmit.world.PackWorld;
import com.volmit.world.RunningWorld;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
/**
* The loot of the object placed at a block, found from the placement the world recorded there: a structure piece gives
* its structure's tables; any other object the tables of the first placement of the column's region, then of its
* surface biome, that places it. Procedural objects give none.
*/
final class PlacedObjectLoot {
private static final String PROCEDURAL_PREFIX = "procedural/";
private static final int STRUCTURE_TABLE_WEIGHT = 1;
private PlacedObjectLoot() {
}
/**
* The loot an object placement gives its containers.
*
* @param packTables tables of the pack
* @param platformTables tables of the platform
* @param overridesGlobalLoot whether the placement's tables replace those of the dimension, region and biomes
*/
record ObjectLoots(List<ObjectLoot> packTables, List<ObjectVanillaLoot> platformTables, boolean overridesGlobalLoot) {
ObjectLoots {
packTables = List.copyOf(packTables);
platformTables = List.copyOf(platformTables);
}
/** Whether the placement names any table. */
boolean defined() {
return !packTables.isEmpty() || !platformTables.isEmpty();
}
}
/** The loot of the object placed at the block; empty when no object placement covers the block. Y is above the dimension's bottom. */
static Optional<ObjectLoots> at(PackWorld world, int x, int y, int z) {
RunningWorld running = world.running().orElseThrow();
Optional<PlacementRecord> recorded = running.placementAt(x, y, z);
if (recorded.isEmpty() || recorded.get().object().path().startsWith(PROCEDURAL_PREFIX)) {
return Optional.empty();
}
ResourceId object = recorded.get().object();
Optional<ObjectPlacement> placement = recorded.get().structure().isPresent()
? structurePlacement(world, recorded.get().structure().get(), object)
: columnPlacement(world.resources(), running.settings().at(ObjectSettings.class, x, z), object);
return placement.map(found -> new ObjectLoots(found.loot(), found.vanillaLoot(), found.overrideGlobalLoot()));
}
/** A structure piece's object gives every table its structure names, each once. */
private static Optional<ObjectPlacement> structurePlacement(PackWorld world, ResourceId structure, ResourceId object) {
Optional<List<String>> tables = world.extension(StructureHost.class).orElseThrow().lootTables(structure);
if (tables.isEmpty() || world.resources().objects().object(object).isEmpty()) {
return Optional.empty();
}
List<ObjectLoot> loot = new ArrayList<>();
for (String table : tables.get()) {
loot.add(new ObjectLoot(table, STRUCTURE_TABLE_WEIGHT));
}
return Optional.of(ObjectPlacement.builder().place(List.of(object.path())).loot(loot).build());
}
private static Optional<ObjectPlacement> columnPlacement(PackResources resources, SettingsStack<ObjectSettings> declared,
ResourceId object) {
Optional<ObjectPlacement> fromRegion = declared.level(Level.REGION).flatMap(settings -> placing(resources, settings, object));
return fromRegion.isPresent() ? fromRegion : declared.level(Level.BIOME).flatMap(settings -> placing(resources, settings, object));
}
private static Optional<ObjectPlacement> placing(PackResources resources, ObjectSettings settings, ResourceId object) {
return settings.objects().stream()
.filter(placement -> placement.place().stream().anyMatch(key -> resources.idOf(key).equals(object)))
.findFirst();
}
}
@@ -0,0 +1,163 @@
/*
* Iris is a World Generator for Minecraft Servers
* Copyright (c) 2026 Arcane Arts (Volmit Software)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package art.arcane.iris.engine.loot;
import art.arcane.iris.builtin.loot.LootResolver;
import art.arcane.iris.builtin.loot.ObjectLootEntry;
import art.arcane.volmlib.util.math.RNG;
import com.volmit.ModuleLog;
import com.volmit.block.BlockSpec;
import com.volmit.block.BlockState;
import com.volmit.resource.PackResources;
import com.volmit.resource.ResourceId;
import com.volmit.service.Loot;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.function.Function;
import java.util.function.Supplier;
/**
* The loot table an object placement gives to one of its containers: the placement's tables and the platform's own,
* each with the blocks it applies to and a weight. A table that names the container's exact block wins over one that
* names the container's kind of block, which wins over one that names no blocks; among equals the weights pick.
*/
final class PlacementLoot {
private static final String VANILLA_NAMESPACE = "minecraft:";
private static final char NAMESPACE_SEPARATOR = ':';
private static final char PROPERTIES_START = '[';
private final PackResources resources;
private final Supplier<Set<ResourceId>> platformTables;
private final long lootSeed;
private final ModuleLog log;
/** @param platformTables the ids of the loot tables the platform has, asked for only when a placement names one */
PlacementLoot(PackResources resources, Supplier<Set<ResourceId>> platformTables, long lootSeed, ModuleLog log) {
this.resources = resources;
this.platformTables = platformTables;
this.lootSeed = lootSeed;
this.log = log;
}
/**
* The table a placement, whose platform tables are {@code platformLoot} and whose pack tables are {@code packLoot},
* gives {@code container}, a storage chest, at the spot {@code x}, {@code worldY}, {@code z}; null when it gives
* it none.
*/
Loot.Source pick(List<? extends ObjectLootEntry> platformLoot, List<? extends ObjectLootEntry> packLoot, BlockState container,
RNG rng, int x, int worldY, int z) {
Candidates candidates = new Candidates(resources.blocks().find(container.key()).orElse(container));
add(candidates, platformLoot, name -> platformSource(name, x, worldY, z));
add(candidates, packLoot, this::packSource);
List<Candidate> pool = candidates.pool();
Candidate picked = LootResolver.pickWeighted(pool, Candidate::weight, rng);
return picked == null ? null : picked.source();
}
private void add(Candidates candidates, List<? extends ObjectLootEntry> entries, Function<String, Loot.Source> sourceOf) {
for (ObjectLootEntry entry : entries) {
if (entry == null || entry.weight() <= 0) {
continue;
}
Loot.Source source = sourceOf.apply(entry.name());
if (source == null) {
log.warn("Couldn't find loot table " + entry.name());
continue;
}
candidates.add(entry, resources, new Candidate(source, entry.weight()));
}
}
private Loot.Source packSource(String key) {
return LootResources.table(resources, key) == null ? null : new Loot.Table(resources.idOf(key));
}
private Loot.Source platformSource(String name, int x, int worldY, int z) {
String key = platformKey(name);
ResourceId table = key == null ? null : platformTableId(key);
if (table == null || !platformTables.get().contains(table)) {
return null;
}
return new Loot.PlatformTable(table, LootTables.seed(lootSeed, LootTables.platformIdentity(key), x, worldY, z));
}
/** The id of the platform table the key names, or null for a key that is no id, which names no table. */
private static ResourceId platformTableId(String key) {
try {
return ResourceId.parse(key);
} catch (IllegalArgumentException notAnId) {
return null;
}
}
/** A placement's name for a platform table as the platform's key for it, or null for a name that cannot be one. */
static String platformKey(String name) {
if (name == null || name.isBlank()) {
return null;
}
return name.indexOf(NAMESPACE_SEPARATOR) < 0 ? VANILLA_NAMESPACE + name : name;
}
private record Candidate(Loot.Source source, int weight) {
}
/** The candidates for one container, in the groups the placement gives them. */
private static final class Candidates {
private final String containerKey;
private final String containerMaterial;
private final List<Candidate> exact = new ArrayList<>();
private final List<Candidate> basic = new ArrayList<>();
private final List<Candidate> global = new ArrayList<>();
private Candidates(BlockState container) {
this.containerKey = container.key();
this.containerMaterial = materialOf(containerKey);
}
void add(ObjectLootEntry entry, PackResources resources, Candidate candidate) {
List<BlockSpec> filter = entry.filter();
if (filter.isEmpty()) {
global.add(candidate);
return;
}
for (BlockSpec filterSpec : filter) {
String filterKey = resources.blocks().resolve(filterSpec).key();
if (entry.exact() && filterKey.equals(containerKey)) {
exact.add(candidate);
} else if (!entry.exact() && materialOf(filterKey).equals(containerMaterial)) {
basic.add(candidate);
}
}
}
List<Candidate> pool() {
if (!exact.isEmpty()) {
return exact;
}
return basic.isEmpty() ? global : basic;
}
private static String materialOf(String blockKey) {
int properties = blockKey.indexOf(PROPERTIES_START);
return properties < 0 ? blockKey : blockKey.substring(0, properties);
}
}
}
@@ -0,0 +1,130 @@
/*
* Iris is a World Generator for Minecraft Servers
* Copyright (c) 2026 Arcane Arts (Volmit Software)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package art.arcane.iris.engine.loot;
import com.volmit.ModuleLog;
import com.volmit.item.ItemAttribute;
import com.volmit.item.DyeColor;
import com.volmit.resource.ContentKey;
import com.volmit.resource.ResourceId;
import java.util.Locale;
import java.util.Optional;
import java.util.OptionalInt;
/**
* The platform things packs name, as they write them, turned into what IrisApi hands the host: ids, items and mobs,
* attribute operations and colours. A blank key names nothing; a key that names nothing the host could look up is left
* out with a warning, once per key.
*/
public final class PlatformKeys {
private static final String PLATFORM_NAMESPACE = "minecraft";
private static final char NAMESPACE_SEPARATOR = ':';
private static final String WARNING_KEY = "iris:platform-key/";
private PlatformKeys() {
}
/** {@code key} as an id, such as {@code minecraft:sharpness} for {@code Sharpness}; see {@link ResourceId#ofPlatformKey}. */
public static Optional<ResourceId> id(String key, ModuleLog log) {
if (key == null || key.isBlank()) {
return Optional.empty();
}
try {
return Optional.of(ResourceId.ofPlatformKey(key));
} catch (IllegalArgumentException invalid) {
log.warnOnce(WARNING_KEY + key, "Ignoring '" + key + "': it names nothing the platform could have");
return Optional.empty();
}
}
/**
* The item {@code key} names. A key of the platform's own namespace, or of none, is a registered item; so is a key of
* another namespace an id can hold as written, such as {@code itemsadder:ruby}, which the host routes to its owner.
* Any other namespaced key is a provider's item, kept as written.
*/
public static Optional<ContentKey> item(String key, ModuleLog log) {
if (key == null || key.isBlank()) {
return Optional.empty();
}
String written = key.trim();
int separator = written.indexOf(NAMESPACE_SEPARATOR);
if (separator < 0 || PLATFORM_NAMESPACE.equalsIgnoreCase(written.substring(0, separator))) {
return id(written, log).map(ContentKey.Registered::new);
}
try {
return Optional.of(new ContentKey.Registered(ResourceId.parse(written)));
} catch (IllegalArgumentException notAnId) {
return provided(written, log);
}
}
/** A provider's mob or item, written {@code provider:name}, such as {@code mythicmobs:SkeletonKing}. */
public static Optional<ContentKey> provided(String key, ModuleLog log) {
if (key == null || key.isBlank()) {
return Optional.empty();
}
String written = key.trim();
int separator = written.indexOf(NAMESPACE_SEPARATOR);
if (separator <= 0 || separator == written.length() - 1) {
log.warnOnce(WARNING_KEY + key, "Ignoring '" + key + "': a provider's content is written provider:name");
return Optional.empty();
}
return Optional.of(new ContentKey.Provided(written.substring(0, separator), written.substring(separator + 1)));
}
/**
* The attribute operation packs name by Bukkit's names, {@code ADD_NUMBER}, {@code ADD_SCALAR} and
* {@code MULTIPLY_SCALAR_1}, or by the platform's own; adding the amount for a name it does not know.
*/
public static ItemAttribute.Operation operation(String name) {
String normalized = name == null ? "" : name.trim().toUpperCase(Locale.ROOT);
return switch (normalized) {
case "ADD_SCALAR", "ADD_MULTIPLIED_BASE" -> ItemAttribute.Operation.ADD_MULTIPLIED_BASE;
case "MULTIPLY_SCALAR_1", "ADD_MULTIPLIED_TOTAL" -> ItemAttribute.Operation.ADD_MULTIPLIED_TOTAL;
default -> ItemAttribute.Operation.ADD_VALUE;
};
}
/** The colour {@code text} writes, {@code #rrggbb}, {@code 0xrrggbb} or a number; empty, with a warning, for anything else. */
public static OptionalInt rgb(String text, ModuleLog log) {
if (text == null || text.isBlank()) {
return OptionalInt.empty();
}
try {
return OptionalInt.of(Integer.decode(text.trim()) & 0xFFFFFF);
} catch (NumberFormatException notAColour) {
log.warnOnce(WARNING_KEY + text, "Ignoring the colour '" + text + "': write it as #rrggbb");
return OptionalInt.empty();
}
}
/** The dye colour {@code name} names, such as {@code RED} or {@code light_blue}; empty, with a warning, for anything else. */
public static Optional<DyeColor> dye(String name, ModuleLog log) {
if (name == null || name.isBlank()) {
return Optional.empty();
}
try {
return Optional.of(DyeColor.valueOf(name.trim().toUpperCase(Locale.ROOT)));
} catch (IllegalArgumentException unknown) {
log.warnOnce(WARNING_KEY + name, "Ignoring the dye colour '" + name + "', which is none of the sixteen dyes");
return Optional.empty();
}
}
}
@@ -0,0 +1,67 @@
/*
* Iris is a World Generator for Minecraft Servers
* Copyright (c) 2026 Arcane Arts (Volmit Software)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package art.arcane.iris.engine.loot;
import art.arcane.iris.modules.loot.BlockDrop;
import com.volmit.block.BlockRegistry;
import com.volmit.block.BlockSpec;
import java.util.LinkedHashSet;
import java.util.Set;
/** A {@link BlockDrop} with the blocks it names resolved to the platform's: which broken blocks it drops for. */
final class ResolvedBlockDrop {
private static final char PROPERTIES_START = '[';
private final BlockDrop drop;
private final boolean exact;
private final Set<String> blocks;
private ResolvedBlockDrop(BlockDrop drop, Set<String> blocks) {
this.drop = drop;
this.exact = drop.exactBlocks();
this.blocks = blocks;
}
/** @param blocks the pack's blocks, which the drop's block specs resolve against */
static ResolvedBlockDrop of(BlockDrop drop, BlockRegistry blocks) {
Set<String> keys = new LinkedHashSet<>();
for (BlockSpec spec : drop.blocks()) {
keys.add(comparable(blocks.resolve(spec).key(), drop.exactBlocks()));
}
return new ResolvedBlockDrop(drop, keys);
}
BlockDrop drop() {
return drop;
}
/** Whether the drop applies to {@code brokenKey}, the platform's key for the broken block: its exact state, or just its kind of block. */
boolean dropsFor(String brokenKey) {
return blocks.contains(comparable(brokenKey, exact));
}
private static String comparable(String key, boolean exact) {
if (exact) {
return key;
}
int properties = key.indexOf(PROPERTIES_START);
return properties < 0 ? key : key.substring(0, properties);
}
}
@@ -0,0 +1,264 @@
/*
* Iris is a World Generator for Minecraft Bukkit Servers
* Copyright (c) 2022 Arcane Arts (Volmit Software)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package art.arcane.iris.engine.mantle.components;
import art.arcane.volmlib.util.math.PowerOfTwoCoordinates;
import com.volmit.mantle.CarvedVoid;
import com.volmit.mantle.MantleLayer;
import java.util.Arrays;
public final class CarveOrphanSweep {
private static final int CHUNK_SIZE = 16;
private static final int CHUNK_AREA = CHUNK_SIZE * CHUNK_SIZE;
private static final int BAND_FLOOR_MARGIN = 4;
private static final int MAX_ORPHAN_CELLS = 16;
private static final ThreadLocal<SweepScratch> SCRATCH = ThreadLocal.withInitial(SweepScratch::new);
public interface CarveAccess {
boolean isCarved(int localX, int y, int localZ);
void markCarved(int localX, int y, int localZ);
default boolean isProtected(int localX, int y, int localZ) {
return false;
}
}
private CarveOrphanSweep() {
}
/** Sweeps the chunk whose first block is {@code originX}, {@code originZ}. */
static int sweepChunk(
MantleLayer<CarvedVoid> voids,
int originX,
int originZ,
int[] surfaceHeights,
int maxSurfaceBreakDepth,
int worldCeilingY,
int[] surfaceFluidBoundaryStartY,
int fluidHeight
) {
return sweep(surfaceHeights, maxSurfaceBreakDepth, 0, worldCeilingY,
new MantleCarveAccess(voids, originX, originZ, surfaceFluidBoundaryStartY, fluidHeight));
}
public static int sweep(int[] surfaceHeights, int maxSurfaceBreakDepth, int worldFloorY, int worldCeilingY, CarveAccess access) {
if (surfaceHeights == null || surfaceHeights.length < CHUNK_AREA || access == null) {
return 0;
}
int minSurfaceY = Integer.MAX_VALUE;
int maxSurfaceY = Integer.MIN_VALUE;
for (int columnIndex = 0; columnIndex < CHUNK_AREA; columnIndex++) {
int surfaceY = surfaceHeights[columnIndex];
if (surfaceY < minSurfaceY) {
minSurfaceY = surfaceY;
}
if (surfaceY > maxSurfaceY) {
maxSurfaceY = surfaceY;
}
}
int bandTop = Math.min(worldCeilingY, maxSurfaceY);
int bandFloor = Math.max(worldFloorY + 1, minSurfaceY - Math.max(0, maxSurfaceBreakDepth) - BAND_FLOOR_MARGIN);
if (bandTop < bandFloor) {
return 0;
}
int bandHeight = bandTop - bandFloor + 1;
int cellCount = bandHeight * CHUNK_AREA;
SweepScratch scratch = SCRATCH.get();
scratch.prepare(cellCount);
long[] solid = scratch.solid;
long[] visited = scratch.visited;
int[] stack = scratch.stack;
int[] component = scratch.component;
boolean carvedPresent = false;
for (int y = bandFloor; y <= bandTop; y++) {
int layer = (y - bandFloor) * CHUNK_AREA;
for (int localX = 0; localX < CHUNK_SIZE; localX++) {
for (int localZ = 0; localZ < CHUNK_SIZE; localZ++) {
int columnIndex = PowerOfTwoCoordinates.packLocal16(localX, localZ);
if (y > surfaceHeights[columnIndex]) {
continue;
}
if (access.isCarved(localX, y, localZ)) {
carvedPresent = true;
continue;
}
setBit(solid, layer + columnIndex);
}
}
}
if (!carvedPresent) {
return 0;
}
int marked = 0;
for (int rootIndex = 0; rootIndex < cellCount; rootIndex++) {
if (!getBit(solid, rootIndex) || getBit(visited, rootIndex)) {
continue;
}
setBit(visited, rootIndex);
stack[0] = rootIndex;
int stackSize = 1;
int componentSize = 0;
boolean anchored = false;
while (stackSize > 0) {
int current = stack[--stackSize];
int columnIndex = current & (CHUNK_AREA - 1);
int localX = columnIndex >>> 4;
int localZ = columnIndex & (CHUNK_SIZE - 1);
int y = bandFloor + (current / CHUNK_AREA);
if (!anchored) {
if (access.isProtected(localX, y, localZ)) {
anchored = true;
} else if (localX == 0 || localX == CHUNK_SIZE - 1 || localZ == 0 || localZ == CHUNK_SIZE - 1) {
anchored = true;
} else if (y == bandFloor && isSolidBelowBand(access, surfaceHeights, columnIndex, localX, localZ, bandFloor - 1, worldFloorY)) {
anchored = true;
} else if (componentSize >= MAX_ORPHAN_CELLS) {
anchored = true;
} else {
component[componentSize++] = current;
}
}
if (y > bandFloor) {
stackSize = push(solid, visited, stack, stackSize, current - CHUNK_AREA);
}
if (y < bandTop) {
stackSize = push(solid, visited, stack, stackSize, current + CHUNK_AREA);
}
if (localX > 0) {
stackSize = push(solid, visited, stack, stackSize, current - CHUNK_SIZE);
}
if (localX < CHUNK_SIZE - 1) {
stackSize = push(solid, visited, stack, stackSize, current + CHUNK_SIZE);
}
if (localZ > 0) {
stackSize = push(solid, visited, stack, stackSize, current - 1);
}
if (localZ < CHUNK_SIZE - 1) {
stackSize = push(solid, visited, stack, stackSize, current + 1);
}
}
if (anchored) {
continue;
}
for (int index = 0; index < componentSize; index++) {
int cell = component[index];
int columnIndex = cell & (CHUNK_AREA - 1);
access.markCarved(columnIndex >>> 4, bandFloor + (cell / CHUNK_AREA), columnIndex & (CHUNK_SIZE - 1));
marked++;
}
}
return marked;
}
private static int push(long[] solid, long[] visited, int[] stack, int stackSize, int neighbor) {
if (!getBit(solid, neighbor) || getBit(visited, neighbor)) {
return stackSize;
}
setBit(visited, neighbor);
stack[stackSize] = neighbor;
return stackSize + 1;
}
private static boolean isSolidBelowBand(CarveAccess access, int[] surfaceHeights, int columnIndex, int localX, int localZ, int belowY, int worldFloorY) {
if (belowY < worldFloorY || belowY > surfaceHeights[columnIndex]) {
return false;
}
return !access.isCarved(localX, belowY, localZ);
}
private static boolean getBit(long[] bits, int index) {
return (bits[index >>> 6] & (1L << (index & 63))) != 0L;
}
private static void setBit(long[] bits, int index) {
bits[index >>> 6] |= 1L << (index & 63);
}
private static final class MantleCarveAccess implements CarveAccess {
private final MantleLayer<CarvedVoid> voids;
private final int originX;
private final int originZ;
private final int[] surfaceFluidBoundaryStartY;
private final int fluidHeight;
private MantleCarveAccess(MantleLayer<CarvedVoid> voids, int originX, int originZ, int[] surfaceFluidBoundaryStartY, int fluidHeight) {
this.voids = voids;
this.originX = originX;
this.originZ = originZ;
this.surfaceFluidBoundaryStartY = surfaceFluidBoundaryStartY;
this.fluidHeight = fluidHeight;
}
@Override
public boolean isCarved(int localX, int y, int localZ) {
return voids.get(originX + localX, y, originZ + localZ) != null;
}
@Override
public void markCarved(int localX, int y, int localZ) {
voids.set(originX + localX, y, originZ + localZ, CarvedVoid.OPEN);
}
@Override
public boolean isProtected(int localX, int y, int localZ) {
int columnIndex = PowerOfTwoCoordinates.packLocal16(localX, localZ);
return SurfaceFluidBoundaryPlan.protects(surfaceFluidBoundaryStartY, columnIndex, y, fluidHeight);
}
}
private static final class SweepScratch {
private final int[] component = new int[MAX_ORPHAN_CELLS];
private long[] solid = new long[0];
private long[] visited = new long[0];
private int[] stack = new int[0];
private void prepare(int cellCount) {
int words = (cellCount + 63) >>> 6;
if (solid.length < words) {
solid = new long[words];
visited = new long[words];
} else {
Arrays.fill(solid, 0, words, 0L);
Arrays.fill(visited, 0, words, 0L);
}
if (stack.length < cellCount) {
stack = new int[cellCount];
}
}
}
}
@@ -0,0 +1,29 @@
/*
* Iris is a World Generator for Minecraft Servers
* Copyright (c) 2026 Arcane Arts (Volmit Software)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package art.arcane.iris.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) {
}
@@ -0,0 +1,228 @@
/*
* Iris is a World Generator for Minecraft Servers
* Copyright (c) 2026 Arcane Arts (Volmit Software)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package art.arcane.iris.engine.mantle.components;
import art.arcane.iris.builtin.carve.CaveAnchorMode;
import art.arcane.iris.modules.objects.CarvedSpace;
import art.arcane.volmlib.util.cache.CacheKey;
import art.arcane.volmlib.util.math.RNG;
import com.volmit.mantle.CarvedVoid;
import com.volmit.resource.ResourceId;
import com.volmit.world.BiomeSample;
import com.volmit.world.TerrainSampler;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
/** Finds the places in the carved caves of a chunk where a cave object may be anchored, remembering what it scanned. */
final class CaveAnchors {
private static final int BEDROCK_CLEARANCE = 6;
private static final int SOLID_NEIGHBOR_REACH_BLOCKS = 3;
private static final int MAX_PACKED_SETTING = 65535;
private final CarvedSpace carved;
private final TerrainSampler terrain;
private final int worldHeight;
private final int caveLavaHeight;
private final Map<Long, Map<Long, List<Integer>>> anchorsBySetting = new HashMap<>();
private final Map<Long, byte[]> carvedColumns = new HashMap<>();
private final Map<Long, Integer> surfaceHeights = new HashMap<>();
CaveAnchors(CarvedSpace carved, TerrainSampler terrain, int worldHeight, int caveLavaHeight) {
this.carved = carved;
this.terrain = terrain;
this.worldHeight = worldHeight;
this.caveLavaHeight = caveLavaHeight;
}
/** A position to anchor a cave object at. */
record Anchor(int x, int y, int z) {
}
/** How a cave placement looks for its anchor. */
record Search(CaveAnchorMode mode, int scanStep, int minDepthBelowSurface, int attempts) {
}
/**
* Looks for an anchor in the chunk whose first block is {@code minX}, {@code minZ}: a column picked at random, a height in
* it picked among those the mode accepts, tried up to the search's attempts.
*
* @param expectedCaveBiome the cave biome the anchor has to be in, or null for any
* @return the anchor, or null when no attempt found one
*/
Anchor find(RNG rng, int minX, int minZ, Search search, ResourceId expectedCaveBiome, boolean underwater) {
for (int attempt = 0; attempt < search.attempts(); attempt++) {
int candidateX = rng.i(minX, minX + 16);
int candidateZ = rng.i(minZ, minZ + 16);
int candidateY = anchorY(rng, candidateX, candidateZ, search);
if (candidateY < 0
|| biomeConflicts(candidateX, candidateY, candidateZ, expectedCaveBiome)
|| !acceptsFluid(underwater, carved.voidAt(candidateX, candidateY, candidateZ), candidateY, caveLavaHeight)) {
continue;
}
return new Anchor(candidateX, candidateY, candidateZ);
}
return null;
}
static boolean acceptsFluid(boolean underwater, Optional<CarvedVoid> carvedVoid, int y, int lavaHeight) {
if (carvedVoid.isEmpty()) {
return false;
}
if (underwater || carvedVoid.get().fill() == CarvedVoid.Fill.AIR) {
return true;
}
return carvedVoid.get().fill() == CarvedVoid.Fill.OPEN && y > lavaHeight;
}
/** One above the highest height an anchor may sit at, or 0 when none may. */
static int scanUpperBound(int worldHeight, int surfaceY, int minDepthBelowSurface) {
int maxAnchorY = maxBuriedY(worldHeight, surfaceY, minDepthBelowSurface);
if (maxAnchorY <= 1) {
return 0;
}
return maxAnchorY + 1;
}
/** The highest height a cave object may reach: no deeper than {@code minDepthBelowSurface} under the surface. */
static int maxBuriedY(int worldHeight, int surfaceY, int minDepthBelowSurface) {
return Math.min(worldHeight - 1, surfaceY - Math.max(0, minDepthBelowSurface));
}
/** Whether the cave biome at the position is not the one expected, nor the surface biome the cave sits under. */
private boolean biomeConflicts(int x, int y, int z, ResourceId expectedCaveBiome) {
if (expectedCaveBiome == null) {
return false;
}
BiomeSample sample = terrain.biome(x, y, z);
return biomeConflicts(sample.caveBiome().orElse(null), sample.surfaceBiome(), expectedCaveBiome);
}
static boolean biomeConflicts(ResourceId at, ResourceId surface, ResourceId expectedCaveBiome) {
if (expectedCaveBiome == null || at == null) {
return false;
}
if (at.equals(expectedCaveBiome)) {
return false;
}
return surface == null || !at.equals(surface);
}
private int anchorY(RNG rng, int x, int z, Search search) {
List<Integer> anchors = anchorsAt(x, z, search);
if (anchors.isEmpty()) {
return -1;
}
if (anchors.size() == 1) {
return anchors.get(0);
}
return anchors.get(rng.i(anchors.size()));
}
private List<Integer> anchorsAt(int x, int z, Search search) {
if (search.scanStep() > MAX_PACKED_SETTING || search.minDepthBelowSurface() > MAX_PACKED_SETTING) {
return scanColumn(x, z, search);
}
long settingKey = ((long) search.mode().ordinal() << 32) | ((long) search.scanStep() << 16) | search.minDepthBelowSurface();
Map<Long, List<Integer>> columns = anchorsBySetting.computeIfAbsent(settingKey, key -> new HashMap<>());
long columnKey = CacheKey.key(x, z);
List<Integer> anchors = columns.get(columnKey);
if (anchors != null) {
return anchors;
}
anchors = scanColumn(x, z, search);
columns.put(columnKey, anchors);
return anchors;
}
private List<Integer> scanColumn(int x, int z, Search search) {
int step = Math.max(1, search.scanStep());
int surfaceY = surfaceHeight(x, z);
int maxAnchorExclusive = scanUpperBound(worldHeight, surfaceY, search.minDepthBelowSurface());
if (maxAnchorExclusive == 0) {
return new ArrayList<>();
}
int carvedHeight = Math.min(worldHeight, maxAnchorExclusive + 3);
byte[] carvedColumn = carvedColumn(x, z, carvedHeight);
return scanRange(search.mode(), step, carvedHeight, maxAnchorExclusive, carvedColumn);
}
private List<Integer> scanRange(CaveAnchorMode mode, int step, int height, int maxAnchorY, byte[] carvedColumn) {
List<Integer> anchors = new ArrayList<>();
for (int y = BEDROCK_CLEARANCE; y < maxAnchorY; y += step) {
if (!isCarved(carvedColumn, y)) {
continue;
}
boolean solidBelow = hasSolidNeighbor(carvedColumn, y, height, -1);
boolean solidAbove = hasSolidNeighbor(carvedColumn, y, height, 1);
if (matches(mode, solidBelow, solidAbove)) {
anchors.add(y);
}
}
return anchors;
}
private static boolean isCarved(byte[] carvedColumn, int y) {
return y >= 0 && y < carvedColumn.length && carvedColumn[y] == 1;
}
private static boolean hasSolidNeighbor(byte[] carvedColumn, int y, int height, int direction) {
for (int distance = 1; distance <= SOLID_NEIGHBOR_REACH_BLOCKS; distance++) {
int neighbor = y + (direction * distance);
if (neighbor < 0 || neighbor >= height || !isCarved(carvedColumn, neighbor)) {
return true;
}
}
return false;
}
private static boolean matches(CaveAnchorMode mode, boolean solidBelow, boolean solidAbove) {
return switch (mode) {
case PROFILE_DEFAULT, FLOOR -> solidBelow;
case CEILING -> solidAbove;
case CENTER -> !solidBelow && !solidAbove;
case ANY -> true;
};
}
private byte[] carvedColumn(int x, int z, int height) {
long columnKey = CacheKey.key(x, z);
byte[] column = carvedColumns.get(columnKey);
if (column != null && column.length == height) {
return column;
}
column = carved.column(x, z, height);
carvedColumns.put(columnKey, column);
return column;
}
private int surfaceHeight(int x, int z) {
long columnKey = CacheKey.key(x, z);
Integer known = surfaceHeights.get(columnKey);
if (known != null) {
return known;
}
int surfaceY = terrain.surfaceHeight(x, z);
surfaceHeights.put(columnKey, surfaceY);
return surfaceY;
}
}
@@ -0,0 +1,69 @@
/*
* Iris is a World Generator for Minecraft Bukkit Servers
* Copyright (c) 2022 Arcane Arts (Volmit Software)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package art.arcane.iris.engine.mantle.components;
import com.volmit.mantle.CarvedVoid;
final class CaveCarveScratch {
final int[] columnMaxY = new int[256];
final int[] fluidMaxY = new int[256];
final int[] surfaceBreakFloorY = new int[256];
final boolean[] surfaceBreakColumn = new boolean[256];
final boolean[] surfaceCeilingColumn = new boolean[256];
final double[] columnThreshold = new double[256];
final double[] passThreshold = new double[256];
final double[] fullWeights = new double[256];
final double[] clampedColumnWeights = new double[256];
final int[] activeColumnIndices = new int[256];
final int[] activeColumnTopY = new int[256];
final int[] planeColumnIndices = new int[256];
final double[] planeThresholdLimit = new double[256];
final boolean[] planeCarve = new boolean[256];
final double[] adaptivePlaneDensity = new double[81];
final double[] adaptivePlanePrediction = new double[256];
final double[] adaptivePlaneAmbiguity = new double[256];
final int[] adaptivePlaneSampleBounds = new int[4];
final int[] adaptiveCellX = new int[256];
final int[] adaptiveCellZ = new int[256];
final int[] adaptiveRow0 = new int[256];
final int[] adaptiveRow1 = new int[256];
final double[] adaptiveTx = new double[256];
final double[] adaptiveTz = new double[256];
final boolean[] warpCacheSet = new boolean[256];
final int[] warpCacheX = new int[256];
final int[] warpCacheY = new int[256];
final int[] warpCacheZ = new int[256];
final double[] warpCacheA = new double[256];
final double[] warpCacheB = new double[256];
final int[] tileIndices = new int[4];
final int[] tileLocalX = new int[4];
final int[] tileLocalZ = new int[4];
final int[] tileTopY = new int[4];
CaveFieldModuleState[] activeModules = new CaveFieldModuleState[0];
double[] activeModuleRemainingMin = new double[0];
double[] activeModuleRemainingMax = new double[0];
int activeModulesY = Integer.MIN_VALUE;
int activeModuleCount;
double[] verticalEdgeFade = new double[0];
double[] surfaceClosureThreshold = new double[0];
CarvedVoid[] voidByY = new CarvedVoid[0];
int adaptiveGeometryStep = -1;
int adaptiveGeometryAxisCells = -1;
boolean fullWeightsInitialized;
}
@@ -0,0 +1,621 @@
/*
* Iris is a World Generator for Minecraft Bukkit Servers
* Copyright (c) 2022 Arcane Arts (Volmit Software)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package art.arcane.iris.engine.mantle.components;
import art.arcane.iris.modules.carve.CaveProfile;
import art.arcane.iris.engine.object.terrain.carving.CarvingResolver;
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 com.volmit.config.Range;
import com.volmit.mantle.CarvedVoid;
import com.volmit.mantle.MantleLayer;
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;
import java.util.IdentityHashMap;
import java.util.List;
import java.util.Map;
/**
* Plans one chunk's caves into the mantle for {@link art.arcane.iris.engine.modifier.CarveModule}: the cave
* profiles of the dimension's carving entries and of the regions and biomes around the chunk, blended over
* their borders. One per engine runtime, keeping a carver per cave profile.
*/
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;
private static final int MAX_BLENDED_PROFILE_PASSES = 2;
private static final int KERNEL_WIDTH = (BLEND_RADIUS * 2) + 1;
private static final int KERNEL_SIZE = KERNEL_WIDTH * KERNEL_WIDTH;
private static final int[] KERNEL_DX = new int[KERNEL_SIZE];
private static final int[] KERNEL_DZ = new int[KERNEL_SIZE];
private static final double[] KERNEL_WEIGHT = new double[KERNEL_SIZE];
private static final ThreadLocal<BlendScratch> BLEND_SCRATCH = ThreadLocal.withInitial(BlendScratch::new);
private final CarveWorld world;
private final DeclaredCaveProfiles declaredProfiles;
private final CarvingResolver resolver;
private final FluidColumns fluidColumns;
private final boolean upperDimensionCarving;
private final Object profileCarverLock = new Object();
private volatile Map<CaveProfile, IrisCaveCarver3D> profileCarvers = new IdentityHashMap<>();
static {
int kernelIndex = 0;
for (int offsetX = -BLEND_RADIUS; offsetX <= BLEND_RADIUS; offsetX++) {
for (int offsetZ = -BLEND_RADIUS; offsetZ <= BLEND_RADIUS; offsetZ++) {
KERNEL_DX[kernelIndex] = offsetX;
KERNEL_DZ[kernelIndex] = offsetZ;
int edgeDistance = Math.max(Math.abs(offsetX), Math.abs(offsetZ));
KERNEL_WEIGHT[kernelIndex] = (BLEND_RADIUS + 1D) - edgeDistance;
kernelIndex++;
}
}
}
/** Whether the dimension's fluid palette gives a column a fluid, which caves near it blend towards. */
@FunctionalInterface
public interface FluidColumns {
boolean hasFluid(int worldX, int worldZ);
}
public CaveCarving(PackWorld packWorld, CarveWorld world, boolean upperDimensionCarving, FluidColumns fluidColumns) {
this.world = world;
this.declaredProfiles = DeclaredCaveProfiles.of(packWorld);
this.resolver = CarvingResolver.of(packWorld);
this.fluidColumns = fluidColumns;
this.upperDimensionCarving = upperDimensionCarving;
}
/** Carves the caves of the chunk at chunk coordinates {@code x}, {@code z} into {@code voids}, reading the terrain around it from {@code terrain}. */
public void carve(MantleLayer<CarvedVoid> voids, TerrainSampler terrain, int x, int z) {
BlendScratch blendScratch = BLEND_SCRATCH.get();
int[] chunkSurfaceHeights = prepareChunkSurfaceHeights(x, z, terrain, blendScratch.chunkSurfaceHeights);
List<WeightedProfile> weightedProfiles = resolveWeightedProfiles(x, z, terrain);
int fluidHeight = world.fluidHeight();
int[] surfaceFluidBoundaryStartY = blendScratch.surfaceFluidBoundaryStartY;
SurfaceFluidBoundaryPlan.fill(
chunkSurfaceHeights,
blendScratch.fieldSurfaceHeights,
blendScratch.fieldHasFluid,
FIELD_SIZE,
BLEND_RADIUS,
fluidHeight,
surfaceFluidBoundaryStartY
);
CaveFluidSupportPlan fluidSupportPlan = new CaveFluidSupportPlan();
for (WeightedProfile weightedProfile : weightedProfiles) {
carveProfile(weightedProfile, voids, x, z, chunkSurfaceHeights, surfaceFluidBoundaryStartY, fluidSupportPlan);
}
if (upperDimensionCarving && hasUpperDimension(terrain, x, z)) {
carveUpperTerrain(terrain, weightedProfiles, voids, x, z, fluidSupportPlan);
}
fluidSupportPlan.resolve(voids, PowerOfTwoCoordinates.chunkToBlock(x), PowerOfTwoCoordinates.chunkToBlock(z), world.height());
if (!weightedProfiles.isEmpty()) {
CarveOrphanSweep.sweepChunk(
voids,
PowerOfTwoCoordinates.chunkToBlock(x),
PowerOfTwoCoordinates.chunkToBlock(z),
chunkSurfaceHeights,
maxSurfaceBreakDepth(weightedProfiles),
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<WeightedProfile> weightedProfiles) {
int maxDepth = 0;
for (WeightedProfile weightedProfile : weightedProfiles) {
maxDepth = Math.max(maxDepth, Math.max(0, weightedProfile.profile.surfaceBreakDepth()));
}
return maxDepth;
}
private void carveProfile(WeightedProfile weightedProfile, MantleLayer<CarvedVoid> voids, int cx, int cz,
int[] chunkSurfaceHeights, int[] surfaceFluidBoundaryStartY,
CaveFluidSupportPlan fluidSupportPlan) {
IrisCaveCarver3D carver = getCarver(weightedProfile.profile);
carver.carve(voids, cx, cz, weightedProfile.columnWeights, MIN_WEIGHT, THRESHOLD_PENALTY,
weightedProfile.worldYRange, chunkSurfaceHeights, surfaceFluidBoundaryStartY, null, fluidSupportPlan);
}
private void carveUpperTerrain(TerrainSampler terrain, List<WeightedProfile> normalProfiles,
MantleLayer<CarvedVoid> voids, int cx, int cz,
CaveFluidSupportPlan fluidSupportPlan) {
int chunkHeight = world.height();
int worldMinHeight = world.minHeight();
int baseX = PowerOfTwoCoordinates.chunkToBlock(cx);
int baseZ = PowerOfTwoCoordinates.chunkToBlock(cz);
int minUpperSurfaceY = chunkHeight;
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 upperY = terrain.upperDimensionY(worldX, worldZ).getAsInt();
if (upperY < minUpperSurfaceY) {
minUpperSurfaceY = upperY;
}
}
}
if (minUpperSurfaceY >= chunkHeight - 2) {
return;
}
Range upperYRange = Range.of(
minUpperSurfaceY + worldMinHeight,
chunkHeight - 1 + worldMinHeight
);
Range fullVerticalRange = Range.of(0, chunkHeight);
int[] ceilingSurfaceHeights = new int[CHUNK_AREA];
Arrays.fill(ceilingSurfaceHeights, chunkHeight - 1);
for (WeightedProfile weightedProfile : normalProfiles) {
Range constrainedRange;
if (weightedProfile.worldYRange != null) {
double min = Math.max(weightedProfile.worldYRange.min(), upperYRange.min());
double max = Math.min(weightedProfile.worldYRange.max(), upperYRange.max());
if (min >= max) {
continue;
}
constrainedRange = Range.of(min, max);
} else {
constrainedRange = upperYRange;
}
IrisCaveCarver3D carver = getCarver(weightedProfile.profile);
carver.carve(voids, cx, cz, weightedProfile.columnWeights, MIN_WEIGHT, THRESHOLD_PENALTY,
constrainedRange, ceilingSurfaceHeights, null, fullVerticalRange, fluidSupportPlan);
}
}
private List<WeightedProfile> resolveWeightedProfiles(int chunkX, int chunkZ, TerrainSampler terrain) {
BlendScratch blendScratch = BLEND_SCRATCH.get();
CaveProfile[] profileField = blendScratch.profileField;
Map<CaveProfile, double[]> columnProfileWeights = blendScratch.columnProfileWeights;
IdentityHashMap<CaveProfile, Boolean> activeProfiles = blendScratch.activeProfiles;
List<CaveProfile> profileOrder = blendScratch.profileOrder;
CaveProfile[] kernelProfiles = blendScratch.kernelProfiles;
double[] kernelProfileWeights = blendScratch.kernelProfileWeights;
activeProfiles.clear();
profileOrder.clear();
fillProfileField(profileField, chunkX, chunkZ, terrain, blendScratch);
for (int localX = 0; localX < CHUNK_SIZE; localX++) {
for (int localZ = 0; localZ < CHUNK_SIZE; localZ++) {
int profileCount = 0;
int centerX = localX + BLEND_RADIUS;
int centerZ = localZ + BLEND_RADIUS;
double totalKernelWeight = 0D;
for (int kernelIndex = 0; kernelIndex < KERNEL_SIZE; kernelIndex++) {
int sampleX = centerX + KERNEL_DX[kernelIndex];
int sampleZ = centerZ + KERNEL_DZ[kernelIndex];
CaveProfile profile = profileField[(sampleX * FIELD_SIZE) + sampleZ];
if (!isProfileEnabled(profile)) {
continue;
}
double kernelWeight = KERNEL_WEIGHT[kernelIndex];
int existingIndex = findProfileIndex(kernelProfiles, profileCount, profile);
if (existingIndex >= 0) {
kernelProfileWeights[existingIndex] += kernelWeight;
} else {
kernelProfiles[profileCount] = profile;
kernelProfileWeights[profileCount] = kernelWeight;
profileCount++;
}
totalKernelWeight += kernelWeight;
}
if (totalKernelWeight <= 0D || profileCount == 0) {
continue;
}
int columnIndex = PowerOfTwoCoordinates.packLocal16(localX, localZ);
for (int profileIndex = 0; profileIndex < profileCount; profileIndex++) {
CaveProfile profile = kernelProfiles[profileIndex];
double kernelWeight = kernelProfileWeights[profileIndex];
kernelProfiles[profileIndex] = null;
kernelProfileWeights[profileIndex] = 0D;
double columnWeight = clampWeight(kernelWeight / totalKernelWeight);
if (columnWeight < MIN_WEIGHT) {
continue;
}
double[] weights = columnProfileWeights.get(profile);
if (weights == null) {
weights = new double[CHUNK_AREA];
columnProfileWeights.put(profile, weights);
} else if (!activeProfiles.containsKey(profile)) {
Arrays.fill(weights, 0D);
}
if (activeProfiles.put(profile, Boolean.TRUE) == null) {
profileOrder.add(profile);
}
weights[columnIndex] = columnWeight;
}
}
}
List<WeightedProfile> columnWeightedProfiles = new ArrayList<>();
for (CaveProfile profile : profileOrder) {
double[] weights = columnProfileWeights.get(profile);
if (weights == null) {
continue;
}
// 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 = maxOf(weights);
if (maxWeight < MIN_WEIGHT) {
continue;
}
double averageWeight = computeAverageWeight(weights);
columnWeightedProfiles.add(new WeightedProfile(profile, weights, averageWeight, null, columnWeightedProfiles.size()));
}
List<WeightedProfile> blendedProfiles = limitAndMergeBlendedProfiles(columnWeightedProfiles, MAX_BLENDED_PROFILE_PASSES, CHUNK_AREA);
List<WeightedProfile> resolvedProfiles = resolveDimensionCarvingProfiles(chunkX, chunkZ, blendScratch);
resolvedProfiles.addAll(blendedProfiles);
return resolvedProfiles;
}
private List<WeightedProfile> resolveDimensionCarvingProfiles(int chunkX, int chunkZ, BlendScratch blendScratch) {
List<WeightedProfile> weightedProfiles = new ArrayList<>();
List<ResolvedCarvingEntry> entries = resolver.entries();
if (entries.isEmpty()) {
return weightedProfiles;
}
Map<ResolvedCarvingEntry, ResolvedCarvingEntry[]> dimensionColumnPlans = blendScratch.dimensionColumnPlans;
dimensionColumnPlans.clear();
for (ResolvedCarvingEntry entry : entries) {
if (!entry.enabled()) {
continue;
}
PackBiome rootBiome = resolver.entryBiome(entry);
if (rootBiome == null) {
continue;
}
ResolvedCarvingEntry[] columnPlan = dimensionColumnPlans.computeIfAbsent(entry, key -> new ResolvedCarvingEntry[CHUNK_AREA]);
buildDimensionColumnPlan(columnPlan, chunkX, chunkZ, entry);
Map<CaveProfile, double[]> rootProfileColumnWeights = new IdentityHashMap<>();
List<CaveProfile> rootProfileOrder = new ArrayList<>();
Range worldYRange = entry.worldYRange();
for (int columnIndex = 0; columnIndex < CHUNK_AREA; columnIndex++) {
ResolvedCarvingEntry resolvedEntry = columnPlan[columnIndex];
PackBiome resolvedBiome = resolver.entryBiome(resolvedEntry);
if (resolvedBiome == null) {
continue;
}
CaveProfile profile = declaredProfiles.ofBiome(resolvedBiome.id());
if (!isProfileEnabled(profile)) {
continue;
}
double[] columnWeights = rootProfileColumnWeights.get(profile);
if (columnWeights == null) {
columnWeights = new double[CHUNK_AREA];
rootProfileColumnWeights.put(profile, columnWeights);
rootProfileOrder.add(profile);
}
columnWeights[columnIndex] = 1D;
}
for (CaveProfile profile : rootProfileOrder) {
weightedProfiles.add(new WeightedProfile(profile, rootProfileColumnWeights.get(profile), -1D, worldYRange, weightedProfiles.size()));
}
}
return weightedProfiles;
}
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++) {
int worldX = baseX + localX;
for (int localZ = 0; localZ < CHUNK_SIZE; localZ++) {
int worldZ = baseZ + localZ;
int columnIndex = PowerOfTwoCoordinates.packLocal16(localX, localZ);
columnPlan[columnIndex] = resolver.resolveFromRoot(entry, worldX, worldZ);
}
}
}
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;
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(terrain, worldX, worldZ, blendScratch.fieldSurfaceHeights[fieldIndex]);
}
}
}
private int findProfileIndex(CaveProfile[] profiles, int size, CaveProfile profile) {
for (int index = 0; index < size; index++) {
if (profiles[index] == profile) {
return index;
}
}
return -1;
}
/**
* 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 = declaredProfiles.ofDimension();
if (isProfileEnabled(dimensionProfile)) {
resolved = dimensionProfile;
}
int roundedSurfaceY = (int) Math.round(surfaceHeight);
int sampleY = Math.max(1, roundedSurfaceY - CAVE_SAMPLE_DEPTH_BELOW_SURFACE_BLOCKS);
BiomeSample sample = terrain.biome(worldX, sampleY, worldZ);
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;
}
}
return resolved;
}
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++) {
int worldZ = startZ + fieldZ;
int fieldIndex = (fieldX * FIELD_SIZE) + fieldZ;
blendScratch.fieldSurfaceHeights[fieldIndex] = terrain.surfaceY(worldX, worldZ);
blendScratch.fieldHasFluid[fieldIndex] = fluidColumns.hasFluid(worldX, worldZ);
}
}
}
private IrisCaveCarver3D getCarver(CaveProfile profile) {
IrisCaveCarver3D carver = profileCarvers.get(profile);
if (carver != null) {
return carver;
}
IrisCaveCarver3D createdCarver = new IrisCaveCarver3D(world, profile);
synchronized (profileCarverLock) {
IrisCaveCarver3D published = profileCarvers.get(profile);
if (published != null) {
return published;
}
Map<CaveProfile, IrisCaveCarver3D> updated = new IdentityHashMap<>(profileCarvers);
updated.put(profile, createdCarver);
profileCarvers = updated;
return createdCarver;
}
}
private boolean isProfileEnabled(CaveProfile profile) {
return profile != null && profile.enabled();
}
private int[] prepareChunkSurfaceHeights(int chunkX, int chunkZ, TerrainSampler terrain, int[] scratch) {
int baseX = PowerOfTwoCoordinates.chunkToBlock(chunkX);
int baseZ = PowerOfTwoCoordinates.chunkToBlock(chunkZ);
for (int localX = 0; localX < CHUNK_SIZE; localX++) {
int worldX = baseX + localX;
for (int localZ = 0; localZ < CHUNK_SIZE; localZ++) {
int columnIndex = PowerOfTwoCoordinates.packLocal16(localX, localZ);
scratch[columnIndex] = terrain.surfaceHeight(worldX, baseZ + localZ);
}
}
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<WeightedProfile> limitAndMergeBlendedProfiles(List<WeightedProfile> blendedProfiles, int maxProfiles) {
return limitAndMergeBlendedProfiles(blendedProfiles, maxProfiles, CHUNK_AREA);
}
private static List<WeightedProfile> limitAndMergeBlendedProfiles(List<WeightedProfile> blendedProfiles, int maxProfiles, int areaSize) {
if (blendedProfiles == null || blendedProfiles.isEmpty()) {
return new ArrayList<>();
}
int clampedLimit = Math.max(1, maxProfiles);
List<WeightedProfile> rankedProfiles = new ArrayList<>(blendedProfiles);
rankedProfiles.sort(CaveCarving::compareBySelectionRank);
List<WeightedProfile> keptProfiles = new ArrayList<>();
int keptCount = Math.min(clampedLimit, rankedProfiles.size());
for (int index = 0; index < keptCount; index++) {
keptProfiles.add(rankedProfiles.get(index));
}
if (rankedProfiles.size() > keptCount) {
for (int columnIndex = 0; columnIndex < areaSize; columnIndex++) {
int dominantIndex = 0;
double dominantWeight = Double.NEGATIVE_INFINITY;
for (int keptIndex = 0; keptIndex < keptProfiles.size(); keptIndex++) {
double keptWeight = keptProfiles.get(keptIndex).columnWeights[columnIndex];
if (keptWeight > dominantWeight) {
dominantWeight = keptWeight;
dominantIndex = keptIndex;
}
}
double droppedWeight = 0D;
for (int droppedIndex = keptCount; droppedIndex < rankedProfiles.size(); droppedIndex++) {
droppedWeight += rankedProfiles.get(droppedIndex).columnWeights[columnIndex];
}
if (droppedWeight <= 0D) {
continue;
}
WeightedProfile dominantProfile = keptProfiles.get(dominantIndex);
double mergedWeight = dominantProfile.columnWeights[columnIndex] + droppedWeight;
dominantProfile.columnWeights[columnIndex] = clampWeight(mergedWeight);
}
}
List<WeightedProfile> mergedProfiles = new ArrayList<>();
for (WeightedProfile keptProfile : keptProfiles) {
double averageWeight = computeAverageWeight(keptProfile.columnWeights, areaSize);
mergedProfiles.add(new WeightedProfile(keptProfile.profile, keptProfile.columnWeights, averageWeight, keptProfile.worldYRange, keptProfile.sequence));
}
mergedProfiles.sort(CaveCarving::compareByCarveOrder);
return mergedProfiles;
}
private static int compareBySelectionRank(WeightedProfile a, WeightedProfile b) {
int weightOrder = Double.compare(b.averageWeight, a.averageWeight);
if (weightOrder != 0) {
return weightOrder;
}
return Integer.compare(a.sequence, b.sequence);
}
private static int compareByCarveOrder(WeightedProfile a, WeightedProfile b) {
int weightOrder = Double.compare(a.averageWeight, b.averageWeight);
if (weightOrder != 0) {
return weightOrder;
}
return Integer.compare(a.sequence, b.sequence);
}
private static double computeAverageWeight(double[] weights) {
return computeAverageWeight(weights, CHUNK_AREA);
}
private static double computeAverageWeight(double[] weights, int areaSize) {
if (weights == null || weights.length == 0) {
return 0D;
}
double sum = 0D;
for (double weight : weights) {
sum += weight;
}
return sum / Math.max(1, areaSize);
}
private static double clampWeight(double value) {
if (Double.isNaN(value) || Double.isInfinite(value)) {
return 0D;
}
if (value <= 0D) {
return 0D;
}
if (value >= 1D) {
return 1D;
}
return value;
}
private static final class WeightedProfile {
private final CaveProfile profile;
private final double[] columnWeights;
private final double averageWeight;
private final Range worldYRange;
private final int sequence;
private WeightedProfile(CaveProfile profile, double[] columnWeights, double averageWeight, Range worldYRange, int sequence) {
this.profile = profile;
this.columnWeights = columnWeights;
this.averageWeight = averageWeight;
this.worldYRange = worldYRange;
this.sequence = sequence;
}
private double averageWeight() {
return averageWeight;
}
}
private static final class BlendScratch {
private final CaveProfile[] profileField = new CaveProfile[FIELD_SIZE * FIELD_SIZE];
private final CaveProfile[] kernelProfiles = new CaveProfile[KERNEL_SIZE];
private final double[] kernelProfileWeights = new double[KERNEL_SIZE];
private final IdentityHashMap<CaveProfile, double[]> columnProfileWeights = new IdentityHashMap<>();
private final IdentityHashMap<ResolvedCarvingEntry, ResolvedCarvingEntry[]> dimensionColumnPlans = new IdentityHashMap<>();
private final IdentityHashMap<CaveProfile, Boolean> activeProfiles = new IdentityHashMap<>();
private final List<CaveProfile> 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 int[] chunkSurfaceHeights = new int[CHUNK_AREA];
private final int[] surfaceFluidBoundaryStartY = new int[CHUNK_AREA];
}
}
@@ -0,0 +1,58 @@
/*
* Iris is a World Generator for Minecraft Bukkit Servers
* Copyright (c) 2022 Arcane Arts (Volmit Software)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package art.arcane.iris.engine.mantle.components;
import art.arcane.iris.builtin.carve.CaveFieldModule;
import com.volmit.config.Range;
import com.volmit.noise.NoiseSampler;
final class CaveFieldModuleState {
final NoiseSampler density;
final int minY;
final int maxY;
final double weight;
final double threshold;
final boolean invert;
final double minContribution;
final double maxContribution;
CaveFieldModuleState(CaveFieldModule module, NoiseSampler density) {
Range range = module.verticalRange();
this.density = density;
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();
double rawMin = invert ? threshold - 1D : -1D - threshold;
double rawMax = invert ? threshold + 1D : 1D - threshold;
this.minContribution = rawMin * weight;
this.maxContribution = rawMax * weight;
}
double sample(double x, int y, double 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.signed(x, y, z);
return invert ? (threshold - sampled) * weight : (sampled - threshold) * weight;
}
}
@@ -0,0 +1,120 @@
/*
* Iris is a World Generator for Minecraft Servers
* Copyright (c) 2026 Arcane Arts (Volmit Software)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package art.arcane.iris.engine.mantle.components;
import art.arcane.volmlib.util.math.PowerOfTwoCoordinates;
import com.volmit.geometry.BlockBox;
import com.volmit.geometry.BlockPosition;
import com.volmit.mantle.CarvedVoid;
import com.volmit.mantle.MantleLayer;
import com.volmit.placement.PlacedMarker;
import com.volmit.placement.PlacementTerrain;
import com.volmit.world.TerrainSampler;
import java.util.BitSet;
/**
* Marks the floors of the caves {@link CaveCarving} planned in a chunk, which the host's cave spawning reads: the lowest
* block of each vertical run of at least three carved blocks, one floor in sixteen. The runs are those the chunk stage
* cuts, minus the blocks it leaves alone: under a dimension stacked above that carving does not go through, and open voids
* the terrain holds fluid in. The roll is seed-derived and keyed by position alone, never random, because the markers
* persist in the mantle: the same seed marks the same floors on every run.
*/
public final class CaveFloorMarking {
static final String CAVE_FLOOR_MARKER = "cave_floor";
private static final int CHUNK_SIZE = 16;
private static final int CHUNK_AREA = CHUNK_SIZE * CHUNK_SIZE;
private static final int MIN_RUN_LENGTH = 3;
private static final long FLOOR_MARKER_SALT = 0xC2B2AE3D27D4EB4FL;
private static final long ROLL_MASK = 15L;
private static final ThreadLocal<BitSet[]> COLUMNS = ThreadLocal.withInitial(() -> {
BitSet[] columns = new BitSet[CHUNK_AREA];
for (int index = 0; index < CHUNK_AREA; index++) {
columns[index] = new BitSet();
}
return columns;
});
private final CarveWorld world;
private final boolean upperDimensionCarving;
public CaveFloorMarking(CarveWorld world, boolean upperDimensionCarving) {
this.world = world;
this.upperDimensionCarving = upperDimensionCarving;
}
/** Marks the floors of the chunk at chunk coordinates {@code chunkX}, {@code chunkZ} in {@code placement}. */
public void mark(MantleLayer<CarvedVoid> voids, TerrainSampler terrain, PlacementTerrain placement, int chunkX, int chunkZ) {
int originX = PowerOfTwoCoordinates.chunkToBlock(chunkX);
int originZ = PowerOfTwoCoordinates.chunkToBlock(chunkZ);
BitSet[] carvedColumns = COLUMNS.get();
fillCarvedColumns(carvedColumns, voids, terrain, originX, originZ);
for (int columnIndex = 0; columnIndex < CHUNK_AREA; columnIndex++) {
markColumn(carvedColumns[columnIndex], placement, originX + PowerOfTwoCoordinates.unpackLocal16X(columnIndex),
originZ + (columnIndex & (CHUNK_SIZE - 1)));
}
}
private void fillCarvedColumns(BitSet[] carvedColumns, MantleLayer<CarvedVoid> voids, TerrainSampler terrain, int originX, int originZ) {
int[] surfaceHeights = new int[CHUNK_AREA];
int[] upperSurfaceHeights = upperDimensionCarving || terrain.upperDimensionY(originX, originZ).isEmpty() ? null : new int[CHUNK_AREA];
for (int columnIndex = 0; columnIndex < CHUNK_AREA; columnIndex++) {
carvedColumns[columnIndex].clear();
int worldX = originX + PowerOfTwoCoordinates.unpackLocal16X(columnIndex);
int worldZ = originZ + (columnIndex & (CHUNK_SIZE - 1));
surfaceHeights[columnIndex] = terrain.surfaceHeight(worldX, worldZ);
if (upperSurfaceHeights != null) {
upperSurfaceHeights[columnIndex] = terrain.upperDimensionY(worldX, worldZ).getAsInt();
}
}
int fluidHeight = terrain.fluidHeight();
voids.visit(new BlockBox(originX, 0, originZ, originX + CHUNK_SIZE, world.height(), originZ + CHUNK_SIZE), (x, y, z, carvedVoid) -> {
int columnIndex = PowerOfTwoCoordinates.packLocal16(x - originX, z - originZ);
if (y <= 0 || upperSurfaceHeights != null && y >= upperSurfaceHeights[columnIndex]) {
return;
}
boolean terrainHoldsFluid = y > surfaceHeights[columnIndex] && y <= fluidHeight;
if (carvedVoid.fill() == CarvedVoid.Fill.OPEN && terrainHoldsFluid) {
return;
}
carvedColumns[columnIndex].set(y);
});
}
private void markColumn(BitSet carvedColumn, PlacementTerrain placement, int worldX, int worldZ) {
int floor = carvedColumn.nextSetBit(0);
while (floor >= 0) {
int ceiling = carvedColumn.nextClearBit(floor) - 1;
if (ceiling - floor + 1 >= MIN_RUN_LENGTH && floorRoll(worldX, floor, worldZ)) {
placement.mark(new PlacedMarker.PackMarker(new BlockPosition(worldX, floor, worldZ), CAVE_FLOOR_MARKER));
}
floor = carvedColumn.nextSetBit(ceiling + 1);
}
}
/** One in sixteen, from a SplitMix64 finalizer over the carve seed, the position and a salt. */
private boolean floorRoll(int x, int y, int z) {
long hash = (world.carveSeed() + FLOOR_MARKER_SALT) ^ art.arcane.volmlib.util.math.BlockPosition.toLong(x, y, z);
hash = (hash ^ (hash >>> 30)) * 0xBF58476D1CE4E5B9L;
hash = (hash ^ (hash >>> 27)) * 0x94D049BB133111EBL;
hash ^= hash >>> 31;
return (hash & ROLL_MASK) == 0L;
}
}
@@ -0,0 +1,90 @@
/*
* Iris is a World Generator for Minecraft Servers
* Copyright (c) 2026 Arcane Arts (Volmit Software)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package art.arcane.iris.engine.mantle.components;
import art.arcane.volmlib.util.math.PowerOfTwoCoordinates;
import com.volmit.mantle.CarvedVoid;
import com.volmit.mantle.MantleLayer;
import java.util.BitSet;
/** The fluid voids a carver planned in one chunk, to be drained back to open voids where no solid cup holds them. */
final class CaveFluidSupportPlan {
private static final int MIN_SUPPORTED_NEIGHBOURS = 4;
private static final int CHUNK_WIDTH = 16;
private static final int COLUMN_BITS = 8;
private static final int COLUMN_MASK = (1 << COLUMN_BITS) - 1;
private final BitSet fluidPositions = new BitSet();
void add(int localX, int y, int localZ) {
int columnIndex = PowerOfTwoCoordinates.packLocal16(localX, localZ);
fluidPositions.set((y << COLUMN_BITS) | columnIndex);
}
/** Turns every planned fluid void of the chunk at block origin {@code originX}, {@code originZ} that is no longer fluid or has no cup under it into an open void. */
void resolve(MantleLayer<CarvedVoid> voids, int originX, int originZ, int worldHeight) {
for (int position = fluidPositions.nextSetBit(0); position >= 0; position = fluidPositions.nextSetBit(position + 1)) {
int y = position >>> COLUMN_BITS;
int columnIndex = position & COLUMN_MASK;
int localX = PowerOfTwoCoordinates.unpackLocal16X(columnIndex);
int localZ = columnIndex & (CHUNK_WIDTH - 1);
int x = originX + localX;
int z = originZ + localZ;
if (voids.get(x, y, z) != CarvedVoid.FLUID || hasCupSupport(voids, originX, originZ, localX, y, localZ, worldHeight)) {
continue;
}
voids.set(x, y, z, CarvedVoid.OPEN);
}
fluidPositions.clear();
}
private static boolean hasCupSupport(MantleLayer<CarvedVoid> voids, int originX, int originZ, int localX, int y, int localZ, int worldHeight) {
if (localX <= 0 || localX >= CHUNK_WIDTH - 1 || localZ <= 0 || localZ >= CHUNK_WIDTH - 1
|| y <= 1 || !isSolid(voids, originX, originZ, localX, y - 1, localZ, worldHeight)
|| !isSolid(voids, originX, originZ, localX, y - 2, localZ, worldHeight)) {
return false;
}
int support = 0;
if (isSolid(voids, originX, originZ, localX + 1, y, localZ, worldHeight)) {
support++;
}
if (isSolid(voids, originX, originZ, localX - 1, y, localZ, worldHeight)) {
support++;
}
if (isSolid(voids, originX, originZ, localX, y, localZ + 1, worldHeight)) {
support++;
}
if (isSolid(voids, originX, originZ, localX, y, localZ - 1, worldHeight)) {
support++;
}
if (isSolid(voids, originX, originZ, localX, y + 1, localZ, worldHeight)) {
support++;
}
return support >= MIN_SUPPORTED_NEIGHBOURS;
}
private static boolean isSolid(MantleLayer<CarvedVoid> voids, int originX, int originZ, int localX, int y, int localZ, int worldHeight) {
if (localX < 0 || localX >= CHUNK_WIDTH || localZ < 0 || localZ >= CHUNK_WIDTH) {
return false;
}
return y >= worldHeight || voids.get(originX + localX, y, originZ + localZ) == null;
}
}
@@ -0,0 +1,68 @@
/*
* Iris is a World Generator for Minecraft Servers
* Copyright (c) 2026 Arcane Arts (Volmit Software)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package art.arcane.iris.engine.mantle.components;
import art.arcane.iris.builtin.objects.ObjectPlacement;
import com.volmit.object.PlaceableObject;
import com.volmit.ModuleLog;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;
/** Debug lines for cave objects that were not placed, at most one per kind of rejection every few seconds. */
final class CaveRejects {
private static final long THROTTLE_MILLIS = 5000L;
private static final Map<String, State> STATES = new ConcurrentHashMap<>();
private CaveRejects() {
}
static void log(ModuleLog log, String scope, String reason, int chunkX, int chunkZ, ObjectPlacement placement,
PlaceableObject object, int densityIndex, int density, CaveAnchors.Search search, Integer anchorY, Throwable error) {
if (!log.debugging()) {
return;
}
String placementKeys = placement == null ? "none" : String.join(",", placement.place());
String objectKey = object == null ? "null" : object.name();
String throttleKey = scope + "|" + reason + "|" + placementKeys + "|" + objectKey;
State state = STATES.computeIfAbsent(throttleKey, key -> new State());
long now = System.currentTimeMillis();
long last = state.lastLogMillis.get();
if ((now - last) < THROTTLE_MILLIS || !state.lastLogMillis.compareAndSet(last, now)) {
state.suppressed.incrementAndGet();
return;
}
int suppressed = state.suppressed.getAndSet(0);
String errorText = error == null ? "none" : error.getClass().getSimpleName() + ":" + error.getMessage();
log.debug("Cave object reject: scope=" + scope + " reason=" + reason + " chunk=" + chunkX + "," + chunkZ + " object=" + objectKey
+ " placements=" + placementKeys + " densityIndex=" + densityIndex + " density=" + density
+ " anchorMode=" + search.mode() + " anchorSearchAttempts=" + search.attempts() + " anchorScanStep=" + search.scanStep()
+ " minDepthBelowSurface=" + search.minDepthBelowSurface() + " anchorY=" + (anchorY == null ? "none" : anchorY)
+ " forcePlace=" + (placement != null && placement.forcePlace())
+ " carvingSupport=" + (placement == null ? "none" : placement.carvingSupport())
+ " suppressed=" + suppressed + " error=" + errorText);
}
private static final class State {
private final AtomicLong lastLogMillis = new AtomicLong(0L);
private final AtomicInteger suppressed = new AtomicInteger(0);
}
}
@@ -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 <https://www.gnu.org/licenses/>.
*/
package art.arcane.iris.engine.mantle.components;
import art.arcane.iris.builtin.anchor.PlaceTrait;
import art.arcane.iris.builtin.carve.CaveAnchorMode;
import art.arcane.iris.modules.carve.CaveProfile;
import art.arcane.iris.builtin.objects.ObjectPlacement;
/** What a cave object placement takes from the cave profile that applies to it. */
final class CaveSettings {
private static final CaveProfile DEFAULT_PROFILE = new CaveProfile();
private static final int DEFAULT_SCAN_STEP = 1;
private static final int DEFAULT_MIN_DEPTH_BELOW_SURFACE = 6;
private static final int DEFAULT_SEARCH_ATTEMPTS = 6;
private final CaveProfile dimensionProfile;
CaveSettings(CaveProfile dimensionProfile) {
this.dimensionProfile = dimensionProfile;
}
/** The profile of the first of {@code preferred} and {@code secondary} that is enabled, else the dimension's, else the default one. */
CaveProfile resolve(CaveProfile preferred, CaveProfile secondary) {
if (preferred != null && preferred.enabled()) {
return preferred;
}
if (secondary != null && secondary.enabled()) {
return secondary;
}
if (dimensionProfile != null) {
return dimensionProfile;
}
return DEFAULT_PROFILE;
}
/** How the placement looks for its anchor in caves: its own mode, else the profile's, else the floor; turned upside down, the ceiling. */
CaveAnchors.Search searchFor(ObjectPlacement placement, CaveProfile profile) {
CaveAnchorMode mode = anchorMode(placement, profile);
if (placement.mode().placeMode().has(PlaceTrait.UPSIDE_DOWN)) {
mode = CaveAnchorMode.CEILING;
}
return new CaveAnchors.Search(mode, scanStep(profile), minDepthBelowSurface(profile), searchAttempts(profile));
}
private static CaveAnchorMode anchorMode(ObjectPlacement placement, CaveProfile profile) {
CaveAnchorMode placementMode = placement.caveAnchorMode();
if (placementMode != null && !placementMode.equals(CaveAnchorMode.PROFILE_DEFAULT)) {
return placementMode;
}
if (profile == null) {
return CaveAnchorMode.FLOOR;
}
CaveAnchorMode profileMode = profile.defaultObjectAnchor();
if (profileMode == null || profileMode.equals(CaveAnchorMode.PROFILE_DEFAULT)) {
return CaveAnchorMode.FLOOR;
}
return profileMode;
}
private static int scanStep(CaveProfile profile) {
return profile == null ? DEFAULT_SCAN_STEP : Math.max(1, profile.anchorScanStep());
}
private static int minDepthBelowSurface(CaveProfile profile) {
return profile == null ? DEFAULT_MIN_DEPTH_BELOW_SURFACE : Math.max(0, profile.objectMinDepthBelowSurface());
}
private static int searchAttempts(CaveProfile profile) {
return profile == null ? DEFAULT_SEARCH_ATTEMPTS : Math.max(1, profile.anchorSearchAttempts());
}
}
@@ -0,0 +1,590 @@
/*
* Iris is a World Generator for Minecraft Servers
* Copyright (c) 2026 Arcane Arts (Volmit Software)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package art.arcane.iris.engine.mantle.components;
import art.arcane.iris.builtin.anchor.ObjectPlaceMode;
import art.arcane.iris.builtin.carve.CarvingMode;
import art.arcane.iris.builtin.carve.CaveLavaHeightSettings;
import art.arcane.iris.modules.carve.CaveProfile;
import art.arcane.iris.builtin.objects.ObjectPlacement;
import art.arcane.iris.builtin.objects.ObjectSettings;
import art.arcane.iris.builtin.objects.RequireSurfaceSupportSettings;
import art.arcane.iris.builtin.objects.SurfaceSupportBufferSettings;
import art.arcane.iris.builtin.objects.UpperObjectsForceSettings;
import art.arcane.iris.builtin.objects.UpperObjectsSettings;
import art.arcane.iris.engine.procedural.ProceduralObjectCatalog;
import art.arcane.iris.modules.objects.CavePlacement;
import art.arcane.iris.modules.objects.TerrainTransaction;
import art.arcane.iris.modules.objects.ObjectPool;
import art.arcane.iris.modules.objects.ObjectSeparation;
import art.arcane.iris.modules.objects.PlacementChanges;
import art.arcane.iris.modules.objects.PlacementTags;
import art.arcane.volmlib.util.math.RNG;
import com.volmit.IrisFeature;
import com.volmit.ModuleLog;
import com.volmit.config.FeatureSettings.Entry;
import com.volmit.config.Level;
import com.volmit.config.SettingsStack;
import com.volmit.object.PlaceableObject;
import com.volmit.resource.ResourceId;
import com.volmit.stage.MantleStageContext;
import com.volmit.placement.PlacementRecord;
import com.volmit.world.TerrainSampler;
import java.util.List;
import java.util.Optional;
import java.util.OptionalInt;
/**
* Places what the objects of one chunk's region and biomes say: the objects of its surface, caves and the terrain stacked
* above, in that order, all drawing from the one random of the chunk.
*/
final class ChunkObjectPlacing {
/** Objects read their chunk's settings at local 8, 8 as Iris always did, not at the API's centre column (local 7, 7): moving it would move objects. */
private static final int OBJECT_COLUMN_OFFSET_BLOCKS = 8;
private static final int CHUNK_WIDTH_BLOCKS = 16;
private static final double CHANCE_JITTER = 0.005;
private static final int[] CAVE_BIOME_SAMPLE_DEPTHS = {48, 80, 112};
private static final int LEGACY_CAVE_SAMPLE_DEPTH = 48;
private static final int UPPER_SURFACE_MARGIN_BLOCKS = 2;
private static final int MINIMUM_UPPER_ANCHOR_Y = 1;
private static final int DIAGNOSTIC_CHUNK_MASK = 31;
private static final int DIAGNOSTIC_SURFACE_MARGIN = 14;
private static final String TREE_FOLDER = "trees/";
private static final String REGEN_THREAD_PREFIX = "Iris-Regen-";
private final ObjectPool objects;
private final ObjectSeparation separation;
private final ModuleLog log;
private final MantleStageContext context;
private final ObjectChunk chunk;
private final TerrainSampler terrain;
private final int chunkX;
private final int chunkZ;
private final int centerX;
private final int centerZ;
private final RNG rng;
private final boolean traceRegen;
private final boolean golden;
private final EffectivePlacements effective;
private final CaveSettings caves;
private final int worldHeight;
private final int caveLavaHeight;
ChunkObjectPlacing(ObjectPool objects, ModuleLog log, MantleStageContext context) {
this.objects = objects;
this.separation = ObjectSeparation.of(context.world());
this.log = log;
this.context = context;
this.chunk = new ObjectChunk(context, log);
this.terrain = context.terrain();
this.chunkX = context.chunkX();
this.chunkZ = context.chunkZ();
this.centerX = context.originX() + OBJECT_COLUMN_OFFSET_BLOCKS;
this.centerZ = context.originZ() + OBJECT_COLUMN_OFFSET_BLOCKS;
this.rng = objects.chunkRandom(chunkX, chunkZ);
this.traceRegen = Thread.currentThread().getName().startsWith(REGEN_THREAD_PREFIX) && log.debugging();
this.golden = chunk.goldenDebug(chunkX, chunkZ);
this.worldHeight = context.mantle().bounds().maxY();
this.caveLavaHeight = Optional.ofNullable(dimensionLevel(CaveLavaHeightSettings.class)).orElseGet(CaveLavaHeightSettings::new).height();
this.effective = new EffectivePlacements(dimensionRequiresSurfaceSupport(), dimensionSurfaceSupportBuffer());
this.caves = new CaveSettings(dimensionLevel(CaveProfile.class));
}
/** Places what originates in this chunk. */
void place() {
Column column = readColumn();
if (log.debugging() && (chunkX & DIAGNOSTIC_CHUNK_MASK) == 0 && (chunkZ & DIAGNOSTIC_CHUNK_MASK) == 0) {
logCaveDiagnostics(column);
}
if (traceRegen) {
logLayerStart(column);
}
Tally tally = placeObjects(column);
if (upperObjectsEnabled()) {
placeUpperObjects(column);
}
if (traceRegen) {
logLayerDone(tally);
}
}
/** The region and biomes at the chunk's centre and what each declares. */
private Column readColumn() {
ResourceId region = terrain.biome(centerX, terrain.bounds().minY(), centerZ).region();
ResourceId surface = terrain.surfaceBiome(centerX, centerZ);
int surfaceY = terrain.surfaceHeight(centerX, centerZ);
ResourceId cave = resolveCaveObjectBiome(surfaceY, surface);
return new Column(region, surface, cave, surfaceY, objectsOf(cave, region, surface), profilesOf(cave, region, surface));
}
private ResourceId resolveCaveObjectBiome(int surfaceY, ResourceId surfaceBiome) {
ResourceId legacy = caveBiomeAt(Math.max(1, surfaceY - LEGACY_CAVE_SAMPLE_DEPTH)).orElse(surfaceBiome);
ResourceId ladderChoice = null;
for (int depth : CAVE_BIOME_SAMPLE_DEPTHS) {
Optional<ResourceId> sampled = caveBiomeAt(Math.max(1, surfaceY - depth));
if (sampled.isEmpty() || sampled.get().equals(surfaceBiome)) {
continue;
}
if (hasCarvingObjects(context.settings().declaredBy(sampled.get(), ObjectSettings.class))) {
ladderChoice = sampled.get();
}
}
return ladderChoice != null ? ladderChoice : legacy;
}
private Optional<ResourceId> caveBiomeAt(int y) {
return terrain.biome(centerX, y, centerZ).caveBiome();
}
private static boolean hasCarvingObjects(Optional<ObjectSettings> settings) {
return settings.isPresent() && !carvingObjects(settings.get()).isEmpty();
}
private ColumnObjects objectsOf(ResourceId cave, ResourceId region, ResourceId surface) {
SettingsStack<ObjectSettings> declared = context.settings().at(ObjectSettings.class, centerX, centerZ);
return new ColumnObjects(levelValue(declared, Level.BIOME), caveSettings(cave, surface, declared, ObjectSettings.class),
levelValue(declared, Level.REGION));
}
private ColumnProfiles profilesOf(ResourceId cave, ResourceId region, ResourceId surface) {
SettingsStack<CaveProfile> declared = context.settings().at(CaveProfile.class, centerX, centerZ);
return new ColumnProfiles(levelValue(declared, Level.BIOME), caveSettings(cave, surface, declared, CaveProfile.class),
levelValue(declared, Level.REGION));
}
private <F extends IrisFeature> F caveSettings(ResourceId cave, ResourceId surface, SettingsStack<F> declared, Class<F> type) {
if (cave.equals(surface)) {
return levelValue(declared, Level.BIOME);
}
return context.settings().declaredBy(cave, type).orElse(null);
}
private <F extends IrisFeature> F dimensionLevel(Class<F> type) {
return levelValue(context.settings().at(type, centerX, centerZ), Level.DIMENSION);
}
/** The value {@code level} declares, or null: the column records below hold null for a level that declares nothing. */
private static <F extends IrisFeature> F levelValue(SettingsStack<F> declared, Level level) {
return declared.level(level).orElse(null);
}
private boolean dimensionRequiresSurfaceSupport() {
RequireSurfaceSupportSettings settings = dimensionLevel(RequireSurfaceSupportSettings.class);
return settings == null ? new RequireSurfaceSupportSettings().require() : settings.require();
}
private int dimensionSurfaceSupportBuffer() {
SurfaceSupportBufferSettings settings = dimensionLevel(SurfaceSupportBufferSettings.class);
return settings == null ? new SurfaceSupportBufferSettings().buffer() : settings.buffer();
}
private boolean upperObjectsEnabled() {
UpperObjectsSettings settings = dimensionLevel(UpperObjectsSettings.class);
return settings != null && settings.enabled() && terrain.upperDimensionY(centerX, centerZ).isPresent();
}
private boolean upperObjectsForced() {
UpperObjectsForceSettings settings = dimensionLevel(UpperObjectsForceSettings.class);
return settings != null && settings.force();
}
private static List<ObjectPlacement> surfaceObjects(ObjectSettings settings) {
return settings == null ? List.of() : settings.objects().stream().filter(p -> p.carvingSupport().supportsSurface()).toList();
}
private static List<ObjectPlacement> carvingObjects(ObjectSettings settings) {
return settings == null ? List.of() : settings.objects().stream().filter(p -> p.carvingSupport().supportsCarving()).toList();
}
private CaveAnchors newAnchors() {
return new CaveAnchors(chunk.carved(), terrain, worldHeight, caveLavaHeight);
}
private Tally placeObjects(Column column) {
Tally tally = new Tally();
CaveProfile biomeCaveProfile = caves.resolve(column.profiles().cave(), column.profiles().region());
CaveProfile regionCaveProfile = caves.resolve(column.profiles().region(), column.profiles().cave());
CaveAnchors anchors = newAnchors();
placeSurfaceScope(tally, "biome-surface", surfaceObjects(column.objects().surface()), column.surface().toString());
placeCaveScope(tally, "biome-cave", carvingObjects(column.objects().cave()), biomeCaveProfile, column.cave(), column.cave().toString(), anchors);
placeSurfaceScope(tally, "region-surface", surfaceObjects(column.objects().region()), column.region().toString());
placeCaveScope(tally, "region-cave", carvingObjects(column.objects().region()), regionCaveProfile, null, column.region().toString(), anchors);
return tally;
}
private void placeSurfaceScope(Tally tally, String scope, List<ObjectPlacement> placements, String ownerName) {
for (ObjectPlacement placement : placements) {
tally.checked(scope);
try {
if (placement.isSeparated()) {
placeSeparatedObject(tally, placement, scope);
continue;
}
boolean passes = rng.chance(separation.chanceAt(placement, centerX, centerZ) + rng.d(-CHANCE_JITTER, CHANCE_JITTER));
traceChance(scope, passes, placement);
if (!passes) {
continue;
}
tally.triggered(scope);
placeObject(tally, placement, scope);
} catch (Throwable failure) {
tally.errors++;
logPlacementFailure("Failed to place objects in the following " + ownerKind(scope) + ": " + ownerName, placement, failure);
}
}
}
/** Places the one object the chunk's candidate stands for, when no closer candidate of a lower rank outranks it. */
private void placeSeparatedObject(Tally tally, ObjectPlacement placement, String scope) {
Optional<ObjectSeparation.Candidate> kept = separation.keptCandidate(chunkX, chunkZ, placement, context.settings());
traceChance(scope, kept.isPresent(), placement);
if (kept.isEmpty()) {
return;
}
tally.triggered(scope);
ObjectSeparation.Candidate candidate = kept.get();
tally.attempts++;
Optional<PlaceableObject> picked = objects.pickScaled(placement, candidate.rng());
if (picked.isEmpty()) {
tally.nullObjects++;
traceNullObject(scope, 0, 1, placement);
return;
}
placeOnSurfaceAt(tally, placement, scope, picked.get(), candidate.x(), candidate.z(), candidate.rng(), 0, 1);
}
private void placeCaveScope(Tally tally, String scope, List<ObjectPlacement> placements, CaveProfile profile,
ResourceId expectedCaveBiome, String ownerName, CaveAnchors anchors) {
for (ObjectPlacement placement : placements) {
tally.checked(scope);
boolean passes = rng.chance(placement.chance());
traceChance(scope, passes, placement);
if (!passes) {
continue;
}
tally.triggered(scope);
try {
placeCaveObject(tally, placement, profile, scope, expectedCaveBiome, anchors);
} catch (Throwable failure) {
tally.errors++;
logPlacementFailure("Failed to place cave objects in the following " + ownerKind(scope) + ": " + ownerName, placement, failure);
}
}
}
private static String ownerKind(String scope) {
return scope.startsWith("biome") ? "biome" : "region";
}
private void logPlacementFailure(String message, ObjectPlacement placement, Throwable failure) {
log.error(message, failure);
log.error("Object(s) " + String.join(", ", placement.place()) + " (" + failure.getClass().getSimpleName() + ").", null);
log.error("Are these objects missing?", null);
}
private void placeObject(Tally tally, ObjectPlacement placement, String scope) {
int blockX = context.originX();
int blockZ = context.originZ();
int density = objects.density(placement, blockX, blockZ);
for (int i = 0; i < density; i++) {
tally.attempts++;
Optional<PlaceableObject> picked = objects.pickScaled(placement, rng);
if (picked.isEmpty()) {
tally.nullObjects++;
traceNullObject(scope, i, density, placement);
continue;
}
int x = rng.i(blockX, blockX + CHUNK_WIDTH_BLOCKS);
int z = rng.i(blockZ, blockZ + CHUNK_WIDTH_BLOCKS);
placeOnSurfaceAt(tally, placement, scope, picked.get(), x, z, rng, i, density);
}
}
private void placeOnSurfaceAt(Tally tally, ObjectPlacement placement, String scope, PlaceableObject object, int x, int z,
RNG placingRng, int densityIndex, int density) {
PlacementChanges changes = effective.forSurface(placement, object);
boolean treePlacement = isTreePlacement(object, placement);
int id = placingRng.i(0, Integer.MAX_VALUE);
String goldenTag = golden ? scope + "/" + object.name() : null;
if (golden) {
log.debug("Goldendebug object attempt: chunk=" + chunkX + "," + chunkZ + " scope=" + scope + " object=" + object.name()
+ " densityIndex=" + densityIndex + " xx=" + x + " zz=" + z + " mode=" + placement.mode());
}
try {
PlacementTags tags = tags(object, id, "surface", treePlacement, placement);
int result = chunk.placeOnSurface(object, x, z, placement, changes, tags, goldenTag);
if (result >= 0) {
tally.placed++;
} else {
tally.rejected++;
}
traceObjectResult(scope, object, result, x, z, densityIndex, density);
} catch (Throwable failure) {
tally.errors++;
log.error("Regen object placement exception: chunk=" + chunkX + "," + chunkZ + " scope=" + scope + " object=" + object.name()
+ " densityIndex=" + densityIndex + " density=" + density + " error=" + failure.getClass().getSimpleName() + ":" + failure.getMessage(), failure);
}
}
private void placeCaveObject(Tally tally, ObjectPlacement placement, CaveProfile profile, String scope,
ResourceId expectedCaveBiome, CaveAnchors anchors) {
int minX = context.originX();
int minZ = context.originZ();
int density = objects.density(placement, minX, minZ);
CaveAnchors.Search search = caves.searchFor(placement, profile);
for (int i = 0; i < density; i++) {
tally.attempts++;
Optional<PlaceableObject> picked = objects.pickScaled(placement, rng);
if (picked.isEmpty()) {
tally.nullObjects++;
traceNullObject(scope, i, density, placement);
CaveRejects.log(log,scope, "NULL_OBJECT", chunkX, chunkZ, placement, null, i, density, search, null, null);
continue;
}
PlaceableObject object = picked.get();
CaveAnchors.Anchor anchor = anchors.find(rng, minX, minZ, search, expectedCaveBiome, placement.underwater());
if (anchor == null) {
tally.rejected++;
CaveRejects.log(log,scope, "NO_ANCHOR", chunkX, chunkZ, placement, object, i, density, search, null, null);
continue;
}
int id = rng.i(0, Integer.MAX_VALUE);
PlacementChanges changes = effective.forCave(placement, object, profile);
try {
PlacementTags tags = tags(object, id, "cave", isTreePlacement(object, placement), placement);
CavePlacement contained = chunk.placeInCave(object, anchor.x(), anchor.y(), anchor.z(), placement, changes,
search.minDepthBelowSurface(), tags, null);
tallyCave(tally, contained, scope, object, placement, i, density, search, anchor);
} catch (Throwable failure) {
tally.errors++;
log.error("Regen cave object placement exception: chunk=" + chunkX + "," + chunkZ + " scope=" + scope + " object=" + object.name()
+ " densityIndex=" + i + " density=" + density + " error=" + failure.getClass().getSimpleName() + ":" + failure.getMessage(), failure);
CaveRejects.log(log,scope, "EXCEPTION", chunkX, chunkZ, placement, object, i, density, search, anchor.y(), failure);
}
}
}
private void tallyCave(Tally tally, CavePlacement contained, String scope, PlaceableObject object, ObjectPlacement placement,
int index, int density, CaveAnchors.Search search, CaveAnchors.Anchor anchor) {
if (contained.wroteBlocks()) {
tally.placed++;
} else {
tally.rejected++;
CaveRejects.log(log,scope, rejectReason(contained), chunkX, chunkZ, placement, object, index, density, search, anchor.y(), null);
}
if (traceRegen) {
log.debug("Regen cave object placement result: chunk=" + chunkX + "," + chunkZ + " scope=" + scope + " object=" + object.name()
+ " resultY=" + contained.resultY() + " anchorY=" + anchor.y() + " px=" + anchor.x() + " pz=" + anchor.z()
+ " wroteBlocks=" + contained.wroteBlocks() + " densityIndex=" + index + " density=" + density);
}
}
private static String rejectReason(CavePlacement contained) {
if (contained.resultY() < 0) {
return "PLACE_NEGATIVE";
}
return contained.commit() == TerrainTransaction.Commit.REJECTED ? "CONTAINMENT" : "NO_WRITES";
}
private void placeUpperObjects(Column column) {
SettingsStack<ObjectSettings> upper = terrain.upperDimension()
.map(dimension -> dimension.settings().at(ObjectSettings.class, centerX, centerZ))
.orElse(SettingsStack.empty());
Optional<Entry<ObjectSettings>> biome = levelEntry(upper, Level.BIOME);
Optional<Entry<ObjectSettings>> region = levelEntry(upper, Level.REGION);
if (biome.isEmpty() && region.isEmpty()) {
return;
}
boolean forcePlace = upperObjectsForced();
biome.ifPresent(declared -> placeUpperScope(declared, "upper-biome-surface", "biome", forcePlace));
region.ifPresent(declared -> placeUpperScope(declared, "upper-region-surface", "region", forcePlace));
}
private static Optional<Entry<ObjectSettings>> levelEntry(SettingsStack<ObjectSettings> declared, Level level) {
return declared.entries().stream().filter(entry -> entry.level() == level).findFirst();
}
private void placeUpperScope(Entry<ObjectSettings> declared, String scope, String kind, boolean forcePlace) {
String ownerKey = declared.source().toString();
for (ObjectPlacement placement : surfaceObjects(declared.value())) {
if (!rng.chance(placement.chance() + rng.d(-CHANCE_JITTER, CHANCE_JITTER))) {
continue;
}
try {
placeUpperObject(placement, forcePlace, scope);
} catch (Throwable failure) {
log.error("Failed to place upper-dimension objects in " + kind + " " + ownerKey + ": " + String.join(", ", placement.place())
+ " (" + failure.getClass().getSimpleName() + ")", failure);
}
}
}
private void placeUpperObject(ObjectPlacement placement, boolean forcePlace, String scope) {
int minX = context.originX();
int minZ = context.originZ();
int density = objects.density(placement, minX, minZ);
for (int i = 0; i < density; i++) {
Optional<PlaceableObject> picked = objects.pickScaled(placement, rng);
if (picked.isEmpty()) {
continue;
}
PlaceableObject object = picked.get();
int x = rng.i(minX, minX + CHUNK_WIDTH_BLOCKS);
int z = rng.i(minZ, minZ + CHUNK_WIDTH_BLOCKS);
OptionalInt upperSurface = terrain.upperDimensionY(x, z);
if (upperSurface.isEmpty() || upperSurface.getAsInt() >= worldHeight - UPPER_SURFACE_MARGIN_BLOCKS) {
continue;
}
int anchorY = upperSurface.getAsInt() - 1 - Math.floorDiv(object.height(), 2);
if (anchorY <= MINIMUM_UPPER_ANCHOR_Y) {
continue;
}
int id = rng.i(0, Integer.MAX_VALUE);
PlacementChanges changes = PlacementChanges.NONE.withPlace(List.of(String.valueOf(object.name())))
.withMode(ObjectPlaceMode.CENTER_HEIGHT)
.withUpsideDown(true).withCarvingSupport(CarvingMode.ANYWHERE);
if (forcePlace) {
changes = changes.withForcePlace(true);
}
PlacementTags tags = tags(object, id, "upper", isTreePlacement(object, placement), placement);
int result = chunk.placeUpper(object, x, anchorY, z, placement, changes, tags);
if (traceRegen) {
log.debug("Upper object placement: chunk=" + chunkX + "," + chunkZ + " scope=" + scope + " object=" + object.name() + " anchorY="
+ anchorY + " upperSurfaceY=" + upperSurface.getAsInt() + " resultY=" + result + " forcePlace=" + forcePlace);
}
}
}
private PlacementTags tags(PlaceableObject object, int id, String context, boolean treePlacement, ObjectPlacement placement) {
boolean buriedTreasure = placement.isDolphinTarget() && placement.underwater();
return new PlacementTags(placementMarker(object, id, context), treePlacement, buriedTreasure);
}
private PlacementRecord placementMarker(PlaceableObject object, int id, String context) {
String key = object == null ? null : object.name();
if (key == null || key.isEmpty() || key.equals("null")) {
String fingerprint = context + "|" + (object == null ? "<null>" : object.getClass().getSimpleName());
log.warnOnce(fingerprint, "Skipping placement marker write: the object has no loadKey (context=" + context + "). "
+ "This would previously produce 'Couldn't find Object: null' warnings on chunk reload.");
return null;
}
return PlacementRecord.of(this.context.world().resources().idOf(key), id);
}
/** Objects in {@code trees/} are trees, procedural ones in {@code procedural/trees/} too, and so is anything a placement grows from saplings. */
private static boolean isTreePlacement(PlaceableObject object, ObjectPlacement placement) {
String key = object == null ? null : object.name();
if (key != null && ProceduralObjectCatalog.isProceduralKey(key)) {
key = key.substring(ProceduralObjectCatalog.KEY_PREFIX.length());
}
return (key != null && key.startsWith(TREE_FOLDER)) || (placement != null && !placement.trees().isEmpty());
}
private void traceChance(String scope, boolean passes, ObjectPlacement placement) {
if (!traceRegen) {
return;
}
log.debug("Regen object placer chance: chunk=" + chunkX + "," + chunkZ + " scope=" + scope + " chanceResult=" + passes
+ " chanceBase=" + placement.chance() + " densityMid=" + placement.middleDensity() + " objects=" + placement.place().size());
}
private void traceNullObject(String scope, int index, int density, ObjectPlacement placement) {
if (!traceRegen) {
return;
}
log.debug("Regen object placement null object: chunk=" + chunkX + "," + chunkZ + " scope=" + scope + " densityIndex=" + index
+ " density=" + density + " placementKeys=" + String.join(",", placement.place()));
}
private void traceObjectResult(String scope, PlaceableObject object, int result, int x, int z, int index, int density) {
if (golden) {
log.debug("Goldendebug object result: chunk=" + chunkX + "," + chunkZ + " scope=" + scope + " object=" + object.name()
+ " resultY=" + result + " fallback=surface");
}
if (traceRegen) {
log.debug("Regen object placement result: chunk=" + chunkX + "," + chunkZ + " scope=" + scope + " object=" + object.name()
+ " resultY=" + result + " px=" + x + " pz=" + z + " fallback=surface densityIndex=" + index + " density=" + density);
}
}
private void logCaveDiagnostics(Column column) {
int carvedBlocks = 0;
int maxY = Math.min(worldHeight - 1, column.surfaceY() - DIAGNOSTIC_SURFACE_MARGIN);
for (int y = 1; y < maxY; y++) {
if (chunk.carved().isCarved(centerX, y, centerZ)) {
carvedBlocks++;
}
}
log.debug("Cave object diag: chunk=" + chunkX + "," + chunkZ + " surfaceBiome=" + column.surface() + " caveBiome=" + column.cave()
+ " surfaceY=" + column.surfaceY() + " maxAnchorY=" + maxY + " carvedAtCenter=" + carvedBlocks
+ " biomeCarvingObjects=" + carvingObjects(column.objects().cave()).size()
+ " regionCarvingObjects=" + carvingObjects(column.objects().region()).size()
+ " sameBiome=" + column.cave().equals(column.surface()));
}
private void logLayerStart(Column column) {
log.debug("Regen object layer start: chunk=" + chunkX + "," + chunkZ + " surfaceBiome=" + column.surface() + " caveBiome=" + column.cave()
+ " region=" + column.region() + " biomeSurfacePlacers=" + surfaceObjects(column.objects().surface()).size()
+ " biomeCavePlacers=" + carvingObjects(column.objects().cave()).size()
+ " regionSurfacePlacers=" + surfaceObjects(column.objects().region()).size()
+ " regionCavePlacers=" + carvingObjects(column.objects().region()).size());
}
private void logLayerDone(Tally tally) {
log.debug("Regen object layer done: chunk=" + chunkX + "," + chunkZ + " " + tally.describe()
+ " objectAttempts=" + tally.attempts + " objectPlaced=" + tally.placed + " objectRejected=" + tally.rejected
+ " objectNull=" + tally.nullObjects + " objectErrors=" + tally.errors);
}
private record Column(ResourceId region, ResourceId surface, ResourceId cave, int surfaceY, ColumnObjects objects,
ColumnProfiles profiles) {
}
private record ColumnObjects(ObjectSettings surface, ObjectSettings cave, ObjectSettings region) {
}
private record ColumnProfiles(CaveProfile surface, CaveProfile cave, CaveProfile region) {
}
/** What placing the objects of a chunk came to. */
private static final class Tally {
private final java.util.Map<String, int[]> scopes = new java.util.LinkedHashMap<>();
private int attempts;
private int placed;
private int rejected;
private int nullObjects;
private int errors;
void checked(String scope) {
scopes.computeIfAbsent(scope, key -> new int[2])[0]++;
}
void triggered(String scope) {
scopes.computeIfAbsent(scope, key -> new int[2])[1]++;
}
String describe() {
StringBuilder text = new StringBuilder();
scopes.forEach((scope, counts) -> text.append(scope).append("PlacersChecked=").append(counts[0])
.append(' ').append(scope).append("PlacersTriggered=").append(counts[1]).append(' '));
return text.toString();
}
}
}
@@ -0,0 +1,90 @@
/*
* Iris is a World Generator for Minecraft Servers
* Copyright (c) 2026 Arcane Arts (Volmit Software)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package art.arcane.iris.engine.mantle.components;
import art.arcane.iris.builtin.anchor.ObjectPlaceMode;
import art.arcane.iris.builtin.anchor.PlaceTrait;
import art.arcane.iris.modules.carve.CaveProfile;
import art.arcane.iris.builtin.objects.ObjectPlacement;
import art.arcane.iris.modules.objects.PlacementChanges;
import com.volmit.object.PlaceableObject;
import java.util.List;
import java.util.Locale;
/** How a dimension and a cave profile change the placement an object is placed with. */
final class EffectivePlacements {
private static final String IMPORTS_FOLDER = "imports/";
private final boolean dimensionRequiresSurfaceSupport;
private final int dimensionSurfaceSupportBuffer;
EffectivePlacements(boolean dimensionRequiresSurfaceSupport, int dimensionSurfaceSupportBuffer) {
this.dimensionRequiresSurfaceSupport = dimensionRequiresSurfaceSupport;
this.dimensionSurfaceSupportBuffer = dimensionSurfaceSupportBuffer;
}
/** The changes to make to {@code placement} to place {@code object} on the surface. */
PlacementChanges forSurface(ObjectPlacement placement, PlaceableObject object) {
return withDimensionSurfaceSupport(placement, withImportedMode(placement, object, PlacementChanges.NONE));
}
/** The changes to make to {@code placement} to place {@code object} in a cave with the cave profile {@code caveProfile}. */
PlacementChanges forCave(ObjectPlacement placement, PlaceableObject object, CaveProfile caveProfile) {
PlacementChanges changes = forSurface(placement, object);
ObjectPlaceMode mode = changes.mode() != null ? changes.mode() : placement.mode();
if (mode != ObjectPlaceMode.CENTER_HEIGHT || caveProfile == null) {
return changes;
}
ObjectPlaceMode profileMode = caveProfile.defaultObjectPlaceMode().orElse(null);
if (profileMode == null) {
return changes;
}
String key = object.name();
List<String> place = key == null || key.isBlank() ? List.of() : List.of(key);
return changes.withPlace(place).withMode(profileMode);
}
/** Imported objects are placed with the fast minimal stilt unless their mode finds its own height. */
private static PlacementChanges withImportedMode(ObjectPlacement placement, PlaceableObject object, PlacementChanges changes) {
String key = object.name();
if (key == null || key.isBlank() || !isImported(key)) {
return changes;
}
ObjectPlaceMode mode = placement.mode();
if (mode.placeMode().has(PlaceTrait.FREE_HEIGHT) || mode == ObjectPlaceMode.FAST_MIN_STILT) {
return changes;
}
return changes.withPlace(List.of(key)).withMode(ObjectPlaceMode.FAST_MIN_STILT);
}
private static boolean isImported(String key) {
return key.toLowerCase(Locale.ROOT).contains(IMPORTS_FOLDER);
}
/** The dimension widens the buffer of a placement, never narrows it, and its support requirement applies on top of the placement's own: both have to want it. */
private PlacementChanges withDimensionSurfaceSupport(ObjectPlacement placement, PlacementChanges changes) {
boolean require = placement.requireSurfaceSupport() && dimensionRequiresSurfaceSupport;
int buffer = Math.max(placement.surfaceSupportBuffer(), dimensionSurfaceSupportBuffer);
if (require == placement.requireSurfaceSupport() && buffer == placement.surfaceSupportBuffer()) {
return changes;
}
return changes.withSurfaceSupport(require, buffer);
}
}
@@ -0,0 +1,68 @@
/*
* Iris is a World Generator for Minecraft Servers
* Copyright (c) 2026 Arcane Arts (Volmit Software)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package art.arcane.iris.engine.mantle.components;
import art.arcane.iris.engine.object.terrain.floating.Column;
import art.arcane.iris.engine.object.terrain.floating.FloatingIslandBoundarySampler;
import art.arcane.iris.engine.object.terrain.floating.FloatingIslandSample;
import art.arcane.iris.engine.object.terrain.floating.FloatingWorld;
import com.volmit.ModuleLog;
import com.volmit.resource.ResourceId;
import java.util.HashMap;
import java.util.Map;
/** The island samples of the columns one chunk's floating objects ask about, each sampled once; null where no island is. */
final class FloatingIslandSampleResolver implements IslandFace.SampleProvider {
private final FloatingWorld world;
private final int worldHeight;
private final FloatingIslandBoundarySampler boundarySampler;
private final Map<Column, FloatingIslandSample> samples = new HashMap<>();
private final ModuleLog log;
FloatingIslandSampleResolver(FloatingWorld world, int worldHeight, FloatingIslandBoundarySampler boundarySampler, ModuleLog log) {
this.world = world;
this.worldHeight = worldHeight;
this.boundarySampler = boundarySampler;
this.log = log;
}
@Override
public FloatingIslandSample sample(int x, int z) {
Column key = new Column(x, z);
if (samples.containsKey(key)) {
return samples.get(key);
}
FloatingIslandSample sample = resolve(x, z);
samples.put(key, sample);
return sample;
}
private FloatingIslandSample resolve(int x, int z) {
ResourceId parent = parent(x, z);
if (parent == null || world.declaredBy(parent).isEmpty()) {
return null;
}
return FloatingIslandSample.sample(parent, x, z, worldHeight, world, boundarySampler, log);
}
ResourceId parent(int x, int z) {
return boundarySampler.parent(x, z);
}
}
@@ -0,0 +1,508 @@
/*
* Iris is a World Generator for Minecraft Servers
* Copyright (c) 2026 Arcane Arts (Volmit Software)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package art.arcane.iris.engine.mantle.components;
import art.arcane.iris.builtin.IrisSeedPurposes;
import art.arcane.iris.modules.floating.FloatingChildBiome;
import art.arcane.iris.modules.floating.FloatingChildSettings;
import art.arcane.iris.modules.floating.IslandFootprint;
import art.arcane.iris.builtin.objects.ObjectPlacement;
import art.arcane.iris.builtin.objects.ObjectSettings;
import art.arcane.iris.engine.procedural.ProceduralObjectCatalog;
import art.arcane.iris.modules.objects.ObjectPool;
import art.arcane.iris.modules.objects.ObjectSize;
import com.volmit.object.PlaceableObject;
import com.volmit.resource.PackResources;
import art.arcane.iris.engine.object.terrain.floating.FloatingIslandBoundarySampler;
import art.arcane.iris.engine.object.terrain.floating.FloatingIslandSample;
import art.arcane.iris.engine.object.terrain.floating.FloatingWorld;
import art.arcane.iris.engine.object.terrain.floating.ResolvedFloatingChild;
import art.arcane.volmlib.util.cache.CacheKey;
import art.arcane.volmlib.util.collection.KList;
import art.arcane.volmlib.util.math.RNG;
import com.volmit.ModuleLog;
import com.volmit.config.FeatureSettings.Entry;
import com.volmit.config.Level;
import com.volmit.config.PackSettings;
import com.volmit.geometry.BlockBox;
import com.volmit.geometry.BlockPosition;
import com.volmit.resource.ResourceId;
import com.volmit.stage.MantleStageContext;
import com.volmit.world.PackWorld;
import java.util.HashMap;
import java.util.HashSet;
import java.util.IdentityHashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
/**
* Places the objects of floating child biomes on and under their islands into the mantle for
* {@link art.arcane.iris.engine.modifier.FloatingModule}. One per world. Its reach is the largest placement reach of any
* floating object the dimension's biomes can place, at least 16 blocks.
*/
public final class FloatingObjectPlacing {
private static final int INVERTED_PICK_ATTEMPTS = 8;
private static final long CHUNK_RANDOM_SALT = 0x0FA710BEL;
private static final int CHUNK_COLUMNS = 256;
private static final int MIN_REACH_BLOCKS = 16;
private static final int LARGE_REACH_WARNING_BLOCKS = 128;
private static final int FLAT_TOLERANCE_BLOCKS = 2;
private static final int LOOSE_FLAT_TOLERANCE_BLOCKS = 4;
private static final int QUARTER_TURN_DEGREES = 90;
private static final int QUARTER_TURNS = 4;
private static final double CHANCE_JITTER = 0.005;
private static final String BIOME_PATH_PREFIX = "biome/";
private final FloatingWorld world;
private final ObjectPool objects;
private final FloatingPlacer placer;
private final long mantleSeed;
private final ModuleLog log;
FloatingObjectPlacing(FloatingWorld world, ObjectPool objects, FloatingPlacer placer, long mantleSeed, ModuleLog log) {
this.world = world;
this.objects = objects;
this.placer = placer;
this.mantleSeed = mantleSeed;
this.log = log;
}
/** The floating object placing of {@code world}. */
public static FloatingObjectPlacing of(PackWorld world, ModuleLog log) {
return world.state(FloatingObjectPlacing.class,
generating -> new FloatingObjectPlacing(FloatingWorld.of(generating), ObjectPool.of(generating),
new FloatingPlacer(generating, log), generating.seed(IrisSeedPurposes.MANTLE), log));
}
/** Places what originates in the chunk of {@code context} into the mantle. */
public void place(MantleStageContext context) {
int minX = context.originX();
int minZ = context.originZ();
BlockBox bounds = context.terrain().bounds();
int worldHeight = bounds.maxY() - bounds.minY();
RNG chunkRng = new RNG(CacheKey.key(context.chunkX(), context.chunkZ()) + mantleSeed + CHUNK_RANDOM_SALT);
FloatingIslandSampleResolver samples = new FloatingIslandSampleResolver(world, worldHeight,
new FloatingIslandBoundarySampler(world::surfaceBiome), log);
FloatingIslandSample.clearChunkMemo();
Chunk chunk = new Chunk(context, minX, minZ,worldHeight, chunkRng, samples, sampleColumns(samples, minX, minZ));
// The maps are lookup indices only. Iteration MUST follow the encounter order of the deterministic 0..255 column
// scan: identity-hash order changes per JVM run, and the shared chunk random makes placement output depend on order.
Map<ResolvedFloatingChild, KList<Integer>> entryColumns = new IdentityHashMap<>();
Map<ResolvedFloatingChild, KList<Integer>> bottomEntryColumns = new IdentityHashMap<>();
KList<ResolvedFloatingChild> entryOrder = new KList<>();
KList<ResolvedFloatingChild> bottomEntryOrder = new KList<>();
for (int i = 0; i < CHUNK_COLUMNS; i++) {
FloatingIslandSample sample = chunk.samples[i];
if (sample == null || sample.entry == null) {
continue;
}
int column = i;
entryColumns.computeIfAbsent(sample.entry, entry -> {
entryOrder.add(entry);
return new KList<>();
}).add(column);
ResolvedFloatingChild bottomEntry = sample.bottomEntry();
if (bottomEntry != null) {
bottomEntryColumns.computeIfAbsent(bottomEntry, entry -> {
bottomEntryOrder.add(entry);
return new KList<>();
}).add(column);
}
}
for (ResolvedFloatingChild entry : entryOrder) {
placeOnTop(chunk, entry, entryColumns.get(entry));
}
for (ResolvedFloatingChild entry : bottomEntryOrder) {
placeUnder(chunk, entry, bottomEntryColumns.get(entry));
}
}
private static FloatingIslandSample[] sampleColumns(FloatingIslandSampleResolver samples, int minX, int minZ) {
FloatingIslandSample[] sampled = new FloatingIslandSample[CHUNK_COLUMNS];
for (int xf = 0; xf < 16; xf++) {
for (int zf = 0; zf < 16; zf++) {
sampled[(zf << 4) | xf] = samples.sample(minX + xf, minZ + zf);
}
}
return sampled;
}
private void placeOnTop(Chunk chunk, ResolvedFloatingChild entry, KList<Integer> columns) {
if (columns.isEmpty()) {
return;
}
ResourceId target = targetOf(chunk, entry, columns);
for (ObjectPlacement placement : entry.settings().floatingObjects()) {
placeFloating(chunk, placement, columns, entry);
}
KList<ObjectPlacement> surface = target != null ? entry.resolveTopObjects(target) : null;
List<ObjectPlacement> extras = entry.settings().extraObjects();
boolean hasSurface = surface != null && !surface.isEmpty();
if (!hasSurface && extras.isEmpty()) {
return;
}
KList<Integer> interior = interiorColumns(chunk, columns, entry, IslandFace.Side.TOP);
if (hasSurface) {
for (ObjectPlacement placement : surface) {
placeAnchored(chunk, placement, columns, interior, entry);
}
}
for (ObjectPlacement placement : extras) {
placeAnchored(chunk, placement, columns, interior, entry);
}
}
private void placeUnder(Chunk chunk, ResolvedFloatingChild entry, KList<Integer> columns) {
if (columns.isEmpty()) {
return;
}
ResourceId target = targetOf(chunk, entry, columns);
KList<ObjectPlacement> bottom = target != null ? entry.resolveBottomObjects() : null;
if (bottom == null || bottom.isEmpty()) {
return;
}
KList<Integer> interior = interiorColumns(chunk, columns, entry, IslandFace.Side.BOTTOM);
for (ObjectPlacement placement : bottom) {
placeInverted(chunk, placement, columns, interior, entry);
}
}
/** The biome the child's objects come from, its parent taken at the first of its columns. */
private ResourceId targetOf(Chunk chunk, ResolvedFloatingChild entry, KList<Integer> columns) {
int firstKey = columns.get(0);
ResourceId parent = chunk.resolver.parent(chunk.minX + (firstKey & 15), chunk.minZ + (firstKey >> 4));
return entry.realBiome(parent);
}
private void placeFloating(Chunk chunk, ObjectPlacement placement, KList<Integer> columns, ResolvedFloatingChild entry) {
RNG rng = chunk.rng;
int density = objects.density(placement, chunk.minX, chunk.minZ);
for (int i = 0; i < density; i++) {
Optional<PlaceableObject> picked = pick(placement, entry, rng);
if (picked.isEmpty()) {
continue;
}
int key = columns.get(rng.i(columns.size()));
placer.placeFloating(chunk.context, picked.get(), chunk.minX + (key & 15), chunk.minZ + (key >> 4), placement, rng);
}
}
private void placeAnchored(Chunk chunk, ObjectPlacement placement, KList<Integer> columns, KList<Integer> interior,
ResolvedFloatingChild entry) {
RNG rng = chunk.rng;
int density = objects.density(placement, chunk.minX, chunk.minZ);
for (int i = 0; i < density; i++) {
Optional<PlaceableObject> picked = pick(placement, entry, rng);
if (picked.isEmpty()) {
continue;
}
PlaceableObject object = picked.get();
IslandFootprint footprint = placer.footprint(object);
KList<Integer> pool = interior.isEmpty() ? columns : interior;
int pickedKey = pool.get(rng.i(pool.size()));
int pickedXf = pickedKey & 15;
int pickedZf = pickedKey >> 4;
FloatingIslandSample pickedSample = chunk.samples[(pickedZf << 4) | pickedXf];
if (pickedSample == null) {
continue;
}
int pickTopY = pickedSample.topY();
int pickedX = chunk.minX + pickedXf;
int pickedZ = chunk.minZ + pickedZf;
if (!isFootprintFlat(footprint, pickedX, pickedZ, pickTopY, chunk.resolver, entry, FLAT_TOLERANCE_BLOCKS)
&& !isFootprintFlat(footprint, pickedX, pickedZ, pickTopY, chunk.resolver, entry, LOOSE_FLAT_TOLERANCE_BLOCKS)) {
continue;
}
int x = pickedX - footprint.tallestX();
int z = pickedZ - footprint.tallestZ();
int y = pickTopY + 1 - footprint.lowestSolidY();
placer.placeOnTop(chunk.context, object, x, y, z, placement, IslandFace.top(chunk.resolver, entry, pickTopY, chunk.worldHeight), rng);
}
}
private void placeInverted(Chunk chunk, ObjectPlacement placement, KList<Integer> columns, KList<Integer> interior,
ResolvedFloatingChild entry) {
RNG rng = chunk.rng;
int density = objects.density(placement, chunk.minX, chunk.minZ);
for (int i = 0; i < density; i++) {
Optional<PlaceableObject> picked = pick(placement, entry, rng);
if (picked.isEmpty()) {
continue;
}
PlaceableObject object = picked.get();
IslandFootprint footprint = placer.footprint(object);
UndersideTurn turn = new UndersideTurn(rng.i(QUARTER_TURNS) * QUARTER_TURN_DEGREES);
Optional<BottomAnchor> anchor = pickBottomAnchor(chunk, footprint, turn, interior.isEmpty() ? columns : interior, entry);
if (anchor.isEmpty()) {
continue;
}
int pickedXf = anchor.get().xf();
int pickedZf = anchor.get().zf();
int pickBottomY = anchor.get().bottomY();
int x = invertedBaseX(chunk.minX, pickedXf, footprint, turn);
int z = invertedBaseZ(chunk.minZ, pickedZf, footprint, turn);
int y = invertedBaseY(pickBottomY, footprint, turn);
placer.placeUnder(chunk.context, object, x, y, z, turn.yRotation(), placement,
IslandFace.bottom(chunk.resolver, entry, pickBottomY, chunk.worldHeight), rng);
}
}
private Optional<BottomAnchor> pickBottomAnchor(Chunk chunk, IslandFootprint footprint, UndersideTurn turn, KList<Integer> pool,
ResolvedFloatingChild entry) {
for (int attempt = 0; attempt < INVERTED_PICK_ATTEMPTS; attempt++) {
int pickedKey = pool.get(chunk.rng.i(pool.size()));
int candidateXf = pickedKey & 15;
int candidateZf = pickedKey >> 4;
FloatingIslandSample candidate = chunk.samples[(candidateZf << 4) | candidateXf];
if (candidate == null) {
continue;
}
int candidateBottomY = candidate.bottomY();
if (candidateBottomY < 0) {
continue;
}
int candidateX = chunk.minX + candidateXf;
int candidateZ = chunk.minZ + candidateZf;
if (!isFootprintFlatBottom(footprint, turn, candidateX, candidateZ, candidateBottomY, chunk.resolver, entry, FLAT_TOLERANCE_BLOCKS)
&& !isFootprintFlatBottom(footprint, turn, candidateX, candidateZ, candidateBottomY, chunk.resolver, entry,
LOOSE_FLAT_TOLERANCE_BLOCKS)) {
continue;
}
return Optional.of(new BottomAnchor(candidateXf, candidateZf, candidateBottomY));
}
return Optional.empty();
}
/** One draw of the chance, then the object the placement picks, scaled, and shrunk as the island shrinks its objects. */
private Optional<PlaceableObject> pick(ObjectPlacement placement, ResolvedFloatingChild entry, RNG rng) {
if (!rng.chance(placement.chance() + rng.d(-CHANCE_JITTER, CHANCE_JITTER))) {
return Optional.empty();
}
Optional<PlaceableObject> scaled = objects.pickScaled(placement, rng);
if (scaled.isEmpty() || !entry.hasObjectShrink()) {
return scaled;
}
return Optional.of(objects.resized(scaled.get(), entry.shrinkFactor()));
}
static boolean isFootprintFlatBottom(IslandFootprint footprint, UndersideTurn turn, int pickedX, int pickedZ, int pickBottomY,
IslandFace.SampleProvider samples, ResolvedFloatingChild entry, int tolerance) {
BlockPosition anchor = invertedFootprintAnchor(footprint, turn);
long[] cells = footprint.columns();
if (cells.length == 0) {
return false;
}
for (long encoded : cells) {
BlockPosition cell = turn.turn(IslandFootprint.columnX(encoded), 0, IslandFootprint.columnZ(encoded));
int columnX = pickedX + cell.x() - anchor.x();
int columnZ = pickedZ + cell.z() - anchor.z();
FloatingIslandSample sample = samples.sample(columnX, columnZ);
if (!IslandFace.matchesAnchor(sample, entry, IslandFace.Side.BOTTOM)) {
return false;
}
int bottomY = sample.bottomY();
if (bottomY < 0 || Math.abs(bottomY - pickBottomY) > tolerance) {
return false;
}
}
return true;
}
static int invertedBaseX(int minX, int pickedXf, IslandFootprint footprint, UndersideTurn turn) {
return minX + pickedXf - invertedFootprintAnchor(footprint, turn).x();
}
static int invertedBaseY(int pickBottomY, IslandFootprint footprint, UndersideTurn turn) {
return pickBottomY - 1 - invertedSolidAnchor(footprint, turn).y();
}
static int invertedBaseZ(int minZ, int pickedZf, IslandFootprint footprint, UndersideTurn turn) {
return minZ + pickedZf - invertedFootprintAnchor(footprint, turn).z();
}
private static BlockPosition invertedFootprintAnchor(IslandFootprint footprint, UndersideTurn turn) {
return turn.turn(footprint.tallestX(), 0, footprint.tallestZ());
}
private static BlockPosition invertedSolidAnchor(IslandFootprint footprint, UndersideTurn turn) {
return turn.turn(footprint.tallestX(), footprint.lowestSolidY(), footprint.tallestZ());
}
static boolean isFootprintFlat(IslandFootprint footprint, int pickedX, int pickedZ, int pickTopY,
IslandFace.SampleProvider samples, ResolvedFloatingChild entry, int tolerance) {
long[] cells = footprint.columns();
if (cells.length == 0) {
return false;
}
for (long encoded : cells) {
int columnX = pickedX + (IslandFootprint.columnX(encoded) - footprint.tallestX());
int columnZ = pickedZ + (IslandFootprint.columnZ(encoded) - footprint.tallestZ());
FloatingIslandSample sample = samples.sample(columnX, columnZ);
if (!IslandFace.matchesAnchor(sample, entry, IslandFace.Side.TOP) || Math.abs(sample.topY() - pickTopY) > tolerance) {
return false;
}
}
return true;
}
private static KList<Integer> interiorColumns(Chunk chunk, KList<Integer> columns, ResolvedFloatingChild entry, IslandFace.Side side) {
KList<Integer> interior = new KList<>();
for (int key : columns) {
int x = chunk.minX + (key & 15);
int z = chunk.minZ + (key >> 4);
if (IslandFace.matchesAnchor(chunk.resolver.sample(x + 1, z), entry, side)
&& IslandFace.matchesAnchor(chunk.resolver.sample(x - 1, z), entry, side)
&& IslandFace.matchesAnchor(chunk.resolver.sample(x, z + 1), entry, side)
&& IslandFace.matchesAnchor(chunk.resolver.sample(x, z - 1), entry, side)) {
interior.add(key);
}
}
return interior;
}
/** How far, in blocks along X and Z, the floating objects of the pack {@code settings} describe may write beyond their chunk. */
public static int reach(PackSettings settings, ModuleLog log) {
Reach reach = new Reach(settings.resources(), biomeObjectsOf(settings), log);
int maxObjectExtent = MIN_REACH_BLOCKS;
try {
for (Entry<FloatingChildSettings> declared : settings.declared(FloatingChildSettings.class)) {
if (declared.level() != Level.BIOME) {
continue;
}
ResourceId biome = biomeIdOf(declared.source());
for (FloatingChildBiome child : declared.value().children()) {
maxObjectExtent = Math.max(maxObjectExtent, reach.of(child, biome));
}
}
} catch (Throwable e) {
log.error("Failed to work out the reach of the floating biomes' objects", e);
}
return maxObjectExtent;
}
/** A settings entry's source names a biome as {@code biome/<key>}; the pack's resources name it by the key alone. */
private static ResourceId biomeIdOf(ResourceId source) {
String path = source.path();
return path.startsWith(BIOME_PATH_PREFIX) ? new ResourceId(source.namespace(), path.substring(BIOME_PATH_PREFIX.length())) : source;
}
/** The object settings every biome of the pack declares, by the biome's id. */
private static Map<ResourceId, ObjectSettings> biomeObjectsOf(PackSettings settings) {
Map<ResourceId, ObjectSettings> byBiome = new HashMap<>();
for (Entry<ObjectSettings> declared : settings.declared(ObjectSettings.class)) {
if (declared.level() == Level.BIOME) {
byBiome.putIfAbsent(biomeIdOf(declared.source()), declared.value());
}
}
return byBiome;
}
/** The reach of floating children's objects, each object sized once. */
private static final class Reach {
private final PackResources resources;
private final ProceduralObjectCatalog procedural;
private final Map<ResourceId, ObjectSettings> biomeObjects;
private final ModuleLog log;
private final Map<String, Optional<ObjectSize>> sizes = new HashMap<>();
private final Set<String> warnedLargeObjects = new HashSet<>();
private Reach(PackResources resources, Map<ResourceId, ObjectSettings> biomeObjects, ModuleLog log) {
this.resources = resources;
this.procedural = ProceduralObjectCatalog.detached(resources, log);
this.biomeObjects = biomeObjects;
this.log = log;
}
/**
* The surface objects a child inherits: those of the biome it names when that biome declares objects, else its
* parent's. A named biome the pack lacks inherits the parent's while placing; one that declares no objects
* inherits none, so counting the parent's for it only widens the reach.
*/
private List<ObjectPlacement> inheritedSurfaceObjects(FloatingChildBiome child, ResourceId parent) {
ResourceId named = child.biome().isBlank() ? parent : ResourceId.ofPackKey(parent.namespace(), child.biome());
ObjectSettings declared = biomeObjects.getOrDefault(named, biomeObjects.get(parent));
return FloatingWorld.surfaceObjects(Optional.ofNullable(declared));
}
int of(FloatingChildBiome child, ResourceId parent) {
int reach = 0;
reach = Math.max(reach, placementRadius(child.floatingObjects()));
reach = Math.max(reach, placementRadius(child.extraObjects()));
reach = Math.max(reach, placementRadius(child.topObjectOverrides()));
reach = Math.max(reach, placementRadius(child.bottomObjectOverrides()));
try {
List<ObjectPlacement> surface = child.inheritObjects() ? inheritedSurfaceObjects(child, parent) : List.of();
reach = Math.max(reach, placementRadius(ResolvedFloatingChild.topObjects(child, surface)));
reach = Math.max(reach, placementRadius(ResolvedFloatingChild.bottomObjects(child)));
} catch (Throwable e) {
log.error("Failed to work out the reach of a floating biome's objects", e);
}
return reach;
}
private int placementRadius(List<ObjectPlacement> placements) {
int radius = 0;
for (ObjectPlacement placement : placements) {
if (placement == null) {
continue;
}
for (String objectKey : placement.place()) {
radius = Math.max(radius, objectReach(objectKey, placement));
}
}
return radius;
}
private int objectReach(String objectKey, ObjectPlacement placement) {
try {
Optional<ObjectSize> size = sizes.computeIfAbsent(objectKey, key -> PlacementReach.sizeOf(resources, procedural, key));
if (size.isEmpty()) {
return 0;
}
int reach = PlacementReach.of(size.get(), placement);
if (reach > LARGE_REACH_WARNING_BLOCKS && warnedLargeObjects.add(objectKey)) {
log.warn("Floating object " + objectKey + " has a large placement reach (" + reach + " blocks) and may increase memory usage!");
}
return reach;
} catch (Throwable e) {
log.error("Failed to size a floating object", e);
return 0;
}
}
}
private record BottomAnchor(int xf, int zf, int bottomY) {
}
/** What one chunk's placements share: where it is, its random, and its columns' island samples. */
private record Chunk(MantleStageContext context, int minX, int minZ, int worldHeight, RNG rng,
FloatingIslandSampleResolver resolver, FloatingIslandSample[] samples) {
}
}
@@ -0,0 +1,244 @@
/*
* Iris is a World Generator for Minecraft Servers
* Copyright (c) 2026 Arcane Arts (Volmit Software)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package art.arcane.iris.engine.mantle.components;
import art.arcane.iris.builtin.objects.ObjectPlacement;
import art.arcane.iris.builtin.objects.ObjectRun;
import art.arcane.iris.builtin.prepare.ObjectRotation;
import art.arcane.iris.builtin.prepare.ObjectTranslate;
import art.arcane.iris.modules.floating.IslandAnchor;
import art.arcane.iris.modules.floating.IslandFootprint;
import art.arcane.iris.modules.objects.ForwardingTerrain;
import art.arcane.iris.modules.objects.TerrainTransaction;
import art.arcane.volmlib.util.math.RNG;
import com.volmit.ModuleLog;
import com.volmit.block.BlockRegistry;
import com.volmit.block.BlockState;
import com.volmit.block.BlockTrait;
import com.volmit.geometry.BlockPosition;
import com.volmit.object.BlockEntityData;
import com.volmit.object.ObjectBlock;
import com.volmit.object.PlaceableObject;
import com.volmit.placement.PlacedMarker;
import com.volmit.placement.PlacementRecord;
import com.volmit.placement.PlacementTerrain;
import com.volmit.stage.MantleStageContext;
import com.volmit.world.PackWorld;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
/**
* Places the objects of floating islands through the pack's placement stages into the mantle of the chunk being
* generated: floating free, or against an island's top or underside, where nothing is written unless every block lands
* where the island lets it. Each object's blocks are recorded as its placement.
*/
final class FloatingPlacer {
private static final ObjectRotation NO_ROTATION = ObjectRotation.of(0, 0, 0);
private static final int SAMPLED_HEIGHT = -1;
private static final Set<String> AIR_MATERIALS = Set.of("minecraft:air", "minecraft:cave_air");
private final PackWorld world;
private final BlockRegistry blocks;
private final ModuleLog log;
FloatingPlacer(PackWorld world, ModuleLog log) {
this.world = world;
this.blocks = world.resources().blocks();
this.log = log;
}
/** Where {@code object} stands: its solid columns, its tallest column and that column's lowest solid block. */
IslandFootprint footprint(PlaceableObject object) {
Map<Long, int[]> columns = new HashMap<>();
for (ObjectBlock block : object.geometry().blocks()) {
if (!blocks.hasTrait(block.state(), BlockTrait.SOLID)) {
continue;
}
BlockPosition position = block.position();
int[] column = columns.computeIfAbsent(IslandFootprint.column(position.x(), position.z()),
ignored -> new int[]{position.y(), 0});
column[0] = Math.min(column[0], position.y());
column[1]++;
}
if (columns.isEmpty()) {
return new IslandFootprint(0, 0, object.center().y(), new long[0]);
}
long tallest = tallestColumn(columns);
long[] footprint = columns.keySet().stream().mapToLong(Long::longValue).toArray();
return new IslandFootprint(IslandFootprint.columnX(tallest), IslandFootprint.columnZ(tallest), columns.get(tallest)[0], footprint);
}
/** The column with the most solid blocks; the lowest bottom wins a tie. */
private static long tallestColumn(Map<Long, int[]> columns) {
long best = 0L;
int tallestCount = 0;
int tallestLow = Integer.MAX_VALUE;
for (Map.Entry<Long, int[]> entry : columns.entrySet()) {
int low = entry.getValue()[0];
int count = entry.getValue()[1];
if (count > tallestCount || (count == tallestCount && low < tallestLow)) {
tallestCount = count;
tallestLow = low;
best = entry.getKey();
}
}
return best;
}
/** Places {@code object} floating free at the column, into the chunk {@code context} generates. */
void placeFloating(MantleStageContext context, PlaceableObject object, int worldX, int worldZ, ObjectPlacement placement,
RNG random) {
ObjectPlacement floating = placement.toBuilder().place(List.of(object.name())).build();
int id = random.i(0, Integer.MAX_VALUE);
try {
place(ObjectRun.of(object, floating, worldX, SAMPLED_HEIGHT, worldZ), context.placementTerrain(), object, id);
} catch (Throwable failure) {
log.error("Failed to place a floating object", failure);
}
}
/**
* Places {@code object} on an island's top, its lowest block at {@code y}; nothing is written unless every block it
* writes is one {@code anchor} lets it write.
*/
void placeOnTop(MantleStageContext context, PlaceableObject object, int worldX, int y, int worldZ, ObjectPlacement placement,
IslandAnchor anchor, RNG random) {
placeAgainstIsland(context, object, worldX, y, worldZ, placement, NO_ROTATION, anchor, random, "anchored");
}
/** Places {@code object} upside down under an island, turned {@code yRotation} degrees about Y, as {@link #placeOnTop} does on top. */
void placeUnder(MantleStageContext context, PlaceableObject object, int worldX, int y, int worldZ, int yRotation,
ObjectPlacement placement, IslandAnchor anchor, RNG random) {
placeAgainstIsland(context, object, worldX, y, worldZ, placement, ObjectRotation.xFlip180WithY(yRotation), anchor, random,
"inverted");
}
private void placeAgainstIsland(MantleStageContext context, PlaceableObject object, int worldX, int y, int worldZ,
ObjectPlacement placement, ObjectRotation rotation, IslandAnchor anchor, RNG random, String kind) {
ObjectPlacement anchored = placement.toBuilder()
.place(List.of(object.name()))
.mode(placement.mode().onFloatingIsland())
.translate(new ObjectTranslate())
.rotation(rotation)
.forcePlace(true)
.bottom(false)
.build();
IslandTransaction transaction = new IslandTransaction(new IslandTerrain(context.placementTerrain(), anchor), anchor);
int id = random.i(0, Integer.MAX_VALUE);
try {
boolean placed = place(ObjectRun.of(object, anchored, worldX, y, worldZ), transaction, object, id);
if (placed) {
transaction.commit();
} else {
transaction.discard();
}
} catch (Throwable failure) {
transaction.discard();
log.error("Failed to place an " + kind + " floating object", failure);
}
}
/** Places the run and records the object's placement beside each block it wrote that is not air. */
private boolean place(ObjectRun run, PlacementTerrain terrain, PlaceableObject object, int id) {
if (!run.placeIn(world, terrain).isPlaced()) {
return false;
}
PlacementRecord placement = PlacementRecord.of(world.resources().idOf(object.name()), id);
for (BlockPosition position : run.objectBlocks()) {
if (placesBlock(terrain.get(position.x(), position.y(), position.z()))) {
terrain.recordPlacement(position.x(), position.y(), position.z(), placement);
}
}
return true;
}
private boolean placesBlock(BlockState state) {
return blocks.hasTrait(state, BlockTrait.CUSTOM) || !AIR_MATERIALS.contains(state.material().toString());
}
/**
* The mantle as an object placed against an island sees it: heights are the island face's, nothing is under water,
* and only the blocks the anchor lets the object write are written.
*/
private static final class IslandTerrain extends ForwardingTerrain {
private final IslandAnchor anchor;
private IslandTerrain(PlacementTerrain delegate, IslandAnchor anchor) {
super(delegate);
this.anchor = anchor;
}
@Override
public int highest(int x, int z, boolean ignoreFluid) {
return anchor.faceY(x, z);
}
@Override
public boolean isUnderwater(int x, int z) {
return false;
}
@Override
public void set(int x, int y, int z, BlockState state) {
if (anchor.writes(x, y, z)) {
delegate().set(x, y, z, state);
}
}
@Override
public void set(int x, int y, int z, BlockState state, BlockEntityData blockEntity) {
if (anchor.writes(x, y, z)) {
delegate().set(x, y, z, state, blockEntity);
}
}
@Override
public void recordPlacement(int x, int y, int z, PlacementRecord placement) {
if (anchor.writes(x, y, z)) {
delegate().recordPlacement(x, y, z, placement);
}
}
@Override
public void mark(PlacedMarker marker) {
BlockPosition position = marker.position();
if (anchor.writes(position.x(), position.y(), position.z())) {
delegate().mark(marker);
}
}
}
/** Writes an object placed against an island only when the anchor lets it write every block. */
private static final class IslandTransaction extends TerrainTransaction {
private final IslandAnchor anchor;
private IslandTransaction(PlacementTerrain delegate, IslandAnchor anchor) {
super(delegate);
this.anchor = anchor;
}
@Override
protected boolean accepts(int x, int y, int z) {
return anchor.writes(x, y, z);
}
}
}
@@ -0,0 +1,99 @@
/*
* Iris is a World Generator for Minecraft Servers
* Copyright (c) 2026 Arcane Arts (Volmit Software)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package art.arcane.iris.engine.mantle.components;
import art.arcane.iris.modules.objects.ForwardingTerrain;
import com.volmit.ModuleLog;
import com.volmit.placement.PlacementTerrain;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
/**
* A terrain that logs the questions a placement asks of it, for the chunks the golden-debug switch names: the
* {@code iris.goldendebug} system property, or else {@code plugins/Iris/goldendebug.txt}, holding
* {@code chunkX,chunkZ[,radius]}.
*/
final class GoldenDebugTerrain extends ForwardingTerrain {
private static final String SWITCH_PROPERTY = "iris.goldendebug";
private static final File SWITCH_FILE = new File("plugins/Iris/goldendebug.txt");
private static final int[] TARGET = parseTarget(readSwitch());
private final String tag;
private final ModuleLog log;
GoldenDebugTerrain(PlacementTerrain delegate, String tag, ModuleLog log) {
super(delegate);
this.tag = tag;
this.log = log;
}
/** Whether the switch names the chunk. */
static boolean isGoldenDebugChunk(int chunkX, int chunkZ) {
return TARGET != null
&& Math.abs(TARGET[0] - chunkX) <= TARGET[2]
&& Math.abs(TARGET[1] - chunkZ) <= TARGET[2];
}
@Override
public int highest(int x, int z, boolean ignoreFluid) {
int result = delegate().highest(x, z, ignoreFluid);
log.debug("Goldendebug query: tag=" + tag + " getHighest(" + x + "," + z + ",ignoreFluid=" + ignoreFluid + ")=" + result);
return result;
}
@Override
public boolean isCarved(int x, int y, int z) {
boolean result = delegate().isCarved(x, y, z);
log.debug("Goldendebug query: tag=" + tag + " isCarved(" + x + "," + y + "," + z + ")=" + result);
return result;
}
private static String readSwitch() {
String property = System.getProperty(SWITCH_PROPERTY);
if (property != null && !property.isBlank()) {
return property;
}
if (!SWITCH_FILE.isFile()) {
return null;
}
try {
return Files.readString(SWITCH_FILE.toPath()).trim();
} catch (IOException | SecurityException unreadable) {
return null;
}
}
private static int[] parseTarget(String raw) {
if (raw == null || raw.isBlank()) {
return null;
}
String[] parts = raw.split(",");
if (parts.length != 2 && parts.length != 3) {
return null;
}
try {
int radius = parts.length == 3 ? Integer.parseInt(parts[2].trim()) : 0;
return new int[]{Integer.parseInt(parts[0].trim()), Integer.parseInt(parts[1].trim()), radius};
} catch (NumberFormatException malformed) {
return null;
}
}
}
@@ -0,0 +1,141 @@
/*
* Iris is a World Generator for Minecraft Servers
* Copyright (c) 2026 Arcane Arts (Volmit Software)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package art.arcane.iris.engine.mantle.components;
import art.arcane.iris.modules.floating.IslandAnchor;
import art.arcane.iris.engine.object.terrain.floating.FloatingIslandSample;
import art.arcane.iris.engine.object.terrain.floating.ResolvedFloatingChild;
/**
* The top or bottom face of one floating child's island, at the height an object is anchored: what Iris's placer asks
* about the island while it places the object, and which blocks the object may write. An object may overhang its anchor
* only where the same child's face lies near the anchor height within {@value #OVERHANG_RADIUS} blocks.
*/
final class IslandFace implements IslandAnchor {
private static final int OVERHANG_RADIUS = 2;
private static final int OVERHANG_HEIGHT_TOLERANCE = 4;
private final SampleProvider samples;
private final ResolvedFloatingChild entry;
private final int anchorY;
private final Side side;
private final int worldHeight;
private IslandFace(SampleProvider samples, ResolvedFloatingChild entry, int anchorY, Side side, int worldHeight) {
this.samples = samples;
this.entry = entry;
this.anchorY = anchorY;
this.side = side;
this.worldHeight = worldHeight;
}
static IslandFace top(SampleProvider samples, ResolvedFloatingChild entry, int anchorY, int worldHeight) {
return new IslandFace(samples, entry, anchorY, Side.TOP, worldHeight);
}
static IslandFace bottom(SampleProvider samples, ResolvedFloatingChild entry, int anchorY, int worldHeight) {
return new IslandFace(samples, entry, anchorY, Side.BOTTOM, worldHeight);
}
@Override
public int faceY(int x, int z) {
FloatingIslandSample sample = samples.sample(x, z);
if (sample == null) {
return anchorY;
}
if (side == Side.TOP) {
return sample.topY();
}
int bottomY = sample.bottomY();
return bottomY < 0 ? anchorY : bottomY;
}
@Override
public boolean hasIsland(int x, int z) {
return samples.sample(x, z) != null;
}
@Override
public boolean islandSolid(int x, int y, int z) {
FloatingIslandSample sample = samples.sample(x, z);
if (sample == null) {
return false;
}
int index = y - sample.islandBaseY;
return index >= 0 && index < sample.solidMask.length && sample.solidMask[index];
}
@Override
public boolean writes(int x, int y, int z) {
return !skipsAirColumn(x, y, z);
}
/** Whether {@code sample} is this face's child's island, by the face this anchor is on. */
static boolean matchesAnchor(FloatingIslandSample sample, ResolvedFloatingChild entry, Side side) {
if (sample == null) {
return false;
}
return side == Side.TOP ? sample.entry == entry : sample.bottomEntry() == entry;
}
private boolean skipsAirColumn(int x, int y, int z) {
if (y < 0 || y >= worldHeight) {
return true;
}
FloatingIslandSample sample = samples.sample(x, z);
if (matchesAnchor(sample, entry, side) && isNearAnchorHeight(sample)) {
return side == Side.BOTTOM && y >= anchorY;
}
if (side == Side.TOP && y <= anchorY) {
return true;
}
if (side == Side.BOTTOM && y >= anchorY) {
return true;
}
return !hasNearbySupport(x, z);
}
private boolean hasNearbySupport(int x, int z) {
for (int dz = -OVERHANG_RADIUS; dz <= OVERHANG_RADIUS; dz++) {
for (int dx = -OVERHANG_RADIUS; dx <= OVERHANG_RADIUS; dx++) {
FloatingIslandSample sample = samples.sample(x + dx, z + dz);
if (matchesAnchor(sample, entry, side) && isNearAnchorHeight(sample)) {
return true;
}
}
}
return false;
}
private boolean isNearAnchorHeight(FloatingIslandSample sample) {
int faceY = side == Side.TOP ? sample.topY() : sample.bottomY();
return faceY >= 0 && Math.abs(faceY - anchorY) <= OVERHANG_HEIGHT_TOLERANCE;
}
enum Side {
TOP,
BOTTOM
}
@FunctionalInterface
interface SampleProvider {
FloatingIslandSample sample(int x, int z);
}
}
@@ -0,0 +1,167 @@
/*
* Iris is a World Generator for Minecraft Servers
* Copyright (c) 2026 Arcane Arts (Volmit Software)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package art.arcane.iris.engine.mantle.components;
import art.arcane.iris.builtin.anchor.PlaceTrait;
import art.arcane.iris.builtin.objects.ObjectPlacement;
import art.arcane.iris.builtin.objects.ObjectRun;
import art.arcane.iris.modules.objects.CarvedSpace;
import art.arcane.iris.modules.objects.CavePlacement;
import art.arcane.iris.modules.objects.CaveTransaction;
import art.arcane.iris.modules.objects.EffectiveSettings;
import art.arcane.iris.modules.objects.ForwardingTerrain;
import art.arcane.iris.modules.objects.PlacementChanges;
import art.arcane.iris.engine.procedural.ProceduralObjectCatalog;
import art.arcane.iris.modules.objects.PlacementTags;
import art.arcane.iris.modules.objects.TerrainTransaction;
import com.volmit.ModuleLog;
import com.volmit.block.BlockRegistry;
import com.volmit.block.BlockTrait;
import com.volmit.geometry.BlockPosition;
import com.volmit.object.PlaceableObject;
import com.volmit.placement.PlacedMarker;
import com.volmit.placement.PlacementOutcome;
import com.volmit.placement.PlacementTerrain;
import com.volmit.stage.MantleStageContext;
import com.volmit.world.PackWorld;
/**
* The chunk whose mantle {@code iris:objects} is placing into: the one place its objects are written. Every placement
* here runs the pack's placement stages ({@link com.volmit.placement.Placements}) over the chunk's mantle, then writes the
* placement's tags beside the object's own blocks.
*/
final class ObjectChunk {
private static final int REJECTED = -1;
private static final int SAMPLED_HEIGHT = -1;
private final PackWorld world;
private final PlacementTerrain terrain;
private final CarvedSpace carved;
private final BlockRegistry blocks;
private final ModuleLog log;
private final int worldHeight;
ObjectChunk(MantleStageContext context, ModuleLog log) {
this.world = context.world();
this.terrain = context.placementTerrain();
this.worldHeight = context.terrain().bounds().maxY();
this.carved = new CarvedSpace(context.mantle().carved(), context.mantle().bounds());
this.blocks = world.resources().blocks();
this.log = log;
}
/** The voids the cave carver planned around the chunk. */
CarvedSpace carved() {
return carved;
}
/** Whether the golden-debug switch is on for the chunk, which logs every decision of its placements. */
boolean goldenDebug(int chunkX, int chunkZ) {
return GoldenDebugTerrain.isGoldenDebugChunk(chunkX, chunkZ);
}
/**
* Places an object on the terrain, where it sits at the height its place mode finds.
*
* @param goldenTag logs the placement's questions under this tag, or null to leave them
* @return the height the object was placed at, negative when the placement rejected it
*/
int placeOnSurface(PlaceableObject object, int x, int z, ObjectPlacement placement, PlacementChanges changes,
PlacementTags tags, String goldenTag) {
PlacementTerrain placer = proceduralTerrain(terrain, object, goldenTag);
return place(ObjectRun.of(object, EffectiveSettings.withChanges(placement, changes), x, SAMPLED_HEIGHT, z), placer, tags);
}
/**
* Places an object in a cave, anchored at {@code anchorY}, and writes it only when all of it lies inside the cave and
* no deeper than {@code minDepthBelowSurface} under the surface.
*
* @param goldenTag logs the placement's questions under this tag, or null to leave them
*/
CavePlacement placeInCave(PlaceableObject object, int x, int anchorY, int z, ObjectPlacement placement, PlacementChanges changes,
int minDepthBelowSurface, PlacementTags tags, String goldenTag) {
ObjectPlacement effective = EffectiveSettings.withChanges(placement, changes);
CaveTransaction transaction = new CaveTransaction(proceduralTerrain(terrain, object, goldenTag), worldHeight, anchorY,
minDepthBelowSurface);
int placeY = anchorY;
if (effective.mode().placeMode().has(PlaceTrait.UPSIDE_DOWN)) {
placeY = Math.max(1, transaction.caveCeiling(x, z) - 1 - Math.floorDiv(object.height(), 2));
}
int result = place(ObjectRun.of(object, effective, x, placeY, z), transaction, tags);
if (result < 0) {
transaction.discard();
return new CavePlacement(result, TerrainTransaction.Commit.EMPTY);
}
return new CavePlacement(result, transaction.commit());
}
/** Places an object at a given height, which the terrain stacked above uses for the objects hung from it. */
int placeUpper(PlaceableObject object, int x, int anchorY, int z, ObjectPlacement placement, PlacementChanges changes,
PlacementTags tags) {
return place(ObjectRun.of(object, EffectiveSettings.withChanges(placement, changes), x, anchorY, z), terrain, tags);
}
private int place(ObjectRun run, PlacementTerrain placer, PlacementTags tags) {
PlacementOutcome outcome = run.placeIn(world, placer);
if (!outcome.isPlaced()) {
return REJECTED;
}
writeTags(placer, run, tags);
return run.anchorY().orElse(REJECTED);
}
/**
* A procedural variant's terrain: it keeps the leaf states the variant baked, persistent or decaying, and the
* golden-debug switch logs its questions. Pack objects use the chunk's terrain as it is.
*/
private PlacementTerrain proceduralTerrain(PlacementTerrain base, PlaceableObject object, String goldenTag) {
if (!ProceduralObjectCatalog.isProceduralKey(object.name())) {
return base;
}
PlacementTerrain keepingBakedLeaves = new DecayingTerrain(base);
return goldenTag == null ? keepingBakedLeaves : new GoldenDebugTerrain(keepingBakedLeaves, goldenTag, log);
}
/** Writes the tags beside each of the object's own blocks. */
private void writeTags(PlacementTerrain placer, ObjectRun run, PlacementTags tags) {
for (BlockPosition position : run.objectBlocks()) {
if (tags.marker() != null) {
placer.recordPlacement(position.x(), position.y(), position.z(), tags.marker());
if (tags.treeMaterial()) {
placer.mark(new PlacedMarker.TreeMaterial(position));
}
}
if (tags.buriedTreasure() && blocks.hasTrait(placer.get(position.x(), position.y(), position.z()), BlockTrait.STORAGE)) {
placer.mark(new PlacedMarker.BuriedTreasure(position));
}
}
}
/** A terrain that leaves non-persistent leaves as they are, so they decay like the real thing. */
private static final class DecayingTerrain extends ForwardingTerrain {
private DecayingTerrain(PlacementTerrain delegate) {
super(delegate);
}
@Override
public boolean preventsDecay() {
return false;
}
}
}
@@ -0,0 +1,73 @@
/*
* Iris is a World Generator for Minecraft Servers
* Copyright (c) 2026 Arcane Arts (Volmit Software)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package art.arcane.iris.engine.mantle.components;
import art.arcane.iris.modules.objects.Declaration;
import art.arcane.iris.builtin.objects.ObjectPlacement;
import art.arcane.iris.builtin.objects.ObjectSettings;
import com.volmit.config.Level;
import com.volmit.resource.PackResources;
import com.volmit.resource.ResourceId;
import com.volmit.service.ObjectsAt;
import com.volmit.world.PackWorld;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
/**
* How {@code iris:objects} tells Iris where its objects are: the objects the biome and region of a chunk would place,
* and the biomes and regions whose surface placements name an object.
*/
public final class ObjectLocating implements ObjectsAt {
@Override
public Set<ResourceId> objectsAt(PackWorld world, int chunkX, int chunkZ) {
return ObjectPlacing.of(world).guess(chunkX, chunkZ).stream()
.map(world.resources()::idOf)
.collect(Collectors.toCollection(LinkedHashSet::new));
}
@Override
public PlacedBy placedBy(PackWorld world, ResourceId object) {
PackResources resources = world.resources();
Set<ResourceId> biomes = new LinkedHashSet<>();
Set<ResourceId> regions = new LinkedHashSet<>();
for (Declaration<ObjectSettings> declaration : Declaration.allOf(world, ObjectSettings.class)) {
if (!placesObject(declaration.settings().objects(), resources, object)) {
continue;
}
(declaration.level() == Level.BIOME ? biomes : regions).add(declaration.id());
}
return new PlacedBy(biomes, regions);
}
private static boolean placesObject(List<ObjectPlacement> placements, PackResources resources, ResourceId object) {
for (ObjectPlacement placement : placements) {
if (placement != null && placement.carvingSupport().supportsSurface() && names(placement, resources, object)) {
return true;
}
}
return false;
}
private static boolean names(ObjectPlacement placement, PackResources resources, ResourceId object) {
return placement.place().stream().anyMatch(key -> key != null && resources.idOf(key).equals(object));
}
}
@@ -0,0 +1,94 @@
/*
* Iris is a World Generator for Minecraft Servers
* Copyright (c) 2026 Arcane Arts (Volmit Software)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package art.arcane.iris.engine.mantle.components;
import art.arcane.iris.builtin.IrisStages;
import art.arcane.iris.builtin.objects.ObjectPlacement;
import art.arcane.iris.builtin.objects.ObjectSettings;
import art.arcane.iris.engine.procedural.ProceduralObjectCatalog;
import art.arcane.iris.builtin.objects.RequireSurfaceSupportSettings;
import art.arcane.iris.builtin.objects.SurfaceSupportBufferSettings;
import art.arcane.iris.modules.objects.PackObjectScenes;
import art.arcane.iris.modules.objects.ProceduralObjectScenes;
import art.arcane.iris.modules.objects.TreeGrowthSettings;
import art.arcane.iris.builtin.objects.UpperObjectsForceSettings;
import art.arcane.iris.builtin.objects.UpperObjectsSettings;
import com.volmit.IrisModule;
import com.volmit.ModuleInfo;
import com.volmit.ModuleLifecycle;
import com.volmit.ModuleLog;
import com.volmit.ModuleSetup;
import com.volmit.config.PackSettings;
import com.volmit.service.ObjectsAt;
import com.volmit.service.SaplingGrowth;
import com.volmit.stage.MantleStageContext;
import com.volmit.world.PackWorld;
import java.util.List;
/**
* Module {@code iris:objects}: the objects the dimension's regions and biomes place, written into the mantle
* once the caves they may anchor in are planned. A port of what was Iris's object mantle component, its work
* done by {@link ObjectPlacing}, one per engine runtime, with the noise of its placements and the variants of the
* procedural objects they place ({@link ProceduralObjectCatalog}) built ahead of generation ({@link #warmUp}). Its
* reach is the pack's largest object placement. It tells
* Iris which objects a chunk would get and which biomes and regions place an object ({@link ObjectLocating}), for the
* object search and studio tools, grows the trees of saplings ({@link TreeGrowing}), and shows the pack's objects in
* the studio with every variant of its procedural objects ({@link PackObjectScenes}, {@link ProceduralObjectScenes}).
*/
public final class ObjectModule implements IrisModule, ModuleLifecycle {
private static final String VERSION = "built-in";
@Override
public ModuleInfo info() {
return ModuleInfo.of("iris:objects", "Objects", VERSION);
}
@Override
public void setup(ModuleSetup setup) {
ModuleLog log = setup.log();
// Ordering only: iris:carve ships in the built-ins jar, which a pack may not have.
setup.stages().define(IrisStages.Objects.PLACE).softAfter(IrisStages.Carve.CAVES).reach(settings -> reach(settings, log))
.run(ObjectModule::place);
var registry = setup.registry();
registry.registerService(ObjectsAt.class, new ObjectLocating());
registry.registerService(SaplingGrowth.class, new TreeGrowing());
List.of(ObjectSettings.class, TreeGrowthSettings.class, RequireSurfaceSupportSettings.class,
SurfaceSupportBufferSettings.class, UpperObjectsSettings.class, UpperObjectsForceSettings.class)
.forEach(registry::registerSettings);
registry.registerResourceKind(ProceduralObjectCatalog.DEFINITIONS);
registry.registerPlacementType(ObjectPlacement.class, ObjectPlacement.jsonFields());
registry.registerLifecycle(this);
setup.tooling().registerView(new PackObjectScenes());
setup.tooling().registerView(new ProceduralObjectScenes());
}
@Override
public void warmUp(PackWorld world) {
new ObjectWarmUp(world).warm();
}
private static void place(MantleStageContext context) {
ObjectPlacing.of(context.world()).place(context);
}
private static int reach(PackSettings settings, ModuleLog log) {
return new PlacementReach(settings.resources(), log).ofPack(settings);
}
}
@@ -0,0 +1,114 @@
/*
* Iris is a World Generator for Minecraft Servers
* Copyright (c) 2026 Arcane Arts (Volmit Software)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package art.arcane.iris.engine.mantle.components;
import art.arcane.iris.builtin.objects.ObjectPlacement;
import art.arcane.iris.builtin.objects.ObjectSettings;
import art.arcane.iris.modules.objects.ObjectPool;
import art.arcane.iris.modules.objects.ObjectSeparation;
import art.arcane.volmlib.util.math.RNG;
import com.volmit.ModuleLog;
import com.volmit.config.FeatureSettings;
import com.volmit.config.Level;
import com.volmit.config.SettingsStack;
import com.volmit.object.PlaceableObject;
import com.volmit.stage.MantleStageContext;
import com.volmit.world.PackWorld;
import java.util.HashSet;
import java.util.Optional;
import java.util.Set;
/**
* Places the objects the dimension's regions and biomes declare, one chunk at a time, into the mantle of a world: the worker
* of {@link ObjectModule}, one per world. It also works out which objects a chunk would get, without placing them.
*/
public final class ObjectPlacing {
private static final int CHUNK_CENTER_OFFSET_BLOCKS = 8;
private static final int CHUNK_SHIFT = 4;
private static final double CHANCE_JITTER = 0.005;
/** A guess draws from the biome's objects before the region's, as placing does. */
private static final Level[] GUESSED_LEVELS = {Level.BIOME, Level.REGION};
private final PackWorld world;
private final ObjectPool objects;
private final ObjectSeparation separation;
private final ModuleLog log;
private ObjectPlacing(PackWorld world) {
this.world = world;
this.objects = ObjectPool.of(world);
this.separation = ObjectSeparation.of(world);
this.log = world.log();
}
/** The object placing of {@code world}. */
public static ObjectPlacing of(PackWorld world) {
return world.state(ObjectPlacing.class, ObjectPlacing::new);
}
/** Places what originates in the chunk {@code context} generates. */
void place(MantleStageContext context) {
new ChunkObjectPlacing(objects, log, context).place();
}
/** The keys of the objects the chunk would get, as far as the chunk's surface objects go. */
public Set<String> guess(int chunkX, int chunkZ) {
RNG rng = objects.chunkRandom(chunkX, chunkZ);
int centerX = (chunkX << CHUNK_SHIFT) + CHUNK_CENTER_OFFSET_BLOCKS;
int centerZ = (chunkZ << CHUNK_SHIFT) + CHUNK_CENTER_OFFSET_BLOCKS;
FeatureSettings worldSettings = world.running().orElseThrow().settings();
SettingsStack<ObjectSettings> declared = worldSettings.at(ObjectSettings.class, centerX, centerZ);
Set<String> keys = new HashSet<>();
for (Level level : GUESSED_LEVELS) {
declared.level(level).ifPresent(settings -> guessFrom(settings, worldSettings, rng, chunkX, chunkZ, keys));
}
return keys;
}
private void guessFrom(ObjectSettings settings, FeatureSettings worldSettings, RNG rng, int chunkX, int chunkZ, Set<String> keys) {
int centerX = (chunkX << CHUNK_SHIFT) + CHUNK_CENTER_OFFSET_BLOCKS;
int centerZ = (chunkZ << CHUNK_SHIFT) + CHUNK_CENTER_OFFSET_BLOCKS;
for (ObjectPlacement placement : settings.objects()) {
if (!placement.carvingSupport().supportsSurface()) {
continue;
}
if (placement.isSeparated()) {
guessSeparatedKey(chunkX, chunkZ, placement, worldSettings).ifPresent(keys::add);
} else if (rng.chance(separation.chanceAt(placement, centerX, centerZ) + rng.d(-CHANCE_JITTER, CHANCE_JITTER))) {
keys.addAll(guessPlacedKeys(rng, chunkX, chunkZ, placement));
}
}
}
private Optional<String> guessSeparatedKey(int chunkX, int chunkZ, ObjectPlacement placement, FeatureSettings worldSettings) {
return separation.keptCandidate(chunkX, chunkZ, placement, worldSettings)
.flatMap(candidate -> objects.pickScaled(placement, candidate.rng()))
.map(PlaceableObject::name);
}
private Set<String> guessPlacedKeys(RNG rng, int x, int z, ObjectPlacement placement) {
Set<String> keys = new HashSet<>();
for (int i = 0; i < objects.density(placement, x, z); i++) {
Optional<PlaceableObject> picked = objects.pickScaled(placement, rng);
picked.ifPresent(object -> keys.add(object.name()));
}
return keys;
}
}
@@ -0,0 +1,69 @@
/*
* Iris is a World Generator for Minecraft Servers
* Copyright (c) 2026 Arcane Arts (Volmit Software)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package art.arcane.iris.engine.mantle.components;
import art.arcane.iris.builtin.objects.ObjectPlacement;
import art.arcane.iris.builtin.objects.ObjectSettings;
import art.arcane.iris.modules.objects.Declaration;
import art.arcane.iris.modules.objects.ObjectPool;
import com.volmit.config.Level;
import com.volmit.world.PackWorld;
import java.util.Comparator;
import java.util.List;
/**
* Builds what object placing would build on first use, for every object placement and procedural object the world's
* biomes and regions declare: the placement's density noise, and a procedural object's variants. The density noise is
* cached per seed and the variants are baked whatever picks one.
*/
final class ObjectWarmUp {
private static final Level[] WARMED_LEVELS = {Level.BIOME, Level.REGION};
private final PackWorld world;
private final ObjectPool objects;
ObjectWarmUp(PackWorld world) {
this.world = world;
this.objects = ObjectPool.of(world);
}
void warm() {
List<Declaration<ObjectSettings>> placements = byKey(Declaration.allOf(world, ObjectSettings.class));
for (Level level : WARMED_LEVELS) {
for (Declaration<ObjectSettings> declaration : placements) {
if (declaration.level() == level) {
warmPlacements(declaration.settings().objects());
}
}
}
}
private static <F extends com.volmit.IrisFeature> List<Declaration<F>> byKey(List<Declaration<F>> declarations) {
return declarations.stream().sorted(Comparator.comparing(Declaration::id)).toList();
}
private void warmPlacements(List<ObjectPlacement> placements) {
for (ObjectPlacement placement : placements) {
if (placement != null) {
objects.warm(placement);
}
}
}
}
@@ -0,0 +1,165 @@
/*
* Iris is a World Generator for Minecraft Servers
* Copyright (c) 2026 Arcane Arts (Volmit Software)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package art.arcane.iris.engine.mantle.components;
import art.arcane.iris.builtin.anchor.PlaceMode;
import art.arcane.iris.builtin.objects.ObjectPlacement;
import art.arcane.iris.builtin.objects.ObjectSettings;
import art.arcane.iris.builtin.prepare.AxisRotationClamp;
import art.arcane.iris.builtin.prepare.ObjectRotation;
import art.arcane.iris.builtin.prepare.ObjectTranslate;
import art.arcane.iris.builtin.vacuum.VacuumSettings;
import art.arcane.iris.engine.procedural.ProceduralObjectCatalog;
import art.arcane.iris.engine.procedural.ProceduralVariants;
import art.arcane.iris.modules.objects.ObjectSize;
import com.volmit.ModuleLog;
import com.volmit.config.FeatureSettings.Entry;
import com.volmit.config.PackSettings;
import com.volmit.geometry.BlockBox;
import com.volmit.resource.PackResources;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
/** How far, in blocks along X and Z, the objects a pack places may write beyond their chunk. */
final class PlacementReach {
private static final int LARGE_REACH_WARNING_BLOCKS = 128;
private static final int MAX_VACUUM_RADIUS_BLOCKS = 128;
private static final double SCALE_PADDING_FACTOR = 2D;
private final PackResources resources;
private final ProceduralObjectCatalog procedural;
private final ModuleLog log;
private final Map<String, Optional<ObjectSize>> sizes = new HashMap<>();
private final Set<String> warnedLargeObjects = new HashSet<>();
PlacementReach(PackResources resources, ModuleLog log) {
this.resources = resources;
this.procedural = ProceduralObjectCatalog.detached(resources, log);
this.log = log;
}
/** The largest reach of any object placement the pack's regions and biomes declare. */
int ofPack(PackSettings settings) {
int radius = 0;
for (Entry<ObjectSettings> entry : settings.declared(ObjectSettings.class)) {
radius = Math.max(radius, ofPlacements(entry.value().objects()));
}
return radius;
}
private int ofPlacements(List<ObjectPlacement> placements) {
int radius = 0;
for (ObjectPlacement placement : placements) {
if (placement == null) {
continue;
}
for (String objectKey : placement.place()) {
radius = Math.max(radius, ofObject(placement, objectKey));
}
}
return radius;
}
private int ofObject(ObjectPlacement placement, String objectKey) {
try {
Optional<ObjectSize> size = sizes.computeIfAbsent(objectKey, key -> sizeOf(resources, procedural, key));
if (size.isEmpty()) {
return 0;
}
int reach = of(size.get(), placement);
if (reach > LARGE_REACH_WARNING_BLOCKS && warnedLargeObjects.add(objectKey)) {
log.warn("Object " + objectKey + " has a large placement reach (" + reach + " blocks) and may increase memory usage!");
}
return reach;
} catch (Throwable failure) {
log.error("Failed to work out the reach of an object placement", failure);
return 0;
}
}
/** The size of the object {@code objectKey} names, for a procedural pool its largest variant; empty when the pack has none. */
static Optional<ObjectSize> sizeOf(PackResources resources, ProceduralObjectCatalog procedural, String objectKey) {
if (ProceduralObjectCatalog.isProceduralKey(objectKey)) {
return procedural.variants(objectKey).map(ProceduralVariants::largestSize);
}
return resources.objects().sizeOf(resources.idOf(objectKey)).map(PlacementReach::sizeOf);
}
private static ObjectSize sizeOf(BlockBox box) {
return new ObjectSize(box.maxX() - box.minX(), box.maxY() - box.minY(), box.maxZ() - box.minZ());
}
static int of(ObjectSize size, ObjectPlacement placement) {
return of(size, placement.mode().placeMode(), placement.scale().maxScale(), placement.rotation(), placement.translate(),
placement.warp() == null || placement.warp().isFlat() ? 0 : placement.warp().multiplier(),
placement.vacuumSettings().orElse(null));
}
private static int of(ObjectSize size, PlaceMode mode, Double maxScale, ObjectRotation rotation, ObjectTranslate translate,
Double warpMultiplier, VacuumSettings vacuum) {
double scale = maxScale == null ? 1D : Math.max(1D, maxScale);
int width = scaledDimension(size.width(), scale);
int height = scaledDimension(size.height(), scale);
int depth = scaledDimension(size.depth(), scale);
boolean rotateX = rotation != null && rotation.enabled() && rotation.xAxis() != null && rotation.xAxis().enabled();
boolean rotateZ = rotation != null && rotation.enabled() && rotation.zAxis() != null && rotation.zAxis().enabled();
int footprint = rotateX || rotateZ ? Math.max(width, Math.max(height, depth)) : Math.max(width, depth);
int translation = translationReach(translate, rotation, rotateX || rotateZ);
int warp = warpMultiplier == null ? 0 : (int) Math.ceil(Math.abs(warpMultiplier) / 2D);
int vacuumReach = mode.bendsTerrain() ? 2 * vacuumRadius(mode, vacuum) : 0;
long reach = (long) footprint + translation + warp + vacuumReach;
return reach > Integer.MAX_VALUE ? Integer.MAX_VALUE : (int) reach;
}
private static int scaledDimension(int dimension, double scale) {
int absoluteDimension = Math.abs(dimension);
if (scale <= 1D) {
return absoluteDimension;
}
return (int) Math.ceil((absoluteDimension * scale) + (scale * SCALE_PADDING_FACTOR));
}
private static int translationReach(ObjectTranslate translate, ObjectRotation rotation, boolean rotateVertically) {
if (translate == null || (translate.x() == 0 && translate.y() == 0 && translate.z() == 0)) {
return 0;
}
double x = translate.x();
double y = translate.y();
double z = translate.z();
if (rotateVertically) {
return (int) Math.ceil(Math.sqrt((x * x) + (y * y) + (z * z)));
}
AxisRotationClamp yAxis = rotation == null ? null : rotation.yAxis();
boolean rotateY = rotation != null && rotation.enabled() && yAxis != null && yAxis.enabled();
return rotateY ? (int) Math.ceil(Math.hypot(x, z)) : (int) Math.max(Math.abs(x), Math.abs(z));
}
private static int vacuumRadius(PlaceMode mode, VacuumSettings settings) {
int radius = mode.vacuum().defaultRadiusBlocks();
if (settings != null && settings.radius() > 0) {
radius = settings.radius();
}
return Math.max(0, Math.min(MAX_VACUUM_RADIUS_BLOCKS, radius));
}
}
@@ -0,0 +1,66 @@
/*
* Iris is a World Generator for Minecraft Servers
* Copyright (c) 2026 Arcane Arts (Volmit Software)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package art.arcane.iris.engine.mantle.components;
import art.arcane.iris.builtin.IrisStages;
import art.arcane.iris.builtin.structure.StructureHost;
import art.arcane.iris.builtin.structure.StructurePlacementSettings;
import art.arcane.iris.builtin.structure.StructureSettings;
import art.arcane.iris.engine.framework.structure.StructureResources;
import com.volmit.IrisModule;
import com.volmit.ModuleInfo;
import com.volmit.ModuleSetup;
import com.volmit.config.PackSettings;
import com.volmit.stage.MantleStageContext;
/**
* Module {@code iris:structure}: the jigsaw structures, pools and pieces of a pack (its resource kinds), the structure
* placements a pack declares, and the mantle stage that places the structures starting in each chunk. Iris builds and
* places the structures ({@link StructureHost}); their validation, the locator and the platform structure answers are
* Iris's own module {@code iris:structure-model}.
* <p>
* It is not in the built-ins jar: Iris registers it with its own modules, because Iris's jigsaw studio, importers and
* exporters read the resources it registers as the same classes.
*/
public final class StructureModule implements IrisModule {
private static final String VERSION = "built-in";
@Override
public ModuleInfo info() {
return ModuleInfo.of("iris:structure", "Structures", VERSION);
}
@Override
public void setup(ModuleSetup setup) {
setup.stages().define(IrisStages.Structure.PLACE).softAfter(IrisStages.Objects.PLACE, IrisStages.Floating.OBJECTS)
.reach(StructureModule::reach).run(StructureModule::place);
var registry = setup.registry();
StructureResources.kinds().forEach(registry::registerResourceKind);
registry.registerSettings(StructureSettings.class);
registry.registerSettings(StructurePlacementSettings.class);
}
private static void place(MantleStageContext context) {
context.world().extension(StructureHost.class).orElseThrow().placeChunk(context);
}
private static int reach(PackSettings settings) {
return settings.extension(StructureHost.class).orElseThrow().reach();
}
}
@@ -0,0 +1,94 @@
/*
* Iris is a World Generator for Minecraft Bukkit Servers
* Copyright (c) 2022 Arcane Arts (Volmit Software)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package art.arcane.iris.engine.mantle.components;
import art.arcane.volmlib.util.math.PowerOfTwoCoordinates;
final class SurfaceFluidBoundaryPlan {
static final int NO_BOUNDARY = Integer.MAX_VALUE;
private static final int CHUNK_SIZE = 16;
private static final int CHUNK_AREA = CHUNK_SIZE * CHUNK_SIZE;
private SurfaceFluidBoundaryPlan() {
}
static void fill(
int[] chunkSurfaceHeights,
double[] fieldSurfaceHeights,
boolean[] fieldHasFluid,
int fieldSize,
int padding,
int fluidHeight,
int[] boundaryStartY
) {
if (chunkSurfaceHeights == null || chunkSurfaceHeights.length < CHUNK_AREA
|| boundaryStartY == null || boundaryStartY.length < CHUNK_AREA
|| padding < 1 || fieldSize < CHUNK_SIZE + (padding * 2)
|| fieldSurfaceHeights == null || fieldSurfaceHeights.length < fieldSize * fieldSize
|| fieldHasFluid == null || fieldHasFluid.length < fieldSize * fieldSize) {
throw new IllegalArgumentException("Surface fluid boundary fields do not cover a padded chunk");
}
for (int localX = 0; localX < CHUNK_SIZE; localX++) {
int fieldX = localX + padding;
for (int localZ = 0; localZ < CHUNK_SIZE; localZ++) {
int fieldZ = localZ + padding;
int columnIndex = PowerOfTwoCoordinates.packLocal16(localX, localZ);
int boundaryY = NO_BOUNDARY;
int surfaceY = chunkSurfaceHeights[columnIndex];
int fieldIndex = (fieldX * fieldSize) + fieldZ;
if (fieldHasFluid[fieldIndex] && surfaceY < fluidHeight) {
boundaryY = surfaceY;
}
boundaryY = lowerBoundary(boundaryY, fieldSurfaceHeights, fieldHasFluid,
((fieldX - 1) * fieldSize) + fieldZ, fluidHeight);
boundaryY = lowerBoundary(boundaryY, fieldSurfaceHeights, fieldHasFluid,
((fieldX + 1) * fieldSize) + fieldZ, fluidHeight);
boundaryY = lowerBoundary(boundaryY, fieldSurfaceHeights, fieldHasFluid,
(fieldX * fieldSize) + fieldZ - 1, fluidHeight);
boundaryY = lowerBoundary(boundaryY, fieldSurfaceHeights, fieldHasFluid,
(fieldX * fieldSize) + fieldZ + 1, fluidHeight);
boundaryStartY[columnIndex] = boundaryY;
}
}
}
static boolean protects(int[] boundaryStartY, int columnIndex, int y, int fluidHeight) {
return boundaryStartY != null
&& columnIndex >= 0
&& columnIndex < boundaryStartY.length
&& y >= boundaryStartY[columnIndex]
&& y <= fluidHeight;
}
private static int lowerBoundary(
int currentBoundaryY,
double[] fieldSurfaceHeights,
boolean[] fieldHasFluid,
int fieldIndex,
int fluidHeight
) {
int neighborSurfaceY = (int) Math.round(fieldSurfaceHeights[fieldIndex]);
if (!fieldHasFluid[fieldIndex] || neighborSurfaceY >= fluidHeight) {
return currentBoundaryY;
}
return Math.min(currentBoundaryY, neighborSurfaceY + 1);
}
}
@@ -0,0 +1,266 @@
/*
* Iris is a World Generator for Minecraft Servers
* Copyright (c) 2026 Arcane Arts (Volmit Software)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package art.arcane.iris.engine.mantle.components;
import art.arcane.iris.builtin.objects.ObjectPlacement;
import art.arcane.iris.builtin.objects.ObjectRun;
import art.arcane.iris.builtin.objects.ObjectSettings;
import art.arcane.iris.engine.procedural.ProceduralObjectCatalog;
import art.arcane.iris.modules.objects.TreeGrowthSettings;
import art.arcane.iris.modules.objects.TreeMode;
import art.arcane.iris.engine.loot.BlockBiomes;
import art.arcane.iris.modules.objects.Declaration;
import art.arcane.iris.modules.objects.ObjectPool;
import art.arcane.volmlib.util.math.RNG;
import com.volmit.block.BlockRegistry;
import com.volmit.block.BlockState;
import com.volmit.block.BlockTrait;
import com.volmit.config.Level;
import com.volmit.geometry.BlockPosition;
import com.volmit.object.BlockEntityData;
import com.volmit.object.PlaceableObject;
import com.volmit.placement.PlacedBlock;
import com.volmit.placement.PlacedMarker;
import com.volmit.placement.PlacementRecord;
import com.volmit.placement.PlacementTerrain;
import com.volmit.placement.StructureVolumes;
import com.volmit.resource.ResourceId;
import com.volmit.service.SaplingGrowth;
import com.volmit.world.PackWorld;
import com.volmit.world.RunningWorld;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;
/**
* How {@code iris:objects} grows trees: when a sapling grows, the tree comes from the tree placements of the biome and
* region at the sapling (the region's too when the dimension uses all of them), placed like any object but into a list
* of blocks the host then places. The same placements tell which objects are trees.
*/
public final class TreeGrowing implements SaplingGrowth {
private static final int SAPLING_WIDTH = 1;
private static final int SAPLING_DEPTH = 1;
private static final String PROCEDURAL_TREE_FOLDER = ProceduralObjectCatalog.KEY_PREFIX + "trees/";
@Override
public Optional<Growth> grow(PackWorld world, Sapling sapling, Surroundings surroundings) {
RunningWorld running = world.running().orElseThrow();
BlockPosition at = sapling.at();
TreeGrowthSettings growth = treeGrowth(running, at);
if (!growth.enabled()) {
return Optional.empty();
}
Optional<ObjectPlacement> placement = pickPlacement(running, growth, sapling);
if (placement.isEmpty()) {
return Optional.empty();
}
List<String> keys = placement.get().place();
Optional<PlaceableObject> tree = ObjectPool.of(world).object(keys.get(RNG.r.i(keys.size())), RNG.r);
if (tree.isEmpty()) {
return Optional.empty();
}
PlaceableObject object = tree.get();
GrowthTerrain terrain = new GrowthTerrain(surroundings, running.layout().fluidHeight(), world.resources().blocks());
BlockPosition center = sapling.center();
ObjectRun run = ObjectRun.of(object, placement.get(), center.x(), center.y() + object.height() / 2, center.z());
run.placeIn(world, terrain);
return Optional.of(new Growth(world.resources().idOf(object.name()), terrain.placed()));
}
@Override
public TreeObjects treeObjects(PackWorld world) {
Set<String> objects = new HashSet<>();
for (Declaration<ObjectSettings> declaration : Declaration.allOf(world, ObjectSettings.class)) {
collectPlacements(declaration.settings().objects(), objects);
}
return new TreeObjects(idsOf(world, placedNames(world, objects)));
}
/** The names objects are placed under: a procedural pool's are its variants' own. */
private static Set<String> placedNames(PackWorld world, Set<String> objectKeys) {
ProceduralObjectCatalog procedural = ProceduralObjectCatalog.of(world);
Set<String> names = new HashSet<>();
for (String key : objectKeys) {
if (ProceduralObjectCatalog.isProceduralKey(key)) {
procedural.placeable(key).forEach(variant -> names.add(variant.name()));
} else {
names.add(key);
}
}
return names;
}
private static Set<ResourceId> idsOf(PackWorld world, Set<String> keys) {
return keys.stream().map(world.resources()::idOf).collect(Collectors.toSet());
}
private static TreeGrowthSettings treeGrowth(RunningWorld running, BlockPosition at) {
return running.settings().at(TreeGrowthSettings.class, at.x(), at.z()).dimension().orElseGet(TreeGrowthSettings::new);
}
/** One placement, picked at random, of the tree placements that grow {@code sapling}'s species. */
private static Optional<ObjectPlacement> pickPlacement(RunningWorld running, TreeGrowthSettings growth, Sapling sapling) {
List<ObjectPlacement> placements = new ArrayList<>();
BlockPosition at = sapling.at();
BlockBiomes.declaredAt(running, ObjectSettings.class, at).ifPresent(settings -> placements.addAll(matching(settings, sapling.species())));
if (growth.mode() == TreeMode.ALL || placements.isEmpty()) {
running.settings().at(ObjectSettings.class, at.x(), at.z()).level(Level.REGION)
.ifPresent(settings -> placements.addAll(matching(settings, sapling.species())));
}
if (placements.isEmpty()) {
return Optional.empty();
}
return Optional.of(placements.get(RNG.r.i(placements.size())));
}
/** The placements whose trees override {@code species}, which packs name by the path of its id, ignoring case. */
private static List<ObjectPlacement> matching(ObjectSettings settings, ResourceId species) {
List<ObjectPlacement> matches = new ArrayList<>();
for (ObjectPlacement placement : settings.objects()) {
if (placement.trees().stream().anyMatch(tree -> tree.matches(SAPLING_WIDTH, SAPLING_DEPTH, species.path()))) {
matches.add(placement);
}
}
return matches;
}
/** The objects of tree placements, and procedural objects in {@code procedural/trees/} wherever they are placed. */
private static void collectPlacements(List<ObjectPlacement> placements, Set<String> objectKeys) {
for (ObjectPlacement placement : placements) {
if (placement == null) {
continue;
}
for (String objectKey : placement.place()) {
if (objectKey != null && !objectKey.isBlank() && (!placement.trees().isEmpty() || isProceduralTree(objectKey))) {
objectKeys.add(objectKey);
}
}
}
}
private static boolean isProceduralTree(String objectKey) {
return objectKey.startsWith(PROCEDURAL_TREE_FOLDER);
}
/**
* The world around a sapling, read through the host, collecting what a tree writes into a list of blocks the host
* then places. Its leaves never decay; it has no caves, water, structures or placement records, and keeps no block
* entities or markers.
*/
private static final class GrowthTerrain implements PlacementTerrain {
private static final StructureVolumes NO_STRUCTURES = new StructureVolumes() {
@Override
public boolean isEmpty() {
return true;
}
@Override
public boolean intersects(int minX, int minY, int minZ, int maxX, int maxY, int maxZ) {
return false;
}
@Override
public boolean containsWithin(int x, int y, int z, int margin) {
return false;
}
};
private final Surroundings surroundings;
private final int fluidHeight;
private final BlockRegistry blocks;
private final List<PlacedBlock> placed = new ArrayList<>();
private GrowthTerrain(Surroundings surroundings, int fluidHeight, BlockRegistry blocks) {
this.surroundings = surroundings;
this.fluidHeight = fluidHeight;
this.blocks = blocks;
}
private List<PlacedBlock> placed() {
return placed;
}
@Override
public int highest(int x, int z, boolean ignoreFluid) {
return surroundings.highest(x, z, ignoreFluid);
}
@Override
public BlockState get(int x, int y, int z) {
return surroundings.get(x, y, z);
}
@Override
public void set(int x, int y, int z, BlockState state) {
placed.add(new PlacedBlock(new BlockPosition(x, y, z), state, Optional.empty()));
}
@Override
public void set(int x, int y, int z, BlockState state, BlockEntityData blockEntity) {
set(x, y, z, state);
}
@Override
public boolean isCarved(int x, int y, int z) {
return false;
}
@Override
public boolean isSurfaceSolid(int x, int y, int z) {
return blocks.hasTrait(get(x, y, z), BlockTrait.SOLID);
}
@Override
public boolean isUnderwater(int x, int z) {
return false;
}
@Override
public int fluidHeight() {
return fluidHeight;
}
@Override
public boolean preventsDecay() {
return true;
}
@Override
public void recordPlacement(int x, int y, int z, PlacementRecord placement) {
}
@Override
public Optional<PlacementRecord> placementAt(int x, int y, int z) {
return Optional.empty();
}
@Override
public StructureVolumes structureVolumes(int minX, int minZ, int maxX, int maxZ) {
return NO_STRUCTURES;
}
@Override
public void mark(PlacedMarker marker) {
}
}
}
@@ -0,0 +1,40 @@
/*
* Iris is a World Generator for Minecraft Servers
* Copyright (c) 2026 Arcane Arts (Volmit Software)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package art.arcane.iris.engine.mantle.components;
import com.volmit.geometry.BlockPosition;
/**
* How Iris turns an object it hangs under an island: upside down about X, then a quarter turn about Y of {@code yRotation}
* degrees (0, 90, 180 or 270), in the object's own block positions.
*/
record UndersideTurn(int yRotation) {
private static final int FULL_TURN_DEGREES = 360;
BlockPosition turn(int x, int y, int z) {
int flippedY = -y;
int flippedZ = -z;
return switch (Math.floorMod(yRotation, FULL_TURN_DEGREES)) {
case 90 -> new BlockPosition(flippedZ, flippedY, -x);
case 180 -> new BlockPosition(-x, flippedY, -flippedZ);
case 270 -> new BlockPosition(-flippedZ, flippedY, x);
default -> new BlockPosition(x, flippedY, flippedZ);
};
}
}
@@ -0,0 +1,111 @@
/*
* Iris is a World Generator for Minecraft Servers
* Copyright (c) 2026 Arcane Arts (Volmit Software)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package art.arcane.iris.engine.modifier;
import art.arcane.iris.builtin.decorant.DecorantSettings;
import art.arcane.iris.builtin.decorant.DecorationPart;
import art.arcane.iris.modules.terrain.BiomeLayers;
import art.arcane.iris.modules.terrain.ColumnSlope;
import art.arcane.iris.modules.terrain.PaletteExplosion;
import art.arcane.iris.modules.terrain.TerrainPalettes;
import art.arcane.iris.engine.decorator.BiomeDecorators;
import art.arcane.iris.engine.decorator.DecoratedBiome;
import art.arcane.iris.engine.decorator.DecorationScene;
import art.arcane.iris.engine.decorator.IrisCeilingDecorator;
import art.arcane.iris.engine.decorator.IrisSurfaceDecorator;
import art.arcane.volmlib.util.math.RNG;
import com.volmit.block.BlockRegistry;
import com.volmit.block.BlockState;
import com.volmit.config.FeatureSettings;
import com.volmit.resource.ResourceId;
import com.volmit.stage.ChunkStageContext;
import com.volmit.world.BiomeKind;
import com.volmit.world.TerrainSampler;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/** A chunk's {@link CaveDressing} from the world's biome layers, terrain palettes and decorators, which carving shares with the terrain and decorant built-ins. */
final class BuiltInCaveDressing implements CaveDressing {
private final BiomeLayers layers;
private final TerrainPalettes palettes;
private final FeatureSettings settings;
private final BlockRegistry blocks;
private final PaletteExplosion explosion;
private final ColumnSlope slope;
private final DecorationScene scene;
private final Map<ResourceId, DecoratedBiome> decoratedBiomes = new HashMap<>();
BuiltInCaveDressing(ChunkStageContext context) {
TerrainSampler terrain = context.terrain();
this.layers = BiomeLayers.of(context.world());
this.palettes = TerrainPalettes.of(context.world());
this.settings = context.settings();
this.blocks = context.world().resources().blocks();
this.explosion = PaletteExplosion.of(settings, context.originX(), context.originZ());
this.slope = (x, z) -> terrain.column((int) x, (int) z).slope();
this.scene = DecorationScene.of(context);
}
@Override
public BlockState fluidAt(int x, int z) {
return palettes.fluidAt(x, z);
}
@Override
public BlockState wall(ResourceId biome, RNG rng, int x, int y, int z) {
return layers.wall(layers.biome(biome, settings)).get(rng, x, y, z);
}
@Override
public List<BlockState> floorLayers(ResourceId biome, int x, int z, RNG rng, int depth, int floorY) {
return layers.generateLayers(layers.biome(biome, settings), explosion, x, z, rng, depth, floorY, slope);
}
@Override
public List<BlockState> ceilingLayers(ResourceId biome, int x, int z, RNG rng, int depth) {
return layers.generateCeilingLayers(layers.biome(biome, settings), explosion, x, z, rng, depth);
}
@Override
public boolean hasDecorators(ResourceId biome, DecorationPart part) {
return scene.decorators().hasDecorators(decorated(biome), part);
}
@Override
public void decorateFloor(int localX, int localZ, int x, int z, ResourceId biome, int floorY, int airThickness) {
new IrisSurfaceDecorator(scene).decorate(localX, localZ, x, x, x, z, z, z, decorated(biome), floorY, airThickness);
}
@Override
public void decorateCeiling(int localX, int localZ, int x, int z, ResourceId biome, int ceilingY, int airThickness) {
new IrisCeilingDecorator(scene).decorate(localX, localZ, x, x, x, z, z, z, decorated(biome), ceilingY, airThickness);
}
@Override
public BlockState oreFor(BlockState rock, BlockState ore) {
return blocks.oreFor(rock, ore);
}
/** The decorators' view of a cave biome: what it declares, under the key its settings come from, as other decorated biomes are. */
private DecoratedBiome decorated(ResourceId biome) {
return decoratedBiomes.computeIfAbsent(biome, id -> new DecoratedBiome(BiomeDecorators.biomeKey(id),
settings.declaredBy(id, DecorantSettings.class).orElse(null), BiomeKind.CAVE));
}
}
@@ -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 <https://www.gnu.org/licenses/>.
*/
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;
}
}
@@ -0,0 +1,150 @@
/*
* Iris is a World Generator for Minecraft Servers
* Copyright (c) 2026 Arcane Arts (Volmit Software)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package art.arcane.iris.engine.modifier;
import art.arcane.iris.builtin.IrisSeedPurposes;
import art.arcane.iris.builtin.IrisStages;
import art.arcane.iris.modules.carve.CarvingBiomeSettings;
import art.arcane.iris.modules.carve.CarvingEnabledSettings;
import art.arcane.iris.modules.carve.CarvingSettings;
import art.arcane.iris.modules.carve.CaveDepthSettings;
import art.arcane.iris.builtin.carve.CaveLavaHeightSettings;
import art.arcane.iris.modules.carve.CaveProfile;
import art.arcane.iris.modules.carve.UpperDimensionCarvingSettings;
import art.arcane.iris.modules.terrain.TerrainPalettes;
import art.arcane.iris.engine.mantle.components.CarveWorld;
import art.arcane.iris.engine.mantle.components.CaveCarving;
import art.arcane.iris.engine.mantle.components.CaveFloorMarking;
import com.volmit.IrisFeature;
import com.volmit.IrisModule;
import com.volmit.ModuleInfo;
import com.volmit.ModuleSetup;
import com.volmit.generation.ChunkContext;
import com.volmit.hunk.Hunk;
import com.volmit.mantle.CarvedVoid;
import com.volmit.mantle.MantleLayer;
import com.volmit.block.BlockRegistry;
import com.volmit.block.BlockState;
import com.volmit.block.BlockTrait;
import com.volmit.service.CaveBiomes;
import com.volmit.stage.ChunkStageContext;
import com.volmit.stage.MantleStageContext;
import com.volmit.world.PackWorld;
import com.volmit.world.TerrainSampler;
import java.util.List;
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 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;
@Override
public ModuleInfo info() {
return ModuleInfo.of("iris:carve", "Caves", VERSION);
}
@Override
public void setup(ModuleSetup setup) {
var registry = setup.registry();
List.of(CaveProfile.class, CarvingSettings.class, CarvingEnabledSettings.class, CarvingBiomeSettings.class,
CaveDepthSettings.class, CaveLavaHeightSettings.class, UpperDimensionCarvingSettings.class)
.forEach(registry::registerSettings);
registry.registerService(CaveBiomes.class, new CaveBiomeBands());
var graph = setup.stages();
graph.define(IrisStages.Carve.CAVES).reach(CAVE_REACH_BLOCKS).run(CarveModule::planCaves);
graph.define(IrisStages.Carve.APPLY).requires(IrisStages.Terrain.SHAPE).run(CarveModule::applyCaves);
}
private static void planCaves(MantleStageContext context) {
if (!carves(context)) {
return;
}
MantleLayer<CarvedVoid> voids = context.mantle().carved();
caveCarving(context).carve(voids, context.terrain(), context.chunkX(), context.chunkZ());
caveFloorMarking(context).mark(voids, context.terrain(), context.placementTerrain(), context.chunkX(), context.chunkZ());
}
private static void applyCaves(ChunkStageContext context) {
Hunk<BlockState> blocks = context.blocks();
caveApplying(context).apply(context.mantle().carved(), context.terrain(), context.chunkX(), context.chunkZ(), blocks, CaveDressing.of(context));
}
private static CaveFloorMarking caveFloorMarking(ChunkContext context) {
return context.world().state(CaveFloorMarking.class, generating -> new CaveFloorMarking(carveWorld(generating, context.terrain()),
upperDimensionCarving(context)));
}
private static CaveCarving caveCarving(ChunkContext context) {
return context.world().state(CaveCarving.class, generating -> new CaveCarving(generating, carveWorld(generating, context.terrain()),
upperDimensionCarving(context), fluidColumns(generating)));
}
private static CaveApplying caveApplying(ChunkContext context) {
return context.world().state(CaveApplying.class, generating -> new CaveApplying(generating, carveWorld(generating, context.terrain()),
upperDimensionCarving(context)));
}
/** The columns the dimension's fluid palette fills with a fluid. */
private static CaveCarving.FluidColumns fluidColumns(PackWorld world) {
TerrainPalettes palettes = TerrainPalettes.of(world);
BlockRegistry blocks = world.resources().blocks();
return (worldX, worldZ) -> {
BlockState fluid = palettes.fluidAt(worldX, worldZ);
return fluid != null && blocks.hasTrait(fluid, BlockTrait.FLUID);
};
}
/** 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(), world.seed(IrisSeedPurposes.CARVE),
terrain.bounds().maxY(), terrain.fluidHeight(), lavaHeight,
world.minWorldY());
}
private static boolean upperDimensionCarving(ChunkContext context) {
return centreDimensionValue(context, UpperDimensionCarvingSettings.class).map(UpperDimensionCarvingSettings::enabled).orElse(false);
}
/**
* A dimension turns carving off with {@code carvingEnabled}. Listing {@code iris:carve/caves} in {@code disabledComponents}
* also does: Iris then skips this stage's mantle pass like any disabled component.
*/
private static boolean carves(ChunkContext context) {
return centreDimensionValue(context, CarvingEnabledSettings.class).map(CarvingEnabledSettings::enabled).orElse(true);
}
private static <F extends IrisFeature> Optional<F> centreDimensionValue(ChunkContext context, Class<F> type) {
return context.settings().at(type, context.centreX(), context.centreZ()).dimension();
}
private static <F extends IrisFeature, V> V dimensionSetting(PackWorld world, Class<F> type, Function<F, V> read, V fallback) {
return world.settings().declared(type).dimension().map(read).orElse(fallback);
}
}
@@ -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 <https://www.gnu.org/licenses/>.
*/
package art.arcane.iris.engine.modifier;
import art.arcane.volmlib.util.math.PowerOfTwoCoordinates;
import com.volmit.mantle.CarvedVoid;
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 CarvedVoid[] 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 CarvedVoid[capacity];
mask = capacity - 1;
resizeAt = Math.max(1, (int) (capacity * LOAD_FACTOR));
}
void put(int x, int y, int z, CarvedVoid 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;
}
}
CarvedVoid 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;
}
CarvedVoid carvedVoid = values[index];
if (carvedVoid != null) {
consumer.accept(unpackX(key), unpackY(key), unpackZ(key), carvedVoid);
}
}
}
void clear() {
Arrays.fill(keys, EMPTY_KEY);
Arrays.fill(values, null);
size = 0;
}
private void resize() {
int[] oldKeys = keys;
CarvedVoid[] oldValues = values;
int nextCapacity = oldKeys.length << 1;
keys = new int[nextCapacity];
Arrays.fill(keys, EMPTY_KEY);
values = new CarvedVoid[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];
CarvedVoid value = oldValues[index];
if (key != EMPTY_KEY && value != null) {
reinsert(key, value);
}
}
}
private void reinsert(int key, CarvedVoid 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, CarvedVoid carvedVoid);
}
}
@@ -0,0 +1,640 @@
/*
* Iris is a World Generator for Minecraft Servers
* Copyright (c) 2026 Arcane Arts (Volmit Software)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package art.arcane.iris.engine.modifier;
import art.arcane.iris.builtin.decorant.DecorationPart;
import art.arcane.volmlib.util.math.BlockPosition;
import art.arcane.volmlib.util.math.PowerOfTwoCoordinates;
import art.arcane.volmlib.util.math.RNG;
import art.arcane.iris.engine.mantle.components.CarveWorld;
import com.volmit.block.BlockRegistry;
import com.volmit.block.BlockState;
import com.volmit.geometry.BlockBox;
import com.volmit.hunk.Hunk;
import com.volmit.mantle.CarvedVoid;
import com.volmit.mantle.MantleLayer;
import com.volmit.resource.PackResources;
import com.volmit.resource.ResourceId;
import com.volmit.world.PackWorld;
import com.volmit.world.TerrainSampler;
import lombok.Data;
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 world, holding the carve stream's random.
*/
public class CaveApplying {
private static final ThreadLocal<IrisCarveScratch> 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_SIZE = 16;
private static final int CHUNK_AREA = 256;
private static final int LAYER_DEPTH = 3;
private final CarveWorld world;
private final PackResources resources;
private final BlockRegistry blocks;
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.upperDimensionCarving = upperDimensionCarving;
this.rng = new RNG(world.carveSeed());
this.caveAir = blocks.find("minecraft:cave_air").orElseThrow();
this.plainAir = blocks.find("minecraft:air").orElseThrow();
this.lava = blocks.find("minecraft:lava").orElseThrow();
}
/**
* Applies the caves to the chunk at chunk coordinates {@code x}, {@code z}, whose blocks are {@code output}; the caves are in
* {@code voids}, which reads one block beyond the chunk to wall the caves that cross its border, {@code terrain} gives the
* heights and cave biomes around the chunk and {@code dressing} what its caves' walls, floors and ceilings get.
*/
public void apply(MantleLayer<CarvedVoid> voids, TerrainSampler terrain, int x, int z, Hunk<BlockState> output, CaveDressing dressing) {
new Application(voids, terrain, x, z, output, dressing).run();
}
static boolean hasExplicitCarveIntent(CarvedVoid carvedVoid) {
return carvedVoid != null && carvedVoid.fill() != CarvedVoid.Fill.OPEN;
}
static boolean isFluidIntent(CarvedVoid carvedVoid) {
return carvedVoid != null && carvedVoid.fill() == CarvedVoid.Fill.FLUID;
}
static boolean shouldPreserveExistingFluid(CarvedVoid carvedVoid, boolean existingIsFluid) {
return existingIsFluid && !hasExplicitCarveIntent(carvedVoid);
}
static boolean usesDefaultLava(int caveLavaHeight, int y) {
return y <= caveLavaHeight;
}
static boolean isUnsupportedSurfaceOre(boolean surfaceIsOre, boolean belowIsSolid) {
return surfaceIsOre && !belowIsSolid;
}
static BlockState resolveExplicitCarveState(CarvedVoid carvedVoid, BlockState fluid, BlockState lava, BlockState air) {
if (carvedVoid == null) {
return null;
}
return switch (carvedVoid.fill()) {
case FLUID -> fluid;
case LAVA -> lava;
case AIR -> air;
case OPEN -> null;
};
}
static boolean canReplaceCaveFloorLayer(Hunk<BlockState> 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<BlockState> 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 MantleLayer<CarvedVoid> voids;
private final TerrainSampler terrain;
private final int chunkX;
private final int chunkZ;
private final int chunkBlockX;
private final int chunkBlockZ;
private final Hunk<BlockState> output;
private final CaveDressing dressing;
private final CaveBlockClasses classes = new CaveBlockClasses(blocks);
private final CaveBiomeCache caveBiomeCache = new CaveBiomeCache(CAVE_BIOME_CACHE_SIZE);
private final IrisCarveScratch scratch = SCRATCH.get();
Application(MantleLayer<CarvedVoid> voids, TerrainSampler terrain, int chunkX, int chunkZ, Hunk<BlockState> output,
CaveDressing dressing) {
this.voids = voids;
this.terrain = terrain;
this.chunkX = chunkX;
this.chunkZ = chunkZ;
this.chunkBlockX = PowerOfTwoCoordinates.chunkToBlock(chunkX);
this.chunkBlockZ = PowerOfTwoCoordinates.chunkToBlock(chunkZ);
this.output = output;
this.dressing = dressing;
}
void run() {
scratch.reset();
CarveWallBuffer walls = scratch.walls;
CarveColumnMask[] columnMasks = scratch.columnMasks;
CarveColumnMask[] boundaryMasks = scratch.boundaryMasks;
int[] surfaceHeights = scratch.surfaceHeights;
Map<ResourceId, ResourceId> customBiomeCache = scratch.customBiomeCache;
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] = terrain.surfaceHeight(worldX, worldZ);
if (protectUpper) {
upperSurfaceHeights[columnIndex] = terrain.upperDimensionY(worldX, worldZ).getAsInt();
}
}
int worldHeightSpan = world.height();
int caveLavaHeight = world.lavaHeight();
BlockBox ownColumns = new BlockBox(chunkBlockX, 0, chunkBlockZ, chunkBlockX + CHUNK_SIZE, worldHeightSpan, chunkBlockZ + CHUNK_SIZE);
voids.visit(ownColumns, (xx, yy, zz, carvedVoid) -> {
if (yy <= 0) {
return;
}
int rx = xx - chunkBlockX;
int rz = zz - chunkBlockZ;
int columnIndex = PowerOfTwoCoordinates.packLocal16(rx, rz);
if (upperSurfaceHeights != null && yy >= upperSurfaceHeights[columnIndex]) {
return;
}
BlockState current = output.get(rx, yy, rz);
boolean explicitCarveIntent = hasExplicitCarveIntent(carvedVoid);
if (shouldPreserveExistingFluid(carvedVoid, classes.isFluid(current))) {
return;
}
columnMasks[columnIndex].add(yy);
if (carvedVoid.biome().isPresent()) {
scratch.customCaveBiomePresent = true;
}
if (classes.isAir(current) && !explicitCarveIntent) {
return;
}
if (explicitCarveIntent) {
// Only a fluid cavern consumes the fluid sample, so never take it per voxel.
BlockState fluid = isFluidIntent(carvedVoid) ? dressing.fluidAt(chunkBlockX + rx, chunkBlockZ + rz) : null;
BlockState carved = resolveExplicitCarveState(carvedVoid, fluid, lava, caveAir);
output.set(rx, yy, rz, carved == null ? plainAir : carved);
} else if (usesDefaultLava(caveLavaHeight, yy)) {
output.set(rx, yy, rz, lava);
} else {
output.set(rx, yy, rz, caveAir);
}
});
if (scratch.customCaveBiomePresent) {
addInternalWallsFromMantle(walls, columnMasks);
} else {
addInternalWallsFromMasks(walls, columnMasks);
}
addCrossChunkBoundaryWalls(walls, boundaryMasks, surfaceHeights);
walls.forEach((rx, yy, rz, carvedVoid) -> {
int worldX = rx + chunkBlockX;
int worldZ = rz + chunkBlockZ;
ResourceId biome = carvedVoid.biome().isEmpty()
? resolveCaveBiome(worldX, yy, worldZ)
: resolveCustomBiome(customBiomeCache, carvedVoid.biome().get());
if (biome != null) {
BlockState data = dressing.wall(biome, rng, worldX, yy, worldZ);
int columnIndex = PowerOfTwoCoordinates.packLocal16(rx, rz);
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.height()) {
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, CarvedVoid.OPEN);
}
if (rx < 15 && !columnMasks[columnIndex + 16].contains(yy)) {
walls.put(rx + 1, yy, rz, CarvedVoid.OPEN);
}
if (rz > 0 && !columnMasks[columnIndex - 1].contains(yy)) {
walls.put(rx, yy, rz - 1, CarvedVoid.OPEN);
}
if (rx > 0 && !columnMasks[columnIndex - 16].contains(yy)) {
walls.put(rx - 1, yy, rz, CarvedVoid.OPEN);
}
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) {
CarvedVoid carvedVoid = ownVoid(rx, yy, rz);
if (carvedVoid != null) {
if (rz < 15 && ownVoid(rx, yy, rz + 1) == null) {
walls.put(rx, yy, rz + 1, carvedVoid);
}
if (rx < 15 && ownVoid(rx + 1, yy, rz) == null) {
walls.put(rx + 1, yy, rz, carvedVoid);
}
if (rz > 0 && ownVoid(rx, yy, rz - 1) == null) {
walls.put(rx, yy, rz - 1, carvedVoid);
}
if (rx > 0 && ownVoid(rx - 1, yy, rz) == null) {
walls.put(rx - 1, yy, rz, carvedVoid);
}
}
yy = columnMask.nextSetBit(yy + 1);
}
}
}
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 westBlockX = chunkBlockX - 1;
int eastBlockX = chunkBlockX + CHUNK_SIZE;
int northBlockZ = chunkBlockZ - 1;
int southBlockZ = chunkBlockZ + CHUNK_SIZE;
for (int yy = 1; yy <= maxY; yy++) {
for (int offset = 0; offset < CHUNK_SIZE; offset++) {
tryAddBoundaryWall(walls, boundaryMasks, 0, yy, offset, westBlockX, chunkBlockZ + offset);
tryAddBoundaryWall(walls, boundaryMasks, CHUNK_SIZE - 1, yy, offset, eastBlockX, chunkBlockZ + offset);
tryAddBoundaryWall(walls, boundaryMasks, offset, yy, 0, chunkBlockX + offset, northBlockZ);
tryAddBoundaryWall(walls, boundaryMasks, offset, yy, CHUNK_SIZE - 1, chunkBlockX + offset, southBlockZ);
}
}
}
private void tryAddBoundaryWall(CarveWallBuffer walls, CarveColumnMask[] boundaryMasks,
int localX, int yy, int localZ, int neighborBlockX, int neighborBlockZ) {
if (ownVoid(localX, yy, localZ) != null) {
return;
}
CarvedVoid neighbor = voids.get(neighborBlockX, yy, neighborBlockZ);
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<ResourceId, ResourceId> 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 <= 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;
}
}
y = columnMask.nextSetBit(y + 1);
}
if (zone.isValid(world.height())) {
processZone(zone, rx, rz, worldX, worldZ, customBiomeCache);
}
}
private void processBoundaryColumnFromMask(CarveColumnMask boundaryMask, CarveWallBuffer walls, int columnIndex,
Map<ResourceId, ResourceId> customBiomeCache) {
int firstHeight = boundaryMask.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);
int zoneFloor = firstHeight;
int zoneCeiling = firstHeight;
int y = boundaryMask.nextSetBit(firstHeight + 1);
while (y >= 0) {
if (y == zoneCeiling + 1) {
zoneCeiling = y;
} else {
paintBoundaryZone(walls, rx, rz, worldX, worldZ, zoneFloor, zoneCeiling, customBiomeCache);
zoneFloor = y;
zoneCeiling = y;
}
y = boundaryMask.nextSetBit(y + 1);
}
paintBoundaryZone(walls, rx, rz, worldX, worldZ, zoneFloor, zoneCeiling, customBiomeCache);
}
private void paintBoundaryZone(CarveWallBuffer walls, int rx, int rz, int worldX, int worldZ, int zoneFloor, int zoneCeiling,
Map<ResourceId, ResourceId> 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;
}
if (floorBiome != null) {
paintFloorLayers(floorBiome, rx, rz, worldX, worldZ, zoneFloor);
}
if (ceilingBiome != null) {
paintCeilingLayers(ceilingBiome, rx, rz, worldX, worldZ, zoneCeiling, world.height());
}
}
/** 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<BlockState> floorLayers = dressing.floorLayers(floorBiome, worldX, worldZ, rng, LAYER_DEPTH, floorY);
for (int i = 0; i < floorY - 1; i++) {
if (i >= floorLayers.size()) {
break;
}
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;
}
output.set(rx, y, rz, classes.isOre(existing) ? dressing.oreFor(existing, layer) : layer);
}
}
/** 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<BlockState> ceilingLayers = dressing.ceilingLayers(ceilingBiome, worldX, worldZ, rng, LAYER_DEPTH);
for (int i = 0; i < ceilingLayers.size(); i++) {
int y = ceilingY + i + 1;
if (y >= maxY) {
break;
}
BlockState layer = ceilingLayers.get(i);
BlockState existing = output.get(rx, y, rz);
if (layer == null || !classes.isSolid(existing)) {
continue;
}
output.set(rx, y, rz, classes.isOre(existing) ? dressing.oreFor(existing, layer) : layer);
}
}
private void processZone(CaveZone zone, int rx, int rz, int xx, int zz, Map<ResourceId, ResourceId> customBiomeCache) {
int maxY = output.height();
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);
}
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(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(rx, rz, xx, zz, ceilingBiome, zone.getCeiling(), zone.airThickness());
}
}
ResourceId resolveCaveBoundaryBiome(int x, int y, int z, int worldX, int worldZ, Map<ResourceId, ResourceId> customBiomeCache) {
return resolveCaveBoundaryBiome(ownVoid(x, y, z), worldX, y, worldZ, customBiomeCache);
}
/** The void at a block of this chunk; null where nothing is carved, and above or below the dimension. */
private CarvedVoid ownVoid(int localX, int y, int localZ) {
if (y < 0 || y >= world.height()) {
return null;
}
return voids.get(chunkBlockX + localX, y, chunkBlockZ + localZ);
}
ResourceId resolveCaveBoundaryBiome(CarvedVoid carvedVoid, int worldX, int y, int worldZ, Map<ResourceId, ResourceId> customBiomeCache) {
if (carvedVoid != null && carvedVoid.biome().isPresent()) {
return resolveCustomBiome(customBiomeCache, carvedVoid.biome().get());
}
return resolveCaveBiome(worldX, y, worldZ);
}
private ResourceId resolveCaveBiome(int x, int y, int z) {
ResourceId center = sampleCaveBiome(x, y, z);
if (center == null) {
return null;
}
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;
}
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 pack's biome with this id; null when the pack has none or it cannot be loaded. */
private ResourceId existingBiomeId(ResourceId id) {
try {
return resources.find(PackResources.BIOMES, id).isPresent() ? id : null;
} catch (IllegalStateException unreadable) {
return null;
}
}
private ResourceId resolveCustomBiome(Map<ResourceId, ResourceId> customBiomeCache, ResourceId customBiome) {
if (customBiomeCache.containsKey(customBiome)) {
return customBiomeCache.get(customBiome);
}
ResourceId id = existingBiomeId(customBiome);
customBiomeCache.put(customBiome, id);
return id;
}
}
@Data
public static class CaveZone {
private int ceiling = -1;
private int floor = -1;
public int airThickness() {
return (ceiling - floor) - 1;
}
public boolean isValid(int height) {
return floor < ceiling && ceiling - floor >= 1 && floor >= 0 && ceiling <= height && airThickness() > 0;
}
public String toString() {
return floor + "-" + ceiling;
}
}
}
@@ -0,0 +1,73 @@
/*
* Iris is a World Generator for Minecraft Servers
* Copyright (c) 2026 Arcane Arts (Volmit Software)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package art.arcane.iris.engine.modifier;
import art.arcane.iris.modules.carve.CaveDepthSettings;
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 com.volmit.resource.ResourceId;
import com.volmit.service.CaveBiomes;
import com.volmit.world.PackWorld;
import java.util.Optional;
/**
* What the carve module tells the host about cave biomes ({@link CaveBiomes}): the biome of the dimension's carving band at a
* position, and how far below the surface a biome's caves begin.
*/
public final class CaveBiomeBands implements CaveBiomes {
@Override
public Optional<ResourceId> overriddenBiome(PackWorld world, int x, int y, int z) {
CarvingResolver resolver = CarvingResolver.of(world);
ResolvedCarvingEntry rootEntry = resolver.rootEntryAt(y);
if (rootEntry == null) {
return Optional.empty();
}
ResolvedCarvingEntry entry = resolver.resolveFromRoot(rootEntry, x, z);
if (resolver.entryBiome(entry) == null) {
return Optional.empty();
}
return Optional.of(world.resources().idOf(entry.biomeKey().trim()));
}
@Override
public int minDepthBelowSurface(PackWorld world, ResourceId biome) {
return Depths.of(world).minDepthBelowSurface(biome);
}
/** The minimum depths the world's biomes declare ({@code caveMinDepthBelowSurface}), found by biome id. */
private static final class Depths {
private final DeclaredByLevel<CaveDepthSettings> 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();
}
}
}
@@ -0,0 +1,99 @@
/*
* Iris is a World Generator for Minecraft Servers
* Copyright (c) 2026 Arcane Arts (Volmit Software)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package art.arcane.iris.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]);
}
}
}
}
@@ -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 <https://www.gnu.org/licenses/>.
*/
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<BlockState, Integer> 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;
}
}
@@ -0,0 +1,55 @@
/*
* Iris is a World Generator for Minecraft Servers
* Copyright (c) 2026 Arcane Arts (Volmit Software)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package art.arcane.iris.engine.modifier;
import art.arcane.iris.builtin.decorant.DecorationPart;
import art.arcane.volmlib.util.math.RNG;
import com.volmit.block.BlockState;
import com.volmit.resource.ResourceId;
import com.volmit.stage.ChunkStageContext;
import java.util.List;
/**
* What a cave's walls, floor and ceiling get in one chunk: its biome's layers and decorators and the dimension's fluid palette.
* {@link #of} answers with the terrain and decorant built-ins, which ship in the same jar; tests answer with fixed blocks.
*/
public interface CaveDressing {
/** The built-ins' dressing of the chunk {@code context} generates. */
static CaveDressing of(ChunkStageContext context) {
return new BuiltInCaveDressing(context);
}
BlockState fluidAt(int x, int z);
/** The block of the biome's wall at the position; null when the biome declares no wall. */
BlockState wall(ResourceId biome, RNG rng, int x, int y, int z);
List<BlockState> floorLayers(ResourceId biome, int x, int z, RNG rng, int depth, int floorY);
List<BlockState> ceilingLayers(ResourceId biome, int x, int z, RNG rng, int depth);
boolean hasDecorators(ResourceId biome, DecorationPart part);
void decorateFloor(int localX, int localZ, int x, int z, ResourceId biome, int floorY, int airThickness);
void decorateCeiling(int localX, int localZ, int x, int z, ResourceId biome, int ceilingY, int airThickness);
/** The ore that suits the {@code rock} it replaces, as the platform decides. */
BlockState oreFor(BlockState rock, BlockState ore);
}
@@ -0,0 +1,70 @@
/*
* Iris is a World Generator for Minecraft Servers
* Copyright (c) 2026 Arcane Arts (Volmit Software)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package art.arcane.iris.engine.modifier;
import art.arcane.volmlib.util.data.VectorMap;
import art.arcane.volmlib.util.math.IrisBlockVector;
import art.arcane.volmlib.util.math.Vector3i;
import com.volmit.block.BlockState;
/**
* The blocks of one deposit clump, around its centre. Blocks are kept in a {@link VectorMap} of positions relative to the centre,
* which is how Iris always held a clump, so a clump's blocks come in the same order and a chunk's deposits draw the same random
* numbers.
*/
final class DepositClump {
private final int width;
private final int height;
private final int depth;
private final Vector3i center;
private final VectorMap<BlockState> blocks = new VectorMap<>();
DepositClump(int width, int height, int depth) {
this.width = width;
this.height = height;
this.depth = depth;
this.center = new Vector3i(width / 2, height / 2, depth / 2);
}
/** How many blocks wide the clump's box is, along X. */
int width() {
return width;
}
Vector3i center() {
return center;
}
/** The clump's blocks by their position relative to its centre. */
VectorMap<BlockState> blocks() {
return blocks;
}
/** Puts {@code block} at {@code x}, {@code y}, {@code z} counted from the corner of the clump's box. */
void setFromCorner(int x, int y, int z, BlockState block) {
if (x >= width || y >= height || z >= depth) {
throw new IllegalArgumentException(x + " " + y + " " + z + " exceeds limit of " + width + " " + height + " " + depth);
}
blocks.put(new IrisBlockVector(x - center.getX(), y - center.getY(), z - center.getZ()), block);
}
/** Puts {@code block} on the centre, which is where a one block clump has its block. */
void setCentre(BlockState block) {
blocks.put(new IrisBlockVector(center.getX(), center.getY(), center.getZ()), block);
}
}
@@ -0,0 +1,78 @@
/*
* Iris is a World Generator for Minecraft Servers
* Copyright (c) 2026 Arcane Arts (Volmit Software)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package art.arcane.iris.engine.modifier;
import art.arcane.iris.builtin.IrisStages;
import art.arcane.iris.modules.deposit.DepositGenerator;
import art.arcane.iris.modules.deposit.DepositSettings;
import art.arcane.iris.modules.deposit.DepositVariantSettings;
import art.arcane.iris.modules.deposit.OreFrequencySettings;
import art.arcane.iris.modules.deposit.OreSizeSettings;
import com.volmit.IrisModule;
import com.volmit.ModuleInfo;
import com.volmit.ModuleSetup;
import com.volmit.config.FeatureSettings;
import com.volmit.stage.ChunkStageContext;
import java.util.List;
/**
* Module {@code iris:deposit}: ores and other deposits. The dimension, a region and a biome each declare their
* own {@link DepositSettings}, and they stack: a chunk gets every level's deposits at its centre column, the
* dimension's first, then the region's, then the biome's. The stage runs where any column of the chunk has
* deposits, but places only what the centre column declares, so a chunk's deposits do not depend on which
* of its columns a biome border crosses.
*/
public final class DepositModule implements IrisModule {
private static final String VERSION = "built-in";
@Override
public ModuleInfo info() {
return ModuleInfo.of("iris:deposit", "Deposits", VERSION);
}
@Override
public void setup(ModuleSetup setup) {
var registry = setup.registry();
registry.registerSettings(DepositVariantSettings.class);
registry.registerSettings(OreFrequencySettings.class);
registry.registerSettings(OreSizeSettings.class);
setup.stages().define(IrisStages.Deposit.ORES)
.when(DepositSettings.class)
.requires(IrisStages.Terrain.SHAPE)
.softAfter(IrisStages.Floating.SOLIDS)
.run(DepositModule::place);
}
private static void place(ChunkStageContext context) {
List<DepositGenerator> generators = generatorsAt(context.settings(), context.centreX(), context.centreZ());
if (generators.isEmpty()) {
return;
}
DepositPlacer.of(context.world()).generate(context, generators);
}
/** Every level's generators at the column {@code x}, {@code z}, in level order. */
static List<DepositGenerator> generatorsAt(FeatureSettings settings, int x, int z) {
return settings.at(DepositSettings.class, x, z).values().stream()
.flatMap(declared -> declared.generators().stream())
.toList();
}
}
@@ -0,0 +1,433 @@
/*
* Iris is a World Generator for Minecraft Servers
* Copyright (c) 2026 Arcane Arts (Volmit Software)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package art.arcane.iris.engine.modifier;
import art.arcane.iris.builtin.IrisSeedPurposes;
import art.arcane.iris.modules.deposit.DepositGenerator;
import art.arcane.iris.modules.deposit.DepositHeightDistribution;
import art.arcane.iris.modules.deposit.DepositPlacementScope;
import art.arcane.iris.modules.deposit.DepositVariant;
import art.arcane.iris.modules.deposit.DepositVariantSettings;
import art.arcane.iris.modules.deposit.OreFrequencySettings;
import art.arcane.iris.modules.deposit.OreSizeSettings;
import art.arcane.iris.engine.modifier.ResolvedDeposit.BiomeIdentity;
import art.arcane.volmlib.util.math.IrisBlockVector;
import art.arcane.volmlib.util.math.RNG;
import com.volmit.ModuleLog;
import com.volmit.block.BlockRegistry;
import com.volmit.block.BlockState;
import com.volmit.block.BlockTrait;
import com.volmit.config.FeatureSettings;
import com.volmit.config.Level;
import com.volmit.config.SettingsStack;
import com.volmit.hunk.Hunk;
import com.volmit.mantle.CarvedVoid;
import com.volmit.mantle.MantleLayer;
import com.volmit.resource.PackResources;
import com.volmit.resource.ResourceId;
import com.volmit.stage.ChunkStageContext;
import com.volmit.world.BiomeSample;
import com.volmit.world.PackWorld;
import com.volmit.world.TerrainSampler;
import java.util.IdentityHashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Predicate;
import java.util.function.Supplier;
/**
* Places deposit clumps into one chunk for {@link DepositModule}: one per world, holding the deposit stream's random and each
* generator made ready for this world ({@link ResolvedDeposit}: resolved blocks and clump shapes). Each generator gets its own
* random, derived from the chunk and its position in the list, and the generators of a chunk run one after the other.
*/
final class DepositPlacer {
private static final double UNCHANGED_ORE_MULTIPLIER = 1D;
private static final int CHUNK_WIDTH = 16;
private static final long CHUNK_X_SEED_FACTOR = 341873128712L;
private static final long CHUNK_Z_SEED_FACTOR = 132897987541L;
private static final int DEFAULT_SURFACE_CLEARANCE = 7;
private static final BlockState BEDROCK = new BlockState("minecraft:bedrock");
private final RNG rng;
private final BlockRegistry registry;
private final PackResources resources;
private final ModuleLog log;
private final boolean tunesOres;
private final boolean remapsOres;
private final Map<DepositGenerator, ResolvedDeposit> resolved = new ConcurrentHashMap<>();
private final Map<DepositVariant, ResolvedDepositVariant> variants = new ConcurrentHashMap<>();
private final Map<ResourceId, Optional<BiomeIdentity>> biomeIdentities = new ConcurrentHashMap<>();
DepositPlacer(PackWorld world) {
this.rng = new RNG(world.seed(IrisSeedPurposes.DEPOSIT));
this.resources = world.resources();
this.registry = resources.blocks();
this.log = world.log();
this.tunesOres = declares(world, OreFrequencySettings.class) || declares(world, OreSizeSettings.class);
this.remapsOres = declares(world, DepositVariantSettings.class);
}
/** The world's deposit placer, kept in its state store. */
static DepositPlacer of(PackWorld world) {
return world.state(DepositPlacer.class, DepositPlacer::new);
}
/** Whether any level of the pack declares {@code settings}; a world that declares none never asks a biome for them. */
private static boolean declares(PackWorld world, Class<? extends com.volmit.IrisFeature> settings) {
return !world.settings().declared(settings).isEmpty();
}
/** Runs {@code generators}, in order, on the chunk of {@code context}. */
void generate(ChunkStageContext context, List<DepositGenerator> generators) {
Placing placing = new Placing(context);
long seed = context.chunkX() * CHUNK_X_SEED_FACTOR + context.chunkZ() * CHUNK_Z_SEED_FACTOR;
long mask = 0;
for (DepositGenerator generator : generators) {
long finalSeed = seed * ++mask;
placing.generate(generator, rng.nextParallelRNG(finalSeed));
}
}
private ResolvedDeposit resolved(DepositGenerator generator) {
return resolved.computeIfAbsent(generator, ignored -> new ResolvedDeposit(generator, rng.getSeed(), registry));
}
private Optional<BiomeIdentity> identityOf(ResourceId biome) {
return biomeIdentities.computeIfAbsent(biome, id -> resources.find(PackResources.BIOMES, id)
.map(found -> new BiomeIdentity(id.path(), found.platformBiome().toString(), found.vanillaBiome().toString())));
}
/** Places deposits into one chunk, with the views of its invocation. */
private final class Placing {
private final Hunk<BlockState> blocks;
private final TerrainSampler terrain;
private final FeatureSettings settings;
private final MantleLayer<CarvedVoid> carvedVoids;
private final int originX;
private final int originZ;
private final int worldHeight;
private final int minWorldY;
private final int[] surfaceHeights = new int[CHUNK_WIDTH * CHUNK_WIDTH];
private boolean surfaceKnown;
private final Map<BlockState, Boolean> airStates = new IdentityHashMap<>();
private final Map<BlockState, Boolean> replaceableStates = new IdentityHashMap<>();
private final Map<BlockState, Map<BlockState, BlockState>> suitedOres = new IdentityHashMap<>();
Placing(ChunkStageContext context) {
this.blocks = context.blocks();
this.terrain = context.terrain();
this.settings = context.settings();
this.carvedVoids = context.mantle().carved();
this.originX = context.originX();
this.originZ = context.originZ();
this.worldHeight = blocks.height();
this.minWorldY = terrain.minWorldY();
}
void generate(DepositGenerator k, RNG rng) {
ResolvedDeposit deposit = resolved(k);
if (k.spawnChance() < rng.d())
return;
for (int l = 0; l < rng.i(k.minPerChunk(), k.maxPerChunk() + 1); l++) {
if (k.perClumpSpawnChance() < rng.d())
continue;
DepositClump clump = deposit.clump(rng);
int dim = clump.width();
int min = dim / 2;
int max = (int) (16D - dim / 2D);
if (min > max || min < 0 || max > 15) {
min = 6;
max = 9;
}
int x = rng.i(min, max + 1);
int z = rng.i(min, max + 1);
int terrainSurface = terrainSurface(x, z);
int height = k.placementScope() == DepositPlacementScope.TERRAIN
? depositSurfaceLimit(terrainSurface, k.surfaceClearance())
: worldHeight - 1;
if (height < 0) {
continue;
}
int y = sampleHeight(
k.heightDistribution(), rng, k.minHeight(), k.maxHeight(),
Math.min(height, worldHeight - 1));
if (y == Integer.MIN_VALUE) {
continue;
}
boolean clippedHeight = k.heightDistribution() == DepositHeightDistribution.CLIPPED_UNIFORM;
if (clippedHeight && y > height - 2)
continue;
int biomeY = Math.max(0, Math.min(worldHeight - 1, y));
boolean oreDeposit = deposit.isOre();
Supplier<BiomeSample> biomes = biomesAt(x, biomeY, z);
if (!deposit.matchesBiome(() -> identityOf(biomes.get().surfaceBiome()).orElse(null),
() -> biomes.get().caveBiome().flatMap(id -> identityOf(id)).orElse(null))) {
continue;
}
if (oreDeposit && tunesOres) {
Optional<ResourceId> caveBiome = biomes.get().caveBiome();
if (caveBiome.isPresent()) {
double frequencyMultiplier = oreFrequencyMultiplier(caveBiome.get());
if (frequencyMultiplier < 1D
&& !passesOreFrequency(frequencyMultiplier, rng.d())) {
continue;
}
double sizeMultiplier = oreSizeMultiplier(caveBiome.get());
if (sizeMultiplier != 1D) {
DepositClump scaledClump = deposit.clump(rng, sizeMultiplier);
int scaledDimension = scaledClump.width();
x = clampDepositCenter(x, scaledDimension, 16);
if (clippedHeight) {
y = clampDepositCenter(y, scaledDimension, worldHeight);
}
z = clampDepositCenter(z, scaledDimension, 16);
clump = scaledClump;
}
}
}
placeClump(k, deposit, clump, rng, x, y, z);
}
}
private void placeClump(DepositGenerator k, ResolvedDeposit deposit, DepositClump clump, RNG rng, int x, int y, int z) {
for (IrisBlockVector j : clump.blocks().keys()) {
int nx = j.getBlockX() + x;
int ny = j.getBlockY() + y;
int nz = j.getBlockZ() + z;
if (nx > 15 || nx < 0 || ny >= worldHeight || ny < 0 || nz < 0 || nz > 15) {
continue;
}
int columnSurface = terrainSurface(nx, nz);
if (!placementSurfaceAllows(
k.placementScope(), ny, columnSurface, k.surfaceClearance())) {
continue;
}
BlockState current = blocks.get(nx, ny, nz);
if (!canReplaceTarget(current)) {
continue;
}
if (!deposit.canReplace(current)) {
continue;
}
if (!k.replaceBedrock() && current.material().equals(BEDROCK.material())) {
continue;
}
if (shouldDiscardExposed(
k.discardChanceOnAirExposure(), rng.d(), isAdjacentToAir(blocks, nx, ny, nz, this::isAir))) {
continue;
}
if (carvedVoids.get(originX + nx, ny, originZ + nz) == null) {
BlockState ore = clump.blocks().get(j);
BlockState remapped = remapped(nx, ny, nz, ore);
BlockState finalBlock = remapped != null
? remapped
: oreSuiting(current, ore);
blocks.set(nx, ny, nz, finalBlock);
}
}
}
/** Asks the host for the biomes of the column only if a filter or an ore tuning reads them, and only once. */
private Supplier<BiomeSample> biomesAt(int localX, int y, int localZ) {
BiomeSample[] sample = new BiomeSample[1];
return () -> {
if (sample[0] == null) {
sample[0] = terrain.biome(originX + localX, y, originZ + localZ);
}
return sample[0];
};
}
/** {@code ore}, or the variant of it that suits the rock it replaces; the platform knows the variants, so each pair is asked once. */
private BlockState oreSuiting(BlockState rock, BlockState ore) {
return suitedOres.computeIfAbsent(rock, known -> new IdentityHashMap<>())
.computeIfAbsent(ore, known -> registry.oreFor(rock, known));
}
private boolean isAir(BlockState state) {
return airStates.computeIfAbsent(state, known -> registry.hasTrait(known, BlockTrait.AIR));
}
private boolean canReplaceTarget(BlockState state) {
return replaceableStates.computeIfAbsent(state, known -> canReplaceDepositTarget(registry, known));
}
/** The height of the terrain at a column of the chunk, as the stages before the deposits see it. */
private int terrainSurface(int localX, int localZ) {
if (!surfaceKnown) {
for (int x = 0; x < CHUNK_WIDTH; x++) {
for (int z = 0; z < CHUNK_WIDTH; z++) {
surfaceHeights[x * CHUNK_WIDTH + z] = terrain.surfaceHeight(originX + x, originZ + z);
}
}
surfaceKnown = true;
}
return surfaceHeights[localX * CHUNK_WIDTH + localZ];
}
private BlockState remapped(int localX, int localY, int localZ, BlockState ore) {
if (!remapsOres) {
return null;
}
int worldX = originX + localX;
int worldZ = originZ + localZ;
int worldY = absoluteWorldY(minWorldY, localY);
Optional<ResourceId> caveBiome = terrain.biome(worldX, localY, worldZ).caveBiome();
if (caveBiome.isPresent()) {
BlockState match = matchDepositVariant(settings.declaredBy(caveBiome.get(), DepositVariantSettings.class), ore, worldY);
if (match != null) {
return match;
}
}
SettingsStack<DepositVariantSettings> declared = settings.at(DepositVariantSettings.class, worldX, worldZ);
BlockState match = matchDepositVariant(declared.level(Level.REGION), ore, worldY);
if (match != null) {
return match;
}
return matchDepositVariant(declared.dimension(), ore, worldY);
}
private BlockState matchDepositVariant(Optional<DepositVariantSettings> owner, BlockState ore, int y) {
for (DepositVariant declared : owner.map(DepositVariantSettings::variants).orElse(List.of())) {
ResolvedDepositVariant variant = variants.computeIfAbsent(declared, rule -> new ResolvedDepositVariant(rule, registry, log));
if (!variant.appliesAt(y)) {
continue;
}
BlockState swapped = variant.remapOrNull(ore);
if (swapped != null) {
return swapped;
}
}
return null;
}
private double oreFrequencyMultiplier(ResourceId caveBiome) {
return settings.declaredBy(caveBiome, OreFrequencySettings.class).map(OreFrequencySettings::multiplier).orElse(UNCHANGED_ORE_MULTIPLIER);
}
private double oreSizeMultiplier(ResourceId caveBiome) {
return settings.declaredBy(caveBiome, OreSizeSettings.class).map(OreSizeSettings::multiplier).orElse(UNCHANGED_ORE_MULTIPLIER);
}
}
static int depositSurfaceLimit(int surfaceY) {
return depositSurfaceLimit(surfaceY, DEFAULT_SURFACE_CLEARANCE);
}
static int depositSurfaceLimit(int surfaceY, int surfaceClearance) {
return surfaceY - Math.max(0, surfaceClearance);
}
static boolean placementSurfaceAllows(
DepositPlacementScope scope, int candidateY, int surfaceY, int surfaceClearance) {
int clearance = Math.max(0, surfaceClearance);
return switch (scope) {
case ABOVE_TERRAIN -> candidateY > surfaceY + clearance;
case FULL_HEIGHT -> true;
case TERRAIN -> candidateY <= surfaceY - clearance;
};
}
static int absoluteWorldY(int minHeight, int localY) {
return minHeight + localY;
}
static boolean canReplaceDepositTarget(BlockRegistry registry, BlockState state) {
return state != null && !registry.hasTrait(state, BlockTrait.AIR) && !registry.hasTrait(state, BlockTrait.FLUID);
}
static int sampleHeight(
DepositHeightDistribution distribution, RNG rng,
int configuredMinimum, int configuredMaximum, int clippedMaximum) {
int minimum = distribution == DepositHeightDistribution.CLIPPED_UNIFORM
? Math.max(0, configuredMinimum)
: configuredMinimum;
int maximum = distribution == DepositHeightDistribution.CLIPPED_UNIFORM
? Math.min(clippedMaximum, configuredMaximum)
: configuredMaximum;
if (minimum > maximum) {
return Integer.MIN_VALUE;
}
if (minimum == maximum) {
return minimum;
}
if (distribution != DepositHeightDistribution.TRIANGLE) {
return minimum + rng.nextInt(maximum - minimum + 1);
}
int span = maximum - minimum;
int lowerHalf = span / 2;
int upperHalf = span - lowerHalf;
return minimum + rng.nextInt(upperHalf + 1) + rng.nextInt(lowerHalf + 1);
}
static boolean shouldDiscardExposed(double chance, double sample, boolean adjacentToAir) {
return adjacentToAir && chance > 0D && sample < Math.min(1D, chance);
}
static boolean isAdjacentToAir(Hunk<BlockState> data, int x, int y, int z, Predicate<BlockState> isAir) {
return isAirAt(data, x - 1, y, z, isAir)
|| isAirAt(data, x + 1, y, z, isAir)
|| isAirAt(data, x, y - 1, z, isAir)
|| isAirAt(data, x, y + 1, z, isAir)
|| isAirAt(data, x, y, z - 1, isAir)
|| isAirAt(data, x, y, z + 1, isAir);
}
private static boolean isAirAt(Hunk<BlockState> data, int x, int y, int z, Predicate<BlockState> isAir) {
if (x < 0 || x >= data.width()
|| y < 0 || y >= data.height()
|| z < 0 || z >= data.depth()) {
return false;
}
return isAir.test(data.get(x, y, z));
}
static boolean passesOreFrequency(double multiplier, double sample) {
return multiplier >= 1D || sample < Math.max(0D, multiplier);
}
static int clampDepositCenter(int center, int dimension, int limit) {
int minimum = dimension / 2;
int maximum = (int) (limit - dimension / 2D);
return Math.max(minimum, Math.min(center, maximum));
}
}
@@ -0,0 +1,465 @@
/*
* Iris is a World Generator for Minecraft Servers
* Copyright (c) 2026 Arcane Arts (Volmit Software)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package art.arcane.iris.engine.modifier;
import art.arcane.iris.builtin.IrisSeedPurposes;
import art.arcane.iris.builtin.decorant.DecorantSettings;
import art.arcane.iris.builtin.decorant.DecorationPart;
import art.arcane.iris.modules.floating.FloatingBottomPaletteMode;
import art.arcane.iris.builtin.prepare.SlopeClip;
import art.arcane.iris.modules.terrain.BiomeLayers;
import art.arcane.iris.modules.terrain.ColumnSlope;
import art.arcane.iris.modules.terrain.LayerNoise;
import art.arcane.iris.modules.terrain.PaletteExplosion;
import art.arcane.iris.builtin.terrain.PaletteLayer;
import art.arcane.iris.modules.terrain.ResolvedLayer;
import art.arcane.iris.engine.decorator.BiomeDecorators;
import art.arcane.iris.engine.decorator.DecoratedBiome;
import art.arcane.iris.engine.decorator.DecorationScene;
import art.arcane.iris.engine.decorator.FloatingDecorator;
import art.arcane.iris.engine.decorator.IrisSeaSurfaceDecorator;
import art.arcane.iris.engine.object.terrain.floating.FloatingIslandBoundarySampler;
import art.arcane.iris.engine.object.terrain.floating.FloatingIslandSample;
import art.arcane.iris.engine.object.terrain.floating.FloatingWorld;
import art.arcane.iris.engine.object.terrain.floating.ResolvedFloatingChild;
import art.arcane.volmlib.util.collection.KList;
import art.arcane.volmlib.util.math.RNG;
import com.volmit.ModuleLog;
import com.volmit.block.BlockRegistry;
import com.volmit.block.BlockState;
import com.volmit.config.FeatureSettings;
import com.volmit.hunk.Hunk;
import com.volmit.mantle.Mantle;
import com.volmit.resource.ResourceId;
import com.volmit.stage.ChunkStageContext;
import com.volmit.world.BiomeKind;
import com.volmit.world.PackWorld;
import com.volmit.world.TerrainSampler;
import java.util.ArrayList;
import java.util.IdentityHashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
/**
* Fills and decorates the floating islands of the dimension's floating child biomes for {@link FloatingModule}:
* the islands' solids (top layers, bottom palette, sea surface) and, later, the decoration on their tops. One
* per world, holding the islands' random.
*/
final class FloatingIslands {
private static final long ISLAND_RANDOM_SALT = 0x7EB0A73F1DCE514DL;
private static final int BOTTOM_PALETTE_SALT = 0xB0770B;
private static final int LAYER_RANDOM_SALT = 0x7A4E;
private static final int FIRST_LAYER_GENERATOR_SEED = 7235;
private static final int MIN_PALETTE_DEPTH = 4;
private static final int CHUNK_WIDTH = 16;
private static final BlockState BARRIER = new BlockState("minecraft:barrier");
private static final BlockState FALLBACK_SOLID = new BlockState("minecraft:stone");
private static final String DEFAULT_FLUID = "minecraft:water";
private static final Runnable NOOP_DECORATION_MISS = () -> {
};
private final FloatingWorld world;
private final RNG rng;
private final BiomeLayers biomeLayers;
private final ModuleLog log;
FloatingIslands(PackWorld world, ModuleLog log) {
this.world = FloatingWorld.of(world);
this.rng = new RNG(world.seed(IrisSeedPurposes.TERRAIN) ^ ISLAND_RANDOM_SALT);
this.biomeLayers = BiomeLayers.of(world);
this.log = log;
}
/** The islands of {@code world}. */
static FloatingIslands of(PackWorld world, ModuleLog log) {
return world.state(FloatingIslands.class, generating -> new FloatingIslands(generating, log));
}
/** Fills the islands' solids into the chunk of {@code context}. */
void fillSolids(ChunkStageContext context) {
Chunk chunk = new Chunk(context);
FloatingIslandSample.clearChunkMemo();
for (int xf = 0; xf < CHUNK_WIDTH; xf++) {
for (int zf = 0; zf < CHUNK_WIDTH; zf++) {
fillColumn(chunk, xf, zf);
}
}
}
private void fillColumn(Chunk chunk, int xf, int zf) {
int wx = chunk.originX + xf;
int wz = chunk.originZ + zf;
ResourceId parent = chunk.boundarySampler.parent(wx, wz);
if (parent == null || world.declaredBy(parent).isEmpty()) {
return;
}
FloatingIslandSample sample = FloatingIslandSample.sampleMemoized(parent, wx, wz, chunk.height, world, chunk.boundarySampler, log);
if (sample == null) {
return;
}
long colSeed = FloatingIslandSample.columnSeed(world.baseSeed(), wx, wz);
int paletteDepth = Math.max(MIN_PALETTE_DEPTH, sample.solidCount + MIN_PALETTE_DEPTH);
Map<ResolvedFloatingChild, PaletteContext> paletteContexts = new IdentityHashMap<>();
Map<ResolvedFloatingChild, Integer> topDepthByEntry = new IdentityHashMap<>();
int[] bottomDepths = bottomDepths(sample, chunk.height);
for (int k = sample.topIdx; k >= 0; k--) {
if (!sample.solidMask[k]) {
continue;
}
int y = sample.islandBaseY + k;
if (y < 0 || y >= chunk.height) {
continue;
}
ResolvedFloatingChild entry = sample.entryAt(k);
PaletteContext paletteContext = paletteContexts.computeIfAbsent(entry,
ignored -> createPaletteContext(chunk, parent, entry, wx, wz, colSeed, paletteDepth));
int depth = topDepthByEntry.getOrDefault(entry, 0);
int bottomDepth = bottomDepths[k] < 0 ? depth : bottomDepths[k];
BlockState block = selectPaletteBlock(entry, paletteContext.topBlocks(), paletteContext.bottomBlocks(), depth, bottomDepth);
if (block != null) {
chunk.output.set(xf, y, zf, block);
}
topDepthByEntry.put(entry, depth + 1);
}
fillLocalFluid(chunk, sample, xf, zf);
paintSkyBiomes(chunk, parent, wx, wz, sample);
}
private void fillLocalFluid(Chunk chunk, FloatingIslandSample sample, int xf, int zf) {
int localFluidHeight = sample.entry.settings().localFluidHeight().orElse(0);
if (localFluidHeight <= 0) {
return;
}
BlockState fluid = fluidOf(chunk.blocks, sample.entry.settings().fluidBlock());
int fluidCap = Math.min(sample.thickness - 1, localFluidHeight);
for (int k = 1; k <= fluidCap; k++) {
if (sample.solidMask[k]) {
continue;
}
int y = sample.islandBaseY + k;
if (y < 0 || y >= chunk.height) {
continue;
}
if (hasSolidBelow(sample, k)) {
chunk.output.set(xf, y, zf, fluid);
}
}
}
private static BlockState fluidOf(BlockRegistry blocks, String key) {
return blocks.find(key).or(() -> blocks.find(DEFAULT_FLUID)).orElseThrow();
}
private static boolean hasSolidBelow(FloatingIslandSample sample, int k) {
for (int kb = k - 1; kb >= 0; kb--) {
if (sample.solidMask[kb]) {
return true;
}
}
return false;
}
/** Decorates the tops of the islands in the chunk of {@code context}. */
void decorateColumns(ChunkStageContext context) {
Chunk chunk = new Chunk(context);
DecorationScene scene = DecorationScene.of(context);
for (int xf = 0; xf < CHUNK_WIDTH; xf++) {
for (int zf = 0; zf < CHUNK_WIDTH; zf++) {
decorateColumn(chunk, scene, xf, zf);
}
}
}
private void decorateColumn(Chunk chunk, DecorationScene scene, int xf, int zf) {
int wx = chunk.originX + xf;
int wz = chunk.originZ + zf;
ResourceId parent = chunk.boundarySampler.parent(wx, wz);
if (parent == null || world.declaredBy(parent).isEmpty()) {
return;
}
FloatingIslandSample sample = FloatingIslandSample.sampleMemoized(parent, wx, wz, chunk.height, world, chunk.boundarySampler, log);
if (sample == null) {
return;
}
ResolvedFloatingChild entry = sample.entry;
ResourceId target = entry.realBiome(parent);
if (!entry.settings().inheritDecorators() || target == null) {
return;
}
DecoratedBiome decorated = decoratedBiome(chunk.settings, target);
decorateTop(chunk, scene, sample, decorated, xf, zf, wx, wz);
decorateLocalFluid(chunk, scene, sample, decorated, xf, zf, wx, wz);
}
private void decorateTop(Chunk chunk, DecorationScene scene, FloatingIslandSample sample, DecoratedBiome decorated,
int xf, int zf, int wx, int wz) {
int topY = sample.topY();
if (topY + 1 >= chunk.height) {
return;
}
BlockState above = chunk.output.get(xf, topY + 1, zf);
if (above != null && !scene.isAir(above)) {
return;
}
int max = Math.max(1, chunk.height - topY);
try {
RNG colRng = rng.nextParallelRNG((int) FloatingIslandSample.columnSeed(world.baseSeed(), wx, wz));
FloatingDecorator.decorateColumn(scene, decorated, DecorationPart.NONE, xf, zf, wx, wz, topY, max, colRng, NOOP_DECORATION_MISS);
} catch (Throwable e) {
log.error("Failed to decorate the top of a floating island", e);
}
}
private void decorateLocalFluid(Chunk chunk, DecorationScene scene, FloatingIslandSample sample, DecoratedBiome decorated,
int xf, int zf, int wx, int wz) {
int localFluidHeight = sample.entry.settings().localFluidHeight().orElse(0);
if (localFluidHeight <= 0) {
return;
}
int fluidCap = Math.min(sample.thickness - 1, localFluidHeight);
int fluidTopY = -1;
for (int k = 1; k <= fluidCap; k++) {
if (sample.solidMask[k]) {
continue;
}
int y = sample.islandBaseY + k;
if (y < 0 || y >= chunk.height) {
continue;
}
if (hasSolidBelow(sample, k) && y > fluidTopY) {
fluidTopY = y;
}
}
if (fluidTopY <= 0 || fluidTopY + 1 >= chunk.height) {
return;
}
BlockState above = chunk.output.get(xf, fluidTopY + 1, zf);
if (above != null && !scene.isAir(above)) {
return;
}
try {
new IrisSeaSurfaceDecorator(scene).decorate(xf, zf, wx, wx + 1, wx - 1, wz, wz + 1, wz - 1, decorated, fluidTopY, chunk.height);
} catch (Throwable e) {
log.error("Failed to decorate the sea surface of a floating island", e);
}
}
/** The decorators' view of the island's biome, which always decorates as land. */
private static DecoratedBiome decoratedBiome(FeatureSettings settings, ResourceId biome) {
return new DecoratedBiome(BiomeDecorators.biomeKey(biome), settings.declaredBy(biome, DecorantSettings.class).orElse(null), BiomeKind.LAND);
}
private PaletteContext createPaletteContext(Chunk chunk, ResourceId parent, ResolvedFloatingChild entry, int wx, int wz, long colSeed,
int paletteDepth) {
ResourceId target = entry == null ? parent : entry.realBiome(parent);
int entrySeed = entry == null ? 0 : entry.settings().biome().hashCode();
RNG layerRng = rng.nextParallelRNG((int) (colSeed ^ LAYER_RANDOM_SALT ^ entrySeed));
KList<BlockState> topBlocks = target == null ? null : surfaceLayers(chunk, target, wx, wz, layerRng, paletteDepth);
if (topBlocks == null || topBlocks.isEmpty()) {
topBlocks = surfaceLayers(chunk, parent, wx, wz, layerRng, paletteDepth);
}
List<BlockState> bottomBlocks = generateBottomPaletteLayers(chunk, entry, wx, wz, layerRng, paletteDepth);
return new PaletteContext(topBlocks, bottomBlocks);
}
private KList<BlockState> surfaceLayers(Chunk chunk, ResourceId biome, int wx, int wz, RNG layerRng, int paletteDepth) {
return biomeLayers.generateLayers(biomeLayers.biome(biome, chunk.settings), chunk.explosion, wx, wz, layerRng, paletteDepth,
paletteDepth, chunk.slope);
}
private List<BlockState> generateBottomPaletteLayers(Chunk chunk, ResolvedFloatingChild entry, double wx, double wz, RNG random,
int paletteDepth) {
if (entry == null || entry.settings().bottomPaletteMode() != FloatingBottomPaletteMode.CUSTOM || entry.settings().bottomPalette().isEmpty()) {
return null;
}
return generatePaletteLayers(chunk, entry.settings().bottomPalette(), wx, wz, random.nextParallelRNG(BOTTOM_PALETTE_SALT), paletteDepth);
}
private List<BlockState> generatePaletteLayers(Chunk chunk, List<PaletteLayer> layers, double wx, double wz, RNG random, int maxDepth) {
List<BlockState> generated = new ArrayList<>();
if (layers.isEmpty() || maxDepth <= 0) {
return generated;
}
int generatorSeed = FIRST_LAYER_GENERATOR_SEED;
for (int i = 0; i < layers.size(); i++) {
ResolvedLayer layer = biomeLayers.resolve(layers.get(i));
LayerNoise heightGenerator = layer.heightNoise(random.nextParallelRNG((generatorSeed++) * generatorSeed * generatorSeed * generatorSeed));
if (heightGenerator == null) {
continue;
}
double layerDepth = heightGenerator.fit(layer.minHeight(), layer.maxHeight(), wx / layer.zoom(), wz / layer.zoom());
SlopeClip slopeClip = layer.slopeCondition();
if (slopeClip != null && !slopeClip.isDefault() && !slopeClip.isValid(chunk.slope.at(wx, wz))) {
layerDepth = 0;
}
if (layerDepth <= 0) {
continue;
}
for (int j = 0; j < layerDepth; j++) {
if (generated.size() >= maxDepth) {
break;
}
try {
generated.add(layer.get(random.nextParallelRNG(i + j), (wx + j) / layer.zoom(), j, (wz - j) / layer.zoom()));
} catch (Throwable e) {
log.error("Failed to pick a block of a floating island's palette", e);
}
}
if (generated.size() >= maxDepth) {
break;
}
if (chunk.explosion.exploded()) {
for (int j = 0; j < chunk.explosion.size(); j++) {
generated.add(BARRIER);
if (generated.size() >= maxDepth) {
break;
}
}
}
}
return generated;
}
private static int[] bottomDepths(FloatingIslandSample sample, int chunkHeight) {
int[] bottomDepths = new int[sample.solidMask.length];
java.util.Arrays.fill(bottomDepths, -1);
Map<ResolvedFloatingChild, Integer> depthByEntry = new IdentityHashMap<>();
int max = Math.min(sample.topIdx, sample.solidMask.length - 1);
for (int k = 0; k <= max; k++) {
if (!sample.solidMask[k]) {
continue;
}
int y = sample.islandBaseY + k;
if (y < 0 || y >= chunkHeight) {
continue;
}
ResolvedFloatingChild entry = sample.entryAt(k);
int depth = depthByEntry.getOrDefault(entry, 0);
bottomDepths[k] = depth;
depthByEntry.put(entry, depth + 1);
}
return bottomDepths;
}
private static BlockState selectPaletteBlock(ResolvedFloatingChild entry, List<BlockState> topBlocks, List<BlockState> bottomBlocks,
int topDepth, int bottomDepth) {
FloatingBottomPaletteMode mode = entry == null ? FloatingBottomPaletteMode.DEPTH : entry.settings().bottomPaletteMode();
if (mode == FloatingBottomPaletteMode.MIRROR_TOP) {
return paletteBlock(topBlocks, Math.min(topDepth, bottomDepth));
}
if (mode == FloatingBottomPaletteMode.CUSTOM && bottomDepth < topDepth) {
if (bottomBlocks != null && !bottomBlocks.isEmpty()) {
return paletteBlock(bottomBlocks, bottomDepth);
}
return paletteBlock(topBlocks, bottomDepth);
}
return paletteBlock(topBlocks, topDepth);
}
private static BlockState paletteBlock(List<BlockState> blocks, int depth) {
if (blocks == null || blocks.isEmpty()) {
return FALLBACK_SOLID;
}
BlockState block = depth >= 0 && depth < blocks.size() ? blocks.get(depth) : blocks.getLast();
return block == null ? FALLBACK_SOLID : block;
}
/** Paints, for each child the column's island is made of, its biome's sky biome into the child's solid blocks. */
private void paintSkyBiomes(Chunk chunk, ResourceId parent, int wx, int wz, FloatingIslandSample sample) {
try {
Map<ResolvedFloatingChild, List<Integer>> solidYsByEntry = new IdentityHashMap<>();
for (int k = 0; k <= sample.topIdx; k++) {
if (!sample.solidMask[k]) {
continue;
}
int y = sample.islandBaseY + k;
if (y < 0 || y >= chunk.height) {
continue;
}
solidYsByEntry.computeIfAbsent(sample.entryAt(k), ignored -> new ArrayList<>()).add(y);
}
for (Map.Entry<ResolvedFloatingChild, List<Integer>> solid : solidYsByEntry.entrySet()) {
ResolvedFloatingChild entry = solid.getKey();
ResourceId target = entry == null ? parent : entry.realBiome(parent);
if (target == null) {
continue;
}
Optional<ResourceId> skyBiome = chunk.terrain.skyBiome(target, wx, wz);
if (skyBiome.isEmpty()) {
continue;
}
for (int y : solid.getValue()) {
chunk.mantle.setPlatformBiome(wx, y, wz, skyBiome.get());
}
}
} catch (Throwable e) {
log.error("Failed to write the sky biomes of a floating island", e);
}
}
private record PaletteContext(List<BlockState> topBlocks, List<BlockState> bottomBlocks) {
}
/** What one chunk's columns share: its views of the blocks, terrain and settings, and its island fields. */
private final class Chunk {
final int originX;
final int originZ;
final Hunk<BlockState> output;
final int height;
final BlockRegistry blocks;
final FeatureSettings settings;
final PaletteExplosion explosion;
final ColumnSlope slope;
final FloatingIslandBoundarySampler boundarySampler;
final TerrainSampler terrain;
final Mantle mantle;
Chunk(ChunkStageContext context) {
this.originX = context.originX();
this.originZ = context.originZ();
this.output = context.blocks();
this.height = output.height();
this.blocks = context.world().resources().blocks();
this.settings = context.settings();
this.explosion = PaletteExplosion.of(settings, context.centreX(), context.centreZ());
this.terrain = context.terrain();
this.mantle = context.mantle();
this.slope = (x, z) -> terrain.column((int) x, (int) z).slope();
this.boundarySampler = new FloatingIslandBoundarySampler(world::surfaceBiome);
}
}
}
@@ -0,0 +1,80 @@
/*
* Iris is a World Generator for Minecraft Servers
* Copyright (c) 2026 Arcane Arts (Volmit Software)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package art.arcane.iris.engine.modifier;
import art.arcane.iris.builtin.IrisStages;
import art.arcane.iris.modules.floating.FloatingChildSettings;
import art.arcane.iris.modules.floating.MergeFloatingChildrenSettings;
import art.arcane.iris.engine.mantle.components.FloatingObjectPlacing;
import com.volmit.IrisModule;
import com.volmit.ModuleInfo;
import com.volmit.ModuleLog;
import com.volmit.ModuleSetup;
import com.volmit.config.PackSettings;
import com.volmit.stage.ChunkStageContext;
import com.volmit.stage.MantleStageContext;
/**
* Module {@code iris:floating}: the islands of floating child biomes, their objects in the mantle after the
* dimension's other objects, their solids after smoothing and their decoration after the chunk's own. The
* mantle stage's work is done by {@link FloatingObjectPlacing}, whose reach is the pack's largest floating object
* placement. The chunk stages' work is done by {@link FloatingIslands}.
*/
public final class FloatingModule implements IrisModule {
private static final String VERSION = "built-in";
private ModuleLog log;
@Override
public ModuleInfo info() {
return ModuleInfo.of("iris:floating", "Floating islands", VERSION);
}
@Override
public void setup(ModuleSetup setup) {
log = setup.log();
var registry = setup.registry();
registry.registerSettings(FloatingChildSettings.class);
registry.registerSettings(MergeFloatingChildrenSettings.class);
var graph = setup.stages();
graph.define(IrisStages.Floating.OBJECTS).softAfter(IrisStages.Objects.PLACE).reach(this::objectReach)
.run(FloatingModule::objects);
// Ordering only: iris:post ships in the built-ins jar, which a pack may not have.
graph.define(IrisStages.Floating.SOLIDS).softAfter(IrisStages.Post.SMOOTH).run(FloatingModule::solids);
// Ordering only: iris:decorant ships in the built-ins jar, which a pack may not have.
graph.define(IrisStages.Floating.DECORATE).softAfter(IrisStages.Decorant.DECORATE).run(FloatingModule::decorate);
}
private static void objects(MantleStageContext context) {
FloatingObjectPlacing.of(context.world(), context.log()).place(context);
}
private int objectReach(PackSettings settings) {
return FloatingObjectPlacing.reach(settings, log);
}
private static void solids(ChunkStageContext context) {
FloatingIslands.of(context.world(), context.log()).fillSolids(context);
}
private static void decorate(ChunkStageContext context) {
FloatingIslands.of(context.world(), context.log()).decorateColumns(context);
}
}
@@ -0,0 +1,58 @@
/*
* Iris is a World Generator for Minecraft Bukkit Servers
* Copyright (c) 2022 Arcane Arts (Volmit Software)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package art.arcane.iris.engine.modifier;
import com.volmit.resource.ResourceId;
import java.util.HashMap;
import java.util.Map;
final class IrisCarveScratch {
final CarveColumnMask[] columnMasks = new CarveColumnMask[256];
final CarveColumnMask[] boundaryMasks = new CarveColumnMask[256];
final int[] surfaceHeights = new int[256];
final CarveWallBuffer walls = new CarveWallBuffer(512);
final Map<ResourceId, ResourceId> customBiomeCache = new HashMap<>();
int[] upperSurfaceHeights;
boolean customCaveBiomePresent;
IrisCarveScratch() {
for (int index = 0; index < columnMasks.length; index++) {
columnMasks[index] = new CarveColumnMask();
boundaryMasks[index] = new CarveColumnMask();
}
}
int[] getOrCreateUpperSurfaceHeights() {
if (upperSurfaceHeights == null) {
upperSurfaceHeights = new int[256];
}
return upperSurfaceHeights;
}
void reset() {
for (int index = 0; index < columnMasks.length; index++) {
columnMasks[index].clear();
boundaryMasks[index].clear();
}
walls.clear();
customBiomeCache.clear();
customCaveBiomePresent = false;
}
}
@@ -0,0 +1,84 @@
/*
* Iris is a World Generator for Minecraft Servers
* Copyright (c) 2026 Arcane Arts (Volmit Software)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package art.arcane.iris.engine.modifier;
import art.arcane.iris.builtin.IrisStages;
import com.volmit.IrisModule;
import com.volmit.ModuleInfo;
import com.volmit.ModuleSetup;
import com.volmit.block.BlockState;
import com.volmit.hunk.Hunk;
import com.volmit.geometry.BlockBox;
import com.volmit.stage.ChunkStageContext;
import com.volmit.world.TerrainSampler;
/**
* Module {@code iris:matter}: copies the blocks the mantle planned for the chunk, its objects and structures,
* into it (a dimension with {@code useMantle} off plans none). Where an upper dimension sits above, blocks at or
* above where it begins are left out. It orders itself after deposits without requiring them, since deposits run
* only where a level declares some.
*/
public final class MatterModule implements IrisModule {
private static final String VERSION = "built-in";
private static final int CHUNK_WIDTH = 16;
private static final int NO_LIMIT = Integer.MAX_VALUE;
@Override
public ModuleInfo info() {
return ModuleInfo.of("iris:matter", "Mantle blocks", VERSION);
}
@Override
public void setup(ModuleSetup setup) {
setup.stages().define(IrisStages.Matter.INSERT)
.requires(IrisStages.Floating.SOLIDS)
.softAfter(IrisStages.Deposit.ORES)
.run(MatterModule::insert);
}
private static void insert(ChunkStageContext context) {
int originX = context.originX();
int originZ = context.originZ();
Hunk<BlockState> blocks = context.blocks();
int[] limits = upperLimits(context.terrain(), originX, originZ);
BlockBox chunk = new BlockBox(originX, 0, originZ, originX + CHUNK_WIDTH, blocks.height(), originZ + CHUNK_WIDTH);
context.mantle().blocks().visit(chunk, (x, y, z, block) -> {
int localX = x - originX;
int localZ = z - originZ;
if (y < limits[column(localX, localZ)]) {
blocks.set(localX, y, localZ, block);
}
});
}
/** Per column, the height from which the upper dimension takes over, or no limit. */
static int[] upperLimits(TerrainSampler terrain, int originX, int originZ) {
int[] limits = new int[CHUNK_WIDTH * CHUNK_WIDTH];
for (int localX = 0; localX < CHUNK_WIDTH; localX++) {
for (int localZ = 0; localZ < CHUNK_WIDTH; localZ++) {
limits[column(localX, localZ)] = terrain.upperDimensionY(originX + localX, originZ + localZ).orElse(NO_LIMIT);
}
}
return limits;
}
private static int column(int localX, int localZ) {
return localX * CHUNK_WIDTH + localZ;
}
}
@@ -0,0 +1,186 @@
/*
* Iris is a World Generator for Minecraft Servers
* Copyright (c) 2026 Arcane Arts (Volmit Software)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package art.arcane.iris.engine.modifier;
import art.arcane.iris.builtin.IrisStages;
import art.arcane.iris.modules.terrain.HideOresSettings;
import com.volmit.IrisModule;
import com.volmit.ModuleInfo;
import com.volmit.ModuleSetup;
import com.volmit.block.BlockRegistry;
import com.volmit.block.BlockState;
import com.volmit.block.BlockTrait;
import com.volmit.hunk.Hunk;
import com.volmit.resource.ResourceId;
import com.volmit.stage.ChunkStageContext;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.IdentityHashMap;
import java.util.List;
import java.util.Map;
/**
* Module {@code iris:perfection}: turns ores back into the stone around them when the
* dimension hides its ores, then removes decorations whose block below cannot hold them, again until none
* is left, since removing one can strand the one above.
*/
public final class PerfectionModule implements IrisModule {
private static final String VERSION = "built-in";
private static final String HALF = "half";
private static final BlockState AIR = new BlockState("minecraft:air");
private static final Map<ResourceId, BlockState> ORE_BASES = oreBases();
@Override
public ModuleInfo info() {
return ModuleInfo.of("iris:perfection", "Perfection", VERSION);
}
@Override
public void setup(ModuleSetup setup) {
setup.stages().define(IrisStages.Perfection.SURFACE).requires(IrisStages.Floating.DECORATE).run(PerfectionModule::perfect);
}
private static void perfect(ChunkStageContext context) {
Hunk<BlockState> blocks = context.blocks();
if (hidesOres(context)) {
hideOres(blocks, new IdentityHashMap<>());
}
Surfaces surfaces = new Surfaces(blocks, context.world().resources().blocks(), new IdentityHashMap<>());
boolean removed;
do {
removed = surfaces.removeUnsupportedDecorants();
} while (removed);
}
/** The dimension's {@code hideOresForHiddenOre}, which every column of the chunk shares. */
private static boolean hidesOres(ChunkStageContext context) {
return context.settings().at(HideOresSettings.class, context.centreX(), context.centreZ()).dimension()
.map(HideOresSettings::hide).orElse(false);
}
/** {@code hidden} remembers per state instance what it is hidden as, itself for a block that is no ore. */
private static void hideOres(Hunk<BlockState> blocks, Map<BlockState, BlockState> hidden) {
for (int x = 0; x < blocks.width(); x++) {
for (int z = 0; z < blocks.depth(); z++) {
for (int y = blocks.height() - 1; y >= 0; y--) {
BlockState block = blocks.get(x, y, z);
BlockState shown = hidden.computeIfAbsent(block, state -> ORE_BASES.getOrDefault(state.material(), state));
if (shown != block) {
blocks.set(x, y, z, shown);
}
}
}
}
}
/**
* The decorations of one chunk and the ground they stand on. Finding the surfaces asks about every block of the chunk,
* which holds few distinct states, so whether a state is solid is asked once per state instance.
*/
private record Surfaces(Hunk<BlockState> blocks, BlockRegistry registry, Map<BlockState, Boolean> solidStates) {
/** One pass over every column; whether it removed anything. */
boolean removeUnsupportedDecorants() {
boolean removed = false;
for (int x = 0; x < blocks.width(); x++) {
for (int z = 0; z < blocks.depth(); z++) {
for (int surface : surfaces(x, z)) {
removed |= removeIfUnsupported(x, surface, z);
}
}
}
return removed;
}
/** The topmost solid block of a column and each solid block with open space above it below that. */
private List<Integer> surfaces(int x, int z) {
List<Integer> surfaces = new ArrayList<>();
int top = topSolid(x, z);
surfaces.add(top);
boolean inside = true;
for (int y = top; y >= 0; y--) {
boolean solid = isSolid(blocks.get(x, y, z));
if (solid != inside) {
inside = solid;
if (inside) {
surfaces.add(y);
}
}
}
return surfaces;
}
private boolean removeIfUnsupported(int x, int y, int z) {
BlockState tip = blocks.get(x, y, z);
if (!registry.hasTrait(tip, BlockTrait.DECORATION)) {
return false;
}
BlockState below = blockAt(x, y - 1, z);
if (below == null || !registry.canPlaceOn(tip, below)) {
blocks.set(x, y, z, AIR);
return true;
}
if (!below.properties().containsKey(HALF)) {
return false;
}
BlockState belowBelow = blockAt(x, y - 2, z);
if (belowBelow != null && registry.canPlaceOn(below, belowBelow)) {
return false;
}
blocks.set(x, y, z, AIR);
blocks.set(x, y - 1, z, AIR);
return true;
}
private int topSolid(int x, int z) {
for (int y = blocks.height() - 1; y >= 0; y--) {
if (isSolid(blocks.get(x, y, z))) {
return y;
}
}
return 0;
}
private boolean isSolid(BlockState block) {
return solidStates.computeIfAbsent(block, state -> !(registry.hasTrait(state, BlockTrait.AIR) || registry.hasTrait(state, BlockTrait.FLUID)));
}
/** The block at {@code y}, or null below the chunk's bottom. */
private BlockState blockAt(int x, int y, int z) {
return y < 0 ? null : blocks.get(x, y, z);
}
}
private static Map<ResourceId, BlockState> oreBases() {
Map<ResourceId, BlockState> bases = new HashMap<>();
BlockState stone = new BlockState("minecraft:stone");
BlockState deepslate = new BlockState("minecraft:deepslate");
BlockState netherrack = new BlockState("minecraft:netherrack");
BlockState blackstone = new BlockState("minecraft:blackstone");
for (String ore : List.of("coal", "copper", "iron", "gold", "redstone", "lapis", "diamond", "emerald")) {
bases.put(ResourceId.parse("minecraft:" + ore + "_ore"), stone);
bases.put(ResourceId.parse("minecraft:deepslate_" + ore + "_ore"), deepslate);
}
bases.put(ResourceId.parse("minecraft:nether_gold_ore"), netherrack);
bases.put(ResourceId.parse("minecraft:nether_quartz_ore"), netherrack);
bases.put(ResourceId.parse("minecraft:ancient_debris"), netherrack);
bases.put(ResourceId.parse("minecraft:gilded_blackstone"), blackstone);
return bases;
}
}
@@ -0,0 +1,47 @@
/*
* Iris is a World Generator for Minecraft Servers
* Copyright (c) 2026 Arcane Arts (Volmit Software)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package art.arcane.iris.engine.modifier;
import art.arcane.iris.builtin.IrisStages;
import art.arcane.iris.modules.post.PostProcessingSettings;
import art.arcane.iris.modules.post.PostProcessingSlabsSettings;
import art.arcane.iris.modules.post.PostProcessingWallsSettings;
import com.volmit.IrisModule;
import com.volmit.ModuleInfo;
import com.volmit.ModuleSetup;
/** Module {@code iris:post}: smooths the carved surface with {@link SurfaceSmoothing}. */
public final class PostModule implements IrisModule {
private static final String VERSION = "built-in";
@Override
public ModuleInfo info() {
return ModuleInfo.of("iris:post", "Post-processing", VERSION);
}
@Override
public void setup(ModuleSetup setup) {
var registry = setup.registry();
registry.registerSettings(PostProcessingSettings.class);
registry.registerSettings(PostProcessingSlabsSettings.class);
registry.registerSettings(PostProcessingWallsSettings.class);
// Ordering only: iris:carve ships in the built-ins jar, which a pack may not have.
setup.stages().define(IrisStages.Post.SMOOTH).softAfter(IrisStages.Carve.APPLY).run(SurfaceSmoothing::smooth);
}
}
@@ -0,0 +1,402 @@
/*
* Iris is a World Generator for Minecraft Servers
* Copyright (c) 2026 Arcane Arts (Volmit Software)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package art.arcane.iris.engine.modifier;
import art.arcane.iris.modules.deposit.DepositBiomeScope;
import art.arcane.iris.modules.deposit.DepositGenerator;
import art.arcane.iris.modules.deposit.DepositShape;
import art.arcane.volmlib.util.collection.KSet;
import art.arcane.volmlib.util.math.BlockPosition;
import art.arcane.volmlib.util.math.RNG;
import com.volmit.block.BlockRegistry;
import com.volmit.block.BlockState;
import com.volmit.block.BlockTrait;
import com.volmit.resource.ResourceId;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Supplier;
/**
* One {@link DepositGenerator} made ready for one world: its palette resolved to blocks, whether it is an ore deposit, the blocks
* it may replace, and the clump shapes it places, built once per size. What the settings describe stays in the settings;
* everything that needs the pack or the world seed is here.
*/
final class ResolvedDeposit {
private static final long FNV_OFFSET_BASIS = 0xcbf29ce484222325L;
private static final long FNV_PRIME = 0x100000001b3L;
private static final int MAX_CLUMP_DIMENSION = 11;
private static final int MAX_DEPOSIT_SIZE = 8192;
private static final int VARIANT_SEED_STEP = 2349;
private static final int VARIANT_SEED_OFFSET = 3598;
private static final int MAX_SCATTER_MAGNITUDE = 7;
private static final String MINECRAFT_NAMESPACE = "minecraft:";
private final DepositGenerator generator;
private final long depositSeed;
private final List<BlockState> palette;
private final boolean ore;
private final Set<ResourceId> replaceableMaterials;
private final Map<ClumpSizes, List<DepositClump>> clumps = new ConcurrentHashMap<>();
/** @param registry the pack's blocks, which resolve the generator's palette and the blocks it may replace */
ResolvedDeposit(DepositGenerator generator, long depositSeed, BlockRegistry registry) {
this.generator = generator;
this.depositSeed = depositSeed;
this.palette = generator.palette().stream().map(registry::resolve).toList();
this.ore = palette.stream().anyMatch(block -> registry.hasTrait(block, BlockTrait.ORE));
this.replaceableMaterials = replaceableMaterials(registry, generator.replaceableBlocks());
}
DepositGenerator generator() {
return generator;
}
/** Whether any block of the palette is an ore: ore deposits follow the cave biome's ore tuning. */
boolean isOre() {
return ore;
}
/** Whether the deposit may replace {@code state}: any block when it names none, otherwise only the named ones. */
boolean canReplace(BlockState state) {
return generator.replaceableBlocks().isEmpty() || replaceableMaterials.contains(state.material());
}
/**
* Whether the biome the generator's scope picks passes its include and exclude filters. The biomes are asked for only when
* the generator has a filter, and a biome that is none (a dimension without cave biomes) matches no key.
*/
boolean matchesBiome(Supplier<BiomeIdentity> surfaceBiome, Supplier<BiomeIdentity> caveBiome) {
if (generator.includedBiomes().isEmpty() && generator.excludedBiomes().isEmpty()) {
return true;
}
BiomeIdentity selected = (generator.biomeScope() == DepositBiomeScope.SURFACE ? surfaceBiome : caveBiome).get();
if (!generator.includedBiomes().isEmpty() && !matchesAnyBiome(selected, generator.includedBiomes())) {
return false;
}
return generator.excludedBiomes().isEmpty() || !matchesAnyBiome(selected, generator.excludedBiomes());
}
/** One clump to place, picked with {@code rng}. */
DepositClump clump(RNG rng) {
return clump(rng, generator.minSize(), generator.maxSize(), 0L);
}
/** One clump to place with every size scaled by {@code sizeMultiplier}, as a biome's ore size tuning asks. */
DepositClump clump(RNG rng, double sizeMultiplier) {
if (sizeMultiplier == 1D) {
return clump(rng);
}
int minSize = scaledDepositSize(generator.minSize(), sizeMultiplier);
int maxSize = scaledDepositSize(generator.maxSize(), sizeMultiplier);
long sizeSeed = ((long) minSize << 32) ^ (maxSize & 0xffffffffL);
return clump(rng, minSize, maxSize, sizeSeed);
}
private DepositClump clump(RNG rng, int minSize, int maxSize, long sizeSeed) {
if (generator.shape() != DepositShape.IRIS) {
return configuredClump(rng, minSize, maxSize);
}
List<DepositClump> variants = clumps.computeIfAbsent(new ClumpSizes(minSize, maxSize), sizes -> {
RNG variantRng = new RNG(depositSeed + stableClumpSalt() + sizeSeed);
List<DepositClump> built = new ArrayList<>();
for (int i = 0; i < generator.varience(); i++) {
built.add(irisClump(variantRng.nextParallelRNG(VARIANT_SEED_STEP * i + VARIANT_SEED_OFFSET), sizes.minSize(), sizes.maxSize()));
}
return List.copyOf(built);
});
return variants.get(rng.i(0, variants.size()));
}
static int scaledDepositSize(int size, double multiplier) {
return Math.max(0, Math.min(MAX_DEPOSIT_SIZE, (int) Math.round(size * multiplier)));
}
/** A hash of everything the generator describes and its resolved palette, so equal generators share clump shapes. */
long stableClumpSalt() {
long hash = FNV_OFFSET_BASIS;
hash = mix(hash, generator.minHeight());
hash = mix(hash, generator.maxHeight());
hash = mixEnum(hash, generator.heightDistribution());
hash = mixEnum(hash, generator.placementScope());
hash = mix(hash, generator.surfaceClearance());
hash = mix(hash, generator.minSize());
hash = mix(hash, generator.maxSize());
hash = mixEnum(hash, generator.shape());
hash = mix(hash, generator.maxPerChunk());
hash = mix(hash, generator.minPerChunk());
hash = mix(hash, Double.doubleToLongBits(generator.spawnChance()));
hash = mix(hash, Double.doubleToLongBits(generator.perClumpSpawnChance()));
hash = mix(hash, Double.doubleToLongBits(generator.discardChanceOnAirExposure()));
hash = mix(hash, palette.size());
for (BlockState block : palette) {
hash = mixString(hash, block == null ? null : block.key());
}
hash = mix(hash, generator.varience());
hash = mixStrings(hash, generator.replaceableBlocks());
hash = mixEnum(hash, generator.biomeScope());
hash = mixStrings(hash, generator.includedBiomes());
hash = mixStrings(hash, generator.excludedBiomes());
return mix(hash, generator.replaceBedrock() ? 1L : 0L);
}
private static long mix(long hash, long value) {
return (hash ^ value) * FNV_PRIME;
}
private static long mixEnum(long hash, Enum<?> value) {
return mixString(hash, value == null ? null : value.name());
}
private static long mixString(long hash, String value) {
if (value == null) {
return mix(hash, -1L);
}
long mixed = mix(hash, value.length());
for (int i = 0; i < value.length(); i++) {
mixed = mix(mixed, value.charAt(i));
}
return mixed;
}
private static long mixStrings(long hash, List<String> values) {
long mixed = mix(hash, values.size());
for (String value : values) {
mixed = mixString(mixed, value);
}
return mixed;
}
private DepositClump configuredClump(RNG rng, int minSize, int maxSize) {
int size = rng.i(minSize, maxSize + 1);
return switch (generator.shape()) {
case VANILLA_ELLIPSOID -> vanillaEllipsoid(rng, size);
case VANILLA_SCATTERED -> vanillaScattered(rng, size);
case IRIS -> irisClump(rng, minSize, maxSize);
};
}
/** Minecraft's ordinary ore vein: a chain of overlapping ellipsoids whose reach grows with {@code size}. */
DepositClump vanillaEllipsoid(RNG rng, int size) {
if (size <= 0) {
return new DepositClump(1, 1, 1);
}
float angle = rng.nextFloat() * (float) Math.PI;
float reach = size / 8F;
double startX = Math.sin(angle) * reach;
double endX = -Math.sin(angle) * reach;
double startZ = Math.cos(angle) * reach;
double endZ = -Math.cos(angle) * reach;
double startY = rng.nextInt(3) - 2;
double endY = rng.nextInt(3) - 2;
double[] nodes = new double[size * 4];
for (int i = 0; i < size; i++) {
float progress = (float) i / size;
double radiusNoise = rng.nextDouble() * size / 16D;
nodes[i * 4] = startX + (endX - startX) * progress;
nodes[i * 4 + 1] = startY + (endY - startY) * progress;
nodes[i * 4 + 2] = startZ + (endZ - startZ) * progress;
nodes[i * 4 + 3] = ((Math.sin(Math.PI * progress) + 1D) * radiusNoise + 1D) / 2D;
}
for (int i = 0; i < size - 1; i++) {
if (nodes[i * 4 + 3] <= 0D) {
continue;
}
for (int j = i + 1; j < size; j++) {
if (nodes[j * 4 + 3] <= 0D) {
continue;
}
double dx = nodes[i * 4] - nodes[j * 4];
double dy = nodes[i * 4 + 1] - nodes[j * 4 + 1];
double dz = nodes[i * 4 + 2] - nodes[j * 4 + 2];
double dr = nodes[i * 4 + 3] - nodes[j * 4 + 3];
if (dr * dr <= dx * dx + dy * dy + dz * dz) {
continue;
}
if (dr > 0D) {
nodes[j * 4 + 3] = -1D;
} else {
nodes[i * 4 + 3] = -1D;
}
}
}
KSet<BlockPosition> cells = new KSet<>();
for (int i = 0; i < size; i++) {
double radius = nodes[i * 4 + 3];
if (radius < 0D) {
continue;
}
double centerX = nodes[i * 4];
double centerY = nodes[i * 4 + 1];
double centerZ = nodes[i * 4 + 2];
int minX = (int) Math.floor(centerX - radius);
int maxX = Math.max((int) Math.floor(centerX + radius), minX);
int minY = (int) Math.floor(centerY - radius);
int maxY = Math.max((int) Math.floor(centerY + radius), minY);
int minZ = (int) Math.floor(centerZ - radius);
int maxZ = Math.max((int) Math.floor(centerZ + radius), minZ);
for (int x = minX; x <= maxX; x++) {
double nx = (x + 0.5D - centerX) / radius;
if (nx * nx >= 1D) {
continue;
}
for (int y = minY; y <= maxY; y++) {
double ny = (y + 0.5D - centerY) / radius;
if (nx * nx + ny * ny >= 1D) {
continue;
}
for (int z = minZ; z <= maxZ; z++) {
double nz = (z + 0.5D - centerZ) / radius;
if (nx * nx + ny * ny + nz * nz < 1D) {
cells.add(new BlockPosition(x, y, z));
}
}
}
}
}
return clumpFromCells(cells, rng);
}
/** Minecraft's scattered ore: up to {@code size} candidate offsets, the later ones further from the centre. */
DepositClump vanillaScattered(RNG rng, int size) {
KSet<BlockPosition> cells = new KSet<>();
int candidates = rng.nextInt(Math.max(0, size) + 1);
for (int i = 0; i < candidates; i++) {
int magnitude = Math.min(i, MAX_SCATTER_MAGNITUDE);
cells.add(new BlockPosition(
Math.round((rng.nextFloat() - rng.nextFloat()) * magnitude),
Math.round((rng.nextFloat() - rng.nextFloat()) * magnitude),
Math.round((rng.nextFloat() - rng.nextFloat()) * magnitude)));
}
return clumpFromCells(cells, rng);
}
private DepositClump clumpFromCells(KSet<BlockPosition> cells, RNG rng) {
if (cells.isEmpty()) {
return new DepositClump(1, 1, 1);
}
int minX = Integer.MAX_VALUE;
int minY = Integer.MAX_VALUE;
int minZ = Integer.MAX_VALUE;
int maxX = Integer.MIN_VALUE;
int maxY = Integer.MIN_VALUE;
int maxZ = Integer.MIN_VALUE;
for (BlockPosition cell : cells) {
minX = Math.min(minX, cell.getX());
minY = Math.min(minY, cell.getY());
minZ = Math.min(minZ, cell.getZ());
maxX = Math.max(maxX, cell.getX());
maxY = Math.max(maxY, cell.getY());
maxZ = Math.max(maxZ, cell.getZ());
}
int extentX = Math.max(Math.abs(minX), Math.abs(maxX));
int extentY = Math.max(Math.abs(minY), Math.abs(maxY));
int extentZ = Math.max(Math.abs(minZ), Math.abs(maxZ));
DepositClump clump = new DepositClump(extentX * 2 + 1, extentY * 2 + 1, extentZ * 2 + 1);
for (BlockPosition cell : cells) {
clump.setFromCorner(cell.getX() + extentX, cell.getY() + extentY, cell.getZ() + extentZ, nextBlock(rng));
}
return clump;
}
/** The traditional Iris clump: a cube just large enough for the block count, filled at random cells. */
private DepositClump irisClump(RNG rng, int minSize, int maxSize) {
int remaining = rng.i(minSize, maxSize + 1);
if (remaining == 1) {
DepositClump single = new DepositClump(1, 1, 1);
single.setCentre(nextBlock(rng));
return single;
}
int dimension = Math.min(MAX_CLUMP_DIMENSION, (int) Math.ceil(Math.cbrt(remaining)));
DepositClump clump = new DepositClump(dimension, dimension, dimension);
if (remaining >= dimension * dimension * dimension) {
fillCube(clump, dimension, rng);
return clump;
}
KSet<BlockPosition> filled = new KSet<>();
while (remaining > 0) {
BlockPosition cell = new BlockPosition(rng.i(0, dimension), rng.i(0, dimension), rng.i(0, dimension));
if (!filled.add(cell)) {
continue;
}
remaining--;
clump.setFromCorner(cell.getX(), cell.getY(), cell.getZ(), nextBlock(rng));
}
return clump;
}
private void fillCube(DepositClump clump, int dimension, RNG rng) {
for (int z = 0; z < dimension; z++) {
for (int y = 0; y < dimension; y++) {
for (int x = 0; x < dimension; x++) {
clump.setFromCorner(x, y, z, nextBlock(rng));
}
}
}
}
private BlockState nextBlock(RNG rng) {
return palette.get(rng.i(0, palette.size()));
}
/** The materials of the blocks the pack names that this platform knows; a block it does not know replaces nothing. */
private static Set<ResourceId> replaceableMaterials(BlockRegistry registry, List<String> keys) {
Set<ResourceId> materials = new HashSet<>();
for (String key : keys) {
registry.find(key).ifPresent(block -> materials.add(block.material()));
}
return materials;
}
private static boolean matchesAnyBiome(BiomeIdentity biome, List<String> configuredBiomes) {
if (biome == null) {
return false;
}
for (String configured : configuredBiomes) {
String namespaced = configured.contains(":") ? configured : MINECRAFT_NAMESPACE + configured;
if (configured.equals(biome.key())
|| namespaced.equals(biome.platformBiome())
|| namespaced.equals(biome.vanillaBiome())) {
return true;
}
}
return false;
}
/** The sizes one set of clump variants is built for: the generator's own, or scaled by a biome's ore tuning. */
record ClumpSizes(int minSize, int maxSize) {
}
/** What a deposit's biome filter compares: the pack key of a biome, the platform biome it is written as and the one vanilla sees. */
record BiomeIdentity(String key, String platformBiome, String vanillaBiome) {
}
}
@@ -0,0 +1,80 @@
/*
* Iris is a World Generator for Minecraft Servers
* Copyright (c) 2026 Arcane Arts (Volmit Software)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package art.arcane.iris.engine.modifier;
import art.arcane.iris.modules.deposit.DepositVariant;
import art.arcane.volmlib.util.cache.AtomicCache;
import com.volmit.ModuleLog;
import com.volmit.block.BlockRegistry;
import com.volmit.block.BlockState;
import com.volmit.resource.ResourceId;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
/**
* One {@link DepositVariant} made ready: its source and replacement block ids resolved to the platform's blocks, built once on
* first use. A rule whose source or replacement the platform does not know remaps nothing.
*/
final class ResolvedDepositVariant {
private final DepositVariant settings;
private final BlockRegistry registry;
private final ModuleLog log;
private final AtomicCache<Map<ResourceId, BlockState>> remapped = new AtomicCache<>();
ResolvedDepositVariant(DepositVariant settings, BlockRegistry registry, ModuleLog log) {
this.settings = settings;
this.registry = registry;
this.log = log;
}
boolean appliesAt(int worldY) {
return worldY >= settings.minHeight() && worldY <= settings.maxHeight();
}
/** The block {@code ore} is rewritten to, or null when the rule does not remap its material. */
BlockState remapOrNull(BlockState ore) {
if (ore == null || settings.remap().isEmpty()) {
return null;
}
return remapped.aquire(this::resolveRemap).get(ore.material());
}
private Map<ResourceId, BlockState> resolveRemap() {
Map<ResourceId, BlockState> resolved = new HashMap<>();
for (Map.Entry<String, String> entry : settings.remap().entrySet()) {
Optional<BlockState> source = known(entry.getKey(), false);
Optional<BlockState> target = known(entry.getValue(), true);
if (source.isEmpty() || target.isEmpty()) {
continue;
}
resolved.put(source.get().material(), target.get());
}
return resolved;
}
/** The block the platform has under {@code key}; a replacement it lacks is reported once. */
private Optional<BlockState> known(String key, boolean reportMissing) {
Optional<BlockState> block = registry.find(key);
if (block.isEmpty() && reportMissing) {
log.warnOnce("deposit-variant-block:" + key, "Deposit variant replaces ores with " + key + ", which this server does not have");
}
return block;
}
}
Loaded 100 of 391 files, more files were not shown because too many files have changed in this diff. Show more