Baseline IrisModule before the IrisApi port

This commit is contained in:
piexel committed 2026-10-06 13:46:55 +02:00
commit 05ab5ba0cf
397 files changed
+56200

No files matched your search

@@ -0,0 +1,115 @@
/*
* 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.actuator;
import art.arcane.iris.engine.object.world.biome.custom.IrisBiomeCustom;
import art.arcane.iris.engine.framework.Engine;
import art.arcane.iris.engine.framework.EngineAssignedActuator;
import art.arcane.iris.engine.object.world.biome.IrisBiome;
import art.arcane.iris.util.project.context.ChunkContext;
import art.arcane.iris.util.project.context.ChunkedDataCache;
import art.arcane.volmlib.util.collection.KMap;
import art.arcane.volmlib.util.documentation.BlockCoordinates;
import art.arcane.iris.util.project.hunk.Hunk;
import art.arcane.volmlib.util.mantle.runtime.Mantle;
import art.arcane.volmlib.util.math.RNG;
import art.arcane.volmlib.util.matter.Matter;
import art.arcane.volmlib.util.matter.MatterBiomeInject;
import art.arcane.volmlib.util.matter.slices.BiomeInjectMatter;
import art.arcane.volmlib.util.scheduling.ChronoLatch;
import art.arcane.volmlib.util.scheduling.PrecisionStopwatch;
import art.arcane.iris.spi.IrisPlatform;
import art.arcane.iris.spi.IrisPlatforms;
import art.arcane.iris.spi.PlatformBiome;
public class IrisBiomeActuator extends EngineAssignedActuator<PlatformBiome> {
private final RNG rng;
private final ChronoLatch cl = new ChronoLatch(5000);
private final KMap<String, ResolvedBiome> resolvedBiomes = new KMap<>();
public IrisBiomeActuator(Engine engine) {
super(engine, "Biome");
rng = new RNG(engine.getSeedManager().getBiome());
}
@BlockCoordinates
@Override
public void onActuate(int x, int z, Hunk<PlatformBiome> h, boolean multicore, ChunkContext context) {
// No catch here: a partial biome write must fail the chunk (EngineAssignedActuator
// rethrows), or the chunk is flagged REAL with default plains columns forever.
PrecisionStopwatch p = PrecisionStopwatch.start();
int width = h.getWidth();
int depth = h.getDepth();
int height = h.getHeight();
Engine engine = getEngine();
Mantle<Matter> mantle = engine.getMantle().getMantle();
ChunkedDataCache<IrisBiome> biomeCache = context.getBiome();
for (int xf = 0; xf < width; xf++) {
IrisBiome ib;
for (int zf = 0; zf < depth; zf++) {
ib = biomeCache.get(xf, zf);
String key;
if (ib.isCustom()) {
IrisBiomeCustom custom = ib.getCustomBiome(rng, engine, x + xf, 0, z + zf);
key = getDimension().getLoadKey() + ":" + custom.getId();
} else {
key = ib.getSkyBiomeKey(rng, engine, x + xf, 0, z + zf);
}
ResolvedBiome resolved = resolve(key);
PlatformBiome biome = resolved.biome();
if (biome != null) {
h.set(xf, 0, zf, xf, height - 1, zf, biome);
}
mantle.set(x + xf, 0, z + zf, resolved.matter());
}
}
engine.getMetrics().getBiome().put(p.getMilliseconds());
}
/**
* The registry lookup and the biome id only depend on the scatter resolved key, so cache the pair
* instead of paying two string keyed lookups per column. Unresolved biomes are never cached, so a
* biome registered later still resolves.
*/
private ResolvedBiome resolve(String key) {
ResolvedBiome cached = key == null ? null : resolvedBiomes.get(key);
if (cached != null) {
return cached;
}
IrisPlatform platform = IrisPlatforms.get();
PlatformBiome biome = platform.registries().biome(key);
ResolvedBiome resolved = new ResolvedBiome(biome, BiomeInjectMatter.get(platform.biomeWriter().biomeIdFor(key)));
if (key != null && biome != null) {
resolvedBiomes.put(key, resolved);
}
return resolved;
}
private record ResolvedBiome(PlatformBiome biome, MatterBiomeInject matter) {
}
}
@@ -0,0 +1,143 @@
/*
* 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.actuator;
import art.arcane.iris.engine.decorator.IrisCeilingDecorator;
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 art.arcane.iris.engine.framework.Engine;
import art.arcane.iris.engine.framework.EngineAssignedActuator;
import art.arcane.iris.engine.framework.EngineDecorator;
import art.arcane.iris.engine.object.world.biome.IrisBiome;
import art.arcane.iris.util.common.data.B;
import art.arcane.iris.util.project.context.ChunkContext;
import art.arcane.volmlib.util.documentation.BlockCoordinates;
import art.arcane.iris.util.project.hunk.Hunk;
import art.arcane.volmlib.util.math.RNG;
import art.arcane.volmlib.util.scheduling.PrecisionStopwatch;
import art.arcane.iris.spi.PlatformBlockState;
import lombok.Getter;
import java.util.function.Predicate;
public class IrisDecorantActuator extends EngineAssignedActuator<PlatformBlockState> {
private static final Predicate<PlatformBlockState> PREDICATE_SOLID = (s) -> s != null && !B.isAirOrFluid(s);
private final RNG rng;
@Getter
private final IrisSurfaceDecorator surfaceDecorator;
@Getter
private final IrisCeilingDecorator ceilingDecorator;
@Getter
private final EngineDecorator seaSurfaceDecorator;
@Getter
private final EngineDecorator seaFloorDecorator;
@Getter
private final EngineDecorator shoreLineDecorator;
private final boolean shouldRay;
public IrisDecorantActuator(Engine engine) {
super(engine, "Decorant");
shouldRay = shouldRayDecorate();
this.rng = new RNG(engine.getSeedManager().getDecorator());
surfaceDecorator = new IrisSurfaceDecorator(getEngine());
ceilingDecorator = new IrisCeilingDecorator(getEngine());
seaSurfaceDecorator = new IrisSeaSurfaceDecorator(getEngine());
shoreLineDecorator = new IrisShoreLineDecorator(getEngine());
seaFloorDecorator = new IrisSeaFloorDecorator(getEngine());
}
@BlockCoordinates
@Override
public void onActuate(int x, int z, Hunk<PlatformBlockState> output, boolean multicore, ChunkContext context) {
if (!getEngine().getDimension().isDecorate()) {
return;
}
PrecisionStopwatch p = PrecisionStopwatch.start();
for (int i = 0; i < output.getWidth(); i++) {
int height;
int realX = Math.round(x + i);
int realZ;
IrisBiome biome, cave;
for (int j = 0; j < output.getDepth(); j++) {
boolean solid;
int emptyFor = 0;
int lastSolid = 0;
realZ = Math.round(z + j);
height = context.getRoundedHeight(i, j);
biome = context.getBiome().get(i, j);
cave = shouldRay ? context.getCave().get(i, j) : null;
if (biome.getDecorators().isEmpty() && (cave == null || cave.getDecorators().isEmpty())) {
continue;
}
if (height < getDimension().getFluidHeight() && PREDICATE_SOLID.test(output.get(i, height, j))
&& height + 1 < output.getHeight() && B.isWater(output.get(i, height + 1, j))) {
getSeaSurfaceDecorator().decorate(i, j,
realX, Math.round(i + 1), Math.round(x + i - 1),
realZ, Math.round(z + j + 1), Math.round(z + j - 1),
output, biome, getDimension().getFluidHeight(), getEngine().getHeight());
getSeaFloorDecorator().decorate(i, j,
realX, realZ, output, biome, height + 1,
getDimension().getFluidHeight() + 1);
}
if (height == getDimension().getFluidHeight()) {
getShoreLineDecorator().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),
output, biome, height, getEngine().getHeight());
}
if (height >= 0 && height < output.getHeight()) {
getSurfaceDecorator().decorate(i, j, realX, realZ, output, biome, height, getEngine().getHeight() - height);
}
if (cave != null && cave.getDecorators().isNotEmpty()) {
for (int k = Math.min(height, output.getHeight() - 1); k > 0; k--) {
solid = PREDICATE_SOLID.test(output.get(i, k, j));
if (solid) {
if (emptyFor > 0) {
getSurfaceDecorator().decorate(i, j, realX, realZ, output, cave, k, lastSolid);
getCeilingDecorator().decorate(i, j, realX, realZ, output, cave, lastSolid - 1, emptyFor);
emptyFor = 0;
}
lastSolid = k;
} else {
emptyFor++;
}
}
}
}
}
getEngine().getMetrics().getDecoration().put(p.getMilliseconds());
}
private boolean shouldRayDecorate() {
return false; // TODO CAVES
}
}
@@ -0,0 +1,261 @@
/*
* 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.actuator;
import art.arcane.iris.engine.framework.Engine;
import art.arcane.iris.engine.framework.EngineAssignedActuator;
import art.arcane.iris.core.loader.IrisData;
import art.arcane.iris.engine.IrisComplex;
import art.arcane.iris.engine.UpperDimensionContext;
import art.arcane.iris.engine.object.world.biome.IrisBiome;
import art.arcane.iris.engine.object.world.dimension.IrisDimension;
import art.arcane.iris.engine.object.terrain.deposit.IrisOreGenerator;
import art.arcane.iris.engine.object.terrain.deposit.IrisOreGeneratorBounds;
import art.arcane.iris.engine.object.world.region.IrisRegion;
import art.arcane.volmlib.util.collection.KList;
import art.arcane.iris.util.project.context.ChunkedDataCache;
import art.arcane.iris.util.project.context.ChunkContext;
import art.arcane.volmlib.util.documentation.BlockCoordinates;
import art.arcane.iris.util.project.hunk.Hunk;
import art.arcane.volmlib.util.math.RNG;
import art.arcane.volmlib.util.scheduling.PrecisionStopwatch;
import art.arcane.iris.spi.PlatformBlockState;
import art.arcane.iris.util.common.data.B;
import lombok.Getter;
public class IrisTerrainNormalActuator extends EngineAssignedActuator<PlatformBlockState> {
private static final PlatformBlockState AIR = B.getState("AIR");
private static final PlatformBlockState BEDROCK = B.getState("BEDROCK");
private static final PlatformBlockState LAVA = B.getState("LAVA");
private static final PlatformBlockState GLASS = B.getState("GLASS");
private static final PlatformBlockState CAVE_AIR = B.getState("CAVE_AIR");
@Getter
private final RNG rng;
@Getter
private int lastBedrock = -1;
public IrisTerrainNormalActuator(Engine engine) {
super(engine, "Terrain");
rng = new RNG(engine.getSeedManager().getTerrain());
}
@BlockCoordinates
@Override
public void onActuate(int x, int z, Hunk<PlatformBlockState> h, boolean multicore, ChunkContext context) {
PrecisionStopwatch p = PrecisionStopwatch.start();
for (int xf = 0; xf < h.getWidth(); xf++) {
terrainSliver(x, z, xf, h, context);
}
getEngine().getMetrics().getTerrain().put(p.getMilliseconds());
}
/**
* This is calling 1/16th of a chunk x/z slice. It is a plane from sky to bedrock 1 thick in the x direction.
*
* @param x the chunk x in blocks
* @param z the chunk z in blocks
* @param xf the current x slice
* @param h the blockdata
*/
@BlockCoordinates
public void terrainSliver(int x, int z, int xf, Hunk<PlatformBlockState> h, ChunkContext context) {
terrainSliverOptimized(x, z, xf, h, context);
}
@BlockCoordinates
private void terrainSliverOptimized(int x, int z, int xf, Hunk<PlatformBlockState> h, ChunkContext context) {
int chunkHeight = h.getHeight();
int chunkDepth = h.getDepth();
IrisDimension dimension = getDimension();
IrisData data = getData();
IrisComplex complex = getComplex();
RNG localRng = rng;
int fluidHeight = dimension.getFluidHeight();
int clampedFluidHeight = Math.min(chunkHeight, fluidHeight);
boolean bedrockEnabled = dimension.isBedrock();
boolean hideOres = dimension.isHideOresForHiddenOre();
ChunkedDataCache<IrisBiome> biomeCache = context.getBiome();
ChunkedDataCache<IrisRegion> regionCache = context.getRegion();
ChunkedDataCache<PlatformBlockState> fluidCache = context.getFluid();
ChunkedDataCache<PlatformBlockState> rockCache = context.getRock();
int realX = xf + x;
UpperDimensionContext upperContext = getEngine().getUpperContext();
// Dimension-level ore lookups are chunk-invariant; resolving them per column paid
// four accessor chains times 256 per chunk for constants.
KList<IrisOreGenerator> dimensionSurfaceOres = hideOres ? null : dimension.getSurfaceOreGenerators();
KList<IrisOreGenerator> dimensionUndergroundOres = hideOres ? null : dimension.getUndergroundOreGenerators();
IrisOreGeneratorBounds dimensionSurfaceOreBounds = hideOres ? IrisOreGeneratorBounds.EMPTY : dimension.getSurfaceOreGeneratorBounds();
IrisOreGeneratorBounds dimensionUndergroundOreBounds = hideOres ? IrisOreGeneratorBounds.EMPTY : dimension.getUndergroundOreGeneratorBounds();
for (int zf = 0; zf < chunkDepth; zf++) {
int realZ = zf + z;
IrisBiome biome = biomeCache.get(xf, zf);
IrisRegion region = regionCache.get(xf, zf);
int he = Math.min(chunkHeight, context.getRoundedHeight(xf, zf));
int hf = Math.max(clampedFluidHeight, he);
if (hf < 0) {
continue;
}
int topY = Math.min(hf, chunkHeight - 1);
PlatformBlockState fluid = fluidCache.get(xf, zf);
PlatformBlockState rock = rockCache.get(xf, zf);
PlatformBlockState mappedSurfaceBlock = complex.getImageMapRuntime().sampleSurfaceBlock(realX, realZ);
KList<IrisOreGenerator> biomeSurfaceOres = hideOres ? null : biome.getSurfaceOreGenerators();
KList<IrisOreGenerator> regionSurfaceOres = hideOres ? null : region.getSurfaceOreGenerators();
KList<IrisOreGenerator> biomeUndergroundOres = hideOres ? null : biome.getUndergroundOreGenerators();
KList<IrisOreGenerator> regionUndergroundOres = hideOres ? null : region.getUndergroundOreGenerators();
IrisOreGeneratorBounds biomeSurfaceOreBounds = hideOres ? IrisOreGeneratorBounds.EMPTY : biome.getSurfaceOreGeneratorBounds();
IrisOreGeneratorBounds regionSurfaceOreBounds = hideOres ? IrisOreGeneratorBounds.EMPTY : region.getSurfaceOreGeneratorBounds();
IrisOreGeneratorBounds biomeUndergroundOreBounds = hideOres ? IrisOreGeneratorBounds.EMPTY : biome.getUndergroundOreGeneratorBounds();
IrisOreGeneratorBounds regionUndergroundOreBounds = hideOres ? IrisOreGeneratorBounds.EMPTY : region.getUndergroundOreGeneratorBounds();
boolean hasSurfaceOres = biomeSurfaceOreBounds.hasOres() || regionSurfaceOreBounds.hasOres() || dimensionSurfaceOreBounds.hasOres();
boolean hasUndergroundOres = biomeUndergroundOreBounds.hasOres() || regionUndergroundOreBounds.hasOres() || dimensionUndergroundOreBounds.hasOres();
KList<PlatformBlockState> blocks = null;
KList<PlatformBlockState> fblocks = null;
for (int i = topY; i >= 0; i--) {
if (i == 0 && bedrockEnabled) {
h.setRaw(xf, i, zf, BEDROCK);
lastBedrock = i;
continue;
}
PlatformBlockState ore = null;
if (hasSurfaceOres) {
if (biomeSurfaceOreBounds.contains(i)) {
ore = generateOres(biomeSurfaceOres, realX, i, realZ, localRng, data);
}
if (ore == null && regionSurfaceOreBounds.contains(i)) {
ore = generateOres(regionSurfaceOres, realX, i, realZ, localRng, data);
}
if (ore == null && dimensionSurfaceOreBounds.contains(i)) {
ore = generateOres(dimensionSurfaceOres, realX, i, realZ, localRng, data);
}
}
if (ore != null) {
h.setRaw(xf, i, zf, ore);
continue;
}
if (i > he && i <= hf) {
int fdepth = hf - i;
if (fblocks == null) {
fblocks = biome.generateSeaLayers(realX, realZ, localRng, hf - he, data);
}
if (fblocks.hasIndex(fdepth)) {
h.setRaw(xf, i, zf, fblocks.get(fdepth));
} else {
h.setRaw(xf, i, zf, fluid);
}
continue;
}
if (i <= he) {
int depth = he - i;
if (depth == 0 && mappedSurfaceBlock != null) {
h.setRaw(xf, i, zf, mappedSurfaceBlock);
continue;
}
if (blocks == null) {
blocks = biome.generateLayers(dimension, realX, realZ, localRng, he, he, data, complex);
}
if (blocks.hasIndex(depth)) {
h.setRaw(xf, i, zf, blocks.get(depth));
continue;
}
if (hasUndergroundOres) {
if (biomeUndergroundOreBounds.contains(i)) {
ore = generateOres(biomeUndergroundOres, realX, i, realZ, localRng, data);
}
if (ore == null && regionUndergroundOreBounds.contains(i)) {
ore = generateOres(regionUndergroundOres, realX, i, realZ, localRng, data);
}
if (ore == null && dimensionUndergroundOreBounds.contains(i)) {
ore = generateOres(dimensionUndergroundOres, realX, i, realZ, localRng, data);
}
}
if (ore != null) {
h.setRaw(xf, i, zf, ore);
} else {
h.setRaw(xf, i, zf, rock);
}
}
}
if (upperContext != null) {
int rawUpperSurface = upperContext.getUpperSurfaceY(realX, realZ);
int upperGap = dimension.getUpperDimensionGap();
int upperSurfaceY = Math.max(rawUpperSurface, he + upperGap);
if (upperSurfaceY < chunkHeight - 1) {
IrisBiome upperBiome = upperContext.getUpperBiome(realX, realZ);
PlatformBlockState upperRock = upperContext.getRockBlock(realX, realZ);
PlatformBlockState upperMappedSurface = upperContext.getSurfaceBlock(realX, realZ);
int upperThickness = chunkHeight - 1 - upperSurfaceY;
KList<PlatformBlockState> upperBlocks = upperBiome != null
? upperBiome.generateLayers(upperContext.getDimension(),
realX, realZ, localRng, upperThickness, upperThickness,
upperContext.getData(), complex)
: null;
for (int y = chunkHeight - 1; y >= upperSurfaceY; y--) {
if (y == chunkHeight - 1 && bedrockEnabled) {
h.setRaw(xf, y, zf, BEDROCK);
continue;
}
if (y == upperSurfaceY && upperMappedSurface != null) {
h.setRaw(xf, y, zf, upperMappedSurface);
continue;
}
int depthFromFace = y - upperSurfaceY;
if (upperBlocks != null && upperBlocks.hasIndex(depthFromFace)) {
h.setRaw(xf, y, zf, upperBlocks.get(depthFromFace));
} else {
h.setRaw(xf, y, zf, upperRock);
}
}
}
}
}
}
private PlatformBlockState generateOres(KList<IrisOreGenerator> oreGenerators, int x, int y, int z, RNG rng, IrisData data) {
if (oreGenerators == null || oreGenerators.isEmpty()) {
return null;
}
int oreCount = oreGenerators.size();
for (int oreIndex = 0; oreIndex < oreCount; oreIndex++) {
IrisOreGenerator oreGenerator = oreGenerators.get(oreIndex);
PlatformBlockState ore = oreGenerator.generate(x, y, z, rng, data);
if (ore != null) {
return ore;
}
}
return null;
}
}
@@ -0,0 +1,536 @@
/*
* 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.decorator;
import art.arcane.iris.core.loader.IrisData;
import art.arcane.iris.engine.mantle.EngineMantle;
import art.arcane.iris.engine.object.world.biome.IrisBiome;
import art.arcane.iris.engine.object.decoration.IrisDecorationPart;
import art.arcane.iris.engine.object.decoration.IrisDecorator;
import art.arcane.iris.engine.object.procedural.IrisProceduralBlocks;
import art.arcane.iris.platform.bukkit.BukkitBlockState;
import art.arcane.iris.spi.IrisLogging;
import art.arcane.iris.spi.PlatformBlockState;
import art.arcane.iris.util.common.data.B;
import art.arcane.iris.util.project.hunk.Hunk;
import art.arcane.volmlib.util.math.RNG;
import org.bukkit.block.BlockFace;
import org.bukkit.block.BlockSupport;
import org.bukkit.block.data.BlockData;
import org.bukkit.block.data.MultipleFacing;
final class DecoratorCore {
private static final long SEED_OFFSET = 29356788L;
private static final long PART_FACTOR = 10439677L;
private static final String WEEPING_VINES = "minecraft:weeping_vines";
private static final String WEEPING_VINES_PLANT = "minecraft:weeping_vines_plant";
private static final String TWISTING_VINES = "minecraft:twisting_vines";
private static final String TWISTING_VINES_PLANT = "minecraft:twisting_vines_plant";
private static volatile PlatformBlockState weepingVines;
private static volatile PlatformBlockState weepingVinesPlant;
private static volatile PlatformBlockState twistingVines;
private static volatile PlatformBlockState twistingVinesPlant;
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;
}
}
static long partSeed(long baseSeed, int partOrdinal) {
return baseSeed + SEED_OFFSET - (partOrdinal * PART_FACTOR);
}
static long partSeed(long baseSeed, IrisDecorationPart part) {
return partSeed(baseSeed, part.ordinal());
}
static IrisDecorator pickDecorator(IrisBiome biome, IrisDecorationPart part, RNG gRNG,
RNG colRng, IrisData data, double realX, double realZ) {
IrisDecorator[] bucket = biome.getDecoratorBucket(part);
if (bucket.length == 0) {
return null;
}
IrisDecorator picked = null;
int count = 0;
for (IrisDecorator d : bucket) {
try {
if (d.passesChanceGate(gRNG, realX, realZ, data)) {
count++;
if (count == 1 || colRng.nextInt(count) == 0) {
picked = d;
}
}
} catch (Throwable e) {
IrisLogging.reportError(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(IrisDecorator decorator,
int x, int z, int realX, int height, int realZ,
Hunk<PlatformBlockState> data, RNG rng, IrisData irisData,
boolean underwater, boolean caveSkipFluid, EngineMantle mantle) {
if (height < 0 || height >= data.getHeight()) {
return;
}
PlatformBlockState bdx = data.get(x, height, z);
PlatformBlockState bd = decorator.pickBlockData(rng, irisData, realX, realZ);
if (!underwater && !canGoOn(bd, bdx)
&& !decorator.isForcePlace() && decorator.getForceBlock() == null) {
return;
}
if (decorator.getForceBlock() != null) {
if (caveSkipFluid && B.isFluid(bdx)) {
return;
}
data.set(x, height, z, fixFacesForHunk(
decorator.getForceBlock().getBlockData(irisData), data, x, z, realX, height, realZ, mantle));
}
if (!decorator.isForcePlace()) {
if (decorator.getWhitelist() != null && !matchesPalette(decorator.getWhitelistArray(irisData), bdx)) {
return;
}
if (decorator.getBlacklist() != null && matchesPalette(decorator.getBlacklistArray(irisData), bdx)) {
return;
}
}
String half = bd == null ? null : IrisProceduralBlocks.propertyValue(bd, "half");
if (half != null) {
int lowerY = height + 1;
int upperY = height + 2;
if (!canPlaceTwoBlockPlant(data, x, z, lowerY, upperY, caveSkipFluid)) {
return;
}
try {
PlatformBlockState upper = bd.withProperty("half", topHalfValue(half));
PlatformBlockState lower = fixFacesForHunk(
bd.withProperty("half", bottomHalfValue(half)),
data, x, z, realX, lowerY, realZ, mantle);
data.set(x, lowerY, z, lower);
data.set(x, upperY, z, upper);
} catch (Throwable e) {
IrisLogging.reportError(e);
}
return;
}
int targetY = height + 1;
if (targetY < data.getHeight() && B.isAir(data.get(x, targetY, z))) {
data.set(x, targetY, z, fixFacesForHunk(bd, data, x, z, realX, targetY, realZ, mantle));
}
}
private static boolean matchesPalette(PlatformBlockState[] palette, PlatformBlockState surface) {
for (int i = 0; i < palette.length; i++) {
if (palette[i].equals(surface)) {
return true;
}
}
return false;
}
static void placeSingleAt(IrisDecorator decorator, int x, int z,
int realX, int height, int realZ, Hunk<PlatformBlockState> data,
RNG rng, IrisData irisData, boolean applyFixFaces, EngineMantle mantle) {
PlatformBlockState bd = decorator.pickBlockData(rng, irisData, realX, realZ);
if (bd == null) {
return;
}
if (applyFixFaces) {
bd = fixFacesForHunk(bd, data, x, z, realX, height, realZ, mantle);
}
data.set(x, height, z, bd);
}
static void placeStackUp(IrisDecorator decorator, int x, int z, int realX, int realZ,
int height, int max, Hunk<PlatformBlockState> data,
RNG rng, IrisData irisData, PlaceOpts opts) {
if (height < 0 || height >= data.getHeight()) {
return;
}
int effectiveMax = max;
if (opts.underwater && height < opts.fluidHeight) {
effectiveMax = opts.fluidHeight;
}
int stack = computeStack(decorator, rng, realX, realZ, irisData, effectiveMax);
if (stack == 1) {
int targetY = height + 1;
if (targetY >= data.getHeight()) {
return;
}
PlatformBlockState existing = data.get(x, targetY, z);
if (!canReplaceStackTarget(existing, opts.underwater)
|| (opts.caveSkipFluid && B.isFluid(existing))) {
return;
}
PlatformBlockState block = decorator.pickBlockDataTop(rng, irisData, realX, realZ);
if (block == null || (!opts.underwater && !canGoOn(block, data.get(x, height, z)))) {
return;
}
block = stackedVineBlock(block, stack, 0);
data.set(x, targetY, z, block);
return;
}
PlatformBlockState bdx = data.get(x, height, z);
for (int i = 0; i < stack; i++) {
int h = height + i;
double threshold = ((double) i) / (stack - 1);
PlatformBlockState bd = threshold >= decorator.getTopThreshold()
? decorator.pickBlockDataTop(rng, irisData, realX, realZ)
: decorator.pickBlockData(rng, irisData, realX, realZ);
if (bd == null) {
break;
}
if (i == 0 && !opts.underwater && !canGoOn(bd, bdx)) {
break;
}
if (opts.underwater && height + 1 + i > opts.fluidHeight) {
break;
}
if (height + 1 + i >= data.getHeight()) {
break;
}
PlatformBlockState existing = data.get(x, height + 1 + i, z);
if (!canReplaceStackTarget(existing, opts.underwater)
|| (opts.caveSkipFluid && B.isFluid(existing))) {
break;
}
if (IrisProceduralBlocks.materialKey(bd).equals("minecraft:pointed_dripstone")) {
bd = dripstoneBlock(stack, i, "up");
}
bd = stackedVineBlock(bd, stack, i);
data.set(x, height + 1 + i, z, bd);
}
}
static void placeStackDown(IrisDecorator decorator, int x, int z, int realX, int realZ,
int height, int minHeight, Hunk<PlatformBlockState> data,
RNG rng, IrisData irisData, int max, PlaceOpts opts, EngineMantle mantle) {
if (height < 0 || height >= data.getHeight()) {
return;
}
int stack = computeStack(decorator, rng, realX, realZ, irisData, max);
if (stack == 1) {
if (opts.caveSkipFluid && B.isFluid(data.get(x, height, z))) {
return;
}
PlatformBlockState block = decorator.pickBlockDataTop(rng, irisData, realX, realZ);
if (block == null) {
return;
}
block = stackedVineBlock(block, stack, 0);
data.set(x, height, z, fixFacesForHunk(block, data, x, z, realX, height, realZ, mantle));
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);
PlatformBlockState bd = threshold >= decorator.getTopThreshold()
? decorator.pickBlockDataTop(rng, irisData, realX, realZ)
: decorator.pickBlockData(rng, irisData, realX, realZ);
if (bd == null) {
break;
}
if (IrisProceduralBlocks.materialKey(bd).equals("minecraft:pointed_dripstone")) {
bd = dripstoneBlock(stack, i, "down");
}
bd = stackedVineBlock(bd, stack, i);
if (opts.caveSkipFluid && B.isFluid(data.get(x, h, z))) {
break;
}
data.set(x, h, z, fixFacesForHunk(bd, data, x, z, realX, h, realZ, mantle));
}
}
static void placeFloatingSimple(IrisDecorator decorator,
int xf, int zf, int realX, int realZ,
int height, int max, Hunk<PlatformBlockState> data,
RNG rng, IrisData irisData) {
PlatformBlockState bd = decorator.pickBlockData(rng, irisData, realX, realZ);
if (bd == null) {
return;
}
String half = IrisProceduralBlocks.propertyValue(bd, "half");
if (half != null) {
int lowerY = height + 1;
int upperY = height + 2;
if (max <= 2 || !canPlaceTwoBlockPlant(data, xf, zf, lowerY, upperY, false)) {
return;
}
try {
PlatformBlockState upper = bd.withProperty("half", topHalfValue(half));
PlatformBlockState lower = bd.withProperty("half", bottomHalfValue(half));
data.set(xf, lowerY, zf, lower);
data.set(xf, upperY, zf, upper);
} catch (Throwable e) {
IrisLogging.reportError(e);
}
return;
}
if (max > 1 && height + 1 < data.getHeight()) {
data.set(xf, height + 1, zf, bd);
}
}
static int placeFloatingStacked(IrisDecorator decorator,
int xf, int zf, int realX, int realZ,
int height, int max, Hunk<PlatformBlockState> data,
RNG rng, IrisData irisData) {
int stack = decorator.getHeight(rng, realX, realZ, irisData);
if (decorator.isScaleStack()) {
stack = Math.min((int) Math.ceil((double) max * ((double) stack / 100)), decorator.getAbsoluteMaxStack());
} 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.getHeight()) {
break;
}
double threshold = stack == 1 ? 0.0 : ((double) i) / (stack - 1);
PlatformBlockState bd = threshold >= decorator.getTopThreshold()
? decorator.pickBlockDataTop(rng, irisData, realX, realZ)
: decorator.pickBlockData(rng, irisData, realX, realZ);
if (bd == null) {
break;
}
bd = stackedVineBlock(bd, stack, i);
data.set(xf, h, zf, bd);
placed++;
}
return placed;
}
static PlatformBlockState fixFacesForHunk(PlatformBlockState b, Hunk<PlatformBlockState> hunk, int rX, int rZ,
int x, int y, int z, EngineMantle mantle) {
if (!B.isVineBlock(b)) {
return b;
}
DecoratorPlatformHooks.FaceFixer fixer = DecoratorPlatformHooks.faceFixer();
if (fixer != null) {
return fixer.fixFaces(b, hunk, rX, rZ, x, y, z, mantle);
}
BlockData rawB = (BlockData) b.nativeHandle();
BlockData cloned = rawB.clone();
MultipleFacing data = (MultipleFacing) cloned;
data.getFaces().forEach(f -> data.setFace(f, false));
boolean found = false;
for (BlockFace f : BlockFace.values()) {
if (!f.isCartesian()) {
continue;
}
int yy = y + f.getModY();
PlatformBlockState rs = null;
if (mantle != null) {
rs = mantle.getMantle().get(x + f.getModX(), yy, z + f.getModZ(), PlatformBlockState.class);
}
BlockData r = rs == null ? (BlockData) EngineMantle.AIR.nativeHandle() : (BlockData) rs.nativeHandle();
if (r.isFaceSturdy(f.getOppositeFace(), BlockSupport.FULL)) {
if (data.getAllowedFaces().contains(f)) {
found = true;
data.setFace(f, true);
}
continue;
}
int xx = rX + f.getModX();
int zz = rZ + f.getModZ();
if (xx < 0 || xx > 15 || zz < 0 || zz > 15 || yy < 0 || yy >= hunk.getHeight()) {
continue;
}
r = (BlockData) hunk.get(xx, yy, zz).nativeHandle();
if (r.isFaceSturdy(f.getOppositeFace(), BlockSupport.FULL)) {
if (data.getAllowedFaces().contains(f)) {
found = true;
data.setFace(f, true);
}
}
}
if (!found) {
BlockFace fallback = data.getAllowedFaces().contains(BlockFace.DOWN) ? BlockFace.DOWN : BlockFace.UP;
if (data.getAllowedFaces().contains(fallback)) {
data.setFace(fallback, true);
}
}
return BukkitBlockState.of(cloned);
}
static boolean canGoOn(PlatformBlockState decorator, PlatformBlockState surface) {
if (!B.canPlaceOnto(decorator, surface)) {
return false;
}
DecoratorPlatformHooks.SurfaceSturdiness sturdiness = DecoratorPlatformHooks.surfaceSturdiness();
if (sturdiness != null) {
return sturdiness.canGoOn(surface);
}
return ((BlockData) surface.nativeHandle()).isFaceSturdy(BlockFace.UP, BlockSupport.FULL);
}
static boolean isValidShorelineSupport(IrisDecorator decorator, PlatformBlockState decorant, PlatformBlockState surface) {
return surface != null
&& B.isSolid(surface)
&& (decorator.isForcePlace() || canGoOn(decorant, surface));
}
static boolean canReplaceStackTarget(PlatformBlockState state, boolean allowFluid) {
return B.isAir(state) || allowFluid && B.isFluid(state);
}
private static boolean canPlaceTwoBlockPlant(Hunk<PlatformBlockState> data, int x, int z,
int lowerY, int upperY, boolean caveSkipFluid) {
if (lowerY < 0 || upperY >= data.getHeight()) {
return false;
}
PlatformBlockState lower = data.get(x, lowerY, z);
PlatformBlockState upper = data.get(x, upperY, z);
return B.isAir(lower) && B.isAir(upper)
&& (!caveSkipFluid || !B.isFluid(lower) && !B.isFluid(upper));
}
private static int computeStack(IrisDecorator decorator, RNG rng, double realX, double realZ,
IrisData irisData, int max) {
int stack = decorator.getHeight(rng, realX, realZ, irisData);
if (decorator.isScaleStack()) {
stack = Math.min((int) Math.ceil((double) max * ((double) stack / 100)), decorator.getAbsoluteMaxStack());
} else {
stack = Math.min(max, stack);
}
return stack;
}
private static volatile PlatformBlockState[] dripstoneUp;
private static volatile PlatformBlockState[] dripstoneDown;
private static PlatformBlockState[] buildDripstoneArr(String direction) {
String[] order = {"tip", "frustum", "base"};
PlatformBlockState[] arr = new PlatformBlockState[3];
for (int k = 0; k < 3; k++) {
arr[k] = B.getState("minecraft:pointed_dripstone[thickness=" + order[k] + ",vertical_direction=" + direction + "]");
}
return arr;
}
private static PlatformBlockState dripstoneBlock(int stack, int i, String direction) {
int thIdx;
if (i == stack - 1) {
thIdx = 0;
} else if (i == stack - 2) {
thIdx = 1;
} else {
thIdx = 2;
}
if (direction.equals("up")) {
if (dripstoneUp == null) {
dripstoneUp = buildDripstoneArr("up");
}
return dripstoneUp[thIdx];
}
if (dripstoneDown == null) {
dripstoneDown = buildDripstoneArr("down");
}
return dripstoneDown[thIdx];
}
static String stackedVineKey(PlatformBlockState state, int stack, int index) {
String material = IrisProceduralBlocks.materialKey(state);
boolean tip = index == stack - 1;
return switch (material) {
case WEEPING_VINES, WEEPING_VINES_PLANT -> tip ? WEEPING_VINES : WEEPING_VINES_PLANT;
case TWISTING_VINES, TWISTING_VINES_PLANT -> tip ? TWISTING_VINES : TWISTING_VINES_PLANT;
default -> null;
};
}
private static PlatformBlockState stackedVineBlock(PlatformBlockState state, int stack, int index) {
String key = stackedVineKey(state, stack, index);
if (key == null) {
return state;
}
return switch (key) {
case WEEPING_VINES -> weepingVines == null ? weepingVines = B.getState(key) : weepingVines;
case WEEPING_VINES_PLANT -> weepingVinesPlant == null ? weepingVinesPlant = B.getState(key) : weepingVinesPlant;
case TWISTING_VINES -> twistingVines == null ? twistingVines = B.getState(key) : twistingVines;
case TWISTING_VINES_PLANT -> twistingVinesPlant == null ? twistingVinesPlant = B.getState(key) : twistingVinesPlant;
default -> state;
};
}
}
@@ -0,0 +1,62 @@
/*
* Iris is a World Generator for Minecraft Bukkit 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.engine.mantle.EngineMantle;
import art.arcane.iris.spi.PlatformBlockState;
import art.arcane.iris.util.project.hunk.Hunk;
public final class DecoratorPlatformHooks {
private static volatile FaceFixer FACE_FIXER = null;
private static volatile SurfaceSturdiness SURFACE_STURDINESS = null;
private DecoratorPlatformHooks() {
}
public interface FaceFixer {
PlatformBlockState fixFaces(PlatformBlockState state, Hunk<PlatformBlockState> hunk, int rX, int rZ, int x, int y, int z, EngineMantle mantle);
}
public interface SurfaceSturdiness {
boolean canGoOn(PlatformBlockState surface);
}
public static synchronized Bindings bind(FaceFixer faceFixer, SurfaceSturdiness surfaceSturdiness) {
Bindings previous = new Bindings(FACE_FIXER, SURFACE_STURDINESS);
FACE_FIXER = faceFixer;
SURFACE_STURDINESS = surfaceSturdiness;
return previous;
}
public static synchronized void restore(Bindings bindings) {
FACE_FIXER = bindings.faceFixer();
SURFACE_STURDINESS = bindings.surfaceSturdiness();
}
static FaceFixer faceFixer() {
return FACE_FIXER;
}
static SurfaceSturdiness surfaceSturdiness() {
return SURFACE_STURDINESS;
}
public record Bindings(FaceFixer faceFixer, SurfaceSturdiness surfaceSturdiness) {
}
}
@@ -0,0 +1,55 @@
/*
* 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.decorator;
import art.arcane.iris.engine.framework.Engine;
import art.arcane.iris.engine.object.world.biome.IrisBiome;
import art.arcane.iris.engine.object.decoration.IrisDecorationPart;
import art.arcane.iris.engine.object.decoration.IrisDecorator;
import art.arcane.iris.util.project.hunk.Hunk;
import art.arcane.volmlib.util.math.RNG;
import art.arcane.iris.spi.PlatformBlockState;
/*
* 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(Engine engine, IrisBiome target, IrisDecorationPart part,
int xf, int zf, int realX, int realZ,
int height, int max, Hunk<PlatformBlockState> data, RNG rng,
Runnable candidatesNullCallback) {
RNG gRNG = new RNG(DecoratorCore.partSeed(engine.getSeedManager().getDecorator(), part));
IrisDecorator decorator = DecoratorCore.pickDecorator(target, part, gRNG, rng, engine.getData(), realX, realZ);
if (decorator == null) {
candidatesNullCallback.run();
return 0;
}
if (!decorator.isStacking()) {
DecoratorCore.placeFloatingSimple(decorator, xf, zf, realX, realZ, height, max, data, rng, engine.getData());
return max > 1 ? 1 : 0;
}
return DecoratorCore.placeFloatingStacked(decorator, xf, zf, realX, realZ, height, max, data, rng, engine.getData());
}
}
@@ -0,0 +1,74 @@
/*
* 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.decorator;
import art.arcane.iris.engine.framework.Engine;
import art.arcane.iris.engine.object.world.biome.InferredType;
import art.arcane.iris.engine.object.world.biome.IrisBiome;
import art.arcane.iris.engine.object.decoration.IrisDecorationPart;
import art.arcane.iris.engine.object.decoration.IrisDecorator;
import art.arcane.iris.util.common.data.B;
import art.arcane.iris.util.project.hunk.Hunk;
import art.arcane.volmlib.util.documentation.BlockCoordinates;
import art.arcane.volmlib.util.math.RNG;
import art.arcane.iris.spi.PlatformBlockState;
public class IrisCeilingDecorator extends IrisEngineDecorator {
private final RNG partRNG;
public IrisCeilingDecorator(Engine engine) {
super(engine, "Ceiling", IrisDecorationPart.CEILING);
this.partRNG = new RNG(DecoratorCore.partSeed(getSeed(), IrisDecorationPart.CEILING));
}
@BlockCoordinates
@Override
public void decorate(int x, int z, int realX, int realX1, int realX_1, int realZ, int realZ1, int realZ_1,
Hunk<PlatformBlockState> data, IrisBiome biome, int height, int max) {
decorate(x, z, realX, realX1, realX_1, realZ, realZ1, realZ_1, data, biome, biome.getInferredType(), height, max);
}
@BlockCoordinates
public void decorate(int x, int z, int realX, int realX1, int realX_1, int realZ, int realZ1, int realZ_1,
Hunk<PlatformBlockState> data, IrisBiome biome, InferredType inferredType, int height, int max) {
boolean caveSkipFluid = IrisSurfaceDecorator.skipsFluid(inferredType);
RNG rng = getRNG(realX, realZ);
IrisDecorator decorator = DecoratorCore.pickDecorator(biome, getPart(), partRNG, rng, getData(), realX, realZ);
if (decorator == null) {
return;
}
if (!decorator.isStacking()) {
if (caveSkipFluid) {
PlatformBlockState state = data.get(x, height, z);
if (B.isFluid(state)) {
return;
}
}
DecoratorCore.placeSingleAt(decorator, x, z, realX, height, realZ, data, rng, getData(), true, getEngine().getMantle());
return;
}
DecoratorCore.PlaceOpts opts = DecoratorCore.SCRATCH_OPTS.get();
opts.reset();
opts.caveSkipFluid = caveSkipFluid;
DecoratorCore.placeStackDown(decorator, x, z, realX, realZ, height, 0, data, rng, getData(), max, opts, getEngine().getMantle());
}
}
@@ -0,0 +1,45 @@
/*
* 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.decorator;
import art.arcane.iris.engine.framework.Engine;
import art.arcane.iris.engine.framework.EngineAssignedComponent;
import art.arcane.iris.engine.framework.EngineDecorator;
import art.arcane.iris.engine.object.decoration.IrisDecorationPart;
import art.arcane.volmlib.util.documentation.BlockCoordinates;
import art.arcane.volmlib.util.math.RNG;
import lombok.Getter;
public abstract class IrisEngineDecorator extends EngineAssignedComponent implements EngineDecorator {
@Getter
private final IrisDecorationPart part;
public IrisEngineDecorator(Engine engine, String name, IrisDecorationPart part) {
super(engine, name + " Decorator");
this.part = part;
}
@BlockCoordinates
protected RNG getRNG(int x, int z) {
long seed = DecoratorCore.partSeed(getSeed(), part);
long modX = 29356788L ^ (part.ordinal() + 6);
long modZ = 10439677L ^ (part.ordinal() + 1);
return new RNG(x * modX + z * modZ + seed);
}
}
@@ -0,0 +1,84 @@
/*
* 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.decorator;
import art.arcane.iris.engine.framework.Engine;
import art.arcane.iris.engine.object.world.biome.IrisBiome;
import art.arcane.iris.engine.object.decoration.IrisDecorationPart;
import art.arcane.iris.engine.object.decoration.IrisDecorator;
import art.arcane.iris.util.project.hunk.Hunk;
import art.arcane.volmlib.util.documentation.BlockCoordinates;
import art.arcane.volmlib.util.math.RNG;
import art.arcane.iris.spi.PlatformBlockState;
public class IrisSeaFloorDecorator extends IrisEngineDecorator {
private final RNG partRNG;
public IrisSeaFloorDecorator(Engine engine) {
super(engine, "Sea Floor", IrisDecorationPart.SEA_FLOOR);
this.partRNG = new RNG(DecoratorCore.partSeed(getSeed(), IrisDecorationPart.SEA_FLOOR));
}
@BlockCoordinates
@Override
public void decorate(int x, int z, int realX, int realX1, int realX_1, int realZ, int realZ1, int realZ_1,
Hunk<PlatformBlockState> data, IrisBiome biome, int height, int max) {
RNG rng = getRNG(realX, realZ);
IrisDecorator decorator = DecoratorCore.pickDecorator(biome, getPart(), partRNG, rng, getData(), realX, realZ);
if (decorator == null) {
return;
}
if (!decorator.isStacking()) {
if (!decorator.isForcePlace() && !decorator.getSlopeCondition().isDefault()
&& !decorator.getSlopeCondition().isValid(getComplex().getSlopeStream().get(realX, realZ))) {
return;
}
if (height >= 0 && height < getEngine().getHeight()) {
data.set(x, height, z, decorator.getBlockData100(biome, rng, realX, height, realZ, getData()));
}
return;
}
int stack = decorator.getHeight(rng, realX, realZ, getData());
if (decorator.isScaleStack()) {
stack = (int) Math.ceil((double) (max - height) * ((double) stack / 100));
} else {
stack = Math.min(stack, max - height);
}
if (stack == 1) {
data.set(x, height, z, decorator.getBlockDataForTop(biome, rng, realX, height, realZ, getData()));
return;
}
int engineHeight = getEngine().getHeight();
for (int i = 0; i < stack; i++) {
int h = height + i;
if (h > max || h > engineHeight) {
continue;
}
double threshold = ((double) i) / (stack - 1);
data.set(x, h, z, threshold >= decorator.getTopThreshold()
? decorator.getBlockDataForTop(biome, rng, realX, h, realZ, getData())
: decorator.getBlockData100(biome, rng, realX, h, realZ, getData()));
}
}
}
@@ -0,0 +1,97 @@
/*
* 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.decorator;
import art.arcane.iris.engine.framework.Engine;
import art.arcane.iris.engine.object.world.biome.IrisBiome;
import art.arcane.iris.engine.object.decoration.IrisDecorationPart;
import art.arcane.iris.engine.object.decoration.IrisDecorator;
import art.arcane.iris.util.project.hunk.Hunk;
import art.arcane.volmlib.util.documentation.BlockCoordinates;
import art.arcane.volmlib.util.math.RNG;
import art.arcane.iris.spi.PlatformBlockState;
public class IrisSeaSurfaceDecorator extends IrisEngineDecorator {
private final RNG partRNG;
public IrisSeaSurfaceDecorator(Engine engine) {
super(engine, "Sea Surface", IrisDecorationPart.SEA_SURFACE);
this.partRNG = new RNG(DecoratorCore.partSeed(getSeed(), IrisDecorationPart.SEA_SURFACE));
}
@BlockCoordinates
@Override
public void decorate(int x, int z, int realX, int realX1, int realX_1, int realZ, int realZ1, int realZ_1,
Hunk<PlatformBlockState> data, IrisBiome biome, int height, int max) {
RNG rng = getRNG(realX, realZ);
IrisDecorator decorator = DecoratorCore.pickDecorator(biome, getPart(), partRNG, rng, getData(), realX, realZ);
if (decorator == null) {
return;
}
if (!decorator.isStacking()) {
int targetY = height + 1;
if (height >= 0 && targetY < getEngine().getHeight()
&& DecoratorCore.canReplaceStackTarget(data.get(x, targetY, z), false)) {
PlatformBlockState block = decorator.getBlockData100(biome, rng, realX, height, realZ, getData());
if (block != null) {
data.set(x, targetY, z, block);
}
}
return;
}
int stack = decorator.getHeight(rng, realX, realZ, getData());
if (decorator.isScaleStack()) {
stack = (int) Math.ceil((double) (max - height) * ((double) stack / 100));
}
if (stack == 1) {
int targetY = height + 1;
if (targetY >= data.getHeight() || !DecoratorCore.canReplaceStackTarget(data.get(x, targetY, z), false)) {
return;
}
PlatformBlockState block = decorator.getBlockDataForTop(biome, rng, realX, height, realZ, getData());
if (block != null) {
data.set(x, targetY, z, block);
}
return;
}
int engineHeight = getEngine().getHeight();
for (int i = 0; i < stack; i++) {
int h = height + i;
int targetY = h + 1;
if (h >= max || targetY >= engineHeight
|| !DecoratorCore.canReplaceStackTarget(data.get(x, targetY, z), false)) {
break;
}
double threshold = ((double) i) / (stack - 1);
PlatformBlockState block = threshold >= decorator.getTopThreshold()
? decorator.getBlockDataForTop(biome, rng, realX, h, realZ, getData())
: decorator.getBlockData100(biome, rng, realX, h, realZ, getData());
if (block == null) {
break;
}
data.set(x, targetY, z, block);
}
}
}
@@ -0,0 +1,126 @@
/*
* 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.decorator;
import art.arcane.iris.engine.framework.Engine;
import art.arcane.iris.engine.object.world.biome.IrisBiome;
import art.arcane.iris.engine.object.decoration.IrisDecorationPart;
import art.arcane.iris.engine.object.decoration.IrisDecorator;
import art.arcane.iris.util.project.hunk.Hunk;
import art.arcane.iris.util.project.stream.ProceduralStream;
import art.arcane.volmlib.util.documentation.BlockCoordinates;
import art.arcane.volmlib.util.math.RNG;
import art.arcane.iris.spi.PlatformBlockState;
public class IrisShoreLineDecorator extends IrisEngineDecorator {
private final RNG partRNG;
public IrisShoreLineDecorator(Engine engine) {
super(engine, "Shore Line", IrisDecorationPart.SHORE_LINE);
this.partRNG = new RNG(DecoratorCore.partSeed(getSeed(), IrisDecorationPart.SHORE_LINE));
}
@BlockCoordinates
@Override
public void decorate(int x, int z, int realX, int realX1, int realX_1, int realZ, int realZ1, int realZ_1,
Hunk<PlatformBlockState> data, IrisBiome biome, int height, int max) {
if (height != getDimension().getFluidHeight()) {
return;
}
double complexFluidHeight = getComplex().getFluidHeight();
ProceduralStream<Double> heightStream = getComplex().getHeightStream();
if (Math.round(heightStream.get(realX1, realZ)) >= complexFluidHeight
&& Math.round(heightStream.get(realX_1, realZ)) >= complexFluidHeight
&& Math.round(heightStream.get(realX, realZ1)) >= complexFluidHeight
&& Math.round(heightStream.get(realX, realZ_1)) >= complexFluidHeight) {
return;
}
RNG rng = getRNG(realX, realZ);
IrisDecorator decorator = DecoratorCore.pickDecorator(biome, getPart(), partRNG, rng, getData(), realX, realZ);
if (decorator == null) {
return;
}
if (!decorator.isForcePlace() && !decorator.getSlopeCondition().isDefault()
&& !decorator.getSlopeCondition().isValid(getComplex().getSlopeStream().get(realX, realZ))) {
return;
}
PlatformBlockState support = data.get(x, height, z);
if (support == null || !support.isSolid()) {
return;
}
if (!decorator.isStacking()) {
int targetY = height + 1;
if (targetY >= data.getHeight()
|| !DecoratorCore.canReplaceStackTarget(data.get(x, targetY, z), false)) {
return;
}
PlatformBlockState block = decorator.getBlockData100(biome, rng, realX, height, realZ, getData());
if (block != null && DecoratorCore.isValidShorelineSupport(decorator, block, support)) {
data.set(x, targetY, z, block);
}
return;
}
int stack = decorator.getHeight(rng, realX, realZ, getData());
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.getHeight() || !DecoratorCore.canReplaceStackTarget(data.get(x, targetY, z), false)) {
return;
}
PlatformBlockState block = decorator.getBlockDataForTop(biome, rng, realX, height, realZ, getData());
if (block != null && DecoratorCore.isValidShorelineSupport(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.getHeight()
|| !DecoratorCore.canReplaceStackTarget(data.get(x, targetY, z), false)) {
break;
}
double threshold = ((double) i) / (stack - 1);
PlatformBlockState block = threshold >= decorator.getTopThreshold()
? decorator.getBlockDataForTop(biome, rng, realX, h, realZ, getData())
: decorator.getBlockData100(biome, rng, realX, h, realZ, getData());
if (block == null) {
break;
}
if (i == 0 && !DecoratorCore.isValidShorelineSupport(decorator, block, support)) {
break;
}
data.set(x, targetY, z, block);
}
}
}
@@ -0,0 +1,96 @@
/*
* 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.decorator;
import art.arcane.iris.engine.framework.Engine;
import art.arcane.iris.engine.object.world.biome.InferredType;
import art.arcane.iris.engine.object.world.biome.IrisBiome;
import art.arcane.iris.engine.object.decoration.IrisDecorationPart;
import art.arcane.iris.engine.object.decoration.IrisDecorator;
import art.arcane.iris.util.project.hunk.Hunk;
import art.arcane.volmlib.util.documentation.BlockCoordinates;
import art.arcane.volmlib.util.math.RNG;
import art.arcane.iris.spi.PlatformBlockState;
public class IrisSurfaceDecorator extends IrisEngineDecorator {
private final RNG partRNG;
public IrisSurfaceDecorator(Engine engine) {
super(engine, "Surface", IrisDecorationPart.NONE);
this.partRNG = new RNG(DecoratorCore.partSeed(getSeed(), IrisDecorationPart.NONE));
}
protected IrisSurfaceDecorator(Engine engine, String name) {
super(engine, name, IrisDecorationPart.NONE);
this.partRNG = new RNG(DecoratorCore.partSeed(getSeed(), IrisDecorationPart.NONE));
}
protected boolean isSlopeValid(IrisDecorator decorator, int realX, int realZ) {
if (decorator.isForcePlace() || decorator.getSlopeCondition().isDefault()) {
return true;
}
return decorator.getSlopeCondition().isValid(getComplex().getSlopeStream().get(realX, realZ));
}
@BlockCoordinates
@Override
public void decorate(int x, int z, int realX, int realX1, int realX_1, int realZ, int realZ1, int realZ_1,
Hunk<PlatformBlockState> data, IrisBiome biome, int height, int max) {
decorate(x, z, realX, realX1, realX_1, realZ, realZ1, realZ_1, data, biome, biome.getInferredType(), height, max);
}
@BlockCoordinates
public void decorate(int x, int z, int realX, int realX1, int realX_1, int realZ, int realZ1, int realZ_1,
Hunk<PlatformBlockState> data, IrisBiome biome, InferredType inferredType, int height, int max) {
int fluidHeight = getDimension().getFluidHeight();
if (inferredType == InferredType.SHORE && height < fluidHeight) {
return;
}
boolean underwater = isUnderwater(inferredType, height, fluidHeight);
boolean caveSkipFluid = skipsFluid(inferredType);
RNG rng = getRNG(realX, realZ);
IrisDecorator decorator = DecoratorCore.pickDecorator(biome, getPart(), partRNG, rng, getData(), realX, realZ);
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, x, z, realX, realZ, height, max, data, rng, getData(), opts);
return;
}
DecoratorCore.placeSurfaceSingle(decorator, x, z, realX, height, realZ,
data, rng, getData(), underwater, caveSkipFluid, getEngine().getMantle());
}
static boolean isUnderwater(InferredType inferredType, int height, int fluidHeight) {
return height < fluidHeight && inferredType != InferredType.CAVE;
}
static boolean skipsFluid(InferredType inferredType) {
return inferredType == InferredType.CAVE;
}
}
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,37 @@
/*
* 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.engine.object.placement.IrisObjectPlacement;
import art.arcane.iris.engine.object.prefab.IrisObject;
import lombok.AllArgsConstructor;
import lombok.Data;
import org.jetbrains.annotations.Nullable;
@Data
@AllArgsConstructor
public class PlacedObject {
@Nullable
private IrisObjectPlacement placement;
@Nullable
private IrisObject object;
private int id;
private int xx;
private int zz;
}
@@ -0,0 +1,54 @@
/*
* 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.engine.object.structure.jigsaw.IrisJigsawPiece;
import art.arcane.iris.engine.object.prefab.IrisObject;
import art.arcane.iris.engine.object.prefab.IrisObjectRotation;
import lombok.AllArgsConstructor;
import lombok.Data;
@Data
@AllArgsConstructor
public class PlacedStructurePiece {
private final IrisJigsawPiece piece;
private final IrisObject object;
private final int x;
private final int y;
private final int z;
private final IrisObjectRotation rotation;
private final int minX;
private final int minY;
private final int minZ;
private final int maxX;
private final int maxY;
private final int maxZ;
public boolean intersects(PlacedStructurePiece o) {
long maxExclusiveX = (long) maxX + 1L;
long maxExclusiveY = (long) maxY + 1L;
long maxExclusiveZ = (long) maxZ + 1L;
long otherMaxExclusiveX = (long) o.maxX + 1L;
long otherMaxExclusiveY = (long) o.maxY + 1L;
long otherMaxExclusiveZ = (long) o.maxZ + 1L;
return minX < otherMaxExclusiveX && maxExclusiveX > o.minX
&& minY < otherMaxExclusiveY && maxExclusiveY > o.minY
&& minZ < otherMaxExclusiveZ && maxExclusiveZ > o.minZ;
}
}
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,359 @@
package art.arcane.iris.engine.framework;
import art.arcane.iris.engine.object.world.biome.IrisBiome;
import art.arcane.iris.engine.object.structure.IrisStructureAnchorMode;
import art.arcane.iris.engine.object.structure.IrisStructurePlacement;
import art.arcane.volmlib.util.math.RNG;
import art.arcane.volmlib.util.matter.MatterCavern;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.Objects;
import java.util.function.IntPredicate;
public final class StructureCaveAnchorResolver {
private static final int CHUNK_COLUMN_COUNT = 256;
private static final int MAX_ATTEMPTS = 64;
private static final int MAX_SCAN_STEP = 16;
private static final int MAX_CLEARANCE = 64;
private static final int MAX_GENERIC_CENTER_SEARCH = 4096;
private static final byte LIQUID_FORCED_AIR = 3;
private StructureCaveAnchorResolver() {
}
public static Anchor resolve(Engine engine, IrisStructurePlacement placement, int chunkX, int chunkZ, RNG rng) {
Objects.requireNonNull(engine, "Cave structure anchor requires an engine");
Objects.requireNonNull(placement, "Cave structure anchor requires a placement");
Objects.requireNonNull(rng, "Cave structure anchor requires a random source");
IrisStructureAnchorMode mode = placement.resolvedAnchor();
if (!mode.isCave() || engine.getMantle() == null || engine.getMantle().getMantle() == null) {
return null;
}
int worldMin = engine.getMinHeight() + 1;
int worldMax = engine.getMinHeight() + engine.getHeight() - 2;
int minimumY = Math.max(worldMin, Math.min(placement.getMinHeight(), placement.getMaxHeight()));
int maximumY = Math.min(worldMax, Math.max(placement.getMinHeight(), placement.getMaxHeight()));
if (minimumY > maximumY) {
return null;
}
int attempts = Math.min(MAX_ATTEMPTS, Math.max(1, placement.getCaveAnchorAttempts()));
int scanStep = Math.min(MAX_SCAN_STEP, Math.max(1, placement.getCaveAnchorScanStep()));
int clearance = Math.min(MAX_CLEARANCE, Math.max(1, placement.getCaveMinimumClearance()));
int chunkMinX = chunkX << 4;
int chunkMinZ = chunkZ << 4;
int[] candidateColumns = candidateColumnIndices(rng, attempts);
for (int candidateColumn : candidateColumns) {
int blockX = chunkMinX + (candidateColumn & 15);
int blockZ = chunkMinZ + (candidateColumn >>> 4);
List<Integer> anchors = anchorsInColumn(
engine, placement, mode, blockX, blockZ,
minimumY, maximumY, scanStep, clearance);
if (!anchors.isEmpty()) {
return new Anchor(blockX, anchors.get(rng.nextInt(anchors.size())), blockZ);
}
}
return null;
}
static int[] candidateColumnIndices(RNG rng, int attempts) {
Objects.requireNonNull(rng, "Cave structure column selection requires a random source");
int count = Math.min(MAX_ATTEMPTS, Math.max(1, attempts));
int start = rng.nextInt(CHUNK_COLUMN_COUNT);
int stride = (rng.nextInt(CHUNK_COLUMN_COUNT / 2) * 2) + 1;
int[] columns = new int[count];
for (int index = 0; index < count; index++) {
columns[index] = (start + (index * stride)) & (CHUNK_COLUMN_COUNT - 1);
}
return columns;
}
static List<Integer> anchorsInColumn(
Engine engine,
IrisStructurePlacement placement,
IrisStructureAnchorMode mode,
int blockX,
int blockZ,
int minimumY,
int maximumY,
int scanStep,
int clearance
) {
if (mode == IrisStructureAnchorMode.CAVE_CENTER) {
return centerAnchorsInColumn(
engine, placement, blockX, blockZ,
minimumY, maximumY, scanStep, clearance);
}
List<Integer> anchors = new ArrayList<>();
int step = Math.max(1, scanStep);
for (int worldY = minimumY; worldY <= maximumY; worldY += step) {
int mantleY = toMantleY(worldY, engine.getMinHeight());
if (!matchesGeometry(engine, mode, blockX, mantleY, blockZ, clearance)) {
continue;
}
if (!matchesAnchorFluid(engine, placement, blockX, mantleY, blockZ)) {
continue;
}
if (!matchesBiome(engine, placement, blockX, mantleY, blockZ)) {
continue;
}
anchors.add(worldY);
}
return List.copyOf(anchors);
}
private static List<Integer> centerAnchorsInColumn(
Engine engine,
IrisStructurePlacement placement,
int blockX,
int blockZ,
int minimumY,
int maximumY,
int scanStep,
int clearance
) {
List<Integer> anchors = new ArrayList<>();
int step = Math.max(1, scanStep);
int worldOffset = engine.getMinHeight();
int minimumMantleY = 0;
int maximumMantleY = engine.getHeight() - 1;
int processedThroughWorldY = Integer.MIN_VALUE;
IntPredicate carved = y -> isCarved(engine, blockX, y, blockZ);
for (int worldY = minimumY; worldY <= maximumY; worldY += step) {
if (worldY <= processedThroughWorldY) {
continue;
}
int mantleY = toMantleY(worldY, worldOffset);
if (!carved.test(mantleY)) {
continue;
}
int lower = cavernLowerBound(carved, mantleY, minimumMantleY);
int upper = cavernUpperBound(carved, mantleY, maximumMantleY);
processedThroughWorldY = upper + worldOffset;
if ((long) upper - lower + 1L < Math.max(1, clearance)) {
continue;
}
int lowerCenterWorldY = lower + Math.floorDiv(upper - lower, 2) + worldOffset;
addCenterAnchor(
anchors, engine, placement, blockX, blockZ,
lowerCenterWorldY, minimumY, maximumY);
int upperCenterWorldY = lower + Math.ceilDiv(upper - lower, 2) + worldOffset;
if (upperCenterWorldY != lowerCenterWorldY) {
addCenterAnchor(
anchors, engine, placement, blockX, blockZ,
upperCenterWorldY, minimumY, maximumY);
}
}
return List.copyOf(anchors);
}
private static void addCenterAnchor(
List<Integer> anchors,
Engine engine,
IrisStructurePlacement placement,
int blockX,
int blockZ,
int worldY,
int minimumY,
int maximumY
) {
if (worldY < minimumY || worldY > maximumY) {
return;
}
int mantleY = toMantleY(worldY, engine.getMinHeight());
if (matchesAnchorFluid(engine, placement, blockX, mantleY, blockZ)
&& matchesBiome(engine, placement, blockX, mantleY, blockZ)) {
anchors.add(worldY);
}
}
static boolean matchesGeometry(
Engine engine,
IrisStructureAnchorMode mode,
int blockX,
int mantleY,
int blockZ,
int clearance
) {
IntPredicate carved = y -> isCarved(engine, blockX, y, blockZ);
if (mode == IrisStructureAnchorMode.CAVE_CENTER) {
return matchesCenterGeometry(
carved, mantleY, Math.max(1, clearance), 0, engine.getHeight() - 1);
}
return matchesGeometry(carved, mode, mantleY, clearance);
}
static boolean matchesGeometry(
IntPredicate carved,
IrisStructureAnchorMode mode,
int mantleY,
int clearance
) {
if (!carved.test(mantleY)) {
return false;
}
int required = Math.max(1, clearance);
return switch (mode) {
case CAVE_FLOOR -> !carved.test(mantleY - 1)
&& carvedRun(carved, mantleY, 1, required);
case CAVE_CEILING -> !carved.test(mantleY + 1)
&& carvedRun(carved, mantleY, -1, required);
case CAVE_CENTER -> matchesCenterGeometry(
carved, mantleY, required,
saturatedSubtract(mantleY, MAX_GENERIC_CENTER_SEARCH),
saturatedAdd(mantleY, MAX_GENERIC_CENTER_SEARCH));
case CAVE_ANY -> carvedRun(
carved, mantleY - Math.floorDiv(required - 1, 2), 1, required);
default -> false;
};
}
private static boolean matchesCenterGeometry(
IntPredicate carved,
int mantleY,
int clearance,
int minimumY,
int maximumY
) {
if (!carved.test(mantleY)) {
return false;
}
int lower = cavernLowerBound(carved, mantleY, minimumY);
int upper = cavernUpperBound(carved, mantleY, maximumY);
if ((long) upper - lower + 1L < clearance) {
return false;
}
int lowerCenter = lower + Math.floorDiv(upper - lower, 2);
int upperCenter = lower + Math.ceilDiv(upper - lower, 2);
return mantleY == lowerCenter || mantleY == upperCenter;
}
private static int cavernLowerBound(IntPredicate carved, int mantleY, int minimumY) {
int lower = mantleY;
while (lower > minimumY && carved.test(lower - 1)) {
lower--;
}
return lower;
}
private static int cavernUpperBound(IntPredicate carved, int mantleY, int maximumY) {
int upper = mantleY;
while (upper < maximumY && carved.test(upper + 1)) {
upper++;
}
return upper;
}
private static int saturatedSubtract(int value, int amount) {
long result = (long) value - amount;
return result < Integer.MIN_VALUE ? Integer.MIN_VALUE : (int) result;
}
private static int saturatedAdd(int value, int amount) {
long result = (long) value + amount;
return result > Integer.MAX_VALUE ? Integer.MAX_VALUE : (int) result;
}
private static boolean carvedRun(
IntPredicate carved,
int mantleY,
int direction,
int length
) {
for (int offset = 0; offset < length; offset++) {
if (!carved.test(mantleY + (direction * offset))) {
return false;
}
}
return true;
}
private static boolean isCarved(Engine engine, int blockX, int mantleY, int blockZ) {
if (mantleY < 0 || mantleY >= engine.getHeight()) {
return false;
}
MatterCavern cavern = cavernAt(engine, blockX, mantleY, blockZ);
return cavern != null && cavern.isCavern();
}
private static boolean matchesAnchorFluid(
Engine engine,
IrisStructurePlacement placement,
int blockX,
int mantleY,
int blockZ
) {
MatterCavern cavern = cavernAt(engine, blockX, mantleY, blockZ);
return acceptsAnchorFluid(
placement.isUnderwater(),
cavern,
mantleY,
engine.getDimension().getCaveLavaHeight());
}
static boolean acceptsAnchorFluid(
boolean underwater,
MatterCavern cavern,
int mantleY,
int defaultLavaHeight
) {
if (cavern == null || !cavern.isCavern()) {
return false;
}
if (underwater) {
return true;
}
if (cavern.getLiquid() == LIQUID_FORCED_AIR) {
return true;
}
return cavern.isAir() && mantleY > defaultLavaHeight;
}
private static MatterCavern cavernAt(Engine engine, int blockX, int mantleY, int blockZ) {
return engine.getMantle().getMantle().get(blockX, mantleY, blockZ, MatterCavern.class);
}
static int toMantleY(int worldY, int worldMinHeight) {
return Math.subtractExact(worldY, worldMinHeight);
}
private static boolean matchesBiome(
Engine engine,
IrisStructurePlacement placement,
int blockX,
int mantleY,
int blockZ
) {
if (placement.getCaveBiomes() == null || placement.getCaveBiomes().isEmpty()) {
return true;
}
IrisBiome biome = engine.getCaveOrMantleBiome(blockX, mantleY, blockZ);
if (biome == null || biome.getLoadKey() == null) {
return false;
}
String actual = biome.getLoadKey().toLowerCase(Locale.ROOT);
for (String allowed : placement.getCaveBiomes()) {
if (matchesBiomeKey(actual, allowed)) {
return true;
}
}
return false;
}
static boolean matchesBiomeKey(String actual, String allowed) {
if (actual == null || actual.isBlank() || allowed == null || allowed.isBlank()) {
return false;
}
String normalizedActual = actual.trim().toLowerCase(Locale.ROOT);
String normalizedAllowed = allowed.trim().toLowerCase(Locale.ROOT);
return normalizedActual.equals(normalizedAllowed)
|| normalizedActual.endsWith(":" + normalizedAllowed)
|| normalizedAllowed.endsWith(":" + normalizedActual);
}
public record Anchor(int x, int y, int z) {
}
}
@@ -0,0 +1,287 @@
/*
* 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.engine.object.structure.vanilla.IrisNativeStructure;
import art.arcane.iris.engine.object.structure.IrisStructureAnchorMode;
import art.arcane.iris.engine.object.structure.IrisStructurePlacement;
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(IrisStructurePlacement placement, int cx, int cz, long seed) {
return switch (placement.getDistribution()) {
case RANDOM_SPREAD -> randomSpreadStart(cx, cz, placement.getSpacing(), placement.getSeparation(),
placementSalt(placement), seed);
case DENSITY -> densityStart(placement, cx, cz, seed);
case CONCENTRIC_RINGS -> concentricRingsStart(cx, cz, placement, seed);
};
}
public static RNG placementRng(IrisStructurePlacement 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(IrisStructurePlacement placement, int placementIndex, long seed) {
int count = Math.max(1, placement.getRingCount());
if (placementIndex < 0 || placementIndex >= count) {
return null;
}
int distance = Math.max(1, placement.getRingDistance());
int spread = Math.max(1, placement.getRingSpread());
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, IrisStructurePlacement placement, long seed) {
if (cx == 0 && cz == 0) {
return false;
}
int distance = Math.max(1, placement.getRingDistance());
int count = Math.max(1, placement.getRingCount());
int spread = Math.max(1, placement.getRingSpread());
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(IrisStructurePlacement placement, int cx, int cz, long seed) {
double density = placement.getDensity();
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(IrisStructurePlacement placement) {
long signature = 1469598103934665603L;
signature = appendLong(signature, placement.getDistribution().ordinal());
signature = appendLong(signature, placement.getSalt());
String placementId = placement.getPlacementId();
if (placementId != null && !placementId.isBlank()) {
signature = appendLong(signature, 1L);
signature = appendSignature(signature, placementId.trim());
} else {
signature = appendLong(signature, 0L);
signature = appendLong(signature, placement.getSpacing());
signature = appendLong(signature, placement.getSeparation());
signature = appendLong(signature, Double.doubleToLongBits(placement.getDensity()));
signature = appendLong(signature, placement.getRingCount());
signature = appendLong(signature, placement.getRingDistance());
signature = appendLong(signature, placement.getRingSpread());
signature = appendLong(signature, placement.getMinHeight());
signature = appendLong(signature, placement.getMaxHeight());
signature = appendLong(signature, placement.isUnderground() ? 1L : 0L);
signature = appendLong(signature, placement.isUnderwater() ? 1L : 0L);
signature = appendSources(signature, placement);
signature = appendAnchor(signature, placement);
}
return signature;
}
private static long placementSeed(IrisStructurePlacement 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, IrisStructurePlacement placement) {
long result = signature;
if (placement.hasIrisStructures()) {
result = appendLong(result, 1L);
result = appendLong(result, placement.getStructures().size());
for (String key : placement.getStructures()) {
result = appendSignature(result, key == null ? "" : key);
}
return result;
}
result = appendLong(result, 2L);
if (placement.getNativeStructures() == null) {
return appendLong(result, 0L);
}
result = appendLong(result, placement.getNativeStructures().size());
for (IrisNativeStructure source : placement.getNativeStructures()) {
if (source == null) {
result = appendSignature(result, "");
result = appendLong(result, 0L);
continue;
}
result = appendSignature(result,
source.getStructure() == null ? "" : source.getStructure());
result = appendLong(result, source.getWeight());
}
return result;
}
private static long appendAnchor(long signature, IrisStructurePlacement placement) {
IrisStructureAnchorMode anchor = placement.getAnchor();
if (anchor == null || anchor == IrisStructureAnchorMode.LEGACY) {
return signature;
}
long result = appendLong(signature, 0x4A49475341574C41L);
result = appendLong(result, anchor.ordinal());
if (!anchor.isCave()) {
return result;
}
result = appendLong(result, placement.getCaveAnchorAttempts());
result = appendLong(result, placement.getCaveAnchorScanStep());
result = appendLong(result, placement.getCaveMinimumClearance());
if (placement.getCaveBiomes() == null) {
return appendLong(result, 0L);
}
Set<String> biomes = new TreeSet<>();
for (String biome : placement.getCaveBiomes()) {
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(IrisStructurePlacement placement) {
String placementId = placement.getPlacementId();
long identity;
if (placementId != null && !placementId.isBlank()) {
identity = appendSignature(1469598103934665603L, placementId.trim());
} else {
identity = 1469598103934665603L;
identity = appendLong(identity, placement.getDistribution().ordinal());
identity = appendLong(identity, placement.getSpacing());
identity = appendLong(identity, placement.getSeparation());
identity = appendLong(identity, Double.doubleToLongBits(placement.getDensity()));
identity = appendLong(identity, placement.getRingCount());
identity = appendLong(identity, placement.getRingDistance());
identity = appendLong(identity, placement.getRingSpread());
identity = appendLong(identity, placement.getMinHeight());
identity = appendLong(identity, placement.getMaxHeight());
identity = appendLong(identity, placement.isUnderground() ? 1L : 0L);
identity = appendLong(identity, placement.isUnderwater() ? 1L : 0L);
identity = appendSources(identity, placement);
identity = appendAnchor(identity, placement);
}
return placement.getSalt() ^ (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,95 @@
package art.arcane.iris.engine.framework;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
import java.util.Objects;
public final class StructurePlacementMarker {
private static final String FAMILY_PREFIX = "@iris-structure:";
private static final String VERSION_PREFIX = FAMILY_PREFIX + "v1:";
private StructurePlacementMarker() {
}
public static String encodeStructure(String objectKey, int placementId, String structureKey) {
String normalizedObjectKey = requireKey(objectKey, "objectKey");
String normalizedStructureKey = requireKey(structureKey, "structureKey");
return VERSION_PREFIX
+ encodeKey(normalizedObjectKey)
+ ":" + placementId
+ ":" + encodeKey(normalizedStructureKey);
}
public static Decoded decode(String marker) {
if (marker == null || marker.isBlank()) {
return null;
}
if (marker.startsWith(FAMILY_PREFIX)) {
return decodeStructure(marker);
}
return decodeLegacy(marker);
}
private static Decoded decodeStructure(String marker) {
if (!marker.startsWith(VERSION_PREFIX)) {
return null;
}
String[] fields = marker.split(":", -1);
if (fields.length != 5 || !fields[0].equals("@iris-structure") || !fields[1].equals("v1")) {
return null;
}
try {
String objectKey = decodeCanonicalKey(fields[2]);
int placementId = Integer.parseInt(fields[3]);
String structureKey = decodeCanonicalKey(fields[4]);
if (objectKey.isBlank() || structureKey.isBlank()) {
return null;
}
return new Decoded(objectKey, placementId, structureKey);
} catch (IllegalArgumentException exception) {
return null;
}
}
private static Decoded decodeLegacy(String marker) {
int separator = marker.indexOf('@');
if (separator <= 0 || separator != marker.lastIndexOf('@') || separator == marker.length() - 1) {
return null;
}
String objectKey = marker.substring(0, separator);
if (objectKey.isEmpty() || objectKey.equals("null")) {
return null;
}
try {
return new Decoded(objectKey, Integer.parseInt(marker.substring(separator + 1)), null);
} catch (NumberFormatException exception) {
return null;
}
}
private static String requireKey(String key, String name) {
String required = Objects.requireNonNull(key, name);
if (required.isBlank()) {
throw new IllegalArgumentException(name + " must not be blank");
}
return required;
}
private static String encodeKey(String key) {
return Base64.getUrlEncoder().withoutPadding().encodeToString(key.getBytes(StandardCharsets.UTF_8));
}
private static String decodeCanonicalKey(String key) {
String decoded = new String(Base64.getUrlDecoder().decode(key), StandardCharsets.UTF_8);
if (!encodeKey(decoded).equals(key)) {
throw new IllegalArgumentException("Non-canonical marker key");
}
return decoded;
}
public record Decoded(String objectKey, int placementId, String structureKey) {
public boolean structureAware() {
return structureKey != null;
}
}
}
@@ -0,0 +1,148 @@
package art.arcane.iris.engine.framework;
import art.arcane.iris.engine.IrisComplex;
import art.arcane.iris.engine.object.world.biome.IrisBiome;
import art.arcane.iris.engine.object.world.region.IrisRegion;
import art.arcane.iris.engine.object.structure.IrisStructurePlacement;
import art.arcane.volmlib.util.collection.KList;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.Collections;
import java.util.IdentityHashMap;
import java.util.List;
import java.util.Objects;
import java.util.Set;
public final class StructurePlacementScope {
private static final List<CachedScopeIndex> SCOPE_INDEXES = new ArrayList<>();
private StructurePlacementScope() {
}
public static KList<IrisStructurePlacement> placementsAt(Engine engine, int chunkX, int chunkZ) {
Engine activeEngine = Objects.requireNonNull(engine, "Structure placement scope requires an engine");
IrisComplex complex = activeEngine.getComplex();
int blockX = (chunkX << 4) + 8;
int blockZ = (chunkZ << 4) + 8;
KList<IrisStructurePlacement> placements = new KList<>();
Set<IrisStructurePlacement> seen = Collections.newSetFromMap(new IdentityHashMap<>());
ScopeIndex index = scopeIndex(activeEngine);
if (complex != null) {
if (index.biome()) {
IrisBiome biome = complex.getTrueBiomeStream().get(blockX, blockZ);
addUnique(placements, seen, biome == null ? null : biome.getStructures());
}
if (index.caveBiome()) {
IrisBiome caveBiome = complex.getCaveBiomeStream().get(blockX, blockZ);
addCaveUnique(placements, seen, caveBiome == null ? null : caveBiome.getStructures());
}
if (index.region()) {
IrisRegion region = complex.getRegionStream().get(blockX, blockZ);
addUnique(placements, seen, region == null ? null : region.getStructures());
}
}
if (index.dimension()) {
addUnique(placements, seen, activeEngine.getDimension().getStructures());
}
return placements;
}
private static ScopeIndex scopeIndex(Engine engine) {
int revision = engine.getCacheID();
synchronized (SCOPE_INDEXES) {
for (int i = SCOPE_INDEXES.size() - 1; i >= 0; i--) {
CachedScopeIndex cached = SCOPE_INDEXES.get(i);
Engine indexedEngine = cached.engine().get();
if (indexedEngine == null) {
SCOPE_INDEXES.remove(i);
continue;
}
if (indexedEngine == engine) {
if (cached.revision() == revision) {
return cached.index();
}
SCOPE_INDEXES.remove(i);
break;
}
}
ScopeIndex index = buildScopeIndex(engine);
SCOPE_INDEXES.add(new CachedScopeIndex(new WeakReference<>(engine), revision, index));
return index;
}
}
private static ScopeIndex buildScopeIndex(Engine engine) {
boolean biome = false;
boolean caveBiome = false;
KList<IrisBiome> allBiomes = engine.getAllBiomes();
if (allBiomes == null) {
biome = true;
caveBiome = true;
} else {
for (IrisBiome candidate : allBiomes) {
KList<IrisStructurePlacement> structures = candidate.getStructures();
if (structures == null || structures.isEmpty()) {
continue;
}
biome = true;
for (IrisStructurePlacement placement : structures) {
if (placement != null && placement.resolvedAnchor().isCave()) {
caveBiome = true;
break;
}
}
}
}
boolean region = false;
if (engine.getDimension() != null) {
KList<IrisRegion> allRegions = engine.getDimension().getAllRegions(engine);
if (allRegions == null) {
region = true;
} else {
for (IrisRegion candidate : allRegions) {
if (candidate.getStructures() != null && !candidate.getStructures().isEmpty()) {
region = true;
break;
}
}
}
}
boolean dimension = engine.getDimension() != null
&& engine.getDimension().getStructures() != null
&& !engine.getDimension().getStructures().isEmpty();
return new ScopeIndex(biome, caveBiome, region, dimension);
}
private static void addUnique(KList<IrisStructurePlacement> destination,
Set<IrisStructurePlacement> seen,
KList<IrisStructurePlacement> source) {
if (source == null) {
return;
}
for (IrisStructurePlacement placement : source) {
if (placement != null && seen.add(placement)) {
destination.add(placement);
}
}
}
private static void addCaveUnique(KList<IrisStructurePlacement> destination,
Set<IrisStructurePlacement> seen,
KList<IrisStructurePlacement> source) {
if (source == null) {
return;
}
for (IrisStructurePlacement placement : source) {
if (placement != null && placement.resolvedAnchor().isCave() && seen.add(placement)) {
destination.add(placement);
}
}
}
private record CachedScopeIndex(WeakReference<Engine> engine, int revision, ScopeIndex index) {
}
private record ScopeIndex(boolean biome, boolean caveBiome, boolean region, boolean dimension) {
}
}
@@ -0,0 +1,127 @@
/*
* 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.engine.object.world.IrisWorld;
import art.arcane.iris.spi.IrisPlatforms;
import art.arcane.volmlib.util.collection.KList;
import com.github.benmanes.caffeine.cache.Cache;
import com.github.benmanes.caffeine.cache.Caffeine;
import java.util.Collections;
import java.util.LinkedHashSet;
import java.util.Locale;
import java.util.Objects;
import java.util.Set;
/**
* Determines which vanilla/datapack structures can ever generate in a world, using the same biome
* gate vanilla applies: a structure is reachable when its biome filter intersects the set of vanilla
* biomes the pack actually produces (its {@code possibleBiomes}). Structures whose required biomes are
* never produced cannot generate and must not be scanned for by {@code /locate} or {@code /iris find}
* (an unbounded scan for an absent biome is what stalls the server).
*
* <p>The reachable set is fixed per live engine/world and is rebuilt after hotload.
*/
public final class StructureReachability {
private static final Cache<Engine, Set<String>> REACHABLE_CACHE = Caffeine.newBuilder().weakKeys().build();
private StructureReachability() {
}
public static Set<String> reachableKeys(Engine engine) {
Engine activeEngine = Objects.requireNonNull(engine, "Structure reachability requires an engine");
if (activeEngine.getData() == null) {
throw new IllegalStateException("Structure reachability requires a bound pack data loader");
}
return REACHABLE_CACHE.get(activeEngine, ignored -> build(activeEngine));
}
public static boolean isReachable(Engine engine, String structureKey) {
String normalizedStructureKey = normalizeStructureKey(structureKey);
return reachableKeys(engine).contains(normalizedStructureKey);
}
public static void invalidate(Engine engine) {
if (engine == null) {
return;
}
REACHABLE_CACHE.invalidate(engine);
}
private static Set<String> build(Engine engine) {
IrisWorld world = engine.getWorld();
if (world == null) {
throw new IllegalStateException("Structure reachability requires a bound Iris world");
}
if (world.platformWorld() == null) {
throw new IllegalStateException("Structure reachability requires a bound platform world");
}
Set<String> reachable = new LinkedHashSet<>();
for (String key : IrisPlatforms.get().structureHooks().reachableStructureKeys(world.platformWorld())) {
if (key == null || key.isBlank()) {
throw new IllegalStateException("Platform structure reachability returned a blank registry key");
}
reachable.add(key.toLowerCase(Locale.ROOT));
}
return Collections.unmodifiableSet(reachable);
}
/**
* The vanilla biome keys (e.g. {@code minecraft:taiga}) from a structure's filter that the pack
* does not produce. An empty list means the structure is reachable. Used by the structure verify
* diagnostic to explain why a structure cannot generate.
*/
public static KList<String> missingBiomeKeys(Engine engine, String structureKey) {
KList<String> missing = new KList<>();
Engine activeEngine = Objects.requireNonNull(engine, "Structure biome diagnostics require an engine");
String normalizedStructureKey = normalizeStructureKey(structureKey);
IrisWorld world = activeEngine.getWorld();
if (world == null) {
throw new IllegalStateException("Structure biome diagnostics require a bound Iris world");
}
if (world.platformWorld() == null) {
throw new IllegalStateException("Structure biome diagnostics require a bound platform world");
}
Set<String> possible = new LinkedHashSet<>();
for (String key : IrisPlatforms.get().structureHooks().possibleBiomeKeys(world.platformWorld())) {
if (key == null || key.isBlank()) {
throw new IllegalStateException("Platform structure biome query returned a blank possible-biome key");
}
possible.add(key.toLowerCase(Locale.ROOT));
}
for (String biomeKey : IrisPlatforms.get().structureHooks().structureBiomeKeys(normalizedStructureKey)) {
if (biomeKey == null || biomeKey.isBlank()) {
throw new IllegalStateException("Platform structure biome query returned a blank required-biome key for "
+ normalizedStructureKey);
}
if (!possible.contains(biomeKey.toLowerCase(Locale.ROOT))) {
missing.add(biomeKey);
}
}
return missing;
}
private static String normalizeStructureKey(String structureKey) {
if (structureKey == null || structureKey.isBlank()) {
throw new IllegalArgumentException("Registered structure key must not be blank");
}
return structureKey.trim().toLowerCase(Locale.ROOT);
}
}
@@ -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,101 @@
package art.arcane.iris.engine.framework.structure;
import art.arcane.iris.engine.object.structure.jigsaw.IrisJigsawPiece;
import art.arcane.iris.engine.object.structure.jigsaw.IrisJigsawPool;
import art.arcane.iris.engine.object.prefab.IrisObject;
import art.arcane.iris.engine.object.structure.IrisStructure;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
public final class CompiledStructureGraph {
private final IrisStructure structure;
private final Map<String, IrisJigsawPool> pools;
private final Map<String, IrisJigsawPiece> pieces;
private final Map<String, IrisObject> objects;
private final Set<String> reachablePools;
private final Set<String> reachablePieces;
private CompiledStructureGraph(Builder builder) {
structure = builder.structure;
pools = Collections.unmodifiableMap(new LinkedHashMap<>(builder.pools));
pieces = Collections.unmodifiableMap(new LinkedHashMap<>(builder.pieces));
objects = Collections.unmodifiableMap(new LinkedHashMap<>(builder.objects));
reachablePools = Collections.unmodifiableSet(new LinkedHashSet<>(builder.reachablePools));
reachablePieces = Collections.unmodifiableSet(new LinkedHashSet<>(builder.reachablePieces));
}
static Builder builder(IrisStructure structure) {
return new Builder(structure);
}
public IrisStructure getStructure() {
return structure;
}
public String getStructureKey() {
String key = structure.getLoadKey();
return key == null || key.isBlank() ? "<unloaded>" : key;
}
public Map<String, IrisJigsawPool> getPools() {
return pools;
}
public Map<String, IrisJigsawPiece> getPieces() {
return pieces;
}
public Map<String, IrisObject> getObjects() {
return objects;
}
public Set<String> getReachablePools() {
return reachablePools;
}
public Set<String> getReachablePieces() {
return reachablePieces;
}
static final class Builder {
private final IrisStructure structure;
private final Map<String, IrisJigsawPool> pools = new LinkedHashMap<>();
private final Map<String, IrisJigsawPiece> pieces = new LinkedHashMap<>();
private final Map<String, IrisObject> objects = new LinkedHashMap<>();
private final Set<String> reachablePools = new LinkedHashSet<>();
private final Set<String> reachablePieces = new LinkedHashSet<>();
private Builder(IrisStructure structure) {
this.structure = Objects.requireNonNull(structure);
}
Map<String, IrisJigsawPool> pools() {
return pools;
}
Map<String, IrisJigsawPiece> pieces() {
return pieces;
}
Map<String, IrisObject> objects() {
return objects;
}
Set<String> reachablePools() {
return reachablePools;
}
Set<String> reachablePieces() {
return reachablePieces;
}
CompiledStructureGraph build() {
return new CompiledStructureGraph(this);
}
}
}
@@ -0,0 +1,386 @@
package art.arcane.iris.engine.framework.structure;
import art.arcane.iris.engine.object.prefab.IrisObject;
import com.google.gson.JsonElement;
import com.google.gson.JsonParser;
import java.io.ByteArrayInputStream;
import java.io.DataInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.LinkedHashSet;
import java.util.Objects;
import java.util.Set;
public final class IrisObjectFrameReader {
private static final String HEADER = "Iris V2 IOB;";
private static final int MAX_FILE_BYTES = 64 * 1024 * 1024;
private static final int MAX_TILE_COUNT = 65_536;
private static final int MAX_CANDIDATE_OFFSETS = 1_024;
private static final long MAX_TILE_PARSE_STATES = 262_144L;
private static final int MAX_LEGACY_SIGN_COLOR_INDEX = 15;
private IrisObjectFrameReader() {
}
public static IrisObject readBounds(InputStream stream, String resourceName) throws IOException {
String activeResourceName = resourceName == null || resourceName.isBlank()
? "<unknown>" : resourceName;
try {
byte[] content = readLimitedContent(Objects.requireNonNull(stream), activeResourceName);
return readBounds(content, activeResourceName);
} catch (IOException e) {
if (e.getMessage() != null && e.getMessage().startsWith("Malformed Iris object resource ")) {
throw e;
}
throw malformed(activeResourceName, e.getMessage() == null
? e.getClass().getSimpleName() : e.getMessage());
} catch (RuntimeException e) {
throw malformed(activeResourceName, e.getMessage() == null
? e.getClass().getSimpleName() : e.getMessage());
}
}
private static IrisObject readBounds(byte[] content, String resourceName) throws IOException {
ByteArrayInputStream bytes = new ByteArrayInputStream(content);
DataInputStream input = new DataInputStream(bytes);
int width = input.readInt();
int height = input.readInt();
int depth = input.readInt();
long volume = requireDimensions(resourceName, width, height, depth);
if (!HEADER.equals(input.readUTF())) {
throw malformed(resourceName, "invalid header");
}
int paletteSize = input.readShort();
if (paletteSize < 0) {
throw malformed(resourceName, "palette exceeds the signed IOB limit");
}
for (int index = 0; index < paletteSize; index++) {
if (input.readUTF().isBlank()) {
throw malformed(resourceName, "palette entry " + index + " is blank");
}
}
int blockCount = input.readInt();
if (blockCount < 0 || blockCount > volume || blockCount > 0 && paletteSize == 0) {
throw malformed(resourceName, "invalid block count " + blockCount);
}
for (int index = 0; index < blockCount; index++) {
int x = input.readShort();
int y = input.readShort();
int z = input.readShort();
int paletteIndex = input.readShort();
requirePosition(resourceName, "block", index, x, y, z, width, height, depth);
if (paletteIndex < 0 || paletteIndex >= paletteSize) {
throw malformed(resourceName, "block " + index
+ " references invalid palette index " + paletteIndex);
}
}
int tileCount = input.readInt();
if (tileCount < 0 || tileCount > volume) {
throw malformed(resourceName, "invalid tile count " + tileCount);
}
if (tileCount > MAX_TILE_COUNT) {
throw malformed(resourceName, "tile count " + tileCount
+ " exceeds limit " + MAX_TILE_COUNT);
}
int tileStart = content.length - bytes.available();
requireCompleteTileFraming(content, tileStart, tileCount, width, height, depth, resourceName);
return new IrisObject(width, height, depth);
}
private static void requireCompleteTileFraming(
byte[] content,
int tileStart,
int tileCount,
int width,
int height,
int depth,
String resourceName
) throws IOException {
Set<Integer> offsets = Set.of(tileStart);
long parseStates = 0L;
for (int tileIndex = 0; tileIndex < tileCount; tileIndex++) {
Set<Integer> nextOffsets = new LinkedHashSet<>();
TileFailureTracker failures = new TileFailureTracker();
for (int offset : offsets) {
parseStates++;
requireParseStateBudget(resourceName, tileIndex, parseStates);
TilePrefix prefix = readTilePrefix(
content, offset, width, height, depth, tileIndex, failures);
if (prefix == null) {
continue;
}
int modernEnd = readModernTileEnd(
content, prefix.payloadOffset(), tileIndex, failures);
if (modernEnd >= 0) {
addCandidateOffset(resourceName, tileIndex, nextOffsets, modernEnd);
}
for (int legacyEnd : readLegacyTileEnds(
content, prefix.payloadOffset(), tileIndex, failures)) {
addCandidateOffset(resourceName, tileIndex, nextOffsets, legacyEnd);
}
}
if (nextOffsets.isEmpty()) {
throw malformed(resourceName, failures.detailOr(
"tile " + tileIndex + " is truncated or malformed"));
}
offsets = nextOffsets;
}
if (!offsets.contains(content.length)) {
throw malformed(resourceName, "tile records leave trailing or incomplete data");
}
}
private static TilePrefix readTilePrefix(
byte[] content,
int offset,
int width,
int height,
int depth,
int tileIndex,
TileFailureTracker failures
) {
try {
ByteArrayInputStream bytes = slice(content, offset);
DataInputStream input = new DataInputStream(bytes);
int x = input.readShort();
int y = input.readShort();
int z = input.readShort();
if (!withinSignedObjectAxis(x, width) || !withinSignedObjectAxis(y, height)
|| !withinSignedObjectAxis(z, depth)) {
failures.record("tile " + tileIndex + " position " + x + "," + y + "," + z
+ " is outside object bounds", 20);
return null;
}
return new TilePrefix(content.length - bytes.available());
} catch (IOException | RuntimeException e) {
return null;
}
}
private static int readModernTileEnd(
byte[] content,
int offset,
int tileIndex,
TileFailureTracker failures
) {
try {
ByteArrayInputStream bytes = slice(content, offset);
DataInputStream input = new DataInputStream(bytes);
String material = input.readUTF();
if (material.isBlank()) {
failures.record("tile " + tileIndex + " modern material is blank", 40);
return -1;
}
JsonElement properties = JsonParser.parseString(input.readUTF());
if (!properties.isJsonObject()) {
failures.record("tile " + tileIndex
+ " modern properties are not a JSON object", 30);
return -1;
}
return content.length - bytes.available();
} catch (IOException | RuntimeException e) {
return -1;
}
}
private static Set<Integer> readLegacyTileEnds(
byte[] content,
int offset,
int tileIndex,
TileFailureTracker failures
) {
try {
ByteArrayInputStream bytes = slice(content, offset);
DataInputStream input = new DataInputStream(bytes);
int id = input.readShort();
return switch (id) {
case 0 -> singletonEnd(content, readLegacySign(input, bytes, tileIndex, failures));
case 1 -> readLegacySpawnerEnds(content, content.length - bytes.available());
case 2 -> readLegacyBannerEnds(content, input, bytes);
case 3 -> singletonEnd(content, readLegacyLootable(input, bytes));
default -> Set.of();
};
} catch (IOException | RuntimeException e) {
return Set.of();
}
}
private static int readLegacySign(
DataInputStream input,
ByteArrayInputStream bytes,
int tileIndex,
TileFailureTracker failures
) throws IOException {
input.readUTF();
input.readUTF();
input.readUTF();
input.readUTF();
int colorIndex = input.readByte();
if (colorIndex < 0 || colorIndex > MAX_LEGACY_SIGN_COLOR_INDEX) {
failures.record("tile " + tileIndex + " legacy sign color index " + colorIndex
+ " is outside 0.." + MAX_LEGACY_SIGN_COLOR_INDEX, 50);
throw new IOException("Invalid legacy sign color index");
}
return bytes.available();
}
private static Set<Integer> readLegacySpawnerEnds(byte[] content, int payloadOffset) {
Set<Integer> ends = new LinkedHashSet<>();
try {
ByteArrayInputStream keyedBytes = slice(content, payloadOffset);
new DataInputStream(keyedBytes).readUTF();
ends.add(content.length - keyedBytes.available());
} catch (IOException | RuntimeException ignored) {
}
if (payloadOffset <= content.length - Short.BYTES) {
ends.add(payloadOffset + Short.BYTES);
}
return Set.copyOf(ends);
}
private static Set<Integer> readLegacyBannerEnds(
byte[] content,
DataInputStream input,
ByteArrayInputStream bytes
) throws IOException {
input.readUnsignedByte();
int patternCount = input.readUnsignedByte();
int patternsOffset = content.length - bytes.available();
Set<Integer> ends = new LinkedHashSet<>();
try {
ByteArrayInputStream keyedBytes = slice(content, patternsOffset);
DataInputStream keyedInput = new DataInputStream(keyedBytes);
for (int index = 0; index < patternCount; index++) {
keyedInput.readUnsignedByte();
keyedInput.readUTF();
}
ends.add(content.length - keyedBytes.available());
} catch (IOException | RuntimeException ignored) {
}
long legacyEnd = (long) patternsOffset + (long) patternCount * 2L;
if (legacyEnd <= content.length) {
ends.add((int) legacyEnd);
}
return Set.copyOf(ends);
}
private static int readLegacyLootable(DataInputStream input, ByteArrayInputStream bytes) throws IOException {
input.readUTF();
input.readUTF();
input.readLong();
return bytes.available();
}
private static Set<Integer> singletonEnd(byte[] content, int remaining) {
return Set.of(content.length - remaining);
}
private static byte[] readLimitedContent(InputStream stream, String resourceName) throws IOException {
return readLimitedContent(stream, resourceName, MAX_FILE_BYTES);
}
static byte[] readLimitedContent(
InputStream stream,
String resourceName,
int maximumBytes
) throws IOException {
byte[] content = stream.readNBytes(maximumBytes + 1);
if (content.length > maximumBytes) {
throw malformed(resourceName, "file exceeds " + maximumBytes + "-byte limit");
}
return content;
}
private static void addCandidateOffset(
String resourceName,
int tileIndex,
Set<Integer> offsets,
int offset
) throws IOException {
offsets.add(offset);
if (offsets.size() > MAX_CANDIDATE_OFFSETS) {
throw malformed(resourceName, "tile " + tileIndex + " exceeds candidate-offset limit "
+ MAX_CANDIDATE_OFFSETS);
}
}
private static void requireParseStateBudget(
String resourceName,
int tileIndex,
long parseStates
) throws IOException {
if (parseStates > MAX_TILE_PARSE_STATES) {
throw malformed(resourceName, "tile " + tileIndex + " exceeds parse-state limit "
+ MAX_TILE_PARSE_STATES);
}
}
private static ByteArrayInputStream slice(byte[] content, int offset) {
if (offset < 0 || offset > content.length) {
throw new IllegalArgumentException("Invalid IOB frame offset " + offset);
}
return new ByteArrayInputStream(content, offset, content.length - offset);
}
private static long requireDimensions(String resourceName, int width, int height, int depth) throws IOException {
if (width < 1 || height < 1 || depth < 1) {
throw malformed(resourceName, "invalid dimensions " + width + "x" + height + "x" + depth);
}
try {
return Math.multiplyExact(Math.multiplyExact((long) width, height), depth);
} catch (ArithmeticException e) {
throw malformed(resourceName, "dimensions overflow the IOB volume limit");
}
}
private static void requirePosition(
String resourceName,
String type,
int index,
int x,
int y,
int z,
int width,
int height,
int depth
) throws IOException {
if (!withinSignedObjectAxis(x, width) || !withinSignedObjectAxis(y, height)
|| !withinSignedObjectAxis(z, depth)) {
throw malformed(resourceName, type + " " + index + " position "
+ x + "," + y + "," + z + " is outside object bounds");
}
}
private static boolean withinSignedObjectAxis(int coordinate, int size) {
int center = size / 2;
return coordinate >= -center && coordinate < size - center;
}
private static IOException malformed(String resourceName, String detail) {
return new IOException("Malformed Iris object resource " + resourceName + ": " + detail);
}
private record TilePrefix(int payloadOffset) {
}
private static final class TileFailureTracker {
private String detail;
private int priority = Integer.MIN_VALUE;
private void record(String candidateDetail, int candidatePriority) {
if (candidatePriority <= priority) {
return;
}
detail = candidateDetail;
priority = candidatePriority;
}
private String detailOr(String fallback) {
return detail == null ? fallback : detail;
}
}
}
@@ -0,0 +1,104 @@
package art.arcane.iris.engine.framework.structure;
import art.arcane.iris.engine.object.structure.jigsaw.IrisJigsawPiece;
import art.arcane.iris.engine.object.structure.jigsaw.IrisJigsawPieceEntry;
import art.arcane.iris.engine.object.structure.jigsaw.IrisJigsawPieceRules;
import art.arcane.iris.engine.object.structure.jigsaw.IrisJigsawPool;
import art.arcane.iris.engine.object.structure.jigsaw.IrisJigsawThemeSet;
import art.arcane.iris.engine.object.structure.IrisStructure;
import art.arcane.volmlib.util.math.RNG;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
public final class JigsawPoolSelection {
private JigsawPoolSelection() {
}
public static String directFallbackKey(IrisJigsawPool pool) {
Objects.requireNonNull(pool);
return normalize(pool.getFallback());
}
public static List<String> candidatePoolKeys(
String primaryKey,
IrisJigsawPool primaryPool,
boolean includePrimary
) {
Objects.requireNonNull(primaryPool);
String normalizedPrimary = normalize(primaryKey);
String directFallback = directFallbackKey(primaryPool);
if (!includePrimary) {
return directFallback.isEmpty() ? List.of() : List.of(directFallback);
}
if (normalizedPrimary.isEmpty()) {
return List.of();
}
return directFallback.isEmpty()
? List.of(normalizedPrimary)
: List.of(normalizedPrimary, directFallback);
}
public static String selectTheme(IrisStructure structure, RNG rng) {
IrisStructure activeStructure = Objects.requireNonNull(structure);
RNG activeRng = Objects.requireNonNull(rng);
if (activeStructure.getThemeSets() == null || activeStructure.getThemeSets().isEmpty()) {
return "";
}
List<IrisJigsawThemeSet> themes = new ArrayList<>(activeStructure.getThemeSets().size());
long totalWeight = 0L;
for (IrisJigsawThemeSet theme : activeStructure.getThemeSets()) {
if (theme == null || normalize(theme.getKey()).isEmpty() || theme.getWeight() <= 0) {
throw new IllegalArgumentException("Jigsaw theme sets require non-blank keys and positive weights");
}
themes.add(theme);
totalWeight = Math.addExact(totalWeight, theme.getWeight());
}
if (themes.size() == 1) {
return normalize(themes.getFirst().getKey());
}
long target = activeRng.nextLong(totalWeight);
for (IrisJigsawThemeSet theme : themes) {
target -= theme.getWeight();
if (target < 0L) {
return normalize(theme.getKey());
}
}
return normalize(themes.getLast().getKey());
}
public static boolean passesChance(IrisJigsawPieceEntry entry, RNG rng) {
IrisJigsawPieceEntry activeEntry = Objects.requireNonNull(entry);
RNG activeRng = Objects.requireNonNull(rng);
double chance = activeEntry.getChance();
if (!Double.isFinite(chance) || chance < 0D || chance > 1D) {
throw new IllegalArgumentException("Jigsaw pool membership chance must be finite and within 0 and 1");
}
if (!activeEntry.requiresChanceRoll()) {
return chance >= 1D;
}
return activeEntry.passesChance(activeRng.nextDouble());
}
public static boolean pieceEligible(
IrisJigsawPiece piece,
String selectedTheme,
int depth,
int existingPlacements
) {
IrisJigsawPiece activePiece = Objects.requireNonNull(piece);
IrisJigsawPieceRules rules = activePiece.resolvedRules();
return activePiece.supportsTheme(normalize(selectedTheme))
&& rules.allowsDepth(depth)
&& rules.allowsPlacement(existingPlacements);
}
public static boolean needsMinimumPlacement(IrisJigsawPiece piece, int existingPlacements) {
return Objects.requireNonNull(piece).resolvedRules().requiresMorePlacements(existingPlacements);
}
private static String normalize(String value) {
return value == null ? "" : value.trim();
}
}
@@ -0,0 +1,139 @@
package art.arcane.iris.engine.framework.structure;
import art.arcane.iris.engine.object.structure.jigsaw.IrisJigsawPiece;
import art.arcane.iris.engine.object.structure.jigsaw.IrisJigsawWorkcell;
import art.arcane.iris.engine.object.structure.jigsaw.IrisJigsawWorkcellArchetype;
import art.arcane.iris.engine.object.prefab.IrisObject;
import art.arcane.iris.engine.object.value.IrisPosition;
import art.arcane.iris.engine.object.structure.IrisStructure;
import java.util.Collections;
import java.util.EnumMap;
import java.util.Map;
import java.util.Objects;
public final class PlanarJigsawWorkcellResolver {
public static final int DEFAULT_SIZE = 16;
public static final int MAX_WIDTH = 128;
public static final int MAX_HEIGHT = 192;
public static final int MAX_DEPTH = 128;
public static final long MAX_VOLUME = 2_097_152L;
private PlanarJigsawWorkcellResolver() {
}
public static Map<IrisJigsawWorkcellArchetype, ResolvedWorkcell> resolve(IrisStructure structure) {
IrisStructure source = Objects.requireNonNull(structure, "Planar jigsaw structure");
EnumMap<IrisJigsawWorkcellArchetype, ResolvedWorkcell> resolved =
new EnumMap<>(IrisJigsawWorkcellArchetype.class);
if (source.getPlanarWorkcells() == null || source.getPlanarWorkcells().isEmpty()) {
IrisPosition fallback = source.getCellSize() == null
? new IrisPosition(DEFAULT_SIZE, DEFAULT_SIZE, DEFAULT_SIZE)
: source.getCellSize();
for (IrisJigsawWorkcellArchetype archetype : IrisJigsawWorkcellArchetype.values()) {
ResolvedWorkcell workcell = new ResolvedWorkcell(
archetype,
"",
fallback.getX(),
fallback.getY(),
fallback.getZ(),
true);
validate(workcell);
resolved.put(archetype, workcell);
}
return Collections.unmodifiableMap(resolved);
}
for (IrisJigsawWorkcell configured : source.getPlanarWorkcells()) {
if (configured == null || configured.getArchetype() == null) {
throw new IllegalArgumentException("Planar jigsaw workcells require an archetype");
}
ResolvedWorkcell workcell = new ResolvedWorkcell(
configured.getArchetype(),
normalizeDisplayName(configured.getDisplayName()),
configured.getWidth(),
configured.getHeight(),
configured.getDepth(),
configured.isEnabled());
validate(workcell);
if (resolved.putIfAbsent(workcell.archetype(), workcell) != null) {
throw new IllegalArgumentException(
"Planar jigsaw workcell " + workcell.archetype() + " is configured more than once");
}
}
if (resolved.size() != IrisJigsawWorkcellArchetype.values().length) {
for (IrisJigsawWorkcellArchetype archetype : IrisJigsawWorkcellArchetype.values()) {
if (!resolved.containsKey(archetype)) {
throw new IllegalArgumentException("Planar jigsaw workcell " + archetype + " is missing");
}
}
}
return Collections.unmodifiableMap(resolved);
}
public static ResolvedWorkcell workcell(
Map<IrisJigsawWorkcellArchetype, ResolvedWorkcell> workcells,
IrisJigsawPiece piece
) {
Map<IrisJigsawWorkcellArchetype, ResolvedWorkcell> resolved = Objects.requireNonNull(
workcells,
"Planar jigsaw workcells");
IrisJigsawWorkcellArchetype archetype = IrisJigsawWorkcellArchetype.fromPiece(piece);
ResolvedWorkcell workcell = resolved.get(archetype);
if (workcell == null) {
throw new IllegalArgumentException("Planar jigsaw workcell " + archetype + " is not configured");
}
return workcell;
}
public static IrisPosition canonicalDimensions(IrisJigsawPiece piece, IrisObject object) {
IrisJigsawPiece sourcePiece = Objects.requireNonNull(piece, "Planar jigsaw piece");
IrisObject sourceObject = Objects.requireNonNull(object, "Planar jigsaw object");
IrisJigsawWorkcellArchetype archetype = IrisJigsawWorkcellArchetype.fromPiece(sourcePiece);
int quarterTurns = archetype.sourceToCanonicalQuarterTurns(sourcePiece);
return Math.floorMod(quarterTurns, 2) == 0
? new IrisPosition(sourceObject.getW(), sourceObject.getH(), sourceObject.getD())
: new IrisPosition(sourceObject.getD(), sourceObject.getH(), sourceObject.getW());
}
public record ResolvedWorkcell(
IrisJigsawWorkcellArchetype archetype,
String displayName,
int width,
int height,
int depth,
boolean enabled
) {
public ResolvedWorkcell {
Objects.requireNonNull(archetype, "Planar jigsaw workcell archetype");
displayName = normalizeDisplayName(displayName);
}
public IrisPosition dimensions() {
return new IrisPosition(width, height, depth);
}
public boolean contains(IrisPosition dimensions) {
IrisPosition size = Objects.requireNonNull(dimensions, "Planar jigsaw object dimensions");
return size.getX() <= width && size.getY() <= height && size.getZ() <= depth;
}
}
private static String normalizeDisplayName(String displayName) {
return displayName == null ? "" : displayName.trim();
}
private static void validate(ResolvedWorkcell workcell) {
if (workcell.width() < 3 || workcell.width() > MAX_WIDTH
|| workcell.height() < 1 || workcell.height() > MAX_HEIGHT
|| workcell.depth() < 3 || workcell.depth() > MAX_DEPTH) {
throw new IllegalArgumentException("Planar jigsaw workcell " + workcell.archetype()
+ " dimensions must keep width/depth within 3..128 and height within 1..192");
}
long volume = (long) workcell.width() * workcell.height() * workcell.depth();
if (volume > MAX_VOLUME) {
throw new IllegalArgumentException("Planar jigsaw workcell " + workcell.archetype()
+ " volume cannot exceed " + MAX_VOLUME + " blocks");
}
}
}
@@ -0,0 +1,71 @@
package art.arcane.iris.engine.framework.structure;
import art.arcane.iris.engine.framework.PlacedStructurePiece;
import java.util.List;
import java.util.Objects;
public record StructureAssemblyResult(
StructureAssemblyStatus status,
List<PlacedStructurePiece> pieces,
String selectedTheme,
String detail
) {
public StructureAssemblyResult {
status = Objects.requireNonNull(status, "Structure assembly status");
pieces = List.copyOf(Objects.requireNonNull(pieces, "Structure assembly pieces"));
selectedTheme = normalize(selectedTheme);
detail = normalize(detail);
if (status == StructureAssemblyStatus.COMPLETE && pieces.isEmpty()) {
throw new IllegalArgumentException("A complete structure assembly must contain at least one piece");
}
if (status == StructureAssemblyStatus.INTENTIONAL_EMPTY && !pieces.isEmpty()) {
throw new IllegalArgumentException("An intentionally empty structure assembly cannot contain pieces");
}
if (status.isFailure() && detail.isEmpty()) {
throw new IllegalArgumentException("A failed structure assembly requires failure detail");
}
}
public static StructureAssemblyResult complete(
List<PlacedStructurePiece> pieces,
String selectedTheme
) {
return new StructureAssemblyResult(
StructureAssemblyStatus.COMPLETE,
pieces,
selectedTheme,
"");
}
public static StructureAssemblyResult intentionalEmpty(
String selectedTheme,
String detail
) {
return new StructureAssemblyResult(
StructureAssemblyStatus.INTENTIONAL_EMPTY,
List.of(),
selectedTheme,
detail);
}
public static StructureAssemblyResult failed(
StructureAssemblyStatus status,
List<PlacedStructurePiece> pieces,
String selectedTheme,
String detail
) {
if (Objects.requireNonNull(status, "Structure assembly failure status").isComplete()) {
throw new IllegalArgumentException("A failed structure assembly requires a failure status");
}
return new StructureAssemblyResult(status, pieces, selectedTheme, detail);
}
public boolean hasOutput() {
return status == StructureAssemblyStatus.COMPLETE && !pieces.isEmpty();
}
private static String normalize(String value) {
return value == null ? "" : value.trim();
}
}
@@ -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,99 @@
package art.arcane.iris.engine.framework.structure;
import art.arcane.iris.core.loader.IrisData;
import art.arcane.iris.engine.framework.StructureAssembler;
import art.arcane.iris.engine.object.value.IrisPosition;
import art.arcane.iris.engine.object.structure.IrisStructure;
import art.arcane.iris.spi.IrisLogging;
import art.arcane.volmlib.util.math.RNG;
import com.github.benmanes.caffeine.cache.Cache;
import com.github.benmanes.caffeine.cache.Caffeine;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
public final class StructureGraphCatalog {
private static final Cache<IrisData, ConcurrentMap<String, StructureGraphCompilation>> CACHE =
Caffeine.newBuilder().weakKeys().build();
private static final Cache<IrisData, ConcurrentMap<String, Boolean>> RUNTIME_OUTPUT =
Caffeine.newBuilder().weakKeys().build();
private static final List<Long> RUNTIME_SAMPLE_SEEDS = List.of(
0L, 1L, 2L, 3L, 5L, 8L, 13L, 21L, 34L, 55L, 89L, 144L, 233L, 377L, 610L, 987L);
private StructureGraphCatalog() {
}
public static StructureGraphCompilation compile(IrisData data, IrisStructure structure) {
IrisData activeData = Objects.requireNonNull(data);
IrisStructure activeStructure = Objects.requireNonNull(structure);
String structureKey = activeStructure.getLoadKey();
if (structureKey == null || structureKey.isBlank()) {
return compileAndReport(activeData, activeStructure);
}
ConcurrentMap<String, StructureGraphCompilation> catalog = CACHE.get(
activeData, ignored -> new ConcurrentHashMap<>());
return catalog.computeIfAbsent(structureKey, ignored -> compileAndReport(activeData, activeStructure));
}
public static void invalidate(IrisData data) {
if (data != null) {
CACHE.invalidate(data);
RUNTIME_OUTPUT.invalidate(data);
}
}
public static boolean guaranteesRuntimeOutput(IrisData data, IrisStructure structure) {
IrisData activeData = Objects.requireNonNull(data);
IrisStructure activeStructure = Objects.requireNonNull(structure);
if (!compile(activeData, activeStructure).guaranteesAssemblyOutput()) {
return false;
}
String structureKey = activeStructure.getLoadKey();
if (structureKey == null || structureKey.isBlank()) {
return sampleRuntimeAssembly(activeData, activeStructure);
}
ConcurrentMap<String, Boolean> catalog = RUNTIME_OUTPUT.get(
activeData, ignored -> new ConcurrentHashMap<>());
return catalog.computeIfAbsent(
structureKey, ignored -> sampleRuntimeAssembly(activeData, activeStructure));
}
private static StructureGraphCompilation compileAndReport(IrisData data, IrisStructure structure) {
StructureGraphCompilation compilation = StructureGraphCompiler.compile(
structure, StructureGraphResolver.forData(data));
String structureKey = structure.getLoadKey() == null || structure.getLoadKey().isBlank()
? "<unkeyed>" : structure.getLoadKey();
for (StructureGraphDiagnostic diagnostic : compilation.getDiagnostics()) {
String message = "[StructureGraph:" + structureKey + "] " + diagnostic.message();
if (diagnostic.severity() == StructureGraphDiagnostic.Severity.ERROR) {
IrisLogging.error(message);
} else {
IrisLogging.warn(message);
}
}
if (!compilation.isAssemblyViable()) {
IrisLogging.error("[StructureGraph:" + structureKey
+ "] Graph rejected because deterministic assembly did not complete.");
}
return compilation;
}
private static boolean sampleRuntimeAssembly(IrisData data, IrisStructure structure) {
for (long seed : RUNTIME_SAMPLE_SEEDS) {
try {
StructureAssembler assembler = StructureAssembler.forData(
data, structure, new IrisPosition(0, 64, 0));
StructureAssemblyResult result = assembler.assemble(new RNG(seed));
if (!result.hasOutput()) {
return false;
}
} catch (Throwable e) {
IrisLogging.reportError(e);
return false;
}
}
return true;
}
}
@@ -0,0 +1,242 @@
package art.arcane.iris.engine.framework.structure;
import art.arcane.iris.engine.object.structure.jigsaw.IrisJigsawConnector;
import art.arcane.iris.engine.object.structure.jigsaw.IrisJigsawBranchFailurePolicy;
import art.arcane.iris.engine.object.structure.jigsaw.IrisJigsawPiece;
import art.arcane.iris.engine.object.structure.jigsaw.IrisJigsawPieceEntry;
import art.arcane.iris.engine.object.structure.jigsaw.IrisJigsawPool;
import art.arcane.iris.engine.object.structure.jigsaw.IrisJigsawThemeSet;
import art.arcane.iris.engine.object.prefab.IrisObject;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
public final class StructureGraphCompilation {
private final CompiledStructureGraph graph;
private final List<StructureGraphDiagnostic> diagnostics;
private final List<StructureGraphAssemblySample> assemblySamples;
StructureGraphCompilation(Builder builder) {
graph = Objects.requireNonNull(builder.graph);
diagnostics = Collections.unmodifiableList(new ArrayList<>(builder.diagnostics));
assemblySamples = Collections.unmodifiableList(new ArrayList<>(builder.assemblySamples));
}
static Builder builder(CompiledStructureGraph graph) {
return new Builder(graph);
}
public CompiledStructureGraph getGraph() {
return graph;
}
public List<StructureGraphDiagnostic> getDiagnostics() {
return diagnostics;
}
public List<StructureGraphAssemblySample> getAssemblySamples() {
return assemblySamples;
}
public boolean hasErrors() {
for (StructureGraphDiagnostic diagnostic : diagnostics) {
if (diagnostic.severity() == StructureGraphDiagnostic.Severity.ERROR) {
return true;
}
}
return false;
}
public boolean isAssemblyViable() {
if (hasErrors() || assemblySamples.isEmpty()) {
return false;
}
for (StructureGraphAssemblySample sample : assemblySamples) {
if (!sample.outcome().isComplete()) {
return false;
}
}
return true;
}
public boolean guaranteesAssemblyOutput() {
if (!isAssemblyViable()) {
return false;
}
String startPoolKey = graph.getStructure().getStartPool();
if (startPoolKey == null || startPoolKey.isBlank()) {
return false;
}
IrisJigsawPool startPool = graph.getPools().get(startPoolKey.trim());
if (startPool == null || startPool.getPieces() == null || startPool.getPieces().isEmpty()) {
return false;
}
for (String theme : themes()) {
if (!startPoolGuaranteesOutput(startPool, theme)
|| !reachableBranchesCanTerminate(theme)) {
return false;
}
}
return true;
}
private boolean startPoolGuaranteesOutput(IrisJigsawPool startPool, String theme) {
boolean certainPhysicalEntry = false;
for (IrisJigsawPieceEntry entry : startPool.getPieces()) {
if (entry == null || entry.getWeight() <= 0 || !Double.isFinite(entry.getChance())
|| entry.getChance() <= 0D || entry.getChance() > 1D) {
continue;
}
if (entry.isEmpty()) {
return false;
}
IrisJigsawPiece piece = graph.getPieces().get(normalize(entry.getPiece()));
if (piece == null || !JigsawPoolSelection.pieceEligible(piece, theme, 0, 0)) {
continue;
}
IrisObject object = graph.getObjects().get(normalize(piece.getObject()));
if (object == null || !fitsStartRadius(object)) {
return false;
}
if (entry.getChance() == 1D) {
certainPhysicalEntry = true;
}
}
return certainPhysicalEntry;
}
private boolean reachableBranchesCanTerminate(String theme) {
for (String pieceKey : graph.getReachablePieces()) {
IrisJigsawPiece piece = graph.getPieces().get(pieceKey);
if (piece == null || piece.getConnectors() == null) {
return false;
}
if (!piece.supportsTheme(theme) || piece.resolvedRules().isTerminal()) {
continue;
}
for (IrisJigsawConnector connector : piece.getConnectors()) {
if (connector == null) {
return false;
}
IrisJigsawPool pool = graph.getPools().get(normalize(connector.getPool()));
if (pool == null) {
return false;
}
if (pool.requiresFallback(graph.getStructure().isRequireCaps())) {
if (!hasRequiredTerminal(pool, theme)) {
return false;
}
} else if (graph.getStructure().resolvedBranchFailurePolicy()
!= IrisJigsawBranchFailurePolicy.TERMINATE_BRANCH
&& !canTerminateWithoutPlacement(pool)) {
return false;
}
}
}
return true;
}
private boolean hasRequiredTerminal(IrisJigsawPool pool, String theme) {
String fallbackKey = JigsawPoolSelection.directFallbackKey(pool);
if (fallbackKey.isEmpty()) {
return false;
}
IrisJigsawPool fallback = graph.getPools().get(fallbackKey);
if (fallback == null || fallback.getPieces() == null) {
return false;
}
for (IrisJigsawPieceEntry entry : fallback.getPieces()) {
if (entry == null || entry.isEmpty() || entry.getWeight() <= 0 || entry.getChance() != 1D) {
continue;
}
IrisJigsawPiece piece = graph.getPieces().get(normalize(entry.getPiece()));
if (piece != null && piece.supportsTheme(theme) && piece.resolvedRules().isTerminal()) {
return true;
}
}
return false;
}
private boolean canTerminateWithoutPlacement(IrisJigsawPool pool) {
if (hasEmptyChoice(pool)) {
return true;
}
if (pool == null) {
return false;
}
String fallbackKey = JigsawPoolSelection.directFallbackKey(pool);
return !fallbackKey.isEmpty() && hasEmptyChoice(graph.getPools().get(fallbackKey));
}
private boolean hasEmptyChoice(IrisJigsawPool pool) {
if (pool == null || pool.getPieces() == null) {
return false;
}
if (pool.getPieces().isEmpty()) {
return true;
}
for (IrisJigsawPieceEntry entry : pool.getPieces()) {
if (entry != null && entry.getWeight() > 0 && entry.getChance() == 1D && entry.isEmpty()) {
return true;
}
}
return false;
}
private boolean fitsStartRadius(IrisObject object) {
long radius = (long) graph.getStructure().getMaxSizeChunks() * 16L;
return axisFitsRadius(object.getW(), radius) && axisFitsRadius(object.getD(), radius);
}
private List<String> themes() {
if (graph.getStructure().getThemeSets() == null || graph.getStructure().getThemeSets().isEmpty()) {
return List.of("");
}
List<String> themes = new ArrayList<>(graph.getStructure().getThemeSets().size());
for (IrisJigsawThemeSet theme : graph.getStructure().getThemeSets()) {
if (theme != null && theme.getKey() != null && !theme.getKey().isBlank()) {
themes.add(theme.getKey().trim());
}
}
return List.copyOf(themes);
}
private boolean axisFitsRadius(int size, long radius) {
if (size < 1 || radius < 1L) {
return false;
}
long minimum = -(size / 2L);
long maximum = minimum + size - 1L;
return minimum >= -radius && maximum <= radius;
}
private String normalize(String value) {
return value == null ? "" : value.trim();
}
static final class Builder {
private final CompiledStructureGraph graph;
private final List<StructureGraphDiagnostic> diagnostics = new ArrayList<>();
private final List<StructureGraphAssemblySample> assemblySamples = new ArrayList<>();
private Builder(CompiledStructureGraph graph) {
this.graph = Objects.requireNonNull(graph);
}
Builder diagnostics(List<StructureGraphDiagnostic> values) {
diagnostics.addAll(values);
return this;
}
Builder assemblySamples(List<StructureGraphAssemblySample> values) {
assemblySamples.addAll(values);
return this;
}
StructureGraphCompilation build() {
return new StructureGraphCompilation(this);
}
}
}
@@ -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,74 @@
package art.arcane.iris.engine.framework.structure;
import art.arcane.iris.core.loader.IrisData;
import art.arcane.iris.engine.object.structure.jigsaw.IrisJigsawPiece;
import art.arcane.iris.engine.object.structure.jigsaw.IrisJigsawPool;
import art.arcane.iris.engine.object.prefab.IrisObject;
import java.util.Objects;
public interface StructureGraphResolver {
IrisJigsawPool loadPool(String key);
IrisJigsawPiece loadPiece(String key);
IrisObject loadObject(String key);
static StructureGraphResolver forData(IrisData data) {
return new IrisDataStructureGraphResolver(Objects.requireNonNull(data));
}
static StructureGraphResolver forCompiledGraph(CompiledStructureGraph graph) {
return new CompiledStructureGraphResolver(Objects.requireNonNull(graph));
}
}
final class IrisDataStructureGraphResolver implements StructureGraphResolver {
private final IrisData data;
IrisDataStructureGraphResolver(IrisData data) {
this.data = data;
}
@Override
public IrisJigsawPool loadPool(String key) {
return data.load(IrisJigsawPool.class, key, false);
}
@Override
public IrisJigsawPiece loadPiece(String key) {
return data.load(IrisJigsawPiece.class, key, false);
}
@Override
public IrisObject loadObject(String key) {
return data.load(IrisObject.class, key, false);
}
}
final class CompiledStructureGraphResolver implements StructureGraphResolver {
private final CompiledStructureGraph graph;
CompiledStructureGraphResolver(CompiledStructureGraph graph) {
this.graph = graph;
}
@Override
public IrisJigsawPool loadPool(String key) {
return graph.getPools().get(normalize(key));
}
@Override
public IrisJigsawPiece loadPiece(String key) {
return graph.getPieces().get(normalize(key));
}
@Override
public IrisObject loadObject(String key) {
return graph.getObjects().get(normalize(key));
}
private static String normalize(String key) {
return key == null ? "" : key.trim();
}
}
@@ -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,201 @@
/*
* 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.structure;
import art.arcane.iris.core.structure.authoring.StructureResourceBundle;
import art.arcane.iris.engine.framework.StructureAssembler;
import art.arcane.iris.engine.object.structure.jigsaw.IrisJigsawPiece;
import art.arcane.iris.engine.object.structure.jigsaw.IrisJigsawPool;
import art.arcane.iris.engine.object.prefab.IrisObject;
import art.arcane.iris.engine.object.value.IrisPosition;
import art.arcane.iris.engine.object.structure.IrisStructure;
import art.arcane.volmlib.util.math.RNG;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
public final class StructureResourceBundleGraphCompiler {
private static final Gson GSON = new GsonBuilder().create();
private static final List<Long> ASSEMBLY_SEEDS = List.of(
0L, 1L, 2L, 3L, 5L, 8L, 13L, 21L, 34L, 55L, 89L, 144L, 233L, 377L, 610L, 987L);
private StructureResourceBundleGraphCompiler() {
}
public static List<StructureGraphCompilation> compile(StructureResourceBundle bundle) {
BundleGraph graph = parse(Objects.requireNonNull(bundle));
List<StructureGraphCompilation> compilations = new ArrayList<>(graph.structures().size());
for (IrisStructure structure : graph.structures().values()) {
compilations.add(StructureGraphCompiler.compile(structure, graph.resolver()));
}
return List.copyOf(compilations);
}
public static void requireViable(StructureResourceBundle bundle) {
BundleGraph graph = parse(Objects.requireNonNull(bundle));
if (graph.structures().isEmpty()) {
throw new StructureGraphValidationException("Structure bundle does not contain a root structure resource");
}
for (IrisStructure structure : graph.structures().values()) {
StructureGraphCompilation compilation = StructureGraphCompiler.compile(structure, graph.resolver());
if (!compilation.isAssemblyViable()) {
throw new StructureGraphValidationException(
"Structure bundle graph is not viable: " + viabilityFailure(compilation));
}
requireGeometryViable(compilation);
}
}
private static String viabilityFailure(StructureGraphCompilation compilation) {
for (StructureGraphDiagnostic diagnostic : compilation.getDiagnostics()) {
if (diagnostic.severity() == StructureGraphDiagnostic.Severity.ERROR) {
return diagnostic.message();
}
}
for (StructureGraphAssemblySample sample : compilation.getAssemblySamples()) {
StructureGraphAssemblySample.Outcome outcome = sample.outcome();
if (!outcome.isComplete()) {
return "sampled assembly at seed " + sample.seed() + " returned "
+ outcome.status() + ": " + outcome.detail();
}
}
return "deterministic assembly did not complete";
}
private static BundleGraph parse(StructureResourceBundle activeBundle) {
Map<String, IrisStructure> structures = new LinkedHashMap<>();
Map<String, IrisJigsawPool> pools = new LinkedHashMap<>();
Map<String, IrisJigsawPiece> pieces = new LinkedHashMap<>();
Map<String, IrisObject> objects = new LinkedHashMap<>();
for (StructureResourceBundle.Resource resource : activeBundle.resources().values()) {
String path = resource.relativePath();
if (matches(path, "structures/", ".json")) {
IrisStructure structure = readJson(resource, IrisStructure.class);
String key = key(path, "structures/", ".json");
structure.setLoadKey(key);
structures.put(key, structure);
} else if (matches(path, "jigsaw-pools/", ".json")) {
pools.put(key(path, "jigsaw-pools/", ".json"), readJson(resource, IrisJigsawPool.class));
} else if (matches(path, "jigsaw-pieces/", ".json")) {
pieces.put(key(path, "jigsaw-pieces/", ".json"), readJson(resource, IrisJigsawPiece.class));
} else if (matches(path, "objects/", ".iob")) {
objects.put(key(path, "objects/", ".iob"), readObjectBounds(resource));
}
}
return new BundleGraph(structures, new BundleResolver(pools, pieces, objects));
}
private static void requireGeometryViable(StructureGraphCompilation compilation) {
String structureKey = compilation.getGraph().getStructureKey();
for (long seed : ASSEMBLY_SEEDS) {
try {
StructureAssembler assembler = StructureAssembler.forCompilation(
compilation, new IrisPosition(0, 64, 0));
StructureAssemblyResult result = assembler.assemble(new RNG(seed));
if (result.status().isFailure()) {
throw new StructureGraphValidationException("Structure bundle graph '" + structureKey
+ "' fails sampled runtime geometry assembly at seed " + seed + ": "
+ result.status() + ": " + result.detail());
}
} catch (StructureGraphValidationException e) {
throw e;
} catch (RuntimeException e) {
throw new IllegalStateException("Structure bundle graph '" + structureKey
+ "' encountered an unexpected sampled runtime geometry failure at seed " + seed + ": "
+ e.getClass().getSimpleName() + ": " + failureMessage(e), e);
}
}
}
private static String failureMessage(RuntimeException exception) {
return exception.getMessage() == null || exception.getMessage().isBlank()
? "no failure detail" : exception.getMessage();
}
private static boolean matches(String path, String prefix, String suffix) {
return path.startsWith(prefix) && path.endsWith(suffix) && path.length() > prefix.length() + suffix.length();
}
private static String key(String path, String prefix, String suffix) {
return path.substring(prefix.length(), path.length() - suffix.length());
}
private static <T> T readJson(StructureResourceBundle.Resource resource, Class<T> type) {
T value;
try {
value = GSON.fromJson(new String(resource.content(), StandardCharsets.UTF_8), type);
} catch (RuntimeException e) {
throw new StructureGraphValidationException("Malformed structure resource " + resource.relativePath(), e);
}
if (value == null) {
throw new StructureGraphValidationException("Empty structure resource " + resource.relativePath());
}
return value;
}
private static IrisObject readObjectBounds(StructureResourceBundle.Resource resource) {
try (ByteArrayInputStream input = new ByteArrayInputStream(resource.content())) {
return IrisObjectFrameReader.readBounds(input, resource.relativePath());
} catch (IOException e) {
throw new StructureGraphValidationException(e.getMessage(), e);
}
}
private record BundleResolver(
Map<String, IrisJigsawPool> pools,
Map<String, IrisJigsawPiece> pieces,
Map<String, IrisObject> objects
) implements StructureGraphResolver {
private BundleResolver {
pools = Map.copyOf(pools);
pieces = Map.copyOf(pieces);
objects = Map.copyOf(objects);
}
@Override
public IrisJigsawPool loadPool(String key) {
return pools.get(key);
}
@Override
public IrisJigsawPiece loadPiece(String key) {
return pieces.get(key);
}
@Override
public IrisObject loadObject(String key) {
return objects.get(key);
}
}
private record BundleGraph(Map<String, IrisStructure> structures, BundleResolver resolver) {
private BundleGraph {
structures = Map.copyOf(structures);
Objects.requireNonNull(resolver);
}
}
}
@@ -0,0 +1,424 @@
package art.arcane.iris.engine.image;
import art.arcane.iris.engine.object.image.IrisImage;
import art.arcane.iris.engine.object.image.IrisImageMap;
import art.arcane.iris.engine.object.image.IrisImageMapOutOfBounds;
import art.arcane.iris.engine.object.image.IrisImageMapSampling;
import art.arcane.iris.engine.object.image.IrisImageMapType;
import java.util.Objects;
public final class CompiledIrisImageMap {
private final State state;
CompiledIrisImageMap(State state) {
this.state = Objects.requireNonNull(state, "Compiled image-map state");
}
public static CompiledIrisImageMap compile(IrisImageMap definition, IrisImage image) {
return IrisImageMapCompiler.compile(definition, image);
}
public IrisImageMap getDefinition() {
return state.definition();
}
public IrisImageMapSourceMetadata getSourceMetadata() {
return state.sourceMetadata();
}
public IrisImageMapType getType() {
return state.type();
}
public int getSourceWidth() {
return state.sourceMetadata().width();
}
public int getSourceHeight() {
return state.sourceMetadata().height();
}
public String getContentHash() {
return state.contentHash();
}
public String contentHash() {
return state.contentHash();
}
public CompiledIrisImageMap withoutDecodedValues() {
return state.scalarValues() == null && state.targetIndices() == null
? this
: new CompiledIrisImageMap(state.withoutDecodedValues());
}
public int getClippedPixelCount() {
return state.clippedPixelCount();
}
public int getUnknownColorPixelCount() {
return state.unknownColorPixelCount();
}
public boolean containsWorld(double worldX, double worldZ) {
if (!Double.isFinite(worldX) || !Double.isFinite(worldZ)) {
return false;
}
double sourceX = state.sourceTransform().sourceX(worldX, worldZ);
double sourceZ = state.sourceTransform().sourceZ(worldX, worldZ);
return validSourceCoordinate(sourceX, sourceZ)
&& sourceX >= 0D
&& sourceZ >= 0D
&& sourceX < state.sourceMetadata().width()
&& sourceZ < state.sourceMetadata().height();
}
public boolean containsWorldForSampling(double worldX, double worldZ) {
if (!Double.isFinite(worldX) || !Double.isFinite(worldZ)) {
return false;
}
double sourceX = state.sourceTransform().sourceX(worldX, worldZ);
double sourceZ = state.sourceTransform().sourceZ(worldX, worldZ);
if (!validSourceCoordinate(sourceX, sourceZ)) {
return false;
}
long baseX = floorToLong(sourceX);
long baseZ = floorToLong(sourceZ);
return switch (state.sampling()) {
case NEAREST -> sourceIndexInBounds(baseX, baseZ);
case BILINEAR -> bilinearKernelInBounds(sourceX, sourceZ, baseX, baseZ);
case BICUBIC -> bicubicKernelInBounds(sourceX, sourceZ, baseX, baseZ);
};
}
public double sampleNormalized(double worldX, double worldZ) {
requireScalarType();
requireWorldCoordinate(worldX, worldZ);
double sourceX = state.sourceTransform().sourceX(worldX, worldZ);
double sourceZ = state.sourceTransform().sourceZ(worldX, worldZ);
requireSourceCoordinate(sourceX, sourceZ);
double sampled = switch (state.sampling()) {
case NEAREST -> scalarAt(floorToLong(sourceX), floorToLong(sourceZ));
case BILINEAR -> bilinear(sourceX, sourceZ);
case BICUBIC -> bicubic(sourceX, sourceZ);
};
return clamp01(sampled);
}
public double sampleHeight(double worldX, double worldZ) {
if (!isHeightType()) {
throw new IrisImageMapValidationException("Image map type " + state.type() + " does not produce terrain heights");
}
double normalized = sampleNormalized(worldX, worldZ);
double height = state.minimumHeight()
+ (normalized * (state.maximumHeight() - state.minimumHeight()))
+ state.verticalOffset();
if (!state.clampHeight()) {
return height;
}
return Math.max(state.minimumHeight(), Math.min(state.maximumHeight(), height));
}
public String sampleTarget(double worldX, double worldZ) {
if (state.type() != IrisImageMapType.COLOR_MAP) {
throw new IrisImageMapValidationException("Image map type " + state.type() + " does not produce legend targets");
}
if (state.targetIndices() == null) {
throw new IrisImageMapValidationException("Compiled image-map view does not retain decoded target data");
}
requireWorldCoordinate(worldX, worldZ);
double transformedX = state.sourceTransform().sourceX(worldX, worldZ);
double transformedZ = state.sourceTransform().sourceZ(worldX, worldZ);
requireSourceCoordinate(transformedX, transformedZ);
long sourceX = floorToLong(transformedX);
long sourceZ = floorToLong(transformedZ);
int resolvedX = resolveIndex(sourceX, state.sourceMetadata().width());
int resolvedZ = resolveIndex(sourceZ, state.sourceMetadata().height());
if (resolvedX < 0 || resolvedZ < 0) {
return state.fallbackTarget();
}
int targetIndex = state.targetIndices().get((resolvedZ * state.sourceMetadata().width()) + resolvedX);
return targetIndex < 0 ? null : state.targets()[targetIndex];
}
private void requireWorldCoordinate(double worldX, double worldZ) {
if (!Double.isFinite(worldX) || !Double.isFinite(worldZ)) {
throw new IrisImageMapValidationException("World coordinates must be finite, got " + worldX + "," + worldZ);
}
}
private void requireSourceCoordinate(double sourceX, double sourceZ) {
if (!validSourceCoordinate(sourceX, sourceZ)) {
throw new IrisImageMapValidationException(
"World coordinates transform outside the supported source-coordinate range: "
+ sourceX + "," + sourceZ
);
}
}
private boolean bilinearKernelInBounds(double sourceX, double sourceZ, long baseX, long baseZ) {
long maximumX = sourceX == baseX ? baseX : baseX + 1L;
long maximumZ = sourceZ == baseZ ? baseZ : baseZ + 1L;
return baseX >= 0L
&& baseZ >= 0L
&& maximumX < state.sourceMetadata().width()
&& maximumZ < state.sourceMetadata().height();
}
private boolean bicubicKernelInBounds(double sourceX, double sourceZ, long baseX, long baseZ) {
if (sourceX == baseX && sourceZ == baseZ) {
return sourceIndexInBounds(baseX, baseZ);
}
return baseX >= 1L
&& baseZ >= 1L
&& baseX + 2L < state.sourceMetadata().width()
&& baseZ + 2L < state.sourceMetadata().height();
}
private boolean sourceIndexInBounds(long sourceX, long sourceZ) {
return sourceX >= 0L
&& sourceZ >= 0L
&& sourceX < state.sourceMetadata().width()
&& sourceZ < state.sourceMetadata().height();
}
private double bilinear(double sourceX, double sourceZ) {
long x0 = floorToLong(sourceX);
long z0 = floorToLong(sourceZ);
double fractionX = sourceX - x0;
double fractionZ = sourceZ - z0;
if (fractionX == 0D && fractionZ == 0D) {
return scalarAt(x0, z0);
}
if (fractionZ == 0D) {
return lerp(scalarAt(x0, z0), scalarAt(x0 + 1L, z0), fractionX);
}
if (fractionX == 0D) {
return lerp(scalarAt(x0, z0), scalarAt(x0, z0 + 1L), fractionZ);
}
double top = lerp(scalarAt(x0, z0), scalarAt(x0 + 1L, z0), fractionX);
double bottom = lerp(scalarAt(x0, z0 + 1L), scalarAt(x0 + 1L, z0 + 1L), fractionX);
return lerp(top, bottom, fractionZ);
}
private double bicubic(double sourceX, double sourceZ) {
long baseX = floorToLong(sourceX);
long baseZ = floorToLong(sourceZ);
double fractionX = sourceX - baseX;
double fractionZ = sourceZ - baseZ;
if (fractionX == 0D && fractionZ == 0D) {
return scalarAt(baseX, baseZ);
}
double row0 = cubicRow(baseX, baseZ - 1L, fractionX);
double row1 = cubicRow(baseX, baseZ, fractionX);
double row2 = cubicRow(baseX, baseZ + 1L, fractionX);
double row3 = cubicRow(baseX, baseZ + 2L, fractionX);
return cubic(row0, row1, row2, row3, fractionZ);
}
private double cubicRow(long baseX, long sourceZ, double fractionX) {
return cubic(
scalarAt(baseX - 1L, sourceZ),
scalarAt(baseX, sourceZ),
scalarAt(baseX + 1L, sourceZ),
scalarAt(baseX + 2L, sourceZ),
fractionX
);
}
private double scalarAt(long sourceX, long sourceZ) {
int resolvedX = resolveIndex(sourceX, state.sourceMetadata().width());
int resolvedZ = resolveIndex(sourceZ, state.sourceMetadata().height());
if (resolvedX < 0 || resolvedZ < 0) {
return state.fallbackValue();
}
return state.scalarValues().get((resolvedZ * state.sourceMetadata().width()) + resolvedX);
}
private int resolveIndex(long coordinate, int length) {
if (coordinate >= 0L && coordinate < length) {
return (int) coordinate;
}
IrisImageMapOutOfBounds outOfBounds = state.outOfBounds();
return switch (outOfBounds) {
case FALLBACK -> -1;
case CLAMP -> coordinate < 0L ? 0 : length - 1;
case REPEAT -> (int) Math.floorMod(coordinate, (long) length);
case MIRROR -> mirrorIndex(coordinate, length);
case ERROR -> throw new IrisImageMapValidationException(
"Source coordinate " + coordinate + " is outside 0.." + (length - 1)
);
};
}
private int mirrorIndex(long coordinate, int length) {
if (length == 1) {
return 0;
}
long period = (long) length * 2L;
long mirrored = Math.floorMod(coordinate, period);
if (mirrored >= length) {
mirrored = period - 1L - mirrored;
}
return (int) mirrored;
}
private boolean isHeightType() {
return state.type() == IrisImageMapType.GRAYSCALE_HEIGHT
|| state.type() == IrisImageMapType.RGB_HEIGHT;
}
private void requireScalarType() {
if (state.scalarValues() == null) {
if (isHeightType()
|| state.type() == IrisImageMapType.BINARY_MASK
|| state.type() == IrisImageMapType.GRAYSCALE_MASK
|| state.type() == IrisImageMapType.ALPHA_MASK) {
throw new IrisImageMapValidationException("Compiled image-map view does not retain decoded scalar data");
}
throw new IrisImageMapValidationException("Image map type " + state.type() + " does not produce normalized scalar data");
}
}
private static long floorToLong(double value) {
return (long) Math.floor(value);
}
private static boolean validSourceCoordinate(double sourceX, double sourceZ) {
double safeMinimum = -9_000_000_000_000_000_000D;
double safeMaximum = 9_000_000_000_000_000_000D;
return Double.isFinite(sourceX)
&& Double.isFinite(sourceZ)
&& sourceX >= safeMinimum
&& sourceX <= safeMaximum
&& sourceZ >= safeMinimum
&& sourceZ <= safeMaximum;
}
private static double lerp(double a, double b, double factor) {
return a + ((b - a) * factor);
}
private static double cubic(double p0, double p1, double p2, double p3, double factor) {
double squared = factor * factor;
double cubed = squared * factor;
return 0.5D * ((2D * p1)
+ ((-p0 + p2) * factor)
+ (((2D * p0) - (5D * p1) + (4D * p2) - p3) * squared)
+ ((-p0 + (3D * p1) - (3D * p2) + p3) * cubed));
}
private static double clamp01(double value) {
return Math.max(0D, Math.min(1D, value));
}
static record State(
IrisImageMap definition,
IrisImageMapSourceMetadata sourceMetadata,
IrisImageMapType type,
FloatTiles scalarValues,
IntTiles targetIndices,
String[] targets,
SourceTransform sourceTransform,
IrisImageMapSampling sampling,
IrisImageMapOutOfBounds outOfBounds,
double fallbackValue,
String fallbackTarget,
double minimumHeight,
double maximumHeight,
double verticalOffset,
boolean clampHeight,
int clippedPixelCount,
int unknownColorPixelCount,
String contentHash
) {
State withoutDecodedValues() {
return new State(
definition,
sourceMetadata,
type,
null,
null,
null,
sourceTransform,
sampling,
outOfBounds,
fallbackValue,
fallbackTarget,
minimumHeight,
maximumHeight,
verticalOffset,
clampHeight,
clippedPixelCount,
unknownColorPixelCount,
contentHash
);
}
}
static record SourceTransform(
double sourceXFromWorldX,
double sourceXFromWorldZ,
double sourceXOffset,
double sourceZFromWorldX,
double sourceZFromWorldZ,
double sourceZOffset
) {
double sourceX(double worldX, double worldZ) {
return (sourceXFromWorldX * worldX) + (sourceXFromWorldZ * worldZ) + sourceXOffset;
}
double sourceZ(double worldX, double worldZ) {
return (sourceZFromWorldX * worldX) + (sourceZFromWorldZ * worldZ) + sourceZOffset;
}
}
static final class FloatTiles {
private static final int TILE_SHIFT = 20;
private static final int TILE_SIZE = 1 << TILE_SHIFT;
private static final int TILE_MASK = TILE_SIZE - 1;
private final float[][] tiles;
FloatTiles(int size) {
int tileCount = (size + TILE_SIZE - 1) >>> TILE_SHIFT;
tiles = new float[tileCount][];
for (int tile = 0; tile < tileCount; tile++) {
int remaining = size - (tile << TILE_SHIFT);
tiles[tile] = new float[Math.min(TILE_SIZE, remaining)];
}
}
float get(int index) {
return tiles[index >>> TILE_SHIFT][index & TILE_MASK];
}
void set(int index, float value) {
tiles[index >>> TILE_SHIFT][index & TILE_MASK] = value;
}
}
static final class IntTiles {
private static final int TILE_SHIFT = 20;
private static final int TILE_SIZE = 1 << TILE_SHIFT;
private static final int TILE_MASK = TILE_SIZE - 1;
private final int[][] tiles;
IntTiles(int size) {
int tileCount = (size + TILE_SIZE - 1) >>> TILE_SHIFT;
tiles = new int[tileCount][];
for (int tile = 0; tile < tileCount; tile++) {
int remaining = size - (tile << TILE_SHIFT);
tiles[tile] = new int[Math.min(TILE_SIZE, remaining)];
}
}
int get(int index) {
return tiles[index >>> TILE_SHIFT][index & TILE_MASK];
}
void set(int index, int value) {
tiles[index >>> TILE_SHIFT][index & TILE_MASK] = value;
}
}
}
@@ -0,0 +1,825 @@
package art.arcane.iris.engine.image;
import art.arcane.iris.engine.object.image.IrisImage;
import art.arcane.iris.engine.object.image.IrisImageColorMode;
import art.arcane.iris.engine.object.image.IrisImageMap;
import art.arcane.iris.engine.object.image.IrisImageMapAlpha;
import art.arcane.iris.engine.object.image.IrisImageMapOrigin;
import art.arcane.iris.engine.object.image.IrisImageMapOutOfBounds;
import art.arcane.iris.engine.object.image.IrisImageMapSampling;
import art.arcane.iris.engine.object.image.IrisImageMapType;
import art.arcane.iris.engine.object.image.IrisImageMapUnknownColor;
import art.arcane.volmlib.util.collection.KMap;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HexFormat;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.regex.Pattern;
public final class IrisImageMapCompiler {
public static final int MINIMUM_DIMENSION = 1;
public static final int MAXIMUM_DIMENSION = 16_384;
public static final long MAXIMUM_PIXELS = 16_777_216L;
private static final Pattern COLOR_PATTERN = Pattern.compile("#[0-9a-fA-F]{6}");
private IrisImageMapCompiler() {
}
public static CompiledIrisImageMap compile(IrisImageMap definition, IrisImage image) {
if (definition == null) {
throw new IrisImageMapValidationException("Image-map definition is required");
}
if (image == null) {
throw new IrisImageMapValidationException("Decoded image source is required");
}
List<String> diagnostics = validate(definition, image);
if (!diagnostics.isEmpty()) {
throw new IrisImageMapValidationException(diagnostics);
}
try {
SourceDigest sourceDigest = hashSource(image);
IrisImageMapSourceMetadata metadata = new IrisImageMapSourceMetadata(
image.getFormat(),
image.getColorMode(),
image.getWidth(),
image.getHeight(),
image.getColorComponentCount(),
image.getChannelCount(),
image.getBitDepth(),
image.hasAlpha(),
sourceDigest.minimumAlpha(),
sourceDigest.maximumAlpha(),
sourceDigest.hash()
);
IrisImageMap snapshot = snapshot(definition);
CompiledIrisImageMap.FloatTiles scalarValues = null;
CompiledIrisImageMap.IntTiles targetIndices = null;
String[] targets = null;
int clippedPixelCount = 0;
int unknownColorPixelCount = 0;
if (definition.getType() == IrisImageMapType.COLOR_MAP) {
CompiledTargets compiledTargets = compileTargets(definition, image);
targetIndices = compiledTargets.indices();
targets = compiledTargets.targets();
unknownColorPixelCount = compiledTargets.unknownColorPixelCount();
} else {
scalarValues = compileScalars(definition, image);
if (definition.getSmoothingRadius() > 0) {
smooth(scalarValues, image.getWidth(), image.getHeight(), definition.getSmoothingRadius());
}
clippedPixelCount = countClippedPixels(
definition, scalarValues, Math.multiplyExact(image.getWidth(), image.getHeight())
);
}
String contentHash = hashContent(snapshot, metadata);
String fallbackTarget = definition.getFallbackTarget() == null || definition.getFallbackTarget().isBlank()
? null
: definition.getFallbackTarget();
CompiledIrisImageMap.SourceTransform sourceTransform = compileSourceTransform(definition);
CompiledIrisImageMap.State state = new CompiledIrisImageMap.State(
snapshot,
metadata,
definition.getType(),
scalarValues,
targetIndices,
targets,
sourceTransform,
definition.getSampling(),
definition.getOutOfBounds(),
definition.getFallbackValue(),
fallbackTarget,
definition.getMinimumHeight(),
definition.getMaximumHeight(),
definition.getVerticalOffset(),
definition.isClamp(),
clippedPixelCount,
unknownColorPixelCount,
contentHash
);
return new CompiledIrisImageMap(state);
} catch (IrisImageMapValidationException exception) {
throw exception;
} catch (RuntimeException exception) {
throw new IrisImageMapValidationException(
"Failed to compile image map '" + definition.getSource() + "': " + exception.getMessage(),
exception
);
}
}
private static List<String> validate(IrisImageMap definition, IrisImage image) {
List<String> diagnostics = new ArrayList<>();
if (definition.getSource() == null || definition.getSource().isBlank()) {
diagnostics.add("Image-map source must not be blank");
}
validateSource(image, diagnostics);
validateCoordinates(definition, diagnostics);
validateScalarSettings(definition, diagnostics);
validateType(definition, image, diagnostics);
validateLegend(definition, diagnostics);
return diagnostics;
}
private static void validateSource(IrisImage image, List<String> diagnostics) {
if (!"png".equals(image.getFormat())) {
diagnostics.add("Image format must be PNG, got " + image.getFormat());
}
int width = image.getWidth();
int height = image.getHeight();
if (width < MINIMUM_DIMENSION || width > MAXIMUM_DIMENSION) {
diagnostics.add("Image width must be " + MINIMUM_DIMENSION + ".." + MAXIMUM_DIMENSION + ", got " + width);
}
if (height < MINIMUM_DIMENSION || height > MAXIMUM_DIMENSION) {
diagnostics.add("Image height must be " + MINIMUM_DIMENSION + ".." + MAXIMUM_DIMENSION + ", got " + height);
}
long pixels = (long) width * height;
if (pixels > MAXIMUM_PIXELS) {
diagnostics.add("Image contains " + pixels + " pixels; maximum is " + MAXIMUM_PIXELS);
}
if (image.getColorMode() == IrisImageColorMode.INDEXED) {
diagnostics.add("Indexed PNG images are unsupported; convert the source to grayscale, RGB, or RGBA");
} else if (image.getColorMode() == IrisImageColorMode.UNSUPPORTED) {
diagnostics.add("Unsupported PNG color mode with " + image.getColorComponentCount()
+ " color components and " + image.getChannelCount() + " channels");
}
}
private static void validateCoordinates(IrisImageMap definition, List<String> diagnostics) {
if (!finiteAtLeast(definition.getBlocksPerPixel(), IrisImageMap.MINIMUM_SCALE)) {
diagnostics.add("blocksPerPixel must be finite and at least " + IrisImageMap.MINIMUM_SCALE);
}
IrisImageMapOrigin origin = definition.getOrigin();
if (origin == null || !Double.isFinite(origin.getX()) || !Double.isFinite(origin.getZ())) {
diagnostics.add("origin X and Z must be finite");
}
IrisImageMapOrigin sourceOrigin = definition.getSourceOrigin();
if (sourceOrigin == null || !Double.isFinite(sourceOrigin.getX()) || !Double.isFinite(sourceOrigin.getZ())) {
diagnostics.add("sourceOrigin X and Z must be finite");
}
if (definition.getRotation() == null) {
diagnostics.add("rotation is required");
}
if (definition.getSampling() == null) {
diagnostics.add("sampling is required");
}
if (definition.getOutOfBounds() == null) {
diagnostics.add("outOfBounds is required");
}
}
private static void validateScalarSettings(IrisImageMap definition, List<String> diagnostics) {
if (!range(definition.getFallbackValue(), 0D, 1D)) {
diagnostics.add("fallbackValue must be finite and within 0..1");
}
if (!Double.isFinite(definition.getMinimumHeight()) || !Double.isFinite(definition.getMaximumHeight())) {
diagnostics.add("minimumHeight and maximumHeight must be finite");
} else if (definition.getMaximumHeight() < definition.getMinimumHeight()) {
diagnostics.add("maximumHeight must be greater than or equal to minimumHeight");
}
if (!Double.isFinite(definition.getVerticalOffset())) {
diagnostics.add("verticalOffset must be finite");
}
if (!finiteAtLeast(definition.getCurveExponent(), IrisImageMap.MINIMUM_SCALE)) {
diagnostics.add("curveExponent must be finite and at least " + IrisImageMap.MINIMUM_SCALE);
}
if (definition.getSmoothingRadius() < 0 || definition.getSmoothingRadius() > 32) {
diagnostics.add("smoothingRadius must be within 0..32");
}
if (!range(definition.getThreshold(), 0D, 1D)) {
diagnostics.add("threshold must be finite and within 0..1");
}
if (!range(definition.getFalloff(), 0D, 1D)) {
diagnostics.add("falloff must be finite and within 0..1");
}
if (!range(definition.getColorTolerance(), 0D, IrisImageMap.MAXIMUM_COLOR_TOLERANCE)) {
diagnostics.add("colorTolerance must be finite and within 0.."
+ IrisImageMap.MAXIMUM_COLOR_TOLERANCE);
}
if (definition.getAlpha() == null) {
diagnostics.add("alpha policy is required");
}
if (definition.getUnknownColor() == null) {
diagnostics.add("unknownColor policy is required");
}
}
private static void validateType(IrisImageMap definition, IrisImage image, List<String> diagnostics) {
IrisImageMapType type = definition.getType();
if (type == null) {
diagnostics.add("Image-map type is required");
return;
}
IrisImageColorMode colorMode = image.getColorMode();
int bitDepth = image.getBitDepth();
switch (type) {
case GRAYSCALE_HEIGHT, BINARY_MASK, GRAYSCALE_MASK -> {
if (colorMode != IrisImageColorMode.GRAYSCALE) {
diagnostics.add(type + " requires a grayscale PNG, got " + colorMode);
}
if (bitDepth != 8 && bitDepth != 16) {
diagnostics.add(type + " requires 8-bit or 16-bit grayscale samples, got " + bitDepth + "-bit");
}
}
case RGB_HEIGHT, COLOR_MAP -> {
if (colorMode != IrisImageColorMode.RGB && colorMode != IrisImageColorMode.RGBA) {
diagnostics.add(type + " requires an RGB or RGBA PNG, got " + colorMode);
}
if (bitDepth != 8) {
diagnostics.add(type + " requires canonical 8-bit RGB channels, got " + bitDepth + "-bit");
}
}
case ALPHA_MASK -> {
if (colorMode != IrisImageColorMode.RGBA || !image.hasAlpha()) {
diagnostics.add("ALPHA_MASK requires an 8-bit RGBA PNG");
}
if (bitDepth != 8) {
diagnostics.add("ALPHA_MASK requires an 8-bit alpha channel, got " + bitDepth + "-bit color channels");
}
if (definition.getAlpha() != null && definition.getAlpha() != IrisImageMapAlpha.IGNORE) {
diagnostics.add("ALPHA_MASK requires alpha=IGNORE because alpha is the map data");
}
}
}
if ((type == IrisImageMapType.COLOR_MAP || type == IrisImageMapType.BINARY_MASK)
&& definition.getSampling() != null
&& definition.getSampling() != IrisImageMapSampling.NEAREST) {
diagnostics.add(type + " requires NEAREST sampling");
}
if (type == IrisImageMapType.COLOR_MAP && definition.getSmoothingRadius() != 0) {
diagnostics.add("COLOR_MAP does not support numeric smoothing");
}
}
private static void validateLegend(IrisImageMap definition, List<String> diagnostics) {
KMap<String, String> colors = definition.getColors();
if (definition.getType() != IrisImageMapType.COLOR_MAP) {
if (colors != null && !colors.isEmpty()) {
diagnostics.add("colors may only be set for COLOR_MAP definitions");
}
if (definition.getColorTolerance() != 0D) {
diagnostics.add("colorTolerance may only be set for COLOR_MAP definitions");
}
return;
}
if (colors == null || colors.isEmpty()) {
diagnostics.add("COLOR_MAP requires at least one #RRGGBB legend entry");
return;
}
Map<Integer, String> decoded = new HashMap<>();
for (Map.Entry<String, String> entry : colors.entrySet()) {
String encoded = entry.getKey();
String target = entry.getValue();
if (encoded == null || !COLOR_PATTERN.matcher(encoded).matches()) {
diagnostics.add("Color legend key must use exact #RRGGBB syntax, got " + encoded);
continue;
}
if (target == null || target.isBlank()) {
diagnostics.add("Color legend target for " + encoded + " must not be blank");
}
int rgb = Integer.parseInt(encoded.substring(1), 16);
String previous = decoded.putIfAbsent(rgb, encoded);
if (previous != null) {
diagnostics.add("Color legend duplicates raw color " + previous + " as " + encoded);
}
}
boolean fallbackRequired = definition.getOutOfBounds() == IrisImageMapOutOfBounds.FALLBACK
|| definition.getUnknownColor() == IrisImageMapUnknownColor.FALLBACK
|| definition.getAlpha() == IrisImageMapAlpha.TRANSPARENT_IS_FALLBACK
|| definition.getAlpha() == IrisImageMapAlpha.MASK;
if (fallbackRequired && (definition.getFallbackTarget() == null || definition.getFallbackTarget().isBlank())) {
diagnostics.add("fallbackTarget is required by the configured color-map fallback policy");
}
}
private static CompiledIrisImageMap.FloatTiles compileScalars(IrisImageMap definition, IrisImage image) {
int width = image.getWidth();
int height = image.getHeight();
CompiledIrisImageMap.FloatTiles values = new CompiledIrisImageMap.FloatTiles(
Math.multiplyExact(width, height)
);
for (int sourceZ = 0; sourceZ < height; sourceZ++) {
for (int sourceX = 0; sourceX < width; sourceX++) {
double alpha = image.getAlphaNormalized(sourceX, sourceZ);
validateAlphaPixel(definition, sourceX, sourceZ, alpha);
double value;
if (definition.getAlpha() == IrisImageMapAlpha.TRANSPARENT_IS_FALLBACK && alpha == 0D) {
value = definition.getFallbackValue();
} else {
value = rawScalar(definition.getType(), image, sourceX, sourceZ);
if (definition.isInverted()) {
value = 1D - value;
}
value = Math.pow(clamp01(value), definition.getCurveExponent());
if (definition.getType() == IrisImageMapType.BINARY_MASK) {
value = threshold(value, definition.getThreshold(), definition.getFalloff());
}
if (definition.getAlpha() == IrisImageMapAlpha.MASK) {
value *= alpha;
}
}
values.set((sourceZ * width) + sourceX, (float) clamp01(value));
}
}
return values;
}
private static double rawScalar(IrisImageMapType type, IrisImage image, int sourceX, int sourceZ) {
return switch (type) {
case GRAYSCALE_HEIGHT, BINARY_MASK, GRAYSCALE_MASK -> image.getBandNormalized(sourceX, sourceZ, 0);
case RGB_HEIGHT -> {
int red = image.getBandSample(sourceX, sourceZ, 0);
int green = image.getBandSample(sourceX, sourceZ, 1);
int blue = image.getBandSample(sourceX, sourceZ, 2);
int encoded = (red << 16) | (green << 8) | blue;
yield encoded / 16_777_215D;
}
case ALPHA_MASK -> image.getAlphaNormalized(sourceX, sourceZ);
case COLOR_MAP -> throw new IrisImageMapValidationException("COLOR_MAP does not produce scalar pixels");
};
}
private static CompiledTargets compileTargets(IrisImageMap definition, IrisImage image) {
Legend legend = compileLegend(definition);
int width = image.getWidth();
int height = image.getHeight();
CompiledIrisImageMap.IntTiles indices = new CompiledIrisImageMap.IntTiles(
Math.multiplyExact(width, height)
);
int unknownColorPixelCount = 0;
for (int sourceZ = 0; sourceZ < height; sourceZ++) {
for (int sourceX = 0; sourceX < width; sourceX++) {
double alpha = image.getAlphaNormalized(sourceX, sourceZ);
validateAlphaPixel(definition, sourceX, sourceZ, alpha);
int targetIndex;
if (definition.getAlpha() == IrisImageMapAlpha.TRANSPARENT_IS_FALLBACK && alpha == 0D) {
targetIndex = legend.fallbackIndex();
} else if (definition.getAlpha() == IrisImageMapAlpha.MASK && alpha < 1D) {
if (alpha == 0D) {
targetIndex = legend.fallbackIndex();
} else {
throw new IrisImageMapValidationException(
"COLOR_MAP alpha=MASK requires binary alpha; pixel " + sourceX + "," + sourceZ
+ " has alpha " + alpha
);
}
} else {
int rgb = image.getRawRgb8(sourceX, sourceZ);
TargetMatch match = matchTarget(definition, legend, rgb, sourceX, sourceZ);
targetIndex = match.targetIndex();
if (match.unknown()) {
unknownColorPixelCount++;
}
}
indices.set((sourceZ * width) + sourceX, targetIndex);
}
}
return new CompiledTargets(indices, legend.targets(), unknownColorPixelCount);
}
private static Legend compileLegend(IrisImageMap definition) {
List<MutableLegendEntry> entries = new ArrayList<>();
for (Map.Entry<String, String> entry : definition.getColors().entrySet()) {
int rgb = Integer.parseInt(entry.getKey().substring(1), 16);
entries.add(new MutableLegendEntry(rgb, entry.getKey().toUpperCase(), entry.getValue()));
}
entries.sort(Comparator.comparingInt(MutableLegendEntry::rgb).thenComparing(MutableLegendEntry::target));
LinkedHashMap<String, Integer> targetIndexes = new LinkedHashMap<>();
Map<Integer, LegendEntry> exact = new HashMap<>();
List<LegendEntry> compiled = new ArrayList<>();
for (MutableLegendEntry entry : entries) {
int targetIndex = targetIndexes.computeIfAbsent(entry.target(), ignored -> targetIndexes.size());
LegendEntry compiledEntry = new LegendEntry(entry.rgb(), entry.encoded(), entry.target(), targetIndex);
exact.put(entry.rgb(), compiledEntry);
compiled.add(compiledEntry);
}
int fallbackIndex = -1;
if (definition.getFallbackTarget() != null && !definition.getFallbackTarget().isBlank()) {
fallbackIndex = targetIndexes.computeIfAbsent(
definition.getFallbackTarget(),
ignored -> targetIndexes.size()
);
}
String[] targets = new String[targetIndexes.size()];
for (Map.Entry<String, Integer> entry : targetIndexes.entrySet()) {
targets[entry.getValue()] = entry.getKey();
}
return new Legend(List.copyOf(compiled), Map.copyOf(exact), targets, fallbackIndex);
}
private static TargetMatch matchTarget(
IrisImageMap definition,
Legend legend,
int rgb,
int sourceX,
int sourceZ
) {
LegendEntry exact = legend.exact().get(rgb);
if (exact != null) {
return new TargetMatch(exact.targetIndex(), false);
}
double toleranceSquared = definition.getColorTolerance() * definition.getColorTolerance();
LegendEntry matched = null;
List<String> ambiguous = new ArrayList<>();
if (toleranceSquared > 0D) {
for (LegendEntry candidate : legend.entries()) {
if (colorDistanceSquared(rgb, candidate.rgb()) <= toleranceSquared) {
if (matched == null) {
matched = candidate;
}
ambiguous.add(candidate.encoded());
}
}
}
if (ambiguous.size() > 1) {
throw new IrisImageMapValidationException(
"Color " + encodeColor(rgb) + " at " + sourceX + "," + sourceZ
+ " ambiguously matches " + String.join(", ", ambiguous)
);
}
if (matched != null) {
return new TargetMatch(matched.targetIndex(), false);
}
int targetIndex = switch (definition.getUnknownColor()) {
case ERROR -> throw new IrisImageMapValidationException(
"Color " + encodeColor(rgb) + " at " + sourceX + "," + sourceZ + " is absent from the legend"
);
case FALLBACK -> legend.fallbackIndex();
case IGNORE -> -1;
};
return new TargetMatch(targetIndex, true);
}
private static int countClippedPixels(
IrisImageMap definition,
CompiledIrisImageMap.FloatTiles values,
int size
) {
if (!definition.isClamp()
|| (definition.getType() != IrisImageMapType.GRAYSCALE_HEIGHT
&& definition.getType() != IrisImageMapType.RGB_HEIGHT)) {
return 0;
}
double minimum = definition.getMinimumHeight();
double maximum = definition.getMaximumHeight();
double range = maximum - minimum;
double offset = definition.getVerticalOffset();
int clipped = 0;
for (int index = 0; index < size; index++) {
double height = minimum + (values.get(index) * range) + offset;
if (height < minimum || height > maximum) {
clipped++;
}
}
return clipped;
}
private static void validateAlphaPixel(IrisImageMap definition, int sourceX, int sourceZ, double alpha) {
if (definition.getAlpha() == IrisImageMapAlpha.ERROR && alpha < 1D) {
throw new IrisImageMapValidationException(
"Transparent pixel at " + sourceX + "," + sourceZ + " violates alpha=ERROR"
);
}
}
private static double threshold(double value, double threshold, double falloff) {
if (falloff == 0D) {
return value >= threshold ? 1D : 0D;
}
return clamp01((value - threshold) / falloff);
}
private static void smooth(CompiledIrisImageMap.FloatTiles values, int width, int height, int radius) {
float[] line = new float[Math.max(width, height)];
int diameter = (radius * 2) + 1;
for (int sourceZ = 0; sourceZ < height; sourceZ++) {
int rowOffset = sourceZ * width;
for (int sourceX = 0; sourceX < width; sourceX++) {
line[sourceX] = values.get(rowOffset + sourceX);
}
double sum = 0D;
for (int offset = -radius; offset <= radius; offset++) {
int sourceX = Math.max(0, Math.min(width - 1, offset));
sum += line[sourceX];
}
for (int sourceX = 0; sourceX < width; sourceX++) {
values.set(rowOffset + sourceX, (float) (sum / diameter));
int leavingX = Math.max(0, Math.min(width - 1, sourceX - radius));
int enteringX = Math.max(0, Math.min(width - 1, sourceX + radius + 1));
sum += line[enteringX] - line[leavingX];
}
}
for (int sourceX = 0; sourceX < width; sourceX++) {
for (int sourceZ = 0; sourceZ < height; sourceZ++) {
line[sourceZ] = values.get((sourceZ * width) + sourceX);
}
double sum = 0D;
for (int offset = -radius; offset <= radius; offset++) {
int sourceZ = Math.max(0, Math.min(height - 1, offset));
sum += line[sourceZ];
}
for (int sourceZ = 0; sourceZ < height; sourceZ++) {
values.set((sourceZ * width) + sourceX, (float) (sum / diameter));
int leavingZ = Math.max(0, Math.min(height - 1, sourceZ - radius));
int enteringZ = Math.max(0, Math.min(height - 1, sourceZ + radius + 1));
sum += line[enteringZ] - line[leavingZ];
}
}
}
private static SourceDigest hashSource(IrisImage image) {
HashAccumulator hash = new HashAccumulator();
hash.addString(image.getFormat());
hash.addString(image.getColorMode().name());
hash.addInt(image.getWidth());
hash.addInt(image.getHeight());
hash.addInt(image.getColorComponentCount());
hash.addInt(image.getChannelCount());
hash.addInt(image.getBitDepth());
hash.addBoolean(image.hasAlpha());
double minimumAlpha = 1D;
double maximumAlpha = image.hasAlpha() ? 0D : 1D;
for (int sourceZ = 0; sourceZ < image.getHeight(); sourceZ++) {
for (int sourceX = 0; sourceX < image.getWidth(); sourceX++) {
double alpha = image.getAlphaNormalized(sourceX, sourceZ);
minimumAlpha = Math.min(minimumAlpha, alpha);
maximumAlpha = Math.max(maximumAlpha, alpha);
for (int band = 0; band < image.getChannelCount(); band++) {
hash.addInt(image.getBandSample(sourceX, sourceZ, band));
}
}
}
return new SourceDigest(hash.finish(), minimumAlpha, maximumAlpha);
}
private static String hashContent(IrisImageMap definition, IrisImageMapSourceMetadata metadata) {
HashAccumulator hash = new HashAccumulator();
hash.addString(metadata.decodedContentHash());
hash.addString(definition.getSource());
hash.addString(definition.getType().name());
hash.addDouble(definition.getBlocksPerPixel());
hash.addDouble(definition.getOrigin().getX());
hash.addDouble(definition.getOrigin().getZ());
hash.addDouble(definition.getSourceOrigin().getX());
hash.addDouble(definition.getSourceOrigin().getZ());
hash.addString(definition.getRotation().name());
hash.addBoolean(definition.isMirrorX());
hash.addBoolean(definition.isMirrorZ());
hash.addString(definition.getSampling().name());
hash.addString(definition.getOutOfBounds().name());
hash.addDouble(definition.getFallbackValue());
hash.addString(definition.getFallbackTarget());
hash.addString(definition.getAlpha().name());
hash.addDouble(definition.getMinimumHeight());
hash.addDouble(definition.getMaximumHeight());
hash.addDouble(definition.getVerticalOffset());
hash.addBoolean(definition.isClamp());
hash.addBoolean(definition.isInverted());
hash.addDouble(definition.getCurveExponent());
hash.addInt(definition.getSmoothingRadius());
hash.addDouble(definition.getThreshold());
hash.addDouble(definition.getFalloff());
hash.addDouble(definition.getColorTolerance());
hash.addString(definition.getUnknownColor().name());
KMap<String, String> configuredColors = definition.getColors();
List<Map.Entry<String, String>> colors = configuredColors == null
? new ArrayList<>()
: new ArrayList<>(configuredColors.entrySet());
colors.sort(Map.Entry.comparingByKey(String.CASE_INSENSITIVE_ORDER));
hash.addInt(colors.size());
for (Map.Entry<String, String> entry : colors) {
hash.addString(entry.getKey().toUpperCase());
hash.addString(entry.getValue());
}
return hash.finish();
}
private static CompiledIrisImageMap.SourceTransform compileSourceTransform(IrisImageMap definition) {
double sourceXFromWorldX;
double sourceXFromWorldZ;
double sourceZFromWorldX;
double sourceZFromWorldZ;
switch (definition.getRotation()) {
case DEG_0 -> {
sourceXFromWorldX = 1D;
sourceXFromWorldZ = 0D;
sourceZFromWorldX = 0D;
sourceZFromWorldZ = 1D;
}
case DEG_90 -> {
sourceXFromWorldX = 0D;
sourceXFromWorldZ = 1D;
sourceZFromWorldX = -1D;
sourceZFromWorldZ = 0D;
}
case DEG_180 -> {
sourceXFromWorldX = -1D;
sourceXFromWorldZ = 0D;
sourceZFromWorldX = 0D;
sourceZFromWorldZ = -1D;
}
case DEG_270 -> {
sourceXFromWorldX = 0D;
sourceXFromWorldZ = -1D;
sourceZFromWorldX = 1D;
sourceZFromWorldZ = 0D;
}
default -> throw new IrisImageMapValidationException(
"Unsupported image-map rotation " + definition.getRotation()
);
}
if (definition.isMirrorX()) {
sourceXFromWorldX = -sourceXFromWorldX;
sourceXFromWorldZ = -sourceXFromWorldZ;
}
if (definition.isMirrorZ()) {
sourceZFromWorldX = -sourceZFromWorldX;
sourceZFromWorldZ = -sourceZFromWorldZ;
}
double inverseScale = 1D / definition.getBlocksPerPixel();
sourceXFromWorldX *= inverseScale;
sourceXFromWorldZ *= inverseScale;
sourceZFromWorldX *= inverseScale;
sourceZFromWorldZ *= inverseScale;
double sourceXOffset = definition.getSourceOrigin().getX()
- (sourceXFromWorldX * definition.getOrigin().getX())
- (sourceXFromWorldZ * definition.getOrigin().getZ());
double sourceZOffset = definition.getSourceOrigin().getZ()
- (sourceZFromWorldX * definition.getOrigin().getX())
- (sourceZFromWorldZ * definition.getOrigin().getZ());
if (!Double.isFinite(sourceXFromWorldX)
|| !Double.isFinite(sourceXFromWorldZ)
|| !Double.isFinite(sourceXOffset)
|| !Double.isFinite(sourceZFromWorldX)
|| !Double.isFinite(sourceZFromWorldZ)
|| !Double.isFinite(sourceZOffset)) {
throw new IrisImageMapValidationException("Image-map coordinate transform must remain finite");
}
return new CompiledIrisImageMap.SourceTransform(
sourceXFromWorldX,
sourceXFromWorldZ,
sourceXOffset,
sourceZFromWorldX,
sourceZFromWorldZ,
sourceZOffset
);
}
private static IrisImageMap snapshot(IrisImageMap definition) {
KMap<String, String> configuredColors = definition.getColors();
KMap<String, String> colors = configuredColors == null ? new KMap<>() : new KMap<>(configuredColors);
return new IrisImageMap()
.setSource(definition.getSource())
.setType(definition.getType())
.setBlocksPerPixel(definition.getBlocksPerPixel())
.setOrigin(new IrisImageMapOrigin(definition.getOrigin().getX(), definition.getOrigin().getZ()))
.setSourceOrigin(new IrisImageMapOrigin(
definition.getSourceOrigin().getX(),
definition.getSourceOrigin().getZ()
))
.setRotation(definition.getRotation())
.setMirrorX(definition.isMirrorX())
.setMirrorZ(definition.isMirrorZ())
.setSampling(definition.getSampling())
.setOutOfBounds(definition.getOutOfBounds())
.setFallbackValue(definition.getFallbackValue())
.setFallbackTarget(definition.getFallbackTarget())
.setAlpha(definition.getAlpha())
.setMinimumHeight(definition.getMinimumHeight())
.setMaximumHeight(definition.getMaximumHeight())
.setVerticalOffset(definition.getVerticalOffset())
.setClamp(definition.isClamp())
.setInverted(definition.isInverted())
.setCurveExponent(definition.getCurveExponent())
.setSmoothingRadius(definition.getSmoothingRadius())
.setThreshold(definition.getThreshold())
.setFalloff(definition.getFalloff())
.setColorTolerance(definition.getColorTolerance())
.setUnknownColor(definition.getUnknownColor())
.setColors(colors);
}
private static double colorDistanceSquared(int first, int second) {
int red = ((first >>> 16) & 0xFF) - ((second >>> 16) & 0xFF);
int green = ((first >>> 8) & 0xFF) - ((second >>> 8) & 0xFF);
int blue = (first & 0xFF) - (second & 0xFF);
return (red * red) + (green * green) + (blue * blue);
}
private static String encodeColor(int rgb) {
return String.format(Locale.ROOT, "#%06X", rgb & 0xFFFFFF);
}
private static boolean finiteAtLeast(double value, double minimum) {
return Double.isFinite(value) && value >= minimum;
}
private static boolean range(double value, double minimum, double maximum) {
return Double.isFinite(value) && value >= minimum && value <= maximum;
}
private static double clamp01(double value) {
return Math.max(0D, Math.min(1D, value));
}
private record MutableLegendEntry(int rgb, String encoded, String target) {
}
private record LegendEntry(int rgb, String encoded, String target, int targetIndex) {
}
private record Legend(
List<LegendEntry> entries,
Map<Integer, LegendEntry> exact,
String[] targets,
int fallbackIndex
) {
}
private record CompiledTargets(
CompiledIrisImageMap.IntTiles indices,
String[] targets,
int unknownColorPixelCount
) {
}
private record TargetMatch(int targetIndex, boolean unknown) {
}
private record SourceDigest(String hash, double minimumAlpha, double maximumAlpha) {
}
private static final class HashAccumulator {
private final MessageDigest digest;
private HashAccumulator() {
try {
digest = MessageDigest.getInstance("SHA-256");
} catch (NoSuchAlgorithmException exception) {
throw new IllegalStateException("SHA-256 is unavailable", exception);
}
}
private void addBoolean(boolean value) {
digest.update((byte) (value ? 1 : 0));
}
private void addInt(int value) {
digest.update((byte) (value >>> 24));
digest.update((byte) (value >>> 16));
digest.update((byte) (value >>> 8));
digest.update((byte) value);
}
private void addLong(long value) {
digest.update((byte) (value >>> 56));
digest.update((byte) (value >>> 48));
digest.update((byte) (value >>> 40));
digest.update((byte) (value >>> 32));
digest.update((byte) (value >>> 24));
digest.update((byte) (value >>> 16));
digest.update((byte) (value >>> 8));
digest.update((byte) value);
}
private void addDouble(double value) {
addLong(Double.doubleToLongBits(value));
}
private void addString(String value) {
if (value == null) {
addInt(-1);
return;
}
byte[] bytes = value.getBytes(StandardCharsets.UTF_8);
addInt(bytes.length);
digest.update(bytes);
}
private String finish() {
return HexFormat.of().formatHex(digest.digest());
}
}
}
@@ -0,0 +1,113 @@
package art.arcane.iris.engine.image;
import art.arcane.iris.engine.object.image.IrisImageMapMask;
import art.arcane.iris.engine.object.image.IrisImageMapMaskOperation;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
public final class IrisImageMapMaskSampler {
private static final IrisImageMapMaskSampler EMPTY = new IrisImageMapMaskSampler(List.of());
private final List<Layer> layers;
public IrisImageMapMaskSampler(List<Layer> layers) {
this.layers = List.copyOf(Objects.requireNonNull(layers, "Image-map mask layers"));
}
public static IrisImageMapMaskSampler empty() {
return EMPTY;
}
public static Layer layer(CompiledIrisImageMap compiled, IrisImageMapMask definition) {
Objects.requireNonNull(definition, "Image-map mask definition");
if (definition.getOperation() == null) {
throw new IrisImageMapValidationException("Image-map mask operation is required");
}
if (!unitRange(definition.getThreshold()) || !unitRange(definition.getFalloff())) {
throw new IrisImageMapValidationException("Image-map mask threshold and falloff must be within 0..1");
}
return new Layer(
Objects.requireNonNull(compiled, "Compiled image-map mask"),
definition.getOperation(),
definition.isInverted(),
definition.getThreshold(),
definition.getFalloff()
);
}
public static IrisImageMapMaskSampler of(
List<CompiledIrisImageMap> compiled,
List<IrisImageMapMask> definitions
) {
if (compiled.size() != definitions.size()) {
throw new IllegalArgumentException("Compiled image-map masks and definitions must have equal sizes");
}
List<Layer> layers = new ArrayList<>(compiled.size());
for (int index = 0; index < compiled.size(); index++) {
layers.add(layer(compiled.get(index), definitions.get(index)));
}
return layers.isEmpty() ? empty() : new IrisImageMapMaskSampler(layers);
}
public boolean isEmpty() {
return layers.isEmpty();
}
public double sample(double worldX, double worldZ) {
double weight = 1D;
for (Layer layer : layers) {
double value = layer.sample(worldX, worldZ);
weight = switch (layer.operation()) {
case MULTIPLY -> weight * value;
case MINIMUM -> Math.min(weight, value);
case MAXIMUM -> Math.max(weight, value);
case ADD -> weight + value;
case SUBTRACT -> weight - value;
};
weight = clamp01(weight);
}
return weight;
}
private static boolean unitRange(double value) {
return Double.isFinite(value) && value >= 0D && value <= 1D;
}
private static double clamp01(double value) {
return Math.max(0D, Math.min(1D, value));
}
public record Layer(
CompiledIrisImageMap compiled,
IrisImageMapMaskOperation operation,
boolean inverted,
double threshold,
double falloff
) {
public Layer {
Objects.requireNonNull(compiled, "Compiled image-map mask");
Objects.requireNonNull(operation, "Image-map mask operation");
if (!unitRange(threshold) || !unitRange(falloff)) {
throw new IrisImageMapValidationException(
"Image-map mask threshold and falloff must be within 0..1"
);
}
}
private double sample(double worldX, double worldZ) {
double value = compiled.sampleNormalized(worldX, worldZ);
if (inverted) {
value = 1D - value;
}
if (threshold == 0D && falloff == 0D) {
return value;
}
if (falloff == 0D) {
return value >= threshold ? 1D : 0D;
}
return clamp01((value - threshold) / falloff);
}
}
}
@@ -0,0 +1,386 @@
package art.arcane.iris.engine.image;
import art.arcane.iris.core.loader.IrisData;
import art.arcane.iris.engine.framework.Engine;
import art.arcane.iris.engine.object.world.biome.IrisBiome;
import art.arcane.iris.engine.object.world.dimension.IrisDimension;
import art.arcane.iris.engine.object.image.IrisImage;
import art.arcane.iris.engine.object.image.IrisImageMap;
import art.arcane.iris.engine.object.image.IrisImageMapApplication;
import art.arcane.iris.engine.object.image.IrisImageMapBinding;
import art.arcane.iris.engine.object.image.IrisImageMapMask;
import art.arcane.iris.engine.object.image.IrisImageMapType;
import art.arcane.iris.engine.object.world.region.IrisRegion;
import art.arcane.iris.engine.object.world.biome.InferredType;
import art.arcane.iris.spi.PlatformBlockState;
import art.arcane.iris.util.common.data.B;
import java.util.ArrayList;
import java.util.EnumMap;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
public final class IrisImageMapRuntime {
private final int minimumWorldHeight;
private final Map<String, RuntimeBinding> bindings;
private final Map<IrisImageMapApplication, RuntimeBinding> applications;
private final Set<IrisRegion> mappedRegions;
private final Set<IrisBiome> mappedBiomes;
private IrisImageMapRuntime(
int minimumWorldHeight,
Map<String, RuntimeBinding> bindings,
Map<IrisImageMapApplication, RuntimeBinding> applications,
Set<IrisRegion> mappedRegions,
Set<IrisBiome> mappedBiomes
) {
this.minimumWorldHeight = minimumWorldHeight;
this.bindings = Map.copyOf(bindings);
this.applications = Map.copyOf(applications);
this.mappedRegions = Set.copyOf(mappedRegions);
this.mappedBiomes = Set.copyOf(mappedBiomes);
}
public static IrisImageMapRuntime compile(Engine engine) {
Objects.requireNonNull(engine, "Image-map runtime requires an engine");
return compile(engine.getData(), engine.getDimension(), engine.getMinHeight());
}
public static IrisImageMapRuntime compile(IrisData data, IrisDimension dimension, int minimumWorldHeight) {
Objects.requireNonNull(data, "Image-map runtime requires Iris data");
Objects.requireNonNull(dimension, "Image-map runtime requires a dimension");
Map<String, RuntimeBinding> bindings = new LinkedHashMap<>();
Map<IrisImageMapApplication, RuntimeBinding> applications = new EnumMap<>(IrisImageMapApplication.class);
Set<IrisRegion> mappedRegions = new LinkedHashSet<>();
Set<IrisBiome> mappedBiomes = new LinkedHashSet<>();
for (IrisImageMapBinding binding : dimension.getImageMaps()) {
RuntimeBinding runtimeBinding = compileBinding(binding, data, dimension, mappedRegions, mappedBiomes);
RuntimeBinding duplicate = bindings.putIfAbsent(runtimeBinding.key, runtimeBinding);
if (duplicate != null) {
throw validation("Duplicate dimension image-map key '" + runtimeBinding.key + "'");
}
IrisImageMapApplication application = runtimeBinding.application;
if (application != IrisImageMapApplication.MASK && application != IrisImageMapApplication.CUSTOM) {
RuntimeBinding applicationDuplicate = applications.putIfAbsent(application, runtimeBinding);
if (applicationDuplicate != null) {
throw validation("Dimension declares more than one " + application + " image-map binding");
}
}
}
for (RuntimeBinding binding : bindings.values()) {
binding.masks = resolveMasks(binding, bindings);
}
return new IrisImageMapRuntime(
minimumWorldHeight, bindings, applications, mappedRegions, mappedBiomes
);
}
public boolean has(IrisImageMapApplication application) {
return applications.containsKey(application);
}
public Set<IrisRegion> getMappedRegions() {
return mappedRegions;
}
public Set<IrisBiome> getMappedBiomes() {
return mappedBiomes;
}
public double sampleTerrainHeight(double worldX, double worldZ, double proceduralLocalHeight) {
RuntimeBinding binding = applications.get(IrisImageMapApplication.TERRAIN_HEIGHT);
if (binding == null) {
return proceduralLocalHeight;
}
double mappedLocalHeight = binding.compiled.sampleHeight(worldX, worldZ) - minimumWorldHeight;
double weight = binding.maskWeight(worldX, worldZ);
return blendTerrainHeight(mappedLocalHeight, proceduralLocalHeight, weight);
}
public IrisRegion sampleRegion(double worldX, double worldZ) {
RuntimeBinding binding = applications.get(IrisImageMapApplication.REGION);
if (binding == null || !selectCategorical(binding.maskWeight(worldX, worldZ))) {
return null;
}
String target = binding.compiled.sampleTarget(worldX, worldZ);
return target == null ? null : binding.regions.get(target);
}
public IrisBiome sampleBiome(double worldX, double worldZ) {
RuntimeBinding binding = applications.get(IrisImageMapApplication.BIOME);
if (binding == null || !selectCategorical(binding.maskWeight(worldX, worldZ))) {
return null;
}
String target = binding.compiled.sampleTarget(worldX, worldZ);
return target == null ? null : binding.biomes.get(target);
}
public PlatformBlockState sampleSurfaceBlock(double worldX, double worldZ) {
RuntimeBinding binding = applications.get(IrisImageMapApplication.SURFACE_BLOCK);
if (binding == null || !selectCategorical(binding.maskWeight(worldX, worldZ))) {
return null;
}
String target = binding.compiled.sampleTarget(worldX, worldZ);
return target == null ? null : binding.blocks.get(target);
}
public CompiledIrisImageMap getCompiled(String key) {
RuntimeBinding binding = bindings.get(key);
return binding == null ? null : binding.compiled;
}
public static double blendTerrainHeight(double mappedLocalHeight, double proceduralLocalHeight, double weight) {
return proceduralLocalHeight + ((mappedLocalHeight - proceduralLocalHeight) * weight);
}
public static boolean selectCategorical(double weight) {
return weight >= 0.5D;
}
private static RuntimeBinding compileBinding(
IrisImageMapBinding binding,
IrisData data,
IrisDimension dimension,
Set<IrisRegion> mappedRegions,
Set<IrisBiome> mappedBiomes
) {
if (binding == null) {
throw validation("Dimension imageMaps contains a null binding");
}
String key = requireText(binding.getKey(), "Dimension image-map key");
String mapKey = requireText(binding.getMap(), "Dimension image-map resource for '" + key + "'");
IrisImageMapApplication application = binding.getApplication();
if (application == null) {
throw validation("Dimension image-map '" + key + "' requires an application");
}
IrisImageMap definition = data.getImageMapLoader().load(mapKey);
if (definition == null) {
throw validation("Dimension image-map '" + key + "' references missing image-map resource '" + mapKey + "'");
}
String source = requireText(definition.getSource(), "Image-map resource '" + mapKey + "' source");
IrisImage image = data.getImageLoader().load(source);
if (image == null) {
throw validation("Image-map resource '" + mapKey + "' references missing or invalid PNG '" + source + "'");
}
CompiledIrisImageMap compiled;
try {
validateApplication(key, application, definition.getType(), binding.getMasks());
compiled = CompiledIrisImageMap.compile(definition, image);
} finally {
data.getImageLoader().unload(source);
}
Map<String, IrisRegion> regions = new LinkedHashMap<>();
Map<String, IrisBiome> biomes = new LinkedHashMap<>();
Map<String, PlatformBlockState> blocks = new LinkedHashMap<>();
Set<String> targets = legendTargets(definition);
if (application == IrisImageMapApplication.REGION) {
for (String target : targets) {
IrisRegion region = data.getRegionLoader().load(localResourceKey(target));
if (region == null) {
throw validation("Image-map '" + key + "' references missing region target '" + target + "'");
}
regions.put(target, region);
mappedRegions.add(region);
}
} else if (application == IrisImageMapApplication.BIOME) {
for (String target : targets) {
String localTarget = localResourceKey(target);
IrisBiome biome = data.getBiomeLoader().load(localTarget);
if (biome == null) {
throw validation("Image-map '" + key + "' references missing biome target '" + target + "'");
}
IrisBiome typedBiome = biome.withInferredType(resolveBiomeType(localTarget, dimension, data));
biomes.put(target, typedBiome);
mappedBiomes.add(typedBiome);
}
} else if (application == IrisImageMapApplication.SURFACE_BLOCK) {
for (String target : targets) {
PlatformBlockState block = B.getStateOrNull(target, false);
if (block == null) {
throw validation("Image-map '" + key + "' references unknown surface block target '" + target + "'");
}
blocks.put(target, block);
}
}
return new RuntimeBinding(
key,
application,
compiled,
Map.copyOf(regions),
Map.copyOf(biomes),
Map.copyOf(blocks),
binding.getMasks() == null ? List.of() : List.copyOf(binding.getMasks())
);
}
private static void validateApplication(
String key,
IrisImageMapApplication application,
IrisImageMapType type,
List<IrisImageMapMask> masks
) {
if (type == null) {
throw validation("Image-map '" + key + "' requires a type");
}
boolean valid = switch (application) {
case TERRAIN_HEIGHT -> type == IrisImageMapType.GRAYSCALE_HEIGHT
|| type == IrisImageMapType.RGB_HEIGHT;
case BIOME, REGION, SURFACE_BLOCK -> type == IrisImageMapType.COLOR_MAP;
case MASK -> isMaskType(type);
case CUSTOM -> true;
};
if (!valid) {
throw validation("Image-map '" + key + "' type " + type + " is incompatible with " + application);
}
if (application == IrisImageMapApplication.MASK && masks != null && !masks.isEmpty()) {
throw validation("MASK image-map '" + key + "' cannot reference additional masks");
}
}
private static IrisImageMapMaskSampler resolveMasks(
RuntimeBinding binding,
Map<String, RuntimeBinding> bindings
) {
if (binding.maskDefinitions.isEmpty()) {
return IrisImageMapMaskSampler.empty();
}
List<IrisImageMapMaskSampler.Layer> masks = new ArrayList<>(binding.maskDefinitions.size());
for (IrisImageMapMask mask : binding.maskDefinitions) {
if (mask == null) {
throw validation("Image-map '" + binding.key + "' contains a null mask reference");
}
String maskKey = requireText(mask.getMap(), "Mask reference on image-map '" + binding.key + "'");
RuntimeBinding maskBinding = bindings.get(maskKey);
if (maskBinding == null) {
throw validation("Image-map '" + binding.key + "' references missing MASK binding '" + maskKey + "'");
}
if (maskBinding.application != IrisImageMapApplication.MASK) {
throw validation("Image-map '" + binding.key + "' references '" + maskKey + "', which is not a MASK binding");
}
if (mask.getOperation() == null) {
throw validation("Mask '" + maskKey + "' on image-map '" + binding.key + "' requires an operation");
}
if (!range(mask.getThreshold()) || !range(mask.getFalloff())) {
throw validation("Mask '" + maskKey + "' threshold and falloff must be finite values within 0..1");
}
masks.add(IrisImageMapMaskSampler.layer(maskBinding.compiled, mask));
}
return new IrisImageMapMaskSampler(masks);
}
private static Set<String> legendTargets(IrisImageMap definition) {
Set<String> targets = new LinkedHashSet<>();
if (definition.getColors() != null) {
for (String target : definition.getColors().values()) {
if (target != null && !target.isBlank()) {
targets.add(target);
}
}
}
String fallback = definition.getFallbackTarget();
if (fallback != null && !fallback.isBlank()) {
targets.add(fallback);
}
return targets;
}
private static InferredType resolveBiomeType(String biomeKey, IrisDimension dimension, IrisData data) {
Set<InferredType> types = new LinkedHashSet<>();
for (IrisRegion region : dimension.getAllRegions(() -> data)) {
if (region == null) {
continue;
}
if (region.getLandBiomes().contains(biomeKey)) {
types.add(InferredType.LAND);
}
if (region.getSeaBiomes().contains(biomeKey)) {
types.add(InferredType.SEA);
}
if (region.getShoreBiomes().contains(biomeKey)) {
types.add(InferredType.SHORE);
}
}
if (types.size() != 1) {
throw validation("Image-mapped biome '" + biomeKey
+ "' must occur in exactly one landBiomes, seaBiomes, or shoreBiomes role across the dimension; found "
+ types);
}
return types.iterator().next();
}
private static String localResourceKey(String target) {
String normalized = requireText(target, "Image-map Iris resource target");
int separator = normalized.indexOf(':');
if (separator < 0) {
return normalized;
}
if (!normalized.startsWith("iris:") || separator == normalized.length() - 1) {
throw validation("Iris biome and region targets must be bare pack keys or use the iris: namespace, got '"
+ target + "'");
}
return normalized.substring(separator + 1);
}
private static String requireText(String value, String name) {
if (value == null || value.isBlank()) {
throw validation(name + " must not be blank");
}
return value.trim();
}
private static boolean range(double value) {
return Double.isFinite(value) && value >= 0D && value <= 1D;
}
private static boolean isMaskType(IrisImageMapType type) {
return type == IrisImageMapType.BINARY_MASK
|| type == IrisImageMapType.GRAYSCALE_MASK
|| type == IrisImageMapType.ALPHA_MASK;
}
private static IrisImageMapValidationException validation(String message) {
return new IrisImageMapValidationException(message);
}
private static final class RuntimeBinding {
private final String key;
private final IrisImageMapApplication application;
private final CompiledIrisImageMap compiled;
private final Map<String, IrisRegion> regions;
private final Map<String, IrisBiome> biomes;
private final Map<String, PlatformBlockState> blocks;
private final List<IrisImageMapMask> maskDefinitions;
private IrisImageMapMaskSampler masks = IrisImageMapMaskSampler.empty();
private RuntimeBinding(
String key,
IrisImageMapApplication application,
CompiledIrisImageMap compiled,
Map<String, IrisRegion> regions,
Map<String, IrisBiome> biomes,
Map<String, PlatformBlockState> blocks,
List<IrisImageMapMask> maskDefinitions
) {
this.key = key;
this.application = application;
this.compiled = compiled;
this.regions = regions;
this.biomes = biomes;
this.blocks = blocks;
this.maskDefinitions = maskDefinitions;
}
private double maskWeight(double worldX, double worldZ) {
return masks.sample(worldX, worldZ);
}
}
}
@@ -0,0 +1,18 @@
package art.arcane.iris.engine.image;
import art.arcane.iris.engine.object.image.IrisImageColorMode;
public record IrisImageMapSourceMetadata(
String format,
IrisImageColorMode colorMode,
int width,
int height,
int colorComponents,
int channels,
int bitDepth,
boolean alpha,
double minimumAlpha,
double maximumAlpha,
String decodedContentHash
) {
}
@@ -0,0 +1,35 @@
package art.arcane.iris.engine.image;
import java.util.List;
public final class IrisImageMapValidationException extends IllegalArgumentException {
private final List<String> diagnostics;
public IrisImageMapValidationException(String diagnostic) {
this(List.of(diagnostic));
}
public IrisImageMapValidationException(List<String> diagnostics) {
super(message(diagnostics));
if (diagnostics == null || diagnostics.isEmpty()) {
throw new IllegalArgumentException("Image-map validation requires at least one diagnostic");
}
this.diagnostics = List.copyOf(diagnostics);
}
public IrisImageMapValidationException(String diagnostic, Throwable cause) {
super(diagnostic, cause);
this.diagnostics = List.of(diagnostic);
}
public List<String> getDiagnostics() {
return diagnostics;
}
private static String message(List<String> diagnostics) {
if (diagnostics == null || diagnostics.isEmpty()) {
return "Image-map validation failed";
}
return String.join("; ", diagnostics);
}
}
@@ -0,0 +1,313 @@
/*
* 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.mantle.runtime.MantleChunk;
import art.arcane.volmlib.util.math.PowerOfTwoCoordinates;
import art.arcane.volmlib.util.matter.Matter;
import art.arcane.volmlib.util.matter.MatterCavern;
import art.arcane.volmlib.util.matter.MatterSlice;
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 MatterCavern ORPHAN_CAVERN = new MatterCavern(true, "", (byte) 0);
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;
}
/**
* Cheap pre-check: may any block in [minY, maxY] be carved at all? Default true keeps
* every implementor correct; the mantle-backed access answers from section slice
* presence so an uncarved chunk skips the full band fill + scan.
*/
default boolean mayContainCarvedCells(int minY, int maxY) {
return true;
}
}
private CarveOrphanSweep() {
}
static int sweepChunk(
MantleChunk<Matter> chunk,
int[] surfaceHeights,
int maxSurfaceBreakDepth,
int worldCeilingY,
int[] surfaceFluidBoundaryStartY,
int fluidHeight
) {
if (chunk == null) {
return 0;
}
return sweep(surfaceHeights, maxSurfaceBreakDepth, 0, worldCeilingY,
new MantleCarveAccess(chunk, 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;
}
if (!access.mayContainCarvedCells(bandFloor, bandTop)) {
// Same early return the carvedPresent check reaches, without zero-filling and
// scanning the whole band first.
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 MantleChunk<Matter> chunk;
private final int[] surfaceFluidBoundaryStartY;
private final int fluidHeight;
private MatterSlice<MatterCavern> cachedSlice;
private int cachedSectionIndex = -1;
private MantleCarveAccess(MantleChunk<Matter> chunk, int[] surfaceFluidBoundaryStartY, int fluidHeight) {
this.chunk = chunk;
this.surfaceFluidBoundaryStartY = surfaceFluidBoundaryStartY;
this.fluidHeight = fluidHeight;
}
@Override
public boolean isCarved(int localX, int y, int localZ) {
MatterSlice<MatterCavern> cavernSlice = resolveSlice(y >> 4);
if (cavernSlice == null) {
return false;
}
MatterCavern cavern = cavernSlice.get(localX, y & 15, localZ);
return cavern != null && cavern.isCavern();
}
@Override
public void markCarved(int localX, int y, int localZ) {
chunk.getOrCreate(y >> 4).slice(MatterCavern.class).set(localX, y & 15, localZ, ORPHAN_CAVERN);
cachedSectionIndex = -1;
cachedSlice = null;
}
@Override
public boolean isProtected(int localX, int y, int localZ) {
int columnIndex = PowerOfTwoCoordinates.packLocal16(localX, localZ);
return SurfaceFluidBoundaryPlan.protects(surfaceFluidBoundaryStartY, columnIndex, y, fluidHeight);
}
@Override
public boolean mayContainCarvedCells(int minY, int maxY) {
int minSection = Math.max(0, minY >> 4);
int maxSection = Math.min(chunk.sectionCount() - 1, maxY >> 4);
for (int sectionIndex = minSection; sectionIndex <= maxSection; sectionIndex++) {
Matter section = chunk.get(sectionIndex);
if (section != null && section.getSlice(MatterCavern.class) != null) {
return true;
}
}
return false;
}
private MatterSlice<MatterCavern> resolveSlice(int sectionIndex) {
if (sectionIndex == cachedSectionIndex) {
return cachedSlice;
}
Matter section = sectionIndex >= 0 && sectionIndex < chunk.sectionCount() ? chunk.get(sectionIndex) : null;
cachedSlice = section == null ? null : section.getSlice(MatterCavern.class);
cachedSectionIndex = sectionIndex;
return cachedSlice;
}
}
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,73 @@
/*
* 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.matter.Matter;
import art.arcane.volmlib.util.matter.MatterCavern;
import art.arcane.volmlib.util.matter.MatterSlice;
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];
MatterCavern[] matterByY = new MatterCavern[0];
Matter[] sectionMatter = new Matter[0];
MatterSlice<?>[] sectionSlices = new MatterSlice<?>[0];
int adaptiveGeometryStep = -1;
int adaptiveGeometryAxisCells = -1;
boolean fullWeightsInitialized;
}
@@ -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.engine.object.terrain.carving.IrisCaveFieldModule;
import art.arcane.iris.engine.object.value.IrisRange;
import art.arcane.iris.util.project.noise.CNG;
final class CaveFieldModuleState {
final CNG density;
final int minY;
final int maxY;
final double weight;
final double threshold;
final boolean invert;
final double minContribution;
final double maxContribution;
CaveFieldModuleState(IrisCaveFieldModule module, CNG density) {
IrisRange range = module.getVerticalRange();
this.density = density;
this.minY = (int) Math.floor(range.getMin());
this.maxY = (int) Math.ceil(range.getMax());
this.weight = module.getWeight();
this.threshold = module.getThreshold();
this.invert = module.isInvert();
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.noiseFastSigned3D(x, y, z);
return invert ? (threshold - sampled) * weight : (sampled - threshold) * weight;
}
double sample(double x, double y, double z) {
double sampled = density.noiseFastSigned3D(x, y, z);
return invert ? (threshold - sampled) * weight : (sampled - threshold) * weight;
}
}
@@ -0,0 +1,120 @@
/*
* 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.mantle.runtime.MantleChunk;
import art.arcane.volmlib.util.math.PowerOfTwoCoordinates;
import art.arcane.volmlib.util.matter.Matter;
import art.arcane.volmlib.util.matter.MatterCavern;
import art.arcane.volmlib.util.matter.MatterSlice;
import java.util.BitSet;
import java.util.IdentityHashMap;
import java.util.Map;
final class CaveFluidSupportPlan {
private final IdentityHashMap<MatterCavern, FluidCandidateGroup> groups = new IdentityHashMap<>();
void add(int localX, int y, int localZ, MatterCavern fluid, MatterCavern air) {
FluidCandidateGroup group = groups.computeIfAbsent(fluid, key -> new FluidCandidateGroup(fluid, air));
int columnIndex = PowerOfTwoCoordinates.packLocal16(localX, localZ);
group.positions.set((y << 8) | columnIndex);
}
void resolve(MantleChunk<Matter> chunk) {
if (chunk == null) {
groups.clear();
return;
}
for (Map.Entry<MatterCavern, FluidCandidateGroup> entry : groups.entrySet()) {
FluidCandidateGroup group = entry.getValue();
for (int position = group.positions.nextSetBit(0); position >= 0; position = group.positions.nextSetBit(position + 1)) {
int y = position >>> 8;
int columnIndex = position & 255;
int localX = PowerOfTwoCoordinates.unpackLocal16X(columnIndex);
int localZ = columnIndex & 15;
MatterCavern current = getCavern(chunk, localX, y, localZ);
if (current != group.fluid || hasCupSupport(chunk, localX, y, localZ)) {
continue;
}
Matter section = chunk.get(y >> 4);
MatterSlice<MatterCavern> cavernSlice = section.getSlice(MatterCavern.class);
cavernSlice.set(localX, y & 15, localZ, group.air);
}
}
groups.clear();
}
private static boolean hasCupSupport(MantleChunk<Matter> chunk, int localX, int y, int localZ) {
if (localX <= 0 || localX >= 15 || localZ <= 0 || localZ >= 15
|| y <= 1 || !isSolid(chunk, localX, y - 1, localZ)
|| !isSolid(chunk, localX, y - 2, localZ)) {
return false;
}
int support = 0;
if (isSolid(chunk, localX + 1, y, localZ)) {
support++;
}
if (isSolid(chunk, localX - 1, y, localZ)) {
support++;
}
if (isSolid(chunk, localX, y, localZ + 1)) {
support++;
}
if (isSolid(chunk, localX, y, localZ - 1)) {
support++;
}
if (isSolid(chunk, localX, y + 1, localZ)) {
support++;
}
return support >= 4;
}
private static boolean isSolid(MantleChunk<Matter> chunk, int localX, int y, int localZ) {
if (localX < 0 || localX >= 16 || localZ < 0 || localZ >= 16) {
return false;
}
MatterCavern cavern = getCavern(chunk, localX, y, localZ);
return cavern == null || !cavern.isCavern();
}
private static MatterCavern getCavern(MantleChunk<Matter> chunk, int localX, int y, int localZ) {
Matter section = chunk.get(y >> 4);
if (section == null) {
return null;
}
MatterSlice<MatterCavern> cavernSlice = section.getSlice(MatterCavern.class);
return cavernSlice == null ? null : cavernSlice.get(localX, y & 15, localZ);
}
private static final class FluidCandidateGroup {
private final MatterCavern fluid;
private final MatterCavern air;
private final BitSet positions = new BitSet();
private FluidCandidateGroup(MatterCavern fluid, MatterCavern air) {
this.fluid = fluid;
this.air = air;
}
}
}
@@ -0,0 +1,286 @@
/*
* Iris is a World Generator for Minecraft Bukkit 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.core.loader.IrisData;
import art.arcane.iris.engine.data.cache.Cache;
import art.arcane.iris.engine.framework.Engine;
import art.arcane.iris.engine.object.placement.IObjectPlacer;
import art.arcane.iris.engine.object.prefab.TileData;
import art.arcane.iris.spi.PlatformBlockState;
import art.arcane.iris.util.common.data.B;
import art.arcane.volmlib.util.collection.KList;
import it.unimi.dsi.fastutil.longs.Long2IntOpenHashMap;
import org.jetbrains.annotations.Nullable;
import java.util.HashMap;
import java.util.Map;
final class CaveObjectPlacementTransaction implements IObjectPlacer {
private static final int CACHE_MISS = Integer.MIN_VALUE;
private final IObjectPlacer delegate;
private final Engine engine;
private final int anchorY;
private final int minDepthBelowSurface;
private final int worldHeight;
private final KList<BufferedMutation> mutations;
private final Map<PositionKey, PlatformBlockState> bufferedBlocks;
private final Long2IntOpenHashMap surfaceHeights;
private final Long2IntOpenHashMap caveCeilings;
private int blockWrites;
CaveObjectPlacementTransaction(IObjectPlacer delegate, int anchorY, int minDepthBelowSurface) {
this.delegate = delegate;
this.engine = delegate.getEngine();
this.anchorY = anchorY;
this.minDepthBelowSurface = Math.max(0, minDepthBelowSurface);
this.worldHeight = engine == null ? 0 : engine.getHeight();
this.mutations = new KList<>();
this.bufferedBlocks = new HashMap<>();
this.surfaceHeights = new Long2IntOpenHashMap();
this.caveCeilings = new Long2IntOpenHashMap();
this.surfaceHeights.defaultReturnValue(CACHE_MISS);
this.caveCeilings.defaultReturnValue(CACHE_MISS);
}
CommitResult commit() {
if (blockWrites == 0) {
discard();
return CommitResult.EMPTY;
}
for (BufferedMutation mutation : mutations) {
if (!isWithinBounds(mutation.x(), mutation.y(), mutation.z())) {
discard();
return CommitResult.REJECTED_BOUNDS;
}
}
for (BufferedMutation mutation : mutations) {
mutation.apply(delegate);
}
discard();
return CommitResult.COMMITTED;
}
void discard() {
mutations.clear();
bufferedBlocks.clear();
blockWrites = 0;
}
int getCaveCeiling(int x, int z) {
long key = Cache.key(x, z);
int cached = caveCeilings.get(key);
if (cached != CACHE_MISS) {
return cached;
}
int ceiling = findCaveCeiling(x, z);
caveCeilings.put(key, ceiling);
return ceiling;
}
static int maxBuriedY(int worldHeight, int surfaceY, int minDepthBelowSurface) {
return Math.min(worldHeight - 1, surfaceY - Math.max(0, minDepthBelowSurface));
}
@Override
public int getHighest(int x, int z, IrisData data) {
return delegate.getHighest(x, z, data);
}
@Override
public int getHighest(int x, int z, IrisData data, boolean ignoreFluid) {
return delegate.getHighest(x, z, data, ignoreFluid);
}
@Override
public void set(int x, int y, int z, PlatformBlockState state) {
if (state == null) {
return;
}
mutations.add(new BlockMutation(x, y, z, state));
bufferedBlocks.put(new PositionKey(x, y, z), state);
blockWrites++;
}
@Override
public PlatformBlockState get(int x, int y, int z) {
PlatformBlockState buffered = bufferedBlocks.get(new PositionKey(x, y, z));
return buffered == null ? delegate.get(x, y, z) : buffered;
}
@Override
public boolean isPreventingDecay() {
return delegate.isPreventingDecay();
}
@Override
public boolean isCarved(int x, int y, int z) {
return delegate.isCarved(x, y, z);
}
@Override
public boolean isSurfaceSolid(int x, int y, int z) {
return delegate.isSurfaceSolid(x, y, z);
}
@Override
public boolean isSolid(int x, int y, int z) {
PlatformBlockState buffered = bufferedBlocks.get(new PositionKey(x, y, z));
return buffered == null ? delegate.isSolid(x, y, z) : B.isSolid(buffered);
}
@Override
public boolean isUnderwater(int x, int z) {
return delegate.isUnderwater(x, z);
}
@Override
public int getFluidHeight() {
return delegate.getFluidHeight();
}
@Override
public boolean isDebugSmartBore() {
return delegate.isDebugSmartBore();
}
@Override
public void setTile(int x, int y, int z, TileData tile) {
if (tile != null) {
mutations.add(new TileMutation(x, y, z, tile));
}
}
@Override
public <T> void setData(int x, int y, int z, T data) {
if (data == null) {
return;
}
mutations.add(new DataMutation(x, y, z, data));
if (data instanceof PlatformBlockState state) {
bufferedBlocks.put(new PositionKey(x, y, z), state);
blockWrites++;
}
}
@Override
public <T> @Nullable T getData(int x, int y, int z, Class<T> type) {
for (int i = mutations.size() - 1; i >= 0; i--) {
BufferedMutation mutation = mutations.get(i);
if (mutation.x() != x || mutation.y() != y || mutation.z() != z) {
continue;
}
Object value = mutation.value();
if (type.isInstance(value)) {
return type.cast(value);
}
}
return delegate.getData(x, y, z, type);
}
@Override
public Engine getEngine() {
return engine;
}
private boolean isWithinBounds(int x, int y, int z) {
if (engine == null || y < 0 || y >= worldHeight) {
return false;
}
int surfaceY = getSurfaceHeight(x, z);
if (y > maxBuriedY(worldHeight, surfaceY, minDepthBelowSurface)) {
return false;
}
return y < getCaveCeiling(x, z);
}
private int getSurfaceHeight(int x, int z) {
long key = Cache.key(x, z);
int cached = surfaceHeights.get(key);
if (cached != CACHE_MISS) {
return cached;
}
int surfaceY = engine.getHeight(x, z, true);
surfaceHeights.put(key, surfaceY);
return surfaceY;
}
private int findCaveCeiling(int x, int z) {
if (worldHeight <= 0 || anchorY < 0 || anchorY >= worldHeight) {
return 0;
}
if (!delegate.isCarved(x, anchorY, z)) {
return Math.min(worldHeight, anchorY + 1);
}
int scanLimit = Math.min(worldHeight - 1, Math.max(anchorY, getSurfaceHeight(x, z)));
for (int y = anchorY + 1; y <= scanLimit; y++) {
if (!delegate.isCarved(x, y, z)) {
return y;
}
}
return Math.min(worldHeight, scanLimit + 1);
}
enum CommitResult {
COMMITTED,
EMPTY,
REJECTED_BOUNDS
}
private interface BufferedMutation {
int x();
int y();
int z();
Object value();
void apply(IObjectPlacer placer);
}
private record BlockMutation(int x, int y, int z, PlatformBlockState value) implements BufferedMutation {
@Override
public void apply(IObjectPlacer placer) {
placer.set(x, y, z, value);
}
}
private record TileMutation(int x, int y, int z, TileData value) implements BufferedMutation {
@Override
public void apply(IObjectPlacer placer) {
placer.setTile(x, y, z, value);
}
}
private record DataMutation(int x, int y, int z, Object value) implements BufferedMutation {
@Override
public void apply(IObjectPlacer placer) {
placer.setData(x, y, z, value);
}
}
private record PositionKey(int x, int y, int z) {
}
}
@@ -0,0 +1,74 @@
/*
* Iris is a World Generator for Minecraft Bukkit 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.core.loader.IrisData;
import art.arcane.iris.engine.data.cache.Cache;
import art.arcane.iris.engine.framework.Engine;
import art.arcane.iris.engine.mantle.EngineMantle;
import art.arcane.iris.engine.modifier.IrisFloatingChildBiomeModifier;
import art.arcane.iris.engine.object.terrain.floating.FloatingIslandBoundarySampler;
import art.arcane.iris.engine.object.terrain.floating.FloatingIslandSample;
import art.arcane.iris.engine.object.world.biome.IrisBiome;
import it.unimi.dsi.fastutil.longs.Long2ObjectOpenHashMap;
import it.unimi.dsi.fastutil.longs.LongOpenHashSet;
import org.jetbrains.annotations.Nullable;
final class FloatingIslandSampleResolver implements IslandObjectPlacer.SampleProvider {
private final IrisData data;
private final Engine engine;
private final int chunkHeight;
private final long baseSeed;
private final FloatingIslandBoundarySampler boundarySampler;
private final Long2ObjectOpenHashMap<FloatingIslandSample> sampleCache;
private final LongOpenHashSet resolvedSamples;
FloatingIslandSampleResolver(EngineMantle engineMantle, FloatingIslandBoundarySampler boundarySampler) {
this.data = engineMantle.getData();
this.engine = engineMantle.getEngine();
this.chunkHeight = engine.getHeight();
this.baseSeed = engine.getSeedManager().getTerrain() ^ IrisFloatingChildBiomeModifier.FLOATING_BASE_SEED_SALT;
this.boundarySampler = boundarySampler;
this.sampleCache = new Long2ObjectOpenHashMap<>();
this.resolvedSamples = new LongOpenHashSet();
}
@Override
public @Nullable FloatingIslandSample sample(int x, int z) {
long key = Cache.key(x, z);
if (resolvedSamples.contains(key)) {
return sampleCache.get(key);
}
IrisBiome parent = parent(x, z);
if (parent == null || parent.getFloatingChildBiomes() == null || parent.getFloatingChildBiomes().isEmpty()) {
resolvedSamples.add(key);
return null;
}
FloatingIslandSample sample = FloatingIslandSample.sample(parent, x, z, chunkHeight, baseSeed, data, engine, boundarySampler);
resolvedSamples.add(key);
if (sample != null) {
sampleCache.put(key, sample);
}
return sample;
}
@Nullable IrisBiome parent(int x, int z) {
return boundarySampler.parent(x, z);
}
}
@@ -0,0 +1,211 @@
/*
* Iris is a World Generator for Minecraft Bukkit 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.core.loader.IrisData;
import art.arcane.iris.engine.framework.Engine;
import art.arcane.iris.engine.object.placement.IObjectPlacer;
import art.arcane.iris.engine.object.prefab.TileData;
import art.arcane.iris.spi.PlatformBlockState;
import art.arcane.iris.util.common.data.B;
import art.arcane.volmlib.util.collection.KList;
import org.jetbrains.annotations.Nullable;
import java.util.HashMap;
import java.util.Map;
final class FloatingObjectPlacementTransaction implements IObjectPlacer {
private final IslandObjectPlacer delegate;
private final KList<BufferedMutation> mutations;
private final Map<PositionKey, PlatformBlockState> bufferedBlocks;
private int blockWrites;
FloatingObjectPlacementTransaction(IslandObjectPlacer delegate) {
this.delegate = delegate;
this.mutations = new KList<>();
this.bufferedBlocks = new HashMap<>();
}
CommitResult commit() {
if (blockWrites == 0) {
discard();
return CommitResult.EMPTY;
}
for (BufferedMutation mutation : mutations) {
if (!delegate.canWriteObjectBlock(mutation.x(), mutation.y(), mutation.z())) {
discard();
return CommitResult.REJECTED_SUPPORT;
}
}
for (BufferedMutation mutation : mutations) {
mutation.apply(delegate);
}
discard();
return CommitResult.COMMITTED;
}
void discard() {
mutations.clear();
bufferedBlocks.clear();
blockWrites = 0;
}
@Override
public int getHighest(int x, int z, IrisData data) {
return delegate.getHighest(x, z, data);
}
@Override
public int getHighest(int x, int z, IrisData data, boolean ignoreFluid) {
return delegate.getHighest(x, z, data, ignoreFluid);
}
@Override
public void set(int x, int y, int z, PlatformBlockState state) {
if (state == null) {
return;
}
mutations.add(new BlockMutation(x, y, z, state));
bufferedBlocks.put(new PositionKey(x, y, z), state);
blockWrites++;
}
@Override
public PlatformBlockState get(int x, int y, int z) {
PlatformBlockState state = bufferedBlocks.get(new PositionKey(x, y, z));
return state == null ? delegate.get(x, y, z) : state;
}
@Override
public boolean isPreventingDecay() {
return delegate.isPreventingDecay();
}
@Override
public boolean isCarved(int x, int y, int z) {
return delegate.isCarved(x, y, z);
}
@Override
public boolean isSurfaceSolid(int x, int y, int z) {
return delegate.isSurfaceSolid(x, y, z);
}
@Override
public boolean isSolid(int x, int y, int z) {
PlatformBlockState state = bufferedBlocks.get(new PositionKey(x, y, z));
return state == null ? delegate.isSolid(x, y, z) : B.isSolid(state);
}
@Override
public boolean isUnderwater(int x, int z) {
return delegate.isUnderwater(x, z);
}
@Override
public int getFluidHeight() {
return delegate.getFluidHeight();
}
@Override
public boolean isDebugSmartBore() {
return delegate.isDebugSmartBore();
}
@Override
public void setTile(int x, int y, int z, TileData tile) {
if (tile != null) {
mutations.add(new TileMutation(x, y, z, tile));
}
}
@Override
public <T> void setData(int x, int y, int z, T data) {
if (data == null) {
return;
}
mutations.add(new DataMutation(x, y, z, data));
if (data instanceof PlatformBlockState state) {
bufferedBlocks.put(new PositionKey(x, y, z), state);
blockWrites++;
}
}
@Override
public <T> @Nullable T getData(int x, int y, int z, Class<T> type) {
for (int i = mutations.size() - 1; i >= 0; i--) {
BufferedMutation mutation = mutations.get(i);
if (mutation.x() != x || mutation.y() != y || mutation.z() != z) {
continue;
}
Object value = mutation.value();
if (type.isInstance(value)) {
return type.cast(value);
}
}
return delegate.getData(x, y, z, type);
}
@Override
public Engine getEngine() {
return delegate.getEngine();
}
enum CommitResult {
COMMITTED,
EMPTY,
REJECTED_SUPPORT
}
private interface BufferedMutation {
int x();
int y();
int z();
Object value();
void apply(IObjectPlacer placer);
}
private record BlockMutation(int x, int y, int z, PlatformBlockState value) implements BufferedMutation {
@Override
public void apply(IObjectPlacer placer) {
placer.set(x, y, z, value);
}
}
private record TileMutation(int x, int y, int z, TileData value) implements BufferedMutation {
@Override
public void apply(IObjectPlacer placer) {
placer.setTile(x, y, z, value);
}
}
private record DataMutation(int x, int y, int z, Object value) implements BufferedMutation {
@Override
public void apply(IObjectPlacer placer) {
placer.setData(x, y, z, value);
}
}
private record PositionKey(int x, int y, int z) {
}
}
@@ -0,0 +1,159 @@
/*
* 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.core.loader.IrisData;
import art.arcane.iris.engine.framework.Engine;
import art.arcane.iris.engine.object.placement.IObjectPlacer;
import art.arcane.iris.engine.object.prefab.TileData;
import art.arcane.iris.spi.IrisLogging;
import art.arcane.iris.spi.PlatformBlockState;
final class GoldenDebugObjectPlacer implements IObjectPlacer {
private static final int[] GOLDEN_DEBUG_TARGET = parseGoldenDebugTarget(resolveGoldenDebugSpec());
private static final boolean GOLDEN_DEBUG = GOLDEN_DEBUG_TARGET != null;
private final IObjectPlacer delegate;
private final String tag;
GoldenDebugObjectPlacer(IObjectPlacer delegate, String tag) {
this.delegate = delegate;
this.tag = tag;
}
private static String resolveGoldenDebugSpec() {
String property = System.getProperty("iris.goldendebug");
if (property != null && !property.isBlank()) {
return property;
}
try {
java.io.File marker = new java.io.File("plugins/Iris/goldendebug.txt");
if (marker.isFile()) {
return java.nio.file.Files.readString(marker.toPath()).trim();
}
} catch (Throwable ignored) {
}
return null;
}
private static int[] parseGoldenDebugTarget(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 e) {
return null;
}
}
static boolean isGoldenDebugChunk(int x, int z) {
return GOLDEN_DEBUG
&& Math.abs(GOLDEN_DEBUG_TARGET[0] - x) <= GOLDEN_DEBUG_TARGET[2]
&& Math.abs(GOLDEN_DEBUG_TARGET[1] - z) <= GOLDEN_DEBUG_TARGET[2];
}
@Override
public int getHighest(int x, int z, IrisData data) {
int result = delegate.getHighest(x, z, data);
IrisLogging.debug("Goldendebug query: tag=" + tag + " getHighest(" + x + "," + z + ")=" + result);
return result;
}
@Override
public int getHighest(int x, int z, IrisData data, boolean ignoreFluid) {
int result = delegate.getHighest(x, z, data, ignoreFluid);
IrisLogging.debug("Goldendebug query: tag=" + tag + " getHighest(" + x + "," + z + ",ignoreFluid=" + ignoreFluid + ")=" + result);
return result;
}
@Override
public void set(int x, int y, int z, PlatformBlockState d) {
delegate.set(x, y, z, d);
}
@Override
public PlatformBlockState get(int x, int y, int z) {
return delegate.get(x, y, z);
}
@Override
public boolean isPreventingDecay() {
return delegate.isPreventingDecay();
}
@Override
public boolean isCarved(int x, int y, int z) {
boolean result = delegate.isCarved(x, y, z);
IrisLogging.debug("Goldendebug query: tag=" + tag + " isCarved(" + x + "," + y + "," + z + ")=" + result);
return result;
}
@Override
public boolean isSurfaceSolid(int x, int y, int z) {
return delegate.isSurfaceSolid(x, y, z);
}
@Override
public boolean isSolid(int x, int y, int z) {
boolean result = delegate.isSolid(x, y, z);
IrisLogging.debug("Goldendebug query: tag=" + tag + " isSolid(" + x + "," + y + "," + z + ")=" + result);
return result;
}
@Override
public boolean isUnderwater(int x, int z) {
return delegate.isUnderwater(x, z);
}
@Override
public int getFluidHeight() {
return delegate.getFluidHeight();
}
@Override
public boolean isDebugSmartBore() {
return delegate.isDebugSmartBore();
}
@Override
public <T> void setData(int xx, int yy, int zz, T data) {
delegate.setData(xx, yy, zz, data);
}
@Override
public <T> T getData(int xx, int yy, int zz, Class<T> t) {
return delegate.getData(xx, yy, zz, t);
}
@Override
public void setTile(int xx, int yy, int zz, TileData tile) {
delegate.setTile(xx, yy, zz, tile);
}
@Override
public Engine getEngine() {
return delegate.getEngine();
}
}
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,678 @@
/*
* 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.engine.object.placement.IrisObjectPlacement;
import art.arcane.iris.core.IrisSettings;
import art.arcane.iris.core.loader.IrisData;
import art.arcane.iris.engine.data.cache.Cache;
import art.arcane.iris.engine.framework.IrisStructureLocator;
import art.arcane.iris.engine.framework.PlacedStructurePiece;
import art.arcane.iris.engine.framework.StructurePlacementScope;
import art.arcane.iris.engine.framework.StructurePlacementMarker;
import art.arcane.iris.engine.framework.TreeBlockMaterial;
import art.arcane.iris.engine.mantle.ComponentFlag;
import art.arcane.iris.engine.mantle.EngineMantle;
import art.arcane.iris.engine.mantle.IrisMantleComponent;
import art.arcane.iris.engine.mantle.MantleWriter;
import art.arcane.iris.engine.object.world.biome.IrisBiome;
import art.arcane.iris.engine.object.world.dimension.IrisDimension;
import art.arcane.iris.engine.object.material.IrisMaterialPalette;
import art.arcane.iris.engine.object.prefab.IrisObject;
import art.arcane.iris.engine.object.placement.ObjectPlaceMode;
import art.arcane.iris.engine.object.world.region.IrisRegion;
import art.arcane.iris.engine.object.structure.IrisStructure;
import art.arcane.iris.engine.object.structure.IrisStructureCarveShape;
import art.arcane.iris.engine.object.structure.IrisStructurePlacement;
import art.arcane.iris.engine.object.structure.IrisStructureStiltSettings;
import art.arcane.iris.engine.object.structure.IrisStructureTerrain;
import art.arcane.iris.engine.object.structure.IrisStructureTerrainMode;
import art.arcane.iris.spi.IrisLogging;
import art.arcane.iris.spi.PlatformBlockState;
import art.arcane.iris.util.common.data.B;
import art.arcane.iris.util.common.math.IrisBlockVector;
import art.arcane.iris.util.project.matter.TileWrapper;
import art.arcane.iris.util.project.noise.CNG;
import art.arcane.volmlib.util.collection.KList;
import art.arcane.iris.util.project.context.ChunkContext;
import art.arcane.volmlib.util.documentation.ChunkCoordinates;
import art.arcane.volmlib.util.mantle.runtime.MantleChunk;
import art.arcane.volmlib.util.matter.Matter;
import art.arcane.volmlib.util.matter.MatterCavern;
import art.arcane.volmlib.util.matter.MatterStructurePOI;
import art.arcane.volmlib.util.mantle.flag.ReservedFlag;
import art.arcane.volmlib.util.math.RNG;
import it.unimi.dsi.fastutil.longs.Long2IntMap;
import it.unimi.dsi.fastutil.longs.Long2IntOpenHashMap;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
@ComponentFlag(ReservedFlag.JIGSAW)
public class IrisStructureComponent extends IrisMantleComponent {
private static final MatterCavern CARVE_CAVERN = new MatterCavern(true, "", (byte) 3);
public IrisStructureComponent(EngineMantle engineMantle) {
super(engineMantle, ReservedFlag.JIGSAW, 3);
}
@Override
@ChunkCoordinates
public void generateLayer(MantleWriter writer, int x, int z, ChunkContext context) {
for (IrisStructurePlacement placement : StructurePlacementScope.placementsAt(
getEngineMantle().getEngine(), x, z)) {
if (!placement.hasIrisStructures()) {
continue;
}
placeFromPlacement(writer, placement, x, z);
}
}
@ChunkCoordinates
private void placeFromPlacement(MantleWriter writer, IrisStructurePlacement placement, int cx, int cz) {
IrisStructureLocator.ResolvedPlacement resolved = IrisStructureLocator.resolvePlacement(
getEngineMantle().getEngine(), placement, cx, cz);
if (resolved == null) {
return;
}
boolean trace = IrisSettings.get().getGeneral().isDebug();
if (trace) {
IrisLogging.debug("[StructTrace] ORIGIN chunk=" + cx + "," + cz + " structures=" + placement.getStructures()
+ " anchor=" + placement.resolvedAnchor() + " band=" + placement.getMinHeight() + ".." + placement.getMaxHeight());
}
String key = resolved.structureKey();
IrisStructure structure = resolved.structure();
KList<PlacedStructurePiece> pieces = resolvedPiecesOrNull(resolved, cx, cz);
if (pieces == null) {
return;
}
RNG rng = resolved.rng();
int baseY = resolved.baseY();
if (trace) {
IrisLogging.debug("[StructTrace] ASSEMBLED chunk=" + cx + "," + cz + " key=" + key + " baseY=" + baseY + " pieces=" + pieces.size());
}
if (!placement.isAnchoredUnderground()) {
clearIntersectingObjectTrees(writer, resolved);
}
IrisStructureTerrain terrain = placement.resolvedTerrain();
IrisStructureTerrainMode terrainMode = terrain.resolvedMode();
if (terrainMode == IrisStructureTerrainMode.FORCE_CARVE) {
forceCarveStructure(writer, pieces, terrain);
} else if (terrainMode == IrisStructureTerrainMode.BORE) {
boreStructure(writer, pieces, terrain);
} else if (terrainMode != IrisStructureTerrainMode.PRESERVE
&& terrainMode != IrisStructureTerrainMode.SOURCE) {
throw new IllegalStateException("Iris assembly terrain mode " + terrainMode
+ " is not implemented for structure '" + key + "'");
}
ObjectPlaceMode mode = structure.getPlaceMode();
int failedPieces = 0;
IrisStructureStiltSettings stilt = placement.getStilt();
Long2IntOpenHashMap foundationColumns = stilt == null
? null : new Long2IntOpenHashMap();
boolean supportNonOccluding = stilt != null && stilt.isSupportNonOccluding();
if (placement.isAnchoredUnderground()) {
ObjectPlaceMode undergroundMode = (mode == ObjectPlaceMode.ORGANIC_STILT || mode == ObjectPlaceMode.CEILING_HANG)
? mode : ObjectPlaceMode.STRUCTURE_PIECE;
for (PlacedStructurePiece p : pieces) {
if (placeObject(writer, structure, p, undergroundMode, p.getY(), rng,
foundationColumns, supportNonOccluding) == -1) {
failedPieces++;
}
}
} else if (mode == ObjectPlaceMode.STRUCTURE_PIECE || mode == ObjectPlaceMode.FLOATING) {
for (PlacedStructurePiece p : pieces) {
if (placeObject(writer, structure, p, ObjectPlaceMode.STRUCTURE_PIECE, p.getY(), rng,
foundationColumns, supportNonOccluding) == -1) {
failedPieces++;
}
}
} else if (pieces.size() == 1) {
if (placeObject(writer, structure, pieces.getFirst(), mode, -1, rng,
foundationColumns, supportNonOccluding) == -1) {
failedPieces++;
}
} else {
for (PlacedStructurePiece p : pieces) {
if (placeObject(writer, structure, p, ObjectPlaceMode.STRUCTURE_PIECE, p.getY(), rng,
foundationColumns, supportNonOccluding) == -1) {
failedPieces++;
}
}
}
requireAppliedPieces(resolved, cx, cz, failedPieces);
if (failedPieces == 0 && stilt != null) {
placeFoundation(writer, foundationColumns, stilt, rng, !placement.isAnchoredUnderground());
}
}
private void placeFoundation(MantleWriter writer, Long2IntOpenHashMap columns,
IrisStructureStiltSettings settings, RNG rng,
boolean surfaceStructure) {
IrisMaterialPalette palette = Objects.requireNonNull(
settings.getPalette(), "Structure stilt palette must not be null");
int mantleOffset = getEngineMantle().getEngine().getMinHeight();
int maxDepth = Math.max(1, settings.getMaxDepth());
for (Long2IntMap.Entry column : columns.long2IntEntrySet()) {
int worldX = StructureFoundationPlanner.unpackX(column.getLongKey());
int worldZ = StructureFoundationPlanner.unpackZ(column.getLongKey());
int foundationY = column.getIntValue();
PlatformBlockState foundationState = writer.getDataIfPresent(
worldX, foundationY, worldZ, PlatformBlockState.class);
if (foundationState == null || !foundationState.isSolid()) {
continue;
}
int terrainHeight = getEngineMantle().trueHeight(worldX, worldZ);
int groundY = StructureFoundationPlanner.findGroundY(
foundationY, maxDepth, 0,
y -> {
PlatformBlockState overlay = writer.getDataIfPresent(
worldX, y, worldZ, PlatformBlockState.class);
boolean carved = writer.getDataIfPresent(
worldX, y, worldZ, MatterCavern.class) != null;
return surfaceStructure
? StructureFoundationPlanner.isSurfaceSupportBoundary(
overlay, carved, y, terrainHeight)
: StructureFoundationPlanner.isGroundSolid(
overlay, carved, y, terrainHeight);
});
if (groundY == StructureFoundationPlanner.NO_GROUND) {
continue;
}
StructureFoundationPlanner.fillSupportColumn(foundationY, groundY, y -> {
writeFoundationSupport(
writer, palette, rng, getData(), worldX, y, worldZ, mantleOffset);
});
}
}
static void writeFoundationSupport(MantleWriter writer, IrisMaterialPalette palette, RNG rng,
IrisData data, int worldX, int mantleY, int worldZ,
int mantleOffset) {
int worldY = mantleY + mantleOffset;
PlatformBlockState support = palette.get(rng, worldX, worldY, worldZ, data);
if (support == null) {
throw new IllegalStateException("Structure stilt palette resolved no block at "
+ worldX + "," + worldY + "," + worldZ);
}
writer.clearData(worldX, mantleY, worldZ, MatterCavern.class);
writer.set(worldX, mantleY, worldZ, support);
}
static KList<PlacedStructurePiece> resolvedPiecesOrNull(
IrisStructureLocator.ResolvedPlacement resolved,
int chunkX,
int chunkZ
) {
if (resolved == null) {
return null;
}
KList<PlacedStructurePiece> pieces = resolved.pieces();
if (!IrisStructureLocator.requirePlacementOutput(
resolved.placement(), resolved.structureKey(), chunkX, chunkZ,
pieces != null && !pieces.isEmpty(), "placement application received no assembled pieces")) {
return null;
}
return pieces;
}
static void requireAppliedPieces(IrisStructureLocator.ResolvedPlacement resolved,
int chunkX, int chunkZ, int failedPieces) {
IrisStructureLocator.requirePlacementOutput(
resolved.placement(), resolved.structureKey(), chunkX, chunkZ, failedPieces == 0,
"object placement rejected " + failedPieces + " of " + resolved.pieces().size()
+ " assembled piece(s)");
}
private void boreStructure(MantleWriter writer, KList<PlacedStructurePiece> pieces,
IrisStructureTerrain terrain) {
int[] bounds = computePieceBounds(pieces);
if (bounds == null) {
return;
}
int pad = Math.max(0, terrain.getHorizontalPadding());
int minX = bounds[0] - pad;
int minY = bounds[1] - Math.max(0, terrain.getFloorPadding());
int minZ = bounds[2] - pad;
int maxX = bounds[3] + pad;
int maxY = bounds[4] + Math.max(0, terrain.getCeilingPadding());
int maxZ = bounds[5] + pad;
int worldMin = getEngineMantle().getEngine().getMinHeight() + 1;
int worldMax = getEngineMantle().getEngine().getMinHeight() + getEngineMantle().getEngine().getHeight() - 1;
minY = Math.max(minY, worldMin);
maxY = Math.min(maxY, worldMax);
if (maxX < minX || maxY < minY || maxZ < minZ) {
return;
}
int mantleOffset = getEngineMantle().getEngine().getMinHeight();
for (int bx = minX; bx <= maxX; bx++) {
for (int by = minY; by <= maxY; by++) {
for (int bz = minZ; bz <= maxZ; bz++) {
writer.setForcedCarve(bx, by - mantleOffset, bz, CARVE_CAVERN);
}
}
}
}
private void forceCarveStructure(MantleWriter writer, KList<PlacedStructurePiece> pieces,
IrisStructureTerrain terrain) {
int[] bounds = computePieceBounds(pieces);
if (bounds == null) {
return;
}
IrisStructureCarveShape shape = terrain.resolvedShape();
int margin = Math.max(0, terrain.getHorizontalPadding());
int head = Math.max(0, terrain.getCeilingPadding());
int floorCut = Math.max(0, terrain.getFloorPadding());
double strength = terrain.resolvedErosionStrength();
int mantleOffset = getEngineMantle().getEngine().getMinHeight();
int worldMin = getEngineMantle().getEngine().getMinHeight() + 1;
int worldMax = getEngineMantle().getEngine().getMinHeight() + getEngineMantle().getEngine().getHeight() - 1;
int upExtension = shape.maximumCeilingExtension(head, strength);
if (shape == IrisStructureCarveShape.BOX) {
carveOverboreBox(writer, bounds, margin, head, floorCut, mantleOffset, worldMin, worldMax);
return;
}
long work = overboreCandidateVolume(bounds, margin, upExtension, floorCut);
StructureCarvingFootprint footprint = StructureCarvingFootprint.from(
pieces, margin, Integer.MAX_VALUE);
if (footprint == null) {
throw new IllegalStateException("Structure force-carve footprint is empty or exceeds addressable memory");
}
double frequency = terrain.resolvedErosionFrequency();
boolean eroded = shape == IrisStructureCarveShape.ERODED && strength > 0D;
CNG blob = null;
CNG roll = null;
if (eroded) {
RNG noiseRng = new RNG(seed() + Cache.key(bounds[0], bounds[2]));
blob = CNG.signature(noiseRng);
roll = CNG.signature(noiseRng.nextParallelRNG(0x2A17));
}
if (IrisSettings.get().getGeneral().isDebug()) {
IrisLogging.info("Overbore carving structure cavern: shape=" + shape + " pieces=" + pieces.size()
+ " footprint=" + footprint.width() + "x" + footprint.depth()
+ " margin=" + margin + " head=" + head + " floorCut=" + floorCut + " work=" + work);
}
double sideReachSquared = (double) margin * margin;
double downReach = Math.max(1D, floorCut);
for (int bz = footprint.minZ(); bz <= footprint.maxZ(); bz++) {
int footprintIndex = footprint.indexAt(footprint.minX(), bz);
for (int bx = footprint.minX(); bx <= footprint.maxX(); bx++, footprintIndex++) {
long horizontalDistanceSquared = footprint.distanceSquaredAt(footprintIndex);
if (horizontalDistanceSquared < 0L || horizontalDistanceSquared > sideReachSquared) {
continue;
}
double normalizedHorizontalDistanceSquared = sideReachSquared == 0D
? 0D : horizontalDistanceSquared / sideReachSquared;
int sourceMinY = footprint.sourceMinYAt(footprintIndex);
int sourceMaxY = footprint.sourceMaxYAt(footprintIndex);
double upReach = eroded
? StructureCarveEnvelope.erodedUpReach(roll, frequency, strength, bx, bz, head)
: Math.max(1D, head);
int columnUpExtension = eroded
? (int) Math.ceil(upReach) : head;
int minY = Math.max(worldMin, sourceMinY - floorCut);
int maxY = Math.min(worldMax, sourceMaxY + columnUpExtension);
for (int by = minY; by <= maxY; by++) {
double normalizedY = StructureCarveEnvelope.normalizedVerticalDistance(
by, sourceMinY, sourceMaxY, upReach, downReach);
double distanceSquared = normalizedHorizontalDistanceSquared
+ normalizedY * normalizedY;
if (distanceSquared <= 0D) {
writer.setForcedCarve(bx, by - mantleOffset, bz, CARVE_CAVERN);
continue;
}
if (distanceSquared > 1D) {
continue;
}
if (!eroded) {
writer.setForcedCarve(bx, by - mantleOffset, bz, CARVE_CAVERN);
continue;
}
double noise = blob.fitDouble(
0D, 1D, bx * frequency, by * frequency, bz * frequency);
if (StructureCarveEnvelope.shouldCarveOverboreCell(
shape, distanceSquared, noise, strength)) {
writer.setForcedCarve(bx, by - mantleOffset, bz, CARVE_CAVERN);
}
}
}
}
}
private void carveOverboreBox(MantleWriter writer, int[] bounds, int margin, int head, int floorCut,
int mantleOffset, int worldMin, int worldMax) {
int minX = bounds[0] - margin;
int minY = Math.max(worldMin, bounds[1] - floorCut);
int minZ = bounds[2] - margin;
int maxX = bounds[3] + margin;
int maxY = Math.min(worldMax, bounds[4] + head);
int maxZ = bounds[5] + margin;
for (int bx = minX; bx <= maxX; bx++) {
for (int by = minY; by <= maxY; by++) {
for (int bz = minZ; bz <= maxZ; bz++) {
writer.setForcedCarve(bx, by - mantleOffset, bz, CARVE_CAVERN);
}
}
}
}
private static long overboreCandidateVolume(int[] bounds, int margin, int upExtension,
int floorCut) {
return inclusiveVolume(
bounds[0] - margin, bounds[1] - floorCut, bounds[2] - margin,
bounds[3] + margin, bounds[4] + upExtension, bounds[5] + margin);
}
private static long inclusiveVolume(int minX, int minY, int minZ, int maxX, int maxY, int maxZ) {
long width = (long) maxX - minX + 1L;
long height = (long) maxY - minY + 1L;
long depth = (long) maxZ - minZ + 1L;
if (width <= 0L || height <= 0L || depth <= 0L
|| width > Long.MAX_VALUE / height
|| width * height > Long.MAX_VALUE / depth) {
return Long.MAX_VALUE;
}
return width * height * depth;
}
private void clearIntersectingObjectTrees(MantleWriter writer, IrisStructureLocator.ResolvedPlacement resolved) {
int mantleOffset = getEngineMantle().getEngine().getMinHeight();
int worldHeight = getEngineMantle().getEngine().getHeight();
Map<String, ObjectMarkerBounds> intersectingObjects = new HashMap<>();
for (PlacedStructurePiece piece : resolved.pieces()) {
for (IrisBlockVector local : piece.getObject().getBlocks().keys()) {
PlatformBlockState structureState = piece.getObject().getBlocks().get(local);
if (!isOccupiedStructureState(structureState)) {
continue;
}
IrisBlockVector rotated = piece.getRotation().rotate(local.clone());
int y = piece.getY() - mantleOffset + rotated.getBlockY();
if (y >= 0 && y < worldHeight) {
collectIntersectingObjectTreeMarker(
writer, piece.getX() + rotated.getBlockX(), y,
piece.getZ() + rotated.getBlockZ(), intersectingObjects);
}
}
}
for (Map.Entry<String, ObjectMarkerBounds> entry : intersectingObjects.entrySet()) {
clearMarkerOwnedObject(writer, entry.getKey(), entry.getValue(), worldHeight);
}
}
static boolean isOccupiedStructureState(PlatformBlockState state) {
return !B.isAir(state);
}
private void collectIntersectingObjectTreeMarker(MantleWriter writer, int x, int y, int z,
Map<String, ObjectMarkerBounds> intersectingObjects) {
PlatformBlockState state = writer.getDataIfPresent(x, y, z, PlatformBlockState.class);
if (state == null || !state.isTreeBlock()) {
return;
}
String marker = writer.getDataIfPresent(x, y, z, String.class);
if (isOrdinaryObjectMarker(marker)) {
intersectingObjects.computeIfAbsent(marker, ignored -> new ObjectMarkerBounds())
.include(x, y, z);
}
}
private void clearMarkerOwnedObject(MantleWriter writer, String marker,
ObjectMarkerBounds intersections, int worldHeight) {
StructurePlacementMarker.Decoded decoded = StructurePlacementMarker.decode(marker);
if (decoded == null) {
return;
}
IrisObject object = getData().load(IrisObject.class, decoded.objectKey(), false);
if (object == null) {
return;
}
int horizontalSpan = Math.max(1, Math.max(object.getW(), object.getD()));
int verticalSpan = Math.max(1, object.getH());
ObjectMarkerBounds search = intersections.expand(horizontalSpan - 1, verticalSpan - 1, worldHeight);
KList<ObjectBlockPosition> positions = new KList<>();
int minChunkX = Math.floorDiv(search.minX, 16);
int maxChunkX = Math.floorDiv(search.maxX, 16);
int minChunkZ = Math.floorDiv(search.minZ, 16);
int maxChunkZ = Math.floorDiv(search.maxZ, 16);
for (int chunkX = minChunkX; chunkX <= maxChunkX; chunkX++) {
for (int chunkZ = minChunkZ; chunkZ <= maxChunkZ; chunkZ++) {
MantleChunk<Matter> chunk = writer.acquireChunk(chunkX, chunkZ);
if (chunk == null) {
continue;
}
int blockX = chunkX << 4;
int blockZ = chunkZ << 4;
chunk.iterate(String.class, (localX, y, localZ, value) -> {
int x = blockX + localX;
int z = blockZ + localZ;
if (marker.equals(value) && search.contains(x, y, z)) {
positions.add(new ObjectBlockPosition(x, y, z));
}
});
}
}
for (ObjectBlockPosition position : positions) {
writer.clearBlock(position.x(), position.y(), position.z());
writer.clearData(position.x(), position.y(), position.z(), String.class);
writer.clearData(position.x(), position.y(), position.z(), TreeBlockMaterial.class);
writer.clearData(position.x(), position.y(), position.z(), TileWrapper.class);
writer.clearData(position.x(), position.y(), position.z(), MatterStructurePOI.class);
}
}
static boolean isOrdinaryObjectMarker(String marker) {
StructurePlacementMarker.Decoded decoded = StructurePlacementMarker.decode(marker);
return decoded != null && !decoded.structureAware();
}
static ObjectMarkerBounds markerSearchBounds(int minX, int minY, int minZ,
int maxX, int maxY, int maxZ,
int horizontalSpan, int verticalSpan,
int worldHeight) {
ObjectMarkerBounds bounds = new ObjectMarkerBounds();
bounds.minX = minX;
bounds.minY = minY;
bounds.minZ = minZ;
bounds.maxX = maxX;
bounds.maxY = maxY;
bounds.maxZ = maxZ;
return bounds.expand(
Math.max(0, horizontalSpan - 1), Math.max(0, verticalSpan - 1), worldHeight);
}
private int[] computePieceBounds(KList<PlacedStructurePiece> pieces) {
if (pieces == null || pieces.isEmpty()) {
return null;
}
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 (PlacedStructurePiece p : pieces) {
minX = Math.min(minX, p.getMinX());
minY = Math.min(minY, p.getMinY());
minZ = Math.min(minZ, p.getMinZ());
maxX = Math.max(maxX, p.getMaxX());
maxY = Math.max(maxY, p.getMaxY());
maxZ = Math.max(maxZ, p.getMaxZ());
}
return new int[]{minX, minY, minZ, maxX, maxY, maxZ};
}
private int placeObject(MantleWriter writer, IrisStructure structure, PlacedStructurePiece p,
ObjectPlaceMode mode, int y, RNG rng, Long2IntOpenHashMap foundationColumns,
boolean supportNonOccluding) {
IrisObject object = p.getObject();
String objectKey = object.getLoadKey();
IrisObjectPlacement config = structure.createLootPlacement(objectKey);
config.setMode(mode);
config.setRotation(p.getRotation());
if (!structure.getEdit().isEmpty()) {
config.setEdit(structure.getEdit());
}
if (mode != ObjectPlaceMode.STRUCTURE_PIECE && mode != ObjectPlaceMode.FLOATING) {
config.setForcePlace(true);
}
int placeY = (y == -1) ? -1 : y - getEngineMantle().getEngine().getMinHeight();
String marker = structurePlacementMarker(structure, p, objectKey);
return object.place(p.getX(), placeY, p.getZ(), writer, config, rng, (position, state) -> {
StructureFoundationPlanner.recordBaseCell(
foundationColumns, position.getX(), position.getY(), position.getZ(), state,
supportNonOccluding);
if (marker != null && shouldWriteStructureMarker(state)) {
writer.setData(position.getX(), position.getY(), position.getZ(), marker);
}
}, null, getData());
}
static boolean shouldWriteStructureMarker(PlatformBlockState state) {
return state != null && state.isStorageChest();
}
static int structurePlacementId(String structureKey, String objectKey, int x, int y, int z) {
int hash = 17;
hash = 31 * hash + structureKey.hashCode();
hash = 31 * hash + objectKey.hashCode();
hash = 31 * hash + x;
hash = 31 * hash + y;
hash = 31 * hash + z;
return hash & Integer.MAX_VALUE;
}
private static String structurePlacementMarker(IrisStructure structure, PlacedStructurePiece piece, String objectKey) {
String structureKey = structure.getLoadKey();
if (structureKey == null || structureKey.isBlank() || objectKey == null || objectKey.isBlank()) {
return null;
}
int placementId = structurePlacementId(structureKey, objectKey, piece.getX(), piece.getY(), piece.getZ());
return StructurePlacementMarker.encodeStructure(objectKey, placementId, structureKey);
}
@Override
protected int computeRadius() {
IrisDimension dimension = getDimension();
int maxBlocks = 0;
for (IrisRegion region : dimension.getAllRegions(this::getData)) {
maxBlocks = Math.max(maxBlocks, maxBlocksFrom(region.getStructures()));
}
for (IrisBiome biome : dimension.getReachableBiomes(this::getData)) {
maxBlocks = Math.max(maxBlocks, maxBlocksFrom(biome.getStructures()));
}
maxBlocks = Math.max(maxBlocks, maxBlocksFrom(dimension.getStructures()));
return maxBlocks;
}
private int maxBlocksFrom(KList<IrisStructurePlacement> placements) {
int max = 0;
for (IrisStructurePlacement placement : placements) {
if (!placement.hasIrisStructures()) {
continue;
}
IrisStructureTerrain terrain = placement.resolvedTerrain();
int carvePadding = terrain.resolvedMode() == IrisStructureTerrainMode.FORCE_CARVE
|| terrain.resolvedMode() == IrisStructureTerrainMode.BORE
? Math.max(0, terrain.getHorizontalPadding()) : 0;
for (String key : placement.getStructures()) {
IrisStructure structure = getData().load(IrisStructure.class, key, false);
if (structure != null) {
max = Math.max(max, Math.max(1, structure.getMaxSizeChunks()) * 16 + carvePadding);
}
}
}
return max;
}
static final class ObjectMarkerBounds {
private int minX = Integer.MAX_VALUE;
private int minY = Integer.MAX_VALUE;
private int minZ = Integer.MAX_VALUE;
private int maxX = Integer.MIN_VALUE;
private int maxY = Integer.MIN_VALUE;
private int maxZ = Integer.MIN_VALUE;
void include(int x, int y, int z) {
minX = Math.min(minX, x);
minY = Math.min(minY, y);
minZ = Math.min(minZ, z);
maxX = Math.max(maxX, x);
maxY = Math.max(maxY, y);
maxZ = Math.max(maxZ, z);
}
ObjectMarkerBounds expand(int horizontal, int vertical, int worldHeight) {
ObjectMarkerBounds expanded = new ObjectMarkerBounds();
expanded.minX = minX - horizontal;
expanded.minY = Math.max(0, minY - vertical);
expanded.minZ = minZ - horizontal;
expanded.maxX = maxX + horizontal;
expanded.maxY = Math.min(worldHeight - 1, maxY + vertical);
expanded.maxZ = maxZ + horizontal;
return expanded;
}
boolean contains(int x, int y, int z) {
return x >= minX && x <= maxX
&& y >= minY && y <= maxY
&& z >= minZ && z <= maxZ;
}
int minX() {
return minX;
}
int minY() {
return minY;
}
int minZ() {
return minZ;
}
int maxX() {
return maxX;
}
int maxY() {
return maxY;
}
int maxZ() {
return maxZ;
}
}
private record ObjectBlockPosition(int x, int y, int z) {
}
}
@@ -0,0 +1,220 @@
/*
* 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.core.loader.IrisData;
import art.arcane.iris.engine.framework.Engine;
import art.arcane.iris.engine.mantle.MantleWriter;
import art.arcane.iris.engine.object.terrain.floating.FloatingIslandSample;
import art.arcane.iris.engine.object.placement.IObjectPlacer;
import art.arcane.iris.engine.object.terrain.floating.IrisFloatingChildBiomes;
import art.arcane.iris.engine.object.prefab.TileData;
import art.arcane.iris.spi.PlatformBlockState;
import org.jetbrains.annotations.Nullable;
public final class IslandObjectPlacer implements IObjectPlacer {
private static final int OVERHANG_RADIUS = 2;
private static final int OVERHANG_HEIGHT_TOLERANCE = 4;
private final MantleWriter wrapped;
private final SampleProvider samples;
private final IrisFloatingChildBiomes entry;
private final int anchorY;
private final AnchorFace face;
private IslandObjectPlacer(MantleWriter wrapped, AnchorSettings settings) {
this.wrapped = wrapped;
this.samples = settings.samples();
this.entry = settings.entry();
this.anchorY = settings.anchorY();
this.face = settings.face();
}
public static IslandObjectPlacer top(MantleWriter wrapped, SampleProvider samples,
IrisFloatingChildBiomes entry, int anchorY) {
return new IslandObjectPlacer(wrapped, new AnchorSettings(samples, entry, anchorY, AnchorFace.TOP));
}
public static IslandObjectPlacer bottom(MantleWriter wrapped, SampleProvider samples,
IrisFloatingChildBiomes entry, int anchorY) {
return new IslandObjectPlacer(wrapped, new AnchorSettings(samples, entry, anchorY, AnchorFace.BOTTOM));
}
public boolean canWriteObjectBlock(int x, int y, int z) {
return !shouldSkipAirColumn(x, y, z);
}
@Override
public int getHighest(int x, int z, IrisData data) {
FloatingIslandSample sample = samples.sample(x, z);
if (face == AnchorFace.TOP) {
return sample == null ? anchorY : sample.topY();
}
if (sample == null) {
return anchorY;
}
int bottomY = sample.bottomY();
return bottomY < 0 ? anchorY : bottomY;
}
@Override
public int getHighest(int x, int z, IrisData data, boolean ignoreFluid) {
return getHighest(x, z, data);
}
@Override
public boolean isUnderwater(int x, int z) {
return false;
}
@Override
public boolean isSolid(int x, int y, int z) {
FloatingIslandSample sample = samples.sample(x, z);
if (sample != null) {
int index = y - sample.islandBaseY;
if (index >= 0 && index < sample.solidMask.length) {
return sample.solidMask[index];
}
return false;
}
return wrapped.isSolid(x, y, z);
}
@Override
public boolean isCarved(int x, int y, int z) {
return wrapped.isCarved(x, y, z);
}
@Override
public boolean isSurfaceSolid(int x, int y, int z) {
return wrapped.isSurfaceSolid(x, y, z);
}
@Override
public void set(int x, int y, int z, PlatformBlockState state) {
if (!shouldSkipAirColumn(x, y, z)) {
wrapped.set(x, y, z, state);
}
}
@Override
public PlatformBlockState get(int x, int y, int z) {
return wrapped.get(x, y, z);
}
@Override
public boolean isPreventingDecay() {
return wrapped.isPreventingDecay();
}
@Override
public int getFluidHeight() {
return wrapped.getFluidHeight();
}
@Override
public boolean isDebugSmartBore() {
return wrapped.isDebugSmartBore();
}
@Override
public void setTile(int x, int y, int z, TileData tile) {
if (!shouldSkipAirColumn(x, y, z)) {
wrapped.setTile(x, y, z, tile);
}
}
@Override
public <T> void setData(int x, int y, int z, T data) {
if (!shouldSkipAirColumn(x, y, z)) {
wrapped.setData(x, y, z, data);
}
}
@Override
public <T> @Nullable T getData(int x, int y, int z, Class<T> type) {
return wrapped.getData(x, y, z, type);
}
@Override
public Engine getEngine() {
return wrapped == null ? null : wrapped.getEngine();
}
static boolean matchesAnchor(FloatingIslandSample sample, IrisFloatingChildBiomes entry, AnchorFace face) {
if (sample == null) {
return false;
}
return face == AnchorFace.TOP ? sample.entry == entry : sample.bottomEntry() == entry;
}
private boolean shouldSkipAirColumn(int x, int y, int z) {
Engine engine = getEngine();
if (engine != null && (y < 0 || y >= engine.getHeight())) {
return true;
}
FloatingIslandSample sample = samples.sample(x, z);
if (matchesAnchor(sample, entry, face) && isNearAnchorHeight(sample)) {
return face == AnchorFace.BOTTOM && y >= anchorY;
}
if (face == AnchorFace.TOP && y <= anchorY) {
return true;
}
if (face == AnchorFace.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, face) && isNearAnchorHeight(sample)) {
return true;
}
}
}
return false;
}
private boolean isNearAnchorHeight(FloatingIslandSample sample) {
int faceY = face == AnchorFace.TOP ? sample.topY() : sample.bottomY();
return faceY >= 0 && Math.abs(faceY - anchorY) <= OVERHANG_HEIGHT_TOLERANCE;
}
public enum AnchorFace {
TOP,
BOTTOM
}
@FunctionalInterface
public interface SampleProvider {
@Nullable FloatingIslandSample sample(int x, int z);
}
private record AnchorSettings(
SampleProvider samples,
IrisFloatingChildBiomes entry,
int anchorY,
AnchorFace face
) {
}
}
@@ -0,0 +1,708 @@
/*
* 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.engine.IrisComplex;
import art.arcane.iris.engine.UpperDimensionContext;
import art.arcane.iris.engine.mantle.ComponentFlag;
import art.arcane.iris.engine.mantle.EngineMantle;
import art.arcane.iris.engine.mantle.IrisMantleComponent;
import art.arcane.iris.engine.mantle.MantleWriter;
import art.arcane.iris.engine.object.world.biome.IrisBiome;
import art.arcane.iris.engine.object.terrain.carving.IrisCaveProfile;
import art.arcane.iris.engine.object.terrain.carving.IrisDimensionCarvingEntry;
import art.arcane.iris.engine.object.terrain.carving.IrisDimensionCarvingResolver;
import art.arcane.iris.engine.object.world.region.IrisRegion;
import art.arcane.iris.engine.object.value.IrisRange;
import art.arcane.iris.spi.PlatformBlockState;
import art.arcane.iris.util.common.data.B;
import art.arcane.iris.util.project.context.ChunkContext;
import art.arcane.iris.util.project.stream.ProceduralStream;
import art.arcane.iris.util.project.stream.utility.ChunkFillableDoubleStream2D;
import art.arcane.iris.util.simd.SimdKernels;
import art.arcane.iris.util.simd.SimdSupport;
import art.arcane.volmlib.util.documentation.ChunkCoordinates;
import art.arcane.volmlib.util.mantle.flag.ReservedFlag;
import art.arcane.volmlib.util.math.PowerOfTwoCoordinates;
import art.arcane.volmlib.util.scheduling.PrecisionStopwatch;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.IdentityHashMap;
import java.util.List;
import java.util.Map;
@ComponentFlag(ReservedFlag.CARVED)
public class MantleCarvingComponent extends IrisMantleComponent {
private static final int CHUNK_SIZE = 16;
private static final int CHUNK_AREA = CHUNK_SIZE * CHUNK_SIZE;
private static final int BLEND_RADIUS = 3;
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 Object profileCarverLock = new Object();
private volatile Map<IrisCaveProfile, 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++;
}
}
}
public MantleCarvingComponent(EngineMantle engineMantle) {
super(engineMantle, ReservedFlag.CARVED, 0);
}
@Override
public void hotload() {
super.hotload();
// Hotload swaps in fresh IrisCaveProfile instances (identity keys), so retained
// entries would strand a full carver set pinning the closed IrisData per reload.
// Carvers rebuild deterministically from the carve seed, so output is unchanged.
synchronized (profileCarverLock) {
profileCarvers = new IdentityHashMap<>();
}
}
@Override
public void generateLayer(MantleWriter writer, int x, int z, ChunkContext context) {
IrisComplex complex = context.getComplex();
IrisDimensionCarvingResolver.State resolverState = new IrisDimensionCarvingResolver.State();
BlendScratch blendScratch = BLEND_SCRATCH.get();
int[] chunkSurfaceHeights = prepareChunkSurfaceHeights(x, z, context, blendScratch.chunkSurfaceHeights);
PrecisionStopwatch resolveStopwatch = PrecisionStopwatch.start();
List<WeightedProfile> weightedProfiles = resolveWeightedProfiles(x, z, complex, resolverState);
getEngineMantle().getEngine().getMetrics().getCarveResolve().put(resolveStopwatch.getMilliseconds());
int fluidHeight = getDimension().getFluidHeight();
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, writer, x, z, chunkSurfaceHeights, surfaceFluidBoundaryStartY, fluidSupportPlan);
}
UpperDimensionContext upperCtx = getEngineMantle().getEngine().getUpperContext();
if (upperCtx != null && getDimension().isUpperDimensionCarving()) {
carveUpperTerrain(upperCtx, weightedProfiles, writer, x, z, chunkSurfaceHeights, fluidSupportPlan);
}
fluidSupportPlan.resolve(writer.acquireChunk(x, z));
if (!weightedProfiles.isEmpty()) {
CarveOrphanSweep.sweepChunk(
writer.acquireChunk(x, z),
chunkSurfaceHeights,
maxSurfaceBreakDepth(weightedProfiles),
writer.getMantle().getWorldHeight() - 1,
surfaceFluidBoundaryStartY,
fluidHeight
);
}
}
private static int maxSurfaceBreakDepth(List<WeightedProfile> weightedProfiles) {
int maxDepth = 0;
for (WeightedProfile weightedProfile : weightedProfiles) {
maxDepth = Math.max(maxDepth, Math.max(0, weightedProfile.profile.getSurfaceBreakDepth()));
}
return maxDepth;
}
@ChunkCoordinates
private void carveProfile(WeightedProfile weightedProfile, MantleWriter writer, int cx, int cz,
int[] chunkSurfaceHeights, int[] surfaceFluidBoundaryStartY,
CaveFluidSupportPlan fluidSupportPlan) {
IrisCaveCarver3D carver = getCarver(weightedProfile.profile);
carver.carve(writer, cx, cz, weightedProfile.columnWeights, MIN_WEIGHT, THRESHOLD_PENALTY,
weightedProfile.worldYRange, chunkSurfaceHeights, surfaceFluidBoundaryStartY, null, fluidSupportPlan);
}
private void carveUpperTerrain(UpperDimensionContext upperCtx, List<WeightedProfile> normalProfiles,
MantleWriter writer, int cx, int cz, int[] lowerSurfaceHeights,
CaveFluidSupportPlan fluidSupportPlan) {
int chunkHeight = getEngineMantle().getEngine().getHeight();
int worldMinHeight = getEngineMantle().getEngine().getWorld().minHeight();
int gap = getDimension().getUpperDimensionGap();
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 columnIndex = PowerOfTwoCoordinates.packLocal16(localX, localZ);
int rawUpper = upperCtx.getUpperSurfaceY(worldX, worldZ);
int upperY = Math.max(rawUpper, lowerSurfaceHeights[columnIndex] + gap);
if (upperY < minUpperSurfaceY) {
minUpperSurfaceY = upperY;
}
}
}
if (minUpperSurfaceY >= chunkHeight - 2) {
return;
}
IrisRange upperYRange = new IrisRange(
minUpperSurfaceY + worldMinHeight,
chunkHeight - 1 + worldMinHeight
);
IrisRange fullVerticalRange = new IrisRange(0, chunkHeight);
int[] ceilingSurfaceHeights = new int[CHUNK_AREA];
Arrays.fill(ceilingSurfaceHeights, chunkHeight - 1);
for (WeightedProfile weightedProfile : normalProfiles) {
IrisRange constrainedRange;
if (weightedProfile.worldYRange != null) {
double min = Math.max(weightedProfile.worldYRange.getMin(), upperYRange.getMin());
double max = Math.min(weightedProfile.worldYRange.getMax(), upperYRange.getMax());
if (min >= max) {
continue;
}
constrainedRange = new IrisRange(min, max);
} else {
constrainedRange = upperYRange;
}
IrisCaveCarver3D carver = getCarver(weightedProfile.profile);
carver.carve(writer, cx, cz, weightedProfile.columnWeights, MIN_WEIGHT, THRESHOLD_PENALTY,
constrainedRange, ceilingSurfaceHeights, null, fullVerticalRange, fluidSupportPlan);
}
}
private List<WeightedProfile> resolveWeightedProfiles(int chunkX, int chunkZ, IrisComplex complex, IrisDimensionCarvingResolver.State resolverState) {
BlendScratch blendScratch = BLEND_SCRATCH.get();
IrisCaveProfile[] profileField = blendScratch.profileField;
Map<IrisCaveProfile, double[]> columnProfileWeights = blendScratch.columnProfileWeights;
IdentityHashMap<IrisCaveProfile, Boolean> activeProfiles = blendScratch.activeProfiles;
List<IrisCaveProfile> profileOrder = blendScratch.profileOrder;
IrisCaveProfile[] kernelProfiles = blendScratch.kernelProfiles;
double[] kernelProfileWeights = blendScratch.kernelProfileWeights;
activeProfiles.clear();
profileOrder.clear();
fillProfileField(profileField, chunkX, chunkZ, complex, resolverState, 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];
IrisCaveProfile 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++) {
IrisCaveProfile 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 (IrisCaveProfile 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 = SimdSupport.kernels().max(weights, weights.length);
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, resolverState, blendScratch);
resolvedProfiles.addAll(blendedProfiles);
return resolvedProfiles;
}
private List<WeightedProfile> resolveDimensionCarvingProfiles(int chunkX, int chunkZ, IrisDimensionCarvingResolver.State resolverState, BlendScratch blendScratch) {
List<WeightedProfile> weightedProfiles = new ArrayList<>();
List<IrisDimensionCarvingEntry> entries = getDimension().getCarving();
if (entries == null || entries.isEmpty()) {
return weightedProfiles;
}
Map<IrisDimensionCarvingEntry, IrisDimensionCarvingEntry[]> dimensionColumnPlans = blendScratch.dimensionColumnPlans;
dimensionColumnPlans.clear();
for (IrisDimensionCarvingEntry entry : entries) {
if (entry == null || !entry.isEnabled()) {
continue;
}
IrisBiome rootBiome = IrisDimensionCarvingResolver.resolveEntryBiome(getEngineMantle().getEngine(), entry, resolverState);
if (rootBiome == null) {
continue;
}
IrisDimensionCarvingEntry[] columnPlan = dimensionColumnPlans.computeIfAbsent(entry, key -> new IrisDimensionCarvingEntry[CHUNK_AREA]);
buildDimensionColumnPlan(columnPlan, chunkX, chunkZ, entry, resolverState);
Map<IrisCaveProfile, double[]> rootProfileColumnWeights = new IdentityHashMap<>();
List<IrisCaveProfile> rootProfileOrder = new ArrayList<>();
IrisRange worldYRange = entry.getWorldYRange();
for (int columnIndex = 0; columnIndex < CHUNK_AREA; columnIndex++) {
IrisDimensionCarvingEntry resolvedEntry = columnPlan[columnIndex];
IrisBiome resolvedBiome = IrisDimensionCarvingResolver.resolveEntryBiome(getEngineMantle().getEngine(), resolvedEntry, resolverState);
if (resolvedBiome == null) {
continue;
}
IrisCaveProfile profile = resolvedBiome.getCaveProfile();
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 (IrisCaveProfile profile : rootProfileOrder) {
weightedProfiles.add(new WeightedProfile(profile, rootProfileColumnWeights.get(profile), -1D, worldYRange, weightedProfiles.size()));
}
}
return weightedProfiles;
}
private void buildDimensionColumnPlan(IrisDimensionCarvingEntry[] columnPlan, int chunkX, int chunkZ, IrisDimensionCarvingEntry entry, IrisDimensionCarvingResolver.State resolverState) {
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] = IrisDimensionCarvingResolver.resolveFromRoot(getEngineMantle().getEngine(), entry, worldX, worldZ, resolverState);
}
}
}
private void fillProfileField(IrisCaveProfile[] profileField, int chunkX, int chunkZ, IrisComplex complex, IrisDimensionCarvingResolver.State resolverState, BlendScratch blendScratch) {
int startX = PowerOfTwoCoordinates.chunkToBlock(chunkX) - BLEND_RADIUS;
int startZ = PowerOfTwoCoordinates.chunkToBlock(chunkZ) - BLEND_RADIUS;
prefillProfileFieldSamples(startX, startZ, complex, blendScratch);
for (int fieldX = 0; fieldX < FIELD_SIZE; fieldX++) {
int worldX = startX + fieldX;
for (int fieldZ = 0; fieldZ < FIELD_SIZE; fieldZ++) {
int worldZ = startZ + fieldZ;
int fieldIndex = (fieldX * FIELD_SIZE) + fieldZ;
profileField[fieldIndex] = resolveColumnProfile(
worldX,
worldZ,
blendScratch.fieldSurfaceHeights[fieldIndex],
blendScratch.fieldRegions[fieldIndex],
blendScratch.fieldSurfaceBiomes[fieldIndex],
blendScratch.fieldCaveBiomes[fieldIndex],
resolverState
);
}
}
}
private int findProfileIndex(IrisCaveProfile[] profiles, int size, IrisCaveProfile profile) {
for (int index = 0; index < size; index++) {
if (profiles[index] == profile) {
return index;
}
}
return -1;
}
private IrisCaveProfile resolveColumnProfile(
int worldX,
int worldZ,
double surfaceHeight,
IrisRegion region,
IrisBiome surfaceBiome,
IrisBiome caveBiome,
IrisDimensionCarvingResolver.State resolverState
) {
IrisCaveProfile resolved = null;
IrisCaveProfile dimensionProfile = getDimension().getCaveProfile();
if (isProfileEnabled(dimensionProfile)) {
resolved = dimensionProfile;
}
if (region != null) {
IrisCaveProfile regionProfile = region.getCaveProfile();
if (isProfileEnabled(regionProfile)) {
resolved = regionProfile;
}
}
if (surfaceBiome != null) {
IrisCaveProfile surfaceProfile = surfaceBiome.getCaveProfile();
if (isProfileEnabled(surfaceProfile)) {
resolved = surfaceProfile;
}
}
int roundedSurfaceY = (int) Math.round(surfaceHeight);
int sampleY = Math.max(1, roundedSurfaceY - 56);
int worldY = sampleY + getEngineMantle().getEngine().getWorld().minHeight();
IrisDimensionCarvingEntry rootCarvingEntry = IrisDimensionCarvingResolver.resolveRootEntry(getEngineMantle().getEngine(), worldY, resolverState);
IrisBiome resolvedCarvingBiome = null;
if (rootCarvingEntry != null) {
IrisDimensionCarvingEntry resolvedCarvingEntry = IrisDimensionCarvingResolver.resolveFromRoot(getEngineMantle().getEngine(), rootCarvingEntry, worldX, worldZ, resolverState);
resolvedCarvingBiome = IrisDimensionCarvingResolver.resolveEntryBiome(getEngineMantle().getEngine(), resolvedCarvingEntry, resolverState);
if (resolvedCarvingBiome != null) {
caveBiome = resolvedCarvingBiome;
}
}
if (caveBiome != null) {
IrisBiome effectiveCaveBiome = caveBiome;
if (resolvedCarvingBiome == null && surfaceBiome != null) {
if (surfaceBiome != null) {
int truncatedSurfaceY = (int) surfaceHeight;
int depthBelowSurface = truncatedSurfaceY - sampleY;
if (depthBelowSurface <= 0) {
effectiveCaveBiome = surfaceBiome;
} else {
int minDepth = Math.max(0, caveBiome.getCaveMinDepthBelowSurface());
if (depthBelowSurface < minDepth) {
effectiveCaveBiome = surfaceBiome;
}
}
}
}
IrisCaveProfile caveProfile = effectiveCaveBiome.getCaveProfile();
if (isProfileEnabled(caveProfile)) {
resolved = caveProfile;
}
}
return resolved;
}
private void prefillProfileFieldSamples(int startX, int startZ, IrisComplex complex, BlendScratch blendScratch) {
fillFieldHeights(complex.getHeightStream(), startX, startZ, blendScratch.fieldSurfaceHeights);
fillFieldFluidPresence(complex.getFluidStream(), startX, startZ, blendScratch.fieldHasFluid);
fillFieldObjects(complex.getRegionStream(), startX, startZ, blendScratch.fieldRegions);
fillFieldObjects(complex.getTrueBiomeStream(), startX, startZ, blendScratch.fieldSurfaceBiomes);
fillFieldObjects(complex.getCaveBiomeStream(), startX, startZ, blendScratch.fieldCaveBiomes);
}
private <T> void fillFieldObjects(ProceduralStream<T> stream, int startX, int startZ, T[] target) {
for (int fieldX = 0; fieldX < FIELD_SIZE; fieldX++) {
int worldX = startX + fieldX;
for (int fieldZ = 0; fieldZ < FIELD_SIZE; fieldZ++) {
target[(fieldX * FIELD_SIZE) + fieldZ] = stream.get(worldX, startZ + fieldZ);
}
}
}
private void fillFieldHeights(ProceduralStream<Double> stream, int startX, int startZ, double[] target) {
for (int fieldX = 0; fieldX < FIELD_SIZE; fieldX++) {
int worldX = startX + fieldX;
for (int fieldZ = 0; fieldZ < FIELD_SIZE; fieldZ++) {
target[(fieldX * FIELD_SIZE) + fieldZ] = stream.getDouble(worldX, startZ + fieldZ);
}
}
}
private void fillFieldFluidPresence(ProceduralStream<PlatformBlockState> stream, int startX, int startZ, boolean[] target) {
for (int fieldX = 0; fieldX < FIELD_SIZE; fieldX++) {
int worldX = startX + fieldX;
for (int fieldZ = 0; fieldZ < FIELD_SIZE; fieldZ++) {
target[(fieldX * FIELD_SIZE) + fieldZ] = B.isFluid(stream.get(worldX, startZ + fieldZ));
}
}
}
private IrisCaveCarver3D getCarver(IrisCaveProfile profile) {
IrisCaveCarver3D carver = profileCarvers.get(profile);
if (carver != null) {
return carver;
}
IrisCaveCarver3D createdCarver = new IrisCaveCarver3D(getEngineMantle().getEngine(), profile);
synchronized (profileCarverLock) {
IrisCaveCarver3D published = profileCarvers.get(profile);
if (published != null) {
return published;
}
Map<IrisCaveProfile, IrisCaveCarver3D> updated = new IdentityHashMap<>(profileCarvers);
updated.put(profile, createdCarver);
profileCarvers = updated;
return createdCarver;
}
}
private boolean isProfileEnabled(IrisCaveProfile profile) {
return profile != null && profile.isEnabled();
}
protected int computeRadius() {
return 1;
}
private int[] prepareChunkSurfaceHeights(int chunkX, int chunkZ, ChunkContext context, int[] scratch) {
int[] surfaceHeights = scratch;
int baseX = PowerOfTwoCoordinates.chunkToBlock(chunkX);
int baseZ = PowerOfTwoCoordinates.chunkToBlock(chunkZ);
boolean useContextHeight = context != null
&& context.getHeight() != null
&& context.getX() == baseX
&& context.getZ() == baseZ;
double[] cachedChunkHeights = null;
if (!useContextHeight && context != null) {
ProceduralStream<Double> heightStream = context.getComplex().getHeightStream();
if (heightStream instanceof ChunkFillableDoubleStream2D cachedHeightStream) {
cachedChunkHeights = BLEND_SCRATCH.get().chunkSurfaceHeightSamples;
cachedHeightStream.fillChunkDoubles(baseX, baseZ, cachedChunkHeights);
}
}
for (int localX = 0; localX < CHUNK_SIZE; localX++) {
int worldX = baseX + localX;
for (int localZ = 0; localZ < CHUNK_SIZE; localZ++) {
int worldZ = baseZ + localZ;
int columnIndex = PowerOfTwoCoordinates.packLocal16(localX, localZ);
if (useContextHeight) {
surfaceHeights[columnIndex] = context.getRoundedHeight(localX, localZ);
continue;
}
if (cachedChunkHeights != null) {
surfaceHeights[columnIndex] = (int) Math.round(cachedChunkHeights[(localZ << 4) + localX]);
continue;
}
surfaceHeights[columnIndex] = getEngineMantle().getEngine().getHeight(worldX, worldZ);
}
}
return surfaceHeights;
}
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(MantleCarvingComponent::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(MantleCarvingComponent::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 IrisCaveProfile profile;
private final double[] columnWeights;
private final double averageWeight;
private final IrisRange worldYRange;
private final int sequence;
private WeightedProfile(IrisCaveProfile profile, double[] columnWeights, double averageWeight, IrisRange 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 IrisCaveProfile[] profileField = new IrisCaveProfile[FIELD_SIZE * FIELD_SIZE];
private final IrisCaveProfile[] kernelProfiles = new IrisCaveProfile[KERNEL_SIZE];
private final double[] kernelProfileWeights = new double[KERNEL_SIZE];
private final IdentityHashMap<IrisCaveProfile, double[]> columnProfileWeights = new IdentityHashMap<>();
private final IdentityHashMap<IrisDimensionCarvingEntry, IrisDimensionCarvingEntry[]> dimensionColumnPlans = new IdentityHashMap<>();
private final IdentityHashMap<IrisCaveProfile, Boolean> activeProfiles = new IdentityHashMap<>();
private final List<IrisCaveProfile> profileOrder = new ArrayList<>();
private final double[] fieldSurfaceHeights = new double[FIELD_SIZE * FIELD_SIZE];
private final boolean[] fieldHasFluid = new boolean[FIELD_SIZE * FIELD_SIZE];
private final IrisRegion[] fieldRegions = new IrisRegion[FIELD_SIZE * FIELD_SIZE];
private final IrisBiome[] fieldSurfaceBiomes = new IrisBiome[FIELD_SIZE * FIELD_SIZE];
private final IrisBiome[] fieldCaveBiomes = new IrisBiome[FIELD_SIZE * FIELD_SIZE];
private final int[] chunkSurfaceHeights = new int[CHUNK_AREA];
private final int[] surfaceFluidBoundaryStartY = new int[CHUNK_AREA];
private final double[] chunkSurfaceHeightSamples = new double[CHUNK_AREA];
}
}
@@ -0,0 +1,614 @@
/*
* 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.engine.object.placement.IrisObjectPlacement;
import art.arcane.iris.core.loader.IrisData;
import art.arcane.iris.engine.IrisComplex;
import art.arcane.iris.engine.data.cache.Cache;
import art.arcane.iris.engine.mantle.ComponentFlag;
import art.arcane.iris.engine.mantle.EngineMantle;
import art.arcane.iris.engine.mantle.IrisMantleComponent;
import art.arcane.iris.engine.mantle.MantleWriter;
import art.arcane.iris.engine.object.terrain.floating.FloatingIslandSample;
import art.arcane.iris.engine.object.placement.FloatingObjectFootprint;
import art.arcane.iris.engine.object.placement.IObjectPlacer;
import art.arcane.iris.engine.object.world.biome.IrisBiome;
import art.arcane.iris.engine.object.terrain.floating.IrisFloatingChildBiomes;
import art.arcane.iris.engine.object.prefab.IrisObject;
import art.arcane.iris.engine.object.prefab.IrisObjectRotation;
import art.arcane.iris.engine.object.prefab.IrisObjectTranslate;
import art.arcane.iris.engine.object.procedural.IrisProceduralBlocks;
import art.arcane.iris.engine.object.placement.ObjectPlaceMode;
import art.arcane.iris.spi.IrisLogging;
import art.arcane.iris.spi.PlatformBlockState;
import art.arcane.iris.util.common.data.B;
import art.arcane.iris.util.common.math.IrisBlockVector;
import art.arcane.iris.util.project.context.ChunkContext;
import art.arcane.volmlib.util.collection.KList;
import art.arcane.volmlib.util.documentation.ChunkCoordinates;
import art.arcane.volmlib.util.mantle.flag.ReservedFlag;
import art.arcane.volmlib.util.math.RNG;
import java.io.File;
import java.util.HashMap;
import java.util.HashSet;
import java.util.IdentityHashMap;
import java.util.Map;
import java.util.Set;
@ComponentFlag(ReservedFlag.FLOATING_OBJECT)
public class MantleFloatingObjectComponent extends IrisMantleComponent {
private static final int INVERTED_PICK_ATTEMPTS = 8;
private static final IrisObjectRotation ROTATION_NONE = IrisObjectRotation.of(0, 0, 0);
public MantleFloatingObjectComponent(EngineMantle engineMantle) {
super(engineMantle, ReservedFlag.FLOATING_OBJECT, 2);
}
@Override
public void generateLayer(MantleWriter writer, int x, int z, ChunkContext context) {
IrisComplex complex = context.getComplex();
IrisData data = getData();
int minX = x << 4;
int minZ = z << 4;
RNG chunkRng = new RNG(Cache.key(x, z) + seed() + 0x0FA710BEL);
FloatingIslandSampleResolver sampleResolver = new FloatingIslandSampleResolver(getEngineMantle(), context.getFloatingIslandBoundarySampler());
FloatingIslandSample.clearChunkMemo();
FloatingIslandSample[] samples = new FloatingIslandSample[256];
for (int xf = 0; xf < 16; xf++) {
for (int zf = 0; zf < 16; zf++) {
int wx = minX + xf;
int wz = minZ + zf;
FloatingIslandSample sample = sampleResolver.sample(wx, wz);
if (sample != null) {
samples[(zf << 4) | xf] = sample;
}
}
}
// The IdentityHashMaps 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 chunkRng makes placement output depend on iteration order.
IdentityHashMap<IrisFloatingChildBiomes, KList<Integer>> entryColumns = new IdentityHashMap<>();
IdentityHashMap<IrisFloatingChildBiomes, KList<Integer>> bottomEntryColumns = new IdentityHashMap<>();
KList<IrisFloatingChildBiomes> entryOrder = new KList<>();
KList<IrisFloatingChildBiomes> bottomEntryOrder = new KList<>();
for (int i = 0; i < 256; i++) {
FloatingIslandSample s = samples[i];
if (s == null || s.entry == null) {
continue;
}
entryColumns.computeIfAbsent(s.entry, e -> {
entryOrder.add(e);
return new KList<>();
}).add(i);
IrisFloatingChildBiomes bottomEntry = s.bottomEntry();
if (bottomEntry != null) {
bottomEntryColumns.computeIfAbsent(bottomEntry, e -> {
bottomEntryOrder.add(e);
return new KList<>();
}).add(i);
}
}
for (IrisFloatingChildBiomes entry : entryOrder) {
KList<Integer> columns = entryColumns.get(entry);
if (columns.isEmpty()) {
continue;
}
int firstKey = columns.get(0);
IrisBiome parent = sampleResolver.parent(minX + (firstKey & 15), minZ + (firstKey >> 4));
IrisBiome target = entry.getRealBiome(parent, data);
KList<IrisObjectPlacement> floating = entry.getFloatingObjects();
if (floating != null && !floating.isEmpty()) {
for (IrisObjectPlacement placement : floating) {
tryPlaceFloatingChunk(writer, complex, chunkRng, data, placement, columns, minX, minZ, entry);
}
}
KList<IrisObjectPlacement> surface = target != null ? entry.resolveTopObjects(target) : null;
KList<IrisObjectPlacement> extras = entry.getExtraObjects();
boolean hasSurface = surface != null && !surface.isEmpty();
boolean hasExtras = extras != null && !extras.isEmpty();
KList<Integer> interior = null;
if (hasSurface || hasExtras) {
interior = interiorColumns(sampleResolver, columns, minX, minZ, entry, IslandObjectPlacer.AnchorFace.TOP);
if (hasSurface) {
for (IrisObjectPlacement placement : surface) {
tryPlaceAnchoredChunk(writer, complex, chunkRng, data, placement, samples, sampleResolver, columns, interior, minX, minZ, entry);
}
}
if (hasExtras) {
for (IrisObjectPlacement placement : extras) {
tryPlaceAnchoredChunk(writer, complex, chunkRng, data, placement, samples, sampleResolver, columns, interior, minX, minZ, entry);
}
}
}
}
for (IrisFloatingChildBiomes entry : bottomEntryOrder) {
KList<Integer> columns = bottomEntryColumns.get(entry);
if (columns.isEmpty()) {
continue;
}
int firstKey = columns.get(0);
IrisBiome parent = sampleResolver.parent(minX + (firstKey & 15), minZ + (firstKey >> 4));
IrisBiome target = entry.getRealBiome(parent, data);
KList<IrisObjectPlacement> bottom = target != null ? entry.resolveBottomObjects(target) : null;
if (bottom != null && !bottom.isEmpty()) {
KList<Integer> interior = interiorColumns(sampleResolver, columns, minX, minZ, entry, IslandObjectPlacer.AnchorFace.BOTTOM);
for (IrisObjectPlacement placement : bottom) {
tryPlaceInvertedChunk(writer, complex, chunkRng, data, placement, samples, sampleResolver, columns, interior, minX, minZ, entry);
}
}
}
}
@ChunkCoordinates
private void tryPlaceFloatingChunk(MantleWriter writer, IrisComplex complex, RNG rng, IrisData data, IrisObjectPlacement placement, KList<Integer> columns, int minX, int minZ, IrisFloatingChildBiomes entry) {
if (placement == null || columns == null || columns.isEmpty()) {
return;
}
int density = placement.getDensity(rng, minX, minZ, data);
double perAttempt = placement.getChance();
for (int i = 0; i < density; i++) {
if (!rng.chance(perAttempt + rng.d(-0.005, 0.005))) {
continue;
}
IrisObject raw = placement.getObject(complex, rng);
if (raw == null) {
continue;
}
IrisObject obj0 = placement.getScale().get(rng, raw);
if (obj0 == null) {
continue;
}
if (entry != null && entry.hasObjectShrink()) {
obj0 = entry.getShrinkScale().get(rng, obj0);
if (obj0 == null) {
continue;
}
}
final IrisObject obj = obj0;
int key = columns.get(rng.i(columns.size()));
int xx = minX + (key & 15);
int zz = minZ + (key >> 4);
IrisObjectPlacement floatingPlacement = placement.toPlacement(obj.getLoadKey());
int id = rng.i(0, Integer.MAX_VALUE);
try {
obj.place(xx, -1, zz, writer, floatingPlacement, rng, (b, bd) -> {
String marker = placementMarker(obj, id);
if (marker != null && shouldWritePlacementMarker(writer, bd, b.getX(), b.getY(), b.getZ())) {
writer.setData(b.getX(), b.getY(), b.getZ(), marker);
}
}, null, data);
} catch (Throwable e) {
IrisLogging.reportError(e);
}
}
}
@ChunkCoordinates
private void tryPlaceAnchoredChunk(MantleWriter writer, IrisComplex complex, RNG rng, IrisData data, IrisObjectPlacement placement, FloatingIslandSample[] samples, IslandObjectPlacer.SampleProvider sampleProvider, KList<Integer> columns, KList<Integer> interior, int minX, int minZ, IrisFloatingChildBiomes entry) {
if (placement == null || columns.isEmpty()) {
return;
}
int density = placement.getDensity(rng, minX, minZ, data);
double perAttempt = placement.getChance();
for (int i = 0; i < density; i++) {
if (!rng.chance(perAttempt + rng.d(-0.005, 0.005))) {
continue;
}
IrisObject raw = placement.getObject(complex, rng);
if (raw == null) {
continue;
}
IrisObject obj0 = placement.getScale().get(rng, raw);
if (obj0 == null) {
continue;
}
if (entry != null && entry.hasObjectShrink()) {
obj0 = entry.getShrinkScale().get(rng, obj0);
if (obj0 == null) {
continue;
}
}
final IrisObject obj = obj0;
FloatingObjectFootprint fp = FloatingObjectFootprint.compute(obj);
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 = samples[(pickedZf << 4) | pickedXf];
if (pickedSample == null) {
continue;
}
int pickTopY = pickedSample.topY();
int pickedX = minX + pickedXf;
int pickedZ = minZ + pickedZf;
if (!isFootprintFlat(fp, pickedX, pickedZ, pickTopY, sampleProvider, entry, 2)) {
if (!isFootprintFlat(fp, pickedX, pickedZ, pickTopY, sampleProvider, entry, 4)) {
continue;
}
}
int wx = minX + pickedXf - fp.getTallestKx();
int wz = minZ + pickedZf - fp.getTallestKz();
IrisObjectPlacement anchored = placement.toPlacement(obj.getLoadKey());
anchored.setMode(translateStiltModeForFloating(anchored.getMode()));
anchored.setTranslate(new IrisObjectTranslate());
anchored.setRotation(ROTATION_NONE);
anchored.setForcePlace(true);
anchored.setBottom(false);
int yv = pickTopY + 1 - fp.getLowestSolidKeyY();
IslandObjectPlacer islandPlacer = IslandObjectPlacer.top(writer, sampleProvider, entry, pickTopY);
FloatingObjectPlacementTransaction transaction = new FloatingObjectPlacementTransaction(islandPlacer);
int id = rng.i(0, Integer.MAX_VALUE);
try {
int resultY = obj.place(wx, yv, wz, transaction, anchored, rng, (b, bd) -> {
String marker = placementMarker(obj, id);
if (marker != null && shouldWritePlacementMarker(transaction, bd, b.getX(), b.getY(), b.getZ())) {
transaction.setData(b.getX(), b.getY(), b.getZ(), marker);
}
}, null, data);
if (resultY < 0) {
transaction.discard();
} else {
transaction.commit();
}
} catch (Throwable e) {
transaction.discard();
IrisLogging.reportError(e);
}
}
}
@ChunkCoordinates
private void tryPlaceInvertedChunk(MantleWriter writer, IrisComplex complex, RNG rng, IrisData data, IrisObjectPlacement placement, FloatingIslandSample[] samples, IslandObjectPlacer.SampleProvider sampleProvider, KList<Integer> columns, KList<Integer> interior, int minX, int minZ, IrisFloatingChildBiomes entry) {
if (placement == null || columns.isEmpty()) {
return;
}
int density = placement.getDensity(rng, minX, minZ, data);
double perAttempt = placement.getChance();
for (int i = 0; i < density; i++) {
if (!rng.chance(perAttempt + rng.d(-0.005, 0.005))) {
continue;
}
IrisObject raw = placement.getObject(complex, rng);
if (raw == null) {
continue;
}
IrisObject obj0 = placement.getScale().get(rng, raw);
if (obj0 == null) {
continue;
}
if (entry != null && entry.hasObjectShrink()) {
obj0 = entry.getShrinkScale().get(rng, obj0);
if (obj0 == null) {
continue;
}
}
final IrisObject obj = obj0;
FloatingObjectFootprint fp = FloatingObjectFootprint.compute(obj);
int invertedYRotation = rng.i(4) * 90;
IrisObjectRotation invertedRotation = IrisObjectRotation.xFlip180WithY(invertedYRotation);
KList<Integer> pool = interior.isEmpty() ? columns : interior;
int pickedXf = -1;
int pickedZf = -1;
int pickBottomY = -1;
boolean foundBottomAnchor = false;
for (int attempt = 0; attempt < INVERTED_PICK_ATTEMPTS; attempt++) {
int pickedKey = pool.get(rng.i(pool.size()));
int candidateXf = pickedKey & 15;
int candidateZf = pickedKey >> 4;
FloatingIslandSample candidateSample = samples[(candidateZf << 4) | candidateXf];
if (candidateSample == null) {
continue;
}
int candidateBottomY = candidateSample.bottomY();
if (candidateBottomY < 0) {
continue;
}
int candidateX = minX + candidateXf;
int candidateZ = minZ + candidateZf;
if (!isFootprintFlatBottom(fp, invertedRotation, candidateX, candidateZ, candidateBottomY, sampleProvider, entry, 2)
&& !isFootprintFlatBottom(fp, invertedRotation, candidateX, candidateZ, candidateBottomY, sampleProvider, entry, 4)) {
continue;
}
pickedXf = candidateXf;
pickedZf = candidateZf;
pickBottomY = candidateBottomY;
foundBottomAnchor = true;
break;
}
if (!foundBottomAnchor) {
continue;
}
int wx = invertedBaseX(minX, pickedXf, fp, invertedRotation);
int wz = invertedBaseZ(minZ, pickedZf, fp, invertedRotation);
IrisObjectPlacement inverted = placement.toPlacement(obj.getLoadKey());
inverted.setMode(translateStiltModeForFloating(inverted.getMode()));
inverted.setTranslate(new IrisObjectTranslate());
inverted.setRotation(invertedRotation);
inverted.setForcePlace(true);
inverted.setBottom(false);
int yv = invertedBaseY(pickBottomY, fp, invertedRotation);
IslandObjectPlacer islandPlacer = IslandObjectPlacer.bottom(writer, sampleProvider, entry, pickBottomY);
FloatingObjectPlacementTransaction transaction = new FloatingObjectPlacementTransaction(islandPlacer);
int id = rng.i(0, Integer.MAX_VALUE);
try {
int resultY = obj.place(wx, yv, wz, transaction, inverted, rng, (b, bd) -> {
String marker = placementMarker(obj, id);
if (marker != null && shouldWritePlacementMarker(transaction, bd, b.getX(), b.getY(), b.getZ())) {
transaction.setData(b.getX(), b.getY(), b.getZ(), marker);
}
}, null, data);
if (resultY < 0) {
transaction.discard();
} else {
transaction.commit();
}
} catch (Throwable e) {
transaction.discard();
IrisLogging.reportError(e);
}
}
}
static boolean isFootprintFlatBottom(FloatingObjectFootprint fp, IrisObjectRotation rotation,
int pickedX, int pickedZ, int pickBottomY,
IslandObjectPlacer.SampleProvider samples,
IrisFloatingChildBiomes entry, int tolerance) {
IrisBlockVector anchor = invertedFootprintAnchor(fp, rotation);
long[] cells = fp.footprintXZ();
if (cells.length == 0) {
return false;
}
for (int i = 0, n = cells.length; i < n; i++) {
long encoded = cells[i];
int kx = (int) (encoded >> 32);
int kz = (int) (encoded & 0xFFFFFFFFL);
IrisBlockVector cell = rotation.rotate(new IrisBlockVector(kx, 0, kz), 0, 0, 0);
int columnX = pickedX + cell.getBlockX() - anchor.getBlockX();
int columnZ = pickedZ + cell.getBlockZ() - anchor.getBlockZ();
FloatingIslandSample sample = samples.sample(columnX, columnZ);
if (!IslandObjectPlacer.matchesAnchor(sample, entry, IslandObjectPlacer.AnchorFace.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, FloatingObjectFootprint fp) {
return invertedBaseX(minX, pickedXf, fp, IrisObjectRotation.xFlip180());
}
static int invertedBaseY(int pickBottomY, FloatingObjectFootprint fp) {
return invertedBaseY(pickBottomY, fp, IrisObjectRotation.xFlip180());
}
static int invertedBaseZ(int minZ, int pickedZf, FloatingObjectFootprint fp) {
return invertedBaseZ(minZ, pickedZf, fp, IrisObjectRotation.xFlip180());
}
static int invertedBaseX(int minX, int pickedXf, FloatingObjectFootprint fp, IrisObjectRotation rotation) {
return minX + pickedXf - invertedFootprintAnchor(fp, rotation).getBlockX();
}
static int invertedBaseY(int pickBottomY, FloatingObjectFootprint fp, IrisObjectRotation rotation) {
return pickBottomY - 1 - invertedSolidAnchor(fp, rotation).getBlockY();
}
static int invertedBaseZ(int minZ, int pickedZf, FloatingObjectFootprint fp, IrisObjectRotation rotation) {
return minZ + pickedZf - invertedFootprintAnchor(fp, rotation).getBlockZ();
}
private static IrisBlockVector invertedFootprintAnchor(FloatingObjectFootprint fp, IrisObjectRotation rotation) {
return rotation.rotate(new IrisBlockVector(fp.getTallestKx(), 0, fp.getTallestKz()), 0, 0, 0);
}
private static IrisBlockVector invertedSolidAnchor(FloatingObjectFootprint fp, IrisObjectRotation rotation) {
return rotation.rotate(new IrisBlockVector(fp.getTallestKx(), fp.getLowestSolidKeyY(), fp.getTallestKz()), 0, 0, 0);
}
private static boolean shouldWritePlacementMarker(IObjectPlacer placer, PlatformBlockState state, int x, int y, int z) {
if (state == null) {
return false;
}
PlatformBlockState existingState = placer.get(x, y, z);
boolean wouldReplace = B.isSolid(existingState) && B.isVineBlock(state);
String material = IrisProceduralBlocks.materialKey(state);
boolean placesBlock = !material.equals("minecraft:air") && !material.equals("minecraft:cave_air") && !wouldReplace;
return state.isCustom() || placesBlock;
}
static boolean isFootprintFlat(FloatingObjectFootprint fp, int pickedX, int pickedZ, int pickTopY,
IslandObjectPlacer.SampleProvider samples,
IrisFloatingChildBiomes entry, int tolerance) {
int tallestKx = fp.getTallestKx();
int tallestKz = fp.getTallestKz();
long[] cells = fp.footprintXZ();
if (cells.length == 0) {
return false;
}
for (int i = 0, n = cells.length; i < n; i++) {
long encoded = cells[i];
int kx = (int) (encoded >> 32);
int kz = (int) (encoded & 0xFFFFFFFFL);
int columnX = pickedX + (kx - tallestKx);
int columnZ = pickedZ + (kz - tallestKz);
FloatingIslandSample sample = samples.sample(columnX, columnZ);
if (!IslandObjectPlacer.matchesAnchor(sample, entry, IslandObjectPlacer.AnchorFace.TOP)
|| Math.abs(sample.topY() - pickTopY) > tolerance) {
return false;
}
}
return true;
}
private static KList<Integer> interiorColumns(IslandObjectPlacer.SampleProvider samples,
KList<Integer> columns, int minX, int minZ,
IrisFloatingChildBiomes entry,
IslandObjectPlacer.AnchorFace face) {
KList<Integer> interior = new KList<>();
for (int key : columns) {
int x = minX + (key & 15);
int z = minZ + (key >> 4);
if (!IslandObjectPlacer.matchesAnchor(samples.sample(x + 1, z), entry, face)) {
continue;
}
if (!IslandObjectPlacer.matchesAnchor(samples.sample(x - 1, z), entry, face)) {
continue;
}
if (!IslandObjectPlacer.matchesAnchor(samples.sample(x, z + 1), entry, face)) {
continue;
}
if (!IslandObjectPlacer.matchesAnchor(samples.sample(x, z - 1), entry, face)) {
continue;
}
interior.add(key);
}
return interior;
}
private static String placementMarker(IrisObject object, int id) {
if (object == null) {
return null;
}
String key = object.getLoadKey();
if (key == null || key.isEmpty() || key.equals("null")) {
return null;
}
return key + "@" + id;
}
private static ObjectPlaceMode translateStiltModeForFloating(ObjectPlaceMode m) {
return switch (m) {
case STILT -> ObjectPlaceMode.MAX_HEIGHT;
case FAST_STILT -> ObjectPlaceMode.FAST_MAX_HEIGHT;
case MIN_STILT -> ObjectPlaceMode.MIN_HEIGHT;
case FAST_MIN_STILT -> ObjectPlaceMode.FAST_MIN_HEIGHT;
case CENTER_STILT -> ObjectPlaceMode.CENTER_HEIGHT;
case ERODE_STILT -> ObjectPlaceMode.MAX_HEIGHT;
case STRUCTURE_PIECE -> ObjectPlaceMode.CENTER_HEIGHT;
default -> m;
};
}
@Override
protected int computeRadius() {
int maxObjectExtent = 16;
Map<String, IrisBlockVector> sizeCache = new HashMap<>();
Set<String> warnedLargeObjects = new HashSet<>();
try {
IrisData data = getData();
for (IrisBiome biome : getDimension().getReachableBiomes(this::getData)) {
KList<IrisFloatingChildBiomes> entries = biome.getFloatingChildBiomes();
if (entries == null || entries.isEmpty()) {
continue;
}
for (IrisFloatingChildBiomes entry : entries) {
maxObjectExtent = Math.max(maxObjectExtent, computePlacementRadius(entry.getFloatingObjects(), data, sizeCache, warnedLargeObjects));
maxObjectExtent = Math.max(maxObjectExtent, computePlacementRadius(entry.getExtraObjects(), data, sizeCache, warnedLargeObjects));
maxObjectExtent = Math.max(maxObjectExtent, computePlacementRadius(entry.getTopObjectOverrides(), data, sizeCache, warnedLargeObjects));
maxObjectExtent = Math.max(maxObjectExtent, computePlacementRadius(entry.getBottomObjectOverrides(), data, sizeCache, warnedLargeObjects));
try {
IrisBiome target = entry.getRealBiome(biome, data);
if (target != null) {
maxObjectExtent = Math.max(maxObjectExtent, computePlacementRadius(entry.resolveTopObjects(target), data, sizeCache, warnedLargeObjects));
maxObjectExtent = Math.max(maxObjectExtent, computePlacementRadius(entry.resolveBottomObjects(target), data, sizeCache, warnedLargeObjects));
}
} catch (Throwable e) {
IrisLogging.reportError(e);
}
}
}
} catch (Throwable e) {
IrisLogging.reportError(e);
}
return maxObjectExtent;
}
private int computePlacementRadius(KList<IrisObjectPlacement> placements, IrisData data,
Map<String, IrisBlockVector> sizeCache,
Set<String> warnedLargeObjects) {
int radius = 0;
if (placements == null) {
return radius;
}
for (IrisObjectPlacement placement : placements) {
if (placement == null || placement.getPlace() == null) {
continue;
}
for (String objectKey : placement.getPlace()) {
try {
IrisBlockVector size = sizeCache.get(objectKey);
if (size == null) {
File file = data.getObjectLoader().findFile(objectKey);
if (file == null) {
continue;
}
size = IrisObject.sampleSize(file);
sizeCache.put(objectKey, size);
}
int reach = MantleObjectComponent.calculatePlacementReach(size, placement);
if (reach > 128 && warnedLargeObjects.add(objectKey)) {
IrisLogging.warn("Floating object " + objectKey + " has a large placement reach (" + reach + " blocks) and may increase memory usage!");
}
radius = Math.max(radius, reach);
} catch (Throwable e) {
IrisLogging.reportError(e);
}
}
}
return radius;
}
}
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,147 @@
/*
* 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.engine.object.structure.IrisStructureCarveShape;
import art.arcane.iris.util.project.noise.CNG;
/**
* Carve envelope math shared by the Iris-assembled structure path and the native (vanilla template)
* structure path so both shrinkwrap a structure footprint the same way. The lobe channel and the
* eroded floor are only sampled by the native path; the Iris-assembled path still carves a uniform
* side reach and a uniform floor cut.
*/
public final class StructureCarveEnvelope {
private static final double CEILING_LOBE_RATIO = 0.5D;
private static final double CEILING_ROLL_FREQUENCY_RATIO = 3D / 7D;
private static final double FLOOR_ROLL_AMPLITUDE = 0.35D;
private static final double FLOOR_ROLL_FREQUENCY_RATIO = 5D / 11D;
// Maps a lobe frequency onto the smooth 2D channel so the auto-derived 0.015 lands near a
// 40 block wavelength: wide enough that walls bulge and recede instead of tracking the footprint.
private static final double LOBE_FREQUENCY_SCALE = 256D;
private StructureCarveEnvelope() {
}
/**
* Per-column horizontal carve reach. The lobe channel only ever removes padding, so the boundary
* stays inside the footprint bounds the carve was sized against and never falls below
* {@code horizontalPadding * (1 - lobeStrength)}.
*/
public static double lobedSideReach(CNG lobe, double lobeFrequency, double lobeStrength,
int x, int z, int horizontalPadding) {
if (horizontalPadding <= 0) {
return 0D;
}
return horizontalPadding * lobeFactor(lobe, lobeFrequency, lobeStrength, x, z);
}
/**
* Ceiling counterpart of {@link #lobedSideReach}, deliberately half as strong so the roof swells
* with the same lobes without collapsing onto the pieces.
*/
public static double lobedUpReach(CNG lobe, double lobeFrequency, double lobeStrength,
int x, int z, double upReach) {
if (upReach <= 0D) {
return upReach;
}
return Math.max(1D, upReach
* lobeFactor(lobe, lobeFrequency, lobeStrength * CEILING_LOBE_RATIO, x, z));
}
private static double lobeFactor(CNG lobe, double lobeFrequency, double lobeStrength,
int x, int z) {
double clampedStrength = Math.max(0D, Math.min(1D, lobeStrength));
if (lobe == null || clampedStrength <= 0D) {
return 1D;
}
double scaledFrequency = lobeFrequency * LOBE_FREQUENCY_SCALE;
double sample = Math.max(0D, Math.min(1D, lobe.fitDouble(
0D, 1D, x * scaledFrequency, z * scaledFrequency)));
return 1D - clampedStrength * (1D - sample);
}
public static double erodedUpReach(CNG roll, double frequency, double strength, int x, int z, int head) {
if (head <= 0) {
return 0D;
}
double clampedStrength = Math.max(0D, Math.min(1D, strength));
if (clampedStrength <= 0D) {
return Math.max(1D, head);
}
double rollFrequency = frequency * CEILING_ROLL_FREQUENCY_RATIO;
double sample = roll.fitDouble(0D, 1D, x * rollFrequency, z * rollFrequency) * 0.7D
+ roll.fitDouble(0D, 1D, x * rollFrequency * 3D, z * rollFrequency * 3D) * 0.3D;
double contrast = Math.max(0D, Math.min(1D, (sample - 0.5D) * 2.6D + 0.5D));
double roundedReach = Math.max(1D, head);
double erodedReach = Math.max(1D, head * (0.4D + 1.4D * contrast));
return roundedReach + clampedStrength * (erodedReach - roundedReach);
}
/**
* Floor counterpart of {@link #erodedUpReach}. The amplitude is deliberately small and the result
* never exceeds the configured floor padding, so a padding of zero leaves every column standing on
* its own supporting block instead of undermining the structure.
*/
public static double erodedDownReach(CNG roll, double frequency, double strength, int x, int z, int floorCut) {
if (floorCut <= 0) {
return 0D;
}
double clampedStrength = Math.max(0D, Math.min(1D, strength));
if (clampedStrength <= 0D) {
return floorCut;
}
double rollFrequency = frequency * FLOOR_ROLL_FREQUENCY_RATIO;
double sample = roll.fitDouble(0D, 1D, x * rollFrequency, z * rollFrequency);
return floorCut * (1D - clampedStrength * FLOOR_ROLL_AMPLITUDE * (1D - sample));
}
public static double normalizedVerticalDistance(int y, int sourceMinY, int sourceMaxY,
double upReach, double downReach) {
if (y > sourceMaxY) {
return (y - sourceMaxY) / upReach;
}
if (y < sourceMinY) {
return (sourceMinY - y) / downReach;
}
return 0D;
}
public static double overboreBoundaryLimit(double noise, double strength) {
double clampedNoise = Math.max(0.0, Math.min(1.0, noise));
double clampedStrength = Math.max(0.0, Math.min(1.0, strength));
return 1D - clampedStrength * (1D - clampedNoise);
}
public static boolean shouldCarveOverboreCell(IrisStructureCarveShape shape, double distanceSquared,
double noise, double strength) {
if (distanceSquared <= 0.0) {
return true;
}
IrisStructureCarveShape resolvedShape = shape == null ? IrisStructureCarveShape.ERODED : shape;
return switch (resolvedShape) {
case BOX -> true;
case ROUNDED -> distanceSquared <= 1D;
case ERODED -> {
double limit = overboreBoundaryLimit(noise, strength);
yield distanceSquared <= 1D && distanceSquared <= limit * limit;
}
};
}
}
@@ -0,0 +1,456 @@
package art.arcane.iris.engine.mantle.components;
import art.arcane.iris.engine.framework.PlacedStructurePiece;
import art.arcane.iris.engine.object.prefab.IrisObject;
import art.arcane.iris.engine.object.prefab.IrisObjectRotation;
import art.arcane.iris.util.common.data.B;
import art.arcane.iris.util.common.math.IrisBlockVector;
import art.arcane.volmlib.util.collection.KList;
import it.unimi.dsi.fastutil.longs.Long2LongMap;
import it.unimi.dsi.fastutil.longs.Long2LongOpenHashMap;
import java.util.Arrays;
public final class StructureCarvingFootprint {
static final int DEFAULT_MAX_CELLS = 1_048_576;
private final int minX;
private final int maxX;
private final int minZ;
private final int maxZ;
private final int width;
private final int depth;
private final long[] distanceSquared;
private final int[] nearestSourceIds;
private final int[] sourceMinY;
private final int[] sourceMaxY;
private StructureCarvingFootprint(FootprintData data) {
minX = data.minX();
maxX = data.maxX();
minZ = data.minZ();
maxZ = data.maxZ();
width = data.width();
depth = data.depth();
distanceSquared = data.distanceSquared();
nearestSourceIds = data.nearestSourceIds();
sourceMinY = data.sourceMinY();
sourceMaxY = data.sourceMaxY();
}
static StructureCarvingFootprint from(KList<PlacedStructurePiece> pieces, int padding) {
return from(pieces, padding, DEFAULT_MAX_CELLS);
}
static StructureCarvingFootprint from(KList<PlacedStructurePiece> pieces, int padding, int maxCells) {
return fromColumns(sink -> emitPieceColumns(pieces, sink), padding, maxCells);
}
/**
* Builds a footprint from any per-column occupancy source. The source reports one contribution per
* occupied column; overlapping contributions merge into a single column whose vertical extents span
* every contribution.
*/
public static StructureCarvingFootprint fromColumns(ColumnSource source, int padding, int maxCells) {
if (padding < 0) {
throw new IllegalArgumentException("padding must be non-negative");
}
if (maxCells < 1) {
throw new IllegalArgumentException("maxCells must be positive");
}
if (source == null) {
return null;
}
SourceCollection sources = collectSources(source);
if (sources == null || sources.columns().isEmpty()) {
return null;
}
Bounds bounds = paddedBounds(sources.bounds(), padding, maxCells);
if (bounds == null) {
return null;
}
int[] nearestSourceIds = new int[bounds.cellCount()];
Arrays.fill(nearestSourceIds, -1);
int sourceCount = sources.columns().size();
int[] sourceX = new int[sourceCount];
int[] sourceZ = new int[sourceCount];
int[] sourceMinY = new int[sourceCount];
int[] sourceMaxY = new int[sourceCount];
int sourceId = 0;
for (Long2LongMap.Entry entry : sources.columns().long2LongEntrySet()) {
int localX = unpackX(entry.getLongKey()) - bounds.minX();
int localZ = unpackZ(entry.getLongKey()) - bounds.minZ();
long heights = entry.getLongValue();
sourceX[sourceId] = localX;
sourceZ[sourceId] = localZ;
sourceMinY[sourceId] = unpackMinY(heights);
sourceMaxY[sourceId] = unpackMaxY(heights);
nearestSourceIds[localZ * bounds.width() + localX] = sourceId;
sourceId++;
}
transformRows(nearestSourceIds, sourceX, sourceZ, bounds.width(), bounds.depth());
long[] distanceSquared = transformColumns(
nearestSourceIds, sourceX, sourceZ, bounds.width(), bounds.depth());
FootprintData data = new FootprintData(
bounds.minX(), bounds.maxX(), bounds.minZ(), bounds.maxZ(),
bounds.width(), bounds.depth(), distanceSquared, nearestSourceIds,
sourceMinY, sourceMaxY);
return new StructureCarvingFootprint(data);
}
public int minX() {
return minX;
}
public int maxX() {
return maxX;
}
public int minZ() {
return minZ;
}
public int maxZ() {
return maxZ;
}
public int width() {
return width;
}
public int depth() {
return depth;
}
public boolean contains(int worldX, int worldZ) {
return worldX >= minX && worldX <= maxX && worldZ >= minZ && worldZ <= maxZ;
}
public int indexAt(int worldX, int worldZ) {
if (!contains(worldX, worldZ)) {
return -1;
}
return (worldZ - minZ) * width + worldX - minX;
}
public long distanceSquaredAt(int worldX, int worldZ) {
return distanceSquaredAt(requireIndex(worldX, worldZ));
}
public long distanceSquaredAt(int index) {
return distanceSquared[index];
}
public int sourceMinYAt(int worldX, int worldZ) {
return sourceMinYAt(requireIndex(worldX, worldZ));
}
public int sourceMinYAt(int index) {
return sourceMinY[nearestSourceIds[index]];
}
public int sourceMaxYAt(int worldX, int worldZ) {
return sourceMaxYAt(requireIndex(worldX, worldZ));
}
public int sourceMaxYAt(int index) {
return sourceMaxY[nearestSourceIds[index]];
}
Column sample(int worldX, int worldZ) {
int index = indexAt(worldX, worldZ);
if (index < 0) {
return null;
}
return new Column(distanceSquaredAt(index), sourceMinYAt(index), sourceMaxYAt(index));
}
private static SourceCollection collectSources(ColumnSource source) {
Long2LongOpenHashMap columns = new Long2LongOpenHashMap();
MutableBounds bounds = new MutableBounds();
boolean usable = source.emit((worldX, worldZ, minY, maxY) -> {
mergeColumn(columns, worldX, worldZ, minY, maxY);
bounds.include(worldX, worldZ);
});
if (!usable) {
return null;
}
return columns.isEmpty() ? null : new SourceCollection(columns, bounds.freeze());
}
private static boolean emitPieceColumns(KList<PlacedStructurePiece> pieces, ColumnSink sink) {
if (pieces == null) {
return true;
}
for (PlacedStructurePiece piece : pieces) {
if (piece == null) {
continue;
}
IrisObject object = piece.getObject();
IrisObjectRotation rotation = piece.getRotation();
if (object == null || rotation == null || object.getBlocks() == null) {
continue;
}
for (IrisBlockVector local : object.getBlocks().keys()) {
if (local == null || B.isAir(object.getBlocks().get(local))) {
continue;
}
IrisBlockVector rotated = rotation.rotate(local.clone());
long worldX = (long) piece.getX() + rotated.getBlockX();
long worldY = (long) piece.getY() + rotated.getBlockY();
long worldZ = (long) piece.getZ() + rotated.getBlockZ();
if (!fitsInteger(worldX) || !fitsInteger(worldY) || !fitsInteger(worldZ)) {
return false;
}
sink.column((int) worldX, (int) worldZ, (int) worldY, (int) worldY);
}
}
return true;
}
private static Bounds paddedBounds(MutableBoundsSnapshot sourceBounds, int padding, int maxCells) {
long paddedMinX = (long) sourceBounds.minX() - padding;
long paddedMaxX = (long) sourceBounds.maxX() + padding;
long paddedMinZ = (long) sourceBounds.minZ() - padding;
long paddedMaxZ = (long) sourceBounds.maxZ() + padding;
if (!fitsInteger(paddedMinX) || !fitsInteger(paddedMaxX)
|| !fitsInteger(paddedMinZ) || !fitsInteger(paddedMaxZ)) {
return null;
}
long width = paddedMaxX - paddedMinX + 1L;
long depth = paddedMaxZ - paddedMinZ + 1L;
if (width < 1L || depth < 1L || width > Integer.MAX_VALUE || depth > Integer.MAX_VALUE
|| width > maxCells / depth) {
return null;
}
int cellCount = (int) (width * depth);
return new Bounds(
(int) paddedMinX, (int) paddedMaxX, (int) paddedMinZ, (int) paddedMaxZ,
(int) width, (int) depth, cellCount);
}
private static void mergeColumn(Long2LongOpenHashMap columns, int x, int z, int minY, int maxY) {
long key = pack(x, z);
if (!columns.containsKey(key)) {
columns.put(key, packHeights(minY, maxY));
return;
}
long existing = columns.get(key);
columns.put(key, packHeights(
Math.min(minY, unpackMinY(existing)), Math.max(maxY, unpackMaxY(existing))));
}
private static void transformRows(int[] nearestSourceIds, int[] sourceX, int[] sourceZ,
int width, int depth) {
for (int z = 0; z < depth; z++) {
int rowStart = z * width;
int previousSource = -1;
for (int x = 0; x < width; x++) {
int index = rowStart + x;
int sourceId = nearestSourceIds[index];
if (isExplicitSource(sourceId, x, z, sourceX, sourceZ)) {
previousSource = sourceId;
} else {
nearestSourceIds[index] = previousSource;
}
}
int nextSource = -1;
for (int x = width - 1; x >= 0; x--) {
int index = rowStart + x;
int currentSource = nearestSourceIds[index];
if (isExplicitSource(currentSource, x, z, sourceX, sourceZ)) {
nextSource = currentSource;
}
if (isBetterHorizontalSource(nextSource, currentSource, x, sourceX)) {
nearestSourceIds[index] = nextSource;
}
}
}
}
private static long[] transformColumns(int[] nearestSourceIds, int[] sourceX, int[] sourceZ,
int width, int depth) {
long[] distanceSquared = new long[nearestSourceIds.length];
int[] siteRows = new int[depth];
int[] siteSourceIds = new int[depth];
int[] starts = new int[depth];
long[] siteCosts = new long[depth];
for (int x = 0; x < width; x++) {
int siteCount = buildEnvelope(
nearestSourceIds, sourceX, width, depth, x,
siteRows, siteSourceIds, starts, siteCosts);
int siteIndex = 0;
for (int z = 0; z < depth; z++) {
while (siteIndex + 1 < siteCount && starts[siteIndex + 1] <= z) {
siteIndex++;
}
int sourceId = siteSourceIds[siteIndex];
int index = z * width + x;
long deltaX = (long) x - sourceX[sourceId];
long deltaZ = (long) z - sourceZ[sourceId];
nearestSourceIds[index] = sourceId;
distanceSquared[index] = deltaX * deltaX + deltaZ * deltaZ;
}
}
return distanceSquared;
}
private static int buildEnvelope(int[] nearestSourceIds, int[] sourceX, int width, int depth,
int x, int[] siteRows, int[] siteSourceIds,
int[] starts, long[] siteCosts) {
int siteCount = 0;
for (int z = 0; z < depth; z++) {
int sourceId = nearestSourceIds[z * width + x];
if (sourceId < 0) {
continue;
}
long deltaX = (long) x - sourceX[sourceId];
long cost = deltaX * deltaX;
int start = Integer.MIN_VALUE;
while (siteCount > 0) {
start = firstStrictlyBetterAt(
siteRows[siteCount - 1], siteCosts[siteCount - 1], z, cost);
if (start > starts[siteCount - 1]) {
break;
}
siteCount--;
}
if (siteCount == 0) {
start = Integer.MIN_VALUE;
}
siteRows[siteCount] = z;
siteSourceIds[siteCount] = sourceId;
siteCosts[siteCount] = cost;
starts[siteCount] = start;
siteCount++;
}
return siteCount;
}
private static int firstStrictlyBetterAt(int existingRow, long existingCost,
int candidateRow, long candidateCost) {
long numerator = candidateCost + (long) candidateRow * candidateRow
- existingCost - (long) existingRow * existingRow;
long denominator = 2L * (candidateRow - existingRow);
long start = Math.floorDiv(numerator, denominator) + 1L;
if (start < Integer.MIN_VALUE) {
return Integer.MIN_VALUE;
}
if (start > Integer.MAX_VALUE) {
return Integer.MAX_VALUE;
}
return (int) start;
}
private static boolean isExplicitSource(int sourceId, int x, int z,
int[] sourceX, int[] sourceZ) {
return sourceId >= 0 && sourceX[sourceId] == x && sourceZ[sourceId] == z;
}
private static boolean isBetterHorizontalSource(int candidateId, int currentId,
int x, int[] sourceX) {
if (candidateId < 0) {
return false;
}
if (currentId < 0) {
return true;
}
long candidateDelta = (long) x - sourceX[candidateId];
long currentDelta = (long) x - sourceX[currentId];
long candidateDistance = candidateDelta * candidateDelta;
long currentDistance = currentDelta * currentDelta;
return candidateDistance < currentDistance
|| candidateDistance == currentDistance && sourceX[candidateId] < sourceX[currentId];
}
private int requireIndex(int worldX, int worldZ) {
int index = indexAt(worldX, worldZ);
if (index < 0) {
throw new IndexOutOfBoundsException(
"coordinate outside carving footprint: " + worldX + "," + worldZ);
}
return index;
}
private static boolean fitsInteger(long value) {
return value >= Integer.MIN_VALUE && value <= Integer.MAX_VALUE;
}
private static long pack(int x, int z) {
return (long) x << 32 | z & 0xffffffffL;
}
private static int unpackX(long packed) {
return (int) (packed >> 32);
}
private static int unpackZ(long packed) {
return (int) packed;
}
private static long packHeights(int minY, int maxY) {
return (long) minY << 32 | maxY & 0xffffffffL;
}
private static int unpackMinY(long packed) {
return (int) (packed >> 32);
}
private static int unpackMaxY(long packed) {
return (int) packed;
}
@FunctionalInterface
public interface ColumnSink {
void column(int worldX, int worldZ, int minY, int maxY);
}
@FunctionalInterface
public interface ColumnSource {
/**
* Reports every occupied column to the sink. Returning false abandons the footprint, which is how
* a source rejects occupancy it cannot address (for example coordinates outside the integer range).
*/
boolean emit(ColumnSink sink);
}
record Column(long distanceSquared, int sourceMinY, int sourceMaxY) {
}
private record Bounds(int minX, int maxX, int minZ, int maxZ,
int width, int depth, int cellCount) {
}
private record FootprintData(int minX, int maxX, int minZ, int maxZ,
int width, int depth, long[] distanceSquared,
int[] nearestSourceIds, int[] sourceMinY, int[] sourceMaxY) {
}
private record SourceCollection(Long2LongOpenHashMap columns, MutableBoundsSnapshot bounds) {
}
private record MutableBoundsSnapshot(int minX, int maxX, int minZ, int maxZ) {
}
private static final class MutableBounds {
private int minX = Integer.MAX_VALUE;
private int maxX = Integer.MIN_VALUE;
private int minZ = Integer.MAX_VALUE;
private int maxZ = Integer.MIN_VALUE;
private void include(int x, int z) {
minX = Math.min(minX, x);
maxX = Math.max(maxX, x);
minZ = Math.min(minZ, z);
maxZ = Math.max(maxZ, z);
}
private MutableBoundsSnapshot freeze() {
return new MutableBoundsSnapshot(minX, maxX, minZ, maxZ);
}
}
}
@@ -0,0 +1,79 @@
package art.arcane.iris.engine.mantle.components;
import art.arcane.iris.spi.PlatformBlockState;
import it.unimi.dsi.fastutil.longs.Long2IntOpenHashMap;
import java.util.function.IntConsumer;
import java.util.function.IntPredicate;
final class StructureFoundationPlanner {
static final int NO_GROUND = Integer.MIN_VALUE;
private StructureFoundationPlanner() {
}
static void recordBaseCell(Long2IntOpenHashMap columns, int x, int y, int z,
PlatformBlockState state, boolean supportNonOccluding) {
if (columns == null || state == null
|| !(supportNonOccluding ? state.isSolid() : state.isOccluding())) {
return;
}
long columnKey = pack(x, z);
if (!columns.containsKey(columnKey) || y < columns.get(columnKey)) {
columns.put(columnKey, y);
}
}
static int findGroundY(int foundationY, int maxDepth, int minimumY, IntPredicate solidAtY) {
if (foundationY <= minimumY) {
return NO_GROUND;
}
long requestedFloor = (long) foundationY - Math.max(1, maxDepth);
int scanFloor = (int) Math.max(minimumY, requestedFloor);
for (int y = foundationY - 1; y >= scanFloor; y--) {
if (solidAtY.test(y)) {
return y;
}
}
return NO_GROUND;
}
static boolean isGroundSolid(PlatformBlockState overlay, boolean carved, int mantleY, int terrainHeight) {
if (mantleY <= 0) {
return true;
}
if (overlay != null) {
return overlay.isSolid();
}
return !carved && mantleY <= terrainHeight;
}
static boolean isSurfaceSupportBoundary(PlatformBlockState overlay, boolean carved,
int mantleY, int terrainHeight) {
return carved || isGroundSolid(overlay, false, mantleY, terrainHeight);
}
static int fillSupportColumn(int foundationY, int groundY, IntConsumer supportAtY) {
if (groundY == NO_GROUND || groundY >= foundationY - 1) {
return 0;
}
int written = 0;
for (int y = foundationY - 1; y > groundY; y--) {
supportAtY.accept(y);
written++;
}
return written;
}
static long pack(int x, int z) {
return ((long) x << 32) | (z & 0xffffffffL);
}
static int unpackX(long packed) {
return (int) (packed >> 32);
}
static int unpackZ(long packed) {
return (int) packed;
}
}
@@ -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,38 @@
/*
* 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.mode;
import art.arcane.iris.engine.actuator.IrisBiomeActuator;
import art.arcane.iris.engine.actuator.IrisTerrainNormalActuator;
import art.arcane.iris.engine.framework.Engine;
import art.arcane.iris.engine.framework.EngineMode;
import art.arcane.iris.engine.framework.IrisEngineMode;
public class ModeEnclosure extends IrisEngineMode implements EngineMode {
public ModeEnclosure(Engine engine) {
super(engine);
var terrain = new IrisTerrainNormalActuator(getEngine());
var biome = new IrisBiomeActuator(getEngine());
registerStage(burst(
(x, z, k, p, m, c) -> terrain.actuate(x, z, k, m, c),
(x, z, k, p, m, c) -> biome.actuate(x, z, p, m, c)
));
}
}
@@ -0,0 +1,38 @@
/*
* 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.mode;
import art.arcane.iris.engine.actuator.IrisBiomeActuator;
import art.arcane.iris.engine.actuator.IrisTerrainNormalActuator;
import art.arcane.iris.engine.framework.Engine;
import art.arcane.iris.engine.framework.EngineMode;
import art.arcane.iris.engine.framework.IrisEngineMode;
public class ModeIslands extends IrisEngineMode implements EngineMode {
public ModeIslands(Engine engine) {
super(engine);
var terrain = new IrisTerrainNormalActuator(getEngine());
var biome = new IrisBiomeActuator(getEngine());
registerStage(burst(
(x, z, k, p, m, c) -> terrain.actuate(x, z, k, m, c),
(x, z, k, p, m, c) -> biome.actuate(x, z, p, m, c)
));
}
}
@@ -0,0 +1,133 @@
/*
* 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.mode;
import art.arcane.iris.engine.actuator.IrisBiomeActuator;
import art.arcane.iris.engine.actuator.IrisDecorantActuator;
import art.arcane.iris.engine.actuator.IrisTerrainNormalActuator;
import art.arcane.iris.engine.framework.Engine;
import art.arcane.iris.engine.framework.EngineMode;
import art.arcane.iris.engine.framework.EnginePlatformHooks;
import art.arcane.iris.engine.framework.EngineStage;
import art.arcane.iris.engine.framework.IrisEngineMode;
import art.arcane.iris.engine.modifier.IrisCarveModifier;
import art.arcane.iris.engine.modifier.IrisCustomModifier;
import art.arcane.iris.engine.modifier.IrisDepositModifier;
import art.arcane.iris.engine.modifier.IrisFloatingChildBiomeModifier;
import art.arcane.iris.engine.modifier.IrisPerfectionModifier;
import art.arcane.iris.engine.modifier.IrisPostModifier;
import art.arcane.iris.spi.IrisLogging;
import java.util.concurrent.atomic.AtomicLong;
public class ModeOverworld extends IrisEngineMode implements EngineMode {
private static final AtomicLong lastMaintenanceBypassLog = new AtomicLong(0L);
private final EnginePlatformHooks platformHooks;
public ModeOverworld(Engine engine) {
super(engine);
platformHooks = engine.getPlatformHooks();
IrisTerrainNormalActuator terrain = new IrisTerrainNormalActuator(getEngine());
IrisBiomeActuator biome = new IrisBiomeActuator(getEngine());
IrisDecorantActuator decorant = new IrisDecorantActuator(getEngine());
IrisCarveModifier cave = new IrisCarveModifier(getEngine());
IrisPostModifier post = new IrisPostModifier(getEngine());
IrisDepositModifier deposit = new IrisDepositModifier(getEngine());
IrisPerfectionModifier perfection = new IrisPerfectionModifier(getEngine());
IrisCustomModifier custom = new IrisCustomModifier(getEngine());
IrisFloatingChildBiomeModifier floatingChildBiomes = new IrisFloatingChildBiomeModifier(getEngine());
EngineStage sBiome = (x, z, k, p, m, c) -> biome.actuate(x, z, p, m, c);
EngineStage sGenMatter = (x, z, k, p, m, c) -> {
if (shouldBypassMantleStages()) {
return;
}
generateMatter(
x >> 4,
z >> 4,
m || getEngine().isStudio(),
c);
};
EngineStage sTerrain = (x, z, k, p, m, c) -> terrain.actuate(x, z, k, m, c);
EngineStage sDecorant = (x, z, k, p, m, c) -> decorant.actuate(x, z, k, m, c);
EngineStage sCave = (x, z, k, p, m, c) -> {
if (shouldBypassMantleStages()) {
return;
}
cave.modify(x >> 4, z >> 4, k, m, c);
};
EngineStage sDeposit = (x, z, k, p, m, c) -> {
if (shouldBypassMantleStages()) {
return;
}
deposit.modify(x, z, k, m, c);
};
EngineStage sPost = (x, z, k, p, m, c) -> {
if (shouldBypassMantleStages()) {
return;
}
post.modify(x, z, k, m, c);
};
EngineStage sInsertMatter = (x, z, K, p, m, c) -> {
if (shouldBypassMantleStages()) {
return;
}
getMantle().insertMatter(x >> 4, z >> 4, K, m);
};
EngineStage sFloatingTerrainSolid = (x, z, k, p, m, c) -> floatingChildBiomes.modify(x, z, k, m, c);
EngineStage sFloatingDecorate = (x, z, k, p, m, c) -> floatingChildBiomes.decorateColumns(x, z, k, m, c);
EngineStage sPerfection = (x, z, k, p, m, c) -> perfection.modify(x, z, k, m, c);
EngineStage sCustom = (x, z, k, p, m, c) -> {
if (shouldBypassMantleStages()) {
return;
}
custom.modify(x, z, k, m, c);
};
registerStage(burst(
sBiome,
sGenMatter,
sTerrain
));
registerStage(sCave);
registerStage(sPost);
registerStage(sFloatingTerrainSolid);
// Never burst these three: all of them write the same block hunk (and sDecorant reads
// the surface sInsertMatter writes), so parallel order is scheduler-dependent. The
// production path already runs them inline in this order; sequential registration
// makes studio (the only multicore path) match production and the goldenhash baseline.
registerStage(sDeposit);
registerStage(sInsertMatter);
registerStage(sDecorant);
registerStage(sFloatingDecorate);
registerStage(sPerfection);
registerStage(sCustom);
}
private boolean shouldBypassMantleStages() {
boolean active = platformHooks.shouldBypassMantleStages(getEngine());
if (active) {
long now = System.currentTimeMillis();
long last = lastMaintenanceBypassLog.get();
if (now - last >= 5000L && lastMaintenanceBypassLog.compareAndSet(last, now)) {
IrisLogging.info("Maintenance regen bypass: skipping mantle-backed overworld stages for Folia safety.");
}
}
return active;
}
}
@@ -0,0 +1,38 @@
/*
* 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.mode;
import art.arcane.iris.engine.actuator.IrisBiomeActuator;
import art.arcane.iris.engine.actuator.IrisTerrainNormalActuator;
import art.arcane.iris.engine.framework.Engine;
import art.arcane.iris.engine.framework.EngineMode;
import art.arcane.iris.engine.framework.IrisEngineMode;
public class ModeSuperFlat extends IrisEngineMode implements EngineMode {
public ModeSuperFlat(Engine engine) {
super(engine);
var terrain = new IrisTerrainNormalActuator(getEngine());
var biome = new IrisBiomeActuator(getEngine());
registerStage(burst(
(x, z, k, p, m, c) -> terrain.actuate(x, z, k, m, c),
(x, z, k, p, m, c) -> biome.actuate(x, z, p, m, c)
));
}
}
@@ -0,0 +1,777 @@
/*
* 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 art.arcane.iris.engine.UpperDimensionContext;
import art.arcane.iris.engine.actuator.IrisDecorantActuator;
import art.arcane.iris.engine.framework.Engine;
import art.arcane.iris.engine.framework.EngineAssignedModifier;
import art.arcane.iris.engine.object.world.biome.InferredType;
import art.arcane.iris.engine.object.world.biome.IrisBiome;
import art.arcane.iris.engine.object.decoration.IrisDecorationPart;
import art.arcane.iris.engine.object.decoration.IrisDecorator;
import art.arcane.iris.engine.object.terrain.carving.IrisDimensionCarvingResolver;
import art.arcane.iris.engine.object.procedural.IrisProceduralBlocks;
import art.arcane.iris.util.project.context.ChunkContext;
import art.arcane.iris.util.common.data.B;
import art.arcane.volmlib.util.documentation.ChunkCoordinates;
import art.arcane.iris.util.project.hunk.Hunk;
import art.arcane.volmlib.util.collection.KList;
import art.arcane.volmlib.util.mantle.runtime.Mantle;
import art.arcane.volmlib.util.mantle.runtime.MantleChunk;
import art.arcane.volmlib.util.mantle.runtime.TectonicPlate;
import art.arcane.volmlib.util.math.BlockPosition;
import art.arcane.volmlib.util.math.M;
import art.arcane.volmlib.util.math.PowerOfTwoCoordinates;
import art.arcane.volmlib.util.math.RNG;
import art.arcane.volmlib.util.matter.Matter;
import art.arcane.volmlib.util.matter.MatterCavern;
import art.arcane.volmlib.util.matter.slices.MarkerMatter;
import art.arcane.volmlib.util.scheduling.PrecisionStopwatch;
import it.unimi.dsi.fastutil.longs.Long2ObjectOpenHashMap;
import lombok.Data;
import art.arcane.iris.spi.PlatformBlockState;
import java.util.Map;
public class IrisCarveModifier extends EngineAssignedModifier<PlatformBlockState> {
private static final byte LIQUID_FLUID = 1;
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 MatterCavern BASIC_CAVERN = new MatterCavern(true, "", (byte) 0);
private final RNG rng;
private final PlatformBlockState AIR = B.getState("CAVE_AIR");
private final PlatformBlockState LAVA = B.getState("LAVA");
private final IrisDecorantActuator decorant;
public IrisCarveModifier(Engine engine) {
super(engine, "Carve");
rng = new RNG(getEngine().getSeedManager().getCarve());
decorant = new IrisDecorantActuator(engine);
}
@Override
@ChunkCoordinates
public void onModify(int x, int z, Hunk<PlatformBlockState> output, boolean multicore, ChunkContext context) {
PrecisionStopwatch caveStopwatch = PrecisionStopwatch.start();
Mantle<Matter> mantle = getEngine().getMantle().getMantle();
IrisDimensionCarvingResolver.State resolverState = new IrisDimensionCarvingResolver.State();
Long2ObjectOpenHashMap<IrisBiome> caveBiomeCache = new Long2ObjectOpenHashMap<>(2048);
IrisCarveScratch scratch = SCRATCH.get();
scratch.reset();
CarveWallBuffer walls = scratch.walls;
CarveColumnMask[] columnMasks = scratch.columnMasks;
CarveColumnMask[] boundaryMasks = scratch.boundaryMasks;
int[] surfaceHeights = scratch.surfaceHeights;
Map<String, IrisBiome> customBiomeCache = scratch.customBiomeCache;
UpperDimensionContext upperCtx = getEngine().getUpperContext();
boolean protectUpper = upperCtx != null && !getEngine().getDimension().isUpperDimensionCarving();
int[] upperSurfaceHeights = protectUpper ? scratch.getOrCreateUpperSurfaceHeights() : null;
int chunkBlockX = PowerOfTwoCoordinates.chunkToBlock(x);
int chunkBlockZ = PowerOfTwoCoordinates.chunkToBlock(z);
for (int columnIndex = 0; columnIndex < 256; columnIndex++) {
int localX = PowerOfTwoCoordinates.unpackLocal16X(columnIndex);
int localZ = columnIndex & 15;
surfaceHeights[columnIndex] = context.getRoundedHeight(localX, localZ);
if (protectUpper) {
int worldX = localX + chunkBlockX;
int worldZ = localZ + chunkBlockZ;
int rawUpper = upperCtx.getUpperSurfaceY(worldX, worldZ);
int gap = getEngine().getDimension().getUpperDimensionGap();
upperSurfaceHeights[columnIndex] = Math.max(rawUpper, surfaceHeights[columnIndex] + gap);
}
}
MantleChunk<Matter> mantleChunk = mantle.getChunk(x, z).use();
try {
PrecisionStopwatch resolveStopwatch = PrecisionStopwatch.start();
int worldHeightSpan = getEngine().getWorld().maxHeight() - getEngine().getWorld().minHeight();
int caveLavaHeight = getEngine().getDimension().getCaveLavaHeight();
mantleChunk.iterate(MatterCavern.class, (xx, yy, zz, cavern) -> {
if (cavern == null) {
return;
}
if (yy >= worldHeightSpan || yy <= 0) {
return;
}
int rx = xx & 15;
int rz = zz & 15;
int columnIndex = PowerOfTwoCoordinates.packLocal16(rx, rz);
if (upperSurfaceHeights != null && yy >= upperSurfaceHeights[columnIndex]) {
return;
}
PlatformBlockState current = output.getRaw(rx, yy, rz);
boolean explicitCarveIntent = hasExplicitCarveIntent(cavern);
if (shouldPreserveExistingFluid(cavern, current)) {
return;
}
columnMasks[columnIndex].add(yy);
if (!cavern.getCustomBiome().isEmpty()) {
scratch.customCaveBiomePresent = true;
}
if (current.isAir() && !explicitCarveIntent) {
return;
}
if (explicitCarveIntent) {
// Only a fluid cavern consumes the fluid sample, and on the maintenance path that
// sample is a full procedural stream evaluation, so never take it per voxel.
PlatformBlockState fluid = isFluidIntent(cavern) ? context.getFluid().get(rx, rz) : null;
output.setRaw(rx, yy, rz, resolveExplicitCarveState(cavern, fluid, LAVA, AIR));
} else if (usesDefaultLava(caveLavaHeight, yy)) {
output.setRaw(rx, yy, rz, LAVA);
} else {
output.setRaw(rx, yy, rz, AIR);
}
});
if (scratch.customCaveBiomePresent) {
addInternalWallsFromMantle(mantleChunk, walls, columnMasks);
} else {
addInternalWallsFromMasks(walls, columnMasks);
}
addCrossChunkBoundaryWalls(mantle, mantleChunk, walls, boundaryMasks, x, z, surfaceHeights);
getEngine().getMetrics().getCarveResolve().put(resolveStopwatch.getMilliseconds());
PrecisionStopwatch applyStopwatch = PrecisionStopwatch.start();
try {
walls.forEach((rx, yy, rz, cavern) -> {
int worldX = rx + chunkBlockX;
int worldZ = rz + chunkBlockZ;
String customBiome = cavern.getCustomBiome();
IrisBiome biome = customBiome.isEmpty()
? resolveCaveBiome(caveBiomeCache, worldX, yy, worldZ, resolverState)
: resolveCustomBiome(customBiomeCache, customBiome);
if (biome != null) {
PlatformBlockState data = biome.getWall().get(rng, worldX, yy, worldZ, getData());
int columnIndex = PowerOfTwoCoordinates.packLocal16(rx, rz);
if (data != null && B.isSolid(output.getRaw(rx, yy, rz)) && yy < surfaceHeights[columnIndex]) {
output.setRaw(rx, yy, rz, data);
}
}
});
for (int columnIndex = 0; columnIndex < 256; columnIndex++) {
processColumnFromMask(output, mantleChunk, mantle, columnMasks[columnIndex], columnIndex, x, z, resolverState, caveBiomeCache, customBiomeCache);
}
for (int columnIndex = 0; columnIndex < 256; columnIndex++) {
if (boundaryMasks[columnIndex].isEmpty() || !columnMasks[columnIndex].isEmpty()) {
continue;
}
processBoundaryColumnFromMask(output, boundaryMasks[columnIndex], walls, columnIndex, x, z, resolverState, caveBiomeCache, customBiomeCache);
}
// Surface-break carving must not leave an ore cap suspended across the opening.
for (int columnIndex = 0; columnIndex < surfaceHeights.length; columnIndex++) {
int surfaceY = surfaceHeights[columnIndex];
if (surfaceY <= 0 || surfaceY >= output.getHeight()) {
continue;
}
int belowY = surfaceY - 1;
if (!columnMasks[columnIndex].contains(belowY) && !boundaryMasks[columnIndex].contains(belowY)) {
continue;
}
int localX = PowerOfTwoCoordinates.unpackLocal16X(columnIndex);
int localZ = columnIndex & 15;
PlatformBlockState surface = output.getRaw(localX, surfaceY, localZ);
PlatformBlockState below = output.getRaw(localX, belowY, localZ);
if (isUnsupportedSurfaceOre(surface, below)) {
output.setRaw(localX, surfaceY, localZ, AIR);
}
}
} finally {
getEngine().getMetrics().getCarveApply().put(applyStopwatch.getMilliseconds());
}
} finally {
getEngine().getMetrics().getCave().put(caveStopwatch.getMilliseconds());
mantleChunk.release();
}
}
static boolean hasExplicitCarveIntent(MatterCavern cavern) {
return cavern != null && (isFluidIntent(cavern) || cavern.isLava() || cavern.getLiquid() == 3);
}
static boolean isFluidIntent(MatterCavern cavern) {
return cavern != null && cavern.getLiquid() == LIQUID_FLUID;
}
static boolean shouldPreserveExistingFluid(MatterCavern cavern, PlatformBlockState current) {
return B.isFluid(current) && !hasExplicitCarveIntent(cavern);
}
static boolean usesDefaultLava(int caveLavaHeight, int y) {
return y <= caveLavaHeight;
}
static boolean isUnsupportedSurfaceOre(PlatformBlockState surface, PlatformBlockState below) {
return B.isOre(surface) && !B.isSolid(below);
}
static PlatformBlockState resolveExplicitCarveState(MatterCavern cavern, PlatformBlockState fluid,
PlatformBlockState lava, PlatformBlockState air) {
if (cavern == null) {
return null;
}
if (isFluidIntent(cavern)) {
return fluid;
}
if (cavern.isLava()) {
return lava;
}
return cavern.getLiquid() == 3 ? air : null;
}
private void addInternalWallsFromMasks(CarveWallBuffer walls, CarveColumnMask[] columnMasks) {
for (int columnIndex = 0; columnIndex < 256; columnIndex++) {
CarveColumnMask columnMask = columnMasks[columnIndex];
if (columnMask.isEmpty()) {
continue;
}
int rx = columnIndex >> 4;
int rz = columnIndex & 15;
int yy = columnMask.nextSetBit(0);
while (yy >= 0) {
if (rz < 15 && !columnMasks[columnIndex + 1].contains(yy)) {
walls.put(rx, yy, rz + 1, BASIC_CAVERN);
}
if (rx < 15 && !columnMasks[columnIndex + 16].contains(yy)) {
walls.put(rx + 1, yy, rz, BASIC_CAVERN);
}
if (rz > 0 && !columnMasks[columnIndex - 1].contains(yy)) {
walls.put(rx, yy, rz - 1, BASIC_CAVERN);
}
if (rx > 0 && !columnMasks[columnIndex - 16].contains(yy)) {
walls.put(rx - 1, yy, rz, BASIC_CAVERN);
}
yy = columnMask.nextSetBit(yy + 1);
}
}
}
private void addInternalWallsFromMantle(MantleChunk<Matter> mc, CarveWallBuffer walls, CarveColumnMask[] columnMasks) {
for (int columnIndex = 0; columnIndex < 256; columnIndex++) {
CarveColumnMask columnMask = columnMasks[columnIndex];
if (columnMask.isEmpty()) {
continue;
}
int rx = columnIndex >> 4;
int rz = columnIndex & 15;
int yy = columnMask.nextSetBit(0);
while (yy >= 0) {
MatterCavern cavern = mc.get(rx, yy, rz, MatterCavern.class);
if (cavern != null) {
if (rz < 15 && mc.get(rx, yy, rz + 1, MatterCavern.class) == null) {
walls.put(rx, yy, rz + 1, cavern);
}
if (rx < 15 && mc.get(rx + 1, yy, rz, MatterCavern.class) == null) {
walls.put(rx + 1, yy, rz, cavern);
}
if (rz > 0 && mc.get(rx, yy, rz - 1, MatterCavern.class) == null) {
walls.put(rx, yy, rz - 1, cavern);
}
if (rx > 0 && mc.get(rx - 1, yy, rz, MatterCavern.class) == null) {
walls.put(rx - 1, yy, rz, cavern);
}
}
yy = columnMask.nextSetBit(yy + 1);
}
}
}
private void addCrossChunkBoundaryWalls(
Mantle<Matter> mantle,
MantleChunk<Matter> mc,
CarveWallBuffer walls,
CarveColumnMask[] boundaryMasks,
int chunkX,
int chunkZ,
int[] surfaceHeights
) {
int baseX = PowerOfTwoCoordinates.chunkToBlock(chunkX);
int baseZ = PowerOfTwoCoordinates.chunkToBlock(chunkZ);
int maxSurfaceY = 0;
for (int index = 0; index < surfaceHeights.length; index++) {
if (surfaceHeights[index] > maxSurfaceY) {
maxSurfaceY = surfaceHeights[index];
}
}
int maxY = Math.min(getEngine().getWorld().maxHeight() - getEngine().getWorld().minHeight() - 1, maxSurfaceY + 1);
if (maxY < 1) {
return;
}
MantleChunk<Matter> west = existingMantleChunk(mantle, chunkX - 1, chunkZ);
MantleChunk<Matter> east = existingMantleChunk(mantle, chunkX + 1, chunkZ);
MantleChunk<Matter> north = existingMantleChunk(mantle, chunkX, chunkZ - 1);
MantleChunk<Matter> south = existingMantleChunk(mantle, chunkX, chunkZ + 1);
if (west == null && east == null && north == null && south == null) {
return;
}
for (int yy = 1; yy <= maxY; yy++) {
for (int offset = 0; offset < 16; offset++) {
if (west != null) {
tryAddBoundaryWall(mc, west, walls, boundaryMasks, 0, yy, offset, 15, offset);
}
if (east != null) {
tryAddBoundaryWall(mc, east, walls, boundaryMasks, 15, yy, offset, 0, offset);
}
if (north != null) {
tryAddBoundaryWall(mc, north, walls, boundaryMasks, offset, yy, 0, offset, 15);
}
if (south != null) {
tryAddBoundaryWall(mc, south, walls, boundaryMasks, offset, yy, 15, offset, 0);
}
}
}
}
private void tryAddBoundaryWall(
MantleChunk<Matter> mc,
MantleChunk<Matter> neighborChunk,
CarveWallBuffer walls,
CarveColumnMask[] boundaryMasks,
int localX,
int yy,
int localZ,
int neighborX,
int neighborZ
) {
if (mc.get(localX, yy, localZ, MatterCavern.class) != null) {
return;
}
MatterCavern neighbor = neighborChunk.get(neighborX, yy, neighborZ, MatterCavern.class);
if (neighbor == null) {
return;
}
walls.put(localX, yy, localZ, neighbor);
int columnIndex = PowerOfTwoCoordinates.packLocal16(localX, localZ);
boundaryMasks[columnIndex].add(yy);
}
private MantleChunk<Matter> existingMantleChunk(Mantle<Matter> mantle, int chunkX, int chunkZ) {
TectonicPlate<Matter> plate = mantle.getLoadedRegions().get(Mantle.key(chunkX >> 5, chunkZ >> 5));
if (plate == null || plate.isClosed()) {
return null;
}
return plate.get(chunkX & 31, chunkZ & 31);
}
private void processColumnFromMask(
Hunk<PlatformBlockState> output,
MantleChunk<Matter> mc,
Mantle<Matter> mantle,
CarveColumnMask columnMask,
int columnIndex,
int chunkX,
int chunkZ,
IrisDimensionCarvingResolver.State resolverState,
Long2ObjectOpenHashMap<IrisBiome> caveBiomeCache,
Map<String, IrisBiome> 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 <= getEngine().getHeight()) {
if (y == buf + 1) {
buf = y;
zone.ceiling = buf;
} else {
if (zone.isValid(getEngine())) {
processZone(output, mc, mantle, zone, rx, rz, worldX, worldZ, resolverState, caveBiomeCache, customBiomeCache);
}
zone = new CaveZone();
zone.setFloor(y);
buf = y;
}
}
y = columnMask.nextSetBit(y + 1);
}
if (zone.isValid(getEngine())) {
processZone(output, mc, mantle, zone, rx, rz, worldX, worldZ, resolverState, caveBiomeCache, customBiomeCache);
}
}
private void processBoundaryColumnFromMask(
Hunk<PlatformBlockState> output,
CarveColumnMask boundaryMask,
CarveWallBuffer walls,
int columnIndex,
int chunkX,
int chunkZ,
IrisDimensionCarvingResolver.State resolverState,
Long2ObjectOpenHashMap<IrisBiome> caveBiomeCache,
Map<String, IrisBiome> 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(output, walls, rx, rz, worldX, worldZ, zoneFloor, zoneCeiling, resolverState, caveBiomeCache, customBiomeCache);
zoneFloor = y;
zoneCeiling = y;
}
y = boundaryMask.nextSetBit(y + 1);
}
paintBoundaryZone(output, walls, rx, rz, worldX, worldZ, zoneFloor, zoneCeiling, resolverState, caveBiomeCache, customBiomeCache);
}
private void paintBoundaryZone(
Hunk<PlatformBlockState> output,
CarveWallBuffer walls,
int rx,
int rz,
int worldX,
int worldZ,
int zoneFloor,
int zoneCeiling,
IrisDimensionCarvingResolver.State resolverState,
Long2ObjectOpenHashMap<IrisBiome> caveBiomeCache,
Map<String, IrisBiome> customBiomeCache
) {
IrisBiome floorBiome = resolveCaveBoundaryBiome(
walls.get(rx, zoneFloor, rz), worldX, zoneFloor, worldZ,
resolverState, caveBiomeCache, customBiomeCache);
IrisBiome ceilingBiome = resolveCaveBoundaryBiome(
walls.get(rx, zoneCeiling, rz), worldX, zoneCeiling, worldZ,
resolverState, caveBiomeCache, customBiomeCache);
if (floorBiome == null && ceilingBiome == null) {
return;
}
if (floorBiome != null) {
KList<PlatformBlockState> floorLayers = floorBiome.generateLayers(
getDimension(), worldX, worldZ, rng, 3, zoneFloor, getData(), getComplex());
for (int i = 0; i < zoneFloor - 1; i++) {
if (!floorLayers.hasIndex(i)) {
break;
}
int floorY = zoneFloor - i - 1;
if (floorY < 0) {
break;
}
PlatformBlockState existing = output.getRaw(rx, floorY, rz);
PlatformBlockState layer = floorLayers.get(i);
if (!B.isSolid(existing) || !canReplaceCaveFloorLayer(output, rx, floorY, rz, layer)) {
continue;
}
if (B.isOre(existing)) {
output.setRaw(rx, floorY, rz, B.toDeepSlateOre(existing, layer));
continue;
}
output.setRaw(rx, floorY, rz, layer);
}
}
if (ceilingBiome != null) {
int worldMaxY = getEngine().getWorld().maxHeight() - getEngine().getWorld().minHeight();
KList<PlatformBlockState> ceilingLayers = ceilingBiome.generateCeilingLayers(
getDimension(), worldX, worldZ, rng, 3, zoneCeiling, getData(), getComplex());
for (int i = 0; i < ceilingLayers.size(); i++) {
int ceilingY = zoneCeiling + i + 1;
if (ceilingY >= worldMaxY) {
break;
}
PlatformBlockState existing = output.getRaw(rx, ceilingY, rz);
if (!B.isSolid(existing)) {
continue;
}
PlatformBlockState layer = ceilingLayers.get(i);
if (B.isOre(existing)) {
output.setRaw(rx, ceilingY, rz, B.toDeepSlateOre(existing, layer));
continue;
}
output.setRaw(rx, ceilingY, rz, layer);
}
}
}
/**
* 1-in-16 marker roll from a SplitMix64 finalizer over (carve seed, block position, salt).
* Deterministic per seed and position, thread-order independent, allocation free.
*/
private boolean markerRoll(int x, int y, int z, long salt) {
long h = (getEngine().getSeedManager().getCarve() + salt) ^ BlockPosition.toLong(x, y, z);
h = (h ^ (h >>> 30)) * 0xBF58476D1CE4E5B9L;
h = (h ^ (h >>> 27)) * 0x94D049BB133111EBL;
h ^= h >>> 31;
return (h & 15L) == 0L;
}
private void processZone(Hunk<PlatformBlockState> output, MantleChunk<Matter> mc, Mantle<Matter> mantle, CaveZone zone, int rx, int rz, int xx, int zz, IrisDimensionCarvingResolver.State resolverState, Long2ObjectOpenHashMap<IrisBiome> caveBiomeCache, Map<String, IrisBiome> customBiomeCache) {
int maxY = output.getHeight();
if (zone.ceiling + 1 < maxY && B.isDecorant(output.getRaw(rx, zone.ceiling + 1, rz))) {
output.setRaw(rx, zone.ceiling + 1, rz, AIR);
}
if (B.isDecorant(output.getRaw(rx, zone.ceiling, rz))) {
output.setRaw(rx, zone.ceiling, rz, AIR);
}
// Seed-derived and position-keyed, never Math.random(): these markers persist into the
// mantle and drive cave spawning, so the same seed must stamp the same markers on
// every run and every platform. Inline mix, no allocation on this hot path.
if (markerRoll(xx, zone.ceiling, zz, 0x9E3779B97F4A7C15L)) {
mantle.set(xx, zone.ceiling, zz, MarkerMatter.CAVE_CEILING);
}
if (markerRoll(xx, zone.floor, zz, 0xC2B2AE3D27D4EB4FL)) {
mantle.set(xx, zone.floor, zz, MarkerMatter.CAVE_FLOOR);
}
IrisBiome floorBiome = resolveCaveBoundaryBiome(mc, rx, zone.floor, rz, xx, zz, resolverState, caveBiomeCache, customBiomeCache);
IrisBiome ceilingBiome = resolveCaveBoundaryBiome(mc, rx, zone.ceiling, rz, xx, zz, resolverState, caveBiomeCache, customBiomeCache);
if (floorBiome == null && ceilingBiome == null) {
return;
}
if (floorBiome != null) {
KList<PlatformBlockState> floorBlocks = floorBiome.generateLayers(getDimension(), xx, zz, rng, 3, zone.floor, getData(), getComplex());
for (int i = 0; i < zone.floor - 1; i++) {
if (!floorBlocks.hasIndex(i)) {
break;
}
int y = zone.floor - i - 1;
PlatformBlockState block = floorBlocks.get(i);
PlatformBlockState existing = output.getRaw(rx, y, rz);
if (!B.isSolid(existing) || !canReplaceCaveFloorLayer(output, rx, y, rz, block)) {
continue;
}
if (B.isOre(existing)) {
output.setRaw(rx, y, rz, B.toDeepSlateOre(existing, block));
continue;
}
output.setRaw(rx, y, rz, block);
}
}
if (ceilingBiome != null) {
KList<PlatformBlockState> ceilingBlocks = ceilingBiome.generateCeilingLayers(getDimension(), xx, zz, rng, 3, zone.ceiling, getData(), getComplex());
for (int i = 0; i < ceilingBlocks.size(); i++) {
int cy = zone.ceiling + i + 1;
if (cy >= maxY) {
break;
}
PlatformBlockState block = ceilingBlocks.get(i);
PlatformBlockState existing = output.getRaw(rx, cy, rz);
if (!B.isSolid(existing)) {
continue;
}
if (B.isOre(existing)) {
output.setRaw(rx, cy, rz, B.toDeepSlateOre(existing, block));
continue;
}
output.setRaw(rx, cy, rz, block);
}
}
IrisDecorator[] surfaceDecorators = floorBiome == null
? new IrisDecorator[0]
: floorBiome.getDecoratorBucket(IrisDecorationPart.NONE);
if (surfaceDecorators.length > 0 && hasStableCaveFloorSupport(output, rx, zone.getFloor(), rz)) {
decorant.getSurfaceDecorator().decorate(rx, rz, xx, xx, xx, zz, zz, zz, output, floorBiome, InferredType.CAVE, zone.getFloor() - 1, zone.airThickness());
}
IrisDecorator[] ceilingDecorators = ceilingBiome == null
? new IrisDecorator[0]
: ceilingBiome.getDecoratorBucket(IrisDecorationPart.CEILING);
if (ceilingDecorators.length > 0 && zone.getCeiling() + 1 < maxY && B.isSolid(output.getRaw(rx, zone.getCeiling() + 1, rz))) {
decorant.getCeilingDecorator().decorate(rx, rz, xx, xx, xx, zz, zz, zz, output, ceilingBiome, InferredType.CAVE, zone.getCeiling(), zone.airThickness());
}
}
IrisBiome resolveCaveBoundaryBiome(MantleChunk<Matter> mantleChunk, int x, int y, int z, int worldX, int worldZ, IrisDimensionCarvingResolver.State resolverState, Long2ObjectOpenHashMap<IrisBiome> caveBiomeCache, Map<String, IrisBiome> customBiomeCache) {
MatterCavern cavern = dataIfPresent(mantleChunk, x, y, z, MatterCavern.class);
return resolveCaveBoundaryBiome(
cavern, worldX, y, worldZ, resolverState, caveBiomeCache, customBiomeCache);
}
private static <T> T dataIfPresent(MantleChunk<Matter> mantleChunk, int x, int y, int z, Class<T> type) {
int section = y >> 4;
if (y < 0 || !mantleChunk.exists(section)) {
return null;
}
Matter matter = mantleChunk.get(section);
if (matter == null || !matter.hasSlice(type)) {
return null;
}
return matter.<T>getSlice(type).get(x & 15, y & 15, z & 15);
}
IrisBiome resolveCaveBoundaryBiome(MatterCavern cavern, int worldX, int y, int worldZ, IrisDimensionCarvingResolver.State resolverState, Long2ObjectOpenHashMap<IrisBiome> caveBiomeCache, Map<String, IrisBiome> customBiomeCache) {
if (cavern != null && !cavern.getCustomBiome().isEmpty()) {
return resolveCustomBiome(customBiomeCache, cavern.getCustomBiome());
}
return resolveCaveBiome(caveBiomeCache, worldX, y, worldZ, resolverState);
}
static boolean canReplaceCaveFloorLayer(Hunk<PlatformBlockState> output, int x, int y, int z, PlatformBlockState layer) {
return !isGravityAffected(layer) || y > 0 && B.isSolid(output.getRaw(x, y - 1, z));
}
static boolean hasStableCaveFloorSupport(Hunk<PlatformBlockState> output, int x, int floorY, int z) {
if (floorY <= 0) {
return false;
}
PlatformBlockState support = output.getRaw(x, floorY - 1, z);
if (!B.isSolid(support)) {
return false;
}
return !isGravityAffected(support) || floorY > 1 && B.isSolid(output.getRaw(x, floorY - 2, z));
}
static boolean isGravityAffected(PlatformBlockState state) {
if (state == null) {
return false;
}
String key = IrisProceduralBlocks.materialKey(state);
return key.equals("minecraft:sand")
|| key.equals("minecraft:red_sand")
|| key.equals("minecraft:gravel")
|| key.equals("minecraft:suspicious_sand")
|| key.equals("minecraft:suspicious_gravel")
|| key.endsWith("_concrete_powder");
}
private IrisBiome resolveCaveBiome(Long2ObjectOpenHashMap<IrisBiome> caveBiomeCache, int x, int y, int z, IrisDimensionCarvingResolver.State resolverState) {
IrisBiome center = sampleCaveBiome(caveBiomeCache, x, y, z, resolverState);
if (center == null) {
return null;
}
IrisBiome xPos = sampleCaveBiome(caveBiomeCache, x + CAVE_BIOME_BLEND_RADIUS, y, z, resolverState);
IrisBiome xNeg = sampleCaveBiome(caveBiomeCache, x - CAVE_BIOME_BLEND_RADIUS, y, z, resolverState);
IrisBiome zPos = sampleCaveBiome(caveBiomeCache, x, y, z + CAVE_BIOME_BLEND_RADIUS, resolverState);
IrisBiome zNeg = sampleCaveBiome(caveBiomeCache, x, y, z - CAVE_BIOME_BLEND_RADIUS, resolverState);
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 IrisBiome sampleCaveBiome(Long2ObjectOpenHashMap<IrisBiome> caveBiomeCache, int x, int y, int z, IrisDimensionCarvingResolver.State resolverState) {
long key = BlockPosition.toLong(x, y, z);
IrisBiome cachedBiome = caveBiomeCache.get(key);
if (cachedBiome != null) {
return cachedBiome;
}
IrisBiome resolvedBiome = getEngine().getCaveBiome(x, y, z, resolverState);
if (resolvedBiome != null) {
caveBiomeCache.put(key, resolvedBiome);
}
return resolvedBiome;
}
private IrisBiome resolveCustomBiome(Map<String, IrisBiome> customBiomeCache, String customBiome) {
if (customBiomeCache.containsKey(customBiome)) {
return customBiomeCache.get(customBiome);
}
IrisBiome loaded = getEngine().getData().getBiomeLoader().load(customBiome);
customBiomeCache.put(customBiome, loaded);
return loaded;
}
@Data
public static class CaveZone {
private int ceiling = -1;
private int floor = -1;
public int airThickness() {
return (ceiling - floor) - 1;
}
public boolean isValid(Engine engine) {
return floor < ceiling && ceiling - floor >= 1 && floor >= 0 && ceiling <= engine.getHeight() && airThickness() > 0;
}
public String toString() {
return floor + "-" + ceiling;
}
}
}
@@ -0,0 +1,277 @@
/*
* 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 art.arcane.iris.engine.object.world.biome.IrisBiome;
import art.arcane.volmlib.util.matter.MatterCavern;
import art.arcane.volmlib.util.math.PowerOfTwoCoordinates;
import java.util.Arrays;
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<String, IrisBiome> 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;
}
}
final class CarveColumnMask {
private long[] words = new long[8];
private int maxWord = -1;
void add(int y) {
if (y < 0) {
return;
}
int wordIndex = y >> 6;
if (wordIndex >= words.length) {
words = Arrays.copyOf(words, Math.max(words.length << 1, wordIndex + 1));
}
words[wordIndex] |= 1L << (y & 63);
if (wordIndex > maxWord) {
maxWord = wordIndex;
}
}
int nextSetBit(int fromBit) {
if (maxWord < 0) {
return -1;
}
int startBit = Math.max(0, fromBit);
int wordIndex = startBit >> 6;
if (wordIndex > maxWord) {
return -1;
}
long word = words[wordIndex] & (-1L << (startBit & 63));
while (true) {
if (word != 0L) {
return (wordIndex << 6) + Long.numberOfTrailingZeros(word);
}
wordIndex++;
if (wordIndex > maxWord) {
return -1;
}
word = words[wordIndex];
}
}
boolean isEmpty() {
return maxWord < 0;
}
boolean contains(int y) {
if (y < 0) {
return false;
}
int wordIndex = y >> 6;
if (wordIndex > maxWord) {
return false;
}
return (words[wordIndex] & (1L << (y & 63))) != 0L;
}
void clear() {
if (maxWord < 0) {
return;
}
for (int index = 0; index <= maxWord; index++) {
words[index] = 0L;
}
maxWord = -1;
}
}
final class CarveWallBuffer {
private static final int EMPTY_KEY = -1;
private static final double LOAD_FACTOR = 0.75D;
private int[] keys;
private MatterCavern[] values;
private int mask;
private int resizeAt;
private int size;
CarveWallBuffer(int expectedSize) {
int capacity = 1;
int minimumCapacity = Math.max(8, expectedSize);
while (capacity < minimumCapacity) {
capacity <<= 1;
}
keys = new int[capacity];
Arrays.fill(keys, EMPTY_KEY);
values = new MatterCavern[capacity];
mask = capacity - 1;
resizeAt = Math.max(1, (int) (capacity * LOAD_FACTOR));
}
void put(int x, int y, int z, MatterCavern value) {
int key = pack(x, y, z);
int index = mix(key) & mask;
while (true) {
int existingKey = keys[index];
if (existingKey == EMPTY_KEY) {
keys[index] = key;
values[index] = value;
size++;
if (size >= resizeAt) {
resize();
}
return;
}
if (existingKey == key) {
values[index] = value;
return;
}
index = (index + 1) & mask;
}
}
MatterCavern get(int x, int y, int z) {
int key = pack(x, y, z);
int index = mix(key) & mask;
while (true) {
int existingKey = keys[index];
if (existingKey == EMPTY_KEY) {
return null;
}
if (existingKey == key) {
return values[index];
}
index = (index + 1) & mask;
}
}
void forEach(Consumer consumer) {
for (int index = 0; index < keys.length; index++) {
int key = keys[index];
if (key == EMPTY_KEY) {
continue;
}
MatterCavern cavern = values[index];
if (cavern != null) {
consumer.accept(unpackX(key), unpackY(key), unpackZ(key), cavern);
}
}
}
void clear() {
Arrays.fill(keys, EMPTY_KEY);
Arrays.fill(values, null);
size = 0;
}
private void resize() {
int[] oldKeys = keys;
MatterCavern[] oldValues = values;
int nextCapacity = oldKeys.length << 1;
keys = new int[nextCapacity];
Arrays.fill(keys, EMPTY_KEY);
values = new MatterCavern[nextCapacity];
mask = nextCapacity - 1;
resizeAt = Math.max(1, (int) (nextCapacity * LOAD_FACTOR));
size = 0;
for (int index = 0; index < oldKeys.length; index++) {
int key = oldKeys[index];
MatterCavern value = oldValues[index];
if (key != EMPTY_KEY && value != null) {
reinsert(key, value);
}
}
}
private void reinsert(int key, MatterCavern value) {
int index = mix(key) & mask;
while (keys[index] != EMPTY_KEY) {
index = (index + 1) & mask;
}
keys[index] = key;
values[index] = value;
size++;
}
private int pack(int x, int y, int z) {
return (y << 8) | PowerOfTwoCoordinates.packLocal16(x & 15, z & 15);
}
private int unpackX(int key) {
return PowerOfTwoCoordinates.unpackLocal16X(key & 255);
}
private int unpackY(int key) {
return key >> 8;
}
private int unpackZ(int key) {
return PowerOfTwoCoordinates.unpackLocal16Z(key);
}
private int mix(int value) {
int mixed = value * 0x9E3779B9;
return mixed ^ (mixed >>> 16);
}
@FunctionalInterface
interface Consumer {
void accept(int x, int y, int z, MatterCavern cavern);
}
}
@@ -0,0 +1,64 @@
package art.arcane.iris.engine.modifier;
import art.arcane.iris.core.link.Identifier;
import art.arcane.iris.engine.framework.Engine;
import art.arcane.iris.engine.framework.EngineAssignedModifier;
import art.arcane.iris.spi.PlatformBlockState;
import art.arcane.iris.util.common.parallel.BurstExecutor;
import art.arcane.iris.util.common.parallel.MultiBurst;
import art.arcane.iris.util.project.context.ChunkContext;
import art.arcane.iris.util.project.hunk.Hunk;
import art.arcane.volmlib.util.mantle.flag.MantleFlag;
import art.arcane.volmlib.util.mantle.runtime.MantleChunk;
import art.arcane.volmlib.util.matter.Matter;
public class IrisCustomModifier extends EngineAssignedModifier<PlatformBlockState> {
public IrisCustomModifier(Engine engine) {
super(engine, "Custom");
}
@Override
public void onModify(int x, int z, Hunk<PlatformBlockState> output, boolean multicore, ChunkContext context) {
MantleChunk<Matter> mc = getEngine().getMantle().getMantle().getChunk(x >> 4, z >> 4);
if (!mc.isFlagged(MantleFlag.CUSTOM_ACTIVE)) {
return;
}
mc.use();
BurstExecutor burst = MultiBurst.burst.burst(output.getHeight());
burst.setMulticore(multicore);
// complete() must run before release() even when queueing throws — detached burst
// tasks must never write into a released chunk, and a lost permit wedges close().
try {
for (int y = 0; y < output.getHeight(); y++) {
int finalY = y;
burst.queue(() -> {
for (int rX = 0; rX < output.getWidth(); rX++) {
for (int rZ = 0; rZ < output.getDepth(); rZ++) {
PlatformBlockState b = output.get(rX, finalY, rZ);
if (b == null || !b.isCustom()) {
continue;
}
String placementKey = b.deferredPlacementKey();
PlatformBlockState baseState = b.placementBaseState();
if (placementKey == null || baseState == null) {
continue;
}
mc.getOrCreate(finalY >> 4)
.slice(Identifier.class)
.set(rX, finalY & 15, rZ, Identifier.fromString(placementKey));
output.set(rX, finalY, rZ, baseState);
}
}
});
}
} finally {
try {
burst.complete();
} finally {
mc.release();
}
}
}
}
@@ -0,0 +1,357 @@
/*
* 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 art.arcane.iris.engine.framework.Engine;
import art.arcane.iris.engine.framework.EngineAssignedModifier;
import art.arcane.iris.engine.object.world.biome.IrisBiome;
import art.arcane.iris.engine.object.terrain.deposit.IrisDepositGenerator;
import art.arcane.iris.engine.object.terrain.deposit.IrisDepositHeightDistribution;
import art.arcane.iris.engine.object.terrain.deposit.IrisDepositPlacementScope;
import art.arcane.iris.engine.object.terrain.deposit.IrisDepositVariant;
import art.arcane.iris.engine.object.world.dimension.IrisDimension;
import art.arcane.iris.engine.object.terrain.carving.IrisDimensionCarvingResolver;
import art.arcane.iris.engine.object.prefab.IrisObject;
import art.arcane.iris.engine.object.procedural.IrisProceduralBlocks;
import art.arcane.iris.engine.object.world.region.IrisRegion;
import art.arcane.iris.util.project.context.ChunkContext;
import art.arcane.volmlib.util.data.HeightMap;
import art.arcane.iris.util.project.hunk.Hunk;
import art.arcane.volmlib.util.mantle.runtime.MantleChunk;
import art.arcane.volmlib.util.math.RNG;
import art.arcane.volmlib.util.matter.MatterCavern;
import art.arcane.iris.util.common.parallel.BurstExecutor;
import art.arcane.volmlib.util.scheduling.PrecisionStopwatch;
import art.arcane.iris.spi.PlatformBlockState;
import art.arcane.iris.util.common.data.B;
public class IrisDepositModifier extends EngineAssignedModifier<PlatformBlockState> {
private final RNG rng;
public IrisDepositModifier(Engine engine) {
super(engine, "Deposit");
rng = new RNG(getEngine().getSeedManager().getDeposit());
}
@Override
public void onModify(int x, int z, Hunk<PlatformBlockState> output, boolean multicore, ChunkContext context) {
PrecisionStopwatch p = PrecisionStopwatch.start();
generateDeposits(output, Math.floorDiv(x, 16), Math.floorDiv(z, 16), multicore, context);
getEngine().getMetrics().getDeposit().put(p.getMilliseconds());
}
public void generateDeposits(Hunk<PlatformBlockState> terrain, int x, int z, boolean multicore, ChunkContext context) {
IrisRegion region = context.getRegion().get(7, 7);
IrisBiome biome = context.getBiome().get(7, 7);
BurstExecutor burst = burst().burst(multicore);
long seed = x * 341873128712L + z * 132897987541L;
long mask = 0;
MantleChunk chunk = getEngine().getMantle().getMantle().getChunk(x, z).use();
try {
for (IrisDepositGenerator k : getDimension().getDeposits()) {
long finalSeed = seed * ++mask;
burst.queue(() -> generate(k, chunk, terrain, rng.nextParallelRNG(finalSeed), x, z, false, context));
}
for (IrisDepositGenerator k : region.getDeposits()) {
long finalSeed = seed * ++mask;
burst.queue(() -> generate(k, chunk, terrain, rng.nextParallelRNG(finalSeed), x, z, false, context));
}
for (IrisDepositGenerator k : biome.getDeposits()) {
long finalSeed = seed * ++mask;
burst.queue(() -> generate(k, chunk, terrain, rng.nextParallelRNG(finalSeed), x, z, false, context));
}
} finally {
// complete() must run before release() even when queueing throws — already
// submitted burst tasks must never write into a released chunk.
try {
burst.complete();
} finally {
chunk.release();
}
}
}
public void generate(IrisDepositGenerator k, MantleChunk chunk, Hunk<PlatformBlockState> data, RNG rng, int cx, int cz, boolean safe, ChunkContext context) {
generate(k, chunk, data, rng, cx, cz, safe, null, context);
}
public void generate(IrisDepositGenerator k, MantleChunk chunk, Hunk<PlatformBlockState> data, RNG rng, int cx, int cz, boolean safe, HeightMap he, ChunkContext context) {
IrisDimensionCarvingResolver.State carvingState = new IrisDimensionCarvingResolver.State();
if (k.getSpawnChance() < rng.d())
return;
for (int l = 0; l < rng.i(k.getMinPerChunk(), k.getMaxPerChunk() + 1); l++) {
if (k.getPerClumpSpawnChance() < rng.d())
continue;
IrisObject clump = k.getClump(getEngine(), rng, getData());
int dim = clump.getW();
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 = getDepositTerrainSurface(cx, cz, x, z, he, context);
int height = k.getPlacementScope() == IrisDepositPlacementScope.TERRAIN
? depositSurfaceLimit(terrainSurface, k.getSurfaceClearance())
: getEngine().getHeight() - 1;
if (height < 0) {
continue;
}
int y = sampleHeight(
k.getHeightDistribution(), rng, k.getMinHeight(), k.getMaxHeight(),
Math.min(height, getEngine().getHeight() - 1));
if (y == Integer.MIN_VALUE) {
continue;
}
boolean clippedHeight = k.getHeightDistribution() == IrisDepositHeightDistribution.CLIPPED_UNIFORM;
if (clippedHeight && y > height - 2)
continue;
int biomeY = Math.max(0, Math.min(getEngine().getHeight() - 1, y));
boolean oreDeposit = k.isOre(getData());
IrisBiome surfaceBiome = context.getBiome().get(x, z);
IrisBiome depositBiome = oreDeposit || k.usesCaveBiomeFilter()
? getEngine().getCaveBiome(
(cx << 4) + x, biomeY, (cz << 4) + z, carvingState)
: null;
if (!k.matchesBiome(surfaceBiome, depositBiome)) {
continue;
}
if (oreDeposit) {
if (depositBiome != null) {
double frequencyMultiplier = depositBiome.getOreDepositFrequencyMultiplier();
if (frequencyMultiplier < 1D
&& !passesOreFrequency(frequencyMultiplier, rng.d())) {
continue;
}
double sizeMultiplier = depositBiome.getOreDepositSizeMultiplier();
if (sizeMultiplier != 1D) {
IrisObject scaledClump = k.getClump(getEngine(), rng, getData(), sizeMultiplier);
int scaledDimension = scaledClump.getW();
x = clampDepositCenter(x, scaledDimension, 16);
if (clippedHeight) {
y = clampDepositCenter(y, scaledDimension, getEngine().getHeight());
}
z = clampDepositCenter(z, scaledDimension, 16);
clump = scaledClump;
}
}
}
IrisDimension dimension = getDimension();
for (art.arcane.iris.util.common.math.IrisBlockVector j : clump.getBlocks().keys()) {
int nx = j.getBlockX() + x;
int ny = j.getBlockY() + y;
int nz = j.getBlockZ() + z;
if (nx > 15 || nx < 0 || ny >= getEngine().getHeight() || ny < 0 || nz < 0 || nz > 15) {
continue;
}
int columnSurface = getDepositTerrainSurface(cx, cz, nx, nz, he, context);
if (!placementSurfaceAllows(
k.getPlacementScope(), ny, columnSurface, k.getSurfaceClearance())) {
continue;
}
PlatformBlockState current = data.get(nx, ny, nz);
if (!canReplaceDepositTarget(current)) {
continue;
}
if (!k.canReplace(current)) {
continue;
}
if (!k.isReplaceBedrock() && IrisProceduralBlocks.materialKey(current).equals("minecraft:bedrock")) {
continue;
}
if (shouldDiscardExposed(
k.getDiscardChanceOnAirExposure(), rng.d(), isAdjacentToAir(data, nx, ny, nz))) {
continue;
}
if (chunk.get(nx, ny, nz, MatterCavern.class) == null) {
PlatformBlockState ore = clump.getBlocks().get(j);
PlatformBlockState remapped = resolveDepositVariant(
cx, cz, nx, ny, nz, ore, dimension, context, carvingState);
PlatformBlockState finalBlock = remapped != null
? remapped
: B.toDeepSlateOre(current, ore);
data.set(nx, ny, nz, finalBlock);
}
}
}
}
private int getDepositTerrainSurface(
int cx, int cz, int localX, int localZ, HeightMap heightMap,
ChunkContext context) {
return heightMap != null
? heightMap.getHeight((cx << 4) + localX, (cz << 4) + localZ)
: context.getRoundedHeight(localX, localZ);
}
static int depositSurfaceLimit(int surfaceY) {
return depositSurfaceLimit(surfaceY, 7);
}
static int depositSurfaceLimit(int surfaceY, int surfaceClearance) {
return surfaceY - Math.max(0, surfaceClearance);
}
static boolean placementSurfaceAllows(
IrisDepositPlacementScope 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(PlatformBlockState state) {
return state != null && !state.isAir() && !state.isFluid();
}
static int sampleHeight(
IrisDepositHeightDistribution distribution, RNG rng,
int configuredMinimum, int configuredMaximum, int clippedMaximum) {
int minimum = distribution == IrisDepositHeightDistribution.CLIPPED_UNIFORM
? Math.max(0, configuredMinimum)
: configuredMinimum;
int maximum = distribution == IrisDepositHeightDistribution.CLIPPED_UNIFORM
? Math.min(clippedMaximum, configuredMaximum)
: configuredMaximum;
if (minimum > maximum) {
return Integer.MIN_VALUE;
}
if (minimum == maximum) {
return minimum;
}
if (distribution != IrisDepositHeightDistribution.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<PlatformBlockState> data, int x, int y, int z) {
return isAirAt(data, x - 1, y, z)
|| isAirAt(data, x + 1, y, z)
|| isAirAt(data, x, y - 1, z)
|| isAirAt(data, x, y + 1, z)
|| isAirAt(data, x, y, z - 1)
|| isAirAt(data, x, y, z + 1);
}
private static boolean isAirAt(Hunk<PlatformBlockState> data, int x, int y, int z) {
if (x < 0 || x >= data.getWidth()
|| y < 0 || y >= data.getHeight()
|| z < 0 || z >= data.getDepth()) {
return false;
}
PlatformBlockState state = data.getRaw(x, y, z);
return state == null || state.isAir();
}
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));
}
private PlatformBlockState resolveDepositVariant(int cx, int cz, int nx, int localY, int nz, PlatformBlockState ore, IrisDimension dimension, ChunkContext context, IrisDimensionCarvingResolver.State carvingState) {
int worldX = (cx << 4) + nx;
int worldZ = (cz << 4) + nz;
int worldY = absoluteWorldY(getEngine().getMinHeight(), localY);
IrisBiome biome = getEngine().getCaveBiome(worldX, localY, worldZ, carvingState);
if (biome != null) {
PlatformBlockState match = matchDepositVariant(biome.getDepositVariants(), ore, worldY);
if (match != null) {
return match;
}
}
IrisRegion region = context.getRegion().get(nx, nz);
if (region != null) {
PlatformBlockState match = matchDepositVariant(region.getDepositVariants(), ore, worldY);
if (match != null) {
return match;
}
}
if (dimension != null) {
PlatformBlockState match = matchDepositVariant(dimension.getDepositVariants(), ore, worldY);
if (match != null) {
return match;
}
}
return null;
}
private PlatformBlockState matchDepositVariant(java.util.List<IrisDepositVariant> variants, PlatformBlockState ore, int y) {
if (variants == null || variants.isEmpty()) {
return null;
}
for (IrisDepositVariant variant : variants) {
if (y < variant.getMinHeight() || y > variant.getMaxHeight()) {
continue;
}
PlatformBlockState swapped = variant.remapOrNull(ore, getData());
if (swapped != null) {
return swapped;
}
}
return null;
}
}
@@ -0,0 +1,406 @@
/*
* 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 art.arcane.iris.engine.object.world.biome.custom.IrisBiomeCustom;
import art.arcane.iris.core.loader.IrisData;
import art.arcane.iris.engine.IrisComplex;
import art.arcane.iris.engine.decorator.FloatingDecorator;
import art.arcane.iris.engine.decorator.IrisSeaSurfaceDecorator;
import art.arcane.iris.engine.framework.Engine;
import art.arcane.iris.engine.framework.EngineAssignedModifier;
import art.arcane.iris.engine.framework.EngineDecorator;
import art.arcane.iris.engine.object.terrain.floating.FloatingBottomPaletteMode;
import art.arcane.iris.engine.object.terrain.floating.FloatingIslandBoundarySampler;
import art.arcane.iris.engine.object.terrain.floating.FloatingIslandSample;
import art.arcane.iris.engine.object.world.biome.IrisBiome;
import art.arcane.iris.engine.object.terrain.IrisBiomePaletteLayer;
import art.arcane.iris.engine.object.decoration.IrisDecorationPart;
import art.arcane.iris.engine.object.world.dimension.IrisDimension;
import art.arcane.iris.engine.object.terrain.floating.IrisFloatingChildBiomes;
import art.arcane.iris.engine.object.placement.IrisSlopeClip;
import art.arcane.iris.spi.IrisLogging;
import art.arcane.iris.util.common.data.B;
import art.arcane.iris.util.project.context.ChunkContext;
import art.arcane.iris.util.project.hunk.Hunk;
import art.arcane.iris.util.project.noise.CNG;
import art.arcane.volmlib.util.collection.KList;
import art.arcane.volmlib.util.math.RNG;
import art.arcane.volmlib.util.matter.MatterBiomeInject;
import art.arcane.volmlib.util.matter.slices.BiomeInjectMatter;
import art.arcane.volmlib.util.scheduling.PrecisionStopwatch;
import art.arcane.iris.spi.IrisPlatforms;
import art.arcane.iris.spi.PlatformBlockState;
import java.util.IdentityHashMap;
import static art.arcane.iris.engine.mantle.EngineMantle.AIR;
public class IrisFloatingChildBiomeModifier extends EngineAssignedModifier<PlatformBlockState> {
public static final long FLOATING_BASE_SEED_SALT = 0x5EED_F107_00F1B10CL;
private static final Runnable NOOP_DECORATION_MISS = () -> {
};
private final RNG rng;
private final EngineDecorator seaSurfaceDecorator;
private static KList<PlatformBlockState> generateBottomPaletteLayers(IrisFloatingChildBiomes entry, IrisDimension dimension, double wx, double wz, RNG random, int paletteDepth, IrisData data, IrisComplex complex) {
if (entry == null || entry.getBottomPaletteMode() != FloatingBottomPaletteMode.CUSTOM || entry.getBottomPalette() == null || entry.getBottomPalette().isEmpty()) {
return null;
}
return generatePaletteLayers(dimension, entry.getBottomPalette(), wx, wz, random.nextParallelRNG(0xB0770B), paletteDepth, data, complex);
}
private static KList<PlatformBlockState> generatePaletteLayers(IrisDimension dimension, KList<IrisBiomePaletteLayer> layers, double wx, double wz, RNG random, int maxDepth, IrisData data, IrisComplex complex) {
KList<PlatformBlockState> generated = new KList<>();
if (layers == null || layers.isEmpty() || maxDepth <= 0) {
return generated;
}
int generatorSeed = 7235;
for (int i = 0; i < layers.size(); i++) {
IrisBiomePaletteLayer layer = layers.get(i);
CNG heightGenerator = layer.getHeightGenerator(random.nextParallelRNG((generatorSeed++) * generatorSeed * generatorSeed * generatorSeed), data);
if (heightGenerator == null) {
continue;
}
double layerDepth = heightGenerator.fit(layer.getMinHeight(), layer.getMaxHeight(), wx / layer.getZoom(), wz / layer.getZoom());
IrisSlopeClip slopeClip = layer.getSlopeCondition();
if (slopeClip != null && !slopeClip.isDefault() && complex != null && !slopeClip.isValid(complex.getSlopeStream().get(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.getZoom(), j, (wz - j) / layer.getZoom(), data));
} catch (Throwable e) {
IrisLogging.reportError(e);
}
}
if (generated.size() >= maxDepth) {
break;
}
if (dimension != null && dimension.isExplodeBiomePalettes()) {
PlatformBlockState barrier = B.getState("minecraft:barrier");
for (int j = 0; j < dimension.getExplodeBiomePaletteSize(); j++) {
generated.add(barrier);
if (generated.size() >= maxDepth) {
break;
}
}
}
}
return generated;
}
private static boolean usesBottomPalette(IrisFloatingChildBiomes entry) {
FloatingBottomPaletteMode mode = entry == null || entry.getBottomPaletteMode() == null ? FloatingBottomPaletteMode.DEPTH : entry.getBottomPaletteMode();
return mode != FloatingBottomPaletteMode.DEPTH;
}
private static int[] bottomDepths(FloatingIslandSample sample, int chunkHeight) {
int[] bottomDepths = new int[sample.solidMask.length];
for (int i = 0; i < bottomDepths.length; i++) {
bottomDepths[i] = -1;
}
IdentityHashMap<IrisFloatingChildBiomes, 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;
}
IrisFloatingChildBiomes entry = sample.entryAt(k);
int depth = depthByEntry.getOrDefault(entry, 0);
bottomDepths[k] = depth;
depthByEntry.put(entry, depth + 1);
}
return bottomDepths;
}
private static PlatformBlockState selectPaletteBlock(IrisFloatingChildBiomes entry, KList<PlatformBlockState> topBlocks, KList<PlatformBlockState> bottomBlocks, int topDepth, int bottomDepth, PlatformBlockState fallbackSolid) {
FloatingBottomPaletteMode mode = entry == null || entry.getBottomPaletteMode() == null ? FloatingBottomPaletteMode.DEPTH : entry.getBottomPaletteMode();
if (mode == FloatingBottomPaletteMode.MIRROR_TOP) {
return paletteBlock(topBlocks, Math.min(topDepth, bottomDepth), fallbackSolid);
}
if (mode == FloatingBottomPaletteMode.CUSTOM && bottomDepth < topDepth) {
if (bottomBlocks != null && !bottomBlocks.isEmpty()) {
return paletteBlock(bottomBlocks, bottomDepth, fallbackSolid);
}
return paletteBlock(topBlocks, bottomDepth, fallbackSolid);
}
return paletteBlock(topBlocks, topDepth, fallbackSolid);
}
private static PlatformBlockState paletteBlock(KList<PlatformBlockState> blocks, int depth, PlatformBlockState fallbackSolid) {
if (blocks == null || blocks.isEmpty()) {
return fallbackSolid;
}
PlatformBlockState block = blocks.hasIndex(depth) ? blocks.get(depth) : blocks.getLast();
return block == null ? fallbackSolid : block;
}
private PaletteContext createPaletteContext(IrisBiome parent, IrisFloatingChildBiomes entry, IrisDimension dimension, int wx, int wz, long colSeed, int paletteDepth, IrisData data, IrisComplex complex) {
IrisBiome target = entry == null ? parent : entry.getRealBiome(parent, data);
int entrySeed = entry == null || entry.getBiome() == null ? 0 : entry.getBiome().hashCode();
RNG layerRng = rng.nextParallelRNG((int) (colSeed ^ 0x7A4E ^ entrySeed));
KList<PlatformBlockState> topBlocks = target == null ? null : target.generateLayers(dimension, wx, wz, layerRng, paletteDepth, paletteDepth, data, complex);
if (topBlocks == null || topBlocks.isEmpty()) {
topBlocks = parent.generateLayers(dimension, wx, wz, layerRng, paletteDepth, paletteDepth, data, complex);
}
KList<PlatformBlockState> bottomBlocks = generateBottomPaletteLayers(entry, dimension, wx, wz, layerRng, paletteDepth, data, complex);
return new PaletteContext(topBlocks, bottomBlocks, B.getState("minecraft:stone"));
}
private static final class PaletteContext {
private final KList<PlatformBlockState> topBlocks;
private final KList<PlatformBlockState> bottomBlocks;
private final PlatformBlockState fallbackSolid;
private PaletteContext(KList<PlatformBlockState> topBlocks, KList<PlatformBlockState> bottomBlocks, PlatformBlockState fallbackSolid) {
this.topBlocks = topBlocks;
this.bottomBlocks = bottomBlocks;
this.fallbackSolid = fallbackSolid;
}
}
public IrisFloatingChildBiomeModifier(Engine engine) {
super(engine, "FloatingChildBiomes");
rng = new RNG(engine.getSeedManager().getTerrain() ^ 0x7EB0A73F1DCE514DL);
seaSurfaceDecorator = new IrisSeaSurfaceDecorator(engine);
}
@Override
public void onModify(int x, int z, Hunk<PlatformBlockState> output, boolean multicore, ChunkContext context) {
PrecisionStopwatch p = PrecisionStopwatch.start();
int chunkHeight = output.getHeight();
IrisData data = getData();
IrisDimension dimension = getDimension();
IrisComplex complex = getComplex();
long baseSeed = getEngine().getSeedManager().getTerrain() ^ FLOATING_BASE_SEED_SALT;
FloatingIslandBoundarySampler boundarySampler = context.getFloatingIslandBoundarySampler();
FloatingIslandSample.clearChunkMemo();
for (int xf = 0; xf < 16; xf++) {
for (int zf = 0; zf < 16; zf++) {
int wx = x + xf;
int wz = z + zf;
IrisBiome parent = boundarySampler.parent(wx, wz);
if (parent == null || parent.getFloatingChildBiomes() == null || parent.getFloatingChildBiomes().isEmpty()) {
continue;
}
FloatingIslandSample sample = FloatingIslandSample.sampleMemoized(parent, wx, wz, chunkHeight, baseSeed, data, getEngine(), boundarySampler);
if (sample == null) {
continue;
}
long colSeed = FloatingIslandSample.columnSeed(baseSeed, wx, wz);
int paletteDepth = Math.max(4, sample.solidCount + 4);
IdentityHashMap<IrisFloatingChildBiomes, PaletteContext> paletteContexts = new IdentityHashMap<>();
IdentityHashMap<IrisFloatingChildBiomes, Integer> topDepthByEntry = new IdentityHashMap<>();
int[] bottomDepths = bottomDepths(sample, chunkHeight);
for (int k = sample.topIdx; k >= 0; k--) {
if (!sample.solidMask[k]) {
continue;
}
int y = sample.islandBaseY + k;
if (y < 0 || y >= chunkHeight) {
continue;
}
IrisFloatingChildBiomes entry = sample.entryAt(k);
PaletteContext paletteContext = paletteContexts.get(entry);
if (paletteContext == null) {
paletteContext = createPaletteContext(parent, entry, dimension, wx, wz, colSeed, paletteDepth, data, complex);
paletteContexts.put(entry, paletteContext);
}
int depth = topDepthByEntry.getOrDefault(entry, 0);
int bottomDepth = bottomDepths == null || bottomDepths[k] < 0 ? depth : bottomDepths[k];
PlatformBlockState block = selectPaletteBlock(entry, paletteContext.topBlocks, paletteContext.bottomBlocks, depth, bottomDepth, paletteContext.fallbackSolid);
if (block != null) {
output.set(xf, y, zf, block);
}
topDepthByEntry.put(entry, depth + 1);
}
IrisFloatingChildBiomes entry = sample.entry;
Integer localFluidHeight = entry.getLocalFluidHeight();
if (localFluidHeight != null && localFluidHeight > 0) {
PlatformBlockState fluid = B.getStateOrNull(entry.getFluidBlock());
if (fluid == null) {
fluid = B.getState("minecraft:water");
}
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 >= chunkHeight) {
continue;
}
boolean hasSolidBelow = false;
for (int kb = k - 1; kb >= 0; kb--) {
if (sample.solidMask[kb]) {
hasSolidBelow = true;
break;
}
}
if (hasSolidBelow) {
output.set(xf, y, zf, fluid);
}
}
}
writeIslandSkyBiomes(parent, wx, wz, sample, chunkHeight, data);
}
}
getEngine().getMetrics().getTerrain().put(p.getMilliseconds());
}
public void decorateColumns(int x, int z, Hunk<PlatformBlockState> output, boolean multicore, ChunkContext context) {
int chunkHeight = output.getHeight();
IrisData data = getData();
IrisComplex complex = getComplex();
long baseSeed = getEngine().getSeedManager().getTerrain() ^ FLOATING_BASE_SEED_SALT;
FloatingIslandBoundarySampler boundarySampler = context.getFloatingIslandBoundarySampler();
for (int xf = 0; xf < 16; xf++) {
for (int zf = 0; zf < 16; zf++) {
int wx = x + xf;
int wz = z + zf;
IrisBiome parent = boundarySampler.parent(wx, wz);
if (parent == null || parent.getFloatingChildBiomes() == null || parent.getFloatingChildBiomes().isEmpty()) {
continue;
}
FloatingIslandSample sample = FloatingIslandSample.sampleMemoized(parent, wx, wz, chunkHeight, baseSeed, data, getEngine(), boundarySampler);
if (sample == null) {
continue;
}
IrisFloatingChildBiomes entry = sample.entry;
IrisBiome target = entry.getRealBiome(parent, data);
if (!entry.isInheritDecorators() || target == null) {
continue;
}
int topY = sample.topY();
int max = Math.max(1, chunkHeight - topY);
if (topY + 1 < chunkHeight) {
PlatformBlockState above = output.get(xf, topY + 1, zf);
if (above == null || above.isAir()) {
try {
RNG colRng = rng.nextParallelRNG((int) FloatingIslandSample.columnSeed(baseSeed, wx, wz));
FloatingDecorator.decorateColumn(getEngine(), target, IrisDecorationPart.NONE, xf, zf, wx, wz, topY, max, output, colRng, NOOP_DECORATION_MISS);
} catch (Throwable e) {
IrisLogging.reportError(e);
}
}
}
Integer localFluidHeight = entry.getLocalFluidHeight();
if (localFluidHeight != null && localFluidHeight > 0) {
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 >= chunkHeight) {
continue;
}
boolean hasSolidBelow = false;
for (int kb = k - 1; kb >= 0; kb--) {
if (sample.solidMask[kb]) {
hasSolidBelow = true;
break;
}
}
if (hasSolidBelow && y > fluidTopY) {
fluidTopY = y;
}
}
if (fluidTopY > 0 && fluidTopY + 1 < chunkHeight && B.isAir(output.get(xf, fluidTopY + 1, zf))) {
try {
seaSurfaceDecorator.decorate(xf, zf, wx, wx + 1, wx - 1, wz, wz + 1, wz - 1, output, target, fluidTopY, chunkHeight);
} catch (Throwable e) {
IrisLogging.reportError(e);
}
}
}
}
}
}
private void writeIslandSkyBiomes(IrisBiome parent, int wx, int wz, FloatingIslandSample sample, int chunkHeight, IrisData data) {
try {
IdentityHashMap<IrisFloatingChildBiomes, MatterBiomeInject> matterByEntry = new IdentityHashMap<>();
for (int k = 0; k <= sample.topIdx; k++) {
if (!sample.solidMask[k]) {
continue;
}
int y = sample.islandBaseY + k;
if (y < 0 || y >= chunkHeight) {
continue;
}
IrisFloatingChildBiomes entry = sample.entryAt(k);
MatterBiomeInject matter = matterByEntry.get(entry);
if (matter == null) {
IrisBiome target = entry == null ? parent : entry.getRealBiome(parent, data);
if (target == null) {
continue;
}
matter = createSkyBiomeMatter(target, wx, wz);
matterByEntry.put(entry, matter);
}
getEngine().getMantle().getMantle().set(wx, y, wz, matter);
}
} catch (Throwable e) {
IrisLogging.reportError(e);
}
}
private MatterBiomeInject createSkyBiomeMatter(IrisBiome target, int wx, int wz) {
if (target.isCustom()) {
IrisBiomeCustom custom = target.getCustomBiome(rng, getEngine(), wx, 0, wz);
return BiomeInjectMatter.get(IrisPlatforms.get().biomeWriter().biomeIdFor(getDimension().getLoadKey() + ":" + custom.getId()));
}
return BiomeInjectMatter.get(IrisPlatforms.get().biomeWriter().biomeIdFor(target.getSkyBiomeKey(rng, getEngine(), wx, 0, wz)));
}
}
@@ -0,0 +1,200 @@
/*
* 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 art.arcane.iris.engine.framework.Engine;
import art.arcane.iris.engine.framework.EngineAssignedModifier;
import art.arcane.iris.engine.object.procedural.IrisProceduralBlocks;
import art.arcane.iris.util.project.context.ChunkContext;
import art.arcane.iris.util.common.data.B;
import art.arcane.iris.util.project.hunk.Hunk;
import art.arcane.iris.util.common.parallel.BurstExecutor;
import art.arcane.volmlib.util.scheduling.PrecisionStopwatch;
import art.arcane.iris.spi.PlatformBlockState;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicBoolean;
public class IrisPerfectionModifier extends EngineAssignedModifier<PlatformBlockState> {
private static final class States {
private static final PlatformBlockState AIR = B.getState("AIR");
private static final PlatformBlockState WATER = B.getState("WATER");
private static final Map<String, PlatformBlockState> ORE_BASES = buildOreBases();
}
public IrisPerfectionModifier(Engine engine) {
super(engine, "Perfection");
}
private static Map<String, PlatformBlockState> buildOreBases() {
Map<String, PlatformBlockState> map = new HashMap<>();
PlatformBlockState stone = B.getState("STONE");
PlatformBlockState deepslate = B.getState("DEEPSLATE");
PlatformBlockState netherrack = B.getState("NETHERRACK");
PlatformBlockState blackstone = B.getState("BLACKSTONE");
map.put("minecraft:coal_ore", stone);
map.put("minecraft:copper_ore", stone);
map.put("minecraft:iron_ore", stone);
map.put("minecraft:gold_ore", stone);
map.put("minecraft:redstone_ore", stone);
map.put("minecraft:lapis_ore", stone);
map.put("minecraft:diamond_ore", stone);
map.put("minecraft:emerald_ore", stone);
map.put("minecraft:deepslate_coal_ore", deepslate);
map.put("minecraft:deepslate_copper_ore", deepslate);
map.put("minecraft:deepslate_iron_ore", deepslate);
map.put("minecraft:deepslate_gold_ore", deepslate);
map.put("minecraft:deepslate_redstone_ore", deepslate);
map.put("minecraft:deepslate_lapis_ore", deepslate);
map.put("minecraft:deepslate_diamond_ore", deepslate);
map.put("minecraft:deepslate_emerald_ore", deepslate);
map.put("minecraft:nether_gold_ore", netherrack);
map.put("minecraft:nether_quartz_ore", netherrack);
map.put("minecraft:ancient_debris", netherrack);
map.put("minecraft:gilded_blackstone", blackstone);
return map;
}
private static String baseKey(PlatformBlockState state) {
String key = state.key();
int bracket = key.indexOf('[');
return bracket < 0 ? key : key.substring(0, bracket);
}
@Override
public void onModify(int x, int z, Hunk<PlatformBlockState> output, boolean multicore, ChunkContext context) {
PrecisionStopwatch p = PrecisionStopwatch.start();
if (getDimension().isHideOresForHiddenOre()) {
hideOres(output, multicore);
}
AtomicBoolean changed = new AtomicBoolean(true);
BurstExecutor burst = burst().burst(multicore);
while (changed.get()) {
changed.set(false);
for (int i = 0; i < 16; i++) {
int finalI = i;
burst.queue(() -> {
List<Integer> surfaces = new ArrayList<>();
List<Integer> ceilings = new ArrayList<>();
for (int j = 0; j < 16; j++) {
surfaces.clear();
ceilings.clear();
int top = getHeight(output, finalI, j);
boolean inside = true;
surfaces.add(top);
for (int k = top; k >= 0; k--) {
PlatformBlockState b = output.get(finalI, k, j);
boolean now = b != null && !(B.isAir(b) || B.isFluid(b));
if (now != inside) {
inside = now;
if (inside) {
surfaces.add(k);
} else {
ceilings.add(k + 1);
}
}
}
for (int k : surfaces) {
PlatformBlockState tip = output.get(finalI, k, j);
if (tip == null) {
continue;
}
boolean remove = false;
boolean remove2 = false;
if (B.isDecorant(tip)) {
PlatformBlockState bel = output.get(finalI, k - 1, j);
if (bel == null) {
remove = true;
} else if (!B.canPlaceOnto(tip, bel)) {
remove = true;
} else if (IrisProceduralBlocks.hasProperty(bel, "half")) {
PlatformBlockState bb = output.get(finalI, k - 2, j);
if (bb == null || !B.canPlaceOnto(bel, bb)) {
remove = true;
remove2 = true;
}
}
if (remove) {
changed.set(true);
output.set(finalI, k, j, States.AIR);
if (remove2) {
output.set(finalI, k - 1, j, States.AIR);
}
}
}
}
}
});
}
burst.complete();
}
getEngine().getMetrics().getPerfection().put(p.getMilliseconds());
}
private void hideOres(Hunk<PlatformBlockState> output, boolean multicore) {
BurstExecutor burst = burst().burst(multicore);
int height = output.getHeight();
for (int i = 0; i < 16; i++) {
int finalI = i;
burst.queue(() -> {
for (int j = 0; j < 16; j++) {
for (int k = height - 1; k >= 0; k--) {
PlatformBlockState block = output.get(finalI, k, j);
if (block == null) {
continue;
}
PlatformBlockState base = States.ORE_BASES.get(baseKey(block));
if (base != null) {
output.set(finalI, k, j, base);
}
}
}
});
}
burst.complete();
}
private int getHeight(Hunk<PlatformBlockState> output, int x, int z) {
for (int i = output.getHeight() - 1; i >= 0; i--) {
PlatformBlockState b = output.get(x, i, z);
if (b != null) {
if (!B.isAir(b) && !B.isFluid(b)) {
return i;
}
}
}
return 0;
}
}
@@ -0,0 +1,345 @@
/*
* 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 art.arcane.iris.engine.framework.Engine;
import art.arcane.iris.engine.framework.EngineAssignedModifier;
import art.arcane.iris.engine.mantle.EngineMantle;
import art.arcane.iris.engine.object.world.biome.IrisBiome;
import art.arcane.iris.engine.object.world.dimension.IrisDimension;
import art.arcane.iris.engine.object.procedural.IrisProceduralBlocks;
import art.arcane.iris.engine.object.placement.IrisSlopeClip;
import art.arcane.iris.util.project.context.ChunkContext;
import art.arcane.iris.util.common.data.B;
import art.arcane.iris.util.project.hunk.Hunk;
import art.arcane.volmlib.util.math.RNG;
import art.arcane.volmlib.util.scheduling.PrecisionStopwatch;
import art.arcane.iris.spi.PlatformBlockState;
public class IrisPostModifier extends EngineAssignedModifier<PlatformBlockState> {
private static final class States {
private static final PlatformBlockState AIR = B.getState("AIR");
}
private final RNG rng;
public IrisPostModifier(Engine engine) {
super(engine, "Post");
rng = new RNG(getEngine().getSeedManager().getPost());
}
@Override
public void onModify(int x, int z, Hunk<PlatformBlockState> output, boolean multicore, ChunkContext context) {
PrecisionStopwatch p = PrecisionStopwatch.start();
// The post stage runs sequentially on production (multicore false); an uncontended
// monitor per probe is still a monitor times ~10k probes per chunk.
Hunk<PlatformBlockState> sync = multicore ? output.synchronize() : output;
int width = output.getWidth();
int depth = output.getDepth();
int planeWidth = width + 2;
int[] heights = heightPlane(x, z, width, depth, planeWidth);
IrisDimension dimension = getDimension();
boolean walls = dimension.isPostProcessingWalls();
boolean slabs = dimension.isPostProcessingSlabs();
int fluidHeight = dimension.getFluidHeight();
for (int i = 0; i < width; i++) {
for (int j = 0; j < depth; j++) {
post(i, j, sync, i + x, j + z, context, heights, planeWidth, walls, slabs, fluidHeight);
}
}
getEngine().getMetrics().getPost().put(p.getMilliseconds());
}
/**
* Every column reads its own height plus its four neighbours, so adjacent columns would otherwise
* resolve the same height stream entry up to five times. Resolve the padded plane once instead. The
* four diagonal corners are never read, so they are left unresolved.
*/
private int[] heightPlane(int x, int z, int width, int depth, int planeWidth) {
int[] heights = new int[planeWidth * (depth + 2)];
EngineMantle mantle = getEngine().getMantle();
for (int j = -1; j <= depth; j++) {
boolean edge = j == -1 || j == depth;
int from = edge ? 0 : -1;
int to = edge ? width - 1 : width;
int row = (j + 1) * planeWidth;
for (int i = from; i <= to; i++) {
heights[row + i + 1] = mantle.trueHeight(x + i, z + j);
}
}
return heights;
}
private void post(int currentPostX, int currentPostZ, Hunk<PlatformBlockState> currentData, int x, int z, ChunkContext context, int[] heights, int planeWidth, boolean walls, boolean slabs, int fluidHeight) {
// x/z are world coordinates, the hunk is indexed relative to this chunk origin.
int originX = x - currentPostX;
int originZ = z - currentPostZ;
int center = (currentPostZ + 1) * planeWidth + currentPostX + 1;
int h = heights[center];
int ha = heights[center + 1];
int hb = heights[center + planeWidth];
int hc = heights[center - 1];
int hd = heights[center - planeWidth];
// Floating Nibs
int g = 0;
if (h < 1) {
return;
}
g += ha < h - 1 ? 1 : 0;
g += hb < h - 1 ? 1 : 0;
g += hc < h - 1 ? 1 : 0;
g += hd < h - 1 ? 1 : 0;
if (g == 4 && isAir(x, h - 1, z, originX, originZ, currentData)) {
setPostBlock(x, h, z, States.AIR, originX, originZ, currentData);
for (int i = h - 1; i > 0; i--) {
if (!isAir(x, i, z, originX, originZ, currentData)) {
h = i;
break;
}
}
}
// Nibs
g = 0;
g += ha == h - 1 ? 1 : 0;
g += hb == h - 1 ? 1 : 0;
g += hc == h - 1 ? 1 : 0;
g += hd == h - 1 ? 1 : 0;
if (g >= 4) {
PlatformBlockState bcState = getPostBlock(x, h, z, originX, originZ, currentData);
PlatformBlockState bState = getPostBlock(x, h + 1, z, originX, originZ, currentData);
if (bState.isOccluding() && bState.isSolid()) {
if (bcState.isSolid()) {
setPostBlock(x, h, z, bState, originX, originZ, currentData);
h--;
}
}
} else {
// Potholes
g = 0;
g += ha == h + 1 ? 1 : 0;
g += hb == h + 1 ? 1 : 0;
g += hc == h + 1 ? 1 : 0;
g += hd == h + 1 ? 1 : 0;
if (g >= 4) {
PlatformBlockState ba = getPostBlock(x, ha, z, originX, originZ, currentData);
PlatformBlockState bb = getPostBlock(x, hb, z, originX, originZ, currentData);
PlatformBlockState bc = getPostBlock(x, hc, z, originX, originZ, currentData);
PlatformBlockState bd = getPostBlock(x, hd, z, originX, originZ, currentData);
g = 0;
g = B.isSolid(ba) ? g + 1 : g;
g = B.isSolid(bb) ? g + 1 : g;
g = B.isSolid(bc) ? g + 1 : g;
g = B.isSolid(bd) ? g + 1 : g;
if (g >= 3) {
setPostBlock(x, h + 1, z, getPostBlock(x, h, z, originX, originZ, currentData), originX, originZ, currentData);
h++;
}
}
}
// Wall Patcher
IrisBiome biome = context.getBiome().get(currentPostX, currentPostZ);
if (walls) {
if (!biome.getWall().getPalette().isEmpty()) {
if (ha < h - 2 || hb < h - 2 || hc < h - 2 || hd < h - 2) {
boolean brokeGround = false;
int max = Math.abs(Math.max(h - ha, Math.max(h - hb, Math.max(h - hc, h - hd))));
for (int i = h; i > h - max; i--) {
PlatformBlockState d = biome.getWall().get(rng, x + i, i + h, z + i, getData());
if (d != null) {
if (isAirOrWater(x, i, z, originX, originZ, currentData)) {
if (brokeGround) {
break;
}
continue;
}
setPostBlock(x, i, z, d, originX, originZ, currentData);
brokeGround = true;
}
}
}
}
}
// Slab
if (slabs) {
//@builder
if ((ha == h + 1 && isSolidNonSlab(x + 1, ha, z, originX, originZ, currentData))
|| (hb == h + 1 && isSolidNonSlab(x, hb, z + 1, originX, originZ, currentData))
|| (hc == h + 1 && isSolidNonSlab(x - 1, hc, z, originX, originZ, currentData))
|| (hd == h + 1 && isSolidNonSlab(x, hd, z - 1, originX, originZ, currentData)))
//@done
{
IrisSlopeClip sc = biome.getSlab().getSlopeCondition();
PlatformBlockState d = sc.isValid(getComplex().getSlopeStream().get(x, z)) ? biome.getSlab().get(rng, x, h, z, getData()) : null;
if (d != null) {
boolean cancel = B.isAir(d);
if (IrisProceduralBlocks.materialKey(d).equals("minecraft:snow") && h + 1 <= fluidHeight) {
cancel = true;
}
if (isSnowLayer(x, h, z, originX, originZ, currentData)) {
cancel = true;
}
if (!cancel && isAirOrWater(x, h + 1, z, originX, originZ, currentData)) {
setPostBlock(x, h + 1, z, d, originX, originZ, currentData);
h++;
}
}
}
}
// Waterlogging
PlatformBlockState b = getPostBlock(x, h, z, originX, originZ, currentData);
if (IrisProceduralBlocks.hasProperty(b, "waterlogged")) {
boolean w = false;
if (h <= fluidHeight + 1) {
if (isWaterOrWaterlogged(x, h + 1, z, originX, originZ, currentData)) {
w = true;
} else if ((isWaterOrWaterlogged(x + 1, h, z, originX, originZ, currentData) || isWaterOrWaterlogged(x - 1, h, z, originX, originZ, currentData) || isWaterOrWaterlogged(x, h, z + 1, originX, originZ, currentData) || isWaterOrWaterlogged(x, h, z - 1, originX, originZ, currentData))) {
w = true;
}
}
if (w != "true".equals(IrisProceduralBlocks.propertyValue(b, "waterlogged"))) {
setPostBlock(x, h, z, b.withProperty("waterlogged", String.valueOf(w)), originX, originZ, currentData);
}
}
// Foliage
b = getPostBlock(x, h + 1, z, originX, originZ, currentData);
if (B.isVineBlock(b)) {
PlatformBlockState result = b;
int finalH = h + 1;
for (String face : IrisProceduralBlocks.FACE_PROPERTIES) {
if (!IrisProceduralBlocks.hasProperty(b, face)) {
continue;
}
int[] mod = IrisProceduralBlocks.faceOffset(face);
PlatformBlockState d = getPostBlock(x + mod[0], finalH + mod[1], z + mod[2], originX, originZ, currentData);
result = result.withProperty(face, String.valueOf(!B.isAir(d) && !B.isVineBlock(d)));
}
if (!result.equals(b)) {
setPostBlock(x, h + 1, z, result, originX, originZ, currentData);
}
}
if (B.isFoliage(b) || IrisProceduralBlocks.materialKey(b).equals("minecraft:dead_bush")) {
PlatformBlockState onto = getPostBlock(x, h, z, originX, originZ, currentData);
if (!B.canPlaceOnto(b, onto) && !B.isDecorant(b)) {
setPostBlock(x, h + 1, z, States.AIR, originX, originZ, currentData);
}
}
}
public boolean isAir(int x, int y, int z, int originX, int originZ, Hunk<PlatformBlockState> currentData) {
String material = IrisProceduralBlocks.materialKey(getPostBlock(x, y, z, originX, originZ, currentData));
return material.equals("minecraft:air") || material.equals("minecraft:cave_air");
}
public boolean hasGravity(int x, int y, int z, int originX, int originZ, Hunk<PlatformBlockState> currentData) {
String material = IrisProceduralBlocks.materialKey(getPostBlock(x, y, z, originX, originZ, currentData));
return material.equals("minecraft:sand") || material.equals("minecraft:red_sand") || material.endsWith("_concrete_powder");
}
public boolean isSolid(int x, int y, int z, int originX, int originZ, Hunk<PlatformBlockState> currentData) {
PlatformBlockState d = getPostBlock(x, y, z, originX, originZ, currentData);
return B.isSolid(d) && !B.isVineBlock(d);
}
public boolean isSolidNonSlab(int x, int y, int z, int originX, int originZ, Hunk<PlatformBlockState> currentData) {
PlatformBlockState d = getPostBlock(x, y, z, originX, originZ, currentData);
return B.isSolid(d) && !IrisProceduralBlocks.materialKey(d).endsWith("_slab");
}
public boolean isAirOrWater(int x, int y, int z, int originX, int originZ, Hunk<PlatformBlockState> currentData) {
String material = IrisProceduralBlocks.materialKey(getPostBlock(x, y, z, originX, originZ, currentData));
return material.equals("minecraft:water") || material.equals("minecraft:air") || material.equals("minecraft:cave_air");
}
public boolean isSlab(int x, int y, int z, int originX, int originZ, Hunk<PlatformBlockState> currentData) {
return IrisProceduralBlocks.materialKey(getPostBlock(x, y, z, originX, originZ, currentData)).endsWith("_slab");
}
public boolean isSnowLayer(int x, int y, int z, int originX, int originZ, Hunk<PlatformBlockState> currentData) {
return IrisProceduralBlocks.materialKey(getPostBlock(x, y, z, originX, originZ, currentData)).equals("minecraft:snow");
}
public boolean isWater(int x, int y, int z, int originX, int originZ, Hunk<PlatformBlockState> currentData) {
return IrisProceduralBlocks.materialKey(getPostBlock(x, y, z, originX, originZ, currentData)).equals("minecraft:water");
}
public boolean isWaterOrWaterlogged(int x, int y, int z, int originX, int originZ, Hunk<PlatformBlockState> currentData) {
PlatformBlockState d = getPostBlock(x, y, z, originX, originZ, currentData);
return IrisProceduralBlocks.materialKey(d).equals("minecraft:water") || "true".equals(IrisProceduralBlocks.propertyValue(d, "waterlogged"));
}
public boolean isLiquid(int x, int y, int z, int originX, int originZ, Hunk<PlatformBlockState> currentData) {
return IrisProceduralBlocks.hasProperty(getPostBlock(x, y, z, originX, originZ, currentData), "level");
}
public void setPostBlock(int x, int y, int z, PlatformBlockState d, int originX, int originZ, Hunk<PlatformBlockState> currentData) {
int lx = x - originX;
int lz = z - originZ;
if (lx < 0 || lz < 0 || lx >= currentData.getWidth() || lz >= currentData.getDepth() || y < 0 || y >= currentData.getHeight()) {
return;
}
currentData.set(lx, y, lz, d);
}
/**
* Neighbour columns can sit one block outside this chunk, and the blocks of an adjacent chunk are not
* available while generating this one. Resolve the hunk index relative to the chunk origin and let
* getClosest clamp to the nearest in-chunk column instead of wrapping to the opposite chunk edge.
*/
public PlatformBlockState getPostBlock(int x, int y, int z, int originX, int originZ, Hunk<PlatformBlockState> h) {
PlatformBlockState b = h.getClosest(x - originX, y, z - originZ);
return b == null ? States.AIR : b;
}
}
@@ -0,0 +1,35 @@
/*
* 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.object.annotations;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
import static java.lang.annotation.ElementType.FIELD;
import static java.lang.annotation.ElementType.PARAMETER;
import static java.lang.annotation.ElementType.TYPE;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
@Retention(RUNTIME)
@Target({PARAMETER, TYPE, FIELD})
public @interface ArrayType {
Class<?> type();
int min() default 0;
}
@@ -0,0 +1,31 @@
/*
* 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.object.annotations;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
import static java.lang.annotation.ElementType.FIELD;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
@Retention(RUNTIME)
@Target({FIELD})
public @interface DependsOn {
String[] value();
}
@@ -0,0 +1,33 @@
/*
* 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.object.annotations;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
import static java.lang.annotation.ElementType.FIELD;
import static java.lang.annotation.ElementType.PARAMETER;
import static java.lang.annotation.ElementType.TYPE;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
@Retention(RUNTIME)
@Target({PARAMETER, TYPE, FIELD})
public @interface Desc {
String value();
}
@@ -0,0 +1,31 @@
/*
* 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.object.annotations;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
import static java.lang.annotation.ElementType.FIELD;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
@Retention(RUNTIME)
@Target({FIELD})
public @interface MaxNumber {
double value();
}
@@ -0,0 +1,31 @@
/*
* 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.object.annotations;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
import static java.lang.annotation.ElementType.FIELD;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
@Retention(RUNTIME)
@Target({FIELD})
public @interface MinNumber {
double value();
}
@@ -0,0 +1,37 @@
/*
* Iris is a World Generator for Minecraft Bukkit 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.object.annotations;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
import static java.lang.annotation.ElementType.FIELD;
import static java.lang.annotation.ElementType.PARAMETER;
import static java.lang.annotation.ElementType.TYPE;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
/**
* Marks a String field (or a list of Strings) as a live biome-registry key, so schema completion offers every
* vanilla, datapack, and mod biome instead of nothing.
*/
@Retention(RUNTIME)
@Target({PARAMETER, TYPE, FIELD})
public @interface RegistryListBiome {
}
@@ -0,0 +1,33 @@
/*
* 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.object.annotations;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
import static java.lang.annotation.ElementType.FIELD;
import static java.lang.annotation.ElementType.PARAMETER;
import static java.lang.annotation.ElementType.TYPE;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
@Retention(RUNTIME)
@Target({PARAMETER, TYPE, FIELD})
public @interface RegistryListBlockType {
}
@@ -0,0 +1,14 @@
package art.arcane.iris.engine.object.annotations;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
import static java.lang.annotation.ElementType.FIELD;
import static java.lang.annotation.ElementType.PARAMETER;
import static java.lang.annotation.ElementType.TYPE;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
@Retention(RUNTIME)
@Target({PARAMETER, TYPE, FIELD})
public @interface RegistryListEnchantment {
}
@@ -0,0 +1,33 @@
/*
* Iris is a World Generator for Minecraft Bukkit 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.object.annotations;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
import static java.lang.annotation.ElementType.FIELD;
import static java.lang.annotation.ElementType.PARAMETER;
import static java.lang.annotation.ElementType.TYPE;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
@Retention(RUNTIME)
@Target({PARAMETER, TYPE, FIELD})
public @interface RegistryListEntityType {
}
@@ -0,0 +1,33 @@
/*
* 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.object.annotations;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
import static java.lang.annotation.ElementType.FIELD;
import static java.lang.annotation.ElementType.PARAMETER;
import static java.lang.annotation.ElementType.TYPE;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
@Retention(RUNTIME)
@Target({PARAMETER, TYPE, FIELD})
public @interface RegistryListFont {
}
@@ -0,0 +1,18 @@
package art.arcane.iris.engine.object.annotations;
import art.arcane.iris.engine.framework.ListFunction;
import art.arcane.volmlib.util.collection.KList;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
import static java.lang.annotation.ElementType.FIELD;
import static java.lang.annotation.ElementType.PARAMETER;
import static java.lang.annotation.ElementType.TYPE;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
@Retention(RUNTIME)
@Target({PARAMETER, TYPE, FIELD})
public @interface RegistryListFunction {
Class<? extends ListFunction<KList<String>>> value();
}
@@ -0,0 +1,33 @@
/*
* 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.object.annotations;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
import static java.lang.annotation.ElementType.FIELD;
import static java.lang.annotation.ElementType.PARAMETER;
import static java.lang.annotation.ElementType.TYPE;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
@Retention(RUNTIME)
@Target({PARAMETER, TYPE, FIELD})
public @interface RegistryListItemType {
}
@@ -0,0 +1,14 @@
package art.arcane.iris.engine.object.annotations;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
import static java.lang.annotation.ElementType.FIELD;
import static java.lang.annotation.ElementType.PARAMETER;
import static java.lang.annotation.ElementType.TYPE;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
@Retention(RUNTIME)
@Target({PARAMETER, TYPE, FIELD})
public @interface RegistryListNativeJigsawPool {
}
@@ -0,0 +1,14 @@
package art.arcane.iris.engine.object.annotations;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
import static java.lang.annotation.ElementType.FIELD;
import static java.lang.annotation.ElementType.PARAMETER;
import static java.lang.annotation.ElementType.TYPE;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
@Retention(RUNTIME)
@Target({PARAMETER, TYPE, FIELD})
public @interface RegistryListPotionEffect {
}
@@ -0,0 +1,35 @@
/*
* 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.object.annotations;
import art.arcane.iris.core.loader.IrisRegistrant;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
import static java.lang.annotation.ElementType.FIELD;
import static java.lang.annotation.ElementType.PARAMETER;
import static java.lang.annotation.ElementType.TYPE;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
@Retention(RUNTIME)
@Target({PARAMETER, TYPE, FIELD})
public @interface RegistryListResource {
Class<? extends IrisRegistrant> value();
}
@@ -0,0 +1,33 @@
/*
* 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.object.annotations;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
import static java.lang.annotation.ElementType.FIELD;
import static java.lang.annotation.ElementType.PARAMETER;
import static java.lang.annotation.ElementType.TYPE;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
@Retention(RUNTIME)
@Target({PARAMETER, TYPE, FIELD})
public @interface RegistryListSpecialEntity {
}
@@ -0,0 +1,33 @@
/*
* 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.object.annotations;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
import static java.lang.annotation.ElementType.FIELD;
import static java.lang.annotation.ElementType.PARAMETER;
import static java.lang.annotation.ElementType.TYPE;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
@Retention(RUNTIME)
@Target({PARAMETER, TYPE, FIELD})
public @interface RegistryListStructure {
}
@@ -0,0 +1,41 @@
/*
* 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.object.annotations;
import art.arcane.iris.engine.object.structure.vanilla.IrisImportedStructureControl;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
import static java.lang.annotation.ElementType.FIELD;
import static java.lang.annotation.ElementType.PARAMETER;
import static java.lang.annotation.ElementType.TYPE;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
@Retention(RUNTIME)
@Target({PARAMETER, TYPE, FIELD})
public @interface RegistryListVanillaStructure {
/**
* When true the field accepts family/namespace prefixes in addition to exact registered keys
* (the {@code IrisImportedStructureControl.matchesKey} contract: "minecraft:village" matches
* every village variant, "nova_structures:" matches a whole namespace). The generated editor
* schema then validates entries against the registry enum OR a key/prefix pattern instead of
* rejecting anything that is not an exact registered key.
*/
boolean prefixes() default false;
}
@@ -0,0 +1,33 @@
/*
* 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.object.annotations;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
import static java.lang.annotation.ElementType.FIELD;
import static java.lang.annotation.ElementType.PARAMETER;
import static java.lang.annotation.ElementType.TYPE;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
@Retention(RUNTIME)
@Target({PARAMETER, TYPE, FIELD})
public @interface RegistryListVanillaStructureSet {
}
@@ -0,0 +1,12 @@
package art.arcane.iris.engine.object.annotations;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface RegistryMapBlockState {
String value();
}
@@ -0,0 +1,33 @@
/*
* 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.object.annotations;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
import static java.lang.annotation.ElementType.FIELD;
import static java.lang.annotation.ElementType.PARAMETER;
import static java.lang.annotation.ElementType.TYPE;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
@Retention(RUNTIME)
@Target({PARAMETER, TYPE, FIELD})
public @interface Required {
}
@@ -0,0 +1,31 @@
/*
* 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.object.annotations;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
import static java.lang.annotation.ElementType.TYPE;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
@Retention(RUNTIME)
@Target({TYPE})
public @interface Snippet {
String value();
}
@@ -0,0 +1,42 @@
package art.arcane.iris.engine.object.annotations.functions;
import art.arcane.iris.core.loader.IrisData;
import art.arcane.iris.engine.framework.ListFunction;
import art.arcane.iris.engine.mantle.ComponentFlag;
import art.arcane.iris.engine.mantle.MantleComponent;
import art.arcane.iris.spi.IrisPlatforms;
import art.arcane.iris.util.common.scheduling.J;
import art.arcane.volmlib.util.collection.KList;
import art.arcane.volmlib.util.io.JarScanner;
import art.arcane.volmlib.util.mantle.flag.MantleFlag;
import java.util.Objects;
public class ComponentFlagFunction implements ListFunction<KList<String>> {
@Override
public String key() {
return "component-flag";
}
@Override
public String fancyName() {
return "Component Flag";
}
@Override
public KList<String> apply(IrisData data) {
var engine = data.getEngine();
if (engine != null) return engine.getMantle().getComponentFlags().toStringList();
JarScanner scanner = new JarScanner(IrisPlatforms.get().pluginJar(), "art.arcane.iris.engine.mantle.components");
J.attempt(scanner::scan);
return scanner.getClasses()
.stream()
.filter(c -> c.isAnnotationPresent(ComponentFlag.class))
.filter(MantleComponent.class::isAssignableFrom)
.map(c -> c.getDeclaredAnnotation(ComponentFlag.class))
.filter(Objects::nonNull)
.map(ComponentFlag::value)
.map(MantleFlag::toString)
.collect(KList.collector());
}
}
@@ -0,0 +1,23 @@
package art.arcane.iris.engine.object.annotations.functions;
import art.arcane.iris.core.loader.IrisData;
import art.arcane.iris.engine.framework.ListFunction;
import art.arcane.iris.spi.IrisPlatforms;
import art.arcane.volmlib.util.collection.KList;
public class LootTableKeyFunction implements ListFunction<KList<String>> {
@Override
public String key() {
return "loot-table-key";
}
@Override
public String fancyName() {
return "LootTable Key";
}
@Override
public KList<String> apply(IrisData data) {
return new KList<>(IrisPlatforms.get().registries().lootTableKeys());
}
}
@@ -0,0 +1,381 @@
/*
* 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.object.compatibility;
import art.arcane.iris.platform.bukkit.BukkitBlockResolution;
import art.arcane.iris.spi.IrisLogging;
import com.google.gson.Gson;
import art.arcane.volmlib.util.collection.KList;
import art.arcane.volmlib.util.io.IO;
import art.arcane.volmlib.util.json.JSONObject;
import art.arcane.iris.util.common.scheduling.J;
import lombok.Data;
import org.bukkit.Material;
import org.bukkit.block.data.BlockData;
import java.io.File;
import java.io.IOException;
@Data
public class IrisCompat {
private KList<IrisCompatabilityBlockFilter> blockFilters;
private KList<IrisCompatabilityItemFilter> itemFilters;
public IrisCompat() {
blockFilters = getDefaultBlockCompatabilityFilters();
itemFilters = getDefaultItemCompatabilityFilters();
}
public static IrisCompat configured(File f) {
IrisCompat def = new IrisCompat();
String defa = new JSONObject(new Gson().toJson(def)).toString(4);
J.attemptAsync(() -> IO.writeAll(new File(f.getParentFile(), "compat.default.json"), defa));
if (!f.exists()) {
J.a(() -> {
try {
IO.writeAll(f, defa);
} catch (IOException e) {
IrisLogging.error("Failed to writeNodeData to compat file");
IrisLogging.reportError(e);
}
});
} else {
// If the file doesn't exist, no additional mappings are present outside default
// so we shouldn't try getting them
try {
IrisCompat rea = new Gson().fromJson(IO.readAll(f), IrisCompat.class);
for (IrisCompatabilityBlockFilter i : rea.getBlockFilters()) {
def.getBlockFilters().add(i);
}
for (IrisCompatabilityItemFilter i : rea.getItemFilters()) {
def.getItemFilters().add(i);
}
} catch (Throwable e) {
IrisLogging.reportError(e);
}
}
return def;
}
private static KList<IrisCompatabilityItemFilter> getDefaultItemCompatabilityFilters() {
KList<IrisCompatabilityItemFilter> filters = new KList<>();
// Below 1.16
filters.add(new IrisCompatabilityItemFilter("NETHERITE_HELMET", "DIAMOND_HELMET"));
filters.add(new IrisCompatabilityItemFilter("NETHERITE_CHESTPLATE", "DIAMOND_CHESTPLATE"));
filters.add(new IrisCompatabilityItemFilter("NETHERITE_BOOTS", "DIAMOND_BOOTS"));
filters.add(new IrisCompatabilityItemFilter("NETHERITE_LEGGINGS", "DIAMOND_LEGGINGS"));
filters.add(new IrisCompatabilityItemFilter("MUSIC_DISC_PIGSTEP", "MUSIC_DISC_FAR"));
filters.add(new IrisCompatabilityItemFilter("NETHERITE_SWORD", "DIAMOND_SWORD"));
filters.add(new IrisCompatabilityItemFilter("NETHERITE_AXE", "DIAMOND_AXE"));
filters.add(new IrisCompatabilityItemFilter("NETHERITE_PICKAXE", "DIAMOND_PICKAXE"));
filters.add(new IrisCompatabilityItemFilter("NETHERITE_HOE", "DIAMOND_HOE"));
filters.add(new IrisCompatabilityItemFilter("NETHERITE_SHOVEL", "DIAMOND_SHOVEL"));
filters.add(new IrisCompatabilityItemFilter("NETHERITE_INGOT", "DIAMOND"));
filters.add(new IrisCompatabilityItemFilter("PIGLIN_BANNER_PATTERN", "PORKCHOP"));
filters.add(new IrisCompatabilityItemFilter("NETHERITE_SCRAP", "GOLD_INGOT"));
filters.add(new IrisCompatabilityItemFilter("WARPED_FUNGUS_ON_A_STICK", "CARROT_ON_A_STICK"));
// Below 1.15
filters.add(new IrisCompatabilityItemFilter("HONEY_BOTTLE", "GLASS_BOTTLE"));
filters.add(new IrisCompatabilityItemFilter("HONEYCOMB", "GLASS"));
// Below 1.14
filters.add(new IrisCompatabilityItemFilter("SWEET_BERRIES", "APPLE"));
filters.add(new IrisCompatabilityItemFilter("SUSPICIOUS_STEW", "MUSHROOM_STEW"));
filters.add(new IrisCompatabilityItemFilter("BLACK_DYE", "INK_SAC"));
filters.add(new IrisCompatabilityItemFilter("WHITE_DYE", "BONE_MEAL"));
filters.add(new IrisCompatabilityItemFilter("BROWN_DYE", "COCOA_BEANS"));
filters.add(new IrisCompatabilityItemFilter("BLUE_DYE", "LAPIS_LAZULI"));
filters.add(new IrisCompatabilityItemFilter("CROSSBOW", "BOW"));
filters.add(new IrisCompatabilityItemFilter("FLOWER_BANNER_PATTERN", "CORNFLOWER"));
filters.add(new IrisCompatabilityItemFilter("SKULL_BANNER_PATTERN", "BONE"));
filters.add(new IrisCompatabilityItemFilter("GLOBE_BANNER_PATTERN", "WHEAT_SEEDS"));
filters.add(new IrisCompatabilityItemFilter("MOJANG_BANNER_PATTERN", "DIRT"));
filters.add(new IrisCompatabilityItemFilter("CREEPER_BANNER_PATTERN", "CREEPER_HEAD"));
return filters;
}
private static KList<IrisCompatabilityBlockFilter> getDefaultBlockCompatabilityFilters() {
KList<IrisCompatabilityBlockFilter> filters = new KList<>();
filters.add(new IrisCompatabilityBlockFilter("CHAIN", "IRON_CHAIN"));
filters.add(new IrisCompatabilityBlockFilter("GRASS", "SHORT_GRASS"));
filters.add(new IrisCompatabilityBlockFilter("SHORT_GRASS", "GRASS"));
// Below 1.16
filters.add(new IrisCompatabilityBlockFilter("WEEPING_VINES", "NETHER_FENCE"));
filters.add(new IrisCompatabilityBlockFilter("WEEPING_VINES_PLANT", "NETHER_FENCE"));
filters.add(new IrisCompatabilityBlockFilter("WARPED_WART_BLOCK", "NETHER_WART_BLOCK"));
filters.add(new IrisCompatabilityBlockFilter("TWISTING_VINES", "BAMBOO"));
filters.add(new IrisCompatabilityBlockFilter("TWISTING_VINES_PLANT", "BAMBOO"));
filters.add(new IrisCompatabilityBlockFilter("TARGET", "COBBLESTONE"));
filters.add(new IrisCompatabilityBlockFilter("SOUL_SOIL", "SOULSAND"));
filters.add(new IrisCompatabilityBlockFilter("SOUL_TORCH", "TORCH"));
filters.add(new IrisCompatabilityBlockFilter("SOUL_LANTERN", "LANTERN"));
filters.add(new IrisCompatabilityBlockFilter("SOUL_FIRE", "FIRE"));
filters.add(new IrisCompatabilityBlockFilter("SOUL_CAMPFIRE", "CAMPFIRE"));
filters.add(new IrisCompatabilityBlockFilter("SHROOMLIGHT", "GLOWSTONE"));
filters.add(new IrisCompatabilityBlockFilter("RESPAWN_ANCHOR", "OBSIDIAN"));
filters.add(new IrisCompatabilityBlockFilter("NETHER_SPROUTS", "RED_MUSHROOM"));
filters.add(new IrisCompatabilityBlockFilter("NETHER_GOLD_ORE", "GOLD_ORE"));
filters.add(new IrisCompatabilityBlockFilter("LODESTONE", "STONE"));
filters.add(new IrisCompatabilityBlockFilter("STRIPPED_WARPED_HYPHAE", "BROWN_MUSHROOM_BLOCK"));
filters.add(new IrisCompatabilityBlockFilter("STRIPPED_CRIMSON_HYPHAE", "RED_MUSHROOM_BLOCK"));
filters.add(new IrisCompatabilityBlockFilter("WARPED_HYPHAE", "MUSHROOM_STEM"));
filters.add(new IrisCompatabilityBlockFilter("CRIMSON_HYPHAE", "RED_MUSHROOM_BLOCK"));
filters.add(new IrisCompatabilityBlockFilter("GILDED_BLACKSTONE", "COBBLESTONE"));
filters.add(new IrisCompatabilityBlockFilter("CRYING_OBSIDIAN", "OBSIDIAN"));
filters.add(new IrisCompatabilityBlockFilter("STRIPPED_WARPED_STEM", "MUSHROOM_STEM"));
filters.add(new IrisCompatabilityBlockFilter("STRIPPED_CRIMSON_STEM", "MUSHROOM_STEM"));
filters.add(new IrisCompatabilityBlockFilter("WARPED_STEM", "MUSHROOM_STEM"));
filters.add(new IrisCompatabilityBlockFilter("CRIMSON_STEM", "MUSHROOM_STEM"));
filters.add(new IrisCompatabilityBlockFilter("CRIMSON_ROOTS", "RED_MUSHROOM"));
filters.add(new IrisCompatabilityBlockFilter("WARPED_ROOTS", "BROWN_MUSHROOM"));
filters.add(new IrisCompatabilityBlockFilter("CRIMSON_PLANKS", "OAK_PLANKS"));
filters.add(new IrisCompatabilityBlockFilter("WARPED_PLANKS", "OAK_PLANKS"));
filters.add(new IrisCompatabilityBlockFilter("WARPED_NYLIUM", "MYCELIUM"));
filters.add(new IrisCompatabilityBlockFilter("CRIMSON_NYLIUM", "MYCELIUM"));
filters.add(new IrisCompatabilityBlockFilter("WARPED_FUNGUS", "BROWN_MUSHROOM"));
filters.add(new IrisCompatabilityBlockFilter("CRIMSON_FUNGUS", "RED_MUSHROOM"));
filters.add(new IrisCompatabilityBlockFilter("CRACKED_NETHER_BRICKS", "NETHER_BRICKS"));
filters.add(new IrisCompatabilityBlockFilter("CHISELED_NETHER_BRICKS", "NETHER_BRICKS"));
filters.add(new IrisCompatabilityBlockFilter("NETHER_FENCE", "LEGACY_NETHER_FENCE"));
filters.add(new IrisCompatabilityBlockFilter("IRON_CHAIN", "IRON_BARS"));
filters.add(new IrisCompatabilityBlockFilter("NETHERITE_BLOCK", "QUARTZ_BLOCK"));
filters.add(new IrisCompatabilityBlockFilter("BLACKSTONE", "COBBLESTONE"));
filters.add(new IrisCompatabilityBlockFilter("BASALT", "STONE"));
filters.add(new IrisCompatabilityBlockFilter("ANCIENT_DEBRIS", "NETHERRACK"));
filters.add(new IrisCompatabilityBlockFilter("NETHERRACK", "LEGACY_NETHERRACK"));
// Below 1.15
filters.add(new IrisCompatabilityBlockFilter("HONEY_BLOCK", "OAK_LEAVES"));
filters.add(new IrisCompatabilityBlockFilter("BEEHIVE", "OAK_LEAVES"));
filters.add(new IrisCompatabilityBlockFilter("BEE_NEST", "OAK_LEAVES"));
// Below 1.14
filters.add(new IrisCompatabilityBlockFilter("GRANITE_WALL", "COBBLESTONE_WALL"));
filters.add(new IrisCompatabilityBlockFilter("BLUE_ICE", "PACKED_ICE"));
filters.add(new IrisCompatabilityBlockFilter("DIORITE_WALL", "COBBLESTONE_WALL"));
filters.add(new IrisCompatabilityBlockFilter("ANDESITE_WALL", "COBBLESTONE_WALL"));
filters.add(new IrisCompatabilityBlockFilter("SWEET_BERRY_BUSH", "GRASS"));
filters.add(new IrisCompatabilityBlockFilter("STONECUTTER", "CRAFTING_TABLE"));
filters.add(new IrisCompatabilityBlockFilter("SANDSTONE_STAIRS", "LEGACY_SANDSTONE_STAIRS"));
filters.add(new IrisCompatabilityBlockFilter("SMOOTH_SANDSTONE_STAIRS", "LEGACY_SANDSTONE_STAIRS"));
filters.add(new IrisCompatabilityBlockFilter("MOSSY_COBBLESTONE_STAIRS", "COBBLESTONE_STAIRS"));
filters.add(new IrisCompatabilityBlockFilter("MOSSY_STONE_BRICK_STAIRS", "STONE_BRICK_STAIRS"));
filters.add(new IrisCompatabilityBlockFilter("POLISHED_GRANITE_STAIRS", "COBBLESTONE_STAIRS"));
filters.add(new IrisCompatabilityBlockFilter("GRANITE_STAIRS", "COBBLESTONE_STAIRS"));
filters.add(new IrisCompatabilityBlockFilter("POLISHED_DIORITE_STAIRS", "COBBLESTONE_STAIRS"));
filters.add(new IrisCompatabilityBlockFilter("DIORITE_STAIRS", "COBBLESTONE_STAIRS"));
filters.add(new IrisCompatabilityBlockFilter("POLISHED_ANDESITE_STAIRS", "COBBLESTONE_STAIRS"));
filters.add(new IrisCompatabilityBlockFilter("ANDESITE_STAIRS", "COBBLESTONE_STAIRS"));
filters.add(new IrisCompatabilityBlockFilter("STONE_STAIRS", "COBBLESTONE_STAIRS"));
filters.add(new IrisCompatabilityBlockFilter("END_STONE_BRICK_STAIRS", "LEGACY_SANDSTONE_STAIRS"));
filters.add(new IrisCompatabilityBlockFilter("NETHER_BRICK_STAIRS", "LEGACY_NETHER_BRICK_STAIRS"));
filters.add(new IrisCompatabilityBlockFilter("RED_NETHER_BRICK_STAIRS", "NETHER_BRICK_STAIRS"));
filters.add(new IrisCompatabilityBlockFilter("SMOOTH_QUARTZ_STAIRS", "LEGACY_QUARTZ_STAIRS"));
filters.add(new IrisCompatabilityBlockFilter("QUARTZ_STAIRS", "LEGACY_QUARTZ_STAIRS"));
filters.add(new IrisCompatabilityBlockFilter("RED_SANDSTONE_STAIRS", "LEGACY_RED_SANDSTONE_STAIRS"));
filters.add(new IrisCompatabilityBlockFilter("SMOOTH_RED_SANDSTONE_STAIRS", "LEGACY_RED_SANDSTONE_STAIRS"));
filters.add(new IrisCompatabilityBlockFilter("STONE_SLAB", "SMOOTH_STONE_SLAB"));
filters.add(new IrisCompatabilityBlockFilter("SMOKER", "FURNACE"));
filters.add(new IrisCompatabilityBlockFilter("SMITHING_TABLE", "CRAFTING_TABLE"));
filters.add(new IrisCompatabilityBlockFilter("END_STONE_BRICK_SLAB", "SANDSTONE_SLAB"));
filters.add(new IrisCompatabilityBlockFilter("RED_NETHER_BRICK_SLAB", "NETHER_BRICK_SLAB"));
filters.add(new IrisCompatabilityBlockFilter("SMOOTH_QUARTZ_SLAB", "QUARTZ_SLAB"));
filters.add(new IrisCompatabilityBlockFilter("CUT_SANDSTONE_SLAB", "SANDSTONE_SLAB"));
filters.add(new IrisCompatabilityBlockFilter("CUT_RED_SANDSTONE_SLAB", "RED_SANDSTONE_SLAB"));
filters.add(new IrisCompatabilityBlockFilter("SMOOTH_RED_SANDSTONE_SLAB", "RED_SANDSTONE_SLAB"));
filters.add(new IrisCompatabilityBlockFilter("SMOOTH_SANDSTONE_SLAB", "SANDSTONE_SLAB"));
filters.add(new IrisCompatabilityBlockFilter("MOSSY_COBBLESTONE_SLAB", "COBBLESTONE_SLAB"));
filters.add(new IrisCompatabilityBlockFilter("MOSSY_STONE_BRICK_SLAB", "STONE_BRICK_SLAB"));
filters.add(new IrisCompatabilityBlockFilter("STONE_SLAB", "SMOOTH_STONE_SLAB"));
filters.add(new IrisCompatabilityBlockFilter("ANDESITE_SLAB", "COBBLESTONE_SLAB"));
filters.add(new IrisCompatabilityBlockFilter("ANDESITE_SLAB", "COBBLESTONE_SLAB"));
filters.add(new IrisCompatabilityBlockFilter("DIORITE_SLAB", "COBBLESTONE_SLAB"));
filters.add(new IrisCompatabilityBlockFilter("GRANITE_SLAB", "COBBLESTONE_SLAB"));
filters.add(new IrisCompatabilityBlockFilter("POLISHED_ANDESITE_SLAB", "SMOOTH_STONE_SLAB"));
filters.add(new IrisCompatabilityBlockFilter("POLISHED_DIORITE_SLAB", "SMOOTH_STONE_SLAB"));
filters.add(new IrisCompatabilityBlockFilter("POLISHED_GRANITE_SLAB", "SMOOTH_STONE_SLAB"));
filters.add(new IrisCompatabilityBlockFilter("WARPED_WALL_SIGN", "LEGACY_WALL_SIGN"));
filters.add(new IrisCompatabilityBlockFilter("WARPED_SIGN", "LEGACY_SIGN_POST"));
filters.add(new IrisCompatabilityBlockFilter("SPRUCE_WALL_SIGN", "LEGACY_WALL_SIGN"));
filters.add(new IrisCompatabilityBlockFilter("SPRUCE_SIGN", "LEGACY_SIGN_POST"));
filters.add(new IrisCompatabilityBlockFilter("OAK_WALL_SIGN", "LEGACY_WALL_SIGN"));
filters.add(new IrisCompatabilityBlockFilter("OAK_SIGN", "LEGACY_SIGN_POST"));
filters.add(new IrisCompatabilityBlockFilter("JUNGLE_WALL_SIGN", "LEGACY_WALL_SIGN"));
filters.add(new IrisCompatabilityBlockFilter("JUNGLE_SIGN", "LEGACY_SIGN_POST"));
filters.add(new IrisCompatabilityBlockFilter("DARK_OAK_WALL_SIGN", "LEGACY_WALL_SIGN"));
filters.add(new IrisCompatabilityBlockFilter("DARK_OAK_SIGN", "LEGACY_SIGN_POST"));
filters.add(new IrisCompatabilityBlockFilter("CRIMSON_WALL_SIGN", "LEGACY_WALL_SIGN"));
filters.add(new IrisCompatabilityBlockFilter("CRIMSON_SIGN", "LEGACY_SIGN_POST"));
filters.add(new IrisCompatabilityBlockFilter("BIRCH_WALL_SIGN", "LEGACY_WALL_SIGN"));
filters.add(new IrisCompatabilityBlockFilter("BIRCH_SIGN", "LEGACY_SIGN_POST"));
filters.add(new IrisCompatabilityBlockFilter("ACACIA_WALL_SIGN", "LEGACY_WALL_SIGN"));
filters.add(new IrisCompatabilityBlockFilter("ACACIA_SIGN", "LEGACY_SIGN_POST"));
filters.add(new IrisCompatabilityBlockFilter("SCAFFOLDING", "BIRCH_FENCE"));
//filters.add(new IrisCompatabilityBlockFilter("LOOM", "LOOM"));
filters.add(new IrisCompatabilityBlockFilter("LECTERN", "BOOKSHELF"));
filters.add(new IrisCompatabilityBlockFilter("LANTERN", "REDSTONE_LAMP"));
filters.add(new IrisCompatabilityBlockFilter("JIGSAW", "AIR"));
filters.add(new IrisCompatabilityBlockFilter("GRINDSTONE", "COBBLESTONE"));
filters.add(new IrisCompatabilityBlockFilter("FLETCHING_TABLE", "CRAFTING_TABLE"));
filters.add(new IrisCompatabilityBlockFilter("COMPOSTER", "CHEST"));
filters.add(new IrisCompatabilityBlockFilter("CARTOGRAPHY_TABLE", "CRAFTING_TABLE"));
filters.add(new IrisCompatabilityBlockFilter("CAMPFIRE", "DARK_OAK_SLAB"));
filters.add(new IrisCompatabilityBlockFilter("BLAST_FURNACE", "FURNACE"));
filters.add(new IrisCompatabilityBlockFilter("BELL", "REDSTONE_LAMP"));
filters.add(new IrisCompatabilityBlockFilter("minecraft:barrel[facing=south]", "minecraft:hay_bale[axis=z]", true));
filters.add(new IrisCompatabilityBlockFilter("minecraft:barrel[facing=north]", "minecraft:hay_bale[axis=z]", true));
filters.add(new IrisCompatabilityBlockFilter("minecraft:barrel[facing=east]", "minecraft:hay_bale[axis=x]", true));
filters.add(new IrisCompatabilityBlockFilter("minecraft:barrel[facing=west]", "minecraft:hay_bale[axis=x]", true));
filters.add(new IrisCompatabilityBlockFilter("minecraft:barrel[facing=up]", "minecraft:hay_bale[axis=y]", true));
filters.add(new IrisCompatabilityBlockFilter("minecraft:barrel[facing=down]", "minecraft:hay_bale[axis=y]", true));
filters.add(new IrisCompatabilityBlockFilter("BAMBOO", "BIRCH_FENCE"));
filters.add(new IrisCompatabilityBlockFilter("BAMBOO_SAPLING", "BIRCH_SAPLING"));
filters.add(new IrisCompatabilityBlockFilter("POTTED_BAMBOO", "POTTED_BIRCH_SAPLING"));
return filters;
}
public BlockData getBlock(String n) {
String buf = n;
int err = 16;
BlockData tx = BukkitBlockResolution.getOrNull(buf, false);
if (tx != null) {
return tx;
}
searching:
while (true) {
if (err-- <= 0) {
IrisLogging.warnOnce("compat-block:" + n, "Can't find block data for " + n + "; using STONE.");
return BukkitBlockResolution.getNoCompat("STONE");
}
String m = buf;
if (m.contains("[")) {
m = m.split("\\Q[\\E")[0];
}
if (m.contains(":")) {
m = m.split("\\Q:\\E", 2)[1];
}
for (IrisCompatabilityBlockFilter i : blockFilters) {
if (i.getWhen().equalsIgnoreCase(i.isExact() ? buf : m)) {
BlockData b = i.getReplace();
if (b != null) {
return b;
}
buf = i.getSupplement();
continue searching;
}
}
IrisLogging.warnOnce("compat-block:" + n, "Can't find block data for " + n + "; using STONE.");
return BukkitBlockResolution.getNoCompat("STONE");
}
}
public Material getItem(String n) {
String buf = n;
int err = 16;
Material txf = BukkitBlockResolution.getMaterialOrNull(buf);
if (txf != null) {
return txf;
}
int nomore = 64;
searching:
while (true) {
if (nomore < 0) {
return BukkitBlockResolution.getMaterial("STONE");
}
nomore--;
if (err-- <= 0) {
break;
}
for (IrisCompatabilityItemFilter i : itemFilters) {
if (i.getWhen().equalsIgnoreCase(buf)) {
Material b = i.getReplace();
if (b != null) {
return b;
}
buf = i.getSupplement();
continue searching;
}
}
break;
}
buf = n;
BlockData tx = BukkitBlockResolution.getOrNull(buf, false);
if (tx != null) {
return tx.getMaterial();
}
nomore = 64;
searching:
while (true) {
if (nomore < 0) {
return BukkitBlockResolution.getMaterial("STONE");
}
nomore--;
if (err-- <= 0) {
return BukkitBlockResolution.getMaterial("STONE");
}
for (IrisCompatabilityBlockFilter i : blockFilters) {
if (i.getWhen().equalsIgnoreCase(buf)) {
BlockData b = i.getReplace();
if (b != null) {
return b.getMaterial();
}
buf = i.getSupplement();
continue searching;
}
}
return BukkitBlockResolution.getMaterial("STONE");
}
}
}
@@ -0,0 +1,72 @@
/*
* 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.object.compatibility;
import art.arcane.iris.platform.bukkit.BukkitBlockResolution;
import art.arcane.iris.engine.data.cache.AtomicCache;
import art.arcane.iris.engine.object.annotations.Desc;
import art.arcane.iris.engine.object.annotations.Required;
import art.arcane.iris.spi.IrisLogging;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.experimental.Accessors;
import org.bukkit.block.data.BlockData;
@Accessors(chain = true)
@NoArgsConstructor
@AllArgsConstructor
@Desc("Find and replace object materials for compatability")
@Data
public class IrisCompatabilityBlockFilter {
private final transient AtomicCache<BlockData> findData = new AtomicCache<>(true);
private final transient AtomicCache<BlockData> replaceData = new AtomicCache<>(true);
@Required
@Desc("When iris sees this block, and it's not reconized")
private String when = "";
@Required
@Desc("Replace it with this block. Dont worry if this block is also not reconized, iris repeat this compat check.")
private String supplement = "";
@Desc("If exact is true, it compares block data for example minecraft:some_log[axis=x]")
private boolean exact = false;
public IrisCompatabilityBlockFilter(String when, String supplement) {
this(when, supplement, false);
}
public BlockData getFind() {
return findData.aquire(() -> BukkitBlockResolution.get(when));
}
public BlockData getReplace() {
return replaceData.aquire(() ->
{
BlockData b = BukkitBlockResolution.getOrNull(supplement, false);
if (b == null) {
return null;
}
IrisLogging.warn("Compat: Using '%s' in place of '%s' since this server doesnt support '%s'", supplement, when, when);
return b;
});
}
}
@@ -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.object.compatibility;
import art.arcane.iris.platform.bukkit.BukkitBlockResolution;
import art.arcane.iris.spi.IrisLogging;
import art.arcane.iris.engine.data.cache.AtomicCache;
import art.arcane.iris.engine.object.annotations.Desc;
import art.arcane.iris.engine.object.annotations.Required;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.experimental.Accessors;
import org.bukkit.Material;
@Accessors(chain = true)
@NoArgsConstructor
@Desc("Find and replace object items for compatability")
@Data
public class IrisCompatabilityItemFilter {
private final transient AtomicCache<Material> findData = new AtomicCache<>(true);
private final transient AtomicCache<Material> replaceData = new AtomicCache<>(true);
@Required
@Desc("When iris sees this block, and it's not reconized")
private String when = "";
@Required
@Desc("Replace it with this block. Dont worry if this block is also not reconized, iris repeat this compat check.")
private String supplement = "";
public IrisCompatabilityItemFilter(String when, String supplement) {
this.when = when;
this.supplement = supplement;
}
public Material getFind() {
return findData.aquire(() -> BukkitBlockResolution.getMaterial(when));
}
public Material getReplace() {
return replaceData.aquire(() ->
{
Material b = BukkitBlockResolution.getMaterialOrNull(supplement);
if (b == null) {
return null;
}
IrisLogging.debug("Compat: Using " + supplement + " in place of " + when + " since this server doesnt support '" + supplement + "'");
return b;
});
}
}
@@ -0,0 +1,39 @@
/*
* 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.object.decoration;
import art.arcane.iris.engine.object.annotations.Desc;
@Desc("Represents a location where decorations should go")
public enum IrisDecorationPart {
@Desc("The default, decorate anywhere")
NONE,
@Desc("Targets shore lines (typically for sugar cane)")
SHORE_LINE,
@Desc("Target sea surfaces (typically for lilypads)")
SEA_SURFACE,
@Desc("Targets the sea floor (entire placement must be bellow sea level)")
SEA_FLOOR,
@Desc("Decorates on cave & carving ceilings or underside of overhangs")
CEILING,
}
@@ -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.object.decoration;
import art.arcane.iris.engine.object.annotations.Desc;
import java.util.Locale;
/**
* Pure-JVM mirror of Minecraft's decoration generation steps, in registry (ordinal) order. The ordinals and
* serialized names match {@code GenerationStep.Decoration} on MC 26.2 so a platform can convert either way
* without core depending on a Minecraft type. Verified against MC 26.2 GenerationStep.Decoration.
*/
@Desc("A vanilla decoration generation step. Placed features are grouped into these steps and run in this order.")
public enum IrisDecorationStep {
@Desc("Raw generation - the earliest step, before lakes.")
RAW_GENERATION("raw_generation"),
@Desc("Lakes.")
LAKES("lakes"),
@Desc("Local modifications such as amethyst geodes, icebergs and dripstone clusters.")
LOCAL_MODIFICATIONS("local_modifications"),
@Desc("Underground structure features (not the structure system - features tagged as underground structures).")
UNDERGROUND_STRUCTURES("underground_structures"),
@Desc("Surface structure features.")
SURFACE_STRUCTURES("surface_structures"),
@Desc("Stronghold step.")
STRONGHOLDS("strongholds"),
@Desc("Underground ores. This is the step that carries vanilla and mod ore veins.")
UNDERGROUND_ORES("underground_ores"),
@Desc("Underground decoration such as glow lichen, sculk patches and cave vegetation.")
UNDERGROUND_DECORATION("underground_decoration"),
@Desc("Fluid springs - the small water and lava spring features.")
FLUID_SPRINGS("fluid_springs"),
@Desc("Vegetal decoration - trees, grass, flowers, kelp and most surface plant life.")
VEGETAL_DECORATION("vegetal_decoration"),
@Desc("Top layer modification - freezing and snow placement.")
TOP_LAYER_MODIFICATION("top_layer_modification");
private final String serializedName;
IrisDecorationStep(String serializedName) {
this.serializedName = serializedName;
}
public String getSerializedName() {
return serializedName;
}
/**
* Resolves a step by its vanilla ordinal. Returns null when the running Minecraft version declares more
* decoration steps than this enum knows about, which the callers treat as "unknown step, generate it".
*/
public static IrisDecorationStep byOrdinal(int ordinal) {
IrisDecorationStep[] values = values();
return ordinal < 0 || ordinal >= values.length ? null : values[ordinal];
}
public static IrisDecorationStep byKey(String key) {
if (key == null || key.isBlank()) {
return null;
}
String normalized = key.trim().toLowerCase(Locale.ROOT);
for (IrisDecorationStep step : values()) {
if (step.serializedName.equals(normalized) || step.name().toLowerCase(Locale.ROOT).equals(normalized)) {
return step;
}
}
return null;
}
}
Loaded 100 of 397 files, more files were not shown because too many files have changed in this diff. Show more